@deepdesk/deepdesk-sdk 11.5.5-beta.3 → 11.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.iife.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -7,6 +7,6 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
|
7
7
|
c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});var li=require("react/jsx-runtime"),Zg={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},qd=({className:t,color:e})=>(0,li.jsx)("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,li.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:Zg[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 di={};j(di,{enUS:()=>Jg,nlNL:()=>Yg});var Jg={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},Yg={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Qd=require("react-redux"),Wt=require("react/jsx-runtime"),Zd=({onLogIn:t})=>{let e=k(di),o=C("floatingMenu"),n=C("productName"),s=(0,Qd.useDispatch)(),r=(0,Xd.useSelector)(Q),i=h("FloatingMenu",Gd);if(r===null||o===!1)return null;let a=()=>{r===!0?s(le(!0)):t()};return(0,Wt.jsxs)("button",{className:(0,jd.default)(i.root,{[i.isLoggedIn]:r,[i.isLoggedOut]:!r}),onClick:a,children:[(0,Wt.jsx)("div",{className:i.text,children:e(r?"search":"signin",{productName:n})}),(0,Wt.jsxs)("div",{className:i.icon,children:[(0,Wt.jsx)(qd,{className:i.logo,color:"pink"}),r===!1&&(0,Wt.jsx)($d,{className:i.lock})]})]})};var Hs=require("react"),Ye=require("react-redux");var Jd=require("react");function St(t){(0,Jd.useEffect)(()=>{let e=o=>{o.isWithinRoot||t(o)};return document.body.addEventListener("mouseup",e),()=>{document.body.removeEventListener("mouseup",e)}},[t])}function $t(t){t.addEventListener("mouseup",e=>{e.isWithinRoot=!0},!0)}function xo(t){let{showMidSentenceSuggestions:e,showSuggestionsBeforePattern:o,showSuggestionsAfterPattern:n}=t.settings,{text:s,selection:r}=t.input.userCommitted;return r.start!==r.end?!1:r.end>=s.length?!0:e?o&&new RegExp(o).test(s.substring(r.end))||n&&new RegExp(n).test(s.substring(0,r.end))?!0:o===!1&&n===!1:!1}var Yd=require("@reduxjs/toolkit"),ef={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var Ds=({ui:t})=>t.overlayCollapsed;var ec=(0,Yd.createSlice)({name:"ui",initialState:ef,reducers:{setShowTabHint(t,e){t.showTabHint=e.payload},setInputHasFocus(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:rn,setInputHasFocus:ci,setOverlayCollapsed:xt,setOpenOverlayWhenTyping:tc,setOverlayCollapsedUserOverwrite:oc}=ec.actions,nc=ec.reducer;var _s=require("react");var ac=require("interweave"),bo=require("react"),an=require("react-redux");var sc=require("react");function rc(t,e,o){(0,sc.useEffect)(()=>{let n=t.current;return n?(n.addEventListener(e,o),()=>{n.removeEventListener(e,o)}):()=>{}},[t,e,o])}var ic={root:"dd-1MBCO",actions:"dd--x4cy",badge:"dd-4Fpkz",formattedText:"dd-EzvTB"};var qt=require("react/jsx-runtime"),of=["search","personal-collection-search","search-autocomplete"];function nf(t,e,o,n={}){let s="";return of.includes(e)?s=_l(Wr(t,o,{stripAgentPart:!0}),n.searchKeywords??[o]):s=Wr(t,o,n),n.placeholders===!0&&(s=Fl(s)),s}var sf=()=>{},rf=({index:t,selected:e,suggestion:o})=>{let n=C("inlineSuggestions"),s=(0,an.useSelector)(ro),r=C("enableSuggestionFeedback"),i=(0,an.useSelector)(p=>p.input.text),a=(0,an.useDispatch)(),l=h("TextSuggestion",ic),d=(0,bo.useRef)(null);(0,bo.useEffect)(()=>{let p=setTimeout(()=>{a(za({text:o.text,suggestion:o}))},500);return()=>{clearTimeout(p)}},[o]),rc(d,"click",()=>{a(ft(t)),a(Oe({suggestion:o,text:o.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let c=(0,bo.useMemo)(()=>nf(o.text,o.source,s,{stripAgentPart:n,placeholders:!0,searchKeywords:o.searchKeywords}),[n,o.text,o.source,s,o.searchKeywords]);return o.source==="gpt"&&!n?null:(0,qt.jsxs)("div",{className:l.root,onMouseEnter:()=>a(ft(t)),children:[(0,qt.jsx)(M,{ref:d,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:sf,children:(0,qt.jsx)(ac.Interweave,{containerTagName:"div",noWrap:!1,tagName:"span",className:l.formattedText,content:c})}),e&&r&&(0,qt.jsx)("div",{className:l.actions,children:(0,qt.jsx)(Ns,{source:"overlay",context:i,suggestion:o})})]})},lc=rf;var ui=require("react/jsx-runtime"),af=({suggestions:t,selectedIndex:e,reverse:o})=>{let n=(0,_s.useMemo)(()=>{let s=t.map((r,i)=>(0,ui.jsx)(lc,{index:i,selected:i===e,suggestion:r},`${r.text}-${r.source}`));return o?s.reverse():s},[t,e,o]);return(0,ui.jsx)(_s.Fragment,{children:n})},Fs=af;var dc={root:"dd-PfvRI",paper:"dd-HYlyY"};var ln=require("react/jsx-runtime"),lf=({textSuggestions:t,selectedIndex:e})=>{let o=(0,Hs.useRef)(null),n=h("InlineSuggestionsOverlay",dc),s=(0,Ye.useSelector)(xo),r=(0,Ye.useDispatch)(),i=(0,Ye.useSelector)(Q),a=(0,Ye.useSelector)(so),l=(0,Ye.useSelector)(Ds),d=C("showTextSuggestions");return St(()=>{setTimeout(()=>{r(xt({collapse:!0,skipWhenInputFocus:!0}))})}),(0,Hs.useEffect)(()=>{let c=o.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`}),l||!s||!d||t.length===0||i!==!0||a===!1?null:(0,ln.jsx)("div",{className:n.root,"data-variant":"inline",children:(0,ln.jsx)("div",{ref:o,className:n.paper,children:(0,ln.jsx)(re,{children:(0,ln.jsx)(Fs,{suggestions:t,selectedIndex:e})})})})},df=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),cc=(0,Ye.connect)(df)(lf);var uc=require("react-redux");var dn=require("react/jsx-runtime"),cf=({children:t})=>{let o=C("locale").replace("-","");return(0,dn.jsx)(Br.Provider,{value:o,children:t})},uf=({store:t,customStyles:e={},children:o})=>(0,dn.jsx)(uc.Provider,{store:t,children:(0,dn.jsx)(cf,{children:(0,dn.jsx)(No.Provider,{value:e,children:o})})}),Gt=uf;var Ks=R(require("classnames")),Co=require("react"),tt=require("react-redux");var pc=require("react");function mc(t,e){let[o,n]=(0,pc.useState)(()=>{if(typeof window>"u")return e;try{let r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return b.error(r),e}});return[o,r=>{try{let i=r instanceof Function?r(o):r;n(i),typeof window<"u"&&window.localStorage.setItem(t,JSON.stringify(i))}catch(i){b.error(i)}}]}var gc=()=>/Mac/i.test(navigator.platform);var hc=R(require("classnames")),et=require("react");var pi={};j(pi,{enUS:()=>pf,nlNL:()=>mf});var pf={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"}]}]},mf={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 fc={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};var bt=require("react/jsx-runtime"),mi=(t,e,o)=>n=>(0,bt.jsx)("button",{className:t.anchorButton,type:"button",value:e,onClick:o,children:n},e),gf=({className:t,loginUrl:e,isEmbedded:o,onSnooze:n,onLogIn:s})=>{let r=k(pi),i=fe(),a=h("Login",fc),l=C("productName"),d=(0,et.useCallback)(x=>{x.preventDefault(),n&&n(parseInt(x.target.value,10))},[]),c=(0,et.useCallback)(x=>{x.preventDefault(),i.send(ao,!0)},[e]),p=(0,et.useMemo)(()=>x=>(0,bt.jsx)("a",{onClick:S=>{S.preventDefault(),s()},href:e,className:a.anchor,target:"_blank",rel:"noreferrer",children:x},"login"),[e]),u=(0,et.useCallback)(x=>(0,bt.jsx)("button",{type:"button",className:a.anchorButton,onClick:c,children:x},"prompt"),[c]),{min:m,hour:f,day:g}=(0,et.useMemo)(()=>({min:mi(a,60*10,d),hour:mi(a,60*60,d),day:mi(a,60*60*12,d)}),[]);return(0,bt.jsxs)("div",{className:(0,hc.default)(t,a.root),children:[r("loginPlease",{login:o?u:p,productName:l}),n&&(0,bt.jsxs)(et.Fragment,{children:[(0,bt.jsx)("br",{}),r("snooze",{min:m,hour:f,day:g})]})]})},Bs=gf;var vc=require("react-redux");var yc={root:"dd-DoQhb",text:"dd-Jwnev"};var cn=require("react/jsx-runtime"),ff=({title:t})=>{let e=h("SearchTrigger",yc),o=(0,vc.useDispatch)();return(0,cn.jsxs)("button",{type:"button",className:e.root,onClick:()=>o(le(!0)),children:[(0,cn.jsx)(uo,{}),(0,cn.jsx)("span",{className:e.text,children:t})]})},Sc=ff;var gi={};j(gi,{enUS:()=>hf,nlNL:()=>yf});var hf={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"}]},yf={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 xc={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 F=require("react/jsx-runtime"),vf=({textSuggestions:t,selectedIndex:e,onLogIn:o})=>{let n=h("SuggestionsOverlay",xc),s=k(gi),r=(0,tt.useSelector)(xo),i=Ha(),a=(0,tt.useDispatch)(),l=(0,Co.useRef)(null),d=C("searchTriggerKey"),c=C("productName"),p=(0,tt.useSelector)(Ds),u=(0,tt.useSelector)(Q),m=(0,tt.useSelector)(so),[f,g]=(0,Co.useState)(null),x=C("showSearch"),y=C("showTextSuggestions"),S=C("adminUrl"),v=C("isEmbedded"),[I,w]=mc("dd-snooze-until-ms",0),P=p||I>Date.now(),N=t.filter(L=>L.source!=="gpt").length,te=()=>{P&&w(0),a(oc(!P))},q=L=>{let B=Date.now()+L*1e3;w(B),b.info(`Snooze until: ${new Date(B)}`),a(xt({collapse:!0}))};return(0,Co.useEffect)(()=>{N===0&&g(null)},[t,N]),St(()=>{a(xt({collapse:!0,skipWhenInputFocus:!0}))}),u===null||m===!1?null:u===!1?(0,F.jsxs)("div",{ref:l,className:(0,Ks.default)(n.root,{[n.isCollapsed]:P}),children:[!P&&(0,F.jsxs)("div",{className:n.triggers,children:[(0,F.jsx)("div",{style:{flex:1}}),(0,F.jsx)("div",{className:n.triggersRight,children:(0,F.jsx)(At,{className:n.toggleButton,title:s("collapse"),onClick:te,isCollapsed:!1})})]}),(0,F.jsx)("div",{className:n.toggleButtonWrapper,children:(0,F.jsx)(At,{className:n.toggleButton,title:s("open",{productName:c}),onClick:te,isCollapsed:!0})}),(0,F.jsx)("div",{className:n.collapsible,children:(0,F.jsx)(Bs,{loginUrl:S,isEmbedded:v,onLogIn:o,onSnooze:q})})]}):!i||!r?null:(0,F.jsxs)("div",{ref:l,className:(0,Ks.default)(n.root,{[n.isCollapsed]:P}),children:[!P&&(0,F.jsxs)("div",{className:n.triggers,children:[(0,F.jsx)("div",{style:{flex:1},children:x&&(0,F.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>g(s(gc()?"searchHintMac":"searchHintWindows",{searchTriggerKey:d.toUpperCase()})),onMouseLeave:()=>g(null),children:(0,F.jsx)(Sc,{title:s("search")})})}),(0,F.jsxs)("div",{className:n.triggersRight,onFocus:()=>{},children:[(0,F.jsx)("div",{className:(0,Ks.default)(!f&&n.hintsHidden,n.hints),children:f}),(0,F.jsx)(At,{className:n.toggleButton,title:s("collapse"),onClick:te,isCollapsed:!1})]})]}),(0,F.jsx)("div",{className:n.toggleButtonWrapper,children:(0,F.jsx)(At,{className:n.toggleButton,title:s("open",{productName:c}),onClick:te,isCollapsed:!0})}),N>0&&y&&(0,F.jsx)("div",{className:n.collapsible,onFocus:()=>{},children:(0,F.jsx)(re,{children:(0,F.jsx)(Fs,{suggestions:t,selectedIndex:e,reverse:!0})})})]})},Sf=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),bc=(0,tt.connect)(Sf)(vf);var tr=R(require("classnames")),qc=require("interweave"),rt=require("react"),Gc=require("react-redux");var wo=require("react");function Us(t){return t.contentEditable==="true"}function xf(t){let e=0,o=0,n=window.getSelection();if(n.rangeCount!==0){let s=n.getRangeAt(0),r=s.cloneRange();r.selectNodeContents(t),r.setEnd(s.endContainer,s.endOffset),o=r.toString().length,r.selectNodeContents(t),r.setEnd(s.startContainer,s.startOffset),e=r.toString().length}return{selectionStart:e,selectionEnd:o}}function Cc(t){let{selectionStart:e,selectionEnd:o}=Us(t)?xf(t):t;return[e,o]}function wc(t){let[,e]=(0,wo.useState)(),o=(0,wo.useRef)(null);return o.current=Cc(t),(0,wo.useEffect)(()=>{let n=()=>{let[s,r]=o.current??[],i=Cc(t);(!i||s!==i[0]||r!==i[1])&&(o.current=i,e({}))};return t.addEventListener("keyup",n),t.addEventListener("click",n),t.addEventListener("focus",n),document.addEventListener("selectionchange",n),()=>{t.removeEventListener("keyup",n),t.removeEventListener("click",n),t.removeEventListener("focus",n),document.removeEventListener("selectionchange",n)}},[t]),o.current}function Tc(t,e){if(!e)return;let o=t,{value:n}=o,[s,r]=e,i=n.match(Hn);if(!i||i.length===0)return;let a=0;i.find(l=>{let d=n.indexOf(l,a);return s>d&&r<d+l.length?(o.selectionStart=d,o.selectionEnd=d+l.length,!0):(a=d+l.length,!1)})}var Ec=require("react"),bf=["div","span","mark","strong","b","i","u","em"];function fi(t,e,o=0){var r;let n=t[t.length-1],s=typeof n=="object"&&n!==null?(r=n.props)==null?void 0:r.tagName:void 0;if(s==="br")return t.pop(),[...t,...e,n];if(bf.includes(s)){let i=Array.isArray(n.props.children)?n.props.children:[n.props.children];return[...t.slice(0,t.length-1),(0,Ec.cloneElement)(n,{children:fi(i,e,o+1)})]}return[...t,...e]}function Ct(t){return t.tagName.toLowerCase()==="textarea"}var kc={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 _c=R(require("classnames")),Fc=require("interweave"),Qs=require("react");var To=require("react");function Rc(t,e){let o;return[(...n)=>{window.cancelAnimationFrame(o);let s=e?e(...n):n;o=window.requestAnimationFrame(()=>{t(...s)})},()=>window.cancelAnimationFrame(o)]}function zs(t){let e=(0,To.useRef)(null),[o,n]=(0,To.useState)(!1);return(0,To.useEffect)(()=>{let s=!1,r=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[i,a]=Rc((c,p)=>{let u=e.current;if(!u)return;let m=c/r,f=p/r,g=u.getBoundingClientRect(),x=m>g.x&&m<g.x+g.width&&f>g.y&&f<g.y+g.height;x&&!s?(s=!0,n(!0)):!x&&s&&(s=!1,n(!1))},({clientX:c,clientY:p})=>[c,p]),[l,d]=Rc(()=>{s=!1,n(!1)});return t.addEventListener("mousemove",i),t.addEventListener("mouseleave",l),()=>{a(),d(),t.removeEventListener("mousemove",i),t.removeEventListener("mouseleave",l)}},[e]),[e,o]}function Pc(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Vs(t){return e=>{t.forEach(o=>{typeof o=="function"?o(e):o!=null&&(o.current=e)})}}function Ic(t){return t!=null}var yi=R(require("classnames")),ye=require("react");var Ws=require("react"),Cf=["bottom","height","left","right","top","width"],wf=(t={},e={})=>Cf.some(o=>t[o]!==e[o]),ot=new Map,Lc,Ac=()=>{let t=[],e=[];ot.forEach((o,n)=>{if(n instanceof Element&&!n.isConnected){e.push(n);return}let s=n.getBoundingClientRect();wf(s,o.rect)&&(o.rect=s,t.push(o))}),e.forEach(o=>{ot.delete(o)}),t.forEach(o=>{o.callbacks.forEach(n=>n(o.rect))}),Lc=window.requestAnimationFrame(Ac)};function Tf(t,e){return{observe(){let o=ot.size===0;if(ot.has(t)){let n=ot.get(t);n.callbacks.push(e),n.rect&&e(n.rect)}else ot.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});o&&Ac()},unobserve(){let o=ot.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||ot.delete(t),ot.size||cancelAnimationFrame(Lc)}}}}function hi(t){let[e,o]=(0,Ws.useState)(null);return(0,Ws.useLayoutEffect)(()=>{if(!t.current)return;let n=Tf(t.current,s=>{o(s)});return n.observe(),()=>{n.unobserve()}},[t]),e}var Eo=require("react"),Nc=require("react-dom");var Mc={root:"dd-r-dgo"};var Oc=({children:t,parentNode:e})=>{let[o,n]=(0,Eo.useState)(null),s=(0,Eo.useContext)(No);return(0,Eo.useLayoutEffect)(()=>{let r=document.createElement("div");return $t(r),r.classList.add(Mc.root),s!=null&&s.portalRootNode&&r.classList.add(s==null?void 0:s.portalRootNode),(e||document.body).appendChild(r),n(r),()=>{r.isConnected&&r.remove()}},[]),o?(0,Nc.createPortal)(t,o):null};var Fe={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 $s=require("react/jsx-runtime"),qs=(t=!1)=>{let[e,o]=(0,ye.useState)(t),n=(0,ye.useCallback)(()=>o(!0),[]),s=(0,ye.useCallback)(()=>o(!1),[]),r=(0,ye.useCallback)(()=>o(a=>!a),[]),i=(0,ye.useRef)(null);return{opened:e,open:n,close:s,toggle:r,triggerRef:i}};function vi(t,e=null,o=0){if(!t)return{display:"none"};let n=e?t.top-e.top<0||t.top<e.top-o?e.top-o:t.top+t.height>e.top+e.height+o?e.top+e.height+o-t.height:t.top:t.top,s=e?t.left<e.left-o?e.left-o:t.left+t.width>e.left+e.width+o?e.left+e.width+o-t.width:t.left:t.left;return{top:n,left:s,height:t.height,width:t.width}}var ko=({className:t,triggerRef:e,boundaryRef:o=(0,ye.createRef)(),position:n="above",align:s="center",children:r,toStyle:i=vi,parentNode:a,...l})=>{let d=hi(e),c=hi(o),p=(0,ye.useMemo)(()=>i(d,c,0),[d,c]);return(0,$s.jsx)(Oc,{parentNode:a,children:(0,$s.jsx)("div",{className:(0,yi.default)(Fe.ref,{[Fe.positionAbove]:n==="above",[Fe.positionBelow]:n==="below",[Fe.positionLeft]:n==="left",[Fe.positionRight]:n==="right",[Fe.alignStart]:s==="start",[Fe.alignCenter]:s==="center",[Fe.alignEnd]:s==="end"}),style:p,...l,role:"dialog",children:(0,$s.jsx)("div",{className:(0,yi.default)(t,Fe.root),children:r})})})};var Dc=R(require("classnames")),Gs=require("react");var nt={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 Si=require("react/jsx-runtime"),js=(0,Gs.forwardRef)(({className:t,children:e,...o},n)=>{let s=(0,Gs.useRef)(null),r=h("TabCompletion",nt);return(0,Si.jsx)("div",{ref:Vs([s,n]),className:(0,Dc.default)(t,r.popoverContentContainer),...o,children:(0,Si.jsx)("div",{className:r.popoverContent,children:e})})});var wt=require("react/jsx-runtime"),Ef=t=>e=>{let o=vi(e);return"top"in o&&(o.width=t.width-(e.left-t.left)-10),o},kf=({inputElement:t,boundaryRef:e,inputStyle:o,children:n,suggestion:s})=>{let r=h("TabCompletion",nt),i=qs(),a=(0,Qs.useMemo)(()=>Ef(t.getBoundingClientRect()),[t]),[l,d]=zs(t);return(0,Qs.useEffect)(()=>{d?i.open():i.close()},[d]),(0,wt.jsxs)("span",{children:[(0,wt.jsx)("mark",{ref:Vs([l,i.triggerRef]),className:(0,_c.default)(r.matchKeyword,{[r.hover]:d}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:n}),i.opened&&(0,wt.jsx)(ko,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:(0,wt.jsx)(js,{style:o,children:(0,wt.jsx)("div",{className:r.hintText,children:s})})})]})},Xs=class extends Fc.Matcher{keywordMatches=[];preparedKeywordMatches=[];usedKeywordMatches=new Set;onBeforeParse(e,o){return o.keywordMatches&&o.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=o.keywordMatches.map(n=>({...n,keywordRegex:new RegExp(`\\b${Pc(n.keyword)}\\b`,"i")})),this.keywordMatches=o.keywordMatches),this.usedKeywordMatches.clear(),e}match(e){let o=this.preparedKeywordMatches.map(s=>{if(this.usedKeywordMatches.has(s))return null;let r=e.match(s.keywordRegex);if(!r)return null;let i=e.charAt(r.index-1),a=e.charAt(r.index+s.keyword.length);return i==="{"&&a==="}"?null:{index:r.index,length:r[0].length,match:r[0],matchString:r[0],suggestion:s.suggestion,preparedKeywordMatch:s,valid:!0}}).filter(Ic);if(o.length===0)return null;let n=o.reduce((s,r)=>r.index<s.index?r:s);return this.usedKeywordMatches.add(n.preparedKeywordMatch),n}replaceWith(e,o){return(0,wt.jsx)(kf,{inputElement:o.inputElement,suggestion:o.suggestion,inputStyle:o.inputStyle,boundaryRef:o.boundaryRef,children:e},`keyword_${o.matchString}_${o.key}`)}asTag(){return"mark"}};var Hc=require("interweave"),Bc=R(require("classnames"));var xi=require("react/jsx-runtime"),Rf=({inputElement:t,children:e})=>{let o=h("TabCompletion",nt),[n,s]=zs(t);return(0,xi.jsx)("mark",{ref:n,className:(0,Bc.default)(o.matchPlaceholder,{[o.hover]:s}),children:e})},Zs=class extends Hc.Matcher{match(e){let o=e.match(/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\}(?!\}))/);return o?{index:o.index,length:o[0].length,match:o[0],matchString:o[0],valid:!0}:null}replaceWith(e,o){return(0,xi.jsx)(Rf,{inputElement:o.inputElement,children:e},`placeholder_${o.matchString}_${o.key}`)}asTag(){return"mark"}};var Ys=R(require("classnames")),Wc=require("interweave"),ee=require("react"),$c=require("react-redux");var bi=require("react/jsx-runtime"),Kc=()=>(0,bi.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,bi.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 Tt=require("react"),un=require("react-redux"),zc=R(require("lodash.debounce"));var Uc={root:"dd-ky-Bv",content:"dd-kV5e1"};function Js(t,e,o){var s;let n=((s=t.imageSizes)==null?void 0:s[e])||t.image||o;if(!n)return null;try{return new URL(n).toString()}catch{return null}}function Ci(t){return t.replace("https://www.","").replace("https://","")}var ve=require("react/jsx-runtime"),Pf=3,If=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),Lf=({onSelectLink:t,onDismiss:e,placeholder:o,visitUrlText:n,linkCount:s=Pf})=>{let r=h("LinkSearch",Uc),[i,a]=(0,Tt.useState)(""),l=(0,un.useDispatch)(),d=(0,un.useSelector)(Pd("url")),c=(0,un.useSelector)(al("URL",If)),[p,u]=(0,Tt.useState)(c.length-1),m=C("fallbackImage"),f=S=>{let v=S.target;a(v.value)},g=(S,v)=>{S.stopPropagation(),S.preventDefault(),window.open(v,"_blank")},x=S=>{var w;let v=p-1<0?c.length-1:p-1,I=p+1===c.length?0:p+1;S.code==="Escape"&&(a(""),e()),S.code==="ArrowUp"&&u(v),S.code==="ArrowDown"&&u(I),S.code==="Enter"&&t(((w=c[p])==null?void 0:w.text)||i)},y=(0,Tt.useCallback)((0,zc.default)(S=>{l(Ot({query:S,type:"URL",tags:["link-search"]}))},300),[]);return(0,Tt.useEffect)(()=>{i&&y(i)},[i]),(0,Tt.useEffect)(()=>()=>{l(Jn())},[]),(0,ve.jsxs)("div",{className:r.root,children:[(0,ve.jsx)(re,{withDivider:!0,children:(i?c:d).slice(0,s).map((S,v)=>(0,ve.jsx)(M,{selected:p===v,onClick:()=>t(S.text),"data-testid":"linksearch-suggestion",children:(0,ve.jsxs)(_,{children:[(0,ve.jsx)(_.Image,{src:Js(S,"small",m||void 0),title:S.title||S.text}),(0,ve.jsxs)(_.Content,{className:r.content,cropText:!0,children:[(0,ve.jsx)(_.Title,{children:S.title||Ci(S.text)}),S.title&&Ci(S.text)]}),(0,ve.jsx)(M.Actions,{children:(0,ve.jsx)(M.ActionButton,{label:n,onClick:I=>g(I,S.text)})})]})},S.text))}),(0,ve.jsx)($o,{value:i,onChange:f,autoFocus:!0,placeholder:o,onKeyUp:x})]})},Vc=Lf;var wi={};j(wi,{enUS:()=>Af,nlNL:()=>Mf});var Af={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},Mf={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var Y=require("react/jsx-runtime"),Nf=(0,ee.forwardRef)((t,e)=>{let o=h("TabCompletion",nt);return(0,Y.jsx)("mark",{ref:e,className:(0,Ys.default)(o.matchSelection)},"selection-start")}),Of=({startRef:t,boundaryRef:e,inputStyle:o,inputElement:n,children:s})=>{let r=k(wi),i=h("TabCompletion",nt),a=(0,ee.useRef)(null),l=(0,ee.useRef)(null),[d,c]=(0,ee.useState)(null),p=(0,$c.useDispatch)(),u=qs(document.activeElement===n),[m]=(0,ee.useState)(()=>document.createRange());u.triggerRef.current=m,(0,ee.useEffect)(()=>()=>m.detach(),[]),(0,ee.useEffect)(()=>{let g=t.current,x=a.current;!g||!x||(m.setStart(g,0),m.setEnd(x,0))},[t.current,a.current]),St(()=>{u.close()});let f=(0,ee.useCallback)(g=>{let x=m.toString(),y=/^http(s?):\/\//.test(g)?g:`https://${g}`;p(qn({text:`[${x}](${y})`,replace:"selection"}))},[]);return(0,Y.jsxs)("span",{children:[(0,Y.jsx)("mark",{ref:a,className:(0,Ys.default)(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":u.opened?"true":"false",children:s}),u.opened&&(0,Y.jsx)(ko,{className:i.popoverRoot,triggerRef:u.triggerRef,boundaryRef:e,position:"above",align:"start",children:(0,Y.jsxs)(js,{style:o,ref:l,children:[(0,Y.jsx)("div",{className:(0,Ys.default)(i.selectionOptions,{[i.selectionOptionsIsHidden]:d!==null}),children:(0,Y.jsxs)("button",{type:"button",tabIndex:d===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>c("insertLink"),children:[(0,Y.jsx)(Kc,{}),(0,Y.jsx)("span",{children:"\xA0"}),(0,Y.jsx)("span",{children:r("insertLink")})]})}),d==="insertLink"&&(0,Y.jsx)(Vc,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:f,onDismiss:()=>{c(null),u.close()}})]})})]},"selection-end")},er=class extends Wc.Matcher{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(e,o){return this.props=o,this.charCount=0,this.startRef=(0,ee.createRef)(),this.foundIndex=0,e}match(e){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[o,n]=this.props.selection;if(o===n)return null;let s=this.foundIndex===0?o:n,r=s>=this.charCount&&s<=this.charCount+e.length?{index:s-this.charCount,length:0,match:"",valid:!0}:null;r&&this.foundIndex++;let i=this.foundIndex===1;return r&&i?this.charCount+=s-this.charCount:this.charCount+=e.length,r?{isStart:i,...r}:null}replaceWith(e,o){return o.isStart?(0,Y.jsx)(Nf,{ref:this.startRef}):(0,Y.jsx)(Of,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};var jc=require("react-redux");var st=require("react/jsx-runtime"),Df=({enabled:t,content:e,tabText:o,showTabHint:n,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:l})=>{let d=h("TabCompletion",kc),c=C("insertLink"),p=C("showMidSentenceSuggestions"),u=C("inlineSuggestions"),m=wc(a),f=(0,rt.useRef)(null),g=(0,jc.useSelector)(Q);(0,rt.useEffect)(()=>{Ct(a)&&m&&Tc(a,m)},[m]);let x=(0,rt.useCallback)(v=>{if(!s||!o)return v;let I=[(0,st.jsx)("span",{className:d.resetIndent,children:"\u200B"},"u200B"),(0,st.jsx)("span",{"data-testid":"tab-completion",className:(0,tr.default)(d.tabText,d.resetIndent),"data-source":l,children:o},"tabText")];return n&&I.push((0,st.jsx)("span",{className:(0,tr.default)(d.hint,d.resetIndent),children:(0,st.jsx)(On,{keyCode:"tab"},"tabHint")})),fi(v,I)},[s,o,n]),y=(0,rt.useMemo)(()=>{let v=[];return c&&v.push(new er("selection")),v.push(new Zs("placeholders")),r&&v.push(new Xs("keywords")),v},[u,c,r]),S=(0,rt.useMemo)(()=>{let v=window.getComputedStyle(a);return{"--dd-color":v.color,"--dd-font-size":v.fontSize,"--dd-font-family":v.fontFamily,"--dd-font-variant":v.fontVariant}},[]);return!t||!g?null:(0,st.jsxs)("div",{ref:v=>{v!=null&&v.parentElement&&(f.current=v==null?void 0:v.parentElement)},className:d.root,style:S,children:[(0,st.jsx)(qc.Interweave,{tagName:"span",containerTagName:"div",className:(0,tr.default)(d.container,d.agentText),disableLineBreaks:Ct(a),content:e||"\u200B",onAfterParse:x,matchers:y,selection:m,keywordMatches:i,inputElement:a,inputStyle:S,boundaryRef:f,inlineSuggestionsOnlyAtEnd:!p}),(0,st.jsx)("br",{})]})},_f=({input:t,ui:e,settings:o,styleSuggestions:n,conversation:s})=>{var g;let{tabCompletionSuggestion:r}=t,i=(r==null?void 0:r.text)||"",a=(r==null?void 0:r.source)||"",l=t.html??lo(t.text),d=i.indexOf(t.text)===0?i.slice(t.text.length):"",{showTabHint:c}=e,{isSupported:p}=s,{showTabCompletion:u,visible:m,showStyleSuggestions:f}=o;return{showTabHint:c,showStyleSuggestions:f,showTabCompletion:u,content:l,tabText:d,source:a,keywordMatches:((g=n.list)==null?void 0:g.keywordMatches)??[],enabled:m&&p!==!1}},Xc=(0,Gc.connect)(_f)(Df);var tp=R(require("classnames")),xn=require("react"),H=require("react-redux");var Et=require("@reduxjs/toolkit");var Qc={list:[],fetchState:"idle"},Jc=t=>t.autoflows.list||[],Zc=t=>e=>{var o;return(o=e.list)==null?void 0:o.find(n=>n.triggerPayload===t)},it=(0,Et.createAsyncThunk)("autoflows/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getAutoflows(t)}),Ti=(0,Et.createAsyncThunk)("autoflows/start",async(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");await n.startAutoflowSession(t),await o(it(t.platformSessionId))}),Ei=(0,Et.createAsyncThunk)("autoflows/stop",async(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");await n.stopAutoflowSession(t.platformSessionId),await o(it(t.platformSessionId))}),Ff=(0,Et.createSlice)({name:"autoflows",initialState:Qc,reducers:{},extraReducers:t=>{t.addCase(Ti.pending,(e,o)=>{let n=Zc(o.meta.arg.triggerPayload)(e);n.state="Started",n.isBusy=!0}),t.addCase(Ei.pending,(e,o)=>{let n=Zc(o.meta.arg.triggerPayload)(e);n.state="Aborted",n.isBusy=!0}),t.addCase(it.pending,e=>{e.fetchState="loading"}),t.addCase(it.rejected,e=>{e.fetchState="error"}),t.addCase(it.fulfilled,(e,o)=>{e.list=o.payload,e.fetchState="done"}),t.addCase(O,()=>Qc)}}),Yc=(0,Et.createAsyncThunk)("autoflows/openStream",(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");let s=n.openStream(t);s.on("sessionAborted",()=>{o(it(t))}),s.on("sessionCompleted",()=>{o(it(t))})}),eu=(0,Et.createAsyncThunk)("autoflows/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),tu=Ff.reducer;var kt=require("@reduxjs/toolkit");var ou={list:[],fetchState:"idle",sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},nu=t=>t.customMessages.list,su=t=>e=>!!e.customMessages.sentSuggestions.find(o=>o===t),ru=t=>e=>!!e.customMessages.answeredSuggestions.find(o=>o===t),iu=t=>e=>!!e.customMessages.errorSuggestions.find(o=>o===t),pn=(0,kt.createAsyncThunk)("customMessages/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getCustomMessages(t)}),or=(0,kt.createAsyncThunk)("customMessages/send",async(t,e)=>{let{platformSessionId:o,suggestion:n}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.sendCustomMessage(o,n)}),nr=(0,kt.createAsyncThunk)("customMessages/answer",async(t,e)=>{let{platformSessionId:o,reply:n}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.answerCustomMessage(o,n)}),au=(0,kt.createSlice)({name:"customMessages",initialState:ou,reducers:{onCustomMessage(t,e){Array.isArray(e.payload)?t.list=e.payload:t.list=[e.payload]}},extraReducers:t=>{t.addCase(pn.pending,e=>{e.fetchState="loading"}).addCase(pn.rejected,e=>{e.fetchState="error"}).addCase(pn.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload||[]}).addCase(or.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.errorSuggestions=e.errorSuggestions.filter(n=>o.meta.arg.suggestion.text!==n)}).addCase(or.rejected,(e,o)=>{let n=e.sentSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1))}).addCase(nr.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.answeredSuggestions.push(o.meta.arg.suggestion.text)}).addCase(nr.rejected,(e,o)=>{let n=e.answeredSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1)),e.answeredSuggestions.splice(n,1)}).addCase(O,()=>ou)}}),lu=(0,kt.createAsyncThunk)("customMessages/openStream",(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.openStream(t).on("customMessageSuggestion",r=>{o(au.actions.onCustomMessage(r))})}),du=(0,kt.createAsyncThunk)("customMessages/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),cu=au.reducer;var mn=require("@reduxjs/toolkit"),Hf={token:null,interval:null},ki=(0,mn.createAsyncThunk)("passwordlessToken/getTemporaryPasswordlessToken",async(t,e)=>{let{deepdeskAPI:o}=e.extra;return{token:await o.requestPasswordlessToken()}}),Ri=(0,mn.createAsyncThunk)("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:o=1e3*60*10}=t,{dispatch:n}=e;return n(ki()),setInterval(()=>n(ki()),o)}),uu=(0,mn.createSlice)({name:"passwordlessToken",initialState:Hf,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(ki.fulfilled,(e,o)=>{e.token=o.payload.token}),t.addCase(Ri.fulfilled,(e,o)=>{e.interval=o.payload})}}),{stopPollPasswordlessToken:pu}=uu.actions,mu=uu.reducer;var Ro=require("@reduxjs/toolkit");var gu={shouldEmit:!0},Pi={cues:[],fetchState:"idle"},fu=t=>{var e;return(e=t.rules)==null?void 0:e.cues},Bf=(0,Ro.createAction)("rules/resetCues"),jt=(0,Ro.createAsyncThunk)("rules/evaluate",async(t,e)=>{var o,n;try{let{deepdeskAPI:s}=e.extra,r=e.getState(),i=(o=r.conversation.current)==null?void 0:o.id;if(!i)throw new Error("No current conversation to evaluate rules");if(!(await s.getAccount()).ruleEngine)throw new Error("Rule engine is not enabled for this account");if(!(await s.getRules()).filter(p=>p.isEnabled).some(p=>p.label===t.label))throw new Error(`No enabled rules found with label: ${t.label}`);return{cues:await s.evaluateRule(t.label,i,{tags:((n=r.conversation.current)==null?void 0:n.tags)||void 0,...t.params}),options:t.options}}catch(s){return b.info(s.message),{cues:[],options:t.options}}}),hu=(0,Ro.createSlice)({name:"answer",initialState:Pi,reducers:{removeCue(t,e){t.cues=t.cues.filter(o=>o.rule.id!==e.payload.id)}},extraReducers:t=>{t.addCase(jt.pending,e=>{e.fetchState="loading"}).addCase(jt.rejected,e=>{e.fetchState="error"}).addCase(jt.fulfilled,(e,o)=>{let n=o.payload.cues.map(r=>r.rule.id),s=e.cues.filter(r=>!n.includes(r.rule.id));e.fetchState="done",e.cues=[...o.payload.cues,...s]}).addCase(O,()=>Pi).addCase(Bf.toString(),()=>Pi)}}),{removeCue:yu}=hu.actions,vu=hu.reducer;var Ru=require("react"),Pu=require("react-redux");var Tu=R(require("classnames")),Eu=require("react");var xu=R(require("classnames"));var Su={root:"dd-uszkm"};var Cu=require("react/jsx-runtime"),Kf=({className:t,children:e})=>{let o=h("Unicode",Su);return(0,Cu.jsx)("span",{className:(0,xu.default)(t,o.root),children:e})},bu=Kf;var wu={isDisabled:"dd-Sp--t",root:"dd-maqTG",buttonStop:"dd-rcq8w",stateBadge:"dd-zOnkT",isCompleted:"dd-GA-rt",isStarted:"dd-PZwtX",isAborted:"dd-PAXSE"};var Ii={};j(Ii,{enUS:()=>Uf,nlNL:()=>zf});var Uf={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]},zf={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]};var pe=require("react/jsx-runtime"),Wf=({disabled:t,state:e,displayName:o,description:n,onStartAutoflow:s,onStopAutoflow:r})=>{let i=h("Autoflow",wu),a=k(Ii),l=e==="Started"?"stop":"start",d=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return(0,pe.jsxs)(M,{className:(0,Tu.default)(i.root,{[i.isDisabled]:t,[i.isCompleted]:e==="Completed",[i.isAborted]:e==="Aborted",[i.isStarted]:e==="Started"}),children:[(0,pe.jsx)(_,{children:(0,pe.jsxs)(_.Content,{children:[(0,pe.jsxs)(_.Title,{children:[e&&(0,pe.jsx)("span",{className:i.stateBadge,children:a(e)}),o]}),(0,pe.jsx)("span",{children:n})]})}),(0,pe.jsx)(M.Actions,{fixed:e==="Started",children:(0,pe.jsx)(M.ActionButton,{primary:!0,className:l==="start"?i.buttonStart:i.buttonStop,onClick:e==="Started"?r:s,disabled:t,label:(0,pe.jsxs)(Eu.Fragment,{children:[(0,pe.jsx)(bu,{children:d})," ",(0,pe.jsx)("span",{children:a(l)})]})})})]})},ku=Wf;var Li=require("react/jsx-runtime"),$f=(t,e)=>{let o=e.filter(n=>n.state==="Started");return o.length>0?o.indexOf(t)===-1:!1},qf=({autoflows:t,onStartAutoflow:e,onStopAutoflow:o,platformSessionId:n})=>(0,Li.jsx)(Ru.Fragment,{children:t.map(s=>(0,Li.jsx)(ku,{displayName:s.displayName,description:s.description,disabled:s.isBusy||$f(s,t),state:s.state,onStartAutoflow:()=>e({platformSessionId:n,triggerPayload:s.triggerPayload}),onStopAutoflow:()=>o({platformSessionId:n,triggerPayload:s.triggerPayload})},s.displayName))}),Gf=({autoflows:t,conversation:e})=>{var o;return{autoflows:t.list,platformSessionId:(o=e.current)==null?void 0:o.sessionId}},jf={onStartAutoflow:Ti,onStopAutoflow:Ei},Iu=(0,Pu.connect)(Gf,jf)(qf);var Lu=R(require("classnames")),Ai=require("react"),Xt=require("react-redux");var at={root:"dd-ERsBr",title:"dd-b36p6",isUsed:"dd-fp2IX",quickReplies:"dd--VrvP",quickReply:"dd-wFhWh",label:"dd-R9sND",errorIcon:"dd-8cdcH"};var ie=require("react/jsx-runtime"),Xf=({suggestion:t})=>{let e=k(Vt),o=(0,Xt.useDispatch)(),n=(0,Xt.useSelector)(su(t.text)),s=(0,Xt.useSelector)(ru(t.text)),r=(0,Xt.useSelector)(iu(t.text)),i=(0,Xt.useSelector)(no),{replyOptions:a}=t,l=(0,Ai.useCallback)(c=>{c.preventDefault(),c.stopPropagation(),!(n||!i)&&o(or({platformSessionId:i,suggestion:t}))},[t,n,o,i]),d=(0,Ai.useCallback)(c=>{if(c.preventDefault(),c.stopPropagation(),!i||!a)return;let p=parseInt(c.target.dataset.index,10),u=a[p];o(nr({platformSessionId:i,reply:u,suggestion:t}))},[t,n,o,i]);return(0,ie.jsxs)(M,{onClick:l,className:(0,Lu.default)(at.root,{[at.isUsed]:n,[at.hasError]:r}),children:[(0,ie.jsx)(_,{children:(0,ie.jsxs)(_.Content,{children:[(0,ie.jsxs)(_.Title,{className:at.title,children:[t.text," ",(0,ie.jsx)(Dn,{className:at.label,children:"analyse tool"})," ",r&&(0,ie.jsx)("span",{className:at.errorIcon,role:"img","aria-label":e("sendingError"),title:e("sendingError"),children:"!"})]}),a&&a.length>0&&(0,ie.jsx)("ul",{className:at.quickReplies,children:a.map(c=>(0,ie.jsx)("li",{className:at.quickReply,children:c.title},c.title))})]})}),(0,ie.jsxs)(M.Actions,{fixed:r||n,children:[a&&a.length>0&&(0,ie.jsx)(M.DropdownButton,{label:e("answer"),disabled:s,children:a.map((c,p)=>(0,ie.jsx)(M.DropdownItem,{index:p,label:c.title,onClick:d},c.title))}),(0,ie.jsx)(M.ActionButton,{primary:!0,disabled:n,onClick:l,label:e(n?"suggestionSent":r?"tryAgain":"sendSuggestion")})]})]})},Au=Xf;var sr=require("react"),Nu=require("react-redux"),Ni=R(require("classnames"));var Mi=require("react/jsx-runtime"),gn=()=>(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 Mu={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};var He=require("react/jsx-runtime"),Qf=({entities:t})=>{let e=h("EntitiesWidgetList",Mu),[o,n]=(0,sr.useState)(void 0),s=(0,Nu.useDispatch)(),r=()=>{n(void 0)},i=a=>{t&&(n(t.indexOf(a)),qe(a.text),s(Z({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,sr.useEffect)(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[o]),!t||t.length===0?null:(0,He.jsx)("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,l)=>(0,He.jsxs)("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[(0,He.jsx)("span",{className:e.entityText,children:a.text}),(0,He.jsxs)("span",{className:e.iconWrapper,children:[(0,He.jsx)("span",{className:(0,Ni.default)(e.icon),children:(0,He.jsx)(gn,{})}),(0,He.jsx)("span",{className:(0,Ni.default)(e.icon,o===l&&e.iconClicked),children:(0,He.jsx)(gn,{})})]})]},a.text))})},Ou=Qf;var Oi=require("react/jsx-runtime"),Du=()=>(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"),_u=()=>(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"),Fu=()=>(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 qu=require("react-redux");var Wu=require("react");var fn=require("react/jsx-runtime"),Hu=({className:t})=>(0,fn.jsxs)("svg",{viewBox:"0 0 12 12",version:"1.1",xmlns:"http://www.w3.org/2000/svg",className:t,children:[(0,fn.jsx)("line",{x1:"2",y1:"10",x2:"10",y2:"2",stroke:"black",strokeWidth:"1"}),(0,fn.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10",stroke:"black",strokeWidth:"1"})]});var Ku=R(require("dompurify")),Rt=require("react"),Uu=R(require("snarkdown"));var Bu={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 Be=require("react/jsx-runtime");function Zf(t){return`<button type="button" 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){let e=t.cloneNode(!0);return e.querySelectorAll("div,button").forEach(o=>o.remove()),e.textContent??""}function Jf(t){return t.replace(/\r\n/g,`
|
|
8
8
|
`)}var Yf=({content:t,useLabel:e,copyLabel:o,onCopy:n,onUse:s})=>{let r=h("Markdown",Bu),i=(0,Rt.useRef)(null),[a,l]=(0,Rt.useState)(null),d=(0,Rt.useMemo)(()=>{let g=(0,Uu.default)(Jf(t));return Ku.default.sanitize(g).replace(/<\/code>/g,`${Zf(r.copyIcon)}</code>`)},[t]),c=g=>{var S;let x=g.target,y=!!((S=i.current)!=null&&S.querySelector("code"));a||y&&x.tagName!=="CODE"||!y&&x!==i.current||(x.addEventListener("mouseleave",()=>l(null),{once:!0}),l(x))},p=()=>{if(!a)return;l(null);let g=a.querySelector("button");g&&(mo(g,r.fadeup),n(Fi(a)))},u=g=>{g.target.tagName.toLowerCase()==="button"&&(mo(g.target,r.fadeup),n(Fi(g.target.parentElement)))},m=()=>{a&&(l(null),s(Fi(a)))},f=g=>{if(g===null)return;let x=g.getBoundingClientRect();x.left<0?g.style.transform=`translateX(${-x.left+2}px)`:x.right>window.innerWidth&&(g.style.transform=`translateX(${window.innerWidth-x.right-2}px)`)};return(0,Be.jsxs)(Rt.Fragment,{children:[a&&(0,Be.jsxs)(ko,{triggerRef:{current:a},className:r.popover,parentNode:a,children:[(0,Be.jsxs)("div",{className:r.options,ref:f,children:[(0,Be.jsx)("button",{type:"button",className:r.option,onClick:p,children:o}),(0,Be.jsx)("div",{className:r.divider}),(0,Be.jsx)("button",{type:"button",className:r.option,onClick:m,children:e})]}),(0,Be.jsx)("div",{className:r.arrow})]}),(0,Be.jsx)("div",{ref:i,className:r.root,dangerouslySetInnerHTML:{__html:d},onMouseOver:c,onClick:u})]})},zu=Yf;var Hi={};j(Hi,{enUS:()=>eh,nlNL:()=>th});var eh={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"}]},th={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"}]};var Vu={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",thumbsUp:"dd-6QwVx",thumbsDown:"dd-d3E8l"};var Ie=require("react/jsx-runtime"),oh=({cue:t,onRemove:e,onCopy:o,onUse:n})=>{let s=h("WidgetCue",Vu),r=k(Hi),i=go(),a=c=>{o&&o(c,t)},l=c=>{n&&n(c,t)},d=c=>{c.preventDefault(),c.stopPropagation(),e(t)};return(0,Wu.useEffect)(()=>{i("Assistant response displayed",{name:t.rule.name,description:t.rule.description,group:t.rule.label,cueText:t.text})},[]),(0,Ie.jsxs)(M,{"data-testid":"cue",children:[(0,Ie.jsx)(_,{children:(0,Ie.jsxs)(_.Content,{children:[t.title&&(0,Ie.jsx)(_.Title,{className:s.title,"data-testid":"widget-cue-title",children:t.title}),(0,Ie.jsx)(zu,{content:t.text,useLabel:r("useCue"),copyLabel:r("copyCue"),onCopy:a,onUse:l})]})}),(0,Ie.jsxs)(M.IconButtonContainer,{children:[(0,Ie.jsx)(ho,{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"}),(0,Ie.jsx)(M.IconButton,{title:r("removeCue"),onClick:d,icon:(0,Ie.jsx)(Hu,{})})]})]})},$u=oh;var hn=require("react/jsx-runtime"),nh=({cues:t})=>{let e=(0,qu.useDispatch)(),o=fe(),n=go(),s=a=>{e(yu({id:a.rule.id})),n("Assistant response closed",{name:a.rule.name,group:a.rule.label,description:a.rule.description,cueText:a.text})},r=(a,l)=>{qe(a),n("Assistant response copied",{name:l.rule.name,group:l.rule.label,description:l.rule.description,copiedText:a})},i=(a,l)=>{o.send(ht,{text:a,suggestion:{source:"cue",sourceText:a}}),n("Assistant response used",{name:l.rule.name,group:l.rule.label,description:l.rule.description,usedText:a})};return(0,hn.jsx)(hn.Fragment,{children:t.map(a=>(0,hn.jsx)($u,{cue:a,onRemove:s,onCopy:r,onUse:i},a.rule.id))})},Gu=nh;var rr=require("react");var ju={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var Le=require("react/jsx-runtime");function sh(t,e){return e.split(".").reduce((o,n)=>!o||typeof o!="object"||!(n in o)?null:o[n],t)}var Xu=({data:t,schema:e})=>{let o=h("WidgetCustomData",ju),n=s=>{qe(s)};return(0,rr.useEffect)(()=>{b.info("Custom data",t,e)},[t]),(0,Le.jsx)("dl",{className:o.root,children:e.map(s=>{let r=sh(t,s.path);return(0,Le.jsxs)(rr.Fragment,{children:[(0,Le.jsx)("dt",{className:o.label,children:s.label}),(0,Le.jsx)("dd",{className:o.value,children:s.type==="boolean"&&r?(0,Le.jsx)("span",{className:o.isTrue,children:s.trueValue}):s.type==="boolean"&&!r?(0,Le.jsx)("span",{className:o.isFalse,children:s.falseValue}):r?(0,Le.jsxs)("button",{type:"button",onClick:()=>n(r),className:o.copyButton,children:[(0,Le.jsx)("span",{children:r}),(0,Le.jsx)(gn,{})]}):"-"})]},s.label)})})};var Zu=require("react");var rh=/(https?:\/\/[^\s]+)/,Qu=t=>t.split(" ").find(e=>rh.test(e));var Se=require("react/jsx-runtime"),ih=({suggestion:t,lines:e,onUse:o})=>{var c;let n=t.text||t.url||t.message,s=Qu(n),r=k(Vt),i=C("showImages"),a=C("fallbackImage"),l=p=>{p.preventDefault(),p.stopPropagation(),o(n)},d=(0,Zu.useCallback)(p=>{window.open(s,"_blank"),p.stopPropagation(),p.preventDefault()},[s]);return(0,Se.jsxs)(M,{onClick:l,"data-testid":"edit-suggestion",children:[(0,Se.jsxs)(_,{children:[i&&t.image&&(0,Se.jsx)(_.Image,{src:Js(t,"small",a||void 0),title:t.title}),(0,Se.jsxs)(_.Content,{children:[t.title&&(0,Se.jsx)(_.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((c=t.searchKeywords)==null?void 0:c.length)>0&&(0,Se.jsx)(M.Labels,{labels:t.searchKeywords}),(0,Se.jsx)(_.Content,{cropText:e==="single",lineClamp:e==="multiple",children:n})]})]}),(0,Se.jsxs)(M.Actions,{children:[s&&(0,Se.jsx)(M.ActionButton,{onClick:d,label:r("visitUrl")}),(0,Se.jsx)(M.ActionButton,{primary:!0,onClick:l,label:r("useSuggestion")})]})]})},Ju=ih;var yn=require("react/jsx-runtime"),ah=({lines:t,suggestions:e})=>{let o=fe(),n=(s,r)=>{o.send(ht,{text:s,suggestion:{...r,source:r.source,sourceText:r.text}})};return(0,yn.jsx)(yn.Fragment,{children:e.map(s=>(0,yn.jsx)(Ju,{suggestion:s,lines:t,onUse:r=>n(r,s)},s.text||s.url||s.message))})},Yu=ah;var vn={};j(vn,{enUS:()=>lh,nlNL:()=>dh});var lh={waiting:[{type:0,value:"Loading\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],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"}]},dh={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],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 Sn={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",sectionList:"dd-bF9pF",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",link:"dd-DRo0x"};var E=require("react/jsx-runtime"),ir=(t,e)=>{let o=(0,H.useSelector)(Q);(0,xn.useEffect)(()=>o?e.every(n=>!!n)?t():()=>{}:()=>{},[...e,o])},ch=({onLogIn:t})=>{let e=h("Widget",Sn),o=C("isEmbedded"),n=C("adminUrl");return(0,E.jsx)("div",{className:e.loginText,children:(0,E.jsx)("div",{children:(0,E.jsx)(Bs,{isEmbedded:o,loginUrl:n,onLogIn:t})})},"login")},ep=({text:t})=>{let e=h("Widget",Sn);return(0,E.jsx)("div",{className:e.stateText,children:(0,E.jsx)("div",{children:(0,E.jsx)("p",{children:t})})},"notification")},uh=()=>{let t=k(vn),e=(0,H.useDispatch)(),o=h("Widget",Sn),n=C("showSearch"),s=C("showSummaryCommand"),r=C("showKnowledgeSearch"),i=(0,H.useSelector)(fo("/admin/")),a=fe(),l=C("productName"),d=n||s||r||i;return ir(()=>(e(Ri()),()=>{e(pu())}),[e]),d?(0,E.jsx)(Me,{title:t("actions"),type:"shortcuts",children:(0,E.jsxs)("div",{className:o.shortcutList,children:[n&&(0,E.jsxs)("button",{type:"button",className:o.shortcut,"data-testid":"shortcut-search","aria-label":t("linkSearch"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0}),children:[(0,E.jsx)(uo,{}),t("linkSearch")]}),s&&(0,E.jsxs)("button",{type:"button",className:o.shortcut,"data-testid":"shortcut-summary","aria-label":t("linkSummary"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,E.jsx)(Fu,{}),t("linkSummary")]}),r&&(0,E.jsxs)("button",{type:"button",className:o.shortcut,"data-testid":"shortcut-knowledge-assist","aria-label":t("linkKnowledgeSearch"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,E.jsx)(_u,{}),t("linkKnowledgeSearch")]}),i&&(0,E.jsxs)("a",{className:o.shortcut,target:"_blank",href:i,"data-testid":"shortcut-studio-login","aria-label":t("linkStudioLogin",{productName:l}),rel:"noreferrer",children:[(0,E.jsx)(Du,{}),t("linkStudioLogin",{productName:l})]})]})}):null},ph=()=>{let t=(0,H.useDispatch)(),e=C("showCustomMessages"),o=(0,H.useSelector)(nu),n=(0,H.useSelector)(no);return ir(()=>(t(pn(n)),t(lu(n)),()=>{t(du(n))}),[t,e,n]),!e||o.length===0?null:(0,E.jsx)(Me,{type:"custom-messages","data-testid":"custom-messages",children:(0,E.jsx)(re,{withDivider:!0,children:o.map(s=>(0,E.jsx)(Au,{suggestion:s},s.text))})})},mh=()=>{let t=k(vn),e=(0,H.useDispatch)(),o=C("showAutoflows"),n=(0,H.useSelector)(Jc),s=(0,H.useSelector)(no);return ir(()=>(e(it(s)),e(Yc(s)),()=>{e(eu(s))}),[e,o,s]),!o||n.length===0?null:(0,E.jsx)(Me,{type:"autoflows",title:t("titleAutoflows"),"data-testid":"autoflows",children:(0,E.jsx)(re,{withDivider:!0,children:(0,E.jsx)(Iu,{})})})},gh=()=>{let t=(0,H.useDispatch)(),e=(0,H.useSelector)(Is),o=(0,H.useSelector)(Cd),n=(0,H.useSelector)(fu),s=(0,H.useSelector)(Ja),r=(0,H.useSelector)(ws),i=(0,H.useSelector)(Ls),a=(0,H.useSelector)(Je),l=(0,H.useSelector)(mt);return(0,xn.useEffect)(()=>{!!s&&!o&&b.warn("Custom data provided, but no schema.")},[s,o]),ir(()=>{e.forEach(({type:d})=>{d==="entities"?t(ke()):Bn.includes(d)||t(Pe(d))})},[t,l,a]),(0,E.jsx)(xn.Fragment,{children:e.map(({type:d,title:c,amount:p,lines:u,schema:m})=>{var f,g;switch(d){case"entities":return r&&r.length>0&&(0,E.jsx)(Me,{type:d,title:c,"data-testid":`type-${d}`,children:(0,E.jsx)(Ou,{entities:r})},d);case"cues":return n&&n.length>0&&(0,E.jsx)(Me,{type:d,title:c,"data-testid":`type-${d}`,children:(0,E.jsx)(re,{withDivider:!0,children:(0,E.jsx)(Gu,{cues:n})})},d);case"custom-data":return s&&m&&(0,E.jsx)(Me,{type:d,title:c,"data-testid":`type-${d}`,children:(0,E.jsx)(re,{withDivider:!0,children:(0,E.jsx)(Xu,{data:s,schema:m})})},d);default:return((g=(f=i[d])==null?void 0:f.suggestions)==null?void 0:g.length)>0&&(0,E.jsx)(Me,{type:d,title:c,"data-testid":`type-${d}`,children:(0,E.jsx)(re,{withDivider:!0,children:(0,E.jsx)(Yu,{lines:u,contentType:d,suggestions:i[d].suggestions.slice(0,p)||[]})})},d)}})})},fh=({onLogIn:t})=>{let e=k(vn),o=h("Widget",Sn),n=(0,H.useSelector)(so),s=(0,H.useSelector)(Q),r=(0,H.useSelector)(no),i=(0,H.useSelector)(Je);return n===!1?(0,E.jsx)(ep,{text:e("notSupported")}):s===!1?(0,E.jsx)(ch,{onLogIn:t}):!i||!r||s===null?(0,E.jsx)(ep,{text:e("waiting")}):(0,E.jsx)("div",{className:(0,tp.default)(o.root),"data-testid":"widget",children:(0,E.jsxs)(_n,{className:o.sectionList,children:[(0,E.jsx)(uh,{}),(0,E.jsx)(ph,{}),(0,E.jsx)(mh,{}),(0,E.jsx)(gh,{})]})})},op=fh;function Po(t){let e=new Range;return e.selectNodeContents(t),e}function np(t,e,o){try{return Pt(t,e,o),!0}catch{return!1}}function ar(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function lr(t){return"tagName"in t&&t.tagName==="BR"}var bn=/[\u200B-\u200D\uFEFF]/g;function Pt(t,e,o){let n=new Range;if(t.firstChild===null&&e===0&&o===0)return n.selectNodeContents(t),n;let s=0,r=!1;function i(l,d){let c=-1,p=/[\u200B-\u200D\uFEFF]/;if(!p.test(l))return d;for(let u=0;u<=l.length;u++)if(p.test(l[u])||c++,c===d)return u;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let d=l.textContent,c=d.replace(bn,""),p=s+c.length,u=e>=s&&e<=p,m=o>=s&&o<=p;if(u){let f=i(d,e-s);f===0&&!m?n.setStartBefore(l):n.setStart(l,f)}m&&(n.setEnd(l,i(d,o-s)),r=!0),s=p;break}case Node.ELEMENT_NODE:{if(lr(l)&&(s===e&&n.setStartBefore(l),s++,s===o)){n.setEndAfter(l),r=!0;return}for(let c=0;c<l.childNodes.length&&(a(l.childNodes[c]),!r);c++);let d=l.lastChild;ar(l)&&d&&!ar(d)&&!lr(d)&&s++;break}default:break}}if(a(t),n.startContainer===document)throw new Error("Offsets out of bound");return n}function Cn(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:o,startOffset:n,endContainer:s,endOffset:r,collapsed:i}=e,a,l,d=0;function c(p){let u=p===o,m=p===s;switch(p.nodeType){case Node.TEXT_NODE:{let f=p.textContent;u&&(a=d+f.substring(0,n).replace(bn,"").length),m&&(l=d+f.substring(0,r).replace(bn,"").length),d+=f.replace(bn,"").length;break}case Node.ELEMENT_NODE:{let f=p.nextSibling===null;lr(p)&&!f&&d++;for(let g=0;g<p.childNodes.length;g++){let x=u&&g===n,y=m&&g===r;if(x&&(a=d),y&&(l=d),l!==void 0||((!x||!i)&&c(p.childNodes[g]),m&&g===r-1&&(l=d),l!==void 0))break}!m&&ar(p)&&!f&&d++,m&&(l=d);break}default:break}}if(c(t),l===void 0)throw new Error("Could not determine start and end");return{start:a??l,end:l}}function wn(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:o,startOffset:n,endContainer:s,endOffset:r}=e,i=-1,a="";function l(d){let c=d===o,p=d===s;switch(c&&i++,d.nodeType){case Node.TEXT_NODE:{if(i!==0)return;let u=c?n:0,m=p?r:void 0,f=d.textContent.replace(bn,"");u===0&&m===void 0?a+=f:a+=f.substring(u,m);break}case Node.ELEMENT_NODE:{let u=d.nextSibling===null;i===0&&lr(d)&&!u&&(a+=`
|
|
9
9
|
`);for(let m=c?n:0;m<(p?Math.min(r,d.childNodes.length):d.childNodes.length)&&(l(d.childNodes[m]),i!==1);m++);!p&&i===0&&ar(d)&&!u&&(a+=`
|
|
10
|
-
`);break}default:break}p&&i++}return l(t),a}var sp=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(sp||{}),lt=class{constructor(e){this.element=e;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(e,o){let n=s=>{o(s)};this.element.addEventListener(e,n),this.disposeHandlers.push(()=>{this.element.removeEventListener(e,n)})}removeEventListener(e,o){this.element.removeEventListener(e,o)}triggerChange(){let e=this.getText(),o=this.getHTML(),n=e!==this.currentText;this.isActive&&(e===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&n&&!this.isSubmitting&&this.emit("change",{plainText:e}),n&&(this.currentSelection=this.getSelection()),this.currentText=e,this.isSubmitting=!1,(this.currentHTML!==o||o===null&&n)&&(this.emit("updated",{plainText:e}),this.triggerCaretPosition(),this.currentHTML=o))}triggerSelection(){let e=this.getSelection();(e.start!==this.currentSelection.start||e.end!==this.currentSelection.end)&&(this.currentSelection=e,this.emit("selection",e),this.triggerCaretPosition())}triggerCaretPosition(){let e=this.getCaretPosition();pt(e,this.currentCaret)||(this.currentCaret=e,this.emit("caret",e))}handleKeyUp(e){let{key:o,shiftKey:n}=e;(o==="Enter"&&n===!0||o==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(e){let{key:o,ctrlKey:n,metaKey:s}=e;this.isPossibleClearInputAction=Object.values(sp).includes(o)||o.toLowerCase()==="z"&&(n||s),this.emit("keydown",e)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){var n,s;let o=((n=e.clipboardData)==null?void 0:n.getData("text"))||((s=e.clipboardData)==null?void 0:s.getData("text/plain"))||"";this.emit("paste",{pastedText:o,selectionText:this.getSelectedText()})}listen(e={shouldObserve:!0}){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),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.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let o=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});e!=null&&e.shouldObserve&&o.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{o.disconnect()}),this.currentSelection=this.getSelection()}focus(){this.element.focus()}emit(e,...o){this.isDisposed||this.eventListeners[e]&&this.eventListeners[e].forEach(n=>{n(...o)})}on(e,o){this.isDisposed||(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o))}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};function rp(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var Qt=class extends lt{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),wn(this.element,e)}getHTML(){return this.element.innerHTML||""}getRange(){var r;let e=this.getRootNode();if(e.activeElement!==this.element)return null;let o="getSelection"in e?e.getSelection():window.getSelection();if(!o)return null;let n="getComposedRanges"in o&&e instanceof ShadowRoot?(r=o.getComposedRanges(e))==null?void 0:r[0]:o.rangeCount>0?o.getRangeAt(0):null;if(!n)return null;let s=this.element.ownerDocument.createRange();return s.setStart(n==null?void 0:n.startContainer,n==null?void 0:n.startOffset),s.setEnd(n==null?void 0:n.endContainer,n==null?void 0:n.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let e=this.getRange();if(!e||!e.collapsed||!("getBoundingClientRect"in e))return null;let o=e.getBoundingClientRect();return!rp(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!rp(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return Cn(this.element,e);let o=this.lastKnownSelection;if(o&&np(this.element,o.start,o.end))return o;let n=Po(this.element);return n.collapse(!1),Cn(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return wn(this.element,Pt(this.element,e,o))}applyChanges(e){var s;if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return(s=this.observer)==null||s.takeRecords(),Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(e={shouldObserve:!0}){super.listen(e),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),e!=null&&e.shouldObserve&&this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let o=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==o&&(o=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>n.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var Zt=class extends lt{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:e,selectionEnd:o}=this.element;return{start:e,end:o}}getSelectedText(){let e=this.getSelection();return e?this.getText().slice(e.start,e.end):""}getCaretPosition(){return null}applyChanges(e){if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let e=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=e==null?void 0:e.get)==null?void 0:s.call(this.element)},set:s=>{var r;(r=e==null?void 0:e.set)==null||r.call(this.element,s),this.triggerChange()}});let o=this.element.disabled,n=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>n.disconnect())}};function ip(t,e,o){let n=`deepdesk-iframe-${t}`,s=document.getElementById(n);if(s)return s;let r=document.createElement("iframe"),i=new URL(e);return Object.entries(o).forEach(([a,l])=>{i.searchParams.append(a,l)}),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=n,r.title=`iframe-${t}`,r.src=i.toString(),window.document.body.appendChild(r),r}function hh(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}var Bi=class{constructor(e){this.name=e;this.broadcastChannel=new BroadcastChannel(e)}broadcastChannel;disposeHandlers=[];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()}},Ki=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=ip(e,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var o;(o=this.iframe.contentWindow)==null||o.postMessage(JSON.stringify(e),this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(o=>o()),(e=this.iframe)==null||e.remove()}},Ui=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(e){this.sessionId!==e&&(this.cleanup(),b.info("Set sessionId",e),this.sessionId=e,this.channel=this.createChannel(e))}createChannel(e){let o=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new Ki(e,this.deepdeskUrl,{debug:!0}):new Bi(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=hh(s.data);typeof r!="object"||r.type!=="event"||r.channel!==e||(b.info("Received broadcast event",this.sessionId,s),(a=(i=this.eventMap)[r.name])==null||a.call(i,r.payload))};return o.onMessage(n),o}send(e,o,n){var i,a;b.info("Broadcast event",{sessionId:this.sessionId,name:e,payload:o});let s={type:"event",name:e,payload:o};n!==!1&&((a=(i=this.eventMap)[e])==null||a.call(i,o));let r=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;r==null||r.postMessage({...s,channel:this.sessionId})}cleanup(e=!1){var o,n;(o=this.channel)==null||o.close(),delete this.channel,e&&((n=this.defaultChannel)==null||n.close(),delete this.defaultChannel)}},ap=Ui;var Io=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var zi=t=>new Promise(e=>{setTimeout(e,t)});var Lo=class extends Io{name="ClientError"},Wi=class extends Io{name="ServerError"},Vi=new Map;async function yh(t){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 o=await t.text();return o===""?null:(b.warn("Unexpected response body:",o.slice(0,20)),JSON.parse(o))}var Ae=class t{constructor(e="",o={}){this.baseUrl=e;this.options=o;o.fetch&&(this.fetch=o.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,o={}){return new Promise((n,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,l=o.method===void 0||o.method.toLowerCase()==="get",{useCache:d=!1,abortLatest:c=!1,attempts:p=1,retryDelay:u=500,refreshTokenOn401:m=!0,retryOnError:f=P=>P instanceof TypeError,retryOnResponse:g=P=>P.status>=500,version:x="v1",...y}=o;if(d)if(l){if(Vi.has(i)){n(Vi.get(i));return}}else throw new Error(`Can't use 'useCache' for ${o.method}`);let S={credentials:"include",...y,headers:{"Content-Type":"application/json",...y.headers}};!l&&this.csrfToken&&(S.headers={...S.headers,"X-CSRFToken":this.csrfToken}),typeof x=="string"&&(S.headers={...S.headers,"X-Deepdesk-API-Version":x});let v=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=async()=>(v--,a(i,S).then(async P=>g(P)&&!r.isAborted&&v>0?(await zi(u),w()):P.status===401&&m===!0&&I===!1?(I=!0,await this.refreshToken(),w()):P).catch(async P=>{if(f(P)&&!r.isAborted&&v>0)return await zi(u),w();throw P}));w().then(async P=>{let N=await yh(P);if(delete this.latestRequestByUrl[i],P.status>=500){s(new Wi("Server Error",N));return}else if(P.status===401){s(new Lo("Unauthorized",N));return}else if(P.status===403){s(new Lo("Forbidden",N));return}else if(P.status===404){s(new Lo("Not Found",N));return}else if(P.status>=400){s(new Lo("Bad Request",N));return}d&&Vi.set(i,N),n(N)}).catch(P=>{s(P)})})}async validateToken(){let{has_valid_access_token:e}=await this.get("/auth/validate");if(!e)return!1;let{is_logged_in:o}=await this.get("/apis/admin/session/validate/",{version:null});return!!o}refreshToken(){return t.refreshingToken||(t.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{t.refreshingToken=null},1e3*60)})),t.refreshingToken}get(e,o){return this.request(e,o)}post(e,o,n){return this.request(e,{method:"POST",body:JSON.stringify(o),...n})}patch(e,o,n){return this.request(e,{method:"PATCH",body:JSON.stringify(o),...n})}put(e,o,n){return this.request(e,{method:"PUT",body:JSON.stringify(o),...n})}delete(e,o){return this.request(e,{method:"DELETE",...o})}};var vh;(e=>{let t;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||={})})(vh||={});function dr(t){return{...A(t),tags:t.tags}}var dt=class t{constructor(e,o={}){this.options=o;this.client=new Ae(e,{fetch:o.fetch}),this.client.patchFetch(n=>async(s,r)=>{let i=await n(s,r);return this.handleDeepdeskVersionHeaders(i),i})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=await this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(t.exchangeTokenPromise||(t.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),t.exchangeTokenPromise):Promise.resolve()}async createConversation(e){await this.preflight(),b.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...U(e),tags:e.tags},{version:"v2"});return dr(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null,useCache:!0});return A(o)}async getKnowledgeAssistant(e){let o=await this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{version:null,useCache:!0});return A(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return A(e)}async getAccount(){let e=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return A(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null,useCache:!0});return A(e)}async checkUserExists(e){let{exists:o}=await this.client.get(`/apis/admin/users/exists?external_id=${e}`);return o}async getConversationBySessionId(e,o={}){await this.preflight(),b.info(`Getting conversation for session ${e}`);let{attempts:n=1,retryDelay:s=1e3}=o,r=await this.client.get(`/api/conversations/by_session_id/${e}`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"});return b.info(`Successfully retrieved conversation ${r.id} for session ${e}`),dr(r)}async isConversationSupported(e,o={}){b.info(`Check if conversation for session ${e} is supported`);let{attempts:n=1,retryDelay:s=1e3}=o;return(await this.client.get(`/api/conversations/by_session_id/${e}/active_profile`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"})).has_active_profile}async updateConversation(e,o){let n=U(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return dr(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...U(s),tags:s.tags})),{version:"v2"})).map(s=>dr(s))}async sendEvent(e,o){let{data:n,...s}=o,r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((i,[a,l])=>({...i,[a]:l}),{});return this.client.post("/api/events",U({...r,...s,data:n,name:e}),{version:"v2"})}async sendEventV1(e,o){let n=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[r,i])=>({...s,[r]:i}),{});return this.client.post("/api/events",{event:e,data:U({...o,...n})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e.filter(n=>n.text)})).entities}async getSummary(e,o={}){let n=await this.client.post("/api/summary",{conversation:{messages:e.filter(s=>s.text&&s.source),agent_id:o.agentId,id:o.externalConversationId},prompt_instruction:o.promptInstruction,model:o.model});return A(n)}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(e){return this.client.post("/apis/admin/session/jwt/",{jwt:e},{version:null}).catch(o=>{throw b.warn(`Invalid token '${e}'`),o})}async authenticateWithKey(e,o){await this.preflight(),await this.client.post("/apis/admin/session/api-key/",U(o),{version:null,refreshTokenOn401:!1,headers:{apikey:e}})}async getTextSuggestions(e,o={},n){return n==="sticky-messages"?this.getPinnedMessages(e):(await this.client.post(`/api/conversations/${e}/recommend/${n}`,U(o),{abortLatest:!0})).map(r=>({...A(r),text:r.text||r.url||r.message,source:n,type:n})).filter((r,i,a)=>i===a.findIndex(l=>l.text===r.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(e,o){return(await this.client.post(`/api/conversations/${e}/autocomplete`,U(o),{abortLatest:!0})).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))}async getPinnedMessages(e){let o=await this.client.get(`/api/conversations/${e}/sticky-messages`,{abortLatest:!0});return A(o).map(n=>({...n,text:n.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(e){let o=await this.client.post("/api/style-suggestions",U(e),{abortLatest:!0});return A(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,U(e),{version:"v2"});return A(o)}async knowledgeAssist(e,o,n,s={}){let r=await this.client.post(`/api/knowledge-assist/assistants/${n}/search`,U({question:e.question,doNotKnowAnswer:e.doNotKnowAnswer,customerInstruction:e.customerInstruction,chatHistory:o.map(i=>({question:i.question,answer:i.answer.answer})),agentId:s.agentId,conversationId:s.conversationId}),{version:"v2"});return A(r)}async requestLoginByEmail(e){let o=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return A(o)}async requestPasswordlessToken(){let e=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return A(e.token)}async getCsrfToken(){let{token:e}=await this.client.get("/apis/admin/session/csrf/",{version:null});return e}async verifyLoginToken(e){let o=await this.client.post("/apis/admin/session/passwordless/login/",{token:e},{version:null});return A(o)}async evaluateRule(e,o,n,s={}){let r=new URLSearchParams;s.raiseForFailingConditions&&r.set("raise_for_failing_conditions","true");let i=await this.client.post(`/api/conversations/${o}/rules/${e}/evaluate?${r.toString()}`,n,{version:"v2"});return A(i.cues)}async getRules(){let e=new URLSearchParams,o=await this.client.get(`/apis/admin/rule-engine/rules/?${e.toString()}`,{version:null,useCache:!0});return A(o)}async translateMessages(e){let o=await this.client.post("/api/translate",U(e),{version:"v2"});return A(o)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(va);if(!o||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&o&&a!==o&&b.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(o)}`),this.latestReceivedDeepdeskVersions[i]=o})}};var Tn=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(Rr(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,A(s))}catch{b.warn(`Invalid JSON for ${e}: ${n}`)}})}connect(){clearTimeout(this.timeoutTimer);let e=new EventSource(this.url,{withCredentials:!0});this.eventSource=e;let o=!1;e.onopen=()=>{o=!0},e.onerror=()=>{o&&e.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{e.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(n=>{this.proxyEvent(n)})}disconnect(){var e;clearTimeout(this.timeoutTimer),this.eventListeners={},(e=this.eventSource)==null||e.close()}emit(e,o){this.eventListeners[e]&&this.eventListeners[e].forEach(n=>n(o))}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),this.proxyEvent(e),()=>{this.off(e,o)}}off(e,o){let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}};var Sh;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(Sh||={});var En=class{constructor(e,o={}){this.apiUrl=e;this.client=new Ae(e,o)}client;streams={};logger=b;async getCustomMessages(e){let o=await this.client.get(`/sessions/${e}/suggestions`);return A(o.suggestions)}async sendCustomMessage(e,o){let n=await this.client.post(`/sessions/${e}/messages`,U(o));return A(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,U(o))}async getAutoflows(e){let o=await this.client.get(`/sessions/${e}/autoflows`);return A(o.autoflows)}async startAutoflowSession(e){let o=await this.client.post("/autoflow-sessions",U(e));return A(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new Tn(`${this.apiUrl}/sessions/${e}/events`),this.streams[e].connect()),this.streams[e]}closeStream(e){this.streams[e]||(this.streams[e].disconnect(),delete this.streams[e])}};var mr=require("@reduxjs/toolkit");var dp=require("@reduxjs/toolkit");var lp={startTime:null,stopTime:null},cp=(0,dp.createSlice)({name:"handlingTime",initialState:lp,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(O,()=>lp)}}),{handlingTimeStart:up,handlingTimeStop:cr,handlingTimeReset:pp}=cp.actions,mp=cp.reducer;var gp=(t={})=>{let e={onAuthError:oo(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};var pr=require("@reduxjs/toolkit");var ur={list:{keywordMatches:[]},fetchState:"idle"};var Jt=(0,pr.createAsyncThunk)("styleSuggestions/getAll",async({text:t},e)=>{var i;let{deepdeskAPI:o}=e.extra,n=e.getState(),{showStyleSuggestions:s}=n.settings,r=(i=n.conversation.current)==null?void 0:i.profileCode;if(!s)return ur.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),xh=(0,pr.createSlice)({name:"styleSuggestions",initialState:ur,reducers:{},extraReducers:t=>{t.addCase(Jt.pending,e=>{e.fetchState="loading"}).addCase(Jt.rejected,e=>{e.fetchState="error"}).addCase(Jt.fulfilled,(e,o)=>{e.fetchState="done",pt(e.list,o.payload)||(e.list=o.payload)}).addCase(Nt,e=>{e.list=ur.list}).addCase(O,()=>ur)}}),fp=xh.reducer;var hp=(t={})=>{let e,o=!0,n={getStyleSuggestions:Jt,debounce:500,...t};return s=>r=>i=>{var m;let a=s.getState().input.text,l=r(i),d=s.getState();if(d.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=d.settings;if(!((m=d.conversation.current)==null?void 0:m.id)||!c)return l;let{text:u}=d.input;return u===a&&!o||(clearTimeout(e),u==="")||(e=setTimeout(()=>{o=!1,s.dispatch(n.getStyleSuggestions({text:u}))},t.debounce)),l}};function bh(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var yp=(t={})=>{let e={getTextSuggestions:Pe,getAutocompleteSuggestions:nn,debounce:200,check:xo,...t},o;return n=>s=>r=>{var g;let{input:{userCommitted:i}}=n.getState(),a=s(r),l=n.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:d,showTabCompletion:c}=l.settings,p=(g=l.conversation.current)==null?void 0:g.id,u=r.type===As.toString();if(!p||!d&&!c)return a;let{input:{userCommitted:m}}=l;return bh(m,i)&&!u||(clearTimeout(o),!e.check(l))||(o=setTimeout(()=>{let x=ro(l);x===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(x))},u?0:e.debounce)),a}};var vp=Jt.fulfilled.toString();function Ch(t,e){let o=new Set([...e.keywordMatches.map(s=>s.keyword)]),n=[];return o.forEach(s=>{let r=t.keywordMatches.filter(l=>l.keyword===s),i=e.keywordMatches.filter(l=>l.keyword===s),a=i.length-r.length;a<=0||n.push(...i.slice(0,a))}),n}var Sp=t=>e=>o=>n=>{var d;if(n.type!==vp){o(n);return}let s=e.getState().styleSuggestions.list;o(n);let r=e.getState(),i=r.styleSuggestions.list,a=(d=r.conversation)==null?void 0:d.current;if(s===i)return;let l=Ch(s,i);n.type===vp&&l.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var wh=(0,mr.combineReducers)({answer:Sd,auth:Ia,autoflows:tu,conversation:Na,contentTypes:Al,customMessages:cu,passwordlessToken:mu,entities:Jl,knowledgeAssistant:hd,handlingTime:mp,info:ol,input:Qa,settings:Ca,profile:wd,search:dl,summary:rd,styleSuggestions:fp,ui:nc,rules:vu,textSuggestions:Ad});function xp(t){return(0,mr.configureStore)({reducer:wh,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),gp(),yp({debounce:200}),hp({debounce:500}),Sp(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var Th=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},Eh=t=>e=>o=>n=>{var a,l,d,c,p,u;let s=e.getState(),r=Cr("inlineSuggestions")(s);switch(n.type){case oo.toString():{!n.payload&&t.emit("logout",void 0);break}case ke.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:(a=s.conversation.current)==null?void 0:a.id,data:{entities:n.payload}});break;case Z.toString():t.sendEvent(n.payload.name,{conversationId:((l=n.payload.options)==null?void 0:l.includeConversationData)&&((d=s.conversation.current)==null?void 0:d.id),data:n.payload.data});break;case Gn.toString():t.handleKeyDown(n.payload);break;case Nt.toString():t.logSendMessage(n.payload);break;case jn.toString():t.handleInputChanged(n.payload);break;case jt.fulfilled.toString():n.isBroadcasted||t.broadcast(Lr,n,!1),(c=n.payload.options)!=null&&c.shouldEmit&&t.emit("cues",n.payload.cues);break;default:break}let i=o(n);switch(n.type){case Nt.toString():t.handleAfterSendMessage(n.payload);break;case rn.toString():t.onUpdateShowTabHint(n.payload);break;case cr.toString():t.logHandlingTime();break;case"analytics/logEvent/fulfilled":{t.emit("event",n.meta.arg);break}case Oe.toString():{let{start:m,end:f}=s.input.selection;t.emit("select-suggestion",{type:Th(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:m,end:f}:{start:0,end:f}},{mayApplyChanges:!0}),r&&(e.dispatch(Ne([])),e.dispatch($e()));break}case qn.toString():{let{start:m,end:f}=s.input.selection;t.emit("replace",{...n.payload,replace:n.payload.replace==="selection"?{start:m,end:f}:{start:0,end:f}},{mayApplyChanges:!0});break}case _o.toString():{let m=e.getState(),{text:f,selection:g}=m.input.userCommitted;t.emit("reset",{text:f,selectionAfter:g},{mayApplyChanges:!0});break}case Xn.toString():t.emit("select-image",n.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:(p=s.conversation.current)==null?void 0:p.id,data:{path:n.payload.suggestion.image,title:n.payload.suggestion.title}});break;case Ne.toString():{r&&n.payload.length>0&&e.dispatch(ft(0));break}case Xe.fulfilled.toString():{t.sendEvent("conversation summarized",{conversationId:(u=s.conversation.current)==null?void 0:u.id,data:{summary:n.payload.summary,model:e.getState().summary.model}});break}default:break}return i},bp=Eh;function $i(t){return t.toISOString().replace("T"," ").replace("Z","")}function Cp(t,e){var r,i,a,l;let o=(r=t.conversation.current)==null?void 0:r.id;if(!o)return b.warn("No conversationId for handling time metrics"),null;let{startTime:n,stopTime:s}=t.handlingTime;return!n||!s?(b.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:o,clientVersion:e.version,agentId:(i=t.info.agentInfo)==null?void 0:i.agentId,agentName:(a=t.info.agentInfo)==null?void 0:a.agentName,agentEmail:(l=t.info.agentInfo)==null?void 0:l.agentEmail,timeStart:$i(n),timeStop:$i(s)}}function wp(t,e,o){var te,q,L,B;let n=(te=e.conversation.current)==null?void 0:te.id;if(!n)return b.warn("No conversationId for send message metrics"),null;let{text:s,metrics:{numCharsTyped:r,numCharsPasted:i,numCharsCut:a,numCharsDeleted:l,numPaste:d,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:u,cuts:m,deletions:f,textSuggestions:g,offeredTextSuggestions:x}}=e[t],y=s.length,v=g.reduce((me,{text:oe,searchTerm:Pn})=>me+oe.length-(Pn?Pn.length:0),0),I=c??Date.now(),w=(Date.now()-I)/1e3+(p||0),P=r/w,N=g.reduce((me,{searchTerm:oe})=>me+(oe?oe.length:0),0);return{conversationId:n,source:"agent",text:s,clientVersion:o.version,pastes:u,cuts:m,deletions:f,lenTextTyped:r+N,lenTextTotal:y,lenTextAssisted:v,lenTextPasted:i,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:w,charsPerSecond:P,numPastes:d,textSuggestionsV2:g,suggestionsCounters:[{source:"gpt",countOffered:x.filter(me=>me.source==="gpt").length}],agentId:(q=e.info.agentInfo)==null?void 0:q.agentId,agentName:(L=e.info.agentInfo)==null?void 0:L.agentName,agentEmail:(B=e.info.agentInfo)==null?void 0:B.agentEmail}}function qi(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return qi(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?qi(s,e):null}function Tp(t,e){return qi(t,e)}function Ep(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function kh(t){return typeof t=="object"&&t!==null&&"tagName"in t}function gr(t){return kh(t)&&(Ct(t)||Us(t))}var Rp,Ke=new Map,Rh=["bottom","height","left","right","top","width"],kp=(t,e)=>!t&&!e?!1:t&&!e||!t&&e?!0:Rh.some(o=>t[o]!==e[o]);function Pp(t){var o,n;if(t.ownerDocument===document)return[];let e=((n=(o=t.ownerDocument)==null?void 0:o.defaultView)==null?void 0:n.frameElement)??null;return e?[e,...Pp(e)]:[]}function Ip(t,e){return!t||!e?null:{...t,top:t.top+e.top,left:t.left+e.left}}var fr=!1,Lp=()=>{fr=!0;let t=[];if(Ke.forEach((e,o)=>{if(!o.isConnected){e.rect=null,t.push(e),Ke.delete(o);return}let n=o.getBoundingClientRect();kp(n,e.rect)&&(e.rect=n,t.push(e))}),t.forEach(e=>{let o=e.parentRects?e.parentRects.reduce(Ip,e.rect):e.rect;kp(o,e.totalRect)&&e.callbacks.forEach(n=>n(o)),e.totalRect=o}),Ke.size===0){fr=!1;return}Rp=window.requestAnimationFrame(Lp)};function Gi(t,e){let o=Pp(t),n=[],s=o.map((r,i)=>Gi(r,a=>{n[i]=a;let l=Ke.get(t);if(!l)return;let d=n.reduce(Ip,l.rect);l.callbacks.forEach(c=>c(d))}));return{observe(r=!0){if(s.forEach(i=>i.observe(!1)),Ke.has(t)){let i=Ke.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else Ke.set(t,{rect:void 0,callbacks:[e],parentRects:n});r&&!fr&&Lp()},unobserve(){s.forEach(i=>i.unobserve());let r=Ke.get(t);if(r){let i=r.callbacks.indexOf(e);i>=0&&r.callbacks.splice(i,1),r.callbacks.length||Ke.delete(t),Ke.size||(cancelAnimationFrame(Rp),fr=!1)}}}}var Ap,Ue=new Map,Mp=()=>{Ue.forEach((t,e)=>{if(!e.isConnected){Ue.delete(e);return}let{clientHeight:o,scrollHeight:n}=e,s=n>o;t.visible!==s&&(t.visible=s,t.callbacks.forEach(r=>r(t.visible)))}),Ue.size!==0&&(Ap=window.requestAnimationFrame(Mp))};function Np(t,e){return{observe(){let o=Ue.size===0;Ue.has(t)?Ue.get(t).callbacks.push(e):Ue.set(t,{visible:void 0,callbacks:[e]}),o&&Mp()},unobserve(){let o=Ue.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||Ue.delete(t),Ue.size||cancelAnimationFrame(Ap)}}}}var ji=["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 Xi(t,e,o){return o.forEach(n=>{e.style[n]=t[n]})}function Ao(t){return parseFloat(t)}function hr(t){return Math.round(t*1e6)}function Op(t){return t/1e6}function Qi(t,e,o){if(t.boxSizing==="content-box")return;let{clientWidth:n}=e,s=Ao(t.width),r=Ao(t.borderLeftWidth),i=Ao(t.borderRightWidth),a=Ao(t.paddingRight),l=Op(hr(s)-hr(r)-hr(i)),d=Op(hr(n));if(l-d>2){let c=l-d;o.style.paddingRight=`${a+c}px`}}function kn(t,e={}){var c;let o=e.overlayContainer||document.createElement("div");o.style.display="none",o.style.position=e.position??"fixed",o.style.pointerEvents="none",o.style.borderColor="transparent",$t(o);let n=window.getComputedStyle(t),s=!0,r=()=>{o.scrollTop=t.scrollTop};Xi(n,o,ji),Qi(n,t,o),e.mirrorOverflow&&(o.style.overflow="hidden",t.addEventListener("scroll",r));let i=Np(t,()=>{Xi(n,o,ji),Qi(n,t,o),r(),setTimeout(r,0)}),a,l=!0,d=Gi(t,p=>{if(p===null){e.onRemove&&e.onRemove(),o.remove();return}if(!l&&e.onMoveStart&&(Promise.resolve().then(()=>e.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{e.onMoveEnd&&e.onMoveEnd(),l=!1},200),p.height===0&&p.width===0){if(s===!0)return;e.onHide&&e.onHide(),o.style.display="none",s=!0;return}if(Xi(n,o,ji),Qi(n,t,o),r(),o.style.top=`${p.top}px`,o.style.left=`${p.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let u=e.closestScrollElement.getBoundingClientRect(),m=window.getComputedStyle(e.closestScrollElement),f=Ao(m.borderTopWidth),g=Ao(m.borderBottomWidth),x=u.top+f-p.top,y=p.top+p.height+-(u.top+u.height-g);o.style.clipPath=`inset(${x}px 0px ${y}px 0px)`}s&&(o.style.display="block",e.onShow&&e.onShow(),s=!1)});return e.appendTo?e.appendTo.appendChild(o):(c=t.parentElement)==null||c.appendChild(o),d.observe(),i.observe(),[o,()=>{t.removeEventListener("scroll",r),d.unobserve(),i.unobserve()}]}var Dp=(t,e)=>({value(){try{let o=sessionStorage.getItem(`dd-${t}`);if(!o)return e;try{return JSON.parse(o)}catch{return e}}catch{return e}},update(o){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(o))}catch{b.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function Ph(t){return t.offsetParent!==null}function _p(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 yr(t,e,o=100){let n=_p(t);e({isVisible:n});let s=setInterval(()=>{let r=_p(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}var V=require("react/jsx-runtime");var Fp=Dp("showTabHint",!0),Rn=class t{static version="11.5.5-beta.3";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:l}){let d=e.replace(/\/api$/,"");this.deepdeskApi=new dt(d,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[bp({broadcast:(p,u,m)=>{this.broadcastEvents.send(p,u,m)},emit:(p,u,m)=>this.emit(p,u,m),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),onUpdateShowTabHint:p=>Fp.update(p),sendEvent:(p,u)=>this.deepdeskApi.sendEvent(p,u)})]};o&&Object.assign(c,{deepdeskBrokerAPI:new En(o)}),this.store=xp(c),this.broadcastEvents=new ap({debug:!0,deepdeskUrl:d,eventMap:cl(this.store),createCustomChannel:l}),this.store.dispatch(rn(Fp.value())),this.store.dispatch(Kn({locale:s,adminUrl:d,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??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?(b.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(b.warn("Profile has not been loaded (yet)"),!0):(b.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(oo(null)),this.store.dispatch(Ve()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();Q(n)&&wa(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(Ve())).payload}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(o){b.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(Tr({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Un(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(zn({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Er(e))).payload}async postMessages(e){return(await this.store.dispatch(Wn(e))).payload}async updateConversation(e){return(await this.store.dispatch(Vn(e))).payload}resetConversation(){this.store.dispatch(O()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Xe());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(Kn(e))}setVisitorInfo(e){this.store.dispatch(el(e))}setCustomData(e){this.store.dispatch(tl(e))}async setAgentInfo(e){await this.store.dispatch(Fo(e))}async setAgentSettings(e){await this.store.dispatch(Pr(e))}async getAgentSettings(){return(await this.store.dispatch(Ir())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(As()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(jn(e))}notifyKeyDown(e){this.store.dispatch(Gn(e))}notifyPaste(e,o){this.store.dispatch(qa({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Wa(e))}notifyExternalSuggestion(e){this.store.dispatch(Oe(e)),this.store.dispatch($e())}async evaluateRule(e,o={},n=gu){let{payload:s,error:r}=await this.store.dispatch(jt({label:e,params:o,options:n}));if(r)throw new Error(r.message);return s.cues}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(xt({collapse:!1})),this.inputMediator&&this.store.dispatch(Ba({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(Ne([])))}handleKeyDown(e){let{overlayCollapsed:o}=this.state.ui,{textSuggestions:n,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=n.length>0,l=s!==-1;if(this.store.dispatch($a(_a(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let d=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Ua()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},c=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(Va()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(_o()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(e.key){case"Up":case"ArrowUp":i?c():d();return;case"Down":case"ArrowDown":{i?d():c();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(ft(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(ft(-1)),this.store.dispatch(_o()),e.preventDefault()):o||(this.store.dispatch(xt({collapse:!0})),this.store.dispatch(tc(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,u=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:m}=this.state.input;this.store.dispatch(rn(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&m&&m.text.startsWith(u)&&(this.store.dispatch(Oe({text:m.text,suggestion:m,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch($e())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Ga()),this.store.dispatch(Ne([]))}handlingTimeStart(){this.state.handlingTime.startTime||(b.info("Start handling time"),this.store.dispatch(up()))}handlingTimeStop(){this.state.handlingTime.startTime&&(b.info("Stop handling time"),this.store.dispatch(cr()))}logSendMessage(e){let o=wp("input",this.state,{version:this.version});o&&(e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o))}logHandlingTime(){let e=Cp(this.state,{version:this.version});e&&(this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(pp()))}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch($e()),this.store.dispatch(Nt(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(Oe({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{let r=this.eventListeners[e];r&&r.forEach(i=>{try{i(o)}catch(a){b.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),b.error(a)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=kn(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{(0,xe.unmountComponentAtNode)(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.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",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=kn(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{(0,xe.unmountComponentAtNode)(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return $t(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{(0,xe.unmountComponentAtNode)(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),b.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(b.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Xa(n.metrics))):b.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch{}}mount(e,o={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!gr(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:n={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:d,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:u,insertLink:m,inputMediator:f,closestScrollSelector:g,appendOverlayTo:x,inlineSuggestions:y,floatingMenu:S}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:d,showSuggestionsAfterPattern:c,showTextSuggestions:i,insertLink:m,isEmbedded:p,inlineSuggestions:y,floatingMenu:!!S}),o.automaticHandlingTime&&this.setupHandlingTime(e),$t(e),this.inputMediator=f||(Ct(e)?new Zt(e):new Qt(e)),this.inputMediator.on("change",({plainText:w})=>{this.notifyInputChanged(w)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(ja({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",w=>{this.notifyKeyDown(w)}),this.inputMediator.on("paste",({pastedText:w,selectionText:P})=>{this.notifyPaste(w,P)}),this.inputMediator.on("cut",({selectionText:w})=>{this.notifyCut(w)});let v=g&&Tp(e,g)||void 0;if(y){let{customStyles:w,appendOverlayTo:P}=o;if(Ct(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let N=this.createInlineContainer(e,"deepdesk-caret");(0,xe.render)((0,V.jsx)(Gt,{store:this.store,customStyles:w,children:(0,V.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(cc,{})})}),N),this.inputMediator.on("caret",q=>{this.store.dispatch(Ne([])),q?(N.style.display="block",N.style.top=`${q.top}px`,N.style.left=`${q.left}px`):N.style.display="none"});let te=this.overlayContainerFactory("floating-menu",v||e,{appendTo:typeof S=="object"&&"appendOverlayTo"in S?S.appendOverlayTo:P},w==null?void 0:w.floatingMenuRootNode);(0,xe.render)((0,V.jsx)(Gt,{store:this.store,customStyles:w,children:(0,V.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(Zd,{onLogIn:()=>this.loginViaPopup().catch(q=>b.warn(q.message))})})}),te)}else{let w=this.overlayContainerFactory("deepdesk-tab-completion",v||e,{appendTo:x,closestScrollElement:v,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),P=this.overlayContainerFactory("deepdesk-suggestions-overlay",v||e,{appendTo:x},n==null?void 0:n.suggestionsRootNode);(0,xe.render)((0,V.jsx)(Gt,{store:this.store,customStyles:n,children:(0,V.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(Xc,{inputElement:e})})}),w),(0,xe.render)((0,V.jsx)(Gt,{store:this.store,customStyles:n,children:(0,V.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(bc,{onLogIn:()=>this.loginViaPopup().catch(N=>b.warn(N.message))})})}),P)}(0,xe.render)((0,V.jsx)(Gt,{store:this.store,customStyles:n,children:(0,V.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(Wd,{})})}),this.createContainer("deepdesk-overlays"));let I;this.inputMediator.on("selection",w=>{clearTimeout(I),w===null?I=setTimeout(()=>{w!==null&&this.store.dispatch(kr(w))},500):this.store.dispatch(kr(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(ci(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(ci(!0))),this.store.dispatch(Ka({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch($e()),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(o=>o()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,o={}){if(this.widgetRoot&&b.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:n,showImages:s,isEmbedded:r}=o;this.widgetRoot=e,this.configure({showImages:s,isEmbedded:r}),(0,xe.render)((0,V.jsx)(Gt,{store:this.store,customStyles:n,children:(0,V.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(op,{onLogIn:()=>this.loginViaPopup().catch(i=>b.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,xe.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=yr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Ep(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(on());let e=Je(this.state);e&&(await this.store.dispatch(Jo()),this.store.dispatch(Kn({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:!!e.knowledgeAssistant,recommendTextSuggestions:e.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(e){return new Promise((o,n)=>{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 l=!1,d=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(u)};r.onmessage=async m=>{var f,g;if((f=m.data)!=null&&f.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((g=m.data)==null?void 0:g.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Bo),l=!0,s.port1.close(),o()}catch(x){console.error(x),n(x)}finally{l=!0,d()}};let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&n(new Error("Popup blocked by browser"));let p=async m=>{var f;if(m.origin===a.origin)switch((f=m.data)==null?void 0:f.type){case"deepdesk-popup-loaded":{try{let g=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(g,a.origin,[s.port2])}catch(g){b.error("Error posting message to popup",g),n(g)}break}case"deepdesk-popup-error":{d(),m.data.message==="Timeout"&&b.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(m.data.message));break}}};window.addEventListener("message",p);let u=setInterval(()=>{c&&!c.closed||(d(),l||n(new Error("Popup closed by user")))},200);this.unmountHandlers.push(d)})}translateMessages(e){return this.deepdeskApi.translateMessages(e)}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(b.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(o){let{message:n}=o;b.info(n),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let o=Is(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(ke()):Bn.includes(n)||this.store.dispatch(Pe(n))})}catch(n){this.handleError(n)}}};async function Hp(t,e,o={}){let{value:n}=t,{start:s,end:r}=o.replace??{start:0,end:n.length},i=`${n.slice(0,s)}${e}${n.slice(r)}`,a=o.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function Bp(t,e,o={}){let n=o.replace?Pt(t,o.replace.start,o.replace.end):Po(t),s,r=()=>{if(o.setRange)return o.setRange(n.cloneRange());n.deleteContents(),s=document.createElement("span"),n.insertNode(s),o.insertBRs!==!1?e.split(`
|
|
10
|
+
`);break}default:break}p&&i++}return l(t),a}var sp=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(sp||{}),lt=class{constructor(e){this.element=e;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(e,o){let n=s=>{o(s)};this.element.addEventListener(e,n),this.disposeHandlers.push(()=>{this.element.removeEventListener(e,n)})}removeEventListener(e,o){this.element.removeEventListener(e,o)}triggerChange(){let e=this.getText(),o=this.getHTML(),n=e!==this.currentText;this.isActive&&(e===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&n&&!this.isSubmitting&&this.emit("change",{plainText:e}),n&&(this.currentSelection=this.getSelection()),this.currentText=e,this.isSubmitting=!1,(this.currentHTML!==o||o===null&&n)&&(this.emit("updated",{plainText:e}),this.triggerCaretPosition(),this.currentHTML=o))}triggerSelection(){let e=this.getSelection();(e.start!==this.currentSelection.start||e.end!==this.currentSelection.end)&&(this.currentSelection=e,this.emit("selection",e),this.triggerCaretPosition())}triggerCaretPosition(){let e=this.getCaretPosition();pt(e,this.currentCaret)||(this.currentCaret=e,this.emit("caret",e))}handleKeyUp(e){let{key:o,shiftKey:n}=e;(o==="Enter"&&n===!0||o==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(e){let{key:o,ctrlKey:n,metaKey:s}=e;this.isPossibleClearInputAction=Object.values(sp).includes(o)||o.toLowerCase()==="z"&&(n||s),this.emit("keydown",e)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){var n,s;let o=((n=e.clipboardData)==null?void 0:n.getData("text"))||((s=e.clipboardData)==null?void 0:s.getData("text/plain"))||"";this.emit("paste",{pastedText:o,selectionText:this.getSelectedText()})}listen(e={shouldObserve:!0}){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),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.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let o=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});e!=null&&e.shouldObserve&&o.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{o.disconnect()}),this.currentSelection=this.getSelection()}focus(){this.element.focus()}emit(e,...o){this.isDisposed||this.eventListeners[e]&&this.eventListeners[e].forEach(n=>{n(...o)})}on(e,o){this.isDisposed||(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o))}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};function rp(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var Qt=class extends lt{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),wn(this.element,e)}getHTML(){return this.element.innerHTML||""}getRange(){var r;let e=this.getRootNode();if(e.activeElement!==this.element)return null;let o="getSelection"in e?e.getSelection():window.getSelection();if(!o)return null;let n="getComposedRanges"in o&&e instanceof ShadowRoot?(r=o.getComposedRanges(e))==null?void 0:r[0]:o.rangeCount>0?o.getRangeAt(0):null;if(!n)return null;let s=this.element.ownerDocument.createRange();return s.setStart(n==null?void 0:n.startContainer,n==null?void 0:n.startOffset),s.setEnd(n==null?void 0:n.endContainer,n==null?void 0:n.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let e=this.getRange();if(!e||!e.collapsed||!("getBoundingClientRect"in e))return null;let o=e.getBoundingClientRect();return!rp(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!rp(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return Cn(this.element,e);let o=this.lastKnownSelection;if(o&&np(this.element,o.start,o.end))return o;let n=Po(this.element);return n.collapse(!1),Cn(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return wn(this.element,Pt(this.element,e,o))}applyChanges(e){var s;if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return(s=this.observer)==null||s.takeRecords(),Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(e={shouldObserve:!0}){super.listen(e),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),e!=null&&e.shouldObserve&&this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let o=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==o&&(o=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>n.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var Zt=class extends lt{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:e,selectionEnd:o}=this.element;return{start:e,end:o}}getSelectedText(){let e=this.getSelection();return e?this.getText().slice(e.start,e.end):""}getCaretPosition(){return null}applyChanges(e){if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let e=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=e==null?void 0:e.get)==null?void 0:s.call(this.element)},set:s=>{var r;(r=e==null?void 0:e.set)==null||r.call(this.element,s),this.triggerChange()}});let o=this.element.disabled,n=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>n.disconnect())}};function ip(t,e,o){let n=`deepdesk-iframe-${t}`,s=document.getElementById(n);if(s)return s;let r=document.createElement("iframe"),i=new URL(e);return Object.entries(o).forEach(([a,l])=>{i.searchParams.append(a,l)}),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=n,r.title=`iframe-${t}`,r.src=i.toString(),window.document.body.appendChild(r),r}function hh(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}var Bi=class{constructor(e){this.name=e;this.broadcastChannel=new BroadcastChannel(e)}broadcastChannel;disposeHandlers=[];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()}},Ki=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=ip(e,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var o;(o=this.iframe.contentWindow)==null||o.postMessage(JSON.stringify(e),this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(o=>o()),(e=this.iframe)==null||e.remove()}},Ui=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(e){this.sessionId!==e&&(this.cleanup(),b.info("Set sessionId",e),this.sessionId=e,this.channel=this.createChannel(e))}createChannel(e){let o=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new Ki(e,this.deepdeskUrl,{debug:!0}):new Bi(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=hh(s.data);typeof r!="object"||r.type!=="event"||r.channel!==e||(b.info("Received broadcast event",this.sessionId,s),(a=(i=this.eventMap)[r.name])==null||a.call(i,r.payload))};return o.onMessage(n),o}send(e,o,n){var i,a;b.info("Broadcast event",{sessionId:this.sessionId,name:e,payload:o});let s={type:"event",name:e,payload:o};n!==!1&&((a=(i=this.eventMap)[e])==null||a.call(i,o));let r=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;r==null||r.postMessage({...s,channel:this.sessionId})}cleanup(e=!1){var o,n;(o=this.channel)==null||o.close(),delete this.channel,e&&((n=this.defaultChannel)==null||n.close(),delete this.defaultChannel)}},ap=Ui;var Io=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var zi=t=>new Promise(e=>{setTimeout(e,t)});var Lo=class extends Io{name="ClientError"},Wi=class extends Io{name="ServerError"},Vi=new Map;async function yh(t){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 o=await t.text();return o===""?null:(b.warn("Unexpected response body:",o.slice(0,20)),JSON.parse(o))}var Ae=class t{constructor(e="",o={}){this.baseUrl=e;this.options=o;o.fetch&&(this.fetch=o.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,o={}){return new Promise((n,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,l=o.method===void 0||o.method.toLowerCase()==="get",{useCache:d=!1,abortLatest:c=!1,attempts:p=1,retryDelay:u=500,refreshTokenOn401:m=!0,retryOnError:f=P=>P instanceof TypeError,retryOnResponse:g=P=>P.status>=500,version:x="v1",...y}=o;if(d)if(l){if(Vi.has(i)){n(Vi.get(i));return}}else throw new Error(`Can't use 'useCache' for ${o.method}`);let S={credentials:"include",...y,headers:{"Content-Type":"application/json",...y.headers}};!l&&this.csrfToken&&(S.headers={...S.headers,"X-CSRFToken":this.csrfToken}),typeof x=="string"&&(S.headers={...S.headers,"X-Deepdesk-API-Version":x});let v=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=async()=>(v--,a(i,S).then(async P=>g(P)&&!r.isAborted&&v>0?(await zi(u),w()):P.status===401&&m===!0&&I===!1?(I=!0,await this.refreshToken(),w()):P).catch(async P=>{if(f(P)&&!r.isAborted&&v>0)return await zi(u),w();throw P}));w().then(async P=>{let N=await yh(P);if(delete this.latestRequestByUrl[i],P.status>=500){s(new Wi("Server Error",N));return}else if(P.status===401){s(new Lo("Unauthorized",N));return}else if(P.status===403){s(new Lo("Forbidden",N));return}else if(P.status===404){s(new Lo("Not Found",N));return}else if(P.status>=400){s(new Lo("Bad Request",N));return}d&&Vi.set(i,N),n(N)}).catch(P=>{s(P)})})}async validateToken(){let{has_valid_access_token:e}=await this.get("/auth/validate");if(!e)return!1;let{is_logged_in:o}=await this.get("/apis/admin/session/validate/",{version:null});return!!o}refreshToken(){return t.refreshingToken||(t.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{t.refreshingToken=null},1e3*60)})),t.refreshingToken}get(e,o){return this.request(e,o)}post(e,o,n){return this.request(e,{method:"POST",body:JSON.stringify(o),...n})}patch(e,o,n){return this.request(e,{method:"PATCH",body:JSON.stringify(o),...n})}put(e,o,n){return this.request(e,{method:"PUT",body:JSON.stringify(o),...n})}delete(e,o){return this.request(e,{method:"DELETE",...o})}};var vh;(e=>{let t;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||={})})(vh||={});function dr(t){return{...A(t),tags:t.tags}}var dt=class t{constructor(e,o={}){this.options=o;this.client=new Ae(e,{fetch:o.fetch}),this.client.patchFetch(n=>async(s,r)=>{let i=await n(s,r);return this.handleDeepdeskVersionHeaders(i),i})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=await this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(t.exchangeTokenPromise||(t.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),t.exchangeTokenPromise):Promise.resolve()}async createConversation(e){await this.preflight(),b.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...U(e),tags:e.tags},{version:"v2"});return dr(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null,useCache:!0});return A(o)}async getKnowledgeAssistant(e){let o=await this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{version:null,useCache:!0});return A(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return A(e)}async getAccount(){let e=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return A(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null,useCache:!0});return A(e)}async checkUserExists(e){let{exists:o}=await this.client.get(`/apis/admin/users/exists?external_id=${e}`);return o}async getConversationBySessionId(e,o={}){await this.preflight(),b.info(`Getting conversation for session ${e}`);let{attempts:n=1,retryDelay:s=1e3}=o,r=await this.client.get(`/api/conversations/by_session_id/${e}`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"});return b.info(`Successfully retrieved conversation ${r.id} for session ${e}`),dr(r)}async isConversationSupported(e,o={}){b.info(`Check if conversation for session ${e} is supported`);let{attempts:n=1,retryDelay:s=1e3}=o;return(await this.client.get(`/api/conversations/by_session_id/${e}/active_profile`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"})).has_active_profile}async updateConversation(e,o){let n=U(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return dr(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...U(s),tags:s.tags})),{version:"v2"})).map(s=>dr(s))}async sendEvent(e,o){let{data:n,...s}=o,r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((i,[a,l])=>({...i,[a]:l}),{});return this.client.post("/api/events",U({...r,...s,data:n,name:e}),{version:"v2"})}async sendEventV1(e,o){let n=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[r,i])=>({...s,[r]:i}),{});return this.client.post("/api/events",{event:e,data:U({...o,...n})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e.filter(n=>n.text)})).entities}async getSummary(e,o={}){let n=await this.client.post("/api/summary",{conversation:{messages:e.filter(s=>s.text&&s.source),agent_id:o.agentId,id:o.externalConversationId},prompt_instruction:o.promptInstruction,model:o.model});return A(n)}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(e){return this.client.post("/apis/admin/session/jwt/",{jwt:e},{version:null}).catch(o=>{throw b.warn(`Invalid token '${e}'`),o})}async authenticateWithKey(e,o){await this.preflight(),await this.client.post("/apis/admin/session/api-key/",U(o),{version:null,refreshTokenOn401:!1,headers:{apikey:e}})}async getTextSuggestions(e,o={},n){return n==="sticky-messages"?this.getPinnedMessages(e):(await this.client.post(`/api/conversations/${e}/recommend/${n}`,U(o),{abortLatest:!0})).map(r=>({...A(r),text:r.text||r.url||r.message,source:n,type:n})).filter((r,i,a)=>i===a.findIndex(l=>l.text===r.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(e,o){return(await this.client.post(`/api/conversations/${e}/autocomplete`,U(o),{abortLatest:!0})).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))}async getPinnedMessages(e){let o=await this.client.get(`/api/conversations/${e}/sticky-messages`,{abortLatest:!0});return A(o).map(n=>({...n,text:n.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(e){let o=await this.client.post("/api/style-suggestions",U(e),{abortLatest:!0});return A(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,U(e),{version:"v2"});return A(o)}async knowledgeAssist(e,o,n,s={}){let r=await this.client.post(`/api/knowledge-assist/assistants/${n}/search`,U({question:e.question,doNotKnowAnswer:e.doNotKnowAnswer,customerInstruction:e.customerInstruction,chatHistory:o.map(i=>({question:i.question,answer:i.answer.answer})),agentId:s.agentId,conversationId:s.conversationId}),{version:"v2"});return A(r)}async requestLoginByEmail(e){let o=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return A(o)}async requestPasswordlessToken(){let e=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return A(e.token)}async getCsrfToken(){let{token:e}=await this.client.get("/apis/admin/session/csrf/",{version:null});return e}async verifyLoginToken(e){let o=await this.client.post("/apis/admin/session/passwordless/login/",{token:e},{version:null});return A(o)}async evaluateRule(e,o,n,s={}){let r=new URLSearchParams;s.raiseForFailingConditions&&r.set("raise_for_failing_conditions","true");let i=await this.client.post(`/api/conversations/${o}/rules/${e}/evaluate?${r.toString()}`,n,{version:"v2"});return A(i.cues)}async getRules(){let e=new URLSearchParams,o=await this.client.get(`/apis/admin/rule-engine/rules/?${e.toString()}`,{version:null,useCache:!0});return A(o)}async translateMessages(e){let o=await this.client.post("/api/translate",U(e),{version:"v2"});return A(o)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(va);if(!o||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&o&&a!==o&&b.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(o)}`),this.latestReceivedDeepdeskVersions[i]=o})}};var Tn=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(Rr(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,A(s))}catch{b.warn(`Invalid JSON for ${e}: ${n}`)}})}connect(){clearTimeout(this.timeoutTimer);let e=new EventSource(this.url,{withCredentials:!0});this.eventSource=e;let o=!1;e.onopen=()=>{o=!0},e.onerror=()=>{o&&e.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{e.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(n=>{this.proxyEvent(n)})}disconnect(){var e;clearTimeout(this.timeoutTimer),this.eventListeners={},(e=this.eventSource)==null||e.close()}emit(e,o){this.eventListeners[e]&&this.eventListeners[e].forEach(n=>n(o))}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),this.proxyEvent(e),()=>{this.off(e,o)}}off(e,o){let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}};var Sh;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(Sh||={});var En=class{constructor(e,o={}){this.apiUrl=e;this.client=new Ae(e,o)}client;streams={};logger=b;async getCustomMessages(e){let o=await this.client.get(`/sessions/${e}/suggestions`);return A(o.suggestions)}async sendCustomMessage(e,o){let n=await this.client.post(`/sessions/${e}/messages`,U(o));return A(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,U(o))}async getAutoflows(e){let o=await this.client.get(`/sessions/${e}/autoflows`);return A(o.autoflows)}async startAutoflowSession(e){let o=await this.client.post("/autoflow-sessions",U(e));return A(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new Tn(`${this.apiUrl}/sessions/${e}/events`),this.streams[e].connect()),this.streams[e]}closeStream(e){this.streams[e]||(this.streams[e].disconnect(),delete this.streams[e])}};var mr=require("@reduxjs/toolkit");var dp=require("@reduxjs/toolkit");var lp={startTime:null,stopTime:null},cp=(0,dp.createSlice)({name:"handlingTime",initialState:lp,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(O,()=>lp)}}),{handlingTimeStart:up,handlingTimeStop:cr,handlingTimeReset:pp}=cp.actions,mp=cp.reducer;var gp=(t={})=>{let e={onAuthError:oo(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};var pr=require("@reduxjs/toolkit");var ur={list:{keywordMatches:[]},fetchState:"idle"};var Jt=(0,pr.createAsyncThunk)("styleSuggestions/getAll",async({text:t},e)=>{var i;let{deepdeskAPI:o}=e.extra,n=e.getState(),{showStyleSuggestions:s}=n.settings,r=(i=n.conversation.current)==null?void 0:i.profileCode;if(!s)return ur.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),xh=(0,pr.createSlice)({name:"styleSuggestions",initialState:ur,reducers:{},extraReducers:t=>{t.addCase(Jt.pending,e=>{e.fetchState="loading"}).addCase(Jt.rejected,e=>{e.fetchState="error"}).addCase(Jt.fulfilled,(e,o)=>{e.fetchState="done",pt(e.list,o.payload)||(e.list=o.payload)}).addCase(Nt,e=>{e.list=ur.list}).addCase(O,()=>ur)}}),fp=xh.reducer;var hp=(t={})=>{let e,o=!0,n={getStyleSuggestions:Jt,debounce:500,...t};return s=>r=>i=>{var m;let a=s.getState().input.text,l=r(i),d=s.getState();if(d.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=d.settings;if(!((m=d.conversation.current)==null?void 0:m.id)||!c)return l;let{text:u}=d.input;return u===a&&!o||(clearTimeout(e),u==="")||(e=setTimeout(()=>{o=!1,s.dispatch(n.getStyleSuggestions({text:u}))},t.debounce)),l}};function bh(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var yp=(t={})=>{let e={getTextSuggestions:Pe,getAutocompleteSuggestions:nn,debounce:200,check:xo,...t},o;return n=>s=>r=>{var g;let{input:{userCommitted:i}}=n.getState(),a=s(r),l=n.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:d,showTabCompletion:c}=l.settings,p=(g=l.conversation.current)==null?void 0:g.id,u=r.type===As.toString();if(!p||!d&&!c)return a;let{input:{userCommitted:m}}=l;return bh(m,i)&&!u||(clearTimeout(o),!e.check(l))||(o=setTimeout(()=>{let x=ro(l);x===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(x))},u?0:e.debounce)),a}};var vp=Jt.fulfilled.toString();function Ch(t,e){let o=new Set([...e.keywordMatches.map(s=>s.keyword)]),n=[];return o.forEach(s=>{let r=t.keywordMatches.filter(l=>l.keyword===s),i=e.keywordMatches.filter(l=>l.keyword===s),a=i.length-r.length;a<=0||n.push(...i.slice(0,a))}),n}var Sp=t=>e=>o=>n=>{var d;if(n.type!==vp){o(n);return}let s=e.getState().styleSuggestions.list;o(n);let r=e.getState(),i=r.styleSuggestions.list,a=(d=r.conversation)==null?void 0:d.current;if(s===i)return;let l=Ch(s,i);n.type===vp&&l.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var wh=(0,mr.combineReducers)({answer:Sd,auth:Ia,autoflows:tu,conversation:Na,contentTypes:Al,customMessages:cu,passwordlessToken:mu,entities:Jl,knowledgeAssistant:hd,handlingTime:mp,info:ol,input:Qa,settings:Ca,profile:wd,search:dl,summary:rd,styleSuggestions:fp,ui:nc,rules:vu,textSuggestions:Ad});function xp(t){return(0,mr.configureStore)({reducer:wh,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),gp(),yp({debounce:200}),hp({debounce:500}),Sp(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var Th=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},Eh=t=>e=>o=>n=>{var a,l,d,c,p,u;let s=e.getState(),r=Cr("inlineSuggestions")(s);switch(n.type){case oo.toString():{!n.payload&&t.emit("logout",void 0);break}case ke.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:(a=s.conversation.current)==null?void 0:a.id,data:{entities:n.payload}});break;case Z.toString():t.sendEvent(n.payload.name,{conversationId:((l=n.payload.options)==null?void 0:l.includeConversationData)&&((d=s.conversation.current)==null?void 0:d.id),data:n.payload.data});break;case Gn.toString():t.handleKeyDown(n.payload);break;case Nt.toString():t.logSendMessage(n.payload);break;case jn.toString():t.handleInputChanged(n.payload);break;case jt.fulfilled.toString():n.isBroadcasted||t.broadcast(Lr,n,!1),(c=n.payload.options)!=null&&c.shouldEmit&&t.emit("cues",n.payload.cues);break;default:break}let i=o(n);switch(n.type){case Nt.toString():t.handleAfterSendMessage(n.payload);break;case rn.toString():t.onUpdateShowTabHint(n.payload);break;case cr.toString():t.logHandlingTime();break;case"analytics/logEvent/fulfilled":{t.emit("event",n.meta.arg);break}case Oe.toString():{let{start:m,end:f}=s.input.selection;t.emit("select-suggestion",{type:Th(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:m,end:f}:{start:0,end:f}},{mayApplyChanges:!0}),r&&(e.dispatch(Ne([])),e.dispatch($e()));break}case qn.toString():{let{start:m,end:f}=s.input.selection;t.emit("replace",{...n.payload,replace:n.payload.replace==="selection"?{start:m,end:f}:{start:0,end:f}},{mayApplyChanges:!0});break}case _o.toString():{let m=e.getState(),{text:f,selection:g}=m.input.userCommitted;t.emit("reset",{text:f,selectionAfter:g},{mayApplyChanges:!0});break}case Xn.toString():t.emit("select-image",n.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:(p=s.conversation.current)==null?void 0:p.id,data:{path:n.payload.suggestion.image,title:n.payload.suggestion.title}});break;case Ne.toString():{r&&n.payload.length>0&&e.dispatch(ft(0));break}case Xe.fulfilled.toString():{t.sendEvent("conversation summarized",{conversationId:(u=s.conversation.current)==null?void 0:u.id,data:{summary:n.payload.summary,model:e.getState().summary.model}});break}default:break}return i},bp=Eh;function $i(t){return t.toISOString().replace("T"," ").replace("Z","")}function Cp(t,e){var r,i,a,l;let o=(r=t.conversation.current)==null?void 0:r.id;if(!o)return b.warn("No conversationId for handling time metrics"),null;let{startTime:n,stopTime:s}=t.handlingTime;return!n||!s?(b.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:o,clientVersion:e.version,agentId:(i=t.info.agentInfo)==null?void 0:i.agentId,agentName:(a=t.info.agentInfo)==null?void 0:a.agentName,agentEmail:(l=t.info.agentInfo)==null?void 0:l.agentEmail,timeStart:$i(n),timeStop:$i(s)}}function wp(t,e,o){var te,q,L,B;let n=(te=e.conversation.current)==null?void 0:te.id;if(!n)return b.warn("No conversationId for send message metrics"),null;let{text:s,metrics:{numCharsTyped:r,numCharsPasted:i,numCharsCut:a,numCharsDeleted:l,numPaste:d,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:u,cuts:m,deletions:f,textSuggestions:g,offeredTextSuggestions:x}}=e[t],y=s.length,v=g.reduce((me,{text:oe,searchTerm:Pn})=>me+oe.length-(Pn?Pn.length:0),0),I=c??Date.now(),w=(Date.now()-I)/1e3+(p||0),P=r/w,N=g.reduce((me,{searchTerm:oe})=>me+(oe?oe.length:0),0);return{conversationId:n,source:"agent",text:s,clientVersion:o.version,pastes:u,cuts:m,deletions:f,lenTextTyped:r+N,lenTextTotal:y,lenTextAssisted:v,lenTextPasted:i,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:w,charsPerSecond:P,numPastes:d,textSuggestionsV2:g,suggestionsCounters:[{source:"gpt",countOffered:x.filter(me=>me.source==="gpt").length}],agentId:(q=e.info.agentInfo)==null?void 0:q.agentId,agentName:(L=e.info.agentInfo)==null?void 0:L.agentName,agentEmail:(B=e.info.agentInfo)==null?void 0:B.agentEmail}}function qi(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return qi(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?qi(s,e):null}function Tp(t,e){return qi(t,e)}function Ep(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function kh(t){return typeof t=="object"&&t!==null&&"tagName"in t}function gr(t){return kh(t)&&(Ct(t)||Us(t))}var Rp,Ke=new Map,Rh=["bottom","height","left","right","top","width"],kp=(t,e)=>!t&&!e?!1:t&&!e||!t&&e?!0:Rh.some(o=>t[o]!==e[o]);function Pp(t){var o,n;if(t.ownerDocument===document)return[];let e=((n=(o=t.ownerDocument)==null?void 0:o.defaultView)==null?void 0:n.frameElement)??null;return e?[e,...Pp(e)]:[]}function Ip(t,e){return!t||!e?null:{...t,top:t.top+e.top,left:t.left+e.left}}var fr=!1,Lp=()=>{fr=!0;let t=[];if(Ke.forEach((e,o)=>{if(!o.isConnected){e.rect=null,t.push(e),Ke.delete(o);return}let n=o.getBoundingClientRect();kp(n,e.rect)&&(e.rect=n,t.push(e))}),t.forEach(e=>{let o=e.parentRects?e.parentRects.reduce(Ip,e.rect):e.rect;kp(o,e.totalRect)&&e.callbacks.forEach(n=>n(o)),e.totalRect=o}),Ke.size===0){fr=!1;return}Rp=window.requestAnimationFrame(Lp)};function Gi(t,e){let o=Pp(t),n=[],s=o.map((r,i)=>Gi(r,a=>{n[i]=a;let l=Ke.get(t);if(!l)return;let d=n.reduce(Ip,l.rect);l.callbacks.forEach(c=>c(d))}));return{observe(r=!0){if(s.forEach(i=>i.observe(!1)),Ke.has(t)){let i=Ke.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else Ke.set(t,{rect:void 0,callbacks:[e],parentRects:n});r&&!fr&&Lp()},unobserve(){s.forEach(i=>i.unobserve());let r=Ke.get(t);if(r){let i=r.callbacks.indexOf(e);i>=0&&r.callbacks.splice(i,1),r.callbacks.length||Ke.delete(t),Ke.size||(cancelAnimationFrame(Rp),fr=!1)}}}}var Ap,Ue=new Map,Mp=()=>{Ue.forEach((t,e)=>{if(!e.isConnected){Ue.delete(e);return}let{clientHeight:o,scrollHeight:n}=e,s=n>o;t.visible!==s&&(t.visible=s,t.callbacks.forEach(r=>r(t.visible)))}),Ue.size!==0&&(Ap=window.requestAnimationFrame(Mp))};function Np(t,e){return{observe(){let o=Ue.size===0;Ue.has(t)?Ue.get(t).callbacks.push(e):Ue.set(t,{visible:void 0,callbacks:[e]}),o&&Mp()},unobserve(){let o=Ue.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||Ue.delete(t),Ue.size||cancelAnimationFrame(Ap)}}}}var ji=["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 Xi(t,e,o){return o.forEach(n=>{e.style[n]=t[n]})}function Ao(t){return parseFloat(t)}function hr(t){return Math.round(t*1e6)}function Op(t){return t/1e6}function Qi(t,e,o){if(t.boxSizing==="content-box")return;let{clientWidth:n}=e,s=Ao(t.width),r=Ao(t.borderLeftWidth),i=Ao(t.borderRightWidth),a=Ao(t.paddingRight),l=Op(hr(s)-hr(r)-hr(i)),d=Op(hr(n));if(l-d>2){let c=l-d;o.style.paddingRight=`${a+c}px`}}function kn(t,e={}){var c;let o=e.overlayContainer||document.createElement("div");o.style.display="none",o.style.position=e.position??"fixed",o.style.pointerEvents="none",o.style.borderColor="transparent",$t(o);let n=window.getComputedStyle(t),s=!0,r=()=>{o.scrollTop=t.scrollTop};Xi(n,o,ji),Qi(n,t,o),e.mirrorOverflow&&(o.style.overflow="hidden",t.addEventListener("scroll",r));let i=Np(t,()=>{Xi(n,o,ji),Qi(n,t,o),r(),setTimeout(r,0)}),a,l=!0,d=Gi(t,p=>{if(p===null){e.onRemove&&e.onRemove(),o.remove();return}if(!l&&e.onMoveStart&&(Promise.resolve().then(()=>e.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{e.onMoveEnd&&e.onMoveEnd(),l=!1},200),p.height===0&&p.width===0){if(s===!0)return;e.onHide&&e.onHide(),o.style.display="none",s=!0;return}if(Xi(n,o,ji),Qi(n,t,o),r(),o.style.top=`${p.top}px`,o.style.left=`${p.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let u=e.closestScrollElement.getBoundingClientRect(),m=window.getComputedStyle(e.closestScrollElement),f=Ao(m.borderTopWidth),g=Ao(m.borderBottomWidth),x=u.top+f-p.top,y=p.top+p.height+-(u.top+u.height-g);o.style.clipPath=`inset(${x}px 0px ${y}px 0px)`}s&&(o.style.display="block",e.onShow&&e.onShow(),s=!1)});return e.appendTo?e.appendTo.appendChild(o):(c=t.parentElement)==null||c.appendChild(o),d.observe(),i.observe(),[o,()=>{t.removeEventListener("scroll",r),d.unobserve(),i.unobserve()}]}var Dp=(t,e)=>({value(){try{let o=sessionStorage.getItem(`dd-${t}`);if(!o)return e;try{return JSON.parse(o)}catch{return e}}catch{return e}},update(o){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(o))}catch{b.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function Ph(t){return t.offsetParent!==null}function _p(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 yr(t,e,o=100){let n=_p(t);e({isVisible:n});let s=setInterval(()=>{let r=_p(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}var V=require("react/jsx-runtime");var Fp=Dp("showTabHint",!0),Rn=class t{static version="11.6.0";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:l}){let d=e.replace(/\/api$/,"");this.deepdeskApi=new dt(d,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[bp({broadcast:(p,u,m)=>{this.broadcastEvents.send(p,u,m)},emit:(p,u,m)=>this.emit(p,u,m),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),onUpdateShowTabHint:p=>Fp.update(p),sendEvent:(p,u)=>this.deepdeskApi.sendEvent(p,u)})]};o&&Object.assign(c,{deepdeskBrokerAPI:new En(o)}),this.store=xp(c),this.broadcastEvents=new ap({debug:!0,deepdeskUrl:d,eventMap:cl(this.store),createCustomChannel:l}),this.store.dispatch(rn(Fp.value())),this.store.dispatch(Kn({locale:s,adminUrl:d,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??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?(b.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(b.warn("Profile has not been loaded (yet)"),!0):(b.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(oo(null)),this.store.dispatch(Ve()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();Q(n)&&wa(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(Ve())).payload}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(o){b.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(Tr({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Un(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(zn({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Er(e))).payload}async postMessages(e){return(await this.store.dispatch(Wn(e))).payload}async updateConversation(e){return(await this.store.dispatch(Vn(e))).payload}resetConversation(){this.store.dispatch(O()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Xe());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(Kn(e))}setVisitorInfo(e){this.store.dispatch(el(e))}setCustomData(e){this.store.dispatch(tl(e))}async setAgentInfo(e){await this.store.dispatch(Fo(e))}async setAgentSettings(e){await this.store.dispatch(Pr(e))}async getAgentSettings(){return(await this.store.dispatch(Ir())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(As()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(jn(e))}notifyKeyDown(e){this.store.dispatch(Gn(e))}notifyPaste(e,o){this.store.dispatch(qa({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Wa(e))}notifyExternalSuggestion(e){this.store.dispatch(Oe(e)),this.store.dispatch($e())}async evaluateRule(e,o={},n=gu){let{payload:s,error:r}=await this.store.dispatch(jt({label:e,params:o,options:n}));if(r)throw new Error(r.message);return s.cues}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(xt({collapse:!1})),this.inputMediator&&this.store.dispatch(Ba({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(Ne([])))}handleKeyDown(e){let{overlayCollapsed:o}=this.state.ui,{textSuggestions:n,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=n.length>0,l=s!==-1;if(this.store.dispatch($a(_a(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let d=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Ua()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},c=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(Va()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(_o()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(e.key){case"Up":case"ArrowUp":i?c():d();return;case"Down":case"ArrowDown":{i?d():c();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(ft(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(ft(-1)),this.store.dispatch(_o()),e.preventDefault()):o||(this.store.dispatch(xt({collapse:!0})),this.store.dispatch(tc(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,u=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:m}=this.state.input;this.store.dispatch(rn(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&m&&m.text.startsWith(u)&&(this.store.dispatch(Oe({text:m.text,suggestion:m,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch($e())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Ga()),this.store.dispatch(Ne([]))}handlingTimeStart(){this.state.handlingTime.startTime||(b.info("Start handling time"),this.store.dispatch(up()))}handlingTimeStop(){this.state.handlingTime.startTime&&(b.info("Stop handling time"),this.store.dispatch(cr()))}logSendMessage(e){let o=wp("input",this.state,{version:this.version});o&&(e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o))}logHandlingTime(){let e=Cp(this.state,{version:this.version});e&&(this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(pp()))}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch($e()),this.store.dispatch(Nt(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(Oe({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{let r=this.eventListeners[e];r&&r.forEach(i=>{try{i(o)}catch(a){b.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),b.error(a)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=kn(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{(0,xe.unmountComponentAtNode)(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.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",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=kn(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{(0,xe.unmountComponentAtNode)(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return $t(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{(0,xe.unmountComponentAtNode)(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),b.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(b.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Xa(n.metrics))):b.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch{}}mount(e,o={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!gr(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:n={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:d,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:u,insertLink:m,inputMediator:f,closestScrollSelector:g,appendOverlayTo:x,inlineSuggestions:y,floatingMenu:S}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:d,showSuggestionsAfterPattern:c,showTextSuggestions:i,insertLink:m,isEmbedded:p,inlineSuggestions:y,floatingMenu:!!S}),o.automaticHandlingTime&&this.setupHandlingTime(e),$t(e),this.inputMediator=f||(Ct(e)?new Zt(e):new Qt(e)),this.inputMediator.on("change",({plainText:w})=>{this.notifyInputChanged(w)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(ja({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",w=>{this.notifyKeyDown(w)}),this.inputMediator.on("paste",({pastedText:w,selectionText:P})=>{this.notifyPaste(w,P)}),this.inputMediator.on("cut",({selectionText:w})=>{this.notifyCut(w)});let v=g&&Tp(e,g)||void 0;if(y){let{customStyles:w,appendOverlayTo:P}=o;if(Ct(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let N=this.createInlineContainer(e,"deepdesk-caret");(0,xe.render)((0,V.jsx)(Gt,{store:this.store,customStyles:w,children:(0,V.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(cc,{})})}),N),this.inputMediator.on("caret",q=>{this.store.dispatch(Ne([])),q?(N.style.display="block",N.style.top=`${q.top}px`,N.style.left=`${q.left}px`):N.style.display="none"});let te=this.overlayContainerFactory("floating-menu",v||e,{appendTo:typeof S=="object"&&"appendOverlayTo"in S?S.appendOverlayTo:P},w==null?void 0:w.floatingMenuRootNode);(0,xe.render)((0,V.jsx)(Gt,{store:this.store,customStyles:w,children:(0,V.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(Zd,{onLogIn:()=>this.loginViaPopup().catch(q=>b.warn(q.message))})})}),te)}else{let w=this.overlayContainerFactory("deepdesk-tab-completion",v||e,{appendTo:x,closestScrollElement:v,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),P=this.overlayContainerFactory("deepdesk-suggestions-overlay",v||e,{appendTo:x},n==null?void 0:n.suggestionsRootNode);(0,xe.render)((0,V.jsx)(Gt,{store:this.store,customStyles:n,children:(0,V.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(Xc,{inputElement:e})})}),w),(0,xe.render)((0,V.jsx)(Gt,{store:this.store,customStyles:n,children:(0,V.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(bc,{onLogIn:()=>this.loginViaPopup().catch(N=>b.warn(N.message))})})}),P)}(0,xe.render)((0,V.jsx)(Gt,{store:this.store,customStyles:n,children:(0,V.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(Wd,{})})}),this.createContainer("deepdesk-overlays"));let I;this.inputMediator.on("selection",w=>{clearTimeout(I),w===null?I=setTimeout(()=>{w!==null&&this.store.dispatch(kr(w))},500):this.store.dispatch(kr(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(ci(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(ci(!0))),this.store.dispatch(Ka({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch($e()),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(o=>o()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,o={}){if(this.widgetRoot&&b.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:n,showImages:s,isEmbedded:r}=o;this.widgetRoot=e,this.configure({showImages:s,isEmbedded:r}),(0,xe.render)((0,V.jsx)(Gt,{store:this.store,customStyles:n,children:(0,V.jsx)(Dt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(op,{onLogIn:()=>this.loginViaPopup().catch(i=>b.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,xe.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=yr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Ep(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(on());let e=Je(this.state);e&&(await this.store.dispatch(Jo()),this.store.dispatch(Kn({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:!!e.knowledgeAssistant,recommendTextSuggestions:e.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(e){return new Promise((o,n)=>{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 l=!1,d=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(u)};r.onmessage=async m=>{var f,g;if((f=m.data)!=null&&f.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((g=m.data)==null?void 0:g.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Bo),l=!0,s.port1.close(),o()}catch(x){console.error(x),n(x)}finally{l=!0,d()}};let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&n(new Error("Popup blocked by browser"));let p=async m=>{var f;if(m.origin===a.origin)switch((f=m.data)==null?void 0:f.type){case"deepdesk-popup-loaded":{try{let g=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(g,a.origin,[s.port2])}catch(g){b.error("Error posting message to popup",g),n(g)}break}case"deepdesk-popup-error":{d(),m.data.message==="Timeout"&&b.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(m.data.message));break}}};window.addEventListener("message",p);let u=setInterval(()=>{c&&!c.closed||(d(),l||n(new Error("Popup closed by user")))},200);this.unmountHandlers.push(d)})}translateMessages(e){return this.deepdeskApi.translateMessages(e)}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(b.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(o){let{message:n}=o;b.info(n),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let o=Is(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(ke()):Bn.includes(n)||this.store.dispatch(Pe(n))})}catch(n){this.handleError(n)}}};async function Hp(t,e,o={}){let{value:n}=t,{start:s,end:r}=o.replace??{start:0,end:n.length},i=`${n.slice(0,s)}${e}${n.slice(r)}`,a=o.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function Bp(t,e,o={}){let n=o.replace?Pt(t,o.replace.start,o.replace.end):Po(t),s,r=()=>{if(o.setRange)return o.setRange(n.cloneRange());n.deleteContents(),s=document.createElement("span"),n.insertNode(s),o.insertBRs!==!1?e.split(`
|
|
11
11
|
`).reverse().forEach((i,a)=>{a>0&&n.insertNode(document.createElement("br")),n.insertNode(document.createTextNode(i))}):n.insertNode(document.createTextNode(e))};return Promise.resolve(r()).then(()=>{try{if(o.selectionAfter!==!1){t.focus();let i=o.selectionAfter?Pt(t,o.selectionAfter.start,o.selectionAfter.end):(n.collapse(!1),n),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(i)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}function Ih(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 Lh(t){let e=document.createDocumentFragment();return t.split(`
|
|
12
12
|
`).forEach((o,n)=>{n>0&&e.appendChild(document.createElement("br"));let s={index:0},r=0;for(;s=o.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(o.slice(r,r+s.index))),e.appendChild(i),r=r+s.index+s[0].length}e.appendChild(document.createTextNode(o.slice(r)))}),e}function Kp(t,e){let o=t.parentElement;if(!o){console.warn("No insert point found");return}let{display:n}=window.getComputedStyle(o);n.includes("block")||n==="table-cell"?o==null||o.insertBefore(e,t.nextSibling):Kp(o,e)}async function Up(t,e,{isBlock:o,isHTML:n}={}){let s;t.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0}));let r=()=>{let i=t.ownerDocument.defaultView??window,a=i.getSelection();if((!a||a.rangeCount===0)&&(t.focus(),a=i.getSelection()),!a||a.rangeCount===0)return;let l=a.getRangeAt(0);if(!l)return;s=document.createElement("span"),l.insertNode(s);let d=n?Ih(e):Lh(e);o?Kp(l.startContainer,d):(l.insertNode(d),l.collapse(!1))};return Promise.resolve(r()).then(()=>{if(t.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0})),t.focus(),!!s)try{s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}function zp(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function Vp(t,e,o){await new dt(t).authenticateWithKey(e,o)}async function Wp(t){let o=await new Ae(t).get("/platform/config/",{version:null,useCache:!0});return A(o)}async function Ah(t){let o=await(t.fetch??window.fetch)(t.url),n=await o.blob();return new File([n],t.name,{type:t.mimeType??o.headers.get("Content-Type")??"image/jpeg"})}async function $p(t,e){let o=await Ah(e),n=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[o]}),t.dispatchEvent(n)}finally{Object.hasOwn(t,"files")&&delete t.files}}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,fetchPlatformConfig,formatTextMarkup,getRangeOffsets,getRangeText,insertCKEditor,isHTML,isSupportedInputElement,updateContentEditable,updateTextArea,useClickOutsideRoot,useStyles,waitForElementVisibilityChange});
|