@deepdesk/deepdesk-sdk 14.3.1-beta.8 → 14.3.1-beta.9

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 CHANGED
@@ -7,6 +7,6 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
7
7
  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 hi=require("react/jsx-runtime"),Ug={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},ec=({className:t,color:e})=>(0,hi.jsx)("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,hi.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:Ug[e||"pink"]})});var tc={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedIn:"dd-XvHAn",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var yi={};oe(yi,{enUS:()=>Vg,nlNL:()=>zg});var Vg={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},zg={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var sc=require("react-redux"),$t=require("react/jsx-runtime"),rc=({onLogIn:t})=>{let e=P(yi),n=T("floatingMenu"),o=T("productName"),s=(0,sc.useDispatch)(),r=(0,oc.useSelector)(se),i=x("FloatingMenu",tc);if(r===null||n===!1)return null;let a=()=>{r===!0?s(be(!0)):t()};return(0,$t.jsxs)("button",{className:(0,nc.default)(i.root,{[i.isLoggedIn]:r,[i.isLoggedOut]:!r}),onClick:a,children:[(0,$t.jsx)("div",{className:i.text,children:e(r?"search":"signin",{productName:o})}),(0,$t.jsxs)("div",{className:i.icon,children:[(0,$t.jsx)(ec,{className:i.logo,color:"pink"}),r===!1&&(0,$t.jsx)(Yd,{className:i.lock})]})]})};var qs=require("react"),ot=require("react-redux");var ic=require("react");function wt(t){(0,ic.useEffect)(()=>{let e=n=>{n.isWithinRoot||t(n)};return document.body.addEventListener("mouseup",e),()=>{document.body.removeEventListener("mouseup",e)}},[t])}function Gt(t){t.addEventListener("mouseup",e=>{e.isWithinRoot=!0},!0)}function We(t){let{showMidSentenceSuggestions:e,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:o}=t.settings,{text:s,selection:r}=t.input;return r.start!==r.end?!1:r.end>=s.length?!0:e?n&&new RegExp(n).test(s.substring(r.end))||o&&new RegExp(o).test(s.substring(0,r.end))?!0:n===!1&&o===!1:!1}var ac=require("@reduxjs/toolkit"),Wg={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1},Vs=({ui:t})=>t.overlayCollapsed,lc=(0,ac.createSlice)({name:"ui",initialState:Wg,reducers:{setShowTabHint(t,e){t.showTabHint=e.payload},setInputFocus(t,e){t.overlayCollapsedUserOverwrite!==!0&&(e.payload===!0&&(t.overlayCollapsed=!1),t.inputHasFocus=e.payload)},setOverlayCollapsed(t,e){e.payload.collapse===!1&&(t.openOverlayWhenTyping=!1),!(e.payload.skipWhenInputFocus&&t.inputHasFocus)&&(t.overlayCollapsed=e.payload.collapse)},setOpenOverlayWhenTyping(t,e){t.openOverlayWhenTyping=e.payload},setOverlayCollapsedUserOverwrite(t,e){t.overlayCollapsedUserOverwrite=e.payload,t.overlayCollapsed=e.payload}}}),{setShowTabHint:Co,setInputFocus:zs,setOverlayCollapsed:Tt,setOpenOverlayWhenTyping:dc,setOverlayCollapsedUserOverwrite:cc}=lc.actions,uc=lc.reducer;var Ws=require("react");var fc=require("interweave"),In=require("react"),wo=require("react-redux");var pc=require("react");function mc(t,e,n){(0,pc.useEffect)(()=>{let o=t.current;return o?(o.addEventListener(e,n),()=>{o.removeEventListener(e,n)}):()=>{}},[t,e,n])}var gc={root:"dd-1MBCO",actions:"dd--x4cy",badge:"dd-4Fpkz",formattedText:"dd-EzvTB"};var Qt=require("react/jsx-runtime"),qg=["search","personal-collection-search","search-autocomplete"];function $g(t,e,n,o={}){var r;let s="";return qg.includes(e)?s=rd(ei(t,n,{stripAgentPart:!0}),(r=o.searchKeywords)!=null?r:[n]):s=ei(t,n,o),o.placeholders===!0&&(s=id(s)),s}var Gg=()=>{},Qg=({selected:t,suggestion:e})=>{let n=T("inlineSuggestions"),o=(0,wo.useSelector)(pn),s=T("enableSuggestionFeedback"),r=(0,wo.useSelector)(c=>c.input.text),i=(0,wo.useDispatch)(),a=x("TextSuggestion",gc),d=(0,In.useRef)(null);(0,In.useEffect)(()=>{let c=setTimeout(()=>{i(el({text:e.text,suggestion:e}))},500);return()=>{clearTimeout(c)}},[e]),mc(d,"click",()=>{i(Le({suggestion:e,text:e.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let l=(0,In.useMemo)(()=>$g(e.text,e.source,o,{stripAgentPart:n,placeholders:!0,searchKeywords:e.searchKeywords}),[n,e.text,e.source,o,e.searchKeywords]);return e.source==="gpt"&&!n?null:(0,Qt.jsxs)("div",{className:a.root,children:[(0,Qt.jsx)(_,{ref:d,as:"button","data-testid":"suggestions-overlay-item",selected:t,onClick:Gg,children:(0,Qt.jsx)(fc.Interweave,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:l})}),s&&(0,Qt.jsx)("div",{className:a.actions,children:(0,Qt.jsx)(Fs,{source:"overlay",context:r,suggestion:e})})]})},hc=Qg;var vi=require("react/jsx-runtime"),Zg=({suggestions:t,selectedIndex:e,reverse:n})=>{let o=(0,Ws.useMemo)(()=>{let s=t.map((r,i)=>(0,vi.jsx)(hc,{index:i,selected:i===e,suggestion:r},`${r.text}-${r.source}`));return n?s.reverse():s},[t,e,n]);return(0,vi.jsx)(Ws.Fragment,{children:o})},js=Zg;var yc={root:"dd-PfvRI",paper:"dd-HYlyY"};var To=require("react/jsx-runtime"),Xg=({textSuggestions:t,selectedIndex:e})=>{let n=(0,qs.useRef)(null),o=x("InlineSuggestionsOverlay",yc),s=(0,ot.useSelector)(We),r=(0,ot.useDispatch)(),i=(0,ot.useSelector)(se),a=(0,ot.useSelector)(un),d=(0,ot.useSelector)(Vs),l=T("showTextSuggestions");return wt(()=>{setTimeout(()=>{r(Tt({collapse:!0,skipWhenInputFocus:!0}))})}),(0,qs.useEffect)(()=>{let c=n.current;if(!c||!c.parentElement)return;c.parentElement.style.left="0px";let p=c.getBoundingClientRect();c.parentElement.style.left=`${Math.min(window.innerWidth-4-p.right,0)}px`}),d||!s||!l||t.length===0||i!==!0||a===!1?null:(0,To.jsx)("div",{className:o.root,"data-variant":"inline",children:(0,To.jsx)("div",{ref:n,className:o.paper,children:(0,To.jsx)(pe,{children:(0,To.jsx)(js,{suggestions:t,selectedIndex:e})})})})},Jg=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),vc=(0,ot.connect)(Jg)(Xg);var Sc=require("react-redux");var Eo=require("react/jsx-runtime"),Yg=({children:t})=>{let n=T("locale").replace("-","");return(0,Eo.jsx)(Qr.Provider,{value:n,children:t})},ef=({store:t,customStyles:e={},children:n})=>(0,Eo.jsx)(Sc.Provider,{store:t,children:(0,Eo.jsx)(Yg,{children:(0,Eo.jsx)(jn.Provider,{value:e,children:n})})}),Zt=ef;var Gs=A(require("classnames")),Ln=require("react"),rt=require("react-redux");var xc=require("react");function bc(t,e){let[n,o]=(0,xc.useState)(()=>{if(typeof window=="undefined")return e;try{let r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return E.error(r),e}});return[n,r=>{try{let i=r instanceof Function?r(n):r;o(i),typeof window!="undefined"&&window.localStorage.setItem(t,JSON.stringify(i))}catch(i){E.error(i)}}]}var Cc=()=>/Mac/i.test(navigator.platform);var Tc=A(require("classnames")),st=require("react");var Si={};oe(Si,{enUS:()=>tf,nlNL:()=>nf});var tf={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"}]}]},nf={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 wc={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};var Et=require("react/jsx-runtime"),xi=(t,e,n)=>o=>(0,Et.jsx)("button",{className:t.anchorButton,type:"button",value:e,onClick:n,children:o},e),of=({className:t,loginUrl:e,isEmbedded:n,onSnooze:o,onLogIn:s})=>{let r=P(Si),i=me(),a=x("Login",wc),d=T("productName"),l=(0,st.useCallback)(v=>{v.preventDefault(),o&&o(parseInt(v.target.value,10))},[]),c=(0,st.useCallback)(v=>{v.preventDefault(),i.send(yn,!0)},[e]),p=(0,st.useMemo)(()=>v=>(0,Et.jsx)("a",{onClick:k=>{k.preventDefault(),s()},href:e,className:a.anchor,target:"_blank",rel:"noreferrer",children:v},"login"),[e]),u=(0,st.useCallback)(v=>(0,Et.jsx)("button",{type:"button",className:a.anchorButton,onClick:c,children:v},"prompt"),[c]),{min:m,hour:y,day:f}=(0,st.useMemo)(()=>({min:xi(a,60*10,l),hour:xi(a,60*60,l),day:xi(a,60*60*12,l)}),[]);return(0,Et.jsxs)("div",{className:(0,Tc.default)(t,a.root),children:[r("loginPlease",{login:n?u:p,productName:d}),o&&(0,Et.jsxs)(st.Fragment,{children:[(0,Et.jsx)("br",{}),r("snooze",{min:m,hour:y,day:f})]})]})},$s=of;var kc=require("react-redux");var Ec={root:"dd-DoQhb",text:"dd-Jwnev"};var ko=require("react/jsx-runtime"),sf=({title:t})=>{let e=x("SearchTrigger",Ec),n=(0,kc.useDispatch)();return(0,ko.jsxs)("button",{type:"button",className:e.root,onClick:()=>n(be(!0)),children:[(0,ko.jsx)(bn,{}),(0,ko.jsx)("span",{className:e.text,children:t})]})},Rc=sf;var bi={};oe(bi,{enUS:()=>rf,nlNL:()=>af});var rf={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"}]},af={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 Ic={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 V=require("react/jsx-runtime"),lf=({textSuggestions:t,selectedIndex:e,onLogIn:n})=>{let o=x("SuggestionsOverlay",Ic),s=P(bi),r=(0,rt.useSelector)(We),i=Ya(),a=(0,rt.useDispatch)(),d=(0,Ln.useRef)(null),l=T("searchTriggerKey"),c=T("productName"),p=(0,rt.useSelector)(Vs),u=(0,rt.useSelector)(se),m=(0,rt.useSelector)(un),[y,f]=(0,Ln.useState)(null),v=T("showSearch"),C=T("showTextSuggestions"),k=T("adminUrl"),S=T("isEmbedded"),[I,w]=bc("dd-snooze-until-ms",0),N=p||I>Date.now(),M=t.filter(ye=>ye.source!=="gpt").length,B=()=>{N&&w(0),a(cc(!N))},ne=ye=>{let D=Date.now()+ye*1e3;w(D),E.info(`Snooze until: ${new Date(D)}`),a(Tt({collapse:!0}))};return(0,Ln.useEffect)(()=>{M===0&&f(null)},[t,M]),wt(()=>{a(Tt({collapse:!0,skipWhenInputFocus:!0}))}),u===null||m===!1?null:u===!1?(0,V.jsxs)("div",{ref:d,className:(0,Gs.default)(o.root,{[o.isCollapsed]:N}),children:[!N&&(0,V.jsxs)("div",{className:o.triggers,children:[(0,V.jsx)("div",{style:{flex:1}}),(0,V.jsx)("div",{className:o.triggersRight,children:(0,V.jsx)(At,{className:o.toggleButton,title:s("collapse"),onClick:B,isCollapsed:!1})})]}),(0,V.jsx)("div",{className:o.toggleButtonWrapper,children:(0,V.jsx)(At,{className:o.toggleButton,title:s("open",{productName:c}),onClick:B,isCollapsed:!0})}),(0,V.jsx)("div",{className:o.collapsible,children:(0,V.jsx)($s,{loginUrl:k,isEmbedded:S,onLogIn:n,onSnooze:ne})})]}):!i||!r?null:(0,V.jsxs)("div",{ref:d,className:(0,Gs.default)(o.root,{[o.isCollapsed]:N}),children:[!N&&(0,V.jsxs)("div",{className:o.triggers,children:[(0,V.jsx)("div",{style:{flex:1},children:v&&(0,V.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>f(s(Cc()?"searchHintMac":"searchHintWindows",{searchTriggerKey:l.toUpperCase()})),onMouseLeave:()=>f(null),children:(0,V.jsx)(Rc,{title:s("search")})})}),(0,V.jsxs)("div",{className:o.triggersRight,onFocus:()=>{},children:[(0,V.jsx)("div",{className:(0,Gs.default)(!y&&o.hintsHidden,o.hints),children:y}),(0,V.jsx)(At,{className:o.toggleButton,title:s("collapse"),onClick:B,isCollapsed:!1})]})]}),(0,V.jsx)("div",{className:o.toggleButtonWrapper,children:(0,V.jsx)(At,{className:o.toggleButton,title:s("open",{productName:c}),onClick:B,isCollapsed:!0})}),M>0&&C&&(0,V.jsx)("div",{className:o.collapsible,onFocus:()=>{},children:(0,V.jsx)(pe,{children:(0,V.jsx)(js,{suggestions:t,selectedIndex:e,reverse:!0})})})]})},df=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),Lc=(0,rt.connect)(df)(lf);var dr=A(require("classnames")),eu=require("interweave"),dt=require("react"),tu=require("react-redux");var Pn=require("react");function Qs(t){return t.contentEditable==="true"}function cf(t){let e=0,n=0,o=window.getSelection();if(o.rangeCount!==0){let s=o.getRangeAt(0),r=s.cloneRange();r.selectNodeContents(t),r.setEnd(s.endContainer,s.endOffset),n=r.toString().length,r.selectNodeContents(t),r.setEnd(s.startContainer,s.startOffset),e=r.toString().length}return{selectionStart:e,selectionEnd:n}}function Pc(t){let{selectionStart:e,selectionEnd:n}=Qs(t)?cf(t):t;return[e,n]}function Ac(t){let[,e]=(0,Pn.useState)(),n=(0,Pn.useRef)(null);return n.current=Pc(t),(0,Pn.useEffect)(()=>{let o=()=>{var a;let[s,r]=(a=n.current)!=null?a:[],i=Pc(t);(!i||s!==i[0]||r!==i[1])&&(n.current=i,e({}))};return t.addEventListener("keyup",o),t.addEventListener("click",o),t.addEventListener("focus",o),document.addEventListener("selectionchange",o),()=>{t.removeEventListener("keyup",o),t.removeEventListener("click",o),t.removeEventListener("focus",o),document.removeEventListener("selectionchange",o)}},[t]),n.current}function Mc(t,e){if(!e)return;let n=t,{value:o}=n,[s,r]=e,i=o.match($o);if(!i||i.length===0)return;let a=0;i.find(d=>{let l=o.indexOf(d,a);return s>l&&r<l+d.length?(n.selectionStart=l,n.selectionEnd=l+d.length,!0):(a=l+d.length,!1)})}var Nc=require("react"),uf=["div","span","mark","strong","b","i","u","em"];function Ci(t,e,n=0){var r;let o=t[t.length-1],s=typeof o=="object"&&o!==null?(r=o.props)==null?void 0:r.tagName:void 0;if(s==="br")return t.pop(),[...t,...e,o];if(uf.includes(s)){let i=Array.isArray(o.props.children)?o.props.children:[o.props.children];return[...t.slice(0,t.length-1),(0,Nc.cloneElement)(o,{children:Ci(i,e,n+1)})]}return[...t,...e]}function Xt(t){return t.tagName.toLowerCase()==="textarea"}var Oc={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 Wc=A(require("classnames")),jc=require("interweave"),sr=require("react");var An=require("react");function Dc(t,e){let n;return[(...o)=>{window.cancelAnimationFrame(n);let s=e?e(...o):o;n=window.requestAnimationFrame(()=>{t(...s)})},()=>window.cancelAnimationFrame(n)]}function Zs(t){let e=(0,An.useRef)(null),[n,o]=(0,An.useState)(!1);return(0,An.useEffect)(()=>{var c;let s=!1,r=parseFloat((c=window.getComputedStyle(document.body).zoom)!=null?c:"1"),[i,a]=Dc((p,u)=>{let m=e.current;if(!m)return;let y=p/r,f=u/r,v=m.getBoundingClientRect(),C=y>v.x&&y<v.x+v.width&&f>v.y&&f<v.y+v.height;C&&!s?(s=!0,o(!0)):!C&&s&&(s=!1,o(!1))},({clientX:p,clientY:u})=>[p,u]),[d,l]=Dc(()=>{s=!1,o(!1)});return t.addEventListener("mousemove",i),t.addEventListener("mouseleave",d),()=>{a(),l(),t.removeEventListener("mousemove",i),t.removeEventListener("mouseleave",d)}},[e]),[e,n]}function _c(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Xs(t){return e=>{t.forEach(n=>{typeof n=="function"?n(e):n!=null&&(n.current=e)})}}function Fc(t){return t!=null}var Ti=A(require("classnames")),we=require("react");var Js=require("react"),pf=["bottom","height","left","right","top","width"],mf=(t={},e={})=>pf.some(n=>t[n]!==e[n]),it=new Map,Hc,Kc=()=>{let t=[],e=[];it.forEach((n,o)=>{if(o instanceof Element&&!o.isConnected){e.push(o);return}let s=o.getBoundingClientRect();mf(s,n.rect)&&(n.rect=s,t.push(n))}),e.forEach(n=>{it.delete(n)}),t.forEach(n=>{n.callbacks.forEach(o=>o(n.rect))}),Hc=window.requestAnimationFrame(Kc)};function gf(t,e){return{observe(){let n=it.size===0;if(it.has(t)){let o=it.get(t);o.callbacks.push(e),o.rect&&e(o.rect)}else it.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});n&&Kc()},unobserve(){let n=it.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||it.delete(t),it.size||cancelAnimationFrame(Hc)}}}}function wi(t){let[e,n]=(0,Js.useState)(null);return(0,Js.useLayoutEffect)(()=>{if(!t.current)return;let o=gf(t.current,s=>{n(s)});return o.observe(),()=>{o.unobserve()}},[t]),e}var Mn=require("react"),Uc=require("react-dom");var Bc={root:"dd-r-dgo"};var Vc=({children:t,parentNode:e})=>{let[n,o]=(0,Mn.useState)(null),s=(0,Mn.useContext)(jn);return(0,Mn.useLayoutEffect)(()=>{let r=document.createElement("div");return Gt(r),r.classList.add(Bc.root),s!=null&&s.portalRootNode&&r.classList.add(s==null?void 0:s.portalRootNode),(e||document.body).appendChild(r),o(r),()=>{r.isConnected&&r.remove()}},[]),n?(0,Uc.createPortal)(t,n):null};var je={ref:"dd-iz-KP",root:"dd-vEMon",positionAbove:"dd-mUCxM",positionBelow:"dd-7oZI7",positionLeft:"dd-BiWvD",positionRight:"dd-JIWea",alignStart:"dd-5ivu6",alignCenter:"dd-rnVkP",alignEnd:"dd-gZBp4"};var Ys=require("react/jsx-runtime"),er=(t=!1)=>{let[e,n]=(0,we.useState)(t),o=(0,we.useCallback)(()=>n(!0),[]),s=(0,we.useCallback)(()=>n(!1),[]),r=(0,we.useCallback)(()=>n(a=>!a),[]),i=(0,we.useRef)(null);return{opened:e,open:o,close:s,toggle:r,triggerRef:i}};function Ei(t,e=null,n=0){if(!t)return{display:"none"};let o=e?t.top-e.top<0||t.top<e.top-n?e.top-n:t.top+t.height>e.top+e.height+n?e.top+e.height+n-t.height:t.top:t.top,s=e?t.left<e.left-n?e.left-n:t.left+t.width>e.left+e.width+n?e.left+e.width+n-t.width:t.left:t.left;return{top:o,left:s,height:t.height,width:t.width}}var Nn=l=>{var c=l,{className:t,triggerRef:e,boundaryRef:n=(0,we.createRef)(),position:o="above",align:s="center",children:r,toStyle:i=Ei,parentNode:a}=c,d=O(c,["className","triggerRef","boundaryRef","position","align","children","toStyle","parentNode"]);let p=wi(e),u=wi(n),m=(0,we.useMemo)(()=>i(p,u,0),[p,u]);return(0,Ys.jsx)(Vc,{parentNode:a,children:(0,Ys.jsx)("div",b(g({className:(0,Ti.default)(je.ref,{[je.positionAbove]:o==="above",[je.positionBelow]:o==="below",[je.positionLeft]:o==="left",[je.positionRight]:o==="right",[je.alignStart]:s==="start",[je.alignCenter]:s==="center",[je.alignEnd]:s==="end"}),style:m},d),{role:"dialog",children:(0,Ys.jsx)("div",{className:(0,Ti.default)(t,je.root),children:r})}))})};var zc=A(require("classnames")),tr=require("react");var at={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 ki=require("react/jsx-runtime"),nr=(0,tr.forwardRef)((s,o)=>{var r=s,{className:t,children:e}=r,n=O(r,["className","children"]);let i=(0,tr.useRef)(null),a=x("TabCompletion",at);return(0,ki.jsx)("div",b(g({ref:Xs([i,o]),className:(0,zc.default)(t,a.popoverContentContainer)},n),{children:(0,ki.jsx)("div",{className:a.popoverContent,children:e})}))});var kt=require("react/jsx-runtime"),ff=t=>e=>{let n=Ei(e);return"top"in n&&(n.width=t.width-(e.left-t.left)-10),n},hf=({inputElement:t,boundaryRef:e,inputStyle:n,children:o,suggestion:s})=>{let r=x("TabCompletion",at),i=er(),a=(0,sr.useMemo)(()=>ff(t.getBoundingClientRect()),[t]),[d,l]=Zs(t);return(0,sr.useEffect)(()=>{l?i.open():i.close()},[l]),(0,kt.jsxs)("span",{children:[(0,kt.jsx)("mark",{ref:Xs([d,i.triggerRef]),className:(0,Wc.default)(r.matchKeyword,{[r.hover]:l}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:o}),i.opened&&(0,kt.jsx)(Nn,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:(0,kt.jsx)(nr,{style:n,children:(0,kt.jsx)("div",{className:r.hintText,children:s})})})]})},or=class extends jc.Matcher{constructor(){super(...arguments);this.keywordMatches=[];this.preparedKeywordMatches=[];this.usedKeywordMatches=new Set}onBeforeParse(n,o){return o.keywordMatches&&o.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=o.keywordMatches.map(s=>b(g({},s),{keywordRegex:new RegExp(`\\b${_c(s.keyword)}\\b`,"i")})),this.keywordMatches=o.keywordMatches),this.usedKeywordMatches.clear(),n}match(n){let o=this.preparedKeywordMatches.map(r=>{if(this.usedKeywordMatches.has(r))return null;let i=n.match(r.keywordRegex);if(!i)return null;let a=n.charAt(i.index-1),d=n.charAt(i.index+r.keyword.length);return a==="{"&&d==="}"?null:{index:i.index,length:i[0].length,match:i[0],matchString:i[0],suggestion:r.suggestion,preparedKeywordMatch:r,valid:!0}}).filter(Fc);if(o.length===0)return null;let s=o.reduce((r,i)=>i.index<r.index?i:r);return this.usedKeywordMatches.add(s.preparedKeywordMatch),s}replaceWith(n,o){return(0,kt.jsx)(hf,{inputElement:o.inputElement,suggestion:o.suggestion,inputStyle:o.inputStyle,boundaryRef:o.boundaryRef,children:n},`keyword_${o.matchString}_${o.key}`)}asTag(){return"mark"}};var qc=require("interweave"),$c=A(require("classnames"));var Ri=require("react/jsx-runtime"),yf=({inputElement:t,children:e})=>{let n=x("TabCompletion",at),[o,s]=Zs(t);return(0,Ri.jsx)("mark",{ref:o,className:(0,$c.default)(n.matchPlaceholder,{[n.hover]:s}),children:e})},rr=class extends qc.Matcher{match(e){let n=e.match(/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\}(?!\}))/);return n?{index:n.index,length:n[0].length,match:n[0],matchString:n[0],valid:!0}:null}replaceWith(e,n){return(0,Ri.jsx)(yf,{inputElement:n.inputElement,children:e},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var ar=A(require("classnames")),Jc=require("interweave"),le=require("react"),Yc=require("react-redux");var Ii=require("react/jsx-runtime"),Gc=()=>(0,Ii.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,Ii.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 qe=require("react"),Ro=require("react-redux"),Zc=A(require("lodash.debounce"));var Qc={root:"dd-ky-Bv",content:"dd-kV5e1"};function ir(t,e,n){var s;let o=((s=t.imageSizes)==null?void 0:s[e])||t.image||n;if(!o)return null;try{return new URL(o).toString()}catch(r){return null}}function Li(t){return t.replace("https://www.","").replace("https://","")}var Te=require("react/jsx-runtime"),vf=3,Sf=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),xf=({onSelectLink:t,onDismiss:e,placeholder:n,visitUrlText:o,linkCount:s=vf})=>{let r=x("LinkSearch",Qc),[i,a]=(0,qe.useState)(""),d=(0,Ro.useDispatch)(),l=(0,Ro.useSelector)(zd("url")),c=(0,Ro.useSelector)(bl("URL")),p=(0,qe.useMemo)(()=>c.map(Sf),[c]),[u,m]=(0,qe.useState)(p.length-1),y=T("fallbackImage"),f=S=>{let I=S.target;a(I.value)},v=(S,I)=>{S.stopPropagation(),S.preventDefault(),window.open(I,"_blank")},C=S=>{var N;let I=u-1<0?p.length-1:u-1,w=u+1===p.length?0:u+1;S.code==="Escape"&&(a(""),e()),S.code==="ArrowUp"&&m(I),S.code==="ArrowDown"&&m(w),S.code==="Enter"&&t(((N=p[u])==null?void 0:N.text)||i)},k=(0,qe.useCallback)((0,Zc.default)(S=>{d(Dt({query:S,type:"URL",tags:["link-search"]}))},300),[]);return(0,qe.useEffect)(()=>{i&&k(i)},[i]),(0,qe.useEffect)(()=>()=>{d(is())},[]),(0,Te.jsxs)("div",{className:r.root,children:[(0,Te.jsx)(pe,{withDivider:!0,children:(i?p:l).slice(0,s).map((S,I)=>(0,Te.jsx)(_,{selected:u===I,onClick:()=>t(S.text),"data-testid":"linksearch-suggestion",children:(0,Te.jsxs)(K,{children:[(0,Te.jsx)(K.Image,{src:ir(S,"small",y||void 0),title:S.title||S.text}),(0,Te.jsxs)(K.Content,{className:r.content,cropText:!0,children:[(0,Te.jsx)(K.Title,{children:S.title||Li(S.text)}),S.title&&Li(S.text)]}),(0,Te.jsx)(_.Actions,{children:(0,Te.jsx)(_.ActionButton,{label:o,onClick:w=>v(w,S.text)})})]})},S.text))}),(0,Te.jsx)(no,{value:i,onChange:f,autoFocus:!0,placeholder:n,onKeyUp:C})]})},Xc=xf;var Pi={};oe(Pi,{enUS:()=>bf,nlNL:()=>Cf});var bf={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},Cf={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var ae=require("react/jsx-runtime"),wf=(0,le.forwardRef)((t,e)=>{let n=x("TabCompletion",at);return(0,ae.jsx)("mark",{ref:e,className:(0,ar.default)(n.matchSelection)},"selection-start")}),Tf=({startRef:t,boundaryRef:e,inputStyle:n,inputElement:o,children:s})=>{let r=P(Pi),i=x("TabCompletion",at),a=(0,le.useRef)(null),d=(0,le.useRef)(null),[l,c]=(0,le.useState)(null),p=(0,Yc.useDispatch)(),u=er(document.activeElement===o),[m]=(0,le.useState)(()=>document.createRange());u.triggerRef.current=m,(0,le.useEffect)(()=>()=>m.detach(),[]),(0,le.useEffect)(()=>{let f=t.current,v=a.current;!f||!v||(m.setStart(f,0),m.setEnd(v,0))},[t.current,a.current]),wt(()=>{u.close()});let y=(0,le.useCallback)(f=>{let v=m.toString(),C=/^http(s?):\/\//.test(f)?f:`https://${f}`;p(es({text:`[${v}](${C})`,replace:"selection"}))},[]);return(0,ae.jsxs)("span",{children:[(0,ae.jsx)("mark",{ref:a,className:(0,ar.default)(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":u.opened?"true":"false",children:s}),u.opened&&(0,ae.jsx)(Nn,{className:i.popoverRoot,triggerRef:u.triggerRef,boundaryRef:e,position:"above",align:"start",children:(0,ae.jsxs)(nr,{style:n,ref:d,children:[(0,ae.jsx)("div",{className:(0,ar.default)(i.selectionOptions,{[i.selectionOptionsIsHidden]:l!==null}),children:(0,ae.jsxs)("button",{type:"button",tabIndex:l===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>c("insertLink"),children:[(0,ae.jsx)(Gc,{}),(0,ae.jsx)("span",{children:"\xA0"}),(0,ae.jsx)("span",{children:r("insertLink")})]})}),l==="insertLink"&&(0,ae.jsx)(Xc,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:y,onDismiss:()=>{c(null),u.close()}})]})})]},"selection-end")},lr=class extends Jc.Matcher{constructor(){super(...arguments);this.charCount=0;this.foundIndex=0;this.startRef=null}onBeforeParse(n,o){return this.props=o,this.charCount=0,this.startRef=(0,le.createRef)(),this.foundIndex=0,n}match(n){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[o,s]=this.props.selection;if(o===s)return null;let r=this.foundIndex===0?o:s,i=r>=this.charCount&&r<=this.charCount+n.length?{index:r-this.charCount,length:0,match:"",valid:!0}:null;i&&this.foundIndex++;let a=this.foundIndex===1;return i&&a?this.charCount+=r-this.charCount:this.charCount+=n.length,i?g({isStart:a},i):null}replaceWith(n,o){return o.isStart?(0,ae.jsx)(wf,{ref:this.startRef}):(0,ae.jsx)(Tf,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};var nu=require("react-redux");var lt=require("react/jsx-runtime"),Ef=({enabled:t,content:e,tabText:n,showTabHint:o,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:d})=>{let l=x("TabCompletion",Oc),c=T("insertLink"),p=T("showMidSentenceSuggestions"),u=T("inlineSuggestions"),m=Ac(a),y=(0,dt.useRef)(null),f=(0,nu.useSelector)(se);(0,dt.useEffect)(()=>{Xt(a)&&m&&Mc(a,m)},[m]);let v=(0,dt.useCallback)(S=>{if(!s||!n)return S;let I=[(0,lt.jsx)("span",{className:l.resetIndent,children:"\u200B"},"u200B"),(0,lt.jsx)("span",{"data-testid":"tab-completion",className:(0,dr.default)(l.tabText,l.resetIndent),"data-source":d,children:n},"tabText")];return o&&I.push((0,lt.jsx)("span",{className:(0,dr.default)(l.hint,l.resetIndent),children:(0,lt.jsx)(Wo,{keyCode:"tab"},"tabHint")})),Ci(S,I)},[s,n,o]),C=(0,dt.useMemo)(()=>{let S=[];return c&&S.push(new lr("selection")),S.push(new rr("placeholders")),r&&S.push(new or("keywords")),S},[u,c,r]),k=(0,dt.useMemo)(()=>{let S=window.getComputedStyle(a);return{"--dd-color":S.color,"--dd-font-size":S.fontSize,"--dd-font-family":S.fontFamily,"--dd-font-variant":S.fontVariant}},[]);return!t||!f?null:(0,lt.jsxs)("div",{ref:S=>{S!=null&&S.parentElement&&(y.current=S==null?void 0:S.parentElement)},className:l.root,style:k,children:[(0,lt.jsx)(eu.Interweave,{tagName:"span",containerTagName:"div",className:(0,dr.default)(l.container,l.agentText),disableLineBreaks:Xt(a),content:e||"\u200B",onAfterParse:v,matchers:C,selection:m,keywordMatches:i,inputElement:a,inputStyle:k,boundaryRef:y,inlineSuggestionsOnlyAtEnd:!p}),(0,lt.jsx)("br",{})]})},kf=t=>{var v,C,k;let{input:e,ui:n,settings:o,styleSuggestions:s,conversation:r}=t,i=mn({input:e}),a=(i==null?void 0:i.text)||"",d=(i==null?void 0:i.source)||"",l=(v=e.html)!=null?v:xn(e.text),c=a.indexOf(e.text)===0?a.slice(e.text.length):"",{showTabHint:p}=n,{isSupported:u}=r,{showTabCompletion:m,visible:y,showStyleSuggestions:f}=o;return{showTabHint:p,showStyleSuggestions:f,showTabCompletion:m&&We(t),content:l,tabText:c,source:d,keywordMatches:(k=(C=s.list)==null?void 0:C.keywordMatches)!=null?k:[],enabled:y&&u!==!1}},ou=(0,tu.connect)(kf)(Ef);var Vu=A(require("classnames")),Fn=require("react"),q=require("react-redux");var Io=require("@reduxjs/toolkit");var Rf={token:null,interval:null},Ai=(0,Io.createAsyncThunk)("passwordlessToken/getTemporaryPasswordlessToken",(t,e)=>h(void 0,null,function*(){let{deepdeskAPI:n}=e.extra;return{token:yield n.requestPasswordlessToken()}})),Mi=(0,Io.createAsyncThunk)("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:n=1e3*60*10}=t,{dispatch:o}=e;return o(Ai()),setInterval(()=>o(Ai()),n)}),su=(0,Io.createSlice)({name:"passwordlessToken",initialState:Rf,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(Ai.fulfilled,(e,n)=>{e.token=n.payload.token}),t.addCase(Mi.fulfilled,(e,n)=>{e.interval=n.payload})}}),{stopPollPasswordlessToken:ru}=su.actions,iu=su.reducer;var pu=require("@reduxjs/toolkit");var On=require("@reduxjs/toolkit");var au={excludeFromWidget:!1},Ni={cues:[],fetchState:"idle"},lu=t=>{var e;return(e=t.rules)==null?void 0:e.cues},If=(0,On.createAction)("rules/resetCues"),Jt=(0,On.createAsyncThunk)("rules/evaluate",(t,e)=>h(void 0,null,function*(){var n,o;try{let{deepdeskAPI:s}=e.extra,r=e.getState(),{platformVariables:i}=r.info,a=(n=r.conversation.current)==null?void 0:n.id;if(!a)throw new Error("No current conversation to evaluate rules");if(!(yield s.getAccount()).ruleEngine)throw new Error("Rule engine is not enabled for this account");if(!(yield s.getRules()).filter(u=>u.isEnabled).some(u=>u.label===t.label))throw new Error(`No enabled rules found with label: ${t.label}`);let p=yield s.evaluateRule(t.label,a,g({tags:((o=r.conversation.current)==null?void 0:o.tags)||void 0},t.params));return i&&(p=p.map(u=>b(g({},u),{title:Z(u.title,i),text:Z(u.text,i)}))),{cues:p,options:t.options}}catch(s){let r=s.message;return E.warn(r),e.rejectWithValue(r)}})),du=(0,On.createSlice)({name:"answer",initialState:Ni,reducers:{removeCue(t,e){t.cues=t.cues.filter(n=>n.rule.id!==e.payload.id)}},extraReducers:t=>{t.addCase(Jt.pending,e=>{e.fetchState="loading"}).addCase(Jt.rejected,e=>{e.fetchState="error"}).addCase(Jt.fulfilled,(e,n)=>{var r;if((r=n.payload.options)!=null&&r.excludeFromWidget){e.fetchState="done";return}let o=n.payload.cues.map(i=>i.rule.id),s=e.cues.filter(i=>!o.includes(i.rule.id));e.fetchState="done",e.cues=[...n.payload.cues,...s]}).addCase(W,()=>Ni).addCase(If.toString(),()=>Ni)}}),{removeCue:cu}=du.actions,uu=du.reducer;function Lf(t){let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n),e|=0;return e}var mu=(0,pu.createSelector)([lu,$l],(t,e)=>{let n=e.map(o=>({text:o.response,title:o.name,callToAction:o.callToAction,isLoading:o.isLoading,rule:{id:Lf(o.code),label:o.code,name:o.name,description:o.name}}));return[...t,...n]});var cr=require("react"),fu=require("react-redux"),Di=A(require("classnames"));var Oi=require("react/jsx-runtime"),Lo=()=>(0,Oi.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,Oi.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 gu={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};var $e=require("react/jsx-runtime"),Pf=({entities:t})=>{let e=x("EntitiesWidgetList",gu),[n,o]=(0,cr.useState)(void 0),s=(0,fu.useDispatch)(),r=()=>{o(void 0)},i=a=>{t&&(o(t.indexOf(a)),Ve(a.text),s(xe({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,cr.useEffect)(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[n]),!t||t.length===0?null:(0,$e.jsx)("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,d)=>(0,$e.jsxs)("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[(0,$e.jsx)("span",{className:e.entityText,children:a.text}),(0,$e.jsxs)("span",{className:e.iconWrapper,children:[(0,$e.jsx)("span",{className:(0,Di.default)(e.icon),children:(0,$e.jsx)(Lo,{})}),(0,$e.jsx)("span",{className:(0,Di.default)(e.icon,n===d&&e.iconClicked),children:(0,$e.jsx)(Lo,{})})]})]},a.text))})},hu=Pf;var _i=require("react/jsx-runtime"),yu=()=>(0,_i.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,_i.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 Fi=require("react/jsx-runtime"),vu=()=>(0,Fi.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Fi.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 Hi=require("react/jsx-runtime"),Su=()=>(0,Hi.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Hi.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 Lu=require("react-redux");var Cu=require("react");var xu={loadingBar:"dd-6as-V",placeHolderShimmer:"dd-TFYmA"};var bu=require("react/jsx-runtime"),Af=({width:t})=>{let e=x("LoadingProgressBar",xu);return(0,bu.jsx)("div",{className:e.loadingBar,style:{width:t}})},ur=Af;var ct=require("react/jsx-runtime"),pr=({title:t})=>{let e=(0,Cu.useRef)(null);return xa(e),(0,ct.jsx)(_,{ref:e,children:(0,ct.jsx)(K,{children:(0,ct.jsxs)(K.Content,{children:[(0,ct.jsx)(K.Title,{children:t}),(0,ct.jsx)(ur,{width:"60%"}),(0,ct.jsx)(ur,{width:"90%"}),(0,ct.jsx)(ur,{width:"50%"})]})})})};var Ru=require("react");var Tu=A(require("dompurify")),ut=require("react"),Eu=A(require("snarkdown"));var wu={root:"dd-L7b3z",popover:"dd-OQOTB",options:"dd-Y12RE",arrow:"dd-cv33T",copyIcon:"dd-6xOsH",option:"dd-9oFX4",divider:"dd-aiZf8",fadeup:"dd-Jq9pd"};var De=require("react/jsx-runtime");function Mf(t){return`<button type="button" data-copy-icon class=${t}><svg version="1.1" x="0px" y="0px" viewBox="0 0 115.77 122.88" width="10px" height="10px" fill="black"><g><path d="M89.62,13.96v7.73h12.19h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02v0.02 v73.27v0.01h-0.02c-0.01,3.84-1.57,7.33-4.1,9.86c-2.51,2.5-5.98,4.06-9.82,4.07v0.02h-0.02h-61.7H40.1v-0.02 c-3.84-0.01-7.34-1.57-9.86-4.1c-2.5-2.51-4.06-5.98-4.07-9.82h-0.02v-0.02V92.51H13.96h-0.01v-0.02c-3.84-0.01-7.34-1.57-9.86-4.1 c-2.5-2.51-4.06-5.98-4.07-9.82H0v-0.02V13.96v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07V0h0.02h61.7 h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02V13.96L89.62,13.96z M79.04,21.69v-7.73v-0.02h0.02 c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v64.59v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h12.19V35.65 v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07v-0.02h0.02H79.04L79.04,21.69z M105.18,108.92V35.65v-0.02 h0.02c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v73.27v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h61.7h0.02 v0.02c0.91,0,1.75-0.39,2.37-1.01c0.61-0.61,1-1.46,1-2.37h-0.02V108.92L105.18,108.92z"/></g></svg></button>`}function Ki(t){var n;let e=t.cloneNode(!0);return e.querySelectorAll("div,button").forEach(o=>o.remove()),(n=e.textContent)!=null?n:""}function Nf(t){return t.replace(/\r\n/g,`
8
8
  `)}var Of=({content:t,useLabel:e,copyLabel:n,onCopy:o,onUse:s})=>{let r=x("Markdown",wu),i=(0,ut.useRef)(null),[a,d]=(0,ut.useState)(null),l=(0,ut.useMemo)(()=>{let f=(0,Eu.default)(Nf(t));return Tu.default.sanitize(f).replaceAll("</code>",`${Mf(r.copyIcon)}</code>`).replaceAll('<a href="','<a target="_blank" rel="noreferrer noopener" href="')},[t]),c=f=>{var k;let v=f.target,C=!!((k=i.current)!=null&&k.querySelector("code"));if(["A","BUTTON"].includes(v.tagName)){d(null);return}a||C&&v.tagName!=="CODE"||!C&&v!==i.current||(v.addEventListener("mouseleave",()=>d(null),{once:!0}),d(v))},p=()=>{if(!a)return;d(null);let f=a.querySelector("button");f&&(En(f,r.fadeup),o(Ki(a)))},u=f=>{let v=f.target;if(v.tagName==="A"){f.stopPropagation();return}"copyIcon"in v.dataset&&(En(v,r.fadeup),o(Ki(v.parentElement)))},m=()=>{!a||!s||(d(null),s(Ki(a)))},y=f=>{if(f===null)return;let v=f.getBoundingClientRect();v.left<0?f.style.transform=`translateX(${-v.left+2}px)`:v.right>window.innerWidth&&(f.style.transform=`translateX(${window.innerWidth-v.right-2}px)`)};return(0,De.jsxs)(ut.Fragment,{children:[a&&(0,De.jsxs)(Nn,{triggerRef:{current:a},className:r.popover,parentNode:a,children:[(0,De.jsxs)("div",{className:r.options,ref:y,children:[(0,De.jsx)("button",{type:"button",className:r.option,onClick:p,children:n}),s&&(0,De.jsxs)(ut.Fragment,{children:[(0,De.jsx)("div",{className:r.divider}),(0,De.jsx)("button",{type:"button",className:r.option,onClick:m,children:e})]})]}),(0,De.jsx)("div",{className:r.arrow})]}),(0,De.jsx)("div",{ref:i,"data-testid":"widget-markdown-content",className:r.root,dangerouslySetInnerHTML:{__html:l},onMouseOver:c,onClick:u})]})},mr=Of;var Bi={};oe(Bi,{enUS:()=>Df,nlNL:()=>_f});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"}]},_f={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 ku={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",inputSpace:"dd-DGYB1"};var Ee=require("react/jsx-runtime"),Ff=({cue:t,onCallToAction:e,onRemove:n,onCopy:o,onUse:s})=>{let r=x("WidgetCue",ku),i=P(Bi),a=Ct(),d=T("hasKeyboardInput"),l=()=>{e&&e(t),n(t)},c=m=>{o&&o(m,t)},p=m=>{s&&s(m,t)},u=m=>{m.preventDefault(),m.stopPropagation(),n(t)};return(0,Ru.useEffect)(()=>{a("Assistant response displayed",{name:t.rule.name,description:t.rule.description,group:t.rule.label,cueText:t.text})},[]),(0,Ee.jsxs)(_,{"data-testid":"cue",children:[(0,Ee.jsx)(K,{children:(0,Ee.jsxs)(K.Content,{children:[t.title&&(0,Ee.jsx)(K.Title,{className:r.title,"data-testid":"widget-cue-title",children:t.rule.label.startsWith("__")?i(t.rule.label):t.title}),(0,Ee.jsx)(mr,{content:t.text,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:c,onUse:d?p:void 0})]})}),(0,Ee.jsxs)(_.ButtonsContainer,{children:[(0,Ee.jsxs)("div",{className:r.actions,children:[t.callToAction&&(0,Ee.jsx)(_.Button,{onClick:l,children:t.callToAction.label}),(0,Ee.jsx)(_.Button,{onClick:u,children:i("removeCue")})]}),(0,Ee.jsx)(Rn,{eventName:"Assistant response feedback",eventData:{name:t.rule.name,group:t.rule.label,description:t.rule.description,cueText:t.text},feedbackText:t.text,feedbackType:"assistant"})]})]})},Iu=Ff;var Dn=require("react/jsx-runtime"),Hf=({cues:t})=>{let e=(0,Lu.useDispatch)(),n=me(),o=Ct(),s=d=>{e(cu({id:d.rule.id})),e(Ql({code:d.rule.label})),o("Assistant response closed",{name:d.rule.name,group:d.rule.label,description:d.rule.description,cueText:d.text})},r=(d,l)=>{Ve(d),o("Assistant response copied",{name:l.rule.name,group:l.rule.label,description:l.rule.description,copiedText:d})},i=d=>{d.callToAction&&(e(ks(d)),o("Assistant call to action",{name:d.rule.name,group:d.rule.label,description:d.rule.description,eventName:d.callToAction.event,value:d.callToAction.value}))},a=(d,l)=>{n.send(Be,{text:d,suggestion:{source:"cue",sourceText:d}}),o("Assistant response used",{name:l.rule.name,group:l.rule.label,description:l.rule.description,usedText:d})};return(0,Dn.jsx)(Dn.Fragment,{children:t.map(d=>d.isLoading?(0,Dn.jsx)(pr,{title:d.title},d.rule.id):(0,Dn.jsx)(Iu,{cue:d,onCallToAction:i,onRemove:s,onCopy:r,onUse:a},d.rule.id))})},Pu=Hf;var gr=require("react");var Au={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var _e=require("react/jsx-runtime");function Kf(t,e){return e.split(".").reduce((n,o)=>!n||typeof n!="object"||!(o in n)?null:n[o],t)}var Mu=({data:t,schema:e})=>{let n=x("WidgetCustomData",Au),o=s=>{Ve(s)};return(0,gr.useEffect)(()=>{E.info("Custom data",t,e)},[t]),(0,_e.jsx)("dl",{className:n.root,children:e.map(s=>{let r=Kf(t,s.path);return(0,_e.jsxs)(gr.Fragment,{children:[(0,_e.jsx)("dt",{className:n.label,children:s.label}),(0,_e.jsx)("dd",{className:n.value,children:s.type==="boolean"&&r?(0,_e.jsx)("span",{className:n.isTrue,children:s.trueValue}):s.type==="boolean"&&!r?(0,_e.jsx)("span",{className:n.isFalse,children:s.falseValue}):r?(0,_e.jsxs)("button",{type:"button",onClick:()=>o(r),className:n.copyButton,children:[(0,_e.jsx)("span",{className:n.copyButtonText,children:r}),(0,_e.jsx)(Lo,{})]}):"-"})]},s.label)})})};var ge=require("react"),Po=require("react-redux");var Ui=require("react/jsx-runtime"),Nu=()=>(0,Ui.jsx)("svg",{focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"ReplayIcon",children:(0,Ui.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 _n={};oe(_n,{enUS:()=>Bf,nlNL:()=>Uf});var Bf={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"}]},Uf={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 Vi={form:"dd-pleCH",formInput:"dd-pGJMY",formSubmit:"dd--gkRg",actionButton:"dd-I2NEH",sources:"dd-xf9c6",source:"dd-a-vyX",link:"dd-PyUPS",linkContent:"dd-gARDA",showMoreSources:"dd-uDGi-"};var F=require("react/jsx-runtime"),Vf=3,zf=({sources:t,onClick:e})=>{let n=P(_n),o=x("WidgetKnowledgeAssistant",Vi),[s,r]=(0,ge.useState)(!1),i=s?t:t.slice(0,Vf);return i.length===0?null:(0,F.jsxs)("ul",{className:o.sources,children:[i.map(a=>(0,F.jsx)("li",{className:o.source,"data-testid":"knowledge-assist-source",children:(0,F.jsx)("a",{className:o.link,rel:"noreferrer",target:"_blank",href:a.url,onClick:d=>{d.stopPropagation(),e(a)},"data-tooltip":a.url?decodeURIComponent(a.url):void 0,children:(0,F.jsx)("span",{className:o.linkContent,children:a.name})})},a.name)),i<t&&(0,F.jsx)("button",{type:"button",className:o.showMoreSources,onClick:()=>r(!0),children:n("showMore",{amount:t.length-i.length})})]})},Wf=({innerRef:t,item:e,index:n,hasKeyboardInput:o,onCopy:s,onUse:r,onSourceClick:i})=>{var d;let a=P(_n);return(0,F.jsxs)(_,{"data-testid":"knowledge-assist-answer",ref:t,children:[(0,F.jsx)(K,{children:(0,F.jsxs)(K.Content,{children:[(0,F.jsx)(K.Title,{children:e.question}),(0,F.jsx)(mr,{content:e.answer.answer,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:s,onUse:o?r:void 0}),(0,F.jsx)(zf,{sources:(d=e.answer.sources)!=null?d:[],onClick:l=>i(l,e.question)})]})}),(0,F.jsxs)(_.ButtonsContainer,{children:[(0,F.jsx)("div",{}),(0,F.jsx)(Rn,{eventName:"knowledge assist feedback",eventData:{question:e.question,isFollowUpQuestion:n>0,isAgent:!0,answer:e.answer.answer},feedbackText:e.answer.answer,feedbackType:"assistant"})]})]})},zi=(0,ge.createContext)(null),Ou=({children:t})=>{let[e,n]=(0,ge.useState)(null),o=(0,Po.useSelector)(uo("knowledge-assist")),[s,r]=(0,ge.useState)(!1),[i,a]=(0,ge.useState)(null),d=(0,Po.useDispatch)(),l=Vt(u=>io({input:u,threadId:e,onNewThreadId(m){n(m)}})),c={isEnabled:o,isSubmitting:s,threadId:e,pendingInput:i,onSubmit(u){return h(this,null,function*(){r(!0),a(u),yield l.call(u),r(!1),a(null)})},onReset(){e&&d(vn(e))}};return(0,F.jsx)(zi.Provider,{value:c,children:t})},Du=()=>{let t=P(_n),e=x("WidgetKnowledgeAssistant",Vi),n=(0,ge.useContext)(zi),o=(0,ge.useRef)(null),[s,r]=(0,ge.useState)(""),i=l=>{r(l.target.value)},a=l=>{l.preventDefault(),n.onSubmit(s).then(()=>{var c;o.current&&((c=o.current)==null||c.focus(),r(""))})},d=l=>{l.preventDefault(),n.onReset()};return n.isEnabled?(0,F.jsxs)("form",{className:e.form,onSubmit:a,children:[(0,F.jsx)("input",{ref:o,className:e.formInput,placeholder:t("inputPlaceholder"),type:"text",disabled:n.isSubmitting,value:s,onChange:i}),(0,F.jsx)("button",{type:"submit",disabled:n.isSubmitting||s==="",className:e.formSubmit,children:t("submitLabel")}),(0,F.jsx)("button",{type:"button",title:t("resetLabel"),disabled:n.threadId===null||n.isSubmitting,onClick:d,className:e.actionButton,children:(0,F.jsx)(Nu,{})})]}):null},_u=()=>{var c,p;let t=P(_n),e=Ct(),n=(0,ge.useRef)(null),o=(0,ge.useContext)(zi),s=(p=(0,Po.useSelector)(ro((c=o.threadId)!=null?c:-1)))!=null?p:[],r=T("hasKeyboardInput"),i=me(),a=u=>{Ve(u),e("Assistant response copied",{name:"Knowledge Assistant",group:"knowlegde-assist",description:"",copiedText:u})},d=(u,m)=>{e("knowledge assist source viewed",{question:m,sourceViewed:u.url||u.name})},l=u=>{i.send(Be,{text:u,suggestion:{source:"cue",sourceText:u}}),e("Assistant response used",{name:"Knowledge Assistant",group:"knowlegde-assist",description:"",usedText:u})};return!o.isEnabled||(s==null?void 0:s.length)===0&&!o.isSubmitting?null:(0,F.jsx)(He,{type:"knowledge",title:t("titleKnowledgeAssistant"),"data-testid":"knowledge",children:(0,F.jsxs)(pe,{withDivider:!0,children:[s.map((u,m)=>(0,F.jsx)(Wf,{innerRef:m===s.length-1?n:void 0,item:u,index:m,hasKeyboardInput:r,onCopy:a,onUse:l,onSourceClick:d},`${u.question}_${u.answer}_${m}`)),o.pendingInput&&(0,F.jsx)(pr,{title:o.pendingInput})]})})};var Hu=require("react");var qf=/(https?:\/\/[^\s]+)/,Fu=t=>t.split(" ").find(e=>qf.test(e));var ke=require("react/jsx-runtime"),$f=({suggestion:t,lines:e,onUse:n})=>{var p;let o=t.text||t.url||t.message,s=Fu(o),r=P(vo),i=T("showImages"),a=T("fallbackImage"),d=T("hasKeyboardInput"),l=u=>{u.preventDefault(),u.stopPropagation(),d&&n(o)},c=(0,Hu.useCallback)(u=>{window.open(s,"_blank"),u.stopPropagation(),u.preventDefault()},[s]);return(0,ke.jsxs)(_,{onClick:d?l:void 0,"data-testid":"edit-suggestion",children:[(0,ke.jsxs)(K,{children:[i&&t.image&&(0,ke.jsx)(K.Image,{src:ir(t,"small",a||void 0),title:t.title}),(0,ke.jsxs)(K.Content,{children:[t.title&&(0,ke.jsx)(K.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((p=t.searchKeywords)==null?void 0:p.length)>0&&(0,ke.jsx)(_.Labels,{labels:t.searchKeywords}),(0,ke.jsx)(K.Content,{cropText:e==="single",lineClamp:e==="multiple",children:o})]})]}),(0,ke.jsxs)(_.Actions,{children:[s&&(0,ke.jsx)(_.ActionButton,{onClick:c,label:r("visitUrl")}),d&&(0,ke.jsx)(_.ActionButton,{primary:!0,onClick:l,label:r("useSuggestion")})]})]})},Ku=$f;var Ao=require("react/jsx-runtime"),Gf=({lines:t,suggestions:e})=>{let n=me(),o=(s,r)=>{n.send(Be,{text:s,suggestion:b(g({},r),{source:r.source,sourceText:r.text})})};return(0,Ao.jsx)(Ao.Fragment,{children:e.map(s=>(0,Ao.jsx)(Ku,{suggestion:s,lines:t,onUse:r=>o(r,s)},s.text||s.url||s.message))})},Bu=Gf;var Mo={};oe(Mo,{enUS:()=>Qf,nlNL:()=>Zf});var Qf={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"}]},Zf={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 Yt={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",sectionList:"dd-bF9pF",footer:"dd-tvofr",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",footerShortcut:"dd-dH7XJ",link:"dd-DRo0x"};var R=require("react/jsx-runtime"),zu=(t,e)=>{let n=(0,q.useSelector)(se);(0,Fn.useEffect)(()=>n?e.every(o=>!!o)?t():()=>{}:()=>{},[...e,n])},Xf=({onLogIn:t})=>{let e=x("Widget",Yt),n=T("isEmbedded"),o=T("adminUrl");return(0,R.jsx)("div",{className:e.loginText,children:(0,R.jsx)("div",{children:(0,R.jsx)($s,{isEmbedded:n,loginUrl:o,onLogIn:t})})},"login")},Uu=({text:t})=>{let e=x("Widget",Yt);return(0,R.jsx)("div",{className:e.stateText,children:(0,R.jsx)("div",{children:(0,R.jsx)("p",{children:t})})},"notification")},Jf=()=>{let t=P(Mo),e=x("Widget",Yt),n=Vt(()=>Ue({})),o=T("showSummaryCommand"),s=(0,q.useSelector)(uo("knowledge-assist"));return(0,R.jsx)(R.Fragment,{children:o&&s&&(0,R.jsx)("button",{type:"button",disabled:n.state==="loading",className:e.footerShortcut,onClick:()=>n.call(),children:t("linkSummary")})})},Yf=()=>{let t=P(Mo),e=(0,q.useDispatch)(),n=x("Widget",Yt),o=T("showSearch"),s=T("showSummaryCommand"),r=T("showKnowledgeSearch"),i=(0,q.useSelector)(uo("knowledge-assist")),a=T("isEmbedded"),d=(0,q.useSelector)(kn("/admin/")),l=me(),c=T("productName"),p=T("hasKeyboardInput"),u=Vt(()=>Ue({})),m=o||s||r||d;return zu(()=>{if(a)return e(Mi()),()=>{e(ru())}},[e,a]),!m||!p?null:(0,R.jsx)(He,{title:t("actions"),type:"shortcuts",children:(0,R.jsxs)("div",{className:n.shortcutList,children:[o&&(0,R.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-search","aria-label":t("linkSearch"),onClick:()=>l.send("ShowCommandPalette",{isOpen:!0}),children:[(0,R.jsx)(bn,{}),t("linkSearch")]}),s&&!i&&(0,R.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-summary","aria-label":t("linkSummary"),disabled:u.state==="loading",onClick:()=>u.call(),children:[(0,R.jsx)(Su,{}),t("linkSummary")]}),r&&!i&&(0,R.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-knowledge-assist","aria-label":t("linkKnowledgeSearch"),onClick:()=>l.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,R.jsx)(vu,{}),t("linkKnowledgeSearch")]}),d&&(0,R.jsxs)("a",{className:n.shortcut,target:"_blank",href:d,"data-testid":"shortcut-studio-login","aria-label":t("linkStudioLogin",{productName:c}),rel:"noreferrer",children:[(0,R.jsx)(yu,{}),t("linkStudioLogin",{productName:c})]})]})})},eh=()=>{let t=(0,q.useDispatch)(),e=(0,q.useSelector)(co),n=(0,q.useSelector)(Yl),o=(0,q.useSelector)(mu),s=(0,q.useSelector)(pl),r=(0,q.useSelector)(Ms),i=(0,q.useSelector)(Hs),a=(0,q.useSelector)(Ht),d=(0,q.useSelector)(Ke);return(0,Fn.useEffect)(()=>{!!s&&!n&&E.warn("Custom data provided, but no schema.")},[s,n]),zu(()=>{e.forEach(({type:l})=>{l==="entities"?t(Ne()):Go.includes(l)||t(Oe(l))})},[t,d,a]),(0,Fn.useEffect)(()=>{o.length>0&&!e.some(l=>l.type==="cues")&&E.warn("Received cues, but cues are not configured in widget.")},[e,o]),(0,R.jsx)(Fn.Fragment,{children:e.map(({type:l,title:c,amount:p,lines:u,schema:m})=>{var y,f;switch(l){case"entities":return r&&r.length>0&&(0,R.jsx)(He,{type:l,title:c,"data-testid":`type-${l}`,children:(0,R.jsx)(hu,{entities:r})},l);case"cues":return o&&o.length>0&&(0,R.jsx)(He,{type:l,title:c,"data-testid":`type-${l}`,children:(0,R.jsx)(pe,{withDivider:!0,children:(0,R.jsx)(Pu,{cues:o})})},l);case"custom-data":return s&&m&&(0,R.jsx)(He,{type:l,title:c,"data-testid":`type-${l}`,children:(0,R.jsx)(pe,{withDivider:!0,children:(0,R.jsx)(Mu,{data:s,schema:m})})},l);default:return((f=(y=i[l])==null?void 0:y.suggestions)==null?void 0:f.length)>0&&(0,R.jsx)(He,{type:l,title:c,"data-testid":`type-${l}`,children:(0,R.jsx)(pe,{withDivider:!0,children:(0,R.jsx)(Bu,{lines:u,contentType:l,suggestions:i[l].suggestions.slice(0,p)||[]})})},l)}})})},th=({children:t})=>{let e=x("Widget",Yt);return(0,R.jsx)("div",{className:e.footer,children:t})},nh=({onLogIn:t})=>{let e=P(Mo),n=x("Widget",Yt),o=(0,q.useSelector)(un),s=(0,q.useSelector)(se),r=(0,q.useSelector)(Ga),i=(0,q.useSelector)(Ht);return o===!1?(0,R.jsx)(Uu,{text:e("notSupported")}):s===!1?(0,R.jsx)(Xf,{onLogIn:t}):!i||!r||s===null?(0,R.jsx)(Uu,{text:e("waiting")}):(0,R.jsx)("div",{className:(0,Vu.default)(n.root),"data-testid":"widget",children:(0,R.jsxs)(Ou,{children:[(0,R.jsxs)(jo,{className:n.sectionList,children:[(0,R.jsx)(Yf,{}),(0,R.jsx)(eh,{}),(0,R.jsx)(_u,{})]}),(0,R.jsxs)(th,{children:[(0,R.jsx)(Du,{}),(0,R.jsx)(Jf,{})]})]})})},Wu=nh;function Hn(t){let e=new Range;return e.selectNodeContents(t),e}function ju(t,e,n){try{return Rt(t,e,n),!0}catch(o){return!1}}function fr(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function hr(t){return"tagName"in t&&t.tagName==="BR"}var No=/[\u200B-\u200D\uFEFF]/g;function Rt(t,e,n){let o=new Range;if(t.firstChild===null&&e===0&&n===0)return o.selectNodeContents(t),o;let s=0,r=!1;function i(d,l){let c=-1,p=/[\u200B-\u200D\uFEFF]/;if(!p.test(d))return l;for(let u=0;u<=d.length;u++)if(p.test(d[u])||c++,c===l)return u;throw new Error("Offset out of range")}function a(d){switch(d.nodeType){case Node.TEXT_NODE:{let l=d.textContent,c=l.replace(No,""),p=s+c.length,u=e>=s&&e<=p,m=n>=s&&n<=p;if(u){let y=i(l,e-s);y===0&&!m?o.setStartBefore(d):o.setStart(d,y)}m&&(o.setEnd(d,i(l,n-s)),r=!0),s=p;break}case Node.ELEMENT_NODE:{if(hr(d)&&(s===e&&o.setStartBefore(d),s++,s===n)){o.setEndAfter(d),r=!0;return}for(let c=0;c<d.childNodes.length&&(a(d.childNodes[c]),!r);c++);let l=d.lastChild;fr(d)&&l&&!fr(l)&&!hr(l)&&s++;break}default:break}}if(a(t),o.startContainer===document)throw new Error("Offsets out of bound");return o}function Oo(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:o,endContainer:s,endOffset:r,collapsed:i}=e,a,d,l=0;function c(p){let u=p===t,m=p===n,y=p===s;switch(p.nodeType){case Node.TEXT_NODE:{let f=p.textContent;m&&(a=l+f.substring(0,o).replace(No,"").length),y&&(d=l+f.substring(0,r).replace(No,"").length),l+=f.replace(No,"").length;break}case Node.ELEMENT_NODE:{if(hr(p)&&p.nextSibling){l++;break}!u&&fr(p)&&p.previousSibling&&l++;for(let f=0;f<p.childNodes.length;f++){let v=m&&f===o,C=y&&f===r;if(v&&(a=l),C&&(d=l),d!==void 0||((!v||!i)&&c(p.childNodes[f]),y&&f===r-1&&(d=l),d!==void 0))break}y&&(d=l);break}default:break}}if(c(t),d===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:d,end:d}}function Do(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:o,endContainer:s,endOffset:r,collapsed:i}=e,a=0,d="";function l(c){let p=c===t,u=c===n,m=c===s;switch(u&&(a=1),c.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let y=u?o:0,f=m?r:void 0;d+=c.textContent.replace(No,"").substring(y,f);break}case Node.ELEMENT_NODE:{if(!i&&a===1&&hr(c)&&c.nextSibling){d+=`
9
9
  `;break}!p&&!i&&a===1&&fr(c)&&c.previousSibling&&(d+=`
10
- `);let y=u?o:0,f=m?Math.min(r,c.childNodes.length):c.childNodes.length;for(let v=y;v<f&&(l(c.childNodes[v]),a!==2);v++);break}default:break}m&&(a=2)}return l(t),d}var qu=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(qu||{}),pt=class{constructor(e){this.element=e;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(e,n){let o=s=>{n(s)};this.element.addEventListener(e,o),this.disposeHandlers.push(()=>{this.element.removeEventListener(e,o)})}removeEventListener(e,n){this.element.removeEventListener(e,n)}handleInteraction(){let e=this.getText(),n=this.getHTML(),o=this.getSelection(),s=this.cachedCaretPosition===null;if(!this.isActive||(e===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),e!==this.cachedText?(this.cachedText=e,this.cachedHTML=n,s=!0,this.emit("change",{plainText:e,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,s=!0,this.emit("change",{plainText:e,rawHTML:n})),(o.start!==this.cachedSelection.start||o.end!==this.cachedSelection.end)&&(this.cachedSelection=o,s=!0,this.emit("selection",o)),!s))return;let r=this.getCaretPosition();yt(r,this.cachedCaretPosition)||(this.cachedCaretPosition=r,this.emit("caretposition",r))}handleClick(){this.handleInteraction()}handleFocus(){let e=!this.isFocused;this.isFocused=!0,e&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let e=this.isFocused;this.isFocused=!1,e&&this.emit("blur")}handleKeyDown(e){let{key:n,ctrlKey:o,metaKey:s}=e;this.isPossibleClearInputAction=Object.values(qu).includes(n)||n.toLowerCase()==="z"&&(o||s),this.emit("keydown",e)}handleKeyUp(e){this.handleInteraction(),this.emit("keyup",e)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){var o,s;let n=((o=e.clipboardData)==null?void 0:o.getData("text"))||((s=e.clipboardData)==null?void 0:s.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 e=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});e.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{e.disconnect()})}focus(){this.element.focus()}emit(e,...n){this.isDisposed||this.eventListeners[e]&&this.eventListeners[e].forEach(o=>{o(...n)})}on(e,n){this.isDisposed||(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n))}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};function $u(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var en=class extends pt{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Do(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let o="getSelection"in n?n.getSelection():window.getSelection();if(!o)return null;let s="getComposedRanges"in o&&n instanceof ShadowRoot?(i=o.getComposedRanges(n))==null?void 0:i[0]:o.rangeCount>0?o.getRangeAt(0):null;if(!s)return null;let r=this.element.ownerDocument.createRange();return r.setStart(s==null?void 0:s.startContainer,s==null?void 0:s.startOffset),r.setEnd(s==null?void 0:s.endContainer,s==null?void 0:s.endOffset),!r||!this.element.contains(r.startContainer)||!this.element.contains(r.endContainer)?null:r}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let o=n.getBoundingClientRect();return!$u(o)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=n.getBoundingClientRect(),n.deleteContents(),!$u(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let n=this.getRange();if(n)return Oo(this.element,n);let o=this.lastKnownSelection;if(o&&ju(this.element,o.start,o.end))return o;let s=Hn(this.element);return s.collapse(!1),Oo(this.element,s)}getSelectedText(){let{start:n,end:o}=this.getSelection();return Do(this.element,Rt(this.element,n,o))}listen(){super.listen();let n=new MutationObserver(r=>{var i,a;r.length===2&&r[0].addedNodes.length===1&&((i=r[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=r[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 o=this.element.isContentEditable,s=new MutationObserver(()=>{this.element.isContentEditable!==o&&(o=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});s.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>s.disconnect())}};var oh=["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 Gu(t,e){let n="mozInnerScreenX"in window,o=document.createElement("div");o.id="input-textarea-caret-position-mirror-div";let s=o.style,r=window.getComputedStyle(t),i=t.ownerDocument.body;s.whiteSpace="pre-wrap",s.wordWrap="break-word",s.position="absolute",s.visibility="hidden",oh.forEach(function(c){s[c]=r[c]}),n?t.scrollHeight>parseInt(r.height)&&(s.overflowY="scroll"):s.overflow="hidden",o.textContent=t.value.substring(0,e);let a=document.createElement("span");a.textContent=t.value.substring(e)||".",o.appendChild(a),i.appendChild(o);let d=t.getBoundingClientRect(),l={top:d.top-t.scrollTop+a.offsetTop+parseInt(r.borderTopWidth)+a.offsetHeight,left:d.left-t.scrollLeft+a.offsetLeft+parseInt(r.borderLeftWidth)};return i.removeChild(o),l}var tn=class extends pt{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:o}=this.element;return{start:n,end:o}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return Gu(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 r;return(r=n==null?void 0:n.get)==null?void 0:r.call(this.element)},set:r=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,r),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let o=this.element.disabled,s=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});s.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>s.disconnect())}};function Qu(t,e,n){let o=`deepdesk-iframe-${t}`,s=document.getElementById(o);if(s)return s;let r=document.createElement("iframe"),i=new URL(e);return Object.entries(n).forEach(([a,d])=>{i.searchParams.append(a,d)}),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=o,r.title=`iframe-${t}`,r.src=i.toString(),window.document.body.appendChild(r),r}function sh(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch(e){return t}}var Wi=class{constructor(e){this.name=e;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(e)}onMessage(e){this.broadcastChannel.addEventListener("message",e),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",e)})}postMessage(e){this.broadcastChannel.postMessage(JSON.stringify(e))}close(){this.disposeHandlers.forEach(e=>e()),this.broadcastChannel.close()}},ji=class{constructor(e,n,o){this.name=e;this.targetOrigin=n;this.options=o;this.disposeHandlers=[];this.iframe=Qu(e,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(e),this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(n=>n()),(e=this.iframe)==null||e.remove()}},qi=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(e){this.sessionId!==e&&(this.cleanup(),E.info("Set sessionId",e),this.sessionId=e,this.channel=this.createChannel(e))}createChannel(e){let n=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new ji(e,this.deepdeskUrl,{debug:!0}):new Wi(e),o=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=sh(s.data);typeof r!="object"||r.type!=="event"||r.channel!==e||(E.info("Received broadcast event",this.sessionId,s),(a=(i=this.eventMap)[r.name])==null||a.call(i,r.payload))};return n.onMessage(o),n}send(e,n,o){var i,a;E.info("Broadcast event",{sessionId:this.sessionId,name:e,payload:n});let s={type:"event",name:e,payload:n};o!==!1&&((a=(i=this.eventMap)[e])==null||a.call(i,n));let r=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;r==null||r.postMessage(b(g({},s),{channel:this.sessionId}))}cleanup(e=!1){var n,o;(n=this.channel)==null||n.close(),delete this.channel,e&&((o=this.defaultChannel)==null||o.close(),delete this.defaultChannel)}},Zu=qi;function rh(t){return t.replace(/(_\w)/g,e=>e[1].toUpperCase())}function H(t){return Array.isArray(t)?t.map(H):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>b(g({},e),{[rh(n)]:H(t[n])}),{}):t}function ih(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Y(t){return Array.isArray(t)?t.map(Y):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>b(g({},e),{[ih(n)]:Y(t[n])}),{}):t}var Kn=class extends Error{constructor(n,o){super(n);this.body=o;this.name="CustomError"}};var $i=t=>new Promise(e=>{setTimeout(e,t)});var Bn=class extends Kn{constructor(){super(...arguments);this.name="ClientError"}},Qi=class extends Kn{constructor(){super(...arguments);this.name="ServerError"}},Gi=new Map;function ah(t){return h(this,null,function*(){if(t.status===204)return t.text().catch(()=>{}),null;let e=t.headers.get("content-type");if(e&&e.includes("application/json"))return t.json();let n=yield t.text();return n===""?null:(E.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var It=class It{constructor(e="",n={}){this.baseUrl=e;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,n={}){return new Promise((o,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,d=n.method===void 0||n.method.toLowerCase()==="get",N=n,{useCache:l=!1,abortLatest:c=!1,attempts:p=1,retryDelay:u=500,refreshTokenOn401:m=!0,retryOnError:y=M=>M instanceof TypeError,retryOnResponse:f=M=>M.status>=500,version:v=null}=N,C=O(N,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(l)if(d){if(Gi.has(i)){o(Gi.get(i));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let k=b(g({credentials:"include"},C),{headers:g({Accept:"application/json","Content-Type":"application/json"},C.headers)});!d&&this.csrfToken&&(k.headers=b(g({},k.headers),{"X-CSRFToken":this.csrfToken})),typeof v=="string"&&(k.headers=b(g({},k.headers),{"X-Deepdesk-API-Version":v}));let S=p,I=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let w=()=>h(this,null,function*(){return S--,a(i,k).then(M=>h(this,null,function*(){return f(M)&&!r.isAborted&&S>0?(yield $i(u),w()):M.status===401&&m===!0&&I===!1?(I=!0,yield this.refreshToken(),w()):M})).catch(M=>h(this,null,function*(){if(y(M)&&!r.isAborted&&S>0)return yield $i(u),w();throw M}))});w().then(M=>h(this,null,function*(){let B=yield ah(M);if(delete this.latestRequestByUrl[i],M.status>=500){s(new Qi("Server Error",B));return}else if(M.status===401){s(new Bn("Unauthorized",B));return}else if(M.status===403){s(new Bn("Forbidden",B));return}else if(M.status===404){s(new Bn("Not Found",B));return}else if(M.status>=400){s(new Bn("Bad Request",B));return}l&&Gi.set(i,B),o(B)})).catch(M=>{s(M)})})}validateToken(){return h(this,null,function*(){let{has_valid_access_token:e}=yield this.get("/auth/validate");if(!e)try{yield this.refreshToken()}catch(o){return!1}let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/");return!!n})}refreshToken(){return It.refreshingToken||(It.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{It.refreshingToken=null},1e3*60)})),It.refreshingToken}get(e,n){return this.request(e,n)}post(e,n,o){return this.request(e,g({method:"POST",body:JSON.stringify(n)},o))}patch(e,n,o){return this.request(e,g({method:"PATCH",body:JSON.stringify(n)},o))}put(e,n,o){return this.request(e,g({method:"PUT",body:JSON.stringify(n)},o))}delete(e,n){return this.request(e,g({method:"DELETE"},n))}};It.refreshingToken=null;var nn=It;var Xu;(e=>{let t;(i=>(i.SEND_MESSAGE="Send Message",i.HANDLING_TIME="Handling Time",i.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",i.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||(e.EventType={}))})(Xu||(Xu={}));function yr(t){return b(g({},H(t)),{tags:t.tags})}var on=class on{constructor(e,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new nn(e,{fetch:n.fetch}),this.client.patchFetch(o=>(s,r)=>h(this,null,function*(){let i=yield o(s,r);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return h(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=yield this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(on.exchangeTokenPromise||(on.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),on.exchangeTokenPromise):Promise.resolve()})}createConversation(e){return h(this,null,function*(){yield this.preflight(),E.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let n=yield this.client.post("/api/conversations",b(g({},Y(e)),{tags:e.tags}),{version:"v2"});return yr(n)})}getMe(){return h(this,null,function*(){let e=yield this.client.get("/apis/admin/session/me/");return H(e)})}postIdentity(e){return h(this,null,function*(){yield this.client.post("/apis/admin/session/me/identities/",Y(e))})}patchMe(e){return h(this,null,function*(){let n=yield this.client.patch("/apis/admin/session/me/",Y(e));return H(n)})}getProfile(e){return h(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${e}/`,{useCache:!0});return H(n)})}getKnowledgeAssistant(e){return h(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{useCache:!0});return H(n)})}getContentTypes(){return h(this,null,function*(){let e=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return H(e)})}getAccount(){return h(this,null,function*(){let e=yield this.client.get("/apis/admin/account/",{useCache:!0});return H(e)})}getPlatformConfig(e){return h(this,null,function*(){let n=e!==void 0?`/platform/config/${e}/`:"/platform/config/",{config:o}=yield this.client.get(n,{useCache:!0});return H(o)})}checkUserExists(e){return h(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${e}`,{version:"v1"});return n})}getConversationBySessionId(o){return h(this,arguments,function*(e,n={}){yield this.preflight(),E.info(`Getting conversation for session ${e}`);let{attempts:s=1,retryDelay:r=1e3}=n,i=yield this.client.get(`/api/conversations/by_session_id/${e}`,{attempts:s,retryDelay:r,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return E.info(`Successfully retrieved conversation ${i.id} for session ${e}`),yr(i)})}isConversationSupported(o){return h(this,arguments,function*(e,n={}){E.info(`Check if conversation for session ${e} is supported`);let{attempts:s=1,retryDelay:r=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${e}/active_profile`,{attempts:s,retryDelay:r,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(e,n){return h(this,null,function*(){let o=Y(n);n.tags&&(o.tags=n.tags);let s=yield this.client.put(`/api/conversations/${e}`,o,{version:"v2"});return yr(s)})}postMessages(e,n){return h(this,null,function*(){return(yield this.client.post(`/api/conversations/${e}/messages`,n.map(s=>b(g({},Y(s)),{tags:s.tags})),{version:"v2"})).map(s=>yr(s))})}sendEvent(e,n){return h(this,null,function*(){let i=n,{data:o}=i,s=O(i,["data"]),r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[d,l])=>b(g({},a),{[d]:l}),{});return this.client.post("/api/events",Y(b(g(g({},r),s),{data:o,name:e})),{version:"v2"})})}sendEventV1(e,n){return h(this,null,function*(){let o=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[r,i])=>b(g({},s),{[r]:i}),{});return this.client.post("/api/events",{event:e,data:Y(g(g({},n),o))},{version:"v1"})})}getEntities(e){return h(this,null,function*(){return(yield this.client.post("/api/entities",{messages:e.filter(o=>o.text)},{version:"v1"})).entities})}getTemporaryExchangeToken(){return h(this,null,function*(){return(yield this.client.get("/auth/exchange-token")).jwt})}exchangeTokenForAccessCookie(e){return h(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:e}).catch(n=>{throw E.warn(`Invalid token '${e}'`),n})})}authenticateWithKey(e,n){return h(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Y(n),{refreshTokenOn401:!1,headers:{apikey:e}})})}getTextSuggestions(s){return h(this,arguments,function*(e,n={},o){return o==="sticky-messages"?this.getPinnedMessages(e):(yield this.client.post(`/api/conversations/${e}/recommend/${o}`,Y(n),{abortLatest:!0,version:"v1"})).map(i=>b(g({},H(i)),{text:i.text||i.url||i.message,source:o,type:o})).filter((i,a,d)=>a===d.findIndex(l=>l.text===i.text))})}isLoggedIn(){return h(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(e,n){return h(this,null,function*(){return(yield this.client.post(`/api/conversations/${e}/autocomplete`,Y(n),{abortLatest:!0,version:"v1"})).map(s=>({score:1,source:s.source,sourceText:s.source_text,text:s.label,trainingJobs:s.training_jobs,searchKeywords:s.search_keywords,type:s.source})).filter((s,r,i)=>r===i.findIndex(a=>a.text===s.text))})}getPinnedMessages(e){return h(this,null,function*(){let n=yield this.client.get(`/api/conversations/${e}/sticky-messages`,{abortLatest:!0,version:"v1"});return H(n).map(o=>b(g({},o),{text:o.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(e){return h(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",Y(e),{abortLatest:!0,version:"v1"});return H(n)})}search(e){return h(this,null,function*(){let n=yield this.client.post(`/api/profiles/${e.profile}/search`,Y(e),{version:"v2"});return H(n)})}knowledgeAssist(r,i,a){return h(this,arguments,function*(e,n,o,s={}){let d=yield this.client.post(`/api/knowledge-assist/assistants/${o}/search`,Y({question:e.question,doNotKnowAnswer:e.doNotKnowAnswer,customerInstruction:e.customerInstruction,chatHistory:n.map(l=>({question:l.question,answer:l.answer.answer})),agentId:s.agentId,conversationId:s.conversationId}),{version:"v2"});return H(d)})}requestLoginByEmail(e){return h(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:e});return H(n)})}requestPasswordlessToken(){return h(this,null,function*(){let e=yield this.client.get("/apis/admin/session/passwordless/request/");return H(e.token)})}getCsrfToken(){return h(this,null,function*(){let{token:e}=yield this.client.get("/apis/admin/session/csrf/");return e})}verifyLoginToken(e){return h(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:e});return H(n)})}evaluateRule(r,i,a){return h(this,arguments,function*(e,n,o,s={}){let d=new URLSearchParams;s.raiseForFailingConditions&&d.set("raise_for_failing_conditions","true");let l=yield this.client.post(`/api/conversations/${n}/rules/${e}/evaluate?${d.toString()}`,o,{version:"v2"});return l?H(l.cues):[]})}getSummary(o){return h(this,arguments,function*(e,n={}){let s=yield this.client.post("/api/summary",{conversation:{messages:e.filter(r=>r.text&&r.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return H(s)})}evaluateAssistant(e,n){return h(this,null,function*(){var a;let o=new URLSearchParams,{expectFormat:s="text"}=n||{};if(s.startsWith("json-schema:")){let d=s.replace("json-schema:","");o.append("expect_response_format","json-schema"),o.append("expect_response_format_schema",d)}else o.append("expect_response_format",s);n!=null&&n.externalConversationId&&o.append("external_conversation_id",n.externalConversationId);let r=n!=null&&n.threadId?`/api/v2/assistants/${e}/threads/${n==null?void 0:n.threadId}/evaluate?${o.toString()}`:`/api/v2/assistants/${e}/evaluate?${o.toString()}`,i=yield this.client.post(r,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return H(i.output)})}createAssistantThread(e){return h(this,null,function*(){let{assistantCode:n}=e,o=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return H(o)})}postMessageToAssistantThread(e){return h(this,null,function*(){let{assistantCode:n,threadId:o,message:s}=e,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/${o}/messages/`,{content:s,role:"user"});return H(r)})}getRules(){return h(this,null,function*(){let e=new URLSearchParams,n=yield this.client.get(`/apis/admin/rule-engine/rules/?${e.toString()}`,{useCache:!0});return H(n)})}translateMessages(e){return h(this,null,function*(){let n=yield this.client.post("/api/translate",Y(e),{version:"v2"});return H(n)})}handleDeepdeskVersionHeaders(e){e.headers.forEach((n,o)=>{let s=o.toLowerCase(),r=s.match(Aa);if(!n||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&E.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};on.exchangeTokenPromise=null;var mt=on;var br=require("@reduxjs/toolkit");var Yu=require("@reduxjs/toolkit");var Ju={startTime:null,stopTime:null},ep=t=>t.handlingTime,tp=(0,Yu.createSlice)({name:"handlingTime",initialState:Ju,reducers:{handlingTimeStart(t){if(t.startTime&&!t.stopTime)throw new Error("Timing already started");t.startTime=new Date,t.stopTime=null},handlingTimeStop(t){if(!t.startTime)throw new Error("Timing not started");t.stopTime=new Date},handlingTimeReset(t){t.startTime=null,t.stopTime=null}},extraReducers:t=>{t.addCase(W,()=>Ju)}}),{handlingTimeStart:np,handlingTimeStop:vr,handlingTimeReset:op}=tp.actions,sp=tp.reducer;var rp=(t={})=>{let e=g({onAuthError:cn(!1)},t);return n=>o=>s=>("error"in s&&s.error.message==="Unauthorized"&&n.dispatch(e.onAuthError),o(s))};var xr=require("@reduxjs/toolkit");var Sr={list:{keywordMatches:[]},fetchState:"idle"};var sn=(0,xr.createAsyncThunk)("styleSuggestions/getAll",(n,o)=>h(void 0,[n,o],function*({text:t},e){var d;let{deepdeskAPI:s}=e.extra,r=e.getState(),{showStyleSuggestions:i}=r.settings,a=(d=r.conversation.current)==null?void 0:d.profileCode;if(!i)return Sr.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return s.getStyleSuggestions({profileCode:a,message:t})})),lh=(0,xr.createSlice)({name:"styleSuggestions",initialState:Sr,reducers:{},extraReducers:t=>{t.addCase(sn.pending,e=>{e.fetchState="loading"}).addCase(sn.rejected,e=>{e.fetchState="error"}).addCase(sn.fulfilled,(e,n)=>{e.fetchState="done",yt(e.list,n.payload)||(e.list=n.payload)}).addCase(Ot,e=>{e.list=Sr.list}).addCase(W,()=>Sr)}}),ip=lh.reducer;var ap=(t={})=>{let e,n=!0,o=g({getStyleSuggestions:sn,debounce:500},t);return s=>r=>i=>{var m;let a=s.getState().input.text,d=r(i),l=s.getState();if(l.auth.isLoggedIn!==!0)return d;let{showStyleSuggestions:c}=l.settings;if(!((m=l.conversation.current)==null?void 0:m.id)||!c)return d;let{text:u}=l.input;return u===a&&!n||(clearTimeout(e),u==="")||(e=setTimeout(()=>{n=!1,s.dispatch(o.getStyleSuggestions({text:u}))},t.debounce)),d}};function dh(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var lp=(t={})=>{let e=g({getTextSuggestions:Oe,getAutocompleteSuggestions:xo,debounce:200,check:We},t),n;return o=>s=>r=>{var f;let{input:i}=o.getState(),a=s(r),d=o.getState();if(d.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:l,showTabCompletion:c}=d.settings,p=(f=d.conversation.current)==null?void 0:f.id,u=r.type===Ks.toString();if(!p||!l&&!c)return a;let{input:m}=d;return dh(m,i)&&!u||(clearTimeout(n),!e.check(d))||(n=setTimeout(()=>{let v=pn(d);v===""?o.dispatch(e.getTextSuggestions("default")):o.dispatch(e.getAutocompleteSuggestions(v))},u?0:e.debounce)),a}};var dp=sn.fulfilled.toString();function ch(t,e){let n=new Set([...e.keywordMatches.map(s=>s.keyword)]),o=[];return n.forEach(s=>{let r=t.keywordMatches.filter(d=>d.keyword===s),i=e.keywordMatches.filter(d=>d.keyword===s),a=i.length-r.length;a<=0||o.push(...i.slice(0,a))}),o}var cp=t=>e=>n=>o=>{var l;if(o.type!==dp){n(o);return}let s=e.getState().styleSuggestions.list;n(o);let r=e.getState(),i=r.styleSuggestions.list,a=(l=r.conversation)==null?void 0:l.current;if(s===i)return;let d=ch(s,i);o.type===dp&&d.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:d}})};var uh=(0,br.combineReducers)({assistants:Zl,auth:za,conversation:Qa,contentTypes:Jl,passwordlessToken:iu,entities:bd,knowledgeAssistant:jl,handlingTime:sp,info:yl,input:dl,settings:_a,profile:ed,search:wl,styleSuggestions:ip,ui:uc,rules:uu,textSuggestions:qd});function up(t){return(0,br.configureStore)({reducer:uh,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI}},serializableCheck:!1}),rp(),lp({debounce:200}),ap({debounce:500}),cp(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var ph=t=>{var e,n;return(n=(e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())!=null?n:"unknown"},mh=t=>e=>n=>o=>{var a,d,l,c,p,u,m;let s=e.getState(),r=Mr("inlineSuggestions")(s);switch(o.type){case cn.toString():{!o.payload&&t.emit("logout",void 0);break}case Ne.fulfilled.toString():o.payload.length>0&&t.sendEvent("entities found",{conversationId:(a=s.conversation.current)==null?void 0:a.id,data:{entities:o.payload}});break;case xe.toString():t.sendEvent(o.payload.name,{conversationId:((d=o.payload.options)==null?void 0:d.includeConversationData)&&((l=s.conversation.current)==null?void 0:l.id),data:o.payload.data});break;case Ot.toString():t.logSendMessage(o.payload);break;case Jt.fulfilled.toString():o.isBroadcasted||t.broadcast(Kr,o,!1),(c=o.payload.options)!=null&&c.shouldEmit&&t.emit("cues",o.payload.cues);break;case ks.toString():t.emit("call-to-action",{cue:o.payload});break;case Ye.fulfilled.toString():o.isBroadcasted||t.broadcast(Br,o,!1);break;default:break}let i=n(o);switch(o.type){case Ot.toString():t.handleAfterSendMessage(o.payload);break;case Co.toString():t.onUpdateShowTabHint(o.payload);break;case vr.toString():t.logHandlingTime();break;case"analytics/logEvent/fulfilled":{t.emit("event",o.meta.arg);break}case es.toString():{let{start:y,end:f}=s.input.selection;t.emit("replace",b(g({},o.payload),{replace:o.payload.replace==="selection"?{start:y,end:f}:{start:0,end:f}}));break}case Le.toString():{let{start:y,end:f}=s.input.selection;t.emit("select-suggestion",b(g({type:ph(o.payload.suggestion)},o.payload),{replace:o.payload.replace==="selection"?{start:y,end:f}:{start:0,end:f}})),r&&e.dispatch(vt([]));break}case ts.toString():t.emit("select-image",o.payload),t.sendEvent("Image attached",{conversationId:(p=s.conversation.current)==null?void 0:p.id,data:{path:o.payload.suggestion.image,title:o.payload.suggestion.title}});break;case vt.toString():{r&&o.payload.length>0&&e.dispatch(ns(0));break}case Ue.fulfilled.toString():{t.sendEvent("conversation summarized",{conversationId:(u=s.conversation.current)==null?void 0:u.id,data:{summary:o.payload,assistant:(m=e.getState().profile.data)==null?void 0:m.summarizerAssistantNew}});break}default:break}return i},pp=mh;var mp=require("@reduxjs/toolkit");function Zi(t){return t.toISOString().replace("T"," ").replace("Z","")}var gh=(t,e)=>e.version,gp=(0,mp.createSelector)([fn,Ke,ep,gh],(t,e,n,o)=>{if(!e)return E.warn("No conversationId for handling time metrics"),null;let{startTime:s,stopTime:r}=n;return!s||!r?(E.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:e,clientVersion:o,agentId:t==null?void 0:t.agentId,agentName:t==null?void 0:t.agentName,agentEmail:t==null?void 0:t.agentEmail,timeStart:Zi(s),timeStop:Zi(r)}});function fp(t,e,n){var B,ne,ye,D;let o=(B=e.conversation.current)==null?void 0:B.id;if(!o)return E.warn("No conversationId for send message metrics"),null;let{text:s,metrics:{numCharsTyped:r,numCharsPasted:i,numCharsCut:a,numCharsDeleted:d,numPaste:l,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:u,cuts:m,deletions:y,textSuggestions:f,offeredTextSuggestions:v}}=e[t],C=s.length,S=f.reduce((U,{text:Fe,searchTerm:ve})=>U+Fe.length-(ve?ve.length:0),0),I=c!=null?c:Date.now(),w=(Date.now()-I)/1e3+(p||0),N=r/w,M=f.reduce((U,{searchTerm:Fe})=>U+(Fe?Fe.length:0),0);return{conversationId:o,source:"agent",text:s,clientVersion:n.version,pastes:u,cuts:m,deletions:y,lenTextTyped:r+M,lenTextTotal:C,lenTextAssisted:S,lenTextPasted:i,lenTextCut:a,lenTextDeleted:d,timeTotalSeconds:w,charsPerSecond:N,numPastes:l,textSuggestionsV2:f,suggestionsCounters:[{source:"gpt",countOffered:v.filter(U=>U.source==="gpt").length}],agentId:(ne=e.info.agentInfo)==null?void 0:ne.agentId,agentName:(ye=e.info.agentInfo)==null?void 0:ye.agentName,agentEmail:(D=e.info.agentInfo)==null?void 0:D.agentEmail}}function Xi(t,e){var r;let n=t.closest(e);if(n)return n;let o=t.getRootNode().host;if(o instanceof HTMLElement)return Xi(o,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?Xi(s,e):null}function hp(t,e){return Xi(t,e)}function yp(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function fh(t){return typeof t=="object"&&t!==null&&"tagName"in t}function Cr(t){return fh(t)&&(Xt(t)||Qs(t))}var Sp,Ge=new Map,hh=["bottom","height","left","right","top","width"],vp=(t,e)=>!t&&!e?!1:t&&!e||!t&&e?!0:hh.some(n=>t[n]!==e[n]);function xp(t){var n,o,s;if(t.ownerDocument===document)return[];let e=(s=(o=(n=t.ownerDocument)==null?void 0:n.defaultView)==null?void 0:o.frameElement)!=null?s:null;return e?[e,...xp(e)]:[]}function bp(t,e){return!t||!e?null:b(g({},t),{top:t.top+e.top,left:t.left+e.left})}var wr=!1,Cp=()=>{wr=!0;let t=[];if(Ge.forEach((e,n)=>{if(!n.isConnected){e.rect=null,t.push(e),Ge.delete(n);return}let o=n.getBoundingClientRect();vp(o,e.rect)&&(e.rect=o,t.push(e))}),t.forEach(e=>{let n=e.parentRects?e.parentRects.reduce(bp,e.rect):e.rect;vp(n,e.totalRect)&&e.callbacks.forEach(o=>o(n)),e.totalRect=n}),Ge.size===0){wr=!1;return}Sp=window.requestAnimationFrame(Cp)};function Ji(t,e){let n=xp(t),o=[],s=n.map((r,i)=>Ji(r,a=>{o[i]=a;let d=Ge.get(t);if(!d)return;let l=o.reduce(bp,d.rect);d.callbacks.forEach(c=>c(l))}));return{observe(r=!0){if(s.forEach(i=>i.observe(!1)),Ge.has(t)){let i=Ge.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else Ge.set(t,{rect:void 0,callbacks:[e],parentRects:o});r&&!wr&&Cp()},unobserve(){s.forEach(i=>i.unobserve());let r=Ge.get(t);if(r){let i=r.callbacks.indexOf(e);i>=0&&r.callbacks.splice(i,1),r.callbacks.length||Ge.delete(t),Ge.size||(cancelAnimationFrame(Sp),wr=!1)}}}}var wp,Qe=new Map,Tp=()=>{Qe.forEach((t,e)=>{if(!e.isConnected){Qe.delete(e);return}let{clientHeight:n,scrollHeight:o}=e,s=o>n;t.visible!==s&&(t.visible=s,t.callbacks.forEach(r=>r(t.visible)))}),Qe.size!==0&&(wp=window.requestAnimationFrame(Tp))};function Ep(t,e){return{observe(){let n=Qe.size===0;Qe.has(t)?Qe.get(t).callbacks.push(e):Qe.set(t,{visible:void 0,callbacks:[e]}),n&&Tp()},unobserve(){let n=Qe.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||Qe.delete(t),Qe.size||cancelAnimationFrame(wp)}}}}var Yi=["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 ea(t,e,n){return n.forEach(o=>{e.style[o]=t[o]})}function Un(t){return parseFloat(t)}function Tr(t){return Math.round(t*1e6)}function kp(t){return t/1e6}function ta(t,e,n){if(t.boxSizing==="content-box")return;let{clientWidth:o}=e,s=Un(t.width),r=Un(t.borderLeftWidth),i=Un(t.borderRightWidth),a=Un(t.paddingRight),d=kp(Tr(s)-Tr(r)-Tr(i)),l=kp(Tr(o));if(d-l>2){let c=d-l;n.style.paddingRight=`${a+c}px`}}function _o(t,e={}){var c,p;let n=e.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=e.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Gt(n);let o=window.getComputedStyle(t),s=!0,r=()=>{n.scrollTop=t.scrollTop};ea(o,n,Yi),ta(o,t,n),e.mirrorOverflow&&(n.style.overflow="hidden",t.addEventListener("scroll",r));let i=Ep(t,()=>{ea(o,n,Yi),ta(o,t,n),r(),setTimeout(r,0)}),a,d=!0,l=Ji(t,u=>{if(u===null){e.onRemove&&e.onRemove(),n.remove();return}if(!d&&e.onMoveStart&&(Promise.resolve().then(()=>e.onMoveStart()),d=!0),clearTimeout(a),a=setTimeout(()=>{e.onMoveEnd&&e.onMoveEnd(),d=!1},200),u.height===0&&u.width===0){if(s===!0)return;e.onHide&&e.onHide(),n.style.display="none",s=!0;return}if(ea(o,n,Yi),ta(o,t,n),r(),n.style.top=`${u.top}px`,n.style.left=`${u.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let m=e.closestScrollElement.getBoundingClientRect(),y=window.getComputedStyle(e.closestScrollElement),f=Un(y.borderTopWidth),v=Un(y.borderBottomWidth),C=m.top+f-u.top,k=u.top+u.height+-(m.top+m.height-v);n.style.clipPath=`inset(${C}px 0px ${k}px 0px)`}s&&(n.style.display="block",e.onShow&&e.onShow(),s=!1)});return e.appendTo?e.appendTo.appendChild(n):(p=t.parentElement)==null||p.appendChild(n),l.observe(),i.observe(),[n,()=>{t.removeEventListener("scroll",r),l.unobserve(),i.unobserve()}]}var Rp=(t,e)=>({value(){try{let n=sessionStorage.getItem(`dd-${t}`);if(!n)return e;try{return JSON.parse(n)}catch(o){return e}}catch(n){return e}},update(n){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(n))}catch(o){E.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function yh(t){return t.offsetParent!==null}function Ip(t){if(!yh(t))return!1;let e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}function Er(t,e,n=100){let o=Ip(t);e({isVisible:o});let s=setInterval(()=>{let r=Ip(t);r!==o&&(o=r,e({isVisible:o}))},n);return()=>{clearTimeout(s)}}var G=require("react/jsx-runtime");var Lp=Rp("showTabHint",!0),Vn=class Vn{constructor({deepdeskUrl:e,version:n=Vn.version||"unknown",locale:o="en-US",token:s,fetch:r,productName:i,createCustomChannel:a}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let d=e.replace(/\/api$/,"");this.deepdeskApi=new mt(d,{token:s,fetch:r}),this.version=n,this.instanceId=Vn.count++;let l={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[pp({broadcast:(c,p,u)=>{this.broadcastEvents.send(c,p,u)},emit:(c,p)=>this.emit(c,p),handleAfterSendMessage:c=>this.handleAfterSendMessage(c),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:c=>this.logSendMessage(c),onUpdateShowTabHint:c=>Lp.update(c),sendEvent:(c,p)=>this.deepdeskApi.sendEvent(c,p)})]};this.store=up(l),this.broadcastEvents=new Zu({debug:!0,deepdeskUrl:d,eventMap:Tl(this.store),createCustomChannel:a}),this.store.dispatch(Co(Lp.value())),this.store.dispatch(Qo({locale:o,adminUrl:d,productName:i}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var e;return(e=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?e: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?(E.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(E.warn("Profile has not been loaded (yet)"),!0):(E.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(cn(null)),this.store.dispatch(Xe()),new Promise(e=>{let n=this.store.subscribe(()=>{let o=this.store.getState();se(o)&&Fa(o)!=="loading"&&(n(),e())});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return h(this,null,function*(){return(yield this.store.dispatch(Xe())).payload})}isConversationSupported(e,n){return h(this,null,function*(){return(yield this.store.dispatch(Nr({sessionId:e,options:n}))).payload})}createConversation(e){return h(this,null,function*(){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(yield this.store.dispatch(Zo(e))).payload})}getConversationBySessionId(e,n){return h(this,null,function*(){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(yield this.store.dispatch(Xo({sessionId:e,options:n}))).payload})}upsertConversation(e){return h(this,null,function*(){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(yield this.store.dispatch(Or(e))).payload})}postMessages(e){return h(this,null,function*(){return(yield this.store.dispatch(Yo(e))).payload})}updateConversation(e){return h(this,null,function*(){return(yield this.store.dispatch(Jo(e))).payload})}resetConversation(){this.store.dispatch(W()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(e){this.store.dispatch(Qo(e))}setVisitorInfo(e){this.store.dispatch(gl(e))}setCustomData(e){this.store.dispatch(fl(e))}setAgentInfo(e,n){return h(this,null,function*(){yield this.store.dispatch(Gn(g(g({},e),n)))})}setAgentSettings(e){return h(this,null,function*(){yield this.store.dispatch(_r(e))})}getAgentSettings(){return h(this,null,function*(){return(yield this.store.dispatch(Fr())).payload})}refresh(){return h(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(os({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let e=[];return this.store.dispatch(Ks()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})})}notifyExternalSuggestion(e){this.store.dispatch(Le(e))}evaluateRule(s){return h(this,arguments,function*(e,n={},o=au){return(yield this.store.dispatch(Jt({label:e,params:n,options:o}))).payload.cues})}evaluateAssistant(e,n){return h(this,null,function*(){let c=n||{},{input:o={},transcript:s,showCuesInWidget:r=!0,includeTags:i,expectFormat:a}=c,d=O(c,["input","transcript","showCuesInWidget","includeTags","expectFormat"]);Object.assign(o,d);let l=yield this.store.dispatch(Ye({assistantCode:e,expectFormat:a||"json-schema:cues",transcript:s,includeTags:i,input:o,skipState:!r}));if(l.error)throw new Error(l.error.message);return l.payload})}evaluateConversationAssistant(e,n){return h(this,null,function*(){yield this.loadProfileConfig();let o={accepted:"conversationAcceptedAssistant","new-message":"conversationNewMessageAssistant",ended:"conversationEndedAssistant"},s=this.state.profile.data[o[e]];if(!s){E.warn(`No assistant set in profile for conversation event "${e}"`);return}yield this.evaluateAssistant(s,g({transcript:"stored-transcript",includeTags:!0},n))})}getSummary(){return h(this,null,function*(){var n;if(!this.hasConversation())return E.warn("No conversation to create summary for."),null;(n=this.state.profile.data)!=null&&n.summarizerAssistantNew||E.warn("No profile loaded yet, or no summarizer assistant set in profile");let e=yield this.store.dispatch(Ue({}));if(e.error)throw new Error(e.error.message);return e.payload})}handleKeyDown(e){let{overlayCollapsed:n,openOverlayWhenTyping:o}=this.state.ui,{textSuggestions:s,selectedSuggestionIndex:r,selection:i}=this.state.input,{inlineSuggestions:a,showTextSuggestions:d}=this.state.settings,l=a?"below":"above",c=s.length>0;if(!We(this.state)||(this.store.dispatch(nl(Dr(e))),e.key!=="Tab"&&!d))return;let p=()=>{n||!c||i&&(e.shiftKey||(this.store.dispatch(rl()),e.preventDefault()))},u=()=>{n||!c||a&&r<=0||i&&(e.shiftKey||(this.store.dispatch(il()),e.preventDefault()))};switch(e.key){case"ArrowUp":l==="below"?u():p();break;case"ArrowDown":{l==="below"?p():u();break}case"Escape":{n||(this.store.dispatch(ns(-1)),this.store.dispatch(Tt({collapse:!0})),this.store.dispatch(dc(!0)),e.preventDefault());break}case"Tab":{e.preventDefault();let m=mn(this.state);if(!m)return;this.store.dispatch(Co(!1)),this.store.dispatch(Le({text:m.text,suggestion:m,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.state.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let m=mn(this.state);if(!m)return;this.store.dispatch(Le({text:m.text,suggestion:m,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.state.settings.inlineSuggestions||e.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let m=mn(this.state);if(!m)return;this.store.dispatch(Le({text:m.text,suggestion:m,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),e.preventDefault();break}default:}n&&o&&this.store.dispatch(Tt({collapse:!1}))}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(vt([]))}handlingTimeStart(){this.state.handlingTime.startTime||(E.info("Start handling time"),this.store.dispatch(np()))}handlingTimeStop(){this.state.handlingTime.startTime&&(E.info("Stop handling time"),this.store.dispatch(vr()))}logSendMessage(e){let n=fp("input",this.state,{version:this.version});n&&(e&&(Object.assign(n,{text:e}),Object.assign(n,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n))}logHandlingTime(){let e=gp(this.state,{version:this.version});e&&(this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(op()))}notifySubmit(e={}){var n;this.shouldAbort()||(this.store.dispatch(Ot((n=e.text)!=null?n:this.state.input.text)),this.store.dispatch(ll()))}emit(e,n){let o=this.eventListeners[e];o&&o.forEach(s=>{try{s(n)}catch(r){E.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),E.error(r)}})}on(e,n){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n),()=>{this.off(e,n)}}off(e,n){if(!e&&!n){this.eventListeners={};return}let o;this.eventListeners[e]&&(o=this.eventListeners[e].indexOf(n),o>-1&&this.eventListeners[e].splice(o,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}setPlatformVariables(e){this.store.dispatch(hl(e))}whenConversationLoaded(e){let n=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&n();let o=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==o&&(o=this.hasConversation(),o&&n())})}overlayContainerFactory(e,n,o,s){let[r,i]=_o(n,o);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{(0,Re.unmountComponentAtNode)(r),i(),r.remove()}),r}createInlineContainer(e,n){var a;let o=document.createElement("div");o.style.position="absolute",o.style.top="0px",o.style.left="0px",o.style.height="0px",o.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",o.appendChild(s);let r=(a=e.ownerDocument.defaultView)==null?void 0:a.frameElement,i=r?r.ownerDocument.defaultView:null;if(r&&(i===window||(i==null?void 0:i.parent)===window)){let[d,l]=_o(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});d.dataset.testid=n,d.style.zIndex="2",d.appendChild(o),this.unmountHandlers.push(()=>{(0,Re.unmountComponentAtNode)(s),l()})}else document.body.appendChild(o);return s}createContainer(e,n=document.body){let o=window.getComputedStyle(n),s=document.createElement("div");return Gt(s),s.dataset.testid=e,s.style.color=o.color,s.style.fontSize=o.fontSize,s.style.fontFamily=o.fontFamily,s.style.fontVariant=o.fontVariant,s.setAttribute("translate","no"),n.appendChild(s),this.unmountHandlers.push(()=>{(0,Re.unmountComponentAtNode)(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,n),E.info(`Stored analytics for ${this.conversationId()}`)}catch(e){}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(e);if(!n)return;let o=JSON.parse(n);o.text.trim()===this.state.input.text.trim()?(E.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(al(o.metrics))):E.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch(e){}}mount(e,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Cr(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:o={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:d,showSuggestionsBeforePattern:l,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:u,insertLink:m,inputMediator:y,closestScrollSelector:f,appendOverlayTo:v,inlineSuggestions:C,floatingMenu:k}=n;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:d,showSuggestionsBeforePattern:l,showSuggestionsAfterPattern:c,showTextSuggestions:i,insertLink:m,isEmbedded:p,inlineSuggestions:C,floatingMenu:!!k}),n.automaticHandlingTime&&this.setupHandlingTime(e),Gt(e),this.inputMediator=y||(Xt(e)?new tn(e):new en(e)),this.inputMediator.on("change",({plainText:w,rawHTML:N})=>{this.store.dispatch(os({text:w,html:N}))}),this.inputMediator.on("keyup",w=>{this.store.dispatch(ol(Dr(w)))}),this.inputMediator.on("keydown",w=>{this.handleKeyDown(w)}),this.inputMediator.on("paste",({pastedText:w,selectionText:N})=>{this.store.dispatch(sl({text:w,selectionText:N}))}),this.inputMediator.on("cut",({selectionText:w})=>{this.store.dispatch(tl(w))});let S;this.inputMediator.on("selection",w=>{clearTimeout(S),w===null?S=setTimeout(()=>{w!==null&&this.store.dispatch(ss(w))},500):this.store.dispatch(ss(w))}),this.inputMediator.on("disabled",()=>{var w;(w=this.inputMediator)==null||w.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{u&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(zs(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(zs(!0))});let I=f&&hp(e,f)||void 0;if(C){let{customStyles:w,appendOverlayTo:N}=n,M=this.createInlineContainer(e,"deepdesk-caret");(0,Re.render)((0,G.jsx)(Zt,{store:this.store,customStyles:w,children:(0,G.jsx)(_t,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(vc,{})})}),M),this.inputMediator.on("caretposition",ne=>{ne?(M.style.display="block",M.style.top=`${ne.top}px`,M.style.left=`${ne.left}px`):M.style.display="none"});let B=this.overlayContainerFactory("floating-menu",I||e,{appendTo:typeof k=="object"&&"appendOverlayTo"in k?k.appendOverlayTo:N},w==null?void 0:w.floatingMenuRootNode);(0,Re.render)((0,G.jsx)(Zt,{store:this.store,customStyles:w,children:(0,G.jsx)(_t,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(rc,{onLogIn:()=>this.loginViaPopup().catch(ne=>E.warn(ne.message))})})}),B)}else{let w=this.overlayContainerFactory("deepdesk-tab-completion",I||e,{appendTo:v,closestScrollElement:I,mirrorOverflow:!0,onRemove:()=>this.unmount()},o==null?void 0:o.rootNode),N=this.overlayContainerFactory("deepdesk-suggestions-overlay",I||e,{appendTo:v},o==null?void 0:o.suggestionsRootNode);(0,Re.render)((0,G.jsx)(Zt,{store:this.store,customStyles:o,children:(0,G.jsx)(_t,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(ou,{inputElement:e})})}),w),(0,Re.render)((0,G.jsx)(Zt,{store:this.store,customStyles:o,children:(0,G.jsx)(_t,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(Lc,{onLogIn:()=>this.loginViaPopup().catch(M=>E.warn(M.message))})})}),N)}(0,Re.render)((0,G.jsx)(Zt,{store:this.store,customStyles:o,children:(0,G.jsx)(_t,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(Jd,{})})}),this.createContainer("deepdesk-overlays")),this.store.dispatch(os({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(ss(this.inputMediator.getSelection())),this.store.dispatch(zs(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var w;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((w=this.state.conversation.current)==null?void 0:w.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,n={}){if(this.widgetRoot&&E.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:o,showImages:s,isEmbedded:r}=n;this.widgetRoot=e,this.configure({showImages:s,isEmbedded:r}),(0,Re.render)((0,G.jsx)(Zt,{store:this.store,customStyles:o,children:(0,G.jsx)(_t,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(Wu,{onLogIn:()=>this.loginViaPopup().catch(i=>E.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Re.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let n=Er(e,({isVisible:o})=>{o?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){yp(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>h(this,null,function*(){yield this.store.dispatch(lo());let e=Ht(this.state);e&&(yield this.store.dispatch(oo()),this.store.dispatch(Qo({showSearch:e.search,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:!!e.summarizerAssistantNew||e.summarizer,showKnowledgeSearch:!!e.knowledgeAssistantNew||!!e.knowledgeAssistant,recommendTextSuggestions:e.recommendTextSuggestions})))})),this.loadProfileConfigPromise)}loginViaPopup(e){return h(this,null,function*(){return new Promise((n,o)=>{let s=new MessageChannel,r=s.port1,i=this.state.settings.adminUrl,a=new URL(e!=null&&e.url?e==null?void 0:e.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let d=!1,l=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(u)};r.onmessage=m=>h(this,null,function*(){var y,f;if((y=m.data)!=null&&y.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((f=m.data)==null?void 0:f.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Zn),d=!0,s.port1.close(),n()}catch(v){console.error(v),o(v)}finally{d=!0,l()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&o(new Error("Popup blocked by browser"));let p=m=>h(this,null,function*(){var y;if(m.origin===a.origin)switch((y=m.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let f=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(f,a.origin,[s.port2])}catch(f){E.error("Error posting message to popup",f),o(f)}break}case"deepdesk-popup-error":{l(),m.data.message==="Timeout"&&E.warn("Popup timed out. Check if the account's platform url is configured correctly."),o(new Error(m.data.message));break}}});window.addEventListener("message",p);let u=setInterval(()=>{c&&!c.closed||(l(),d||o(new Error("Popup closed by user")))},200);this.unmountHandlers.push(l)})})}translateMessages(e){return this.deepdeskApi.translateMessages(e)}checkForTrialMode(e){return h(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(E.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(e)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:o}=n;E.info(o),this.shouldRender=!1}})}refreshWidgetSuggestions(){return h(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let n=co(this.state);try{n.forEach(({type:o})=>{o==="entities"?this.store.dispatch(Ne()):Go.includes(o)||this.store.dispatch(Oe(o))})}catch(o){this.handleError(o)}})}};Vn.version="14.3.1-beta.8",Vn.count=0;var Fo=Vn;function vh(t){return h(this,null,function*(){var s,r,i;let n=yield((s=t.fetch)!=null?s:window.fetch)(t.url),o=yield n.blob();return new File([o],t.name,{type:(i=(r=t.mimeType)!=null?r:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function Pp(t,e){return h(this,null,function*(){let n=yield vh(e),o=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[n]}),t.dispatchEvent(o)}finally{Object.hasOwn(t,"files")&&delete t.files}})}function Ap(t,e,n){return h(this,null,function*(){yield new mt(t).authenticateWithKey(e,n)})}function Mp(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function Np(o,s){return h(this,arguments,function*(t,e,n={}){var p,u;let{value:r}=t,{start:i,end:a}=(p=n.replace)!=null?p:{start:0,end:r.length},d=`${r.slice(0,i)}${e}${r.slice(a)}`,l=(u=n.selectionAfter)!=null?u:{start:i+e.length,end:i+e.length},c=()=>{if(n.setValue)return n.setValue(d);t.value=d};return Promise.resolve(c()).then(()=>{t.selectionStart=l.start,t.selectionEnd=l.end,t.blur(),t.focus()})})}function Op(o,s){return h(this,arguments,function*(t,e,n={}){let r=n.replace?Rt(t,n.replace.start,n.replace.end):Hn(t),i,a=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),i=document.createElement("span"),r.insertNode(i),n.insertBRs!==!1?e.split(`
10
+ `);let y=u?o:0,f=m?Math.min(r,c.childNodes.length):c.childNodes.length;for(let v=y;v<f&&(l(c.childNodes[v]),a!==2);v++);break}default:break}m&&(a=2)}return l(t),d}var qu=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(qu||{}),pt=class{constructor(e){this.element=e;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(e,n){let o=s=>{n(s)};this.element.addEventListener(e,o),this.disposeHandlers.push(()=>{this.element.removeEventListener(e,o)})}removeEventListener(e,n){this.element.removeEventListener(e,n)}handleInteraction(){let e=this.getText(),n=this.getHTML(),o=this.getSelection(),s=this.cachedCaretPosition===null;if(!this.isActive||(e===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),e!==this.cachedText?(this.cachedText=e,this.cachedHTML=n,s=!0,this.emit("change",{plainText:e,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,s=!0,this.emit("change",{plainText:e,rawHTML:n})),(o.start!==this.cachedSelection.start||o.end!==this.cachedSelection.end)&&(this.cachedSelection=o,s=!0,this.emit("selection",o)),!s))return;let r=this.getCaretPosition();yt(r,this.cachedCaretPosition)||(this.cachedCaretPosition=r,this.emit("caretposition",r))}handleClick(){this.handleInteraction()}handleFocus(){let e=!this.isFocused;this.isFocused=!0,e&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let e=this.isFocused;this.isFocused=!1,e&&this.emit("blur")}handleKeyDown(e){let{key:n,ctrlKey:o,metaKey:s}=e;this.isPossibleClearInputAction=Object.values(qu).includes(n)||n.toLowerCase()==="z"&&(o||s),this.emit("keydown",e)}handleKeyUp(e){this.handleInteraction(),this.emit("keyup",e)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){var o,s;let n=((o=e.clipboardData)==null?void 0:o.getData("text"))||((s=e.clipboardData)==null?void 0:s.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 e=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});e.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{e.disconnect()})}focus(){this.element.focus()}emit(e,...n){this.isDisposed||this.eventListeners[e]&&this.eventListeners[e].forEach(o=>{o(...n)})}on(e,n){this.isDisposed||(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n))}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};function $u(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var en=class extends pt{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Do(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let o="getSelection"in n?n.getSelection():window.getSelection();if(!o)return null;let s="getComposedRanges"in o&&n instanceof ShadowRoot?(i=o.getComposedRanges(n))==null?void 0:i[0]:o.rangeCount>0?o.getRangeAt(0):null;if(!s)return null;let r=this.element.ownerDocument.createRange();return r.setStart(s==null?void 0:s.startContainer,s==null?void 0:s.startOffset),r.setEnd(s==null?void 0:s.endContainer,s==null?void 0:s.endOffset),!r||!this.element.contains(r.startContainer)||!this.element.contains(r.endContainer)?null:r}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let o=n.getBoundingClientRect();return!$u(o)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=n.getBoundingClientRect(),n.deleteContents(),!$u(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let n=this.getRange();if(n)return Oo(this.element,n);let o=this.lastKnownSelection;if(o&&ju(this.element,o.start,o.end))return o;let s=Hn(this.element);return s.collapse(!1),Oo(this.element,s)}getSelectedText(){let{start:n,end:o}=this.getSelection();return Do(this.element,Rt(this.element,n,o))}listen(){super.listen();let n=new MutationObserver(r=>{var i,a;r.length===2&&r[0].addedNodes.length===1&&((i=r[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=r[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 o=this.element.isContentEditable,s=new MutationObserver(()=>{this.element.isContentEditable!==o&&(o=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});s.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>s.disconnect())}};var oh=["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 Gu(t,e){let n="mozInnerScreenX"in window,o=document.createElement("div");o.id="input-textarea-caret-position-mirror-div";let s=o.style,r=window.getComputedStyle(t),i=t.ownerDocument.body;s.whiteSpace="pre-wrap",s.wordWrap="break-word",s.position="absolute",s.visibility="hidden",oh.forEach(function(c){s[c]=r[c]}),n?t.scrollHeight>parseInt(r.height)&&(s.overflowY="scroll"):s.overflow="hidden",o.textContent=t.value.substring(0,e);let a=document.createElement("span");a.textContent=t.value.substring(e)||".",o.appendChild(a),i.appendChild(o);let d=t.getBoundingClientRect(),l={top:d.top-t.scrollTop+a.offsetTop+parseInt(r.borderTopWidth)+a.offsetHeight,left:d.left-t.scrollLeft+a.offsetLeft+parseInt(r.borderLeftWidth)};return i.removeChild(o),l}var tn=class extends pt{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:o}=this.element;return{start:n,end:o}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return Gu(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 r;return(r=n==null?void 0:n.get)==null?void 0:r.call(this.element)},set:r=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,r),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let o=this.element.disabled,s=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});s.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>s.disconnect())}};function Qu(t,e,n){let o=`deepdesk-iframe-${t}`,s=document.getElementById(o);if(s)return s;let r=document.createElement("iframe"),i=new URL(e);return Object.entries(n).forEach(([a,d])=>{i.searchParams.append(a,d)}),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=o,r.title=`iframe-${t}`,r.src=i.toString(),window.document.body.appendChild(r),r}function sh(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch(e){return t}}var Wi=class{constructor(e){this.name=e;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(e)}onMessage(e){this.broadcastChannel.addEventListener("message",e),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",e)})}postMessage(e){this.broadcastChannel.postMessage(JSON.stringify(e))}close(){this.disposeHandlers.forEach(e=>e()),this.broadcastChannel.close()}},ji=class{constructor(e,n,o){this.name=e;this.targetOrigin=n;this.options=o;this.disposeHandlers=[];this.iframe=Qu(e,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(e),this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(n=>n()),(e=this.iframe)==null||e.remove()}},qi=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(e){this.sessionId!==e&&(this.cleanup(),E.info("Set sessionId",e),this.sessionId=e,this.channel=this.createChannel(e))}createChannel(e){let n=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new ji(e,this.deepdeskUrl,{debug:!0}):new Wi(e),o=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=sh(s.data);typeof r!="object"||r.type!=="event"||r.channel!==e||(E.info("Received broadcast event",this.sessionId,s),(a=(i=this.eventMap)[r.name])==null||a.call(i,r.payload))};return n.onMessage(o),n}send(e,n,o){var i,a;E.info("Broadcast event",{sessionId:this.sessionId,name:e,payload:n});let s={type:"event",name:e,payload:n};o!==!1&&((a=(i=this.eventMap)[e])==null||a.call(i,n));let r=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;r==null||r.postMessage(b(g({},s),{channel:this.sessionId}))}cleanup(e=!1){var n,o;(n=this.channel)==null||n.close(),delete this.channel,e&&((o=this.defaultChannel)==null||o.close(),delete this.defaultChannel)}},Zu=qi;function rh(t){return t.replace(/(_\w)/g,e=>e[1].toUpperCase())}function H(t){return Array.isArray(t)?t.map(H):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>b(g({},e),{[rh(n)]:H(t[n])}),{}):t}function ih(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Y(t){return Array.isArray(t)?t.map(Y):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>b(g({},e),{[ih(n)]:Y(t[n])}),{}):t}var Kn=class extends Error{constructor(n,o){super(n);this.body=o;this.name="CustomError"}};var $i=t=>new Promise(e=>{setTimeout(e,t)});var Bn=class extends Kn{constructor(){super(...arguments);this.name="ClientError"}},Qi=class extends Kn{constructor(){super(...arguments);this.name="ServerError"}},Gi=new Map;function ah(t){return h(this,null,function*(){if(t.status===204)return t.text().catch(()=>{}),null;let e=t.headers.get("content-type");if(e&&e.includes("application/json"))return t.json();let n=yield t.text();return n===""?null:(E.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var It=class It{constructor(e="",n={}){this.baseUrl=e;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,n={}){return new Promise((o,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,d=n.method===void 0||n.method.toLowerCase()==="get",N=n,{useCache:l=!1,abortLatest:c=!1,attempts:p=1,retryDelay:u=500,refreshTokenOn401:m=!0,retryOnError:y=M=>M instanceof TypeError,retryOnResponse:f=M=>M.status>=500,version:v=null}=N,C=O(N,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(l)if(d){if(Gi.has(i)){o(Gi.get(i));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let k=b(g({credentials:"include"},C),{headers:g({Accept:"application/json","Content-Type":"application/json"},C.headers)});!d&&this.csrfToken&&(k.headers=b(g({},k.headers),{"X-CSRFToken":this.csrfToken})),typeof v=="string"&&(k.headers=b(g({},k.headers),{"X-Deepdesk-API-Version":v}));let S=p,I=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let w=()=>h(this,null,function*(){return S--,a(i,k).then(M=>h(this,null,function*(){return f(M)&&!r.isAborted&&S>0?(yield $i(u),w()):M.status===401&&m===!0&&I===!1?(I=!0,yield this.refreshToken(),w()):M})).catch(M=>h(this,null,function*(){if(y(M)&&!r.isAborted&&S>0)return yield $i(u),w();throw M}))});w().then(M=>h(this,null,function*(){let B=yield ah(M);if(delete this.latestRequestByUrl[i],M.status>=500){s(new Qi("Server Error",B));return}else if(M.status===401){s(new Bn("Unauthorized",B));return}else if(M.status===403){s(new Bn("Forbidden",B));return}else if(M.status===404){s(new Bn("Not Found",B));return}else if(M.status>=400){s(new Bn("Bad Request",B));return}l&&Gi.set(i,B),o(B)})).catch(M=>{s(M)})})}validateToken(){return h(this,null,function*(){let{has_valid_access_token:e}=yield this.get("/auth/validate");if(!e)try{yield this.refreshToken()}catch(o){return!1}let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/");return!!n})}refreshToken(){return It.refreshingToken||(It.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{It.refreshingToken=null},1e3*60)})),It.refreshingToken}get(e,n){return this.request(e,n)}post(e,n,o){return this.request(e,g({method:"POST",body:JSON.stringify(n)},o))}patch(e,n,o){return this.request(e,g({method:"PATCH",body:JSON.stringify(n)},o))}put(e,n,o){return this.request(e,g({method:"PUT",body:JSON.stringify(n)},o))}delete(e,n){return this.request(e,g({method:"DELETE"},n))}};It.refreshingToken=null;var nn=It;var Xu;(e=>{let t;(i=>(i.SEND_MESSAGE="Send Message",i.HANDLING_TIME="Handling Time",i.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",i.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||(e.EventType={}))})(Xu||(Xu={}));function yr(t){return b(g({},H(t)),{tags:t.tags})}var on=class on{constructor(e,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new nn(e,{fetch:n.fetch}),this.client.patchFetch(o=>(s,r)=>h(this,null,function*(){let i=yield o(s,r);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return h(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=yield this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(on.exchangeTokenPromise||(on.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),on.exchangeTokenPromise):Promise.resolve()})}createConversation(e){return h(this,null,function*(){yield this.preflight(),E.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let n=yield this.client.post("/api/conversations",b(g({},Y(e)),{tags:e.tags}),{version:"v2"});return yr(n)})}getMe(){return h(this,null,function*(){let e=yield this.client.get("/apis/admin/session/me/");return H(e)})}postIdentity(e){return h(this,null,function*(){yield this.client.post("/apis/admin/session/me/identities/",Y(e))})}patchMe(e){return h(this,null,function*(){let n=yield this.client.patch("/apis/admin/session/me/",Y(e));return H(n)})}getProfile(e){return h(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${e}/`,{useCache:!0});return H(n)})}getKnowledgeAssistant(e){return h(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{useCache:!0});return H(n)})}getContentTypes(){return h(this,null,function*(){let e=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return H(e)})}getAccount(){return h(this,null,function*(){let e=yield this.client.get("/apis/admin/account/",{useCache:!0});return H(e)})}getPlatformConfig(e){return h(this,null,function*(){let n=e!==void 0?`/platform/config/${e}/`:"/platform/config/",{config:o}=yield this.client.get(n,{useCache:!0});return H(o)})}checkUserExists(e){return h(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${e}`,{version:"v1"});return n})}getConversationBySessionId(o){return h(this,arguments,function*(e,n={}){yield this.preflight(),E.info(`Getting conversation for session ${e}`);let{attempts:s=1,retryDelay:r=1e3}=n,i=yield this.client.get(`/api/conversations/by_session_id/${e}`,{attempts:s,retryDelay:r,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return E.info(`Successfully retrieved conversation ${i.id} for session ${e}`),yr(i)})}isConversationSupported(o){return h(this,arguments,function*(e,n={}){E.info(`Check if conversation for session ${e} is supported`);let{attempts:s=1,retryDelay:r=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${e}/active_profile`,{attempts:s,retryDelay:r,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(e,n){return h(this,null,function*(){let o=Y(n);n.tags&&(o.tags=n.tags);let s=yield this.client.put(`/api/conversations/${e}`,o,{version:"v2"});return yr(s)})}postMessages(e,n){return h(this,null,function*(){return(yield this.client.post(`/api/conversations/${e}/messages`,n.map(s=>b(g({},Y(s)),{tags:s.tags})),{version:"v2"})).map(s=>yr(s))})}sendEvent(e,n){return h(this,null,function*(){let i=n,{data:o}=i,s=O(i,["data"]),r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[d,l])=>b(g({},a),{[d]:l}),{});return this.client.post("/api/events",Y(b(g(g({},r),s),{data:o,name:e})),{version:"v2"})})}sendEventV1(e,n){return h(this,null,function*(){let o=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[r,i])=>b(g({},s),{[r]:i}),{});return this.client.post("/api/events",{event:e,data:Y(g(g({},n),o))},{version:"v1"})})}getEntities(e){return h(this,null,function*(){return(yield this.client.post("/api/entities",{messages:e.filter(o=>o.text)},{version:"v1"})).entities})}getTemporaryExchangeToken(){return h(this,null,function*(){return(yield this.client.get("/auth/exchange-token")).jwt})}exchangeTokenForAccessCookie(e){return h(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:e}).catch(n=>{throw E.warn(`Invalid token '${e}'`),n})})}authenticateWithKey(e,n){return h(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Y(n),{refreshTokenOn401:!1,headers:{apikey:e}})})}getTextSuggestions(s){return h(this,arguments,function*(e,n={},o){return o==="sticky-messages"?this.getPinnedMessages(e):(yield this.client.post(`/api/conversations/${e}/recommend/${o}`,Y(n),{abortLatest:!0,version:"v1"})).map(i=>b(g({},H(i)),{text:i.text||i.url||i.message,source:o,type:o})).filter((i,a,d)=>a===d.findIndex(l=>l.text===i.text))})}isLoggedIn(){return h(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(e,n){return h(this,null,function*(){return(yield this.client.post(`/api/conversations/${e}/autocomplete`,Y(n),{abortLatest:!0,version:"v1"})).map(s=>({score:1,source:s.source,sourceText:s.source_text,text:s.label,trainingJobs:s.training_jobs,searchKeywords:s.search_keywords,type:s.source})).filter((s,r,i)=>r===i.findIndex(a=>a.text===s.text))})}getPinnedMessages(e){return h(this,null,function*(){let n=yield this.client.get(`/api/conversations/${e}/sticky-messages`,{abortLatest:!0,version:"v1"});return H(n).map(o=>b(g({},o),{text:o.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(e){return h(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",Y(e),{abortLatest:!0,version:"v1"});return H(n)})}search(e){return h(this,null,function*(){let n=yield this.client.post(`/api/profiles/${e.profile}/search`,Y(e),{version:"v2"});return H(n)})}knowledgeAssist(r,i,a){return h(this,arguments,function*(e,n,o,s={}){let d=yield this.client.post(`/api/knowledge-assist/assistants/${o}/search`,Y({question:e.question,doNotKnowAnswer:e.doNotKnowAnswer,customerInstruction:e.customerInstruction,chatHistory:n.map(l=>({question:l.question,answer:l.answer.answer})),agentId:s.agentId,conversationId:s.conversationId}),{version:"v2"});return H(d)})}requestLoginByEmail(e){return h(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:e});return H(n)})}requestPasswordlessToken(){return h(this,null,function*(){let e=yield this.client.get("/apis/admin/session/passwordless/request/");return H(e.token)})}getCsrfToken(){return h(this,null,function*(){let{token:e}=yield this.client.get("/apis/admin/session/csrf/");return e})}verifyLoginToken(e){return h(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:e});return H(n)})}evaluateRule(r,i,a){return h(this,arguments,function*(e,n,o,s={}){let d=new URLSearchParams;s.raiseForFailingConditions&&d.set("raise_for_failing_conditions","true");let l=yield this.client.post(`/api/conversations/${n}/rules/${e}/evaluate?${d.toString()}`,o,{version:"v2"});return l?H(l.cues):[]})}getSummary(o){return h(this,arguments,function*(e,n={}){let s=yield this.client.post("/api/summary",{conversation:{messages:e.filter(r=>r.text&&r.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return H(s)})}evaluateAssistant(e,n){return h(this,null,function*(){var a;let o=new URLSearchParams,{expectFormat:s="text"}=n||{};if(s.startsWith("json-schema:")){let d=s.replace("json-schema:","");o.append("expect_response_format","json-schema"),o.append("expect_response_format_schema",d)}else o.append("expect_response_format",s);n!=null&&n.externalConversationId&&o.append("external_conversation_id",n.externalConversationId);let r=n!=null&&n.threadId?`/api/v2/assistants/${e}/threads/${n==null?void 0:n.threadId}/evaluate?${o.toString()}`:`/api/v2/assistants/${e}/evaluate?${o.toString()}`,i=yield this.client.post(r,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return H(i.output)})}createAssistantThread(e){return h(this,null,function*(){let{assistantCode:n}=e,o=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return H(o)})}postMessageToAssistantThread(e){return h(this,null,function*(){let{assistantCode:n,threadId:o,message:s}=e,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/${o}/messages/`,{content:s,role:"user"});return H(r)})}getRules(){return h(this,null,function*(){let e=new URLSearchParams,n=yield this.client.get(`/apis/admin/rule-engine/rules/?${e.toString()}`,{useCache:!0});return H(n)})}translateMessages(e){return h(this,null,function*(){let n=yield this.client.post("/api/translate",Y(e),{version:"v2"});return H(n)})}handleDeepdeskVersionHeaders(e){e.headers.forEach((n,o)=>{let s=o.toLowerCase(),r=s.match(Aa);if(!n||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&E.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};on.exchangeTokenPromise=null;var mt=on;var br=require("@reduxjs/toolkit");var Yu=require("@reduxjs/toolkit");var Ju={startTime:null,stopTime:null},ep=t=>t.handlingTime,tp=(0,Yu.createSlice)({name:"handlingTime",initialState:Ju,reducers:{handlingTimeStart(t){if(t.startTime&&!t.stopTime)throw new Error("Timing already started");t.startTime=new Date,t.stopTime=null},handlingTimeStop(t){if(!t.startTime)throw new Error("Timing not started");t.stopTime=new Date},handlingTimeReset(t){t.startTime=null,t.stopTime=null}},extraReducers:t=>{t.addCase(W,()=>Ju)}}),{handlingTimeStart:np,handlingTimeStop:vr,handlingTimeReset:op}=tp.actions,sp=tp.reducer;var rp=(t={})=>{let e=g({onAuthError:cn(!1)},t);return n=>o=>s=>("error"in s&&s.error.message==="Unauthorized"&&n.dispatch(e.onAuthError),o(s))};var xr=require("@reduxjs/toolkit");var Sr={list:{keywordMatches:[]},fetchState:"idle"};var sn=(0,xr.createAsyncThunk)("styleSuggestions/getAll",(n,o)=>h(void 0,[n,o],function*({text:t},e){var d;let{deepdeskAPI:s}=e.extra,r=e.getState(),{showStyleSuggestions:i}=r.settings,a=(d=r.conversation.current)==null?void 0:d.profileCode;if(!i)return Sr.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return s.getStyleSuggestions({profileCode:a,message:t})})),lh=(0,xr.createSlice)({name:"styleSuggestions",initialState:Sr,reducers:{},extraReducers:t=>{t.addCase(sn.pending,e=>{e.fetchState="loading"}).addCase(sn.rejected,e=>{e.fetchState="error"}).addCase(sn.fulfilled,(e,n)=>{e.fetchState="done",yt(e.list,n.payload)||(e.list=n.payload)}).addCase(Ot,e=>{e.list=Sr.list}).addCase(W,()=>Sr)}}),ip=lh.reducer;var ap=(t={})=>{let e,n=!0,o=g({getStyleSuggestions:sn,debounce:500},t);return s=>r=>i=>{var m;let a=s.getState().input.text,d=r(i),l=s.getState();if(l.auth.isLoggedIn!==!0)return d;let{showStyleSuggestions:c}=l.settings;if(!((m=l.conversation.current)==null?void 0:m.id)||!c)return d;let{text:u}=l.input;return u===a&&!n||(clearTimeout(e),u==="")||(e=setTimeout(()=>{n=!1,s.dispatch(o.getStyleSuggestions({text:u}))},t.debounce)),d}};function dh(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var lp=(t={})=>{let e=g({getTextSuggestions:Oe,getAutocompleteSuggestions:xo,debounce:200,check:We},t),n;return o=>s=>r=>{var f;let{input:i}=o.getState(),a=s(r),d=o.getState();if(d.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:l,showTabCompletion:c}=d.settings,p=(f=d.conversation.current)==null?void 0:f.id,u=r.type===Ks.toString();if(!p||!l&&!c)return a;let{input:m}=d;return dh(m,i)&&!u||(clearTimeout(n),!e.check(d))||(n=setTimeout(()=>{let v=pn(d);v===""?o.dispatch(e.getTextSuggestions("default")):o.dispatch(e.getAutocompleteSuggestions(v))},u?0:e.debounce)),a}};var dp=sn.fulfilled.toString();function ch(t,e){let n=new Set([...e.keywordMatches.map(s=>s.keyword)]),o=[];return n.forEach(s=>{let r=t.keywordMatches.filter(d=>d.keyword===s),i=e.keywordMatches.filter(d=>d.keyword===s),a=i.length-r.length;a<=0||o.push(...i.slice(0,a))}),o}var cp=t=>e=>n=>o=>{var l;if(o.type!==dp){n(o);return}let s=e.getState().styleSuggestions.list;n(o);let r=e.getState(),i=r.styleSuggestions.list,a=(l=r.conversation)==null?void 0:l.current;if(s===i)return;let d=ch(s,i);o.type===dp&&d.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:d}})};var uh=(0,br.combineReducers)({assistants:Zl,auth:za,conversation:Qa,contentTypes:Jl,passwordlessToken:iu,entities:bd,knowledgeAssistant:jl,handlingTime:sp,info:yl,input:dl,settings:_a,profile:ed,search:wl,styleSuggestions:ip,ui:uc,rules:uu,textSuggestions:qd});function up(t){return(0,br.configureStore)({reducer:uh,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI}},serializableCheck:!1}),rp(),lp({debounce:200}),ap({debounce:500}),cp(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var ph=t=>{var e,n;return(n=(e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())!=null?n:"unknown"},mh=t=>e=>n=>o=>{var a,d,l,c,p,u,m;let s=e.getState(),r=Mr("inlineSuggestions")(s);switch(o.type){case cn.toString():{!o.payload&&t.emit("logout",void 0);break}case Ne.fulfilled.toString():o.payload.length>0&&t.sendEvent("entities found",{conversationId:(a=s.conversation.current)==null?void 0:a.id,data:{entities:o.payload}});break;case xe.toString():t.sendEvent(o.payload.name,{conversationId:((d=o.payload.options)==null?void 0:d.includeConversationData)&&((l=s.conversation.current)==null?void 0:l.id),data:o.payload.data});break;case Ot.toString():t.logSendMessage(o.payload);break;case Jt.fulfilled.toString():o.isBroadcasted||t.broadcast(Kr,o,!1),(c=o.payload.options)!=null&&c.shouldEmit&&t.emit("cues",o.payload.cues);break;case ks.toString():t.emit("call-to-action",{cue:o.payload});break;case Ye.fulfilled.toString():o.isBroadcasted||t.broadcast(Br,o,!1);break;default:break}let i=n(o);switch(o.type){case Ot.toString():t.handleAfterSendMessage(o.payload);break;case Co.toString():t.onUpdateShowTabHint(o.payload);break;case vr.toString():t.logHandlingTime();break;case"analytics/logEvent/fulfilled":{t.emit("event",o.meta.arg);break}case es.toString():{let{start:y,end:f}=s.input.selection;t.emit("replace",b(g({},o.payload),{replace:o.payload.replace==="selection"?{start:y,end:f}:{start:0,end:f}}));break}case Le.toString():{let{start:y,end:f}=s.input.selection;t.emit("select-suggestion",b(g({type:ph(o.payload.suggestion)},o.payload),{replace:o.payload.replace==="selection"?{start:y,end:f}:{start:0,end:f}})),r&&e.dispatch(vt([]));break}case ts.toString():t.emit("select-image",o.payload),t.sendEvent("Image attached",{conversationId:(p=s.conversation.current)==null?void 0:p.id,data:{path:o.payload.suggestion.image,title:o.payload.suggestion.title}});break;case vt.toString():{r&&o.payload.length>0&&e.dispatch(ns(0));break}case Ue.fulfilled.toString():{t.sendEvent("conversation summarized",{conversationId:(u=s.conversation.current)==null?void 0:u.id,data:{summary:o.payload,assistant:(m=e.getState().profile.data)==null?void 0:m.summarizerAssistantNew}});break}default:break}return i},pp=mh;var mp=require("@reduxjs/toolkit");function Zi(t){return t.toISOString().replace("T"," ").replace("Z","")}var gh=(t,e)=>e.version,gp=(0,mp.createSelector)([fn,Ke,ep,gh],(t,e,n,o)=>{if(!e)return E.warn("No conversationId for handling time metrics"),null;let{startTime:s,stopTime:r}=n;return!s||!r?(E.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:e,clientVersion:o,agentId:t==null?void 0:t.agentId,agentName:t==null?void 0:t.agentName,agentEmail:t==null?void 0:t.agentEmail,timeStart:Zi(s),timeStop:Zi(r)}});function fp(t,e,n){var B,ne,ye,D;let o=(B=e.conversation.current)==null?void 0:B.id;if(!o)return E.warn("No conversationId for send message metrics"),null;let{text:s,metrics:{numCharsTyped:r,numCharsPasted:i,numCharsCut:a,numCharsDeleted:d,numPaste:l,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:u,cuts:m,deletions:y,textSuggestions:f,offeredTextSuggestions:v}}=e[t],C=s.length,S=f.reduce((U,{text:Fe,searchTerm:ve})=>U+Fe.length-(ve?ve.length:0),0),I=c!=null?c:Date.now(),w=(Date.now()-I)/1e3+(p||0),N=r/w,M=f.reduce((U,{searchTerm:Fe})=>U+(Fe?Fe.length:0),0);return{conversationId:o,source:"agent",text:s,clientVersion:n.version,pastes:u,cuts:m,deletions:y,lenTextTyped:r+M,lenTextTotal:C,lenTextAssisted:S,lenTextPasted:i,lenTextCut:a,lenTextDeleted:d,timeTotalSeconds:w,charsPerSecond:N,numPastes:l,textSuggestionsV2:f,suggestionsCounters:[{source:"gpt",countOffered:v.filter(U=>U.source==="gpt").length}],agentId:(ne=e.info.agentInfo)==null?void 0:ne.agentId,agentName:(ye=e.info.agentInfo)==null?void 0:ye.agentName,agentEmail:(D=e.info.agentInfo)==null?void 0:D.agentEmail}}function Xi(t,e){var r;let n=t.closest(e);if(n)return n;let o=t.getRootNode().host;if(o instanceof HTMLElement)return Xi(o,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?Xi(s,e):null}function hp(t,e){return Xi(t,e)}function yp(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function fh(t){return typeof t=="object"&&t!==null&&"tagName"in t}function Cr(t){return fh(t)&&(Xt(t)||Qs(t))}var Sp,Ge=new Map,hh=["bottom","height","left","right","top","width"],vp=(t,e)=>!t&&!e?!1:t&&!e||!t&&e?!0:hh.some(n=>t[n]!==e[n]);function xp(t){var n,o,s;if(t.ownerDocument===document)return[];let e=(s=(o=(n=t.ownerDocument)==null?void 0:n.defaultView)==null?void 0:o.frameElement)!=null?s:null;return e?[e,...xp(e)]:[]}function bp(t,e){return!t||!e?null:b(g({},t),{top:t.top+e.top,left:t.left+e.left})}var wr=!1,Cp=()=>{wr=!0;let t=[];if(Ge.forEach((e,n)=>{if(!n.isConnected){e.rect=null,t.push(e),Ge.delete(n);return}let o=n.getBoundingClientRect();vp(o,e.rect)&&(e.rect=o,t.push(e))}),t.forEach(e=>{let n=e.parentRects?e.parentRects.reduce(bp,e.rect):e.rect;vp(n,e.totalRect)&&e.callbacks.forEach(o=>o(n)),e.totalRect=n}),Ge.size===0){wr=!1;return}Sp=window.requestAnimationFrame(Cp)};function Ji(t,e){let n=xp(t),o=[],s=n.map((r,i)=>Ji(r,a=>{o[i]=a;let d=Ge.get(t);if(!d)return;let l=o.reduce(bp,d.rect);d.callbacks.forEach(c=>c(l))}));return{observe(r=!0){if(s.forEach(i=>i.observe(!1)),Ge.has(t)){let i=Ge.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else Ge.set(t,{rect:void 0,callbacks:[e],parentRects:o});r&&!wr&&Cp()},unobserve(){s.forEach(i=>i.unobserve());let r=Ge.get(t);if(r){let i=r.callbacks.indexOf(e);i>=0&&r.callbacks.splice(i,1),r.callbacks.length||Ge.delete(t),Ge.size||(cancelAnimationFrame(Sp),wr=!1)}}}}var wp,Qe=new Map,Tp=()=>{Qe.forEach((t,e)=>{if(!e.isConnected){Qe.delete(e);return}let{clientHeight:n,scrollHeight:o}=e,s=o>n;t.visible!==s&&(t.visible=s,t.callbacks.forEach(r=>r(t.visible)))}),Qe.size!==0&&(wp=window.requestAnimationFrame(Tp))};function Ep(t,e){return{observe(){let n=Qe.size===0;Qe.has(t)?Qe.get(t).callbacks.push(e):Qe.set(t,{visible:void 0,callbacks:[e]}),n&&Tp()},unobserve(){let n=Qe.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||Qe.delete(t),Qe.size||cancelAnimationFrame(wp)}}}}var Yi=["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 ea(t,e,n){return n.forEach(o=>{e.style[o]=t[o]})}function Un(t){return parseFloat(t)}function Tr(t){return Math.round(t*1e6)}function kp(t){return t/1e6}function ta(t,e,n){if(t.boxSizing==="content-box")return;let{clientWidth:o}=e,s=Un(t.width),r=Un(t.borderLeftWidth),i=Un(t.borderRightWidth),a=Un(t.paddingRight),d=kp(Tr(s)-Tr(r)-Tr(i)),l=kp(Tr(o));if(d-l>2){let c=d-l;n.style.paddingRight=`${a+c}px`}}function _o(t,e={}){var c,p;let n=e.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=e.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Gt(n);let o=window.getComputedStyle(t),s=!0,r=()=>{n.scrollTop=t.scrollTop};ea(o,n,Yi),ta(o,t,n),e.mirrorOverflow&&(n.style.overflow="hidden",t.addEventListener("scroll",r));let i=Ep(t,()=>{ea(o,n,Yi),ta(o,t,n),r(),setTimeout(r,0)}),a,d=!0,l=Ji(t,u=>{if(u===null){e.onRemove&&e.onRemove(),n.remove();return}if(!d&&e.onMoveStart&&(Promise.resolve().then(()=>e.onMoveStart()),d=!0),clearTimeout(a),a=setTimeout(()=>{e.onMoveEnd&&e.onMoveEnd(),d=!1},200),u.height===0&&u.width===0){if(s===!0)return;e.onHide&&e.onHide(),n.style.display="none",s=!0;return}if(ea(o,n,Yi),ta(o,t,n),r(),n.style.top=`${u.top}px`,n.style.left=`${u.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let m=e.closestScrollElement.getBoundingClientRect(),y=window.getComputedStyle(e.closestScrollElement),f=Un(y.borderTopWidth),v=Un(y.borderBottomWidth),C=m.top+f-u.top,k=u.top+u.height+-(m.top+m.height-v);n.style.clipPath=`inset(${C}px 0px ${k}px 0px)`}s&&(n.style.display="block",e.onShow&&e.onShow(),s=!1)});return e.appendTo?e.appendTo.appendChild(n):(p=t.parentElement)==null||p.appendChild(n),l.observe(),i.observe(),[n,()=>{t.removeEventListener("scroll",r),l.unobserve(),i.unobserve()}]}var Rp=(t,e)=>({value(){try{let n=sessionStorage.getItem(`dd-${t}`);if(!n)return e;try{return JSON.parse(n)}catch(o){return e}}catch(n){return e}},update(n){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(n))}catch(o){E.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function yh(t){return t.offsetParent!==null}function Ip(t){if(!yh(t))return!1;let e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}function Er(t,e,n=100){let o=Ip(t);e({isVisible:o});let s=setInterval(()=>{let r=Ip(t);r!==o&&(o=r,e({isVisible:o}))},n);return()=>{clearTimeout(s)}}var G=require("react/jsx-runtime");var Lp=Rp("showTabHint",!0),Vn=class Vn{constructor({deepdeskUrl:e,version:n=Vn.version||"unknown",locale:o="en-US",token:s,fetch:r,productName:i,createCustomChannel:a}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let d=e.replace(/\/api$/,"");this.deepdeskApi=new mt(d,{token:s,fetch:r}),this.version=n,this.instanceId=Vn.count++;let l={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[pp({broadcast:(c,p,u)=>{this.broadcastEvents.send(c,p,u)},emit:(c,p)=>this.emit(c,p),handleAfterSendMessage:c=>this.handleAfterSendMessage(c),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:c=>this.logSendMessage(c),onUpdateShowTabHint:c=>Lp.update(c),sendEvent:(c,p)=>this.deepdeskApi.sendEvent(c,p)})]};this.store=up(l),this.broadcastEvents=new Zu({debug:!0,deepdeskUrl:d,eventMap:Tl(this.store),createCustomChannel:a}),this.store.dispatch(Co(Lp.value())),this.store.dispatch(Qo({locale:o,adminUrl:d,productName:i}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var e;return(e=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?e: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?(E.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(E.warn("Profile has not been loaded (yet)"),!0):(E.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(cn(null)),this.store.dispatch(Xe()),new Promise(e=>{let n=this.store.subscribe(()=>{let o=this.store.getState();se(o)&&Fa(o)!=="loading"&&(n(),e())});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return h(this,null,function*(){return(yield this.store.dispatch(Xe())).payload})}isConversationSupported(e,n){return h(this,null,function*(){return(yield this.store.dispatch(Nr({sessionId:e,options:n}))).payload})}createConversation(e){return h(this,null,function*(){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(yield this.store.dispatch(Zo(e))).payload})}getConversationBySessionId(e,n){return h(this,null,function*(){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(yield this.store.dispatch(Xo({sessionId:e,options:n}))).payload})}upsertConversation(e){return h(this,null,function*(){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(yield this.store.dispatch(Or(e))).payload})}postMessages(e){return h(this,null,function*(){return(yield this.store.dispatch(Yo(e))).payload})}updateConversation(e){return h(this,null,function*(){return(yield this.store.dispatch(Jo(e))).payload})}resetConversation(){this.store.dispatch(W()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(e){this.store.dispatch(Qo(e))}setVisitorInfo(e){this.store.dispatch(gl(e))}setCustomData(e){this.store.dispatch(fl(e))}setAgentInfo(e,n){return h(this,null,function*(){yield this.store.dispatch(Gn(g(g({},e),n)))})}setAgentSettings(e){return h(this,null,function*(){yield this.store.dispatch(_r(e))})}getAgentSettings(){return h(this,null,function*(){return(yield this.store.dispatch(Fr())).payload})}refresh(){return h(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(os({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let e=[];return this.store.dispatch(Ks()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})})}notifyExternalSuggestion(e){this.store.dispatch(Le(e))}evaluateRule(s){return h(this,arguments,function*(e,n={},o=au){return(yield this.store.dispatch(Jt({label:e,params:n,options:o}))).payload.cues})}evaluateAssistant(e,n){return h(this,null,function*(){let c=n||{},{input:o={},transcript:s,showCuesInWidget:r=!0,includeTags:i,expectFormat:a}=c,d=O(c,["input","transcript","showCuesInWidget","includeTags","expectFormat"]);Object.assign(o,d);let l=yield this.store.dispatch(Ye({assistantCode:e,expectFormat:a||"json-schema:cues",transcript:s,includeTags:i,input:o,skipState:!r}));if(l.error)throw new Error(l.error.message);return l.payload})}evaluateConversationAssistant(e,n){return h(this,null,function*(){yield this.loadProfileConfig();let o={accepted:"conversationAcceptedAssistant","new-message":"conversationNewMessageAssistant",ended:"conversationEndedAssistant"},s=this.state.profile.data[o[e]];if(!s){E.warn(`No assistant set in profile for conversation event "${e}"`);return}yield this.evaluateAssistant(s,g({transcript:"stored-transcript",includeTags:!0},n))})}getSummary(){return h(this,null,function*(){var n;if(!this.hasConversation())return E.warn("No conversation to create summary for."),null;(n=this.state.profile.data)!=null&&n.summarizerAssistantNew||E.warn("No profile loaded yet, or no summarizer assistant set in profile");let e=yield this.store.dispatch(Ue({}));if(e.error)throw new Error(e.error.message);return e.payload})}handleKeyDown(e){let{overlayCollapsed:n,openOverlayWhenTyping:o}=this.state.ui,{textSuggestions:s,selectedSuggestionIndex:r,selection:i}=this.state.input,{inlineSuggestions:a,showTextSuggestions:d}=this.state.settings,l=a?"below":"above",c=s.length>0;if(!We(this.state)||(this.store.dispatch(nl(Dr(e))),e.key!=="Tab"&&!d))return;let p=()=>{n||!c||i&&(e.shiftKey||(this.store.dispatch(rl()),e.preventDefault()))},u=()=>{n||!c||a&&r<=0||i&&(e.shiftKey||(this.store.dispatch(il()),e.preventDefault()))};switch(e.key){case"ArrowUp":l==="below"?u():p();break;case"ArrowDown":{l==="below"?p():u();break}case"Escape":{n||(this.store.dispatch(ns(-1)),this.store.dispatch(Tt({collapse:!0})),this.store.dispatch(dc(!0)),e.preventDefault());break}case"Tab":{e.preventDefault();let m=mn(this.state);if(!m)return;this.store.dispatch(Co(!1)),this.store.dispatch(Le({text:m.text,suggestion:m,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.state.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let m=mn(this.state);if(!m)return;this.store.dispatch(Le({text:m.text,suggestion:m,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.state.settings.inlineSuggestions||e.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let m=mn(this.state);if(!m)return;this.store.dispatch(Le({text:m.text,suggestion:m,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),e.preventDefault();break}default:}n&&o&&this.store.dispatch(Tt({collapse:!1}))}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(vt([]))}handlingTimeStart(){this.state.handlingTime.startTime||(E.info("Start handling time"),this.store.dispatch(np()))}handlingTimeStop(){this.state.handlingTime.startTime&&(E.info("Stop handling time"),this.store.dispatch(vr()))}logSendMessage(e){let n=fp("input",this.state,{version:this.version});n&&(e&&(Object.assign(n,{text:e}),Object.assign(n,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n))}logHandlingTime(){let e=gp(this.state,{version:this.version});e&&(this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(op()))}notifySubmit(e={}){var n;this.shouldAbort()||(this.store.dispatch(Ot((n=e.text)!=null?n:this.state.input.text)),this.store.dispatch(ll()))}emit(e,n){let o=this.eventListeners[e];o&&o.forEach(s=>{try{s(n)}catch(r){E.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),E.error(r)}})}on(e,n){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n),()=>{this.off(e,n)}}off(e,n){if(!e&&!n){this.eventListeners={};return}let o;this.eventListeners[e]&&(o=this.eventListeners[e].indexOf(n),o>-1&&this.eventListeners[e].splice(o,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}setPlatformVariables(e){this.store.dispatch(hl(e))}whenConversationLoaded(e){let n=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&n();let o=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==o&&(o=this.hasConversation(),o&&n())})}overlayContainerFactory(e,n,o,s){let[r,i]=_o(n,o);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{(0,Re.unmountComponentAtNode)(r),i(),r.remove()}),r}createInlineContainer(e,n){var a;let o=document.createElement("div");o.style.position="absolute",o.style.top="0px",o.style.left="0px",o.style.height="0px",o.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",o.appendChild(s);let r=(a=e.ownerDocument.defaultView)==null?void 0:a.frameElement,i=r?r.ownerDocument.defaultView:null;if(r&&(i===window||(i==null?void 0:i.parent)===window)){let[d,l]=_o(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});d.dataset.testid=n,d.style.zIndex="2",d.appendChild(o),this.unmountHandlers.push(()=>{(0,Re.unmountComponentAtNode)(s),l()})}else document.body.appendChild(o);return s}createContainer(e,n=document.body){let o=window.getComputedStyle(n),s=document.createElement("div");return Gt(s),s.dataset.testid=e,s.style.color=o.color,s.style.fontSize=o.fontSize,s.style.fontFamily=o.fontFamily,s.style.fontVariant=o.fontVariant,s.setAttribute("translate","no"),n.appendChild(s),this.unmountHandlers.push(()=>{(0,Re.unmountComponentAtNode)(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,n),E.info(`Stored analytics for ${this.conversationId()}`)}catch(e){}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(e);if(!n)return;let o=JSON.parse(n);o.text.trim()===this.state.input.text.trim()?(E.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(al(o.metrics))):E.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch(e){}}mount(e,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Cr(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:o={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:d,showSuggestionsBeforePattern:l,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:u,insertLink:m,inputMediator:y,closestScrollSelector:f,appendOverlayTo:v,inlineSuggestions:C,floatingMenu:k}=n;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:d,showSuggestionsBeforePattern:l,showSuggestionsAfterPattern:c,showTextSuggestions:i,insertLink:m,isEmbedded:p,inlineSuggestions:C,floatingMenu:!!k}),n.automaticHandlingTime&&this.setupHandlingTime(e),Gt(e),this.inputMediator=y||(Xt(e)?new tn(e):new en(e)),this.inputMediator.on("change",({plainText:w,rawHTML:N})=>{this.store.dispatch(os({text:w,html:N}))}),this.inputMediator.on("keyup",w=>{this.store.dispatch(ol(Dr(w)))}),this.inputMediator.on("keydown",w=>{this.handleKeyDown(w)}),this.inputMediator.on("paste",({pastedText:w,selectionText:N})=>{this.store.dispatch(sl({text:w,selectionText:N}))}),this.inputMediator.on("cut",({selectionText:w})=>{this.store.dispatch(tl(w))});let S;this.inputMediator.on("selection",w=>{clearTimeout(S),w===null?S=setTimeout(()=>{w!==null&&this.store.dispatch(ss(w))},500):this.store.dispatch(ss(w))}),this.inputMediator.on("disabled",()=>{var w;(w=this.inputMediator)==null||w.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{u&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(zs(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(zs(!0))});let I=f&&hp(e,f)||void 0;if(C){let{customStyles:w,appendOverlayTo:N}=n,M=this.createInlineContainer(e,"deepdesk-caret");(0,Re.render)((0,G.jsx)(Zt,{store:this.store,customStyles:w,children:(0,G.jsx)(_t,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(vc,{})})}),M),this.inputMediator.on("caretposition",ne=>{ne?(M.style.display="block",M.style.top=`${ne.top}px`,M.style.left=`${ne.left}px`):M.style.display="none"});let B=this.overlayContainerFactory("floating-menu",I||e,{appendTo:typeof k=="object"&&"appendOverlayTo"in k?k.appendOverlayTo:N},w==null?void 0:w.floatingMenuRootNode);(0,Re.render)((0,G.jsx)(Zt,{store:this.store,customStyles:w,children:(0,G.jsx)(_t,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(rc,{onLogIn:()=>this.loginViaPopup().catch(ne=>E.warn(ne.message))})})}),B)}else{let w=this.overlayContainerFactory("deepdesk-tab-completion",I||e,{appendTo:v,closestScrollElement:I,mirrorOverflow:!0,onRemove:()=>this.unmount()},o==null?void 0:o.rootNode),N=this.overlayContainerFactory("deepdesk-suggestions-overlay",I||e,{appendTo:v},o==null?void 0:o.suggestionsRootNode);(0,Re.render)((0,G.jsx)(Zt,{store:this.store,customStyles:o,children:(0,G.jsx)(_t,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(ou,{inputElement:e})})}),w),(0,Re.render)((0,G.jsx)(Zt,{store:this.store,customStyles:o,children:(0,G.jsx)(_t,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(Lc,{onLogIn:()=>this.loginViaPopup().catch(M=>E.warn(M.message))})})}),N)}(0,Re.render)((0,G.jsx)(Zt,{store:this.store,customStyles:o,children:(0,G.jsx)(_t,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(Jd,{})})}),this.createContainer("deepdesk-overlays")),this.store.dispatch(os({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(ss(this.inputMediator.getSelection())),this.store.dispatch(zs(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var w;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((w=this.state.conversation.current)==null?void 0:w.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,n={}){if(this.widgetRoot&&E.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:o,showImages:s,isEmbedded:r}=n;this.widgetRoot=e,this.configure({showImages:s,isEmbedded:r}),(0,Re.render)((0,G.jsx)(Zt,{store:this.store,customStyles:o,children:(0,G.jsx)(_t,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(Wu,{onLogIn:()=>this.loginViaPopup().catch(i=>E.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Re.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let n=Er(e,({isVisible:o})=>{o?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){yp(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>h(this,null,function*(){yield this.store.dispatch(lo());let e=Ht(this.state);e&&(yield this.store.dispatch(oo()),this.store.dispatch(Qo({showSearch:e.search,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:!!e.summarizerAssistantNew||e.summarizer,showKnowledgeSearch:!!e.knowledgeAssistantNew||!!e.knowledgeAssistant,recommendTextSuggestions:e.recommendTextSuggestions})))})),this.loadProfileConfigPromise)}loginViaPopup(e){return h(this,null,function*(){return new Promise((n,o)=>{let s=new MessageChannel,r=s.port1,i=this.state.settings.adminUrl,a=new URL(e!=null&&e.url?e==null?void 0:e.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let d=!1,l=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(u)};r.onmessage=m=>h(this,null,function*(){var y,f;if((y=m.data)!=null&&y.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((f=m.data)==null?void 0:f.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Zn),d=!0,s.port1.close(),n()}catch(v){console.error(v),o(v)}finally{d=!0,l()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&o(new Error("Popup blocked by browser"));let p=m=>h(this,null,function*(){var y;if(m.origin===a.origin)switch((y=m.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let f=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(f,a.origin,[s.port2])}catch(f){E.error("Error posting message to popup",f),o(f)}break}case"deepdesk-popup-error":{l(),m.data.message==="Timeout"&&E.warn("Popup timed out. Check if the account's platform url is configured correctly."),o(new Error(m.data.message));break}}});window.addEventListener("message",p);let u=setInterval(()=>{c&&!c.closed||(l(),d||o(new Error("Popup closed by user")))},200);this.unmountHandlers.push(l)})})}translateMessages(e){return this.deepdeskApi.translateMessages(e)}checkForTrialMode(e){return h(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(E.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(e)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:o}=n;E.info(o),this.shouldRender=!1}})}refreshWidgetSuggestions(){return h(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let n=co(this.state);try{n.forEach(({type:o})=>{o==="entities"?this.store.dispatch(Ne()):Go.includes(o)||this.store.dispatch(Oe(o))})}catch(o){this.handleError(o)}})}};Vn.version="14.3.1-beta.9",Vn.count=0;var Fo=Vn;function vh(t){return h(this,null,function*(){var s,r,i;let n=yield((s=t.fetch)!=null?s:window.fetch)(t.url),o=yield n.blob();return new File([o],t.name,{type:(i=(r=t.mimeType)!=null?r:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function Pp(t,e){return h(this,null,function*(){let n=yield vh(e),o=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[n]}),t.dispatchEvent(o)}finally{Object.hasOwn(t,"files")&&delete t.files}})}function Ap(t,e,n){return h(this,null,function*(){yield new mt(t).authenticateWithKey(e,n)})}function Mp(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function Np(o,s){return h(this,arguments,function*(t,e,n={}){var p,u;let{value:r}=t,{start:i,end:a}=(p=n.replace)!=null?p:{start:0,end:r.length},d=`${r.slice(0,i)}${e}${r.slice(a)}`,l=(u=n.selectionAfter)!=null?u:{start:i+e.length,end:i+e.length},c=()=>{if(n.setValue)return n.setValue(d);t.value=d};return Promise.resolve(c()).then(()=>{t.selectionStart=l.start,t.selectionEnd=l.end,t.blur(),t.focus()})})}function Op(o,s){return h(this,arguments,function*(t,e,n={}){let r=n.replace?Rt(t,n.replace.start,n.replace.end):Hn(t),i,a=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),i=document.createElement("span"),r.insertNode(i),n.insertBRs!==!1?e.split(`
11
11
  `).reverse().forEach((d,l)=>{l>0&&r.insertNode(document.createElement("br")),r.insertNode(document.createTextNode(d))}):r.insertNode(document.createTextNode(e))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){t.focus();let d=n.selectionAfter?Rt(t,n.selectionAfter.start,n.selectionAfter.end):(r.collapse(!1),r),l=window.getSelection();l==null||l.removeAllRanges(),l==null||l.addRange(d)}if(!i)return;i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}function Sh(t){let e=document.createElement("template");return e.innerHTML=t.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),e.content}function xh(t){let e=document.createDocumentFragment();return t.split(`
12
12
  `).forEach((n,o)=>{o>0&&e.appendChild(document.createElement("br"));let s={index:0},r=0;for(;s=n.slice(r).match(/(\[([^\]]+)])\(([^)]+)\)/);){let i=document.createElement("a");i.href=s[3],i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),i.appendChild(document.createTextNode(s[2])),e.appendChild(document.createTextNode(n.slice(r,r+s.index))),e.appendChild(i),r=r+s.index+s[0].length}e.appendChild(document.createTextNode(n.slice(r)))}),e}function Dp(t,e){let n=t.parentElement;if(!n){console.warn("No insert point found");return}let{display:o}=window.getComputedStyle(n);o.includes("block")||o==="table-cell"?n==null||n.insertBefore(e,t.nextSibling):Dp(n,e)}function _p(s,r){return h(this,arguments,function*(t,e,{isBlock:n,isHTML:o}={}){let i;t.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0}));let a=()=>{var u;let d=(u=t.ownerDocument.defaultView)!=null?u:window,l=d.getSelection();if((!l||l.rangeCount===0)&&(t.focus(),l=d.getSelection()),!l||l.rangeCount===0)return;let c=l.getRangeAt(0);if(!c)return;i=document.createElement("span"),c.insertNode(i);let p=o?Sh(e):xh(e);n?Dp(c.startContainer,p):(c.insertNode(p),c.collapse(!1))};return Promise.resolve(a()).then(()=>{if(t.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0})),t.focus(),!!i)try{i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}0&&(module.exports={Card,ContentEditableInput,DeepdeskAPI,DeepdeskSDK,HTTPClient,InputMediator,InputType,KeyboardHint,Label,Locale,Section,SectionList,Sources,Suggestion,SuggestionList,TextAreaInput,ToggleButton,attachFile,authenticateWithKey,createFullRange,createOverlayContainer,createRangeFromOffsets,escapeHTML,formatTextMarkup,getRangeOffsets,getRangeText,insertCKEditor,isHTML,isSupportedInputElement,updateContentEditable,updateTextArea,useClickOutsideRoot,useStyles,waitForElementVisibilityChange});