@deepdesk/deepdesk-sdk 14.3.1-beta.4 → 14.3.1-beta.6

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
@@ -5,8 +5,8 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
5
5
  c-6.8,6.8-15.4,10.2-24.7,10.2h-349c-9.4,0-17.9-3.4-24.7-10.2c-6.8-6.8-10.2-15.4-10.2-24.7V267.9c0-9.4,3.4-17.9,10.2-24.7
6
6
  c6.8-6.8,15.4-10.2,24.7-10.2h11.9v-70c0-44.4,16.2-82.8,47.8-115.2S212.1,0,256.4,0s82.8,16.2,115.2,47.8
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 gi=require("react/jsx-runtime"),_g={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},$d=({className:t,color:e})=>(0,gi.jsx)("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,gi.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:_g[e||"pink"]})});var Gd={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedIn:"dd-XvHAn",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var fi={};oe(fi,{enUS:()=>Fg,nlNL:()=>Hg});var Fg={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},Hg={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Zd=require("react-redux"),qt=require("react/jsx-runtime"),Jd=({onLogIn:t})=>{let e=P(fi),n=T("floatingMenu"),o=T("productName"),s=(0,Zd.useDispatch)(),r=(0,Xd.useSelector)(se),i=x("FloatingMenu",Gd);if(r===null||n===!1)return null;let a=()=>{r===!0?s(be(!0)):t()};return(0,qt.jsxs)("button",{className:(0,Qd.default)(i.root,{[i.isLoggedIn]:r,[i.isLoggedOut]:!r}),onClick:a,children:[(0,qt.jsx)("div",{className:i.text,children:e(r?"search":"signin",{productName:o})}),(0,qt.jsxs)("div",{className:i.icon,children:[(0,qt.jsx)($d,{className:i.logo,color:"pink"}),r===!1&&(0,qt.jsx)(qd,{className:i.lock})]})]})};var js=require("react"),ot=require("react-redux");var Yd=require("react");function Ct(t){(0,Yd.useEffect)(()=>{let e=n=>{n.isWithinRoot||t(n)};return document.body.addEventListener("mouseup",e),()=>{document.body.removeEventListener("mouseup",e)}},[t])}function $t(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 ec=require("@reduxjs/toolkit"),Kg={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1},Us=({ui:t})=>t.overlayCollapsed,tc=(0,ec.createSlice)({name:"ui",initialState:Kg,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:bo,setInputFocus:Vs,setOverlayCollapsed:wt,setOpenOverlayWhenTyping:nc,setOverlayCollapsedUserOverwrite:oc}=tc.actions,sc=tc.reducer;var zs=require("react");var lc=require("interweave"),Rn=require("react"),Co=require("react-redux");var rc=require("react");function ic(t,e,n){(0,rc.useEffect)(()=>{let o=t.current;return o?(o.addEventListener(e,n),()=>{o.removeEventListener(e,n)}):()=>{}},[t,e,n])}var ac={root:"dd-1MBCO",actions:"dd--x4cy",badge:"dd-4Fpkz",formattedText:"dd-EzvTB"};var Gt=require("react/jsx-runtime"),Ug=["search","personal-collection-search","search-autocomplete"];function Vg(t,e,n,o={}){var r;let s="";return Ug.includes(e)?s=Jl(Jr(t,n,{stripAgentPart:!0}),(r=o.searchKeywords)!=null?r:[n]):s=Jr(t,n,o),o.placeholders===!0&&(s=Yl(s)),s}var zg=()=>{},Wg=({selected:t,suggestion:e})=>{let n=T("inlineSuggestions"),o=(0,Co.useSelector)(un),s=T("enableSuggestionFeedback"),r=(0,Co.useSelector)(c=>c.input.text),i=(0,Co.useDispatch)(),a=x("TextSuggestion",ac),d=(0,Rn.useRef)(null);(0,Rn.useEffect)(()=>{let c=setTimeout(()=>{i(Ga({text:e.text,suggestion:e}))},500);return()=>{clearTimeout(c)}},[e]),ic(d,"click",()=>{i(Le({suggestion:e,text:e.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let l=(0,Rn.useMemo)(()=>Vg(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,Gt.jsxs)("div",{className:a.root,children:[(0,Gt.jsx)(_,{ref:d,as:"button","data-testid":"suggestions-overlay-item",selected:t,onClick:zg,children:(0,Gt.jsx)(lc.Interweave,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:l})}),s&&(0,Gt.jsx)("div",{className:a.actions,children:(0,Gt.jsx)(_s,{source:"overlay",context:r,suggestion:e})})]})},dc=Wg;var hi=require("react/jsx-runtime"),jg=({suggestions:t,selectedIndex:e,reverse:n})=>{let o=(0,zs.useMemo)(()=>{let s=t.map((r,i)=>(0,hi.jsx)(dc,{index:i,selected:i===e,suggestion:r},`${r.text}-${r.source}`));return n?s.reverse():s},[t,e,n]);return(0,hi.jsx)(zs.Fragment,{children:o})},Ws=jg;var cc={root:"dd-PfvRI",paper:"dd-HYlyY"};var wo=require("react/jsx-runtime"),qg=({textSuggestions:t,selectedIndex:e})=>{let n=(0,js.useRef)(null),o=x("InlineSuggestionsOverlay",cc),s=(0,ot.useSelector)(We),r=(0,ot.useDispatch)(),i=(0,ot.useSelector)(se),a=(0,ot.useSelector)(cn),d=(0,ot.useSelector)(Us),l=T("showTextSuggestions");return Ct(()=>{setTimeout(()=>{r(wt({collapse:!0,skipWhenInputFocus:!0}))})}),(0,js.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,wo.jsx)("div",{className:o.root,"data-variant":"inline",children:(0,wo.jsx)("div",{ref:n,className:o.paper,children:(0,wo.jsx)(pe,{children:(0,wo.jsx)(Ws,{suggestions:t,selectedIndex:e})})})})},$g=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),uc=(0,ot.connect)($g)(qg);var pc=require("react-redux");var To=require("react/jsx-runtime"),Gg=({children:t})=>{let n=T("locale").replace("-","");return(0,To.jsx)($r.Provider,{value:n,children:t})},Qg=({store:t,customStyles:e={},children:n})=>(0,To.jsx)(pc.Provider,{store:t,children:(0,To.jsx)(Gg,{children:(0,To.jsx)(Wn.Provider,{value:e,children:n})})}),Qt=Qg;var $s=A(require("classnames")),In=require("react"),rt=require("react-redux");var mc=require("react");function gc(t,e){let[n,o]=(0,mc.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 fc=()=>/Mac/i.test(navigator.platform);var yc=A(require("classnames")),st=require("react");var yi={};oe(yi,{enUS:()=>Xg,nlNL:()=>Zg});var Xg={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"}]}]},Zg={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 hc={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};var Tt=require("react/jsx-runtime"),vi=(t,e,n)=>o=>(0,Tt.jsx)("button",{className:t.anchorButton,type:"button",value:e,onClick:n,children:o},e),Jg=({className:t,loginUrl:e,isEmbedded:n,onSnooze:o,onLogIn:s})=>{let r=P(yi),i=me(),a=x("Login",hc),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(hn,!0)},[e]),p=(0,st.useMemo)(()=>v=>(0,Tt.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,Tt.jsx)("button",{type:"button",className:a.anchorButton,onClick:c,children:v},"prompt"),[c]),{min:m,hour:y,day:f}=(0,st.useMemo)(()=>({min:vi(a,60*10,l),hour:vi(a,60*60,l),day:vi(a,60*60*12,l)}),[]);return(0,Tt.jsxs)("div",{className:(0,yc.default)(t,a.root),children:[r("loginPlease",{login:n?u:p,productName:d}),o&&(0,Tt.jsxs)(st.Fragment,{children:[(0,Tt.jsx)("br",{}),r("snooze",{min:m,hour:y,day:f})]})]})},qs=Jg;var Sc=require("react-redux");var vc={root:"dd-DoQhb",text:"dd-Jwnev"};var Eo=require("react/jsx-runtime"),Yg=({title:t})=>{let e=x("SearchTrigger",vc),n=(0,Sc.useDispatch)();return(0,Eo.jsxs)("button",{type:"button",className:e.root,onClick:()=>n(be(!0)),children:[(0,Eo.jsx)(xn,{}),(0,Eo.jsx)("span",{className:e.text,children:t})]})},xc=Yg;var Si={};oe(Si,{enUS:()=>ef,nlNL:()=>tf});var ef={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"}]},tf={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 bc={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"),nf=({textSuggestions:t,selectedIndex:e,onLogIn:n})=>{let o=x("SuggestionsOverlay",bc),s=P(Si),r=(0,rt.useSelector)(We),i=$a(),a=(0,rt.useDispatch)(),d=(0,In.useRef)(null),l=T("searchTriggerKey"),c=T("productName"),p=(0,rt.useSelector)(Us),u=(0,rt.useSelector)(se),m=(0,rt.useSelector)(cn),[y,f]=(0,In.useState)(null),v=T("showSearch"),C=T("showTextSuggestions"),k=T("adminUrl"),S=T("isEmbedded"),[I,w]=gc("dd-snooze-until-ms",0),N=p||I>Date.now(),M=t.filter(ye=>ye.source!=="gpt").length,B=()=>{N&&w(0),a(oc(!N))},ne=ye=>{let D=Date.now()+ye*1e3;w(D),E.info(`Snooze until: ${new Date(D)}`),a(wt({collapse:!0}))};return(0,In.useEffect)(()=>{M===0&&f(null)},[t,M]),Ct(()=>{a(wt({collapse:!0,skipWhenInputFocus:!0}))}),u===null||m===!1?null:u===!1?(0,V.jsxs)("div",{ref:d,className:(0,$s.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)(Pt,{className:o.toggleButton,title:s("collapse"),onClick:B,isCollapsed:!1})})]}),(0,V.jsx)("div",{className:o.toggleButtonWrapper,children:(0,V.jsx)(Pt,{className:o.toggleButton,title:s("open",{productName:c}),onClick:B,isCollapsed:!0})}),(0,V.jsx)("div",{className:o.collapsible,children:(0,V.jsx)(qs,{loginUrl:k,isEmbedded:S,onLogIn:n,onSnooze:ne})})]}):!i||!r?null:(0,V.jsxs)("div",{ref:d,className:(0,$s.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(fc()?"searchHintMac":"searchHintWindows",{searchTriggerKey:l.toUpperCase()})),onMouseLeave:()=>f(null),children:(0,V.jsx)(xc,{title:s("search")})})}),(0,V.jsxs)("div",{className:o.triggersRight,onFocus:()=>{},children:[(0,V.jsx)("div",{className:(0,$s.default)(!y&&o.hintsHidden,o.hints),children:y}),(0,V.jsx)(Pt,{className:o.toggleButton,title:s("collapse"),onClick:B,isCollapsed:!1})]})]}),(0,V.jsx)("div",{className:o.toggleButtonWrapper,children:(0,V.jsx)(Pt,{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)(Ws,{suggestions:t,selectedIndex:e,reverse:!0})})})]})},of=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),Cc=(0,rt.connect)(of)(nf);var lr=A(require("classnames")),$c=require("interweave"),dt=require("react"),Gc=require("react-redux");var Ln=require("react");function Gs(t){return t.contentEditable==="true"}function sf(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 wc(t){let{selectionStart:e,selectionEnd:n}=Gs(t)?sf(t):t;return[e,n]}function Tc(t){let[,e]=(0,Ln.useState)(),n=(0,Ln.useRef)(null);return n.current=wc(t),(0,Ln.useEffect)(()=>{let o=()=>{var a;let[s,r]=(a=n.current)!=null?a:[],i=wc(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 Ec(t,e){if(!e)return;let n=t,{value:o}=n,[s,r]=e,i=o.match(qo);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 kc=require("react"),rf=["div","span","mark","strong","b","i","u","em"];function xi(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(rf.includes(s)){let i=Array.isArray(o.props.children)?o.props.children:[o.props.children];return[...t.slice(0,t.length-1),(0,kc.cloneElement)(o,{children:xi(i,e,n+1)})]}return[...t,...e]}function Xt(t){return t.tagName.toLowerCase()==="textarea"}var Rc={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 Fc=A(require("classnames")),Hc=require("interweave"),or=require("react");var Pn=require("react");function Ic(t,e){let n;return[(...o)=>{window.cancelAnimationFrame(n);let s=e?e(...o):o;n=window.requestAnimationFrame(()=>{t(...s)})},()=>window.cancelAnimationFrame(n)]}function Qs(t){let e=(0,Pn.useRef)(null),[n,o]=(0,Pn.useState)(!1);return(0,Pn.useEffect)(()=>{var c;let s=!1,r=parseFloat((c=window.getComputedStyle(document.body).zoom)!=null?c:"1"),[i,a]=Ic((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]=Ic(()=>{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 Lc(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Xs(t){return e=>{t.forEach(n=>{typeof n=="function"?n(e):n!=null&&(n.current=e)})}}function Pc(t){return t!=null}var Ci=A(require("classnames")),we=require("react");var Zs=require("react"),af=["bottom","height","left","right","top","width"],lf=(t={},e={})=>af.some(n=>t[n]!==e[n]),it=new Map,Ac,Mc=()=>{let t=[],e=[];it.forEach((n,o)=>{if(o instanceof Element&&!o.isConnected){e.push(o);return}let s=o.getBoundingClientRect();lf(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))}),Ac=window.requestAnimationFrame(Mc)};function df(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&&Mc()},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(Ac)}}}}function bi(t){let[e,n]=(0,Zs.useState)(null);return(0,Zs.useLayoutEffect)(()=>{if(!t.current)return;let o=df(t.current,s=>{n(s)});return o.observe(),()=>{o.unobserve()}},[t]),e}var An=require("react"),Oc=require("react-dom");var Nc={root:"dd-r-dgo"};var Dc=({children:t,parentNode:e})=>{let[n,o]=(0,An.useState)(null),s=(0,An.useContext)(Wn);return(0,An.useLayoutEffect)(()=>{let r=document.createElement("div");return $t(r),r.classList.add(Nc.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,Oc.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 Js=require("react/jsx-runtime"),Ys=(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 wi(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 Mn=l=>{var c=l,{className:t,triggerRef:e,boundaryRef:n=(0,we.createRef)(),position:o="above",align:s="center",children:r,toStyle:i=wi,parentNode:a}=c,d=O(c,["className","triggerRef","boundaryRef","position","align","children","toStyle","parentNode"]);let p=bi(e),u=bi(n),m=(0,we.useMemo)(()=>i(p,u,0),[p,u]);return(0,Js.jsx)(Dc,{parentNode:a,children:(0,Js.jsx)("div",b(g({className:(0,Ci.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,Js.jsx)("div",{className:(0,Ci.default)(t,je.root),children:r})}))})};var _c=A(require("classnames")),er=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 Ti=require("react/jsx-runtime"),tr=(0,er.forwardRef)((s,o)=>{var r=s,{className:t,children:e}=r,n=O(r,["className","children"]);let i=(0,er.useRef)(null),a=x("TabCompletion",at);return(0,Ti.jsx)("div",b(g({ref:Xs([i,o]),className:(0,_c.default)(t,a.popoverContentContainer)},n),{children:(0,Ti.jsx)("div",{className:a.popoverContent,children:e})}))});var Et=require("react/jsx-runtime"),cf=t=>e=>{let n=wi(e);return"top"in n&&(n.width=t.width-(e.left-t.left)-10),n},uf=({inputElement:t,boundaryRef:e,inputStyle:n,children:o,suggestion:s})=>{let r=x("TabCompletion",at),i=Ys(),a=(0,or.useMemo)(()=>cf(t.getBoundingClientRect()),[t]),[d,l]=Qs(t);return(0,or.useEffect)(()=>{l?i.open():i.close()},[l]),(0,Et.jsxs)("span",{children:[(0,Et.jsx)("mark",{ref:Xs([d,i.triggerRef]),className:(0,Fc.default)(r.matchKeyword,{[r.hover]:l}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:o}),i.opened&&(0,Et.jsx)(Mn,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:(0,Et.jsx)(tr,{style:n,children:(0,Et.jsx)("div",{className:r.hintText,children:s})})})]})},nr=class extends Hc.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${Lc(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(Pc);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,Et.jsx)(uf,{inputElement:o.inputElement,suggestion:o.suggestion,inputStyle:o.inputStyle,boundaryRef:o.boundaryRef,children:n},`keyword_${o.matchString}_${o.key}`)}asTag(){return"mark"}};var Kc=require("interweave"),Bc=A(require("classnames"));var Ei=require("react/jsx-runtime"),pf=({inputElement:t,children:e})=>{let n=x("TabCompletion",at),[o,s]=Qs(t);return(0,Ei.jsx)("mark",{ref:o,className:(0,Bc.default)(n.matchPlaceholder,{[n.hover]:s}),children:e})},sr=class extends Kc.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,Ei.jsx)(pf,{inputElement:n.inputElement,children:e},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var ir=A(require("classnames")),jc=require("interweave"),le=require("react"),qc=require("react-redux");var ki=require("react/jsx-runtime"),Uc=()=>(0,ki.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,ki.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"),ko=require("react-redux"),zc=A(require("lodash.debounce"));var Vc={root:"dd-ky-Bv",content:"dd-kV5e1"};function rr(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 Ri(t){return t.replace("https://www.","").replace("https://","")}var Te=require("react/jsx-runtime"),mf=3,gf=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),ff=({onSelectLink:t,onDismiss:e,placeholder:n,visitUrlText:o,linkCount:s=mf})=>{let r=x("LinkSearch",Vc),[i,a]=(0,qe.useState)(""),d=(0,ko.useDispatch)(),l=(0,ko.useSelector)(_d("url")),c=(0,ko.useSelector)(gl("URL")),p=(0,qe.useMemo)(()=>c.map(gf),[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(Ot({query:S,type:"URL",tags:["link-search"]}))},300),[]);return(0,qe.useEffect)(()=>{i&&k(i)},[i]),(0,qe.useEffect)(()=>()=>{d(rs())},[]),(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:rr(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||Ri(S.text)}),S.title&&Ri(S.text)]}),(0,Te.jsx)(_.Actions,{children:(0,Te.jsx)(_.ActionButton,{label:o,onClick:w=>v(w,S.text)})})]})},S.text))}),(0,Te.jsx)(to,{value:i,onChange:f,autoFocus:!0,placeholder:n,onKeyUp:C})]})},Wc=ff;var Ii={};oe(Ii,{enUS:()=>hf,nlNL:()=>yf});var hf={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},yf={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"),vf=(0,le.forwardRef)((t,e)=>{let n=x("TabCompletion",at);return(0,ae.jsx)("mark",{ref:e,className:(0,ir.default)(n.matchSelection)},"selection-start")}),Sf=({startRef:t,boundaryRef:e,inputStyle:n,inputElement:o,children:s})=>{let r=P(Ii),i=x("TabCompletion",at),a=(0,le.useRef)(null),d=(0,le.useRef)(null),[l,c]=(0,le.useState)(null),p=(0,qc.useDispatch)(),u=Ys(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]),Ct(()=>{u.close()});let y=(0,le.useCallback)(f=>{let v=m.toString(),C=/^http(s?):\/\//.test(f)?f:`https://${f}`;p(Yo({text:`[${v}](${C})`,replace:"selection"}))},[]);return(0,ae.jsxs)("span",{children:[(0,ae.jsx)("mark",{ref:a,className:(0,ir.default)(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":u.opened?"true":"false",children:s}),u.opened&&(0,ae.jsx)(Mn,{className:i.popoverRoot,triggerRef:u.triggerRef,boundaryRef:e,position:"above",align:"start",children:(0,ae.jsxs)(tr,{style:n,ref:d,children:[(0,ae.jsx)("div",{className:(0,ir.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)(Uc,{}),(0,ae.jsx)("span",{children:"\xA0"}),(0,ae.jsx)("span",{children:r("insertLink")})]})}),l==="insertLink"&&(0,ae.jsx)(Wc,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:y,onDismiss:()=>{c(null),u.close()}})]})})]},"selection-end")},ar=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)(vf,{ref:this.startRef}):(0,ae.jsx)(Sf,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};var Qc=require("react-redux");var lt=require("react/jsx-runtime"),xf=({enabled:t,content:e,tabText:n,showTabHint:o,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:d})=>{let l=x("TabCompletion",Rc),c=T("insertLink"),p=T("showMidSentenceSuggestions"),u=T("inlineSuggestions"),m=Tc(a),y=(0,dt.useRef)(null),f=(0,Qc.useSelector)(se);(0,dt.useEffect)(()=>{Xt(a)&&m&&Ec(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,lr.default)(l.tabText,l.resetIndent),"data-source":d,children:n},"tabText")];return o&&I.push((0,lt.jsx)("span",{className:(0,lr.default)(l.hint,l.resetIndent),children:(0,lt.jsx)(zo,{keyCode:"tab"},"tabHint")})),xi(S,I)},[s,n,o]),C=(0,dt.useMemo)(()=>{let S=[];return c&&S.push(new ar("selection")),S.push(new sr("placeholders")),r&&S.push(new nr("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)($c.Interweave,{tagName:"span",containerTagName:"div",className:(0,lr.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",{})]})},bf=t=>{var v,C,k;let{input:e,ui:n,settings:o,styleSuggestions:s,conversation:r}=t,i=pn({input:e}),a=(i==null?void 0:i.text)||"",d=(i==null?void 0:i.source)||"",l=(v=e.html)!=null?v:Sn(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}},Xc=(0,Gc.connect)(bf)(xf);var Fu=A(require("classnames")),_n=require("react"),q=require("react-redux");var Ro=require("@reduxjs/toolkit");var Cf={token:null,interval:null},Li=(0,Ro.createAsyncThunk)("passwordlessToken/getTemporaryPasswordlessToken",(t,e)=>h(void 0,null,function*(){let{deepdeskAPI:n}=e.extra;return{token:yield n.requestPasswordlessToken()}})),Pi=(0,Ro.createAsyncThunk)("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:n=1e3*60*10}=t,{dispatch:o}=e;return o(Li()),setInterval(()=>o(Li()),n)}),Zc=(0,Ro.createSlice)({name:"passwordlessToken",initialState:Cf,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(Li.fulfilled,(e,n)=>{e.token=n.payload.token}),t.addCase(Pi.fulfilled,(e,n)=>{e.interval=n.payload})}}),{stopPollPasswordlessToken:Jc}=Zc.actions,Yc=Zc.reducer;var ru=require("@reduxjs/toolkit");var Nn=require("@reduxjs/toolkit");var eu={excludeFromWidget:!1},Ai={cues:[],fetchState:"idle"},tu=t=>{var e;return(e=t.rules)==null?void 0:e.cues},wf=(0,Nn.createAction)("rules/resetCues"),Zt=(0,Nn.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:X(u.title,i),text:X(u.text,i)}))),{cues:p,options:t.options}}catch(s){let r=s.message;return E.warn(r),e.rejectWithValue(r)}})),nu=(0,Nn.createSlice)({name:"answer",initialState:Ai,reducers:{removeCue(t,e){t.cues=t.cues.filter(n=>n.rule.id!==e.payload.id)}},extraReducers:t=>{t.addCase(Zt.pending,e=>{e.fetchState="loading"}).addCase(Zt.rejected,e=>{e.fetchState="error"}).addCase(Zt.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,()=>Ai).addCase(wf.toString(),()=>Ai)}}),{removeCue:ou}=nu.actions,su=nu.reducer;function Tf(t){let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n),e|=0;return e}var iu=(0,ru.createSelector)([tu,Bl],(t,e)=>{let n=e.map(o=>({text:o.response,title:o.name,callToAction:o.callToAction,isLoading:o.isLoading,rule:{id:Tf(o.code),label:o.code,name:o.name,description:o.name}}));return[...t,...n]});var dr=require("react"),lu=require("react-redux"),Ni=A(require("classnames"));var Mi=require("react/jsx-runtime"),Io=()=>(0,Mi.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,Mi.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 au={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"),Ef=({entities:t})=>{let e=x("EntitiesWidgetList",au),[n,o]=(0,dr.useState)(void 0),s=(0,lu.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,dr.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,Ni.default)(e.icon),children:(0,$e.jsx)(Io,{})}),(0,$e.jsx)("span",{className:(0,Ni.default)(e.icon,n===d&&e.iconClicked),children:(0,$e.jsx)(Io,{})})]})]},a.text))})},du=Ef;var Oi=require("react/jsx-runtime"),cu=()=>(0,Oi.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,Oi.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 Di=require("react/jsx-runtime"),uu=()=>(0,Di.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Di.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 _i=require("react/jsx-runtime"),pu=()=>(0,_i.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,_i.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 Tu=require("react-redux");var yu=require("react");var mu=require("react"),gu=t=>{(0,mu.useEffect)(()=>{let e=t.current;e&&e.scrollIntoView({behavior:"smooth"})},[])};var fu={loadingBar:"dd-6as-V",placeHolderShimmer:"dd-TFYmA"};var hu=require("react/jsx-runtime"),kf=({width:t})=>{let e=x("LoadingProgressBar",fu);return(0,hu.jsx)("div",{className:e.loadingBar,style:{width:t}})},cr=kf;var ct=require("react/jsx-runtime"),ur=({title:t})=>{let e=(0,yu.useRef)(null);return gu(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)(cr,{width:"60%"}),(0,ct.jsx)(cr,{width:"90%"}),(0,ct.jsx)(cr,{width:"50%"})]})})})};var Cu=require("react");var Su=A(require("dompurify")),ut=require("react"),xu=A(require("snarkdown"));var vu={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 Rf(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 Fi(t){var n;let e=t.cloneNode(!0);return e.querySelectorAll("div,button").forEach(o=>o.remove()),(n=e.textContent)!=null?n:""}function If(t){return t.replace(/\r\n/g,`
8
- `)}var Lf=({content:t,useLabel:e,copyLabel:n,onCopy:o,onUse:s})=>{let r=x("Markdown",vu),i=(0,ut.useRef)(null),[a,d]=(0,ut.useState)(null),l=(0,ut.useMemo)(()=>{let f=(0,xu.default)(If(t));return Su.default.sanitize(f).replaceAll("</code>",`${Rf(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&&(Tn(f,r.fadeup),o(Fi(a)))},u=f=>{let v=f.target;if(v.tagName==="A"){f.stopPropagation();return}"copyIcon"in v.dataset&&(Tn(v,r.fadeup),o(Fi(v.parentElement)))},m=()=>{!a||!s||(d(null),s(Fi(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)(Mn,{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,className:r.root,dangerouslySetInnerHTML:{__html:l},onMouseOver:c,onClick:u})]})},pr=Lf;var Hi={};oe(Hi,{enUS:()=>Pf,nlNL:()=>Af});var Pf={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"}]},Af={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 bu={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"),Mf=({cue:t,onCallToAction:e,onRemove:n,onCopy:o,onUse:s})=>{let r=x("WidgetCue",bu),i=P(Hi),a=bt(),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,Cu.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)(pr,{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)(kn,{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"})]})]})},wu=Mf;var On=require("react/jsx-runtime"),Nf=({cues:t})=>{let e=(0,Tu.useDispatch)(),n=me(),o=bt(),s=d=>{e(ou({id:d.rule.id})),e(Vl({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(Es(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,On.jsx)(On.Fragment,{children:t.map(d=>d.isLoading?(0,On.jsx)(ur,{title:d.title},d.rule.id):(0,On.jsx)(wu,{cue:d,onCallToAction:i,onRemove:s,onCopy:r,onUse:a},d.rule.id))})},Eu=Nf;var mr=require("react");var ku={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 Of(t,e){return e.split(".").reduce((n,o)=>!n||typeof n!="object"||!(o in n)?null:n[o],t)}var Ru=({data:t,schema:e})=>{let n=x("WidgetCustomData",ku),o=s=>{Ve(s)};return(0,mr.useEffect)(()=>{E.info("Custom data",t,e)},[t]),(0,_e.jsx)("dl",{className:n.root,children:e.map(s=>{let r=Of(t,s.path);return(0,_e.jsxs)(mr.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)(Io,{})]}):"-"})]},s.label)})})};var ge=require("react"),Lo=require("react-redux");var Ki=require("react/jsx-runtime"),Iu=()=>(0,Ki.jsx)("svg",{focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"ReplayIcon",children:(0,Ki.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 Dn={};oe(Dn,{enUS:()=>Df,nlNL:()=>_f});var Df={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"}]},_f={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 Bi={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"),Ff=3,Hf=({sources:t,onClick:e})=>{let n=P(Dn),o=x("WidgetKnowledgeAssistant",Bi),[s,r]=(0,ge.useState)(!1),i=s?t:t.slice(0,Ff);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})})]})},Kf=({innerRef:t,item:e,index:n,hasKeyboardInput:o,onCopy:s,onUse:r,onSourceClick:i})=>{var d;let a=P(Dn);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)(pr,{content:e.answer.answer,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:s,onUse:o?r:void 0}),(0,F.jsx)(Hf,{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)(kn,{eventName:"knowledge assist feedback",eventData:{question:e.question,isFollowUpQuestion:n>0,isAgent:!0,answer:e.answer.answer},feedbackText:e.answer.answer,feedbackType:"assistant"})]})]})},Ui=(0,ge.createContext)(null),Lu=({children:t})=>{let[e,n]=(0,ge.useState)(null),o=(0,Lo.useSelector)(co("knowledge-assist")),[s,r]=(0,ge.useState)(!1),[i,a]=(0,ge.useState)(null),d=(0,Lo.useDispatch)(),l=Ut(u=>ro({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(yn(e))}};return(0,F.jsx)(Ui.Provider,{value:c,children:t})},Pu=()=>{let t=P(Dn),e=x("WidgetKnowledgeAssistant",Bi),n=(0,ge.useContext)(Ui),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)(Iu,{})})]}):null},Au=()=>{var c,p;let t=P(Dn),e=bt(),n=(0,ge.useRef)(null),o=(0,ge.useContext)(Ui),s=(p=(0,Lo.useSelector)(so((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)(Kf,{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)(ur,{title:o.pendingInput})]})})};var Nu=require("react");var Uf=/(https?:\/\/[^\s]+)/,Mu=t=>t.split(" ").find(e=>Uf.test(e));var ke=require("react/jsx-runtime"),Vf=({suggestion:t,lines:e,onUse:n})=>{var p;let o=t.text||t.url||t.message,s=Mu(o),r=P(yo),i=T("showImages"),a=T("fallbackImage"),d=T("hasKeyboardInput"),l=u=>{u.preventDefault(),u.stopPropagation(),d&&n(o)},c=(0,Nu.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:rr(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")})]})]})},Ou=Vf;var Po=require("react/jsx-runtime"),zf=({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,Po.jsx)(Po.Fragment,{children:e.map(s=>(0,Po.jsx)(Ou,{suggestion:s,lines:t,onUse:r=>o(r,s)},s.text||s.url||s.message))})},Du=zf;var Ao={};oe(Ao,{enUS:()=>Wf,nlNL:()=>jf});var Wf={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"}]},jf={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 Jt={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"),Hu=(t,e)=>{let n=(0,q.useSelector)(se);(0,_n.useEffect)(()=>n?e.every(o=>!!o)?t():()=>{}:()=>{},[...e,n])},qf=({onLogIn:t})=>{let e=x("Widget",Jt),n=T("isEmbedded"),o=T("adminUrl");return(0,R.jsx)("div",{className:e.loginText,children:(0,R.jsx)("div",{children:(0,R.jsx)(qs,{isEmbedded:n,loginUrl:o,onLogIn:t})})},"login")},_u=({text:t})=>{let e=x("Widget",Jt);return(0,R.jsx)("div",{className:e.stateText,children:(0,R.jsx)("div",{children:(0,R.jsx)("p",{children:t})})},"notification")},$f=()=>{let t=P(Ao),e=x("Widget",Jt),n=Ut(()=>Ue({})),o=T("showSummaryCommand"),s=(0,q.useSelector)(co("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")})})},Gf=()=>{let t=P(Ao),e=(0,q.useDispatch)(),n=x("Widget",Jt),o=T("showSearch"),s=T("showSummaryCommand"),r=T("showKnowledgeSearch"),i=(0,q.useSelector)(co("knowledge-assist")),a=T("isEmbedded"),d=(0,q.useSelector)(En("/admin/")),l=me(),c=T("productName"),p=T("hasKeyboardInput"),u=Ut(()=>Ue({})),m=o||s||r||d;return Hu(()=>{if(a)return e(Pi()),()=>{e(Jc())}},[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)(xn,{}),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)(pu,{}),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)(uu,{}),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)(cu,{}),t("linkStudioLogin",{productName:c})]})]})})},Qf=()=>{let t=(0,q.useDispatch)(),e=(0,q.useSelector)(lo),n=(0,q.useSelector)(ql),o=(0,q.useSelector)(iu),s=(0,q.useSelector)(rl),r=(0,q.useSelector)(As),i=(0,q.useSelector)(Fs),a=(0,q.useSelector)(Ft),d=(0,q.useSelector)(Ke);return(0,_n.useEffect)(()=>{!!s&&!n&&E.warn("Custom data provided, but no schema.")},[s,n]),Hu(()=>{e.forEach(({type:l})=>{l==="entities"?t(Ne()):$o.includes(l)||t(Oe(l))})},[t,d,a]),(0,_n.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)(_n.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)(du,{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)(Eu,{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)(Ru,{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)(Du,{lines:u,contentType:l,suggestions:i[l].suggestions.slice(0,p)||[]})})},l)}})})},Xf=({children:t})=>{let e=x("Widget",Jt);return(0,R.jsx)("div",{className:e.footer,children:t})},Zf=({onLogIn:t})=>{let e=P(Ao),n=x("Widget",Jt),o=(0,q.useSelector)(cn),s=(0,q.useSelector)(se),r=(0,q.useSelector)(Va),i=(0,q.useSelector)(Ft);return o===!1?(0,R.jsx)(_u,{text:e("notSupported")}):s===!1?(0,R.jsx)(qf,{onLogIn:t}):!i||!r||s===null?(0,R.jsx)(_u,{text:e("waiting")}):(0,R.jsx)("div",{className:(0,Fu.default)(n.root),"data-testid":"widget",children:(0,R.jsxs)(Lu,{children:[(0,R.jsxs)(Wo,{className:n.sectionList,children:[(0,R.jsx)(Gf,{}),(0,R.jsx)(Qf,{}),(0,R.jsx)(Au,{})]}),(0,R.jsxs)(Xf,{children:[(0,R.jsx)(Pu,{}),(0,R.jsx)($f,{})]})]})})},Ku=Zf;function Fn(t){let e=new Range;return e.selectNodeContents(t),e}function Bu(t,e,n){try{return kt(t,e,n),!0}catch(o){return!1}}function gr(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function fr(t){return"tagName"in t&&t.tagName==="BR"}var Mo=/[\u200B-\u200D\uFEFF]/g;function kt(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(Mo,""),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(fr(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;gr(d)&&l&&!gr(l)&&!fr(l)&&s++;break}default:break}}if(a(t),o.startContainer===document)throw new Error("Offsets out of bound");return o}function No(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(Mo,"").length),y&&(d=l+f.substring(0,r).replace(Mo,"").length),l+=f.replace(Mo,"").length;break}case Node.ELEMENT_NODE:{if(fr(p)&&p.nextSibling){l++;break}!u&&gr(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 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=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(Mo,"").substring(y,f);break}case Node.ELEMENT_NODE:{if(!i&&a===1&&fr(c)&&c.nextSibling){d+=`
8
+ `)}var Lf=({content:t,useLabel:e,copyLabel:n,onCopy:o,onUse:s})=>{let r=x("Markdown",vu),i=(0,ut.useRef)(null),[a,d]=(0,ut.useState)(null),l=(0,ut.useMemo)(()=>{let f=(0,xu.default)(If(t));return Su.default.sanitize(f).replaceAll("</code>",`${Rf(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&&(Tn(f,r.fadeup),o(Fi(a)))},u=f=>{let v=f.target;if(v.tagName==="A"){f.stopPropagation();return}"copyIcon"in v.dataset&&(Tn(v,r.fadeup),o(Fi(v.parentElement)))},m=()=>{!a||!s||(d(null),s(Fi(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)(Mn,{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})]})},pr=Lf;var Hi={};oe(Hi,{enUS:()=>Pf,nlNL:()=>Af});var Pf={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"}]},Af={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 bu={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"),Mf=({cue:t,onCallToAction:e,onRemove:n,onCopy:o,onUse:s})=>{let r=x("WidgetCue",bu),i=P(Hi),a=bt(),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,Cu.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)(pr,{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)(kn,{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"})]})]})},wu=Mf;var On=require("react/jsx-runtime"),Nf=({cues:t})=>{let e=(0,Tu.useDispatch)(),n=me(),o=bt(),s=d=>{e(ou({id:d.rule.id})),e(Vl({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(Es(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,On.jsx)(On.Fragment,{children:t.map(d=>d.isLoading?(0,On.jsx)(ur,{title:d.title},d.rule.id):(0,On.jsx)(wu,{cue:d,onCallToAction:i,onRemove:s,onCopy:r,onUse:a},d.rule.id))})},Eu=Nf;var mr=require("react");var ku={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 Of(t,e){return e.split(".").reduce((n,o)=>!n||typeof n!="object"||!(o in n)?null:n[o],t)}var Ru=({data:t,schema:e})=>{let n=x("WidgetCustomData",ku),o=s=>{Ve(s)};return(0,mr.useEffect)(()=>{E.info("Custom data",t,e)},[t]),(0,_e.jsx)("dl",{className:n.root,children:e.map(s=>{let r=Of(t,s.path);return(0,_e.jsxs)(mr.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)(Io,{})]}):"-"})]},s.label)})})};var ge=require("react"),Lo=require("react-redux");var Ki=require("react/jsx-runtime"),Iu=()=>(0,Ki.jsx)("svg",{focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"ReplayIcon",children:(0,Ki.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 Dn={};oe(Dn,{enUS:()=>Df,nlNL:()=>_f});var Df={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"}]},_f={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 Bi={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"),Ff=3,Hf=({sources:t,onClick:e})=>{let n=P(Dn),o=x("WidgetKnowledgeAssistant",Bi),[s,r]=(0,ge.useState)(!1),i=s?t:t.slice(0,Ff);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})})]})},Kf=({innerRef:t,item:e,index:n,hasKeyboardInput:o,onCopy:s,onUse:r,onSourceClick:i})=>{var d;let a=P(Dn);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)(pr,{content:e.answer.answer,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:s,onUse:o?r:void 0}),(0,F.jsx)(Hf,{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)(kn,{eventName:"knowledge assist feedback",eventData:{question:e.question,isFollowUpQuestion:n>0,isAgent:!0,answer:e.answer.answer},feedbackText:e.answer.answer,feedbackType:"assistant"})]})]})},Ui=(0,ge.createContext)(null),Lu=({children:t})=>{let[e,n]=(0,ge.useState)(null),o=(0,Lo.useSelector)(co("knowledge-assist")),[s,r]=(0,ge.useState)(!1),[i,a]=(0,ge.useState)(null),d=(0,Lo.useDispatch)(),l=Ut(u=>ro({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(yn(e))}};return(0,F.jsx)(Ui.Provider,{value:c,children:t})},Pu=()=>{let t=P(Dn),e=x("WidgetKnowledgeAssistant",Bi),n=(0,ge.useContext)(Ui),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)(Iu,{})})]}):null},Au=()=>{var c,p;let t=P(Dn),e=bt(),n=(0,ge.useRef)(null),o=(0,ge.useContext)(Ui),s=(p=(0,Lo.useSelector)(so((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)(Kf,{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)(ur,{title:o.pendingInput})]})})};var Nu=require("react");var Uf=/(https?:\/\/[^\s]+)/,Mu=t=>t.split(" ").find(e=>Uf.test(e));var ke=require("react/jsx-runtime"),Vf=({suggestion:t,lines:e,onUse:n})=>{var p;let o=t.text||t.url||t.message,s=Mu(o),r=P(yo),i=T("showImages"),a=T("fallbackImage"),d=T("hasKeyboardInput"),l=u=>{u.preventDefault(),u.stopPropagation(),d&&n(o)},c=(0,Nu.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:rr(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")})]})]})},Ou=Vf;var Po=require("react/jsx-runtime"),zf=({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,Po.jsx)(Po.Fragment,{children:e.map(s=>(0,Po.jsx)(Ou,{suggestion:s,lines:t,onUse:r=>o(r,s)},s.text||s.url||s.message))})},Du=zf;var Ao={};oe(Ao,{enUS:()=>Wf,nlNL:()=>jf});var Wf={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"}]},jf={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 Jt={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"),Hu=(t,e)=>{let n=(0,q.useSelector)(se);(0,_n.useEffect)(()=>n?e.every(o=>!!o)?t():()=>{}:()=>{},[...e,n])},qf=({onLogIn:t})=>{let e=x("Widget",Jt),n=T("isEmbedded"),o=T("adminUrl");return(0,R.jsx)("div",{className:e.loginText,children:(0,R.jsx)("div",{children:(0,R.jsx)(qs,{isEmbedded:n,loginUrl:o,onLogIn:t})})},"login")},_u=({text:t})=>{let e=x("Widget",Jt);return(0,R.jsx)("div",{className:e.stateText,children:(0,R.jsx)("div",{children:(0,R.jsx)("p",{children:t})})},"notification")},$f=()=>{let t=P(Ao),e=x("Widget",Jt),n=Ut(()=>Ue({})),o=T("showSummaryCommand"),s=(0,q.useSelector)(co("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")})})},Gf=()=>{let t=P(Ao),e=(0,q.useDispatch)(),n=x("Widget",Jt),o=T("showSearch"),s=T("showSummaryCommand"),r=T("showKnowledgeSearch"),i=(0,q.useSelector)(co("knowledge-assist")),a=T("isEmbedded"),d=(0,q.useSelector)(En("/admin/")),l=me(),c=T("productName"),p=T("hasKeyboardInput"),u=Ut(()=>Ue({})),m=o||s||r||d;return Hu(()=>{if(a)return e(Pi()),()=>{e(Jc())}},[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)(xn,{}),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)(pu,{}),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)(uu,{}),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)(cu,{}),t("linkStudioLogin",{productName:c})]})]})})},Qf=()=>{let t=(0,q.useDispatch)(),e=(0,q.useSelector)(lo),n=(0,q.useSelector)(ql),o=(0,q.useSelector)(iu),s=(0,q.useSelector)(rl),r=(0,q.useSelector)(As),i=(0,q.useSelector)(Fs),a=(0,q.useSelector)(Ft),d=(0,q.useSelector)(Ke);return(0,_n.useEffect)(()=>{!!s&&!n&&E.warn("Custom data provided, but no schema.")},[s,n]),Hu(()=>{e.forEach(({type:l})=>{l==="entities"?t(Ne()):$o.includes(l)||t(Oe(l))})},[t,d,a]),(0,_n.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)(_n.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)(du,{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)(Eu,{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)(Ru,{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)(Du,{lines:u,contentType:l,suggestions:i[l].suggestions.slice(0,p)||[]})})},l)}})})},Xf=({children:t})=>{let e=x("Widget",Jt);return(0,R.jsx)("div",{className:e.footer,children:t})},Zf=({onLogIn:t})=>{let e=P(Ao),n=x("Widget",Jt),o=(0,q.useSelector)(cn),s=(0,q.useSelector)(se),r=(0,q.useSelector)(Va),i=(0,q.useSelector)(Ft);return o===!1?(0,R.jsx)(_u,{text:e("notSupported")}):s===!1?(0,R.jsx)(qf,{onLogIn:t}):!i||!r||s===null?(0,R.jsx)(_u,{text:e("waiting")}):(0,R.jsx)("div",{className:(0,Fu.default)(n.root),"data-testid":"widget",children:(0,R.jsxs)(Lu,{children:[(0,R.jsxs)(Wo,{className:n.sectionList,children:[(0,R.jsx)(Gf,{}),(0,R.jsx)(Qf,{}),(0,R.jsx)(Au,{})]}),(0,R.jsxs)(Xf,{children:[(0,R.jsx)(Pu,{}),(0,R.jsx)($f,{})]})]})})},Ku=Zf;function Fn(t){let e=new Range;return e.selectNodeContents(t),e}function Bu(t,e,n){try{return kt(t,e,n),!0}catch(o){return!1}}function gr(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function fr(t){return"tagName"in t&&t.tagName==="BR"}var Mo=/[\u200B-\u200D\uFEFF]/g;function kt(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(Mo,""),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(fr(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;gr(d)&&l&&!gr(l)&&!fr(l)&&s++;break}default:break}}if(a(t),o.startContainer===document)throw new Error("Offsets out of bound");return o}function No(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(Mo,"").length),y&&(d=l+f.substring(0,r).replace(Mo,"").length),l+=f.replace(Mo,"").length;break}case Node.ELEMENT_NODE:{if(fr(p)&&p.nextSibling){l++;break}!u&&gr(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 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=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(Mo,"").substring(y,f);break}case Node.ELEMENT_NODE:{if(!i&&a===1&&fr(c)&&c.nextSibling){d+=`
9
9
  `;break}!p&&!i&&a===1&&gr(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 Uu=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(Uu||{}),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();ht(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(Uu).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 Vu(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var Yt=class extends pt{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Oo(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!Vu(o)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=n.getBoundingClientRect(),n.deleteContents(),!Vu(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let n=this.getRange();if(n)return No(this.element,n);let o=this.lastKnownSelection;if(o&&Bu(this.element,o.start,o.end))return o;let s=Fn(this.element);return s.collapse(!1),No(this.element,s)}getSelectedText(){let{start:n,end:o}=this.getSelection();return Oo(this.element,kt(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 Jf=["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 zu(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",Jf.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 en=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 zu(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 Wu(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 Yf(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch(e){return t}}var Vi=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()}},zi=class{constructor(e,n,o){this.name=e;this.targetOrigin=n;this.options=o;this.disposeHandlers=[];this.iframe=Wu(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()}},Wi=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 zi(e,this.deepdeskUrl,{debug:!0}):new Vi(e),o=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=Yf(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)}},ju=Wi;function eh(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),{[eh(n)]:H(t[n])}),{}):t}function th(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),{[th(n)]:Y(t[n])}),{}):t}var Hn=class extends Error{constructor(n,o){super(n);this.body=o;this.name="CustomError"}};var ji=t=>new Promise(e=>{setTimeout(e,t)});var Kn=class extends Hn{constructor(){super(...arguments);this.name="ClientError"}},$i=class extends Hn{constructor(){super(...arguments);this.name="ServerError"}},qi=new Map;function nh(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 Rt=class Rt{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(qi.has(i)){o(qi.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 ji(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 ji(u),w();throw M}))});w().then(M=>h(this,null,function*(){let B=yield nh(M);if(delete this.latestRequestByUrl[i],M.status>=500){s(new $i("Server Error",B));return}else if(M.status===401){s(new Kn("Unauthorized",B));return}else if(M.status===403){s(new Kn("Forbidden",B));return}else if(M.status===404){s(new Kn("Not Found",B));return}else if(M.status>=400){s(new Kn("Bad Request",B));return}l&&qi.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 Rt.refreshingToken||(Rt.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{Rt.refreshingToken=null},1e3*60)})),Rt.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))}};Rt.refreshingToken=null;var tn=Rt;var qu;(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={}))})(qu||(qu={}));function hr(t){return b(g({},H(t)),{tags:t.tags})}var nn=class nn{constructor(e,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new tn(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?(nn.exchangeTokenPromise||(nn.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),nn.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 hr(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}`),hr(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 hr(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=>hr(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(ka);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})}};nn.exchangeTokenPromise=null;var mt=nn;var xr=require("@reduxjs/toolkit");var Gu=require("@reduxjs/toolkit");var $u={startTime:null,stopTime:null},Qu=t=>t.handlingTime,Xu=(0,Gu.createSlice)({name:"handlingTime",initialState:$u,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,()=>$u)}}),{handlingTimeStart:Zu,handlingTimeStop:yr,handlingTimeReset:Ju}=Xu.actions,Yu=Xu.reducer;var ep=(t={})=>{let e=g({onAuthError:dn(!1)},t);return n=>o=>s=>("error"in s&&s.error.message==="Unauthorized"&&n.dispatch(e.onAuthError),o(s))};var Sr=require("@reduxjs/toolkit");var vr={list:{keywordMatches:[]},fetchState:"idle"};var on=(0,Sr.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 vr.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return s.getStyleSuggestions({profileCode:a,message:t})})),oh=(0,Sr.createSlice)({name:"styleSuggestions",initialState:vr,reducers:{},extraReducers:t=>{t.addCase(on.pending,e=>{e.fetchState="loading"}).addCase(on.rejected,e=>{e.fetchState="error"}).addCase(on.fulfilled,(e,n)=>{e.fetchState="done",ht(e.list,n.payload)||(e.list=n.payload)}).addCase(Nt,e=>{e.list=vr.list}).addCase(W,()=>vr)}}),tp=oh.reducer;var np=(t={})=>{let e,n=!0,o=g({getStyleSuggestions:on,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 sh(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var op=(t={})=>{let e=g({getTextSuggestions:Oe,getAutocompleteSuggestions:So,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===Hs.toString();if(!p||!l&&!c)return a;let{input:m}=d;return sh(m,i)&&!u||(clearTimeout(n),!e.check(d))||(n=setTimeout(()=>{let v=un(d);v===""?o.dispatch(e.getTextSuggestions("default")):o.dispatch(e.getAutocompleteSuggestions(v))},u?0:e.debounce)),a}};var sp=on.fulfilled.toString();function rh(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 rp=t=>e=>n=>o=>{var l;if(o.type!==sp){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=rh(s,i);o.type===sp&&d.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:d}})};var ih=(0,xr.combineReducers)({assistants:zl,auth:Fa,conversation:za,contentTypes:jl,passwordlessToken:Yc,entities:gd,knowledgeAssistant:Hl,handlingTime:Yu,info:cl,input:ol,settings:Pa,profile:$l,search:hl,styleSuggestions:tp,ui:sc,rules:su,textSuggestions:Kd});function ip(t){return(0,xr.configureStore)({reducer:ih,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI}},serializableCheck:!1}),ep(),op({debounce:200}),np({debounce:500}),rp(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var ah=t=>{var e,n;return(n=(e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())!=null?n:"unknown"},lh=t=>e=>n=>o=>{var a,d,l,c,p,u,m;let s=e.getState(),r=Pr("inlineSuggestions")(s);switch(o.type){case dn.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 Nt.toString():t.logSendMessage(o.payload);break;case Zt.fulfilled.toString():o.isBroadcasted||t.broadcast(Fr,o,!1),(c=o.payload.options)!=null&&c.shouldEmit&&t.emit("cues",o.payload.cues);break;case Es.toString():t.emit("call-to-action",{cue:o.payload});break;case Ye.fulfilled.toString():o.isBroadcasted||t.broadcast(Hr,o,!1);break;default:break}let i=n(o);switch(o.type){case Nt.toString():t.handleAfterSendMessage(o.payload);break;case bo.toString():t.onUpdateShowTabHint(o.payload);break;case yr.toString():t.logHandlingTime();break;case"analytics/logEvent/fulfilled":{t.emit("event",o.meta.arg);break}case Yo.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:ah(o.payload.suggestion)},o.payload),{replace:o.payload.replace==="selection"?{start:y,end:f}:{start:0,end:f}})),r&&e.dispatch(yt([]));break}case es.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 yt.toString():{r&&o.payload.length>0&&e.dispatch(ts(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},ap=lh;var lp=require("@reduxjs/toolkit");function Gi(t){return t.toISOString().replace("T"," ").replace("Z","")}var dh=(t,e)=>e.version,dp=(0,lp.createSelector)([gn,Ke,Qu,dh],(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:Gi(s),timeStop:Gi(r)}});function cp(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 Qi(t,e){var r;let n=t.closest(e);if(n)return n;let o=t.getRootNode().host;if(o instanceof HTMLElement)return Qi(o,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?Qi(s,e):null}function up(t,e){return Qi(t,e)}function pp(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function ch(t){return typeof t=="object"&&t!==null&&"tagName"in t}function br(t){return ch(t)&&(Xt(t)||Gs(t))}var gp,Ge=new Map,uh=["bottom","height","left","right","top","width"],mp=(t,e)=>!t&&!e?!1:t&&!e||!t&&e?!0:uh.some(n=>t[n]!==e[n]);function fp(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,...fp(e)]:[]}function hp(t,e){return!t||!e?null:b(g({},t),{top:t.top+e.top,left:t.left+e.left})}var Cr=!1,yp=()=>{Cr=!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();mp(o,e.rect)&&(e.rect=o,t.push(e))}),t.forEach(e=>{let n=e.parentRects?e.parentRects.reduce(hp,e.rect):e.rect;mp(n,e.totalRect)&&e.callbacks.forEach(o=>o(n)),e.totalRect=n}),Ge.size===0){Cr=!1;return}gp=window.requestAnimationFrame(yp)};function Xi(t,e){let n=fp(t),o=[],s=n.map((r,i)=>Xi(r,a=>{o[i]=a;let d=Ge.get(t);if(!d)return;let l=o.reduce(hp,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&&!Cr&&yp()},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(gp),Cr=!1)}}}}var vp,Qe=new Map,Sp=()=>{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&&(vp=window.requestAnimationFrame(Sp))};function xp(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&&Sp()},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(vp)}}}}var Zi=["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 Ji(t,e,n){return n.forEach(o=>{e.style[o]=t[o]})}function Bn(t){return parseFloat(t)}function wr(t){return Math.round(t*1e6)}function bp(t){return t/1e6}function Yi(t,e,n){if(t.boxSizing==="content-box")return;let{clientWidth:o}=e,s=Bn(t.width),r=Bn(t.borderLeftWidth),i=Bn(t.borderRightWidth),a=Bn(t.paddingRight),d=bp(wr(s)-wr(r)-wr(i)),l=bp(wr(o));if(d-l>2){let c=d-l;n.style.paddingRight=`${a+c}px`}}function Do(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",$t(n);let o=window.getComputedStyle(t),s=!0,r=()=>{n.scrollTop=t.scrollTop};Ji(o,n,Zi),Yi(o,t,n),e.mirrorOverflow&&(n.style.overflow="hidden",t.addEventListener("scroll",r));let i=xp(t,()=>{Ji(o,n,Zi),Yi(o,t,n),r(),setTimeout(r,0)}),a,d=!0,l=Xi(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(Ji(o,n,Zi),Yi(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=Bn(y.borderTopWidth),v=Bn(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 Cp=(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 ph(t){return t.offsetParent!==null}function wp(t){if(!ph(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 Tr(t,e,n=100){let o=wp(t);e({isVisible:o});let s=setInterval(()=>{let r=wp(t);r!==o&&(o=r,e({isVisible:o}))},n);return()=>{clearTimeout(s)}}var G=require("react/jsx-runtime");var Tp=Cp("showTabHint",!0),Un=class Un{constructor({deepdeskUrl:e,version:n=Un.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=Un.count++;let l={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[ap({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=>Tp.update(c),sendEvent:(c,p)=>this.deepdeskApi.sendEvent(c,p)})]};this.store=ip(l),this.broadcastEvents=new ju({debug:!0,deepdeskUrl:d,eventMap:yl(this.store),createCustomChannel:a}),this.store.dispatch(bo(Tp.value())),this.store.dispatch(Go({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(dn(null)),this.store.dispatch(Ze()),new Promise(e=>{let n=this.store.subscribe(()=>{let o=this.store.getState();se(o)&&Aa(o)!=="loading"&&(n(),e())});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return h(this,null,function*(){return(yield this.store.dispatch(Ze())).payload})}isConversationSupported(e,n){return h(this,null,function*(){return(yield this.store.dispatch(Ar({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(Qo(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(Mr(e))).payload})}postMessages(e){return h(this,null,function*(){return(yield this.store.dispatch(Jo(e))).payload})}updateConversation(e){return h(this,null,function*(){return(yield this.store.dispatch(Zo(e))).payload})}resetConversation(){this.store.dispatch(W()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(e){this.store.dispatch(Go(e))}setVisitorInfo(e){this.store.dispatch(al(e))}setCustomData(e){this.store.dispatch(ll(e))}setAgentInfo(e,n){return h(this,null,function*(){yield this.store.dispatch($n(g(g({},e),n)))})}setAgentSettings(e){return h(this,null,function*(){yield this.store.dispatch(Or(e))})}getAgentSettings(){return h(this,null,function*(){return(yield this.store.dispatch(Dr())).payload})}refresh(){return h(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(ns({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let e=[];return this.store.dispatch(Hs()),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=eu){return(yield this.store.dispatch(Zt({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(Xa(Nr(e))),e.key!=="Tab"&&!d))return;let p=()=>{n||!c||i&&(e.shiftKey||(this.store.dispatch(Ya()),e.preventDefault()))},u=()=>{n||!c||a&&r<=0||i&&(e.shiftKey||(this.store.dispatch(el()),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(ts(-1)),this.store.dispatch(wt({collapse:!0})),this.store.dispatch(nc(!0)),e.preventDefault());break}case"Tab":{e.preventDefault();let m=pn(this.state);if(!m)return;this.store.dispatch(bo(!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=pn(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=pn(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(wt({collapse:!1}))}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(yt([]))}handlingTimeStart(){this.state.handlingTime.startTime||(E.info("Start handling time"),this.store.dispatch(Zu()))}handlingTimeStop(){this.state.handlingTime.startTime&&(E.info("Stop handling time"),this.store.dispatch(yr()))}logSendMessage(e){let n=cp("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=dp(this.state,{version:this.version});e&&(this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Ju()))}notifySubmit(e={}){var n;this.shouldAbort()||(this.store.dispatch(Nt((n=e.text)!=null?n:this.state.input.text)),this.store.dispatch(nl()))}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(dl(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]=Do(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]=Do(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 $t(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(tl(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(!br(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),$t(e),this.inputMediator=y||(Xt(e)?new en(e):new Yt(e)),this.inputMediator.on("change",({plainText:w,rawHTML:N})=>{this.store.dispatch(ns({text:w,html:N}))}),this.inputMediator.on("keyup",w=>{this.store.dispatch(Za(Nr(w)))}),this.inputMediator.on("keydown",w=>{this.handleKeyDown(w)}),this.inputMediator.on("paste",({pastedText:w,selectionText:N})=>{this.store.dispatch(Ja({text:w,selectionText:N}))}),this.inputMediator.on("cut",({selectionText:w})=>{this.store.dispatch(Qa(w))});let S;this.inputMediator.on("selection",w=>{clearTimeout(S),w===null?S=setTimeout(()=>{w!==null&&this.store.dispatch(os(w))},500):this.store.dispatch(os(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(Vs(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Vs(!0))});let I=f&&up(e,f)||void 0;if(C){let{customStyles:w,appendOverlayTo:N}=n,M=this.createInlineContainer(e,"deepdesk-caret");(0,Re.render)((0,G.jsx)(Qt,{store:this.store,customStyles:w,children:(0,G.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(uc,{})})}),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)(Qt,{store:this.store,customStyles:w,children:(0,G.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(Jd,{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)(Qt,{store:this.store,customStyles:o,children:(0,G.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(Xc,{inputElement:e})})}),w),(0,Re.render)((0,G.jsx)(Qt,{store:this.store,customStyles:o,children:(0,G.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(Cc,{onLogIn:()=>this.loginViaPopup().catch(M=>E.warn(M.message))})})}),N)}(0,Re.render)((0,G.jsx)(Qt,{store:this.store,customStyles:o,children:(0,G.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(jd,{})})}),this.createContainer("deepdesk-overlays")),this.store.dispatch(ns({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(os(this.inputMediator.getSelection())),this.store.dispatch(Vs(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)(Qt,{store:this.store,customStyles:o,children:(0,G.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(Ku,{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=Tr(e,({isVisible:o})=>{o?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){pp(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(ao());let e=Ft(this.state);e&&(yield this.store.dispatch(no()),this.store.dispatch(Go({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(Qn),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=lo(this.state);try{n.forEach(({type:o})=>{o==="entities"?this.store.dispatch(Ne()):$o.includes(o)||this.store.dispatch(Oe(o))})}catch(o){this.handleError(o)}})}};Un.version="14.3.1-beta.4",Un.count=0;var _o=Un;function mh(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 Ep(t,e){return h(this,null,function*(){let n=yield mh(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 kp(t,e,n){return h(this,null,function*(){yield new mt(t).authenticateWithKey(e,n)})}function Rp(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function Ip(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 Lp(o,s){return h(this,arguments,function*(t,e,n={}){let r=n.replace?kt(t,n.replace.start,n.replace.end):Fn(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 Uu=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(Uu||{}),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();ht(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(Uu).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 Vu(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var Yt=class extends pt{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Oo(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!Vu(o)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=n.getBoundingClientRect(),n.deleteContents(),!Vu(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let n=this.getRange();if(n)return No(this.element,n);let o=this.lastKnownSelection;if(o&&Bu(this.element,o.start,o.end))return o;let s=Fn(this.element);return s.collapse(!1),No(this.element,s)}getSelectedText(){let{start:n,end:o}=this.getSelection();return Oo(this.element,kt(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 Jf=["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 zu(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",Jf.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 en=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 zu(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 Wu(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 Yf(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch(e){return t}}var Vi=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()}},zi=class{constructor(e,n,o){this.name=e;this.targetOrigin=n;this.options=o;this.disposeHandlers=[];this.iframe=Wu(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()}},Wi=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 zi(e,this.deepdeskUrl,{debug:!0}):new Vi(e),o=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=Yf(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)}},ju=Wi;function eh(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),{[eh(n)]:H(t[n])}),{}):t}function th(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),{[th(n)]:Y(t[n])}),{}):t}var Hn=class extends Error{constructor(n,o){super(n);this.body=o;this.name="CustomError"}};var ji=t=>new Promise(e=>{setTimeout(e,t)});var Kn=class extends Hn{constructor(){super(...arguments);this.name="ClientError"}},$i=class extends Hn{constructor(){super(...arguments);this.name="ServerError"}},qi=new Map;function nh(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 Rt=class Rt{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(qi.has(i)){o(qi.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 ji(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 ji(u),w();throw M}))});w().then(M=>h(this,null,function*(){let B=yield nh(M);if(delete this.latestRequestByUrl[i],M.status>=500){s(new $i("Server Error",B));return}else if(M.status===401){s(new Kn("Unauthorized",B));return}else if(M.status===403){s(new Kn("Forbidden",B));return}else if(M.status===404){s(new Kn("Not Found",B));return}else if(M.status>=400){s(new Kn("Bad Request",B));return}l&&qi.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 Rt.refreshingToken||(Rt.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{Rt.refreshingToken=null},1e3*60)})),Rt.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))}};Rt.refreshingToken=null;var tn=Rt;var qu;(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={}))})(qu||(qu={}));function hr(t){return b(g({},H(t)),{tags:t.tags})}var nn=class nn{constructor(e,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new tn(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?(nn.exchangeTokenPromise||(nn.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),nn.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 hr(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}`),hr(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 hr(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=>hr(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(ka);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})}};nn.exchangeTokenPromise=null;var mt=nn;var xr=require("@reduxjs/toolkit");var Gu=require("@reduxjs/toolkit");var $u={startTime:null,stopTime:null},Qu=t=>t.handlingTime,Xu=(0,Gu.createSlice)({name:"handlingTime",initialState:$u,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,()=>$u)}}),{handlingTimeStart:Zu,handlingTimeStop:yr,handlingTimeReset:Ju}=Xu.actions,Yu=Xu.reducer;var ep=(t={})=>{let e=g({onAuthError:dn(!1)},t);return n=>o=>s=>("error"in s&&s.error.message==="Unauthorized"&&n.dispatch(e.onAuthError),o(s))};var Sr=require("@reduxjs/toolkit");var vr={list:{keywordMatches:[]},fetchState:"idle"};var on=(0,Sr.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 vr.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return s.getStyleSuggestions({profileCode:a,message:t})})),oh=(0,Sr.createSlice)({name:"styleSuggestions",initialState:vr,reducers:{},extraReducers:t=>{t.addCase(on.pending,e=>{e.fetchState="loading"}).addCase(on.rejected,e=>{e.fetchState="error"}).addCase(on.fulfilled,(e,n)=>{e.fetchState="done",ht(e.list,n.payload)||(e.list=n.payload)}).addCase(Nt,e=>{e.list=vr.list}).addCase(W,()=>vr)}}),tp=oh.reducer;var np=(t={})=>{let e,n=!0,o=g({getStyleSuggestions:on,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 sh(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var op=(t={})=>{let e=g({getTextSuggestions:Oe,getAutocompleteSuggestions:So,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===Hs.toString();if(!p||!l&&!c)return a;let{input:m}=d;return sh(m,i)&&!u||(clearTimeout(n),!e.check(d))||(n=setTimeout(()=>{let v=un(d);v===""?o.dispatch(e.getTextSuggestions("default")):o.dispatch(e.getAutocompleteSuggestions(v))},u?0:e.debounce)),a}};var sp=on.fulfilled.toString();function rh(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 rp=t=>e=>n=>o=>{var l;if(o.type!==sp){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=rh(s,i);o.type===sp&&d.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:d}})};var ih=(0,xr.combineReducers)({assistants:zl,auth:Fa,conversation:za,contentTypes:jl,passwordlessToken:Yc,entities:gd,knowledgeAssistant:Hl,handlingTime:Yu,info:cl,input:ol,settings:Pa,profile:$l,search:hl,styleSuggestions:tp,ui:sc,rules:su,textSuggestions:Kd});function ip(t){return(0,xr.configureStore)({reducer:ih,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI}},serializableCheck:!1}),ep(),op({debounce:200}),np({debounce:500}),rp(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var ah=t=>{var e,n;return(n=(e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())!=null?n:"unknown"},lh=t=>e=>n=>o=>{var a,d,l,c,p,u,m;let s=e.getState(),r=Pr("inlineSuggestions")(s);switch(o.type){case dn.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 Nt.toString():t.logSendMessage(o.payload);break;case Zt.fulfilled.toString():o.isBroadcasted||t.broadcast(Fr,o,!1),(c=o.payload.options)!=null&&c.shouldEmit&&t.emit("cues",o.payload.cues);break;case Es.toString():t.emit("call-to-action",{cue:o.payload});break;case Ye.fulfilled.toString():o.isBroadcasted||t.broadcast(Hr,o,!1);break;default:break}let i=n(o);switch(o.type){case Nt.toString():t.handleAfterSendMessage(o.payload);break;case bo.toString():t.onUpdateShowTabHint(o.payload);break;case yr.toString():t.logHandlingTime();break;case"analytics/logEvent/fulfilled":{t.emit("event",o.meta.arg);break}case Yo.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:ah(o.payload.suggestion)},o.payload),{replace:o.payload.replace==="selection"?{start:y,end:f}:{start:0,end:f}})),r&&e.dispatch(yt([]));break}case es.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 yt.toString():{r&&o.payload.length>0&&e.dispatch(ts(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},ap=lh;var lp=require("@reduxjs/toolkit");function Gi(t){return t.toISOString().replace("T"," ").replace("Z","")}var dh=(t,e)=>e.version,dp=(0,lp.createSelector)([gn,Ke,Qu,dh],(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:Gi(s),timeStop:Gi(r)}});function cp(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 Qi(t,e){var r;let n=t.closest(e);if(n)return n;let o=t.getRootNode().host;if(o instanceof HTMLElement)return Qi(o,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?Qi(s,e):null}function up(t,e){return Qi(t,e)}function pp(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function ch(t){return typeof t=="object"&&t!==null&&"tagName"in t}function br(t){return ch(t)&&(Xt(t)||Gs(t))}var gp,Ge=new Map,uh=["bottom","height","left","right","top","width"],mp=(t,e)=>!t&&!e?!1:t&&!e||!t&&e?!0:uh.some(n=>t[n]!==e[n]);function fp(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,...fp(e)]:[]}function hp(t,e){return!t||!e?null:b(g({},t),{top:t.top+e.top,left:t.left+e.left})}var Cr=!1,yp=()=>{Cr=!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();mp(o,e.rect)&&(e.rect=o,t.push(e))}),t.forEach(e=>{let n=e.parentRects?e.parentRects.reduce(hp,e.rect):e.rect;mp(n,e.totalRect)&&e.callbacks.forEach(o=>o(n)),e.totalRect=n}),Ge.size===0){Cr=!1;return}gp=window.requestAnimationFrame(yp)};function Xi(t,e){let n=fp(t),o=[],s=n.map((r,i)=>Xi(r,a=>{o[i]=a;let d=Ge.get(t);if(!d)return;let l=o.reduce(hp,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&&!Cr&&yp()},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(gp),Cr=!1)}}}}var vp,Qe=new Map,Sp=()=>{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&&(vp=window.requestAnimationFrame(Sp))};function xp(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&&Sp()},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(vp)}}}}var Zi=["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 Ji(t,e,n){return n.forEach(o=>{e.style[o]=t[o]})}function Bn(t){return parseFloat(t)}function wr(t){return Math.round(t*1e6)}function bp(t){return t/1e6}function Yi(t,e,n){if(t.boxSizing==="content-box")return;let{clientWidth:o}=e,s=Bn(t.width),r=Bn(t.borderLeftWidth),i=Bn(t.borderRightWidth),a=Bn(t.paddingRight),d=bp(wr(s)-wr(r)-wr(i)),l=bp(wr(o));if(d-l>2){let c=d-l;n.style.paddingRight=`${a+c}px`}}function Do(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",$t(n);let o=window.getComputedStyle(t),s=!0,r=()=>{n.scrollTop=t.scrollTop};Ji(o,n,Zi),Yi(o,t,n),e.mirrorOverflow&&(n.style.overflow="hidden",t.addEventListener("scroll",r));let i=xp(t,()=>{Ji(o,n,Zi),Yi(o,t,n),r(),setTimeout(r,0)}),a,d=!0,l=Xi(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(Ji(o,n,Zi),Yi(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=Bn(y.borderTopWidth),v=Bn(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 Cp=(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 ph(t){return t.offsetParent!==null}function wp(t){if(!ph(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 Tr(t,e,n=100){let o=wp(t);e({isVisible:o});let s=setInterval(()=>{let r=wp(t);r!==o&&(o=r,e({isVisible:o}))},n);return()=>{clearTimeout(s)}}var G=require("react/jsx-runtime");var Tp=Cp("showTabHint",!0),Un=class Un{constructor({deepdeskUrl:e,version:n=Un.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=Un.count++;let l={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[ap({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=>Tp.update(c),sendEvent:(c,p)=>this.deepdeskApi.sendEvent(c,p)})]};this.store=ip(l),this.broadcastEvents=new ju({debug:!0,deepdeskUrl:d,eventMap:yl(this.store),createCustomChannel:a}),this.store.dispatch(bo(Tp.value())),this.store.dispatch(Go({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(dn(null)),this.store.dispatch(Ze()),new Promise(e=>{let n=this.store.subscribe(()=>{let o=this.store.getState();se(o)&&Aa(o)!=="loading"&&(n(),e())});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return h(this,null,function*(){return(yield this.store.dispatch(Ze())).payload})}isConversationSupported(e,n){return h(this,null,function*(){return(yield this.store.dispatch(Ar({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(Qo(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(Mr(e))).payload})}postMessages(e){return h(this,null,function*(){return(yield this.store.dispatch(Jo(e))).payload})}updateConversation(e){return h(this,null,function*(){return(yield this.store.dispatch(Zo(e))).payload})}resetConversation(){this.store.dispatch(W()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(e){this.store.dispatch(Go(e))}setVisitorInfo(e){this.store.dispatch(al(e))}setCustomData(e){this.store.dispatch(ll(e))}setAgentInfo(e,n){return h(this,null,function*(){yield this.store.dispatch($n(g(g({},e),n)))})}setAgentSettings(e){return h(this,null,function*(){yield this.store.dispatch(Or(e))})}getAgentSettings(){return h(this,null,function*(){return(yield this.store.dispatch(Dr())).payload})}refresh(){return h(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(ns({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let e=[];return this.store.dispatch(Hs()),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=eu){return(yield this.store.dispatch(Zt({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(Xa(Nr(e))),e.key!=="Tab"&&!d))return;let p=()=>{n||!c||i&&(e.shiftKey||(this.store.dispatch(Ya()),e.preventDefault()))},u=()=>{n||!c||a&&r<=0||i&&(e.shiftKey||(this.store.dispatch(el()),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(ts(-1)),this.store.dispatch(wt({collapse:!0})),this.store.dispatch(nc(!0)),e.preventDefault());break}case"Tab":{e.preventDefault();let m=pn(this.state);if(!m)return;this.store.dispatch(bo(!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=pn(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=pn(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(wt({collapse:!1}))}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(yt([]))}handlingTimeStart(){this.state.handlingTime.startTime||(E.info("Start handling time"),this.store.dispatch(Zu()))}handlingTimeStop(){this.state.handlingTime.startTime&&(E.info("Stop handling time"),this.store.dispatch(yr()))}logSendMessage(e){let n=cp("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=dp(this.state,{version:this.version});e&&(this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Ju()))}notifySubmit(e={}){var n;this.shouldAbort()||(this.store.dispatch(Nt((n=e.text)!=null?n:this.state.input.text)),this.store.dispatch(nl()))}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(dl(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]=Do(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]=Do(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 $t(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(tl(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(!br(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),$t(e),this.inputMediator=y||(Xt(e)?new en(e):new Yt(e)),this.inputMediator.on("change",({plainText:w,rawHTML:N})=>{this.store.dispatch(ns({text:w,html:N}))}),this.inputMediator.on("keyup",w=>{this.store.dispatch(Za(Nr(w)))}),this.inputMediator.on("keydown",w=>{this.handleKeyDown(w)}),this.inputMediator.on("paste",({pastedText:w,selectionText:N})=>{this.store.dispatch(Ja({text:w,selectionText:N}))}),this.inputMediator.on("cut",({selectionText:w})=>{this.store.dispatch(Qa(w))});let S;this.inputMediator.on("selection",w=>{clearTimeout(S),w===null?S=setTimeout(()=>{w!==null&&this.store.dispatch(os(w))},500):this.store.dispatch(os(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(Vs(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Vs(!0))});let I=f&&up(e,f)||void 0;if(C){let{customStyles:w,appendOverlayTo:N}=n,M=this.createInlineContainer(e,"deepdesk-caret");(0,Re.render)((0,G.jsx)(Qt,{store:this.store,customStyles:w,children:(0,G.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(uc,{})})}),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)(Qt,{store:this.store,customStyles:w,children:(0,G.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(Jd,{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)(Qt,{store:this.store,customStyles:o,children:(0,G.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(Xc,{inputElement:e})})}),w),(0,Re.render)((0,G.jsx)(Qt,{store:this.store,customStyles:o,children:(0,G.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(Cc,{onLogIn:()=>this.loginViaPopup().catch(M=>E.warn(M.message))})})}),N)}(0,Re.render)((0,G.jsx)(Qt,{store:this.store,customStyles:o,children:(0,G.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(jd,{})})}),this.createContainer("deepdesk-overlays")),this.store.dispatch(ns({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(os(this.inputMediator.getSelection())),this.store.dispatch(Vs(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)(Qt,{store:this.store,customStyles:o,children:(0,G.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,G.jsx)(Ku,{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=Tr(e,({isVisible:o})=>{o?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){pp(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(ao());let e=Ft(this.state);e&&(yield this.store.dispatch(no()),this.store.dispatch(Go({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(Qn),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=lo(this.state);try{n.forEach(({type:o})=>{o==="entities"?this.store.dispatch(Ne()):$o.includes(o)||this.store.dispatch(Oe(o))})}catch(o){this.handleError(o)}})}};Un.version="14.3.1-beta.6",Un.count=0;var _o=Un;function mh(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 Ep(t,e){return h(this,null,function*(){let n=yield mh(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 kp(t,e,n){return h(this,null,function*(){yield new mt(t).authenticateWithKey(e,n)})}function Rp(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function Ip(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 Lp(o,s){return h(this,arguments,function*(t,e,n={}){let r=n.replace?kt(t,n.replace.start,n.replace.end):Fn(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?kt(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 gh(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 fh(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 Pp(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):Pp(n,e)}function Ap(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?gh(e):fh(e);n?Pp(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});