@deepdesk/deepdesk-sdk 16.0.0 → 16.0.1-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.
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.iife.js +1 -1
- package/package.json +1 -1
- package/styles/index.js +1 -1
- package/styles.css +1 -1
- package/widget.css +1 -1
package/dist/index.iife.js
CHANGED
|
@@ -80,7 +80,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let o="<p>An error
|
|
|
80
80
|
c6.8-6.8,15.4-10.2,24.7-10.2h11.9v-70c0-44.4,16.2-82.8,47.8-115.2S212.1,0,256.4,0s82.8,16.2,115.2,47.8
|
|
81
81
|
c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});var H0=S(k()),E4={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},wP=({className:e,color:t})=>(0,H0.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,H0.jsx)("path",{d:"M172.03 0.0199966H0V86.03C47.5 86.03 86 124.54 86 172.04C86 124.54 124.51 86.03 172.01 86.03C219.51 86.03 258.03 124.54 258.03 172.04C258.03 219.54 219.52 258.05 172.01 258.05C124.5 258.05 86 219.54 86 172.04C86 219.54 47.5 258.05 0 258.05V344.06H172.03C267.04 344.06 344.06 267.04 344.06 172.03C344.06 77.02 267.04 0 172.03 0V0.0199966Z",fill:E4[t||"pink"]})});var SP={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedIn:"dd-XvHAn",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var z0={};Mt(z0,{enUS:()=>T4,nlNL:()=>C4});var T4={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},C4={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Gi=S(k()),EP=({onLogIn:e})=>{let t=re(z0),n=Y("floatingMenu"),r=Y("productName"),o=fe(),i=W(Ft),s=M("FloatingMenu",SP);if(i===null||n===!1)return null;let a=()=>{i===!0?o(Rn(!0)):e()};return(0,Gi.jsxs)("button",{className:(0,bP.default)(s.root,{[s.isLoggedIn]:i,[s.isLoggedOut]:!i}),onClick:a,children:[(0,Gi.jsx)("div",{className:s.text,children:t(i?"search":"signin",{productName:r})}),(0,Gi.jsxs)("div",{className:s.icon,children:[(0,Gi.jsx)(wP,{className:s.logo,color:"pink"}),i===!1&&(0,Gi.jsx)(xP,{className:s.lock})]})]})};var im=S(K());function Er(e){let{showMidSentenceSuggestions:t,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:r}=e.settings,{text:o,selection:i}=e.input;return i.start!==i.end?!1:i.end>=o.length?!0:t?n&&new RegExp(n).test(o.substring(i.end))||r&&new RegExp(r).test(o.substring(0,i.end))?!0:n===!1&&r===!1:!1}var k4={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1},tm=({ui:e})=>e.overlayCollapsed,TP=Te({name:"ui",initialState:k4,reducers:{setShowTabHint(e,t){e.showTabHint=t.payload},setInputFocus(e,t){e.overlayCollapsedUserOverwrite!==!0&&(t.payload===!0&&(e.overlayCollapsed=!1),e.inputHasFocus=t.payload)},setOverlayCollapsed(e,t){t.payload.collapse===!1&&(e.openOverlayWhenTyping=!1),!(t.payload.skipWhenInputFocus&&e.inputHasFocus)&&(e.overlayCollapsed=t.payload.collapse)},setOpenOverlayWhenTyping(e,t){e.openOverlayWhenTyping=t.payload},setOverlayCollapsedUserOverwrite(e,t){e.overlayCollapsedUserOverwrite=t.payload,e.overlayCollapsed=t.payload}}}),{setShowTabHint:ic,setInputFocus:nm,setOverlayCollapsed:$o,setOpenOverlayWhenTyping:CP,setOverlayCollapsedUserOverwrite:kP}=TP.actions,RP=TP.reducer;var rm=S(K());var qo=S(K());var PP=S(K());function AP(e,t,n){(0,PP.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var IP={root:"dd-1MBCO",actions:"dd--x4cy",badge:"dd-4Fpkz",formattedText:"dd-EzvTB"};var Yi=S(k()),P4=["search","personal-collection-search","search-autocomplete"];function A4(e,t,n,r={}){var i;let o="";return P4.includes(t)?o=LC(Mv(e,n,{stripAgentPart:!0}),(i=r.searchKeywords)!=null?i:[n]):o=Mv(e,n,r),r.placeholders===!0&&(o=OC(o)),o}var I4=()=>{},L4=({selected:e,suggestion:t})=>{let n=Y("inlineSuggestions"),r=W(ra),[o,i]=(0,qo.useState)(!1),s=Y("enableSuggestionFeedback"),a=W(d=>d.input.text),l=fe(),u=M("TextSuggestion",IP),c=(0,qo.useRef)(null);(0,qo.useEffect)(()=>{let d=setTimeout(()=>{l(xT({text:t.text,suggestion:t}))},500);return()=>{clearTimeout(d)}},[t]),AP(c,"click",()=>{l(Bn({suggestion:t,text:t.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let f=(0,qo.useMemo)(()=>A4(t.text,t.source,r,{stripAgentPart:n,placeholders:!0,searchKeywords:t.searchKeywords}),[n,t.text,t.source,r,t.searchKeywords]);return t.source==="gpt"&&!n?null:(0,Yi.jsxs)("div",{className:u.root,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:[(0,Yi.jsx)(be,{ref:c,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:I4,children:(0,Yi.jsx)(la,{containerTagName:"div",noWrap:!1,tagName:"span",className:u.formattedText,content:f})}),s&&o&&(0,Yi.jsx)("div",{className:u.actions,children:(0,Yi.jsx)(Qp,{source:"overlay",context:a,suggestion:t})})]})},LP=L4;var B0=S(k()),O4=({suggestions:e,selectedIndex:t,reverse:n})=>{let r=(0,rm.useMemo)(()=>{let o=e.map((i,s)=>(0,B0.jsx)(LP,{index:s,selected:s===t,suggestion:i},`${i.text}-${i.source}`));return n?o.reverse():o},[e,t,n]);return(0,B0.jsx)(rm.Fragment,{children:r})},om=O4;var OP={root:"dd-PfvRI",paper:"dd-HYlyY"};var sc=S(k()),M4=({textSuggestions:e,selectedIndex:t})=>{let n=(0,im.useRef)(null),r=M("InlineSuggestionsOverlay",OP),o=W(Er),i=fe(),s=W(Ft),a=W(na),l=W(tm),u=Y("showTextSuggestions");return jo(()=>{setTimeout(()=>{i($o({collapse:!0,skipWhenInputFocus:!0}))})}),(0,im.useEffect)(()=>{let c=n.current;if(!c||!c.parentElement)return;c.parentElement.style.left="0px";let f=c.getBoundingClientRect();c.parentElement.style.left=`${Math.min(window.innerWidth-4-f.right,0)}px`}),l||!o||!u||e.length===0||s!==!0||a===!1?null:(0,sc.jsx)("div",{className:r.root,"data-variant":"inline",children:(0,sc.jsx)("div",{ref:n,className:r.paper,children:(0,sc.jsx)(Xt,{children:(0,sc.jsx)(om,{suggestions:e,selectedIndex:t})})})})},N4=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),MP=xi(N4)(M4);var ac=S(k()),_4=({children:e})=>{let n=Y("locale").replace("-","");return(0,ac.jsx)(yv.Provider,{value:n,children:e})},D4=({store:e,customStyles:t={},children:n})=>(0,ac.jsx)(Qy,{store:e,children:(0,ac.jsx)(_4,{children:(0,ac.jsx)(qa.Provider,{value:t,children:n})})}),Go=D4;var am=S(De()),Ia=S(K());var NP=S(K());function _P(e,t){let[n,r]=(0,NP.useState)(()=>{if(typeof window=="undefined")return t;try{let i=window.localStorage.getItem(e);return i?JSON.parse(i):t}catch(i){return X.error(i),t}});return[n,i=>{try{let s=i instanceof Function?i(n):i;r(s),typeof window!="undefined"&&window.localStorage.setItem(e,JSON.stringify(s))}catch(s){X.error(s)}}]}var DP=()=>/Mac/i.test(navigator.platform);var HP=S(De()),eo=S(K());var U0={};Mt(U0,{enUS:()=>F4,nlNL:()=>H4});var F4={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Sign in"}]},{type:0,value:" to enable "},{type:1,value:"productName"},{type:0,value:"."}],snooze:[{type:0,value:"Snooze for "},{type:8,value:"min",children:[{type:0,value:"10 minutes"}]},{type:0,value:", "},{type:8,value:"hour",children:[{type:0,value:"1 hour"}]},{type:0,value:" or "},{type:8,value:"day",children:[{type:0,value:"1 day"}]}]},H4={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Log in"}]},{type:0,value:" bij "},{type:1,value:"productName"},{type:0,value:"."}],snooze:[{type:0,value:"Snooze voor "},{type:8,value:"min",children:[{type:0,value:"10 minuten"}]},{type:0,value:", "},{type:8,value:"hour",children:[{type:0,value:"1 uur"}]},{type:0,value:" of "},{type:8,value:"day",children:[{type:0,value:"1 dag"}]}]};var FP={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};var Yo=S(k()),j0=(e,t,n)=>r=>(0,Yo.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),z4=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r,onLogIn:o})=>{let i=re(U0),s=nn(),a=M("Login",FP),l=Y("productName"),u=(0,eo.useCallback)(g=>{g.preventDefault(),r&&r(parseInt(g.target.value,10))},[]),c=(0,eo.useCallback)(g=>{g.preventDefault(),s.send(sa,!0)},[t]),f=(0,eo.useMemo)(()=>g=>(0,Yo.jsx)("a",{onClick:v=>{v.preventDefault(),o()},href:t,className:a.anchor,target:"_blank",rel:"noreferrer",children:g},"login"),[t]),d=(0,eo.useCallback)(g=>(0,Yo.jsx)("button",{type:"button",className:a.anchorButton,onClick:c,children:g},"prompt"),[c]),{min:p,hour:h,day:y}=(0,eo.useMemo)(()=>({min:j0(a,60*10,u),hour:j0(a,60*60,u),day:j0(a,60*60*12,u)}),[]);return(0,Yo.jsxs)("div",{className:(0,HP.default)(e,a.root),children:[i("loginPlease",{login:n?d:f,productName:l}),r&&(0,Yo.jsxs)(eo.Fragment,{children:[(0,Yo.jsx)("br",{}),i("snooze",{min:p,hour:h,day:y})]})]})},sm=z4;var zP={root:"dd-DoQhb",text:"dd-Jwnev"};var lc=S(k()),B4=({title:e})=>{let t=M("SearchTrigger",zP),n=fe(),r=at();return(0,lc.jsxs)("button",{type:"button",className:t.root,onClick:()=>{n(Rn(!0)),r("open search",{via:"autocomplete-overlay"})},children:[(0,lc.jsx)(ca,{}),(0,lc.jsx)("span",{className:t.text,children:e})]})},BP=B4;var V0={};Mt(V0,{enUS:()=>U4,nlNL:()=>j4});var U4={arrowHint:[{type:0,value:"Tip: use arrow keys to navigate suggestions"}],searchHintWindows:[{type:0,value:"Press CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],searchHintMac:[{type:0,value:"Press CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Close"}],search:[{type:0,value:"Search"}]},j4={arrowHint:[{type:0,value:"Tip: Selecteer suggesties met pijltoetsen"}],searchHintWindows:[{type:0,value:"Druk CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],searchHintMac:[{type:0,value:"Druk CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Sluiten"}],search:[{type:0,value:"Zoeken"}]};var UP={root:"dd-oa7Vc",isInline:"dd-bwk31",toggleButton:"dd-MSB8Z",toggleButtonWrapper:"dd-ZkCzT",toggleButtonWrapperHidden:"dd-Sq66c",isCollapsed:"dd-vkrPk",collapsible:"dd-CWQJe",hints:"dd-IOoo3",hintsHidden:"dd-psVuT",triggers:"dd-toIoo",triggersRight:"dd-mc4l2"};var Ke=S(k()),V4=({textSuggestions:e,selectedIndex:t,onLogIn:n})=>{let r=M("SuggestionsOverlay",UP),o=re(V0),i=W(Er),s=vT(),a=fe(),l=(0,Ia.useRef)(null),u=Y("searchTriggerKey"),c=Y("productName"),f=W(tm),d=W(Ft),p=W(na),[h,y]=(0,Ia.useState)(null),g=Y("showSearch"),m=Y("showTextSuggestions"),v=Y("adminUrl"),x=Y("isEmbedded"),[w,C]=_P("dd-snooze-until-ms",0),T=f||w>Date.now(),R=e.filter(q=>q.source!=="gpt").length,I=()=>{T&&C(0),a(kP(!T))},L=q=>{let N=Date.now()+q*1e3;C(N),X.info(`Snooze until: ${new Date(N)}`),a($o({collapse:!0}))};return(0,Ia.useEffect)(()=>{R===0&&y(null)},[e,R]),jo(()=>{a($o({collapse:!0,skipWhenInputFocus:!0}))}),d===null||p===!1?null:d===!1?(0,Ke.jsxs)("div",{ref:l,className:(0,am.default)(r.root,{[r.isCollapsed]:T}),children:[!T&&(0,Ke.jsxs)("div",{className:r.triggers,children:[(0,Ke.jsx)("div",{style:{flex:1}}),(0,Ke.jsx)("div",{className:r.triggersRight,children:(0,Ke.jsx)(ti,{className:r.toggleButton,title:o("collapse"),onClick:I,isCollapsed:!1})})]}),(0,Ke.jsx)("div",{className:r.toggleButtonWrapper,children:(0,Ke.jsx)(ti,{className:r.toggleButton,title:o("open",{productName:c}),onClick:I,isCollapsed:!0})}),(0,Ke.jsx)("div",{className:r.collapsible,children:(0,Ke.jsx)(sm,{loginUrl:v,isEmbedded:x,onLogIn:n,onSnooze:L})})]}):!s||!i?null:(0,Ke.jsxs)("div",{ref:l,className:(0,am.default)(r.root,{[r.isCollapsed]:T}),children:[!T&&(0,Ke.jsxs)("div",{className:r.triggers,children:[(0,Ke.jsx)("div",{style:{flex:1},children:g&&(0,Ke.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>y(o(DP()?"searchHintMac":"searchHintWindows",{searchTriggerKey:u.toUpperCase()})),onMouseLeave:()=>y(null),children:(0,Ke.jsx)(BP,{title:o("search")})})}),(0,Ke.jsxs)("div",{className:r.triggersRight,onFocus:()=>{},children:[(0,Ke.jsx)("div",{className:(0,am.default)(!h&&r.hintsHidden,r.hints),children:h}),(0,Ke.jsx)(ti,{className:r.toggleButton,title:o("collapse"),onClick:I,isCollapsed:!1})]})]}),(0,Ke.jsx)("div",{className:r.toggleButtonWrapper,children:(0,Ke.jsx)(ti,{className:r.toggleButton,title:o("open",{productName:c}),onClick:I,isCollapsed:!0})}),R>0&&m&&(0,Ke.jsx)("div",{className:r.collapsible,onFocus:()=>{},children:(0,Ke.jsx)(Xt,{children:(0,Ke.jsx)(om,{suggestions:e,selectedIndex:t,reverse:!0})})})]})},W4=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),jP=xi(W4)(V4);var xm=S(De());var ro=S(K());var La=S(K());function lm(e){return e.contentEditable==="true"}function K4(e){let t=0,n=0,r=window.getSelection();if(r.rangeCount!==0){let o=r.getRangeAt(0),i=o.cloneRange();i.selectNodeContents(e),i.setEnd(o.endContainer,o.endOffset),n=i.toString().length,i.selectNodeContents(e),i.setEnd(o.startContainer,o.startOffset),t=i.toString().length}return{selectionStart:t,selectionEnd:n}}function VP(e){let{selectionStart:t,selectionEnd:n}=lm(e)?K4(e):e;return[t,n]}function WP(e){let[,t]=(0,La.useState)(),n=(0,La.useRef)(null);return n.current=VP(e),(0,La.useEffect)(()=>{let r=()=>{var a;let[o,i]=(a=n.current)!=null?a:[],s=VP(e);(!s||o!==s[0]||i!==s[1])&&(n.current=s,t({}))};return e.addEventListener("keyup",r),e.addEventListener("click",r),e.addEventListener("focus",r),document.addEventListener("selectionchange",r),()=>{e.removeEventListener("keyup",r),e.removeEventListener("click",r),e.removeEventListener("focus",r),document.removeEventListener("selectionchange",r)}},[e]),n.current}function KP(e,t){if(!t)return;let n=e,{value:r}=n,[o,i]=t,s=r.match(Nc);if(!s||s.length===0)return;let a=0;s.find(l=>{let u=r.indexOf(l,a);return o>u&&i<u+l.length?(n.selectionStart=u,n.selectionEnd=u+l.length,!0):(a=u+l.length,!1)})}var $P=S(K()),$4=["div","span","mark","strong","b","i","u","em"];function W0(e,t,n=0){var i;let r=e[e.length-1],o=typeof r=="object"&&r!==null?(i=r.props)==null?void 0:i.tagName:void 0;if(o==="br")return e.pop(),[...e,...t,r];if($4.includes(o)){let s=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,$P.cloneElement)(r,{children:W0(s,t,n+1)})]}return[...e,...t]}function Xi(e){return e.tagName.toLowerCase()==="textarea"}var qP={root:"dd-7-cgW",container:"dd-PsRQ8",agentText:"dd-qnW-V",tabText:"dd-cUHUr",hint:"dd-v7fSg",matchSelection:"dd-8cr8y",focus:"dd-3tr9l",resetIndent:"dd-TvQfZ",matchKeyword:"dd-oJkRD",matchPlaceholder:"dd-QvNoo",hover:"dd--wi0R",hintText:"dd-7gQQh",popover:"dd-xbRu-",popoverRoot:"dd-rA2x8",popoverContentContainer:"dd-JHICl",popoverContent:"dd--mfkC",selectionOptions:"dd-p52wn",selectionOptionsIsHidden:"dd-sSTDp",selectionOptionsButton:"dd-Q6kRY",caret:"dd-jIhc8",popoverSuggestionsRoot:"dd-iFDbL",suggestionsOverlayInputStyles:"dd-zzENA"};var ZP=S(De());var mm=S(K());var Oa=S(K());function GP(e,t){let n;return[(...r)=>{window.cancelAnimationFrame(n);let o=t?t(...r):r;n=window.requestAnimationFrame(()=>{e(...o)})},()=>window.cancelAnimationFrame(n)]}function um(e){let t=(0,Oa.useRef)(null),[n,r]=(0,Oa.useState)(!1);return(0,Oa.useEffect)(()=>{var c;let o=!1,i=parseFloat((c=window.getComputedStyle(document.body).zoom)!=null?c:"1"),[s,a]=GP((f,d)=>{let p=t.current;if(!p)return;let h=f/i,y=d/i,g=p.getBoundingClientRect(),m=h>g.x&&h<g.x+g.width&&y>g.y&&y<g.y+g.height;m&&!o?(o=!0,r(!0)):!m&&o&&(o=!1,r(!1))},({clientX:f,clientY:d})=>[f,d]),[l,u]=GP(()=>{o=!1,r(!1)});return e.addEventListener("mousemove",s),e.addEventListener("mouseleave",l),()=>{a(),u(),e.removeEventListener("mousemove",s),e.removeEventListener("mouseleave",l)}},[t]),[t,n]}function YP(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function cm(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function XP(e){return e!=null}var QP=S(De()),dm=S(K());var to={root:"dd-7-cgW",container:"dd-PsRQ8",agentText:"dd-qnW-V",tabText:"dd-cUHUr",hint:"dd-v7fSg",matchSelection:"dd-8cr8y",focus:"dd-3tr9l",resetIndent:"dd-TvQfZ",matchKeyword:"dd-oJkRD",matchPlaceholder:"dd-QvNoo",hover:"dd--wi0R",hintText:"dd-7gQQh",popover:"dd-xbRu-",popoverRoot:"dd-rA2x8",popoverContentContainer:"dd-JHICl",popoverContent:"dd--mfkC",selectionOptions:"dd-p52wn",selectionOptionsIsHidden:"dd-sSTDp",selectionOptionsButton:"dd-Q6kRY",caret:"dd-jIhc8",popoverSuggestionsRoot:"dd-iFDbL",suggestionsOverlayInputStyles:"dd-zzENA"};var K0=S(k()),fm=(0,dm.forwardRef)((o,r)=>{var i=o,{className:e,children:t}=i,n=te(i,["className","children"]);let s=(0,dm.useRef)(null),a=M("TabCompletion",to);return(0,K0.jsx)("div",A(b({ref:cm([s,r]),className:(0,QP.default)(e,a.popoverContentContainer)},n),{children:(0,K0.jsx)("div",{className:a.popoverContent,children:t})}))});var Xo=S(k()),q4=e=>t=>{let n=Zv(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},G4=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let i=M("TabCompletion",to),s=Sp(),a=(0,mm.useMemo)(()=>q4(e.getBoundingClientRect()),[e]),[l,u]=um(e);return(0,mm.useEffect)(()=>{u?s.open():s.close()},[u]),(0,Xo.jsxs)("span",{children:[(0,Xo.jsx)("mark",{ref:cm([l,s.triggerRef]),className:(0,ZP.default)(i.matchKeyword,{[i.hover]:u}),"aria-haspopup":"dialog","aria-expanded":s.opened?"true":"false",children:r}),s.opened&&(0,Xo.jsx)(ha,{className:i.popover,triggerRef:s.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,Xo.jsx)(fm,{style:n,children:(0,Xo.jsx)("div",{className:i.hintText,children:o})})})]})},pm=class extends $r{constructor(){super(...arguments);this.keywordMatches=[];this.preparedKeywordMatches=[];this.usedKeywordMatches=new Set}onBeforeParse(n,r){return r.keywordMatches&&r.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=r.keywordMatches.map(o=>A(b({},o),{keywordRegex:new RegExp(`\\b${YP(o.keyword)}\\b`,"i")})),this.keywordMatches=r.keywordMatches),this.usedKeywordMatches.clear(),n}match(n){let r=this.preparedKeywordMatches.map(i=>{if(this.usedKeywordMatches.has(i))return null;let s=n.match(i.keywordRegex);if(!s)return null;let a=n.charAt(s.index-1),l=n.charAt(s.index+i.keyword.length);return a==="{"&&l==="}"?null:{index:s.index,length:s[0].length,match:s[0],matchString:s[0],suggestion:i.suggestion,preparedKeywordMatch:i,valid:!0}}).filter(XP);if(r.length===0)return null;let o=r.reduce((i,s)=>s.index<i.index?s:i);return this.usedKeywordMatches.add(o.preparedKeywordMatch),o}replaceWith(n,r){return(0,Xo.jsx)(G4,{inputElement:r.inputElement,suggestion:r.suggestion,inputStyle:r.inputStyle,boundaryRef:r.boundaryRef,children:n},`keyword_${r.matchString}_${r.key}`)}asTag(){return"mark"}};var JP=S(De());var $0=S(k()),Y4=({inputElement:e,children:t})=>{let n=M("TabCompletion",to),[r,o]=um(e);return(0,$0.jsx)("mark",{ref:r,className:(0,JP.default)(n.matchPlaceholder,{[n.hover]:o}),children:t})},gm=class extends $r{match(t){let n=t.match(/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\}(?!\}))/);return n?{index:n.index,length:n[0].length,match:n[0],matchString:n[0],valid:!0}:null}replaceWith(t,n){return(0,$0.jsx)(Y4,{inputElement:n.inputElement,children:t},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var ym=S(De());var $t=S(K());var q0=S(k()),eA=()=>(0,q0.jsx)("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:(0,q0.jsx)("path",{fill:"currentColor",d:"M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"})});var Tr=S(K());var nA=S(bv());var tA={root:"dd-ky-Bv",content:"dd-kV5e1"};function hm(e,t,n){var o;let r=((o=e.imageSizes)==null?void 0:o[t])||e.image||n;if(!r)return null;try{return new URL(r).toString()}catch(i){return null}}function G0(e){return e.replace("https://www.","").replace("https://","")}var Mn=S(k()),X4=3,Q4=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),Z4=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=X4})=>{let i=M("LinkSearch",tA),[s,a]=(0,Tr.useState)(""),l=fe(),u=W(uP("url")),c=W(BT("URL")),f=(0,Tr.useMemo)(()=>c.map(Q4),[c]),[d,p]=(0,Tr.useState)(f.length-1),h=Y("fallbackImage"),y=x=>{let w=x.target;a(w.value)},g=(x,w)=>{x.stopPropagation(),x.preventDefault(),window.open(w,"_blank")},m=x=>{var T;let w=d-1<0?f.length-1:d-1,C=d+1===f.length?0:d+1;x.code==="Escape"&&(a(""),t()),x.code==="ArrowUp"&&p(w),x.code==="ArrowDown"&&p(C),x.code==="Enter"&&e(((T=f[d])==null?void 0:T.text)||s)},v=(0,Tr.useCallback)((0,nA.default)(x=>{l(bi({query:x,type:"URL",tags:["link-search"]}))},300),[]);return(0,Tr.useEffect)(()=>{s&&v(s)},[s]),(0,Tr.useEffect)(()=>()=>{l(jf())},[]),(0,Mn.jsxs)("div",{className:i.root,children:[(0,Mn.jsx)(Xt,{withDivider:!0,children:(s?f:u).slice(0,o).map((x,w)=>(0,Mn.jsx)(be,{selected:d===w,onClick:()=>e(x.text),"data-testid":"linksearch-suggestion",children:(0,Mn.jsxs)(Oe,{children:[(0,Mn.jsx)(Oe.Image,{src:hm(x,"small",h||void 0),title:x.title||x.text}),(0,Mn.jsxs)(Oe.Content,{className:i.content,cropText:!0,children:[(0,Mn.jsx)(Oe.Title,{children:x.title||G0(x.text)}),x.title&&G0(x.text)]}),(0,Mn.jsx)(be.Actions,{children:(0,Mn.jsx)(be.ActionButton,{label:r,onClick:C=>g(C,x.text)})})]})},x.text))}),(0,Mn.jsx)(vu,{value:s,onChange:y,autoFocus:!0,placeholder:n,onKeyUp:m})]})},rA=Z4;var Y0={};Mt(Y0,{enUS:()=>J4,nlNL:()=>eF});var J4={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},eF={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var Kt=S(k()),tF=(0,$t.forwardRef)((e,t)=>{let n=M("TabCompletion",to);return(0,Kt.jsx)("mark",{ref:t,className:(0,ym.default)(n.matchSelection)},"selection-start")}),nF=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let i=re(Y0),s=M("TabCompletion",to),a=(0,$t.useRef)(null),l=(0,$t.useRef)(null),[u,c]=(0,$t.useState)(null),f=fe(),d=Sp(document.activeElement===r),[p]=(0,$t.useState)(()=>document.createRange());d.triggerRef.current=p,(0,$t.useEffect)(()=>()=>p.detach(),[]),(0,$t.useEffect)(()=>{let y=e.current,g=a.current;!y||!g||(p.setStart(y,0),p.setEnd(g,0))},[e.current,a.current]),jo(()=>{d.close()});let h=(0,$t.useCallback)(y=>{let g=p.toString(),m=/^http(s?):\/\//.test(y)?y:`https://${y}`;f(Df({text:`[${g}](${m})`,replace:"selection"}))},[]);return(0,Kt.jsxs)("span",{children:[(0,Kt.jsx)("mark",{ref:a,className:(0,ym.default)(s.matchSelection),"aria-haspopup":"dialog","aria-expanded":d.opened?"true":"false",children:o}),d.opened&&(0,Kt.jsx)(ha,{className:s.popoverRoot,triggerRef:d.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,Kt.jsxs)(fm,{style:n,ref:l,children:[(0,Kt.jsx)("div",{className:(0,ym.default)(s.selectionOptions,{[s.selectionOptionsIsHidden]:u!==null}),children:(0,Kt.jsxs)("button",{type:"button",tabIndex:u===null?-1:void 0,className:s.selectionOptionsButton,onClick:()=>c("insertLink"),children:[(0,Kt.jsx)(eA,{}),(0,Kt.jsx)("span",{children:"\xA0"}),(0,Kt.jsx)("span",{children:i("insertLink")})]})}),u==="insertLink"&&(0,Kt.jsx)(rA,{placeholder:i("linkInputPlaceholder"),visitUrlText:i("visitUrl"),onSelectLink:h,onDismiss:()=>{c(null),d.close()}})]})})]},"selection-end")},vm=class extends $r{constructor(){super(...arguments);this.charCount=0;this.foundIndex=0;this.startRef=null}onBeforeParse(n,r){return this.props=r,this.charCount=0,this.startRef=(0,$t.createRef)(),this.foundIndex=0,n}match(n){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[r,o]=this.props.selection;if(r===o)return null;let i=this.foundIndex===0?r:o,s=i>=this.charCount&&i<=this.charCount+n.length?{index:i-this.charCount,length:0,match:"",valid:!0}:null;s&&this.foundIndex++;let a=this.foundIndex===1;return s&&a?this.charCount+=i-this.charCount:this.charCount+=n.length,s?b({isStart:a},s):null}replaceWith(n,r){return r.isStart?(0,Kt.jsx)(tF,{ref:this.startRef}):(0,Kt.jsx)(nF,{inputElement:r.inputElement,startRef:this.startRef,boundaryRef:r.boundaryRef,inputStyle:r.inputStyle})}asTag(){return"mark"}};var no=S(k()),rF=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:i,keywordMatches:s,inputElement:a,source:l})=>{let u=M("TabCompletion",qP),c=Y("insertLink"),f=Y("showMidSentenceSuggestions"),d=Y("inlineSuggestions"),p=WP(a),h=(0,ro.useRef)(null),y=W(Ft);(0,ro.useEffect)(()=>{Xi(a)&&p&&KP(a,p)},[p]);let g=(0,ro.useCallback)(x=>{if(!o||!n)return x;let w=[(0,no.jsx)("span",{className:u.resetIndent,children:"\u200B"},"u200B"),(0,no.jsx)("span",{"data-testid":"tab-completion",className:(0,xm.default)(u.tabText,u.resetIndent),"data-source":l,children:n},"tabText")];return r&&w.push((0,no.jsx)("span",{className:(0,xm.default)(u.hint,u.resetIndent),children:(0,no.jsx)(Oc,{keyCode:"tab"},"tabHint")})),W0(x,w)},[o,n,r]),m=(0,ro.useMemo)(()=>{let x=[];return c&&x.push(new vm("selection")),x.push(new gm("placeholders")),i&&x.push(new pm("keywords")),x},[d,c,i]),v=(0,ro.useMemo)(()=>{let x=window.getComputedStyle(a);return{"--dd-color":x.color,"--dd-font-size":x.fontSize,"--dd-font-family":x.fontFamily,"--dd-font-variant":x.fontVariant}},[]);return!e||!y?null:(0,no.jsxs)("div",{ref:x=>{x!=null&&x.parentElement&&(h.current=x==null?void 0:x.parentElement)},className:u.root,style:v,children:[(0,no.jsx)(la,{tagName:"span",containerTagName:"div",className:(0,xm.default)(u.container,u.agentText),disableLineBreaks:Xi(a),content:t||"\u200B",onAfterParse:g,matchers:m,selection:p,keywordMatches:s,inputElement:a,inputStyle:v,boundaryRef:h,inlineSuggestionsOnlyAtEnd:!f}),(0,no.jsx)("br",{})]})},oF=e=>{var g,m,v;let{input:t,ui:n,settings:r,styleSuggestions:o,conversation:i}=e,s=oa({input:t}),a=(s==null?void 0:s.text)||"",l=(s==null?void 0:s.source)||"",u=(g=t.html)!=null?g:ua(t.text),c=a.indexOf(t.text)===0?a.slice(t.text.length):"",{showTabHint:f}=n,{isSupported:d}=i,{showTabCompletion:p,visible:h,showStyleSuggestions:y}=r;return{showTabHint:f,showStyleSuggestions:y,showTabCompletion:p&&Er(e),content:u,tabText:c,source:l,keywordMatches:(v=(m=o.list)==null?void 0:m.keywordMatches)!=null?v:[],enabled:h&&d!==!1}},oA=xi(oF)(rF);var Da=S(K());var iF={token:null,interval:null},X0=de("passwordlessToken/getTemporaryPasswordlessToken",(e,t)=>P(void 0,null,function*(){let{deepdeskAPI:n}=t.extra;return{token:yield n.requestPasswordlessToken()}})),Q0=de("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(X0()),setInterval(()=>r(X0()),n)}),iA=Te({name:"passwordlessToken",initialState:iF,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(X0.fulfilled,(t,n)=>{t.token=n.payload.token}),e.addCase(Q0.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:sA}=iA.actions,aA=iA.reducer;function sF(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t}var lA=zn([dC],e=>e.map(n=>({text:n.response,title:n.name,callToAction:n.callToAction,isLoading:n.isLoading,specialType:n.specialType,rule:{id:sF(n.code),label:n.code,name:n.name,description:n.name}})));var wm=S(K());var J0=S(De());var Z0=S(k()),uc=()=>(0,Z0.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,Z0.jsx)("path",{d:"M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"})});var uA={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};var Cr=S(k()),aF=({entities:e})=>{let t=M("EntitiesWidgetList",uA),[n,r]=(0,wm.useState)(void 0),o=fe(),i=()=>{r(void 0)},s=a=>{e&&(r(e.indexOf(a)),vr(a.text),o(Vr({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,wm.useEffect)(()=>{let a=setTimeout(i,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,Cr.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,Cr.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>s(a),children:[(0,Cr.jsx)("span",{className:t.entityText,children:a.text}),(0,Cr.jsxs)("span",{className:t.iconWrapper,children:[(0,Cr.jsx)("span",{className:(0,J0.default)(t.icon),children:(0,Cr.jsx)(uc,{})}),(0,Cr.jsx)("span",{className:(0,J0.default)(t.icon,n===l&&t.iconClicked),children:(0,Cr.jsx)(uc,{})})]})]},a.text))})},cA=aF;var ex=S(k()),dA=()=>(0,ex.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,ex.jsx)("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});var tx=S(k()),fA=()=>(0,tx.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,tx.jsx)("path",{d:"M543-340q16.595 0 28.798-12.202Q584-364.405 584-381t-12.202-28.798Q559.595-422 543-422t-28.798 12.202Q502-397.595 502-381t12.202 28.798Q526.405-340 543-340Zm-25-126h47q2-29 8.5-43t32.5-39q27-26 37.5-45.395Q654-612.79 654-639q0-45.882-31.5-74.941Q591-743 540-743q-38 0-68 20.5T428-665l45 19q11-25 27.5-38t39.5-13q29.778 0 48.389 17Q607-663 607-637q0 20-9 35t-32 32q-32 29-40 46.5t-8 57.5ZM260-200q-24 0-42-18t-18-42v-560q0-24 18-42t42-18h560q24 0 42 18t18 42v560q0 24-18 42t-42 18H260Zm0-60h560v-560H260v560ZM140-80q-24 0-42-18t-18-42v-620h60v620h620v60H140Zm120-740v560-560Z"})});var nx=S(k()),pA=()=>(0,nx.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,nx.jsx)("path",{d:"M319-250h322v-60H319v60Zm0-170h322v-60H319v60ZM220-80q-24 0-42-18t-18-42v-680q0-24 18-42t42-18h361l219 219v521q0 24-18 42t-42 18H220Zm331-554v-186H220v680h520v-494H551ZM220-820v186-186 680-680Z"})});var mA={root:"dd-ohnXe",trigger:"dd-7i-S3",button:"dd-t53Cg",nav:"dd-qZFnm",item:"dd-FZC0F"};var gA={root:"dd-nazq3",rotation:"dd-3EHTv"};var yA=S(k()),lF=({size:e=12})=>{let t=M("LoadingSpinner",gA);return(0,yA.jsx)("span",{style:{width:`${e}px`,height:`${e}px`},className:t.root})},hA=lF;var rx=S(k()),vA=()=>(0,rx.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 512 512",fill:"currentColor",children:(0,rx.jsx)("path",{d:"M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224c0-17.7-14.3-32-32-32s-32 14.3-32 32s14.3 32 32 32s32-14.3 32-32z"})});var nr=S(k()),uF=()=>{let e=M("OnDemandAssistants",mA),t=Yr(Vn),n=Yr(jn),r=W(vC),o=W(xC),i=W(fC),s=at(),a=o.filter(c=>c.isPinned),l=o.filter(c=>!c.isPinned),u=c=>{if(s("trigger on demand assistant",{assistantCode:c}),c===r){n.call({transcript:"in-memory-transcript"});return}t.call({assistantCode:c,expectFormat:"json-schema:cues",transcript:"in-memory-transcript"})};return o.length===0?null:(0,nr.jsxs)("div",{className:e.root,children:[a.map(({assistant:c,assistantName:f})=>(0,nr.jsx)("button",{type:"button",className:e.button,disabled:i==="loading",onClick:()=>u(c),children:f},c)),l.length>0&&(0,nr.jsxs)(an,{placement:"top-end",children:[(0,nr.jsxs)(an.Trigger,{className:e.trigger,children:[i==="loading"&&(0,nr.jsx)(hA,{}),i==="error"&&(0,nr.jsx)(vA,{}),!["loading","error"].includes(i)&&(0,nr.jsx)(kp,{"data-testid":"trigger"})]}),(0,nr.jsx)(an.Content,{className:e.nav,children:l.map(({assistant:c,assistantName:f})=>(0,nr.jsx)(an.Button,{className:e.item,disabled:i==="loading",onClick:()=>u(c),children:f},c))})]})]})},xA=uF;var bA=S(K());var wA={loadingBar:"dd-6as-V",placeHolderShimmer:"dd-TFYmA"};var SA=S(k()),cF=({width:e})=>{let t=M("LoadingProgressBar",wA);return(0,SA.jsx)("div",{className:t.loadingBar,style:{width:e}})},Sm=cF;var oo=S(k()),bm=({title:e})=>{let t=(0,bA.useRef)(null);return bw(t),(0,oo.jsx)(be,{ref:t,children:(0,oo.jsx)(Oe,{children:(0,oo.jsxs)(Oe.Content,{children:[(0,oo.jsx)(Oe.Title,{children:e}),(0,oo.jsx)(Sm,{width:"60%"}),(0,oo.jsx)(Sm,{width:"90%"}),(0,oo.jsx)(Sm,{width:"50%"})]})})})};var cc={};Mt(cc,{enUS:()=>dF,nlNL:()=>fF});var dF={useCue:[{type:0,value:"Add to message"}],__summarizerAssistant__:[{type:0,value:"Summary"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},fF={useCue:[{type:0,value:"Voeg toe aan bericht"}],__summarizerAssistant__:[{type:0,value:"Samenvatting"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var Qi=S(K());var ox={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 It=S(k()),pF=500,mF=100,gF=({content:e,onChange:t,onCopy:n})=>{let r=(0,Qi.useRef)(null),o=M("WidgetCue",ox);return(0,Qi.useEffect)(()=>{let i=r.current;if(!i)return;i.style.setProperty("height","0px");let s=Math.min(Math.max(i.scrollHeight,mF),pF);i.style.setProperty("height",`${s}px`)},[e]),(0,It.jsx)("textarea",{ref:r,className:o.editableCue,onCopy:n,onChange:t,value:e})},hF=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o})=>{var y;let i=M("WidgetCue",ox),s=re(cc),a=at(),l=Y("hasKeyboardInput"),[u,c]=(0,Qi.useState)(e.text),f=()=>{t&&t(e),n(e)},d=g=>{r&&r(g,e)},p=g=>{o&&o(g,e)},h=g=>{g.preventDefault(),g.stopPropagation(),n(e)};return(0,Qi.useEffect)(()=>{a("Assistant response displayed",{name:e.rule.name,description:e.rule.description,group:e.rule.label,cueText:e.text})},[]),(0,It.jsxs)(be,{"data-testid":"cue",children:[(0,It.jsx)(Oe,{children:(0,It.jsxs)(Oe.Content,{children:[e.title&&(0,It.jsx)(Oe.Title,{className:i.title,"data-testid":"widget-cue-title",children:e.rule.label.startsWith("__")?s(e.rule.label):e.title}),e.specialType==="summary"?(0,It.jsx)(gF,{content:u,onCopy:()=>{let g=document.getSelection();g&&d(g.toString())},onChange:g=>{var m;return c((m=g.target.value)!=null?m:"")}}):(0,It.jsx)(zi,{content:e.text,useLabel:s("useCue"),copyLabel:s("copyCue"),onCopy:d,onUse:l?p:void 0})]})}),(0,It.jsxs)(be.ButtonsContainer,{children:[(0,It.jsxs)("div",{className:i.actions,children:[e.specialType==="summary"&&(0,It.jsx)(be.Button,{onClick:()=>d(u),children:s("copyCue")}),e.callToAction&&(0,It.jsx)(be.Button,{onClick:f,children:e.callToAction.label}),(0,It.jsx)(be.Button,{onClick:h,children:s("removeCue")})]}),e.specialType==="summary"?(0,It.jsx)(Mi,{eventName:"summary feedback",feedbackText:(y=e.text)!=null?y:"",feedbackType:"summary",eventData:{summary:e.text}}):(0,It.jsx)(Mi,{eventName:"Assistant response feedback",eventData:{name:e.rule.name,group:e.rule.label,description:e.rule.description,cueText:e.text},feedbackText:e.text,feedbackType:"assistant"})]})]})},EA=hF;var Ma=S(k()),yF=({cues:e})=>{let t=fe(),n=nn(),r=re(cc),o=at(),i=u=>{t(mC({code:u.rule.label})),o("Assistant response closed",{name:u.rule.name,group:u.rule.label,description:u.rule.description,cueText:u.text})},s=(u,c)=>{switch(vr(u),c.specialType){case"summary":o("summary copied to clipboard",{originalText:c.text,finalText:u,assistant:c.rule.label});break;default:o("Assistant response copied",{name:c.rule.name,group:c.rule.label,description:c.rule.description,copiedText:u})}},a=u=>{u.callToAction&&(t(ep(u)),o("Assistant call to action",{name:u.rule.name,group:u.rule.label,description:u.rule.description,eventName:u.callToAction.event,value:u.callToAction.value}))},l=(u,c)=>{n.send(yr,{text:u,suggestion:{source:"cue",sourceText:u}}),o("Assistant response used",{name:c.rule.name,group:c.rule.label,description:c.rule.description,usedText:u})};return(0,Ma.jsx)(Ma.Fragment,{children:e.map(u=>u.isLoading?(0,Ma.jsx)(bm,{title:u.rule.label.startsWith("__")?r(u.rule.label):u.title},u.rule.id):(0,Ma.jsx)(EA,{cue:u,onCallToAction:a,onRemove:i,onCopy:s,onUse:l},u.rule.id))})},TA=yF;var Em=S(K());var CA={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var rr=S(k());function vF(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var kA=({data:e,schema:t})=>{let n=M("WidgetCustomData",CA),r=o=>{vr(o)};return(0,Em.useEffect)(()=>{X.info("Custom data",e,t)},[e]),(0,rr.jsx)("dl",{className:n.root,children:t.map(o=>{let i=vF(e,o.path);return(0,rr.jsxs)(Em.Fragment,{children:[(0,rr.jsx)("dt",{className:n.label,children:o.label}),(0,rr.jsx)("dd",{className:n.value,children:o.type==="boolean"&&i?(0,rr.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!i?(0,rr.jsx)("span",{className:n.isFalse,children:o.falseValue}):i?(0,rr.jsxs)("button",{type:"button",onClick:()=>r(i),className:n.copyButton,children:[(0,rr.jsx)("span",{className:n.copyButtonText,children:i}),(0,rr.jsx)(uc,{})]}):"-"})]},o.label)})})};var yt=S(K());var ix=S(k()),RA=()=>(0,ix.jsx)("svg",{focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"ReplayIcon",children:(0,ix.jsx)("path",{d:"M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8"})});var Na={};Mt(Na,{enUS:()=>xF,nlNL:()=>wF});var xF={titleKnowledgeAssistant:[{type:0,value:"Knowledge Assistant"}],inputPlaceholder:[{type:0,value:"What is your question?"}],useCue:[{type:0,value:"Add to message"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Submit"}],resetLabel:[{type:0,value:"Reset"}],showMore:[{type:0,value:"Show "},{type:1,value:"amount"},{type:0,value:" more"}]},wF={titleKnowledgeAssistant:[{type:0,value:"Knowledge Assistant"}],inputPlaceholder:[{type:0,value:"Wat is je vraag?"}],useCue:[{type:0,value:"Voeg toe aan bericht"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Verzend"}],resetLabel:[{type:0,value:"Reset"}],showMore:[{type:0,value:"Toon "},{type:1,value:"amount"},{type:0,value:" meer"}]};var sx={form:"dd-pleCH",formInput:"dd-pGJMY",formSubmit:"dd--gkRg",actionButton:"dd-I2NEH",sources:"dd-xf9c6",source:"dd-a-vyX",tooltip:"dd-EsgcZ",linkContent:"dd-gARDA",showMoreSources:"dd-uDGi-"};var xe=S(k()),SF=3,bF=({sources:e,onClick:t})=>{let n=re(Na),r=M("WidgetKnowledgeAssistant",sx),[o,i]=(0,yt.useState)(!1),s=o?e:e.slice(0,SF);return s.length===0?null:(0,xe.jsxs)("ul",{className:r.sources,children:[s.map(a=>(0,xe.jsx)("li",{className:r.source,"data-testid":"knowledge-assist-source",children:(0,xe.jsxs)(an,{tooltip:!0,placement:"top-start",children:[(0,xe.jsx)(an.Trigger,{as:"a",rel:"noreferrer",target:"_blank",href:a.url,onClick:l=>{l.stopPropagation(),t(a)},children:(0,xe.jsx)("span",{className:r.linkContent,children:a.name})}),a.url&&(0,xe.jsx)(an.Content,{className:r.tooltip,children:decodeURIComponent(a.url)})]})},a.name)),s<e&&(0,xe.jsx)("button",{type:"button",className:r.showMoreSources,onClick:()=>i(!0),children:n("showMore",{amount:e.length-s.length})})]})},EF=({title:e,description:t})=>(0,xe.jsx)(be,{"data-testid":"knowledge-assist-empty-state",children:(0,xe.jsx)(Oe,{children:(0,xe.jsxs)(Oe.Content,{children:[(0,xe.jsx)(Oe.Title,{children:e}),(0,xe.jsx)(zi,{content:t})]})})}),TF=({innerRef:e,item:t,index:n,hasKeyboardInput:r,onCopy:o,onUse:i,onSourceClick:s})=>{var l;let a=re(Na);return(0,xe.jsxs)(be,{"data-testid":"knowledge-assist-answer",ref:e,children:[(0,xe.jsx)(Oe,{children:(0,xe.jsxs)(Oe.Content,{children:[(0,xe.jsx)(Oe.Title,{children:t.question}),(0,xe.jsx)(zi,{content:t.answer.answer,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:o,onUse:r?i:void 0}),(0,xe.jsx)(bF,{sources:(l=t.answer.sources)!=null?l:[],onClick:u=>s(u,t.question)})]})}),(0,xe.jsxs)(be.ButtonsContainer,{children:[(0,xe.jsx)("div",{}),(0,xe.jsx)(Mi,{eventName:"knowledge assist feedback",eventData:{question:t.question,isFollowUpQuestion:n>0,isAgent:!0,answer:t.answer.answer},feedbackText:t.answer.answer,feedbackType:"assistant"})]})]})},ax=(0,yt.createContext)(null),Tm=({assistantCode:e,evaluateKnowledgeAssistFn:t,initialQuestion:n,children:r})=>{let[o,i]=(0,yt.useState)(null),[s,a]=(0,yt.useState)(!1),[l,u]=(0,yt.useState)(!!n),[c,f]=(0,yt.useState)(null),d=fe(),p=at(),h=Yr(m=>{if(!e)throw new Error("No knowledge assistant was defined");return t({assistantCode:e,input:m,threadId:o,onNewThreadId(v){i(v)}})},{onSuccess(m){var v;p("knowledge assist question answered",{question:m.question,answer:m.answer.answer,sources:(v=m.answer.sources)!=null?v:[],isFollowUpQuestion:m.threadId===o,isAutoInitiated:l}),u(!1)}}),y=m=>P(void 0,null,function*(){a(!0),f(m),yield h.call(m),a(!1),f(null)}),g={isEnabled:!!e,isSubmitting:s,threadId:o,pendingInput:c,onSubmit:y,onReset(){o&&d(aa(o)),i(null)}};return(0,yt.useEffect)(()=>{n&&y(n)},[n]),(0,xe.jsx)(ax.Provider,{value:g,children:r})},Cm=()=>{let e=re(Na),t=M("WidgetKnowledgeAssistant",sx),n=(0,yt.useContext)(ax),r=(0,yt.useRef)(null),[o,i]=(0,yt.useState)(""),s=u=>{i(u.target.value)},a=u=>{u.preventDefault(),n.onSubmit(o).then(()=>{var c;r.current&&((c=r.current)==null||c.focus(),i(""))})},l=u=>{u.preventDefault(),n.onReset()};return n.isEnabled?(0,xe.jsxs)("form",{className:t.form,onSubmit:a,children:[(0,xe.jsx)("input",{ref:r,className:t.formInput,placeholder:e("inputPlaceholder"),type:"text",disabled:n.isSubmitting,value:o,onChange:s}),(0,xe.jsx)("button",{type:"submit",disabled:n.isSubmitting||o==="",className:t.formSubmit,children:e("submitLabel")}),(0,xe.jsx)("button",{type:"button",title:e("resetLabel"),disabled:n.threadId===null||n.isSubmitting,onClick:l,className:t.actionButton,children:(0,xe.jsx)(RA,{})})]}):null},km=({emptyState:e})=>{var f,d;let t=re(Na),n=at(),r=(0,yt.useRef)(null),o=(0,yt.useContext)(ax),i=(d=W(wu((f=o.threadId)!=null?f:-1)))!=null?d:[],s=Y("hasKeyboardInput"),a=nn(),l=p=>{vr(p),n("Assistant response copied",{name:"Knowledge Assistant",group:"knowlegde-assist",description:"",copiedText:p})},u=(p,h)=>{n("knowledge assist source viewed",{question:h,sourceViewed:p.url||p.name})},c=p=>{a.send(yr,{text:p,suggestion:{source:"cue",sourceText:p}}),n("Assistant response used",{name:"Knowledge Assistant",group:"knowlegde-assist",description:"",usedText:p})};return!o.isEnabled||(i==null?void 0:i.length)===0&&!o.isSubmitting&&!e?null:(0,xe.jsx)(ar,{type:"knowledge",title:t("titleKnowledgeAssistant"),"data-testid":"knowledge",children:(0,xe.jsxs)(Xt,{withDivider:!0,children:[e&&i.length===0&&!o.pendingInput&&(0,xe.jsx)(EF,b({},e)),i.map((p,h)=>(0,xe.jsx)(TF,{innerRef:h===i.length-1?r:void 0,item:p,index:h,hasKeyboardInput:s,onCopy:l,onUse:c,onSourceClick:u},`${p.question}_${p.answer}_${h}`)),o.pendingInput&&(0,xe.jsx)(bm,{title:o.pendingInput})]})})};var IA=S(K());var CF=/(https?:\/\/[^\s]+)/,AA=e=>e.split(" ").find(t=>CF.test(t));var Nn=S(k()),kF=({suggestion:e,lines:t,onUse:n})=>{var f;let r=e.text||e.url||e.message,o=AA(r),i=re(Wu),s=Y("showImages"),a=Y("fallbackImage"),l=Y("hasKeyboardInput"),u=d=>{d.preventDefault(),d.stopPropagation(),l&&n(r)},c=(0,IA.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,Nn.jsxs)(be,{onClick:l?u:void 0,"data-testid":"edit-suggestion",children:[(0,Nn.jsxs)(Oe,{children:[s&&e.image&&(0,Nn.jsx)(Oe.Image,{src:hm(e,"small",a||void 0),title:e.title}),(0,Nn.jsxs)(Oe.Content,{children:[e.title&&(0,Nn.jsx)(Oe.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((f=e.searchKeywords)==null?void 0:f.length)>0&&(0,Nn.jsx)(be.Labels,{labels:e.searchKeywords}),(0,Nn.jsx)(Oe.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,Nn.jsxs)(be.Actions,{children:[o&&(0,Nn.jsx)(be.ActionButton,{onClick:c,label:i("visitUrl")}),l&&(0,Nn.jsx)(be.ActionButton,{primary:!0,onClick:u,label:i("useSuggestion")})]})]})},LA=kF;var dc=S(k()),RF=({lines:e,suggestions:t})=>{let n=nn(),r=(o,i)=>{n.send(yr,{text:o,suggestion:A(b({},i),{source:i.source,sourceText:i.text})})};return(0,dc.jsx)(dc.Fragment,{children:t.map(o=>(0,dc.jsx)(LA,{suggestion:o,lines:e,onUse:i=>r(i,o)},o.text||o.url||o.message))})},OA=RF;var Rm={};Mt(Rm,{enUS:()=>PF,nlNL:()=>AF});var PF={waiting:[{type:0,value:"Loading\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"My "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Summarize"}],linkKnowledgeSearch:[{type:0,value:"Knowledge Assist"}],linkSearch:[{type:0,value:"Search"}]},AF={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"Mijn "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Gesprek samenvatten"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}]};var _a={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 oe=S(k()),NA=(e,t)=>{let n=W(Ft);(0,Da.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},IF=({onLogIn:e})=>{let t=M("Widget",_a),n=Y("isEmbedded"),r=Y("adminUrl");return(0,oe.jsx)("div",{className:t.loginText,children:(0,oe.jsx)("div",{children:(0,oe.jsx)(sm,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},MA=({text:e})=>{let t=M("Widget",_a);return(0,oe.jsx)("div",{className:t.stateText,children:(0,oe.jsx)("div",{children:(0,oe.jsx)("p",{children:e})})},"notification")},LF=()=>{let e=re(Rm),t=fe(),n=M("Widget",_a),r=Y("showSearch"),o=Y("showSummaryCommand"),i=Y("showKnowledgeSearch"),s=W(Ev("knowledge-assist")),a=Y("isEmbedded"),l=W(ma("/admin/")),u=nn(),c=Y("productName"),f=Y("hasKeyboardInput"),d=Yr(()=>jn({})),p=at(),h=r||o||i||l;return NA(()=>{if(a)return t(Q0()),()=>{t(sA())}},[t,a]),!h||!f?null:(0,oe.jsx)(ar,{title:e("actions"),type:"shortcuts",children:(0,oe.jsxs)("div",{className:n.shortcutList,children:[r&&(0,oe.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-search","aria-label":e("linkSearch"),onClick:()=>{u.send("ShowCommandPalette",{isOpen:!0}),p("open search",{via:"widget-shortcut"})},children:[(0,oe.jsx)(ca,{}),e("linkSearch")]}),o&&!s&&(0,oe.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-summary","aria-label":e("linkSummary"),disabled:d.state==="loading",onClick:()=>d.call(),children:[(0,oe.jsx)(pA,{}),e("linkSummary")]}),i&&!s&&(0,oe.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-knowledge-assist","aria-label":e("linkKnowledgeSearch"),onClick:()=>{u.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),p("open knowledge assistant",{via:"widget-shortcut"})},children:[(0,oe.jsx)(fA,{}),e("linkKnowledgeSearch")]}),l&&(0,oe.jsxs)("a",{className:n.shortcut,target:"_blank",href:l,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:c}),rel:"noreferrer",onClick:()=>{p("open my deepdesk",{via:"widget-shortcut"})},children:[(0,oe.jsx)(dA,{}),e("linkStudioLogin",{productName:c})]})]})})},OF=()=>{let e=fe(),t=W(Eu),n=W(wC),r=W(lA),o=W(LT),i=W(mp),s=W(Zp),a=W(ki),l=W(hr);return(0,Da.useEffect)(()=>{!!o&&!n&&X.warn("Custom data provided, but no schema.")},[o,n]),NA(()=>{t.forEach(({type:u})=>{u==="entities"?e($n()):_c.includes(u)||e(tr(u))})},[e,l,a]),(0,Da.useEffect)(()=>{r.length>0&&!t.some(u=>u.type==="cues")&&X.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,oe.jsx)(Da.Fragment,{children:t.map(({type:u,title:c,amount:f,lines:d,schema:p})=>{var h,y;switch(u){case"entities":return i&&i.length>0&&(0,oe.jsx)(ar,{type:u,title:c,"data-testid":`type-${u}`,children:(0,oe.jsx)(cA,{entities:i})},u);case"cues":return r&&r.length>0&&(0,oe.jsx)(ar,{type:u,title:c,"data-testid":`type-${u}`,children:(0,oe.jsx)(Xt,{withDivider:!0,children:(0,oe.jsx)(TA,{cues:r})})},u);case"custom-data":return o&&p&&(0,oe.jsx)(ar,{type:u,title:c,"data-testid":`type-${u}`,children:(0,oe.jsx)(Xt,{withDivider:!0,children:(0,oe.jsx)(kA,{data:o,schema:p})})},u);default:return((y=(h=s[u])==null?void 0:h.suggestions)==null?void 0:y.length)>0&&(0,oe.jsx)(ar,{type:u,title:c,"data-testid":`type-${u}`,children:(0,oe.jsx)(Xt,{withDivider:!0,children:(0,oe.jsx)(OA,{lines:d,contentType:u,suggestions:s[u].suggestions.slice(0,f)||[]})})},u)}})})},lx=({children:e})=>{let t=M("Widget",_a);return(0,oe.jsx)("div",{className:t.footer,children:e})},ux=({children:e})=>{let t=M("Widget",_a);return(0,oe.jsx)("div",{className:t.root,"data-testid":"widget",children:e})},MF=({onLogIn:e,knowledgeAssistOptions:t={}})=>{let n=re(Rm),r=W(na),o=W(Ft),i=W(gT),s=W(ki),a=W(Ev("knowledge-assist")),l=W(tp),u=W(np);return r===!1?(0,oe.jsx)(MA,{text:n("notSupported")}):o===!1?(0,oe.jsx)(IF,{onLogIn:e}):!s||!i||o===null?(0,oe.jsx)(MA,{text:n("waiting")}):(0,oe.jsx)(ux,{children:(0,oe.jsxs)(Tm,{initialQuestion:t.initialQuestion,assistantCode:l!=null?l:u,evaluateKnowledgeAssistFn:u?Ti:Ci,children:[(0,oe.jsxs)(cs,{children:[(0,oe.jsx)(LF,{}),(0,oe.jsx)(OF,{}),a&&(0,oe.jsx)(km,{emptyState:t.emptyState})]}),(0,oe.jsxs)(lx,{children:[a&&(0,oe.jsx)(Cm,{}),(0,oe.jsx)(xA,{})]})]})})},_A=MF;function Fa(e){let t=new Range;return t.selectNodeContents(e),t}function DA(e,t,n){try{return Qo(e,t,n),!0}catch(r){return!1}}function Pm(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function Am(e){return"tagName"in e&&e.tagName==="BR"}var fc=/[\u200B-\u200D\uFEFF]/g;function Qo(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,i=!1;function s(l,u){let c=-1,f=/[\u200B-\u200D\uFEFF]/;if(!f.test(l))return u;for(let d=0;d<=l.length;d++)if(f.test(l[d])||c++,c===u)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let u=l.textContent,c=u.replace(fc,""),f=o+c.length,d=t>=o&&t<=f,p=n>=o&&n<=f;if(d){let h=s(u,t-o);h===0&&!p?r.setStartBefore(l):r.setStart(l,h)}p&&(r.setEnd(l,s(u,n-o)),i=!0),o=f;break}case Node.ELEMENT_NODE:{if(Am(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),i=!0;return}for(let c=0;c<l.childNodes.length&&(a(l.childNodes[c]),!i);c++);let u=l.lastChild;Pm(l)&&u&&!Pm(u)&&!Am(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function pc(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a,l,u=0;function c(f){let d=f===e,p=f===n,h=f===o;switch(f.nodeType){case Node.TEXT_NODE:{let y=f.textContent;p&&(a=u+y.substring(0,r).replace(fc,"").length),h&&(l=u+y.substring(0,i).replace(fc,"").length),u+=y.replace(fc,"").length;break}case Node.ELEMENT_NODE:{if(Am(f)&&f.nextSibling){u++;break}!d&&Pm(f)&&f.previousSibling&&u++;for(let y=0;y<f.childNodes.length;y++){let g=p&&y===r,m=h&&y===i;if(g&&(a=u),m&&(l=u),l!==void 0||((!g||!s)&&c(f.childNodes[y]),h&&y===i-1&&(l=u),l!==void 0))break}h&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:l,end:l}}function mc(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a=0,l="";function u(c){let f=c===e,d=c===n,p=c===o;switch(d&&(a=1),c.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let h=d?r:0,y=p?i:void 0;l+=c.textContent.replace(fc,"").substring(h,y);break}case Node.ELEMENT_NODE:{if(!s&&a===1&&Am(c)&&c.nextSibling){l+=`
|
|
82
82
|
`;break}!f&&!s&&a===1&&Pm(c)&&c.previousSibling&&(l+=`
|
|
83
|
-
`);let h=d?r:0,y=p?Math.min(i,c.childNodes.length):c.childNodes.length;for(let g=h;g<y&&(u(c.childNodes[g]),a!==2);g++);break}default:break}p&&(a=2)}return u(e),l}var FA=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(FA||{}),io=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();Do(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(FA).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 HA(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Zi=class extends io{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),mc(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var s;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(s=r.getComposedRanges(n))==null?void 0:s[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!HA(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!HA(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return pc(this.element,n);let r=this.lastKnownSelection;if(r&&DA(this.element,r.start,r.end))return r;let o=Fa(this.element);return o.collapse(!1),pc(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return mc(this.element,Qo(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 NF=["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 zA(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",NF.forEach(function(c){o[c]=i[c]}),n?e.scrollHeight>parseInt(i.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),s.appendChild(r);let l=e.getBoundingClientRect(),u={top:l.top-e.scrollTop+a.offsetTop+parseInt(i.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+parseInt(i.borderLeftWidth)};return s.removeChild(r),u}var Ji=class extends io{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 zA(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 BA(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function _F(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var cx=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()}},dx=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=BA(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()}},fx=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),X.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new dx(t,this.deepdeskUrl,{debug:!0}):new cx(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=_F(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(X.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;X.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage(A(b({},o),{channel:this.sessionId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},UA=fx;function DF(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function $e(e){return Array.isArray(e)?e.map($e):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>A(b({},t),{[DF(n)]:$e(e[n])}),{}):e}function FF(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function vt(e){return Array.isArray(e)?e.map(vt):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>A(b({},t),{[FF(n)]:vt(e[n])}),{}):e}var Ha=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var px=e=>new Promise(t=>{setTimeout(t,e)});var za=class extends Ha{constructor(){super(...arguments);this.name="ClientError"}},gx=class extends Ha{constructor(){super(...arguments);this.name="ServerError"}},mx=new Map;function HF(e){return P(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(X.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var Zo=class Zo{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",T=n,{useCache:u=!1,abortLatest:c=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:h=R=>R instanceof TypeError,retryOnResponse:y=R=>R.status>=500,version:g=null}=T,m=te(T,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(mx.has(s)){r(mx.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let v=A(b({credentials:"include"},m),{headers:b({Accept:"application/json","Content-Type":"application/json"},m.headers)});!l&&this.csrfToken&&(v.headers=A(b({},v.headers),{"X-CSRFToken":this.csrfToken})),typeof g=="string"&&(v.headers=A(b({},v.headers),{"X-Deepdesk-API-Version":g}));let x=f,w=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&c&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let C=()=>P(this,null,function*(){return x--,a(s,v).then(R=>P(this,null,function*(){return y(R)&&!i.isAborted&&x>0?(yield px(d),C()):R.status===401&&p===!0&&w===!1?(w=!0,yield this.refreshToken(),C()):R})).catch(R=>P(this,null,function*(){if(h(R)&&!i.isAborted&&x>0)return yield px(d),C();throw R}))});C().then(R=>P(this,null,function*(){let I=yield HF(R);if(delete this.latestRequestByUrl[s],R.status>=500){o(new gx("Server Error",I));return}else if(R.status===401){o(new za("Unauthorized",I));return}else if(R.status===403){o(new za("Forbidden",I));return}else if(R.status===404){o(new za("Not Found",I));return}else if(R.status>=400){o(new za("Bad Request",I));return}u&&mx.set(s,I),r(I)})).catch(R=>{o(R)})})}validateToken(){return P(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)try{yield this.refreshToken()}catch(r){return!1}let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/");return!!n})}refreshToken(){return Zo.refreshingToken||(Zo.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{Zo.refreshingToken=null},1e3*60)})),Zo.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))}};Zo.refreshingToken=null;var es=Zo;var jA;(t=>{let e;(s=>(s.SEND_MESSAGE="Send Message",s.HANDLING_TIME="Handling Time",s.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",s.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||(t.EventType={}))})(jA||(jA={}));function Im(e){return A(b({},$e(e)),{tags:e.tags})}var ts=class ts{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new es(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>P(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return P(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(ts.exchangeTokenPromise||(ts.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),ts.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return P(this,null,function*(){yield this.preflight(),X.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",A(b({},vt(t)),{tags:t.tags}),{version:"v2"});return Im(n)})}getMe(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return $e(t)})}postIdentity(t){return P(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",vt(t))})}patchMe(t){return P(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",vt(t));return $e(n)})}getProfile(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return $e(n)})}getKnowledgeAssistant(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return $e(n)})}getContentTypes(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return $e(t)})}getAccount(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return $e(t)})}getPlatformConfig(t){return P(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return $e(r)})}checkUserExists(t){return P(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationBySessionId(r){return P(this,arguments,function*(t,n={}){yield this.preflight(),X.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return X.info(`Successfully retrieved conversation ${s.id} for session ${t}`),Im(s)})}isConversationSupported(r){return P(this,arguments,function*(t,n={}){X.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return P(this,null,function*(){yield this.preflight();let r=vt(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Im(o)})}postMessages(t,n){return P(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>A(b({},vt(o)),{tags:o.tags})),{version:"v2"})).map(o=>Im(o))})}sendEvent(t,n){return P(this,null,function*(){yield this.preflight();let s=n,{data:r}=s,o=te(s,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>A(b({},a),{[l]:u}),{});return this.client.post("/api/events",vt(A(b(b({},i),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return P(this,null,function*(){yield this.preflight();let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>A(b({},o),{[i]:s}),{});return this.client.post("/api/events",{event:t,data:vt(b(b({},n),r))},{version:"v1"})})}getEntities(t){return P(this,null,function*(){return yield this.preflight(),(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)},{version:"v1"})).entities})}getTemporaryExchangeToken(){return P(this,null,function*(){return(yield this.client.get("/auth/exchange-token")).jwt})}exchangeTokenForAccessCookie(t){return P(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw X.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return P(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",vt(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return P(this,arguments,function*(t,n={},r){return yield this.preflight(),r==="sticky-messages"?this.getPinnedMessages(t):(yield this.client.post(`/api/conversations/${t}/recommend/${r}`,vt(n),{abortLatest:!0,version:"v1"})).map(s=>A(b({},$e(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,l)=>a===l.findIndex(u=>u.text===s.text))})}isLoggedIn(){return P(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return P(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/conversations/${t}/autocomplete`,vt(n),{abortLatest:!0,version:"v1"})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return P(this,null,function*(){let n=yield this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0,version:"v1"});return $e(n).map(r=>A(b({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return P(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",vt(t),{abortLatest:!0,version:"v1"});return $e(n)})}search(t){return P(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,vt(t),{version:"v2"});return $e(n)})}knowledgeAssist(i,s,a){return P(this,arguments,function*(t,n,r,o={}){yield this.preflight();let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,vt({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(u=>({question:u.question,answer:u.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return $e(l)})}requestLoginByEmail(t){return P(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return $e(n)})}requestPasswordlessToken(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return $e(t.token)})}getCsrfToken(){return P(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return P(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return $e(n)})}getSummary(r){return P(this,arguments,function*(t,n={}){yield this.preflight();let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(i=>i.text&&i.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return $e(o)})}evaluateAssistant(t,n){return P(this,null,function*(){var a;yield this.preflight();let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let l=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",l)}else r.append("expect_response_format",o);n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let i=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,s=yield this.client.post(i,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return $e(s.output)})}createAssistantThread(t){return P(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return $e(r)})}postMessageToAssistantThread(t){return P(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 $e(i)})}translateMessages(t){return P(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/translate",vt(t),{version:"v2"});return $e(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Mw);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&X.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};ts.exchangeTokenPromise=null;var so=ts;var VA={startTime:null,stopTime:null},WA=e=>e.handlingTime,KA=Te({name:"handlingTime",initialState:VA,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(it,()=>VA)}}),{handlingTimeStart:$A,handlingTimeStop:Lm,handlingTimeReset:qA}=KA.actions,GA=KA.reducer;var YA=(e={})=>{let t=b({onAuthError:ta(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Om={list:{keywordMatches:[]},fetchState:"idle"};var ns=de("styleSuggestions/getAll",(n,r)=>P(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(l=i.conversation.current)==null?void 0:l.profileCode;if(!s)return Om.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),zF=Te({name:"styleSuggestions",initialState:Om,reducers:{},extraReducers:e=>{e.addCase(ns.pending,t=>{t.fetchState="loading"}).addCase(ns.rejected,t=>{t.fetchState="error"}).addCase(ns.fulfilled,(t,n)=>{t.fetchState="done",Do(t.list,n.payload)||(t.list=n.payload)}).addCase(Si,t=>{t.list=Om.list}).addCase(it,()=>Om)}}),XA=zF.reducer;var QA=(e={})=>{let t,n=!0,r=b({getStyleSuggestions:ns,debounce:500},e);return o=>i=>s=>{var p;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((p=u.conversation.current)==null?void 0:p.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function BF(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var ZA=(e={})=>{let t=b({getTextSuggestions:tr,getAutocompleteSuggestions:rc,debounce:200,check:Er},e),n;return r=>o=>i=>{var y;let{input:s}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,f=(y=l.conversation.current)==null?void 0:y.id,d=i.type===Jp.toString();if(!f||!u&&!c)return a;let{input:p}=l;return BF(p,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let g=ra(l);g===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(g))},d?0:t.debounce)),a}};var JA=ns.fulfilled.toString();function UF(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var eI=e=>t=>n=>r=>{var u;if(r.type!==JA){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=UF(o,s);r.type===JA&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var jF=Jd({assistants:gC,auth:iT,conversation:hT,contentTypes:yC,passwordlessToken:aA,entities:$C,handlingTime:GA,info:DT,input:PT,settings:ZE,profile:SC,search:jT,styleSuggestions:XA,ui:RP,textSuggestions:fP});function tI(e){return oE({reducer:jF,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}),YA(),ZA({debounce:200}),QA({debounce:500}),eI(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var VF=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},WF=e=>t=>n=>r=>{var a,l,u,c,f,d;let o=t.getState(),i=tu("inlineSuggestions")(o);switch(r.type){case ta.toString():{!r.payload&&e.emit("logout",void 0);break}case $n.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 Vr.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Si.toString():e.logSendMessage(r.payload);break;case ep.toString():e.emit("call-to-action",{cue:r.payload});break;case Vn.fulfilled.toString():r.isBroadcasted||e.broadcast(av,r,!1);break;default:break}let s=n(r);switch(r.type){case Si.toString():e.handleAfterSendMessage(r.payload);break;case ic.toString():e.onUpdateShowTabHint(r.payload);break;case Lm.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case Df.toString():{let{start:p,end:h}=o.input.selection;e.emit("replace",A(b({},r.payload),{replace:r.payload.replace==="selection"?{start:p,end:h}:{start:0,end:h}}));break}case Bn.toString():{let{start:p,end:h}=o.input.selection;e.emit("select-suggestion",A(b({type:VF(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:p,end:h}:{start:0,end:h}})),i&&t.dispatch(Fo([]));break}case Ff.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 Fo.toString():{i&&r.payload.length>0&&t.dispatch(Hf(0));break}case jn.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{summary:r.payload,assistant:(d=t.getState().profile.data)==null?void 0:d.summarizerAssistantNew}}),e.emit("summary-generated",{summary:r.payload});break}default:break}return s},nI=WF;function hx(e){return e.toISOString().replace("T"," ").replace("Z","")}var KF=(e,t)=>t.version,rI=zn([ia,hr,WA,KF],(e,t,n,r)=>{if(!t)return X.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:i}=n;return!o||!i?(X.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:hx(o),timeStop:hx(i)}});function oI(e,t,n){var I,L,q,N;let r=(I=t.conversation.current)==null?void 0:I.id;if(!r)return X.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:i,numCharsPasted:s,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:f,pastes:d,cuts:p,deletions:h,textSuggestions:y,offeredTextSuggestions:g}}=t[e],m=o.length,x=y.reduce((z,{text:B,searchTerm:le})=>z+B.length-(le?le.length:0),0),w=c!=null?c:Date.now(),C=(Date.now()-w)/1e3+(f||0),T=i/C,R=y.reduce((z,{searchTerm:B})=>z+(B?B.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:p,deletions:h,lenTextTyped:i+R,lenTextTotal:m,lenTextAssisted:x,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:C,charsPerSecond:T,numPastes:u,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:g.filter(z=>z.source==="gpt").length}],agentId:(L=t.info.agentInfo)==null?void 0:L.agentId,agentName:(q=t.info.agentInfo)==null?void 0:q.agentName,agentEmail:(N=t.info.agentInfo)==null?void 0:N.agentEmail}}function yx(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return yx(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?yx(o,t):null}function vx(e,t){return yx(e,t)}function iI(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)&&(Xi(e)||lm(e))}var aI,kr=new Map,qF=["bottom","height","left","right","top","width"],sI=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:qF.some(n=>e[n]!==t[n]);function lI(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,...lI(t)]:[]}function uI(e,t){return!e||!t?null:A(b({},e),{top:e.top+t.top,left:e.left+t.left})}var Nm=!1,cI=()=>{Nm=!0;let e=[];if(kr.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),kr.delete(n);return}let r=n.getBoundingClientRect();sI(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(uI,t.rect):t.rect;sI(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),kr.size===0){Nm=!1;return}aI=window.requestAnimationFrame(cI)};function xx(e,t){let n=lI(e),r=[],o=n.map((i,s)=>xx(i,a=>{r[s]=a;let l=kr.get(e);if(!l)return;let u=r.reduce(uI,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),kr.has(e)){let s=kr.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else kr.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!Nm&&cI()},unobserve(){o.forEach(s=>s.unobserve());let i=kr.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||kr.delete(e),kr.size||(cancelAnimationFrame(aI),Nm=!1)}}}}var dI,Rr=new Map,fI=()=>{Rr.forEach((e,t)=>{if(!t.isConnected){Rr.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)))}),Rr.size!==0&&(dI=window.requestAnimationFrame(fI))};function pI(e,t){return{observe(){let n=Rr.size===0;Rr.has(e)?Rr.get(e).callbacks.push(t):Rr.set(e,{visible:void 0,callbacks:[t]}),n&&fI()},unobserve(){let n=Rr.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Rr.delete(e),Rr.size||cancelAnimationFrame(dI)}}}}var wx=["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 Sx(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Ba(e){return parseFloat(e)}function _m(e){return Math.round(e*1e6)}function mI(e){return e/1e6}function bx(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Ba(e.width),i=Ba(e.borderLeftWidth),s=Ba(e.borderRightWidth),a=Ba(e.paddingRight),l=mI(_m(o)-_m(i)-_m(s)),u=mI(_m(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function gc(e,t={}){var c,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",_i(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};Sx(r,n,wx),bx(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=pI(e,()=>{Sx(r,n,wx),bx(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=xx(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(Sx(r,n,wx),bx(r,e,n),i(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let p=t.closestScrollElement.getBoundingClientRect(),h=window.getComputedStyle(t.closestScrollElement),y=Ba(h.borderTopWidth),g=Ba(h.borderBottomWidth),m=p.top+y-d.top,v=d.top+d.height+-(p.top+p.height-g);n.style.clipPath=`inset(${m}px 0px ${v}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var gI=(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){X.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function GF(e){return e.offsetParent!==null}function hI(e){if(!GF(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 Dm(e,t,n=100){let r=hI(e);t({isVisible:r});let o=setInterval(()=>{let i=hI(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Me=S(k());var yI=gI("showTabHint",!0),Ua=class Ua{constructor({deepdeskUrl:t,version:n=Ua.version||"unknown",locale:r="en-US",token:o,fetch:i,productName:s,createCustomChannel:a}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.floatingMenu=null;this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=t.replace(/\/api$/,"");this.deepdeskApi=new so(l,{token:o,fetch:i}),this.version=n,this.instanceId=Ua.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[nI({broadcast:(c,f,d)=>{this.broadcastEvents.send(c,f,d)},emit:(c,f)=>this.emit(c,f),handleAfterSendMessage:c=>this.handleAfterSendMessage(c),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:c=>this.logSendMessage(c),onUpdateShowTabHint:c=>yI.update(c),sendEvent:(c,f)=>this.deepdeskApi.sendEvent(c,f)})]};this.store=tI(u),this.broadcastEvents=new UA({debug:!0,deepdeskUrl:l,eventMap:VT(this.store),createCustomChannel:a}),this.store.dispatch(ic(yI.value())),this.store.dispatch(If({locale:r,adminUrl:l,productName:s}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(X.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(X.warn("Profile has not been loaded (yet)"),!0):(X.warn("No conversation loaded (yet)"),!0)}login(){this.store.dispatch(ta(null)),this.store.dispatch(Ur());let t=n=>Ft(n)&&JE(n)!=="loading";return new Promise(n=>{let r=this.subscribe(t,o=>{o&&(r(),n())});this.unmountHandlers.push(()=>{r()})})}isLoggedIn(){return P(this,null,function*(){return(yield this.store.dispatch(Ur())).payload})}isConversationSupported(t,n){return P(this,null,function*(){return(yield this.store.dispatch(tv({sessionId:t,options:n}))).payload})}createConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(Of(t))).payload})}getConversationBySessionId(t,n){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(Mf({sessionId:t,options:n}))).payload})}upsertConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(nv(t))).payload})}postMessages(t){return P(this,null,function*(){return(yield this.store.dispatch(_f(t))).payload})}updateConversation(t){return P(this,null,function*(){return(yield this.store.dispatch(Nf(t))).payload})}resetConversation(){this.store.dispatch(it()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(If(t))}setVisitorInfo(t){this.store.dispatch(MT(t))}setCustomData(t){this.store.dispatch(NT(t))}setAgentInfo(t,n){return P(this,null,function*(){yield this.store.dispatch(ou(b(b({},t),n)))})}setAgentSettings(t){return P(this,null,function*(){yield this.store.dispatch(ov(t))})}getAgentSettings(){return P(this,null,function*(){return(yield this.store.dispatch(iv())).payload})}refresh(){return P(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(zf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(Jp()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(Bn(t))}evaluateAssistant(t,n){return P(this,null,function*(){let c=n||{},{input:r={},transcript:o,showCuesInWidget:i=!0,includeTags:s,expectFormat:a}=c,l=te(c,["input","transcript","showCuesInWidget","includeTags","expectFormat"]);Object.assign(r,l);let u=yield this.store.dispatch(Vn({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeTags:s,input:r,skipState:!i}));if(u.error)throw new Error(u.error.message);return u.payload})}evaluateConversationAssistant(t,n){return P(this,null,function*(){yield this.loadProfileConfig();let r={accepted:"conversationAcceptedAssistant","new-message":"conversationNewMessageAssistant",ended:"conversationEndedAssistant"},o=this.state.profile.data[r[t]];if(!o){X.warn(`No assistant set in profile for conversation event "${t}"`);return}yield this.evaluateAssistant(o,b({transcript:"stored-transcript",includeTags:!0},n))})}getSummary(){return P(this,null,function*(){var n;if(!this.hasConversation())return X.warn("No conversation to create summary for."),null;(n=this.state.profile.data)!=null&&n.summarizerAssistantNew||X.warn("No profile loaded yet, or no summarizer assistant set in profile");let t=yield this.store.dispatch(jn({}));if(t.error)throw new Error(t.error.message);return t.payload})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.settings,u=a?"below":"above",c=o.length>0;if(this.store.dispatch(ST(rv(t))),!Er(this.state)||t.key!=="Tab"&&!l)return;let f=()=>{n||!c||s&&(t.shiftKey||(this.store.dispatch(TT()),t.preventDefault()))},d=()=>{n||!c||a&&i<=0||s&&(t.shiftKey||(this.store.dispatch(CT()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():f();break;case"ArrowDown":{u==="below"?f():d();break}case"Escape":{n||(this.store.dispatch(Hf(-1)),this.store.dispatch($o({collapse:!0})),this.store.dispatch(CP(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let p=oa(this.state);if(!p)return;this.store.dispatch(ic(!1)),this.store.dispatch(Bn({text:p.text,suggestion:p,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let p=oa(this.state);if(!p)return;this.store.dispatch(Bn({text:p.text,suggestion:p,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let p=oa(this.state);if(!p)return;this.store.dispatch(Bn({text:p.text,suggestion:p,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch($o({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Fo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(X.info("Start handling time"),this.store.dispatch($A()))}handlingTimeStop(){this.state.handlingTime.startTime&&(X.info("Stop handling time"),this.store.dispatch(Lm()))}logSendMessage(t){let n=oI("input",this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n))}logHandlingTime(){let t=rI(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(qA()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Si((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(RT()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){X.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),X.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(_T(t))}whenConversationLoaded(t){let n=o=>{var i;return(i=o.conversation.current)==null?void 0:i.id},r=()=>this.loadProfileConfig().then(()=>t());n(this.state)&&r(),this.subscribe(n,o=>{o&&r()})}overlayContainerFactory(t,n,r,o){let[i,s]=gc(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,lt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,s=i?i.ownerDocument.defaultView:null;if(i&&(s===window||(s==null?void 0:s.parent)===window)){let[l,u]=gc(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{(0,lt.unmountComponentAtNode)(o),u()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return _i(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,lt.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),X.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()?(X.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(kT(r.metrics))):X.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,l=te(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),u={customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),_i(t),this.inputMediator=a||(Xi(t)?new Ji(t):new Zi(t)),this.inputMediator.on("change",({plainText:p,rawHTML:h})=>{this.store.dispatch(zf({text:p,html:h}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(bT(rv(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:h})=>{this.store.dispatch(ET({text:p,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(wT(p))});let c;this.inputMediator.on("selection",p=>{clearTimeout(c),p===null?c=setTimeout(()=>{p!==null&&this.store.dispatch(Bf(p))},500):this.store.dispatch(Bf(p))}),this.inputMediator.on("disabled",()=>{var p;(p=this.inputMediator)==null||p.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{this.settings.detectSubmit&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(nm(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(nm(!0))}),this.renderSuggestions(t,u),this.subscribe(tu("inlineSuggestions"),()=>{this.renderSuggestions(t,u)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(zf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(Bf(this.inputMediator.getSelection())),this.store.dispatch(nm(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var p;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((p=this.state.conversation.current)==null?void 0:p.sessionId)}),this.isMounted=!0}subscribe(t,n){let r=t(this.store.getState());return this.store.subscribe(()=>{let o=t(this.store.getState());o!==r&&(r=o,n(r))})}unmount(){var t,n,r,o;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.floatingMenu)==null||r.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(o=this.inputMediator)==null||o.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderSuggestions(t,n){var r,o,i;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(i=this.aboveSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.aboveSuggestions=this.renderAboveSuggestions(t,n)}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret");(0,lt.render)((0,Me.jsx)(Go,{store:this.store,customStyles:r,children:(0,Me.jsx)(Ho,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(MP,{})})}),o);let i=s=>{s?(o.style.display="block",o.style.top=`${s.top}px`,o.style.left=`${s.left}px`):o.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var s;(0,lt.unmountComponentAtNode)(o),(s=this.inputMediator)==null||s.off("caretposition",i),o.remove()}}}renderAboveSuggestions(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i}=n,s=o&&vx(t,o)||void 0,a=this.overlayContainerFactory("deepdesk-tab-completion",s||t,{appendTo:i,closestScrollElement:s,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),l=this.overlayContainerFactory("deepdesk-suggestions-overlay",s||t,{appendTo:i},r==null?void 0:r.suggestionsRootNode);return(0,lt.render)((0,Me.jsx)(Go,{store:this.store,customStyles:r,children:(0,Me.jsx)(Ho,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(oA,{inputElement:t})})}),a),(0,lt.render)((0,Me.jsx)(Go,{store:this.store,customStyles:r,children:(0,Me.jsx)(Ho,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(jP,{onLogIn:()=>this.loginViaPopup().catch(u=>X.warn(u.message))})})}),l),{unmount(){(0,lt.unmountComponentAtNode)(a),(0,lt.unmountComponentAtNode)(l),a.remove(),l.remove()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i,floatingMenuParent:s}=n,a=o&&vx(t,o)||void 0,l=this.overlayContainerFactory("floating-menu",a||t,{appendTo:s!=null?s:i},r==null?void 0:r.floatingMenuParent);return(0,lt.render)((0,Me.jsx)(Go,{store:this.store,customStyles:r,children:(0,Me.jsx)(Ho,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(EP,{onLogIn:()=>this.loginViaPopup().catch(u=>X.warn(u.message))})})}),l),{unmount(){(0,lt.unmountComponentAtNode)(l),l.remove()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays");return(0,lt.render)((0,Me.jsx)(Go,{store:this.store,customStyles:n,children:(0,Me.jsx)(Ho,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(vP,{})})}),r),{unmount(){(0,lt.unmountComponentAtNode)(r),r.remove()}}}renderWidget(t,n={}){if(this.widgetRoot&&X.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,lt.render)((0,Me.jsx)(Go,{store:this.store,customStyles:r,children:(0,Me.jsx)(Ho,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(_A,{knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(s=>X.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,lt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}renderKnowledgeAssistantWidget(t,n,r={}){let{customStyles:o,initialQuestion:i}=r;return(0,lt.render)((0,Me.jsx)(Go,{store:this.store,customStyles:o,children:(0,Me.jsx)(Ho,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(ux,{children:(0,Me.jsxs)(Tm,{assistantCode:t,initialQuestion:i,evaluateKnowledgeAssistFn:r.isLegacyKnowledgeAssist?Ti:Ci,children:[(0,Me.jsx)(cs,{children:(0,Me.jsx)(km,{emptyState:r.emptyState})}),(0,Me.jsx)(lx,{children:(0,Me.jsx)(Cm,{})})]})})})}),n),{unmount(){(0,lt.unmountComponentAtNode)(n),n.remove()}}}setupHandlingTime(t){let n=Dm(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){iI(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>P(this,null,function*(){yield this.store.dispatch(bu());let t=ki(this.state);t&&this.store.dispatch(If({showSearch:t.search,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew||t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions}))})),this.loadProfileConfigPromise)}loginViaPopup(t){return P(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=p=>P(this,null,function*(){var h,y;if((h=p.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((y=p.data)==null?void 0:y.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(su),l=!0,o.port1.close(),n()}catch(g){console.error(g),r(g)}finally{l=!0,u()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let f=p=>P(this,null,function*(){var h;if(p.origin===a.origin)switch((h=p.data)==null?void 0:h.type){case"deepdesk-popup-loaded":{try{let y=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(y,a.origin,[o.port2])}catch(y){X.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-error":{u(),p.data.message==="Timeout"&&X.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(p.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}checkForTrialMode(t){return P(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(X.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;X.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return P(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Eu(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch($n()):_c.includes(r)||this.store.dispatch(tr(r))})}catch(r){this.handleError(r)}})}};Ua.version="16.0.0",Ua.count=0;var hc=Ua;function YF(e){return P(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 vI(e,t){return P(this,null,function*(){let n=yield YF(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 xI(e,t,n){return P(this,null,function*(){yield new so(e).authenticateWithKey(t,n)})}function wI(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function SI(r,o){return P(this,arguments,function*(e,t,n={}){var f,d;let{value:i}=e,{start:s,end:a}=(f=n.replace)!=null?f:{start:0,end:i.length},l=`${i.slice(0,s)}${t}${i.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+t.length},c=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(c()).then(()=>{e.selectionStart=u.start,e.selectionEnd=u.end,e.blur(),e.focus()})})}function bI(r,o){return P(this,arguments,function*(e,t,n={}){let i=n.replace?Qo(e,n.replace.start,n.replace.end):Fa(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(`
|
|
83
|
+
`);let h=d?r:0,y=p?Math.min(i,c.childNodes.length):c.childNodes.length;for(let g=h;g<y&&(u(c.childNodes[g]),a!==2);g++);break}default:break}p&&(a=2)}return u(e),l}var FA=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(FA||{}),io=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();Do(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(FA).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 HA(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Zi=class extends io{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),mc(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var s;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(s=r.getComposedRanges(n))==null?void 0:s[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!HA(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!HA(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return pc(this.element,n);let r=this.lastKnownSelection;if(r&&DA(this.element,r.start,r.end))return r;let o=Fa(this.element);return o.collapse(!1),pc(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return mc(this.element,Qo(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 NF=["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 zA(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",NF.forEach(function(c){o[c]=i[c]}),n?e.scrollHeight>parseInt(i.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),s.appendChild(r);let l=e.getBoundingClientRect(),u={top:l.top-e.scrollTop+a.offsetTop+parseInt(i.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+parseInt(i.borderLeftWidth)};return s.removeChild(r),u}var Ji=class extends io{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 zA(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 BA(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function _F(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var cx=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()}},dx=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=BA(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()}},fx=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),X.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new dx(t,this.deepdeskUrl,{debug:!0}):new cx(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=_F(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(X.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;X.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage(A(b({},o),{channel:this.sessionId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},UA=fx;function DF(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function $e(e){return Array.isArray(e)?e.map($e):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>A(b({},t),{[DF(n)]:$e(e[n])}),{}):e}function FF(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function vt(e){return Array.isArray(e)?e.map(vt):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>A(b({},t),{[FF(n)]:vt(e[n])}),{}):e}var Ha=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var px=e=>new Promise(t=>{setTimeout(t,e)});var za=class extends Ha{constructor(){super(...arguments);this.name="ClientError"}},gx=class extends Ha{constructor(){super(...arguments);this.name="ServerError"}},mx=new Map;function HF(e){return P(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(X.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var Zo=class Zo{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",T=n,{useCache:u=!1,abortLatest:c=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:h=R=>R instanceof TypeError,retryOnResponse:y=R=>R.status>=500,version:g=null}=T,m=te(T,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(mx.has(s)){r(mx.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let v=A(b({credentials:"include"},m),{headers:b({Accept:"application/json","Content-Type":"application/json"},m.headers)});!l&&this.csrfToken&&(v.headers=A(b({},v.headers),{"X-CSRFToken":this.csrfToken})),typeof g=="string"&&(v.headers=A(b({},v.headers),{"X-Deepdesk-API-Version":g}));let x=f,w=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&c&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let C=()=>P(this,null,function*(){return x--,a(s,v).then(R=>P(this,null,function*(){return y(R)&&!i.isAborted&&x>0?(yield px(d),C()):R.status===401&&p===!0&&w===!1?(w=!0,yield this.refreshToken(),C()):R})).catch(R=>P(this,null,function*(){if(h(R)&&!i.isAborted&&x>0)return yield px(d),C();throw R}))});C().then(R=>P(this,null,function*(){let I=yield HF(R);if(delete this.latestRequestByUrl[s],R.status>=500){o(new gx("Server Error",I));return}else if(R.status===401){o(new za("Unauthorized",I));return}else if(R.status===403){o(new za("Forbidden",I));return}else if(R.status===404){o(new za("Not Found",I));return}else if(R.status>=400){o(new za("Bad Request",I));return}u&&mx.set(s,I),r(I)})).catch(R=>{o(R)})})}validateToken(){return P(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)try{yield this.refreshToken()}catch(r){return!1}let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/");return!!n})}refreshToken(){return Zo.refreshingToken||(Zo.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{Zo.refreshingToken=null},1e3*60)})),Zo.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))}};Zo.refreshingToken=null;var es=Zo;var jA;(t=>{let e;(s=>(s.SEND_MESSAGE="Send Message",s.HANDLING_TIME="Handling Time",s.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",s.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||(t.EventType={}))})(jA||(jA={}));function Im(e){return A(b({},$e(e)),{tags:e.tags})}var ts=class ts{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new es(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>P(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return P(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(ts.exchangeTokenPromise||(ts.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),ts.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return P(this,null,function*(){yield this.preflight(),X.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",A(b({},vt(t)),{tags:t.tags}),{version:"v2"});return Im(n)})}getMe(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return $e(t)})}postIdentity(t){return P(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",vt(t))})}patchMe(t){return P(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",vt(t));return $e(n)})}getProfile(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return $e(n)})}getKnowledgeAssistant(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return $e(n)})}getContentTypes(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return $e(t)})}getAccount(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return $e(t)})}getPlatformConfig(t){return P(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return $e(r)})}checkUserExists(t){return P(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationBySessionId(r){return P(this,arguments,function*(t,n={}){yield this.preflight(),X.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return X.info(`Successfully retrieved conversation ${s.id} for session ${t}`),Im(s)})}isConversationSupported(r){return P(this,arguments,function*(t,n={}){X.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return P(this,null,function*(){yield this.preflight();let r=vt(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Im(o)})}postMessages(t,n){return P(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>A(b({},vt(o)),{tags:o.tags})),{version:"v2"})).map(o=>Im(o))})}sendEvent(t,n){return P(this,null,function*(){yield this.preflight();let s=n,{data:r}=s,o=te(s,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>A(b({},a),{[l]:u}),{});return this.client.post("/api/events",vt(A(b(b({},i),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return P(this,null,function*(){yield this.preflight();let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>A(b({},o),{[i]:s}),{});return this.client.post("/api/events",{event:t,data:vt(b(b({},n),r))},{version:"v1"})})}getEntities(t){return P(this,null,function*(){return yield this.preflight(),(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)},{version:"v1"})).entities})}getTemporaryExchangeToken(){return P(this,null,function*(){return(yield this.client.get("/auth/exchange-token")).jwt})}exchangeTokenForAccessCookie(t){return P(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw X.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return P(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",vt(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return P(this,arguments,function*(t,n={},r){return yield this.preflight(),r==="sticky-messages"?this.getPinnedMessages(t):(yield this.client.post(`/api/conversations/${t}/recommend/${r}`,vt(n),{abortLatest:!0,version:"v1"})).map(s=>A(b({},$e(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,l)=>a===l.findIndex(u=>u.text===s.text))})}isLoggedIn(){return P(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return P(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/conversations/${t}/autocomplete`,vt(n),{abortLatest:!0,version:"v1"})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return P(this,null,function*(){let n=yield this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0,version:"v1"});return $e(n).map(r=>A(b({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return P(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",vt(t),{abortLatest:!0,version:"v1"});return $e(n)})}search(t){return P(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,vt(t),{version:"v2"});return $e(n)})}knowledgeAssist(i,s,a){return P(this,arguments,function*(t,n,r,o={}){yield this.preflight();let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,vt({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(u=>({question:u.question,answer:u.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return $e(l)})}requestLoginByEmail(t){return P(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return $e(n)})}requestPasswordlessToken(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return $e(t.token)})}getCsrfToken(){return P(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return P(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return $e(n)})}getSummary(r){return P(this,arguments,function*(t,n={}){yield this.preflight();let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(i=>i.text&&i.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return $e(o)})}evaluateAssistant(t,n){return P(this,null,function*(){var a;yield this.preflight();let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let l=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",l)}else r.append("expect_response_format",o);n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let i=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,s=yield this.client.post(i,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return $e(s.output)})}createAssistantThread(t){return P(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return $e(r)})}postMessageToAssistantThread(t){return P(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 $e(i)})}translateMessages(t){return P(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/translate",vt(t),{version:"v2"});return $e(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Mw);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&X.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};ts.exchangeTokenPromise=null;var so=ts;var VA={startTime:null,stopTime:null},WA=e=>e.handlingTime,KA=Te({name:"handlingTime",initialState:VA,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(it,()=>VA)}}),{handlingTimeStart:$A,handlingTimeStop:Lm,handlingTimeReset:qA}=KA.actions,GA=KA.reducer;var YA=(e={})=>{let t=b({onAuthError:ta(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Om={list:{keywordMatches:[]},fetchState:"idle"};var ns=de("styleSuggestions/getAll",(n,r)=>P(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(l=i.conversation.current)==null?void 0:l.profileCode;if(!s)return Om.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),zF=Te({name:"styleSuggestions",initialState:Om,reducers:{},extraReducers:e=>{e.addCase(ns.pending,t=>{t.fetchState="loading"}).addCase(ns.rejected,t=>{t.fetchState="error"}).addCase(ns.fulfilled,(t,n)=>{t.fetchState="done",Do(t.list,n.payload)||(t.list=n.payload)}).addCase(Si,t=>{t.list=Om.list}).addCase(it,()=>Om)}}),XA=zF.reducer;var QA=(e={})=>{let t,n=!0,r=b({getStyleSuggestions:ns,debounce:500},e);return o=>i=>s=>{var p;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((p=u.conversation.current)==null?void 0:p.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function BF(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var ZA=(e={})=>{let t=b({getTextSuggestions:tr,getAutocompleteSuggestions:rc,debounce:200,check:Er},e),n;return r=>o=>i=>{var y;let{input:s}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,f=(y=l.conversation.current)==null?void 0:y.id,d=i.type===Jp.toString();if(!f||!u&&!c)return a;let{input:p}=l;return BF(p,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let g=ra(l);g===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(g))},d?0:t.debounce)),a}};var JA=ns.fulfilled.toString();function UF(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var eI=e=>t=>n=>r=>{var u;if(r.type!==JA){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=UF(o,s);r.type===JA&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var jF=Jd({assistants:gC,auth:iT,conversation:hT,contentTypes:yC,passwordlessToken:aA,entities:$C,handlingTime:GA,info:DT,input:PT,settings:ZE,profile:SC,search:jT,styleSuggestions:XA,ui:RP,textSuggestions:fP});function tI(e){return oE({reducer:jF,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}),YA(),ZA({debounce:200}),QA({debounce:500}),eI(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var VF=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},WF=e=>t=>n=>r=>{var a,l,u,c,f,d;let o=t.getState(),i=tu("inlineSuggestions")(o);switch(r.type){case ta.toString():{!r.payload&&e.emit("logout",void 0);break}case $n.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 Vr.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Si.toString():e.logSendMessage(r.payload);break;case ep.toString():e.emit("call-to-action",{cue:r.payload});break;case Vn.fulfilled.toString():r.isBroadcasted||e.broadcast(av,r,!1);break;default:break}let s=n(r);switch(r.type){case Si.toString():e.handleAfterSendMessage(r.payload);break;case ic.toString():e.onUpdateShowTabHint(r.payload);break;case Lm.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case Df.toString():{let{start:p,end:h}=o.input.selection;e.emit("replace",A(b({},r.payload),{replace:r.payload.replace==="selection"?{start:p,end:h}:{start:0,end:h}}));break}case Bn.toString():{let{start:p,end:h}=o.input.selection;e.emit("select-suggestion",A(b({type:VF(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:p,end:h}:{start:0,end:h}})),i&&t.dispatch(Fo([]));break}case Ff.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 Fo.toString():{i&&r.payload.length>0&&t.dispatch(Hf(0));break}case jn.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{summary:r.payload,assistant:(d=t.getState().profile.data)==null?void 0:d.summarizerAssistantNew}}),e.emit("summary-generated",{summary:r.payload});break}default:break}return s},nI=WF;function hx(e){return e.toISOString().replace("T"," ").replace("Z","")}var KF=(e,t)=>t.version,rI=zn([ia,hr,WA,KF],(e,t,n,r)=>{if(!t)return X.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:i}=n;return!o||!i?(X.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:hx(o),timeStop:hx(i)}});function oI(e,t,n){var I,L,q,N;let r=(I=t.conversation.current)==null?void 0:I.id;if(!r)return X.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:i,numCharsPasted:s,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:f,pastes:d,cuts:p,deletions:h,textSuggestions:y,offeredTextSuggestions:g}}=t[e],m=o.length,x=y.reduce((z,{text:B,searchTerm:le})=>z+B.length-(le?le.length:0),0),w=c!=null?c:Date.now(),C=(Date.now()-w)/1e3+(f||0),T=i/C,R=y.reduce((z,{searchTerm:B})=>z+(B?B.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:p,deletions:h,lenTextTyped:i+R,lenTextTotal:m,lenTextAssisted:x,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:C,charsPerSecond:T,numPastes:u,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:g.filter(z=>z.source==="gpt").length}],agentId:(L=t.info.agentInfo)==null?void 0:L.agentId,agentName:(q=t.info.agentInfo)==null?void 0:q.agentName,agentEmail:(N=t.info.agentInfo)==null?void 0:N.agentEmail}}function yx(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return yx(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?yx(o,t):null}function vx(e,t){return yx(e,t)}function iI(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)&&(Xi(e)||lm(e))}var aI,kr=new Map,qF=["bottom","height","left","right","top","width"],sI=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:qF.some(n=>e[n]!==t[n]);function lI(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,...lI(t)]:[]}function uI(e,t){return!e||!t?null:A(b({},e),{top:e.top+t.top,left:e.left+t.left})}var Nm=!1,cI=()=>{Nm=!0;let e=[];if(kr.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),kr.delete(n);return}let r=n.getBoundingClientRect();sI(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(uI,t.rect):t.rect;sI(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),kr.size===0){Nm=!1;return}aI=window.requestAnimationFrame(cI)};function xx(e,t){let n=lI(e),r=[],o=n.map((i,s)=>xx(i,a=>{r[s]=a;let l=kr.get(e);if(!l)return;let u=r.reduce(uI,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),kr.has(e)){let s=kr.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else kr.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!Nm&&cI()},unobserve(){o.forEach(s=>s.unobserve());let i=kr.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||kr.delete(e),kr.size||(cancelAnimationFrame(aI),Nm=!1)}}}}var dI,Rr=new Map,fI=()=>{Rr.forEach((e,t)=>{if(!t.isConnected){Rr.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)))}),Rr.size!==0&&(dI=window.requestAnimationFrame(fI))};function pI(e,t){return{observe(){let n=Rr.size===0;Rr.has(e)?Rr.get(e).callbacks.push(t):Rr.set(e,{visible:void 0,callbacks:[t]}),n&&fI()},unobserve(){let n=Rr.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Rr.delete(e),Rr.size||cancelAnimationFrame(dI)}}}}var wx=["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 Sx(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Ba(e){return parseFloat(e)}function _m(e){return Math.round(e*1e6)}function mI(e){return e/1e6}function bx(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Ba(e.width),i=Ba(e.borderLeftWidth),s=Ba(e.borderRightWidth),a=Ba(e.paddingRight),l=mI(_m(o)-_m(i)-_m(s)),u=mI(_m(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function gc(e,t={}){var c,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",_i(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};Sx(r,n,wx),bx(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=pI(e,()=>{Sx(r,n,wx),bx(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=xx(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(Sx(r,n,wx),bx(r,e,n),i(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let p=t.closestScrollElement.getBoundingClientRect(),h=window.getComputedStyle(t.closestScrollElement),y=Ba(h.borderTopWidth),g=Ba(h.borderBottomWidth),m=p.top+y-d.top,v=d.top+d.height+-(p.top+p.height-g);n.style.clipPath=`inset(${m}px 0px ${v}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var gI=(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){X.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function GF(e){return e.offsetParent!==null}function hI(e){if(!GF(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 Dm(e,t,n=100){let r=hI(e);t({isVisible:r});let o=setInterval(()=>{let i=hI(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Me=S(k());var yI=gI("showTabHint",!0),Ua=class Ua{constructor({deepdeskUrl:t,version:n=Ua.version||"unknown",locale:r="en-US",token:o,fetch:i,productName:s,createCustomChannel:a}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.floatingMenu=null;this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=t.replace(/\/api$/,"");this.deepdeskApi=new so(l,{token:o,fetch:i}),this.version=n,this.instanceId=Ua.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[nI({broadcast:(c,f,d)=>{this.broadcastEvents.send(c,f,d)},emit:(c,f)=>this.emit(c,f),handleAfterSendMessage:c=>this.handleAfterSendMessage(c),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:c=>this.logSendMessage(c),onUpdateShowTabHint:c=>yI.update(c),sendEvent:(c,f)=>this.deepdeskApi.sendEvent(c,f)})]};this.store=tI(u),this.broadcastEvents=new UA({debug:!0,deepdeskUrl:l,eventMap:VT(this.store),createCustomChannel:a}),this.store.dispatch(ic(yI.value())),this.store.dispatch(If({locale:r,adminUrl:l,productName:s}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(X.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(X.warn("Profile has not been loaded (yet)"),!0):(X.warn("No conversation loaded (yet)"),!0)}login(){this.store.dispatch(ta(null)),this.store.dispatch(Ur());let t=n=>Ft(n)&&JE(n)!=="loading";return new Promise(n=>{let r=this.subscribe(t,o=>{o&&(r(),n())});this.unmountHandlers.push(()=>{r()})})}isLoggedIn(){return P(this,null,function*(){return(yield this.store.dispatch(Ur())).payload})}isConversationSupported(t,n){return P(this,null,function*(){return(yield this.store.dispatch(tv({sessionId:t,options:n}))).payload})}createConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(Of(t))).payload})}getConversationBySessionId(t,n){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(Mf({sessionId:t,options:n}))).payload})}upsertConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(nv(t))).payload})}postMessages(t){return P(this,null,function*(){return(yield this.store.dispatch(_f(t))).payload})}updateConversation(t){return P(this,null,function*(){return(yield this.store.dispatch(Nf(t))).payload})}resetConversation(){this.store.dispatch(it()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(If(t))}setVisitorInfo(t){this.store.dispatch(MT(t))}setCustomData(t){this.store.dispatch(NT(t))}setAgentInfo(t,n){return P(this,null,function*(){yield this.store.dispatch(ou(b(b({},t),n)))})}setAgentSettings(t){return P(this,null,function*(){yield this.store.dispatch(ov(t))})}getAgentSettings(){return P(this,null,function*(){return(yield this.store.dispatch(iv())).payload})}refresh(){return P(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(zf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(Jp()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(Bn(t))}evaluateAssistant(t,n){return P(this,null,function*(){let c=n||{},{input:r={},transcript:o,showCuesInWidget:i=!0,includeTags:s,expectFormat:a}=c,l=te(c,["input","transcript","showCuesInWidget","includeTags","expectFormat"]);Object.assign(r,l);let u=yield this.store.dispatch(Vn({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeTags:s,input:r,skipState:!i}));if(u.error)throw new Error(u.error.message);return u.payload})}evaluateConversationAssistant(t,n){return P(this,null,function*(){yield this.loadProfileConfig();let r={accepted:"conversationAcceptedAssistant","new-message":"conversationNewMessageAssistant",ended:"conversationEndedAssistant"},o=this.state.profile.data[r[t]];if(!o){X.warn(`No assistant set in profile for conversation event "${t}"`);return}yield this.evaluateAssistant(o,b({transcript:"stored-transcript",includeTags:!0},n))})}getSummary(){return P(this,null,function*(){var n;if(!this.hasConversation())return X.warn("No conversation to create summary for."),null;(n=this.state.profile.data)!=null&&n.summarizerAssistantNew||X.warn("No profile loaded yet, or no summarizer assistant set in profile");let t=yield this.store.dispatch(jn({}));if(t.error)throw new Error(t.error.message);return t.payload})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.settings,u=a?"below":"above",c=o.length>0;if(this.store.dispatch(ST(rv(t))),!Er(this.state)||t.key!=="Tab"&&!l)return;let f=()=>{n||!c||s&&(t.shiftKey||(this.store.dispatch(TT()),t.preventDefault()))},d=()=>{n||!c||a&&i<=0||s&&(t.shiftKey||(this.store.dispatch(CT()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():f();break;case"ArrowDown":{u==="below"?f():d();break}case"Escape":{n||(this.store.dispatch(Hf(-1)),this.store.dispatch($o({collapse:!0})),this.store.dispatch(CP(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let p=oa(this.state);if(!p)return;this.store.dispatch(ic(!1)),this.store.dispatch(Bn({text:p.text,suggestion:p,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let p=oa(this.state);if(!p)return;this.store.dispatch(Bn({text:p.text,suggestion:p,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let p=oa(this.state);if(!p)return;this.store.dispatch(Bn({text:p.text,suggestion:p,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch($o({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Fo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(X.info("Start handling time"),this.store.dispatch($A()))}handlingTimeStop(){this.state.handlingTime.startTime&&(X.info("Stop handling time"),this.store.dispatch(Lm()))}logSendMessage(t){let n=oI("input",this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n))}logHandlingTime(){let t=rI(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(qA()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Si((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(RT()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){X.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),X.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(_T(t))}whenConversationLoaded(t){let n=o=>{var i;return(i=o.conversation.current)==null?void 0:i.id},r=()=>this.loadProfileConfig().then(()=>t());n(this.state)&&r(),this.subscribe(n,o=>{o&&r()})}overlayContainerFactory(t,n,r,o){let[i,s]=gc(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,lt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,s=i?i.ownerDocument.defaultView:null;if(i&&(s===window||(s==null?void 0:s.parent)===window)){let[l,u]=gc(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{(0,lt.unmountComponentAtNode)(o),u()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return _i(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,lt.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),X.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()?(X.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(kT(r.metrics))):X.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,l=te(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),u={customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),_i(t),this.inputMediator=a||(Xi(t)?new Ji(t):new Zi(t)),this.inputMediator.on("change",({plainText:p,rawHTML:h})=>{this.store.dispatch(zf({text:p,html:h}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(bT(rv(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:h})=>{this.store.dispatch(ET({text:p,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(wT(p))});let c;this.inputMediator.on("selection",p=>{clearTimeout(c),p===null?c=setTimeout(()=>{p!==null&&this.store.dispatch(Bf(p))},500):this.store.dispatch(Bf(p))}),this.inputMediator.on("disabled",()=>{var p;(p=this.inputMediator)==null||p.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{this.settings.detectSubmit&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(nm(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(nm(!0))}),this.renderSuggestions(t,u),this.subscribe(tu("inlineSuggestions"),()=>{this.renderSuggestions(t,u)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(zf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(Bf(this.inputMediator.getSelection())),this.store.dispatch(nm(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var p;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((p=this.state.conversation.current)==null?void 0:p.sessionId)}),this.isMounted=!0}subscribe(t,n){let r=t(this.store.getState());return this.store.subscribe(()=>{let o=t(this.store.getState());o!==r&&(r=o,n(r))})}unmount(){var t,n,r,o;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.floatingMenu)==null||r.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(o=this.inputMediator)==null||o.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderSuggestions(t,n){var r,o,i;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(i=this.aboveSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.aboveSuggestions=this.renderAboveSuggestions(t,n)}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret");(0,lt.render)((0,Me.jsx)(Go,{store:this.store,customStyles:r,children:(0,Me.jsx)(Ho,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(MP,{})})}),o);let i=s=>{s?(o.style.display="block",o.style.top=`${s.top}px`,o.style.left=`${s.left}px`):o.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var s;(0,lt.unmountComponentAtNode)(o),(s=this.inputMediator)==null||s.off("caretposition",i),o.remove()}}}renderAboveSuggestions(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i}=n,s=o&&vx(t,o)||void 0,a=this.overlayContainerFactory("deepdesk-tab-completion",s||t,{appendTo:i,closestScrollElement:s,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),l=this.overlayContainerFactory("deepdesk-suggestions-overlay",s||t,{appendTo:i},r==null?void 0:r.suggestionsRootNode);return(0,lt.render)((0,Me.jsx)(Go,{store:this.store,customStyles:r,children:(0,Me.jsx)(Ho,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(oA,{inputElement:t})})}),a),(0,lt.render)((0,Me.jsx)(Go,{store:this.store,customStyles:r,children:(0,Me.jsx)(Ho,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(jP,{onLogIn:()=>this.loginViaPopup().catch(u=>X.warn(u.message))})})}),l),{unmount(){(0,lt.unmountComponentAtNode)(a),(0,lt.unmountComponentAtNode)(l),a.remove(),l.remove()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i,floatingMenuParent:s}=n,a=o&&vx(t,o)||void 0,l=this.overlayContainerFactory("floating-menu",a||t,{appendTo:s!=null?s:i},r==null?void 0:r.floatingMenuParent);return(0,lt.render)((0,Me.jsx)(Go,{store:this.store,customStyles:r,children:(0,Me.jsx)(Ho,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(EP,{onLogIn:()=>this.loginViaPopup().catch(u=>X.warn(u.message))})})}),l),{unmount(){(0,lt.unmountComponentAtNode)(l),l.remove()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays");return(0,lt.render)((0,Me.jsx)(Go,{store:this.store,customStyles:n,children:(0,Me.jsx)(Ho,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(vP,{})})}),r),{unmount(){(0,lt.unmountComponentAtNode)(r),r.remove()}}}renderWidget(t,n={}){if(this.widgetRoot&&X.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,lt.render)((0,Me.jsx)(Go,{store:this.store,customStyles:r,children:(0,Me.jsx)(Ho,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(_A,{knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(s=>X.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,lt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}renderKnowledgeAssistantWidget(t,n,r={}){let{customStyles:o,initialQuestion:i}=r;return(0,lt.render)((0,Me.jsx)(Go,{store:this.store,customStyles:o,children:(0,Me.jsx)(Ho,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(ux,{children:(0,Me.jsxs)(Tm,{assistantCode:t,initialQuestion:i,evaluateKnowledgeAssistFn:r.isLegacyKnowledgeAssist?Ti:Ci,children:[(0,Me.jsx)(cs,{children:(0,Me.jsx)(km,{emptyState:r.emptyState})}),(0,Me.jsx)(lx,{children:(0,Me.jsx)(Cm,{})})]})})})}),n),{unmount(){(0,lt.unmountComponentAtNode)(n),n.remove()}}}setupHandlingTime(t){let n=Dm(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){iI(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>P(this,null,function*(){yield this.store.dispatch(bu());let t=ki(this.state);t&&this.store.dispatch(If({showSearch:t.search,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew||t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions}))})),this.loadProfileConfigPromise)}loginViaPopup(t){return P(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=p=>P(this,null,function*(){var h,y;if((h=p.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((y=p.data)==null?void 0:y.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(su),l=!0,o.port1.close(),n()}catch(g){console.error(g),r(g)}finally{l=!0,u()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let f=p=>P(this,null,function*(){var h;if(p.origin===a.origin)switch((h=p.data)==null?void 0:h.type){case"deepdesk-popup-loaded":{try{let y=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(y,a.origin,[o.port2])}catch(y){X.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-error":{u(),p.data.message==="Timeout"&&X.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(p.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}checkForTrialMode(t){return P(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(X.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;X.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return P(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Eu(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch($n()):_c.includes(r)||this.store.dispatch(tr(r))})}catch(r){this.handleError(r)}})}};Ua.version="16.0.1-beta.0",Ua.count=0;var hc=Ua;function YF(e){return P(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 vI(e,t){return P(this,null,function*(){let n=yield YF(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 xI(e,t,n){return P(this,null,function*(){yield new so(e).authenticateWithKey(t,n)})}function wI(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function SI(r,o){return P(this,arguments,function*(e,t,n={}){var f,d;let{value:i}=e,{start:s,end:a}=(f=n.replace)!=null?f:{start:0,end:i.length},l=`${i.slice(0,s)}${t}${i.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+t.length},c=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(c()).then(()=>{e.selectionStart=u.start,e.selectionEnd=u.end,e.blur(),e.focus()})})}function bI(r,o){return P(this,arguments,function*(e,t,n={}){let i=n.replace?Qo(e,n.replace.start,n.replace.end):Fa(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(`
|
|
84
84
|
`).reverse().forEach((l,u)=>{u>0&&i.insertNode(document.createElement("br")),i.insertNode(document.createTextNode(l))}):i.insertNode(document.createTextNode(t))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let l=n.selectionAfter?Qo(e,n.selectionAfter.start,n.selectionAfter.end):(i.collapse(!1),i),u=window.getSelection();u==null||u.removeAllRanges(),u==null||u.addRange(l)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}function XF(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 QF(e){let t=document.createDocumentFragment();return e.split(`
|
|
85
85
|
`).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 EI(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):EI(n,t)}function TI(o,i){return P(this,arguments,function*(e,t,{isBlock:n,isHTML:r}={}){let s;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let a=()=>{var d;let l=(d=e.ownerDocument.defaultView)!=null?d:window,u=l.getSelection();if((!u||u.rangeCount===0)&&(e.focus(),u=l.getSelection()),!u||u.rangeCount===0)return;let c=u.getRangeAt(0);if(!c)return;s=document.createElement("span"),c.insertNode(s);let f=r?XF(t):QF(t);n?EI(c.startContainer,f):(c.insertNode(f),c.collapse(!1))};return Promise.resolve(a()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!s)try{s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}return HI(ZF);})();
|
|
86
86
|
/*! Bundled license information:
|