@deepdesk/deepdesk-sdk 10.12.1-beta.6 → 10.12.1-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -6,6 +6,6 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
6
6
  c6.8-6.8,15.4-10.2,24.7-10.2h11.9v-70c0-44.4,16.2-82.8,47.8-115.2S212.1,0,256.4,0s82.8,16.2,115.2,47.8
7
7
  c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});var Oi=require("react/jsx-runtime"),Mf={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},Kp=({className:t,color:e})=>(0,Oi.jsx)("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,Oi.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:Mf[e||"pink"]})});var Up={root:"_root_1tvv4_1",text:"_text_1tvv4_18",isLoggedIn:"_isLoggedIn_1tvv4_25",isLoggedOut:"_isLoggedOut_1tvv4_29",icon:"_icon_1tvv4_39",logo:"_logo_1tvv4_44",lock:"_lock_1tvv4_49"};var Di={};$(Di,{enUS:()=>Nf,nlNL:()=>Of});var Nf={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},Of={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Vp=require("react-redux"),Xt=require("react/jsx-runtime"),qp=({onLogIn:t})=>{let e=T(Di),o=C("floatingMenu"),n=C("productName"),s=(0,Vp.useDispatch)(),r=(0,jp.useSelector)(ne),i=y("FloatingMenu",Up);if(r===null||o===!1)return null;let a=()=>{r===!0?s(te(!0)):t()};return(0,Xt.jsxs)("button",{className:(0,zp.default)(i.root,{[i.isLoggedIn]:r,[i.isLoggedOut]:!r}),onClick:a,children:[(0,Xt.jsx)("div",{className:i.text,children:e(r?"search":"signin",{productName:n})}),(0,Xt.jsxs)("div",{className:i.icon,children:[(0,Xt.jsx)(Kp,{className:i.logo,color:"pink"}),r===!1&&(0,Xt.jsx)(Fp,{className:i.lock})]})]})};var nr=require("react"),rt=require("react-redux");function Lo(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 tr=require("react");var Xp=require("interweave"),Mo=require("react"),er=require("react-redux");var Wp=require("react");function $p(t,e,o){(0,Wp.useEffect)(()=>{let n=t.current;return n?(n.addEventListener(e,o),()=>{n.removeEventListener(e,o)}):()=>{}},[t,e,o])}var Gp={root:"_root_4u430_1",actions:"_actions_4u430_8",badge:"_badge_4u430_15",formattedText:"_formattedText_4u430_19"};var Zt=require("react/jsx-runtime"),Hf=["search","personal-collection-search","search-autocomplete"];function Bf(t,e,o,n={}){let s="";return Hf.includes(e)?s=Fl(ai(t,o,{stripAgentPart:!0}),n.searchKeywords??[o]):s=ai(t,o,n),n.placeholders===!0&&(s=Kl(s)),s}var Ff=()=>{},Kf=({index:t,selected:e,suggestion:o,onFeedback:n})=>{let s=C("inlineSuggestions"),r=(0,er.useSelector)(lo),i=(0,er.useDispatch)(),a=y("TextSuggestion",Gp),l=(0,Mo.useRef)(null);(0,Mo.useEffect)(()=>{let p=setTimeout(()=>{i(nl({text:o.text,suggestion:o}))},500);return()=>{clearTimeout(p)}},[o]),$p(l,"click",()=>{i(yt(t)),i(Re({suggestion:o,text:o.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let c=(0,Mo.useMemo)(()=>Bf(o.text,o.source,r,{stripAgentPart:s,placeholders:!0,searchKeywords:o.searchKeywords}),[s,o.text,o.source,r,o.searchKeywords]);return o.source==="gpt"&&!s?null:(0,Zt.jsxs)("div",{className:a.root,onMouseEnter:()=>i(yt(t)),children:[(0,Zt.jsx)(L,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:Ff,children:(0,Zt.jsx)(Xp.Interweave,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:c})}),e&&n&&(0,Zt.jsx)("div",{className:a.actions,children:(0,Zt.jsx)(Ps,{onFeedback:()=>n(o),suggestion:o.text})})]})},Zp=Kf;var Hi=require("react/jsx-runtime"),Uf=({onFeedback:t,suggestions:e,selectedIndex:o,reverse:n})=>{let s=(0,tr.useMemo)(()=>{let r=e.map((i,a)=>(0,Hi.jsx)(Zp,{index:a,selected:a===o,suggestion:i,onFeedback:t},`${i.text}-${i.source}`));return n?r.reverse():r},[e,o,n]);return(0,Hi.jsx)(tr.Fragment,{children:s})},or=Uf;var Qp={root:"_root_otdbu_1",paper:"_paper_otdbu_11"};var bn=require("react/jsx-runtime"),zf=({textSuggestions:t,selectedIndex:e})=>{let o=(0,nr.useRef)(null),n=y("InlineSuggestionsOverlay",Qp),s=(0,rt.useSelector)(Lo),r=(0,rt.useDispatch)(),i=(0,rt.useSelector)(ne),a=(0,rt.useSelector)(ao),l=(0,rt.useSelector)(zs),c=C("showTextSuggestions");return fo(()=>{setTimeout(()=>{r(bt({collapse:!0,skipWhenInputFocus:!0}))})}),(0,nr.useEffect)(()=>{let p=o.current;if(!p||!p.parentElement)return;p.parentElement.style.left="0px";let d=p.getBoundingClientRect();p.parentElement.style.left=`${Math.min(window.innerWidth-4-d.right,0)}px`}),l||!s||!c||t.length===0||i!==!0||a===!1?null:(0,bn.jsx)("div",{className:n.root,"data-variant":"inline",children:(0,bn.jsx)("div",{ref:o,className:n.paper,children:(0,bn.jsx)(ue,{children:(0,bn.jsx)(or,{suggestions:t,selectedIndex:e})})})})},jf=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),Jp=(0,rt.connect)(jf)(zf);var Yp=require("react-redux");var Cn=require("react/jsx-runtime"),Vf=({children:t})=>{let o=C("locale").replace("-","");return(0,Cn.jsx)(Jr.Provider,{value:o,children:t})},qf=({store:t,customStyles:e={},children:o})=>(0,Cn.jsx)(Yp.Provider,{store:t,children:(0,Cn.jsx)(Vf,{children:(0,Cn.jsx)(Uo.Provider,{value:e,children:o})})}),Qt=qf;var rr=k(require("classnames")),No=require("react"),ze=require("react-redux");var ed=require("react");function td(t,e){let[o,n]=(0,ed.useState)(()=>{if(typeof window>"u")return e;try{let r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return w.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){w.error(i)}}]}var nd=k(require("classnames")),it=require("react");var Bi={};$(Bi,{enUS:()=>Wf,nlNL:()=>$f});var Wf={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"}]}]},$f={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 od={root:"_root_1vfca_1",anchor:"_anchor_1vfca_6",anchorButton:"_anchorButton_1vfca_11"};var Tt=require("react/jsx-runtime"),Fi=(t,e,o)=>n=>(0,Tt.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=T(Bi),i=be(),a=y("Login",od),l=C("productName"),c=(0,it.useCallback)(h=>{h.preventDefault(),n&&n(parseInt(h.target.value,10))},[]),p=(0,it.useCallback)(h=>{h.preventDefault(),i.send(Eo,!0)},[e]),d=(0,it.useMemo)(()=>h=>(0,Tt.jsx)("a",{onClick:x=>{x.preventDefault(),s()},href:e,className:a.anchor,target:"_blank",rel:"noreferrer",children:h},"login"),[e]),g=(0,it.useCallback)(h=>(0,Tt.jsx)("button",{type:"button",className:a.anchorButton,onClick:p,children:h},"prompt"),[p]),{min:u,hour:m,day:f}=(0,it.useMemo)(()=>({min:Fi(a,60*10,c),hour:Fi(a,60*60,c),day:Fi(a,60*60*12,c)}),[]);return(0,Tt.jsxs)("div",{className:(0,nd.default)(t,a.root),children:[r("loginPlease",{login:o?g:d,productName:l}),n&&(0,Tt.jsxs)(it.Fragment,{children:[(0,Tt.jsx)("br",{}),r("snooze",{min:u,hour:m,day:f})]})]})},sr=Gf;var rd=require("react-redux");var sd={root:"_root_1g8fi_1",text:"_text_1g8fi_19"};var wn=require("react/jsx-runtime"),Xf=({title:t})=>{let e=y("SearchTrigger",sd),o=(0,rd.useDispatch)();return(0,wn.jsxs)("button",{type:"button",className:e.root,onClick:()=>o(te(!0)),children:[(0,wn.jsx)(_o,{}),(0,wn.jsx)("span",{className:e.text,children:t})]})},id=Xf;var Ki={};$(Ki,{enUS:()=>Zf,nlNL:()=>Qf});var Zf={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"}]},Qf={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 ad={root:"_root_onpov_1",isInline:"_isInline_onpov_14",toggleButton:"_toggleButton_onpov_21",toggleButtonWrapper:"_toggleButtonWrapper_onpov_25",toggleButtonWrapperHidden:"_toggleButtonWrapperHidden_onpov_32",isCollapsed:"_isCollapsed_onpov_36",collapsible:"_collapsible_onpov_36",hints:"_hints_onpov_44",hintsHidden:"_hintsHidden_onpov_51",triggers:"_triggers_onpov_56",triggersRight:"_triggersRight_onpov_71"};var F=require("react/jsx-runtime"),Jf=({textSuggestions:t,selectedIndex:e,onLogIn:o})=>{let n=y("SuggestionsOverlay",ad),s=T(Ki),r=(0,ze.useSelector)(Lo),i=Ja(),a=(0,ze.useDispatch)(),l=(0,No.useRef)(null),c=C("searchTriggerKey"),p=C("productName"),d=(0,ze.useSelector)(zs),g=(0,ze.useSelector)(ne),u=(0,ze.useSelector)(ao),[m,f]=(0,No.useState)(null),h=C("showSearch"),E=C("showTextSuggestions"),x=C("adminUrl"),_=C("isEmbedded"),[b,v]=td("dd-snooze-until-ms",0),A=d||b>Date.now(),O=(0,ze.useSelector)(I=>I.input.text),K=t.filter(I=>I.source!=="gpt").length,H=()=>{A&&v(0),a(Hc(!A))},W=I=>{a(Q({name:"suggestion feedback",data:{text:I.text,source:"overlay",context:O},options:{includeConversationData:!0}}))},z=I=>{let ye=Date.now()+I*1e3;v(ye),w.info(`Snooze until: ${new Date(ye)}`),a(bt({collapse:!0}))};return(0,No.useEffect)(()=>{K===0&&f(null)},[t,K]),fo(()=>{a(bt({collapse:!0,skipWhenInputFocus:!0}))}),g===null||u===!1?null:g===!1?(0,F.jsxs)("div",{ref:l,className:(0,rr.default)(n.root,{[n.isCollapsed]:A}),children:[!A&&(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)(Mt,{className:n.toggleButton,title:s("collapse"),onClick:H,isCollapsed:!1})})]}),(0,F.jsx)("div",{className:n.toggleButtonWrapper,children:(0,F.jsx)(Mt,{className:n.toggleButton,title:s("open",{productName:p}),onClick:H,isCollapsed:!0})}),(0,F.jsx)("div",{className:n.collapsible,children:(0,F.jsx)(sr,{loginUrl:x,isEmbedded:_,onLogIn:o,onSnooze:z})})]}):!i||!r?null:(0,F.jsxs)("div",{ref:l,className:(0,rr.default)(n.root,{[n.isCollapsed]:A}),children:[!A&&(0,F.jsxs)("div",{className:n.triggers,children:[(0,F.jsx)("div",{style:{flex:1},children:h&&(0,F.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>f(s(Ds()?"searchHintMac":"searchHintWindows",{searchTriggerKey:c.toUpperCase()})),onMouseLeave:()=>f(null),children:(0,F.jsx)(id,{title:s("search")})})}),(0,F.jsxs)("div",{className:n.triggersRight,onFocus:()=>{},children:[(0,F.jsx)("div",{className:(0,rr.default)(!m&&n.hintsHidden,n.hints),children:m}),(0,F.jsx)(Mt,{className:n.toggleButton,title:s("collapse"),onClick:H,isCollapsed:!1})]})]}),(0,F.jsx)("div",{className:n.toggleButtonWrapper,children:(0,F.jsx)(Mt,{className:n.toggleButton,title:s("open",{productName:p}),onClick:H,isCollapsed:!0})}),K>0&&E&&(0,F.jsx)("div",{className:n.collapsible,onFocus:()=>{},children:(0,F.jsx)(ue,{children:(0,F.jsx)(or,{onFeedback:W,suggestions:t,selectedIndex:e,reverse:!0})})})]})},Yf=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),ld=(0,ze.connect)(Yf)(Jf);var vr=k(require("classnames")),kd=require("interweave"),ct=require("react"),Id=require("react-redux");var cd=require("react"),eh=["div","span","mark","strong","b","i","u","em"];function Ui(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(eh.includes(s)){let i=Array.isArray(n.props.children)?n.props.children:[n.props.children];return[...t.slice(0,t.length-1),(0,cd.cloneElement)(n,{children:Ui(i,e,o+1)})]}return[...t,...e]}function Et(t){return t.tagName.toLowerCase()==="textarea"}var pd={root:"_root_81non_1",container:"_container_81non_3",agentText:"_agentText_81non_5",tabText:"_tabText_81non_6",hint:"_hint_81non_6",matchSelection:"_matchSelection_81non_10",focus:"_focus_81non_16",resetIndent:"_resetIndent_81non_20",matchKeyword:"_matchKeyword_81non_24",matchPlaceholder:"_matchPlaceholder_81non_25",hover:"_hover_81non_31",hintText:"_hintText_81non_64",popover:"_popover_81non_72",popoverRoot:"_popoverRoot_81non_77",popoverContentContainer:"_popoverContentContainer_81non_81",popoverContent:"_popoverContent_81non_81",selectionOptions:"_selectionOptions_81non_107",selectionOptionsIsHidden:"_selectionOptionsIsHidden_81non_112",selectionOptionsButton:"_selectionOptionsButton_81non_116",caret:"_caret_81non_132",popoverSuggestionsRoot:"_popoverSuggestionsRoot_81non_136",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_81non_141"};var Sd=k(require("classnames")),_d=require("interweave"),mr=require("react");function dd(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function ir(t){return e=>{t.forEach(o=>{typeof o=="function"?o(e):o!=null&&(o.current=e)})}}function ud(t){return t!=null}var ji=k(require("classnames")),Ce=require("react");var ar=require("react"),th=["bottom","height","left","right","top","width"],oh=(t={},e={})=>th.some(o=>t[o]!==e[o]),at=new Map,gd,md=()=>{let t=[],e=[];at.forEach((o,n)=>{if(n instanceof Element&&!n.isConnected){e.push(n);return}let s=n.getBoundingClientRect();oh(s,o.rect)&&(o.rect=s,t.push(o))}),e.forEach(o=>{at.delete(o)}),t.forEach(o=>{o.callbacks.forEach(n=>n(o.rect))}),gd=window.requestAnimationFrame(md)};function nh(t,e){return{observe(){let o=at.size===0;if(at.has(t)){let n=at.get(t);n.callbacks.push(e),n.rect&&e(n.rect)}else at.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});o&&md()},unobserve(){let o=at.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||at.delete(t),at.size||cancelAnimationFrame(gd)}}}}function zi(t){let[e,o]=(0,ar.useState)(null);return(0,ar.useLayoutEffect)(()=>{if(!t.current)return;let n=nh(t.current,s=>{o(s)});return n.observe(),()=>{n.unobserve()}},[t]),e}var Oo=require("react"),hd=require("react-dom");var fd={root:"_root_1jq08_1"};var yd=({children:t})=>{let[e,o]=(0,Oo.useState)(null),n=(0,Oo.useContext)(Uo);return(0,Oo.useLayoutEffect)(()=>{let s=document.createElement("div");return Dt(s),s.classList.add(fd.root),n!=null&&n.portalRootNode&&s.classList.add(n==null?void 0:n.portalRootNode),document.body.appendChild(s),o(s),()=>{s.isConnected&&document.body.removeChild(s)}},[]),e?(0,hd.createPortal)(t,e):null};var je={ref:"_ref_1rcyi_1",root:"_root_1rcyi_7",positionAbove:"_positionAbove_1rcyi_13",positionBelow:"_positionBelow_1rcyi_17",positionLeft:"_positionLeft_1rcyi_21",positionRight:"_positionRight_1rcyi_25",alignStart:"_alignStart_1rcyi_29",alignCenter:"_alignCenter_1rcyi_34",alignEnd:"_alignEnd_1rcyi_40"};var lr=require("react/jsx-runtime"),cr=(t=!1)=>{let[e,o]=(0,Ce.useState)(t),n=(0,Ce.useCallback)(()=>o(!0),[]),s=(0,Ce.useCallback)(()=>o(!1),[]),r=(0,Ce.useCallback)(()=>o(a=>!a),[]),i=(0,Ce.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 pr=({className:t,triggerRef:e,boundaryRef:o=(0,Ce.createRef)(),position:n="above",align:s="center",children:r,toStyle:i=Vi,...a})=>{let l=zi(e),c=zi(o),p=(0,Ce.useMemo)(()=>i(l,c,0),[l,c]);return(0,lr.jsx)(yd,{children:(0,lr.jsx)("div",{className:(0,ji.default)(je.ref,{[je.positionAbove]:n==="above",[je.positionBelow]:n==="below",[je.positionLeft]:n==="left",[je.positionRight]:n==="right",[je.alignStart]:s==="start",[je.alignCenter]:s==="center",[je.alignEnd]:s==="end"}),style:p,...a,role:"dialog",children:(0,lr.jsx)("div",{className:(0,ji.default)(t,je.root),children:r})})})};var vd=k(require("classnames")),dr=require("react");var qi=require("react/jsx-runtime"),ur=(0,dr.forwardRef)(({className:t,children:e,...o},n)=>{let s=(0,dr.useRef)(null),r=y("TabCompletion",Ge);return(0,qi.jsx)("div",{ref:ir([s,n]),className:(0,vd.default)(t,r.popoverContentContainer),...o,children:(0,qi.jsx)("div",{className:r.popoverContent,children:e})})});var kt=require("react/jsx-runtime"),sh=t=>e=>{let o=Vi(e);return"top"in o&&(o.width=t.width-(e.left-t.left)-10),o},rh=({inputElement:t,boundaryRef:e,inputStyle:o,children:n,suggestion:s})=>{let r=y("TabCompletion",Ge),i=cr(),a=(0,mr.useMemo)(()=>sh(t.getBoundingClientRect()),[t]),[l,c]=bs(t);return(0,mr.useEffect)(()=>{c?i.open():i.close()},[c]),(0,kt.jsxs)("span",{children:[(0,kt.jsx)("mark",{ref:ir([l,i.triggerRef]),className:(0,Sd.default)(r.matchKeyword,{[r.hover]:c}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:n}),i.opened&&(0,kt.jsx)(pr,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:(0,kt.jsx)(ur,{style:o,children:(0,kt.jsx)("div",{className:r.hintText,children:s})})})]})},gr=class extends _d.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${dd(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(ud);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,kt.jsx)(rh,{inputElement:o.inputElement,suggestion:o.suggestion,inputStyle:o.inputStyle,boundaryRef:o.boundaryRef,children:e},`keyword_${o.matchString}_${o.key}`)}asTag(){return"mark"}};var hr=k(require("classnames")),Td=require("interweave"),ie=require("react"),Ed=require("react-redux");var Wi=require("react/jsx-runtime"),xd=()=>(0,Wi.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,Wi.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 It=require("react"),Tn=require("react-redux"),Cd=k(require("lodash.debounce"));var bd={root:"_root_1muu8_1",content:"_content_1muu8_7"};function fr(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 $i(t){return t.replace("https://www.","").replace("https://","")}var we=require("react/jsx-runtime"),ih=3,ah=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),lh=({onSelectLink:t,onDismiss:e,placeholder:o,visitUrlText:n,linkCount:s=ih})=>{let r=y("LinkSearch",bd),[i,a]=(0,It.useState)(""),l=(0,Tn.useDispatch)(),c=(0,Tn.useSelector)(Ks("url")),p=(0,Tn.useSelector)(dc("URL",ah)),[d,g]=(0,It.useState)(p.length-1),u=C("fallbackImage"),m=x=>{let _=x.target;a(_.value)},f=(x,_)=>{x.stopPropagation(),x.preventDefault(),window.open(_,"_blank")},h=x=>{var v;let _=d-1<0?p.length-1:d-1,b=d+1===p.length?0:d+1;x.code==="Escape"&&(a(""),e()),x.code==="ArrowUp"&&g(_),x.code==="ArrowDown"&&g(b),x.code==="Enter"&&t(((v=p[d])==null?void 0:v.text)||i)},E=(0,It.useCallback)((0,Cd.default)(x=>{l(jt({query:x,type:"URL",tags:["link-search"]}))},300),[]);return(0,It.useEffect)(()=>{i&&E(i)},[i]),(0,It.useEffect)(()=>()=>{l(Ns())},[]),(0,we.jsxs)("div",{className:r.root,children:[(0,we.jsx)(ue,{withDivider:!0,children:(i?p:c).slice(0,s).map((x,_)=>(0,we.jsx)(L,{selected:d===_,onClick:()=>t(x.text),"data-testid":"linksearch-suggestion",children:(0,we.jsxs)(D,{children:[(0,we.jsx)(D.Image,{src:fr(x,"small",u||void 0),title:x.title||x.text}),(0,we.jsxs)(D.Content,{className:r.content,cropText:!0,children:[(0,we.jsx)(D.Title,{children:x.title||$i(x.text)}),x.title&&$i(x.text)]}),(0,we.jsx)(L.Actions,{children:(0,we.jsx)(L.ActionButton,{label:n,onClick:b=>f(b,x.text)})})]})},x.text))}),(0,we.jsx)(un,{value:i,onChange:m,autoFocus:!0,placeholder:o,onKeyUp:h})]})},wd=lh;var Gi={};$(Gi,{enUS:()=>ch,nlNL:()=>ph});var ch={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},ph={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var re=require("react/jsx-runtime"),dh=(0,ie.forwardRef)((t,e)=>{let o=y("TabCompletion",Ge);return(0,re.jsx)("mark",{ref:e,className:(0,hr.default)(o.matchSelection)},"selection-start")}),uh=({startRef:t,boundaryRef:e,inputStyle:o,inputElement:n,children:s})=>{let r=T(Gi),i=y("TabCompletion",Ge),a=(0,ie.useRef)(null),l=(0,ie.useRef)(null),[c,p]=(0,ie.useState)(null),d=(0,Ed.useDispatch)(),g=cr(document.activeElement===n),[u]=(0,ie.useState)(()=>document.createRange());g.triggerRef.current=u,(0,ie.useEffect)(()=>()=>u.detach(),[]),(0,ie.useEffect)(()=>{let f=t.current,h=a.current;!f||!h||(u.setStart(f,0),u.setEnd(h,0))},[t.current,a.current]),fo(()=>{g.close()});let m=(0,ie.useCallback)(f=>{let h=u.toString(),E=/^http(s?):\/\//.test(f)?f:`https://${f}`;d(os({text:`[${h}](${E})`,replace:"selection"}))},[]);return(0,re.jsxs)("span",{children:[(0,re.jsx)("mark",{ref:a,className:(0,hr.default)(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":g.opened?"true":"false",children:s}),g.opened&&(0,re.jsx)(pr,{className:i.popoverRoot,triggerRef:g.triggerRef,boundaryRef:e,position:"above",align:"start",children:(0,re.jsxs)(ur,{style:o,ref:l,children:[(0,re.jsx)("div",{className:(0,hr.default)(i.selectionOptions,{[i.selectionOptionsIsHidden]:c!==null}),children:(0,re.jsxs)("button",{type:"button",tabIndex:c===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>p("insertLink"),children:[(0,re.jsx)(xd,{}),(0,re.jsx)("span",{children:"\xA0"}),(0,re.jsx)("span",{children:r("insertLink")})]})}),c==="insertLink"&&(0,re.jsx)(wd,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:m,onDismiss:()=>{p(null),g.close()}})]})})]},"selection-end")},yr=class extends Td.Matcher{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(e,o){return this.props=o,this.charCount=0,this.startRef=(0,ie.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,re.jsx)(dh,{ref:this.startRef}):(0,re.jsx)(uh,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};var Rd=require("react-redux");var lt=require("react/jsx-runtime"),gh=({enabled:t,content:e,tabText:o,showTabHint:n,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:l})=>{let c=y("TabCompletion",pd),p=C("insertLink"),d=C("showMidSentenceSuggestions"),g=C("inlineSuggestions"),u=ws(a),m=(0,ct.useRef)(null),f=(0,Rd.useSelector)(ne);(0,ct.useEffect)(()=>{Et(a)&&u&&Ts(a,u)},[u]);let h=(0,ct.useCallback)(_=>{if(!s||!o)return _;let b=[(0,lt.jsx)("span",{className:c.resetIndent,children:"\u200B"},"u200B"),(0,lt.jsx)("span",{"data-testid":"tab-completion",className:(0,vr.default)(c.tabText,c.resetIndent),"data-source":l,children:o},"tabText")];return n&&b.push((0,lt.jsx)("span",{className:(0,vr.default)(c.hint,c.resetIndent),children:(0,lt.jsx)(jn,{keyCode:"tab"},"tabHint")})),Ui(_,b)},[s,o,n]),E=(0,ct.useMemo)(()=>{let _=[];return p&&_.push(new yr("selection")),_.push(new go("placeholders")),r&&_.push(new gr("keywords")),_},[g,p,r]),x=(0,ct.useMemo)(()=>{let _=window.getComputedStyle(a);return{"--dd-color":_.color,"--dd-font-size":_.fontSize,"--dd-font-family":_.fontFamily,"--dd-font-variant":_.fontVariant}},[]);return!t||!f?null:(0,lt.jsxs)("div",{ref:_=>{_!=null&&_.parentElement&&(m.current=_==null?void 0:_.parentElement)},className:c.root,style:x,children:[(0,lt.jsx)(kd.Interweave,{tagName:"span",containerTagName:"div",className:(0,vr.default)(c.container,c.agentText),disableLineBreaks:Et(a),content:e||"\u200B",onAfterParse:h,matchers:E,selection:u,keywordMatches:i,inputElement:a,inputStyle:x,boundaryRef:m,inlineSuggestionsOnlyAtEnd:!d}),(0,lt.jsx)("br",{})]})},mh=({input:t,ui:e,settings:o,styleSuggestions:n,conversation:s})=>{var f;let{tabCompletionSuggestion:r}=t,i=(r==null?void 0:r.text)||"",a=(r==null?void 0:r.source)||"",l=t.html??yo(t.text),c=i.indexOf(t.text)===0?i.slice(t.text.length):"",{showTabHint:p}=e,{isSupported:d}=s,{showTabCompletion:g,visible:u,showStyleSuggestions:m}=o;return{showTabHint:p,showStyleSuggestions:m,showTabCompletion:g,content:l,tabText:c,source:a,keywordMatches:((f=n.list)==null?void 0:f.keywordMatches)??[],enabled:u&&d!==!1}},Pd=(0,Id.connect)(mh)(gh);var Cu=k(require("classnames")),wu=require("react"),X=require("react-redux");var Rt=require("@reduxjs/toolkit");var Ad={list:[],fetchState:"idle",isInitialRequest:null},Md=t=>t.autoflows.list||[],Ld=t=>e=>{var o;return(o=e.list)==null?void 0:o.find(n=>n.triggerPayload===t)},pt=(0,Rt.createAsyncThunk)("autoflows/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getAutoflows(t)}),Xi=(0,Rt.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(pt(t.platformSessionId))}),Zi=(0,Rt.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(pt(t.platformSessionId))}),fh=(0,Rt.createSlice)({name:"autoflows",initialState:Ad,reducers:{},extraReducers:t=>{t.addCase(Xi.pending,(e,o)=>{let n=Ld(o.meta.arg.triggerPayload)(e);n.state="Started",n.isBusy=!0}),t.addCase(Zi.pending,(e,o)=>{let n=Ld(o.meta.arg.triggerPayload)(e);n.state="Aborted",n.isBusy=!0}),t.addCase(pt.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}),t.addCase(pt.rejected,e=>{e.fetchState="error"}),t.addCase(pt.fulfilled,(e,o)=>{e.list=o.payload,e.fetchState="done"}),t.addCase(M,()=>Ad)}}),Nd=(0,Rt.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(pt(t))}),s.on("sessionCompleted",()=>{o(pt(t))})}),Od=(0,Rt.createAsyncThunk)("autoflows/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),Dd=fh.reducer;var Pt=require("@reduxjs/toolkit");var Hd={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},Bd=t=>t.customMessages.list,Fd=t=>e=>!!e.customMessages.sentSuggestions.find(o=>o===t),Kd=t=>e=>!!e.customMessages.answeredSuggestions.find(o=>o===t),Ud=t=>e=>!!e.customMessages.errorSuggestions.find(o=>o===t),En=(0,Pt.createAsyncThunk)("customMessages/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getCustomMessages(t)}),Sr=(0,Pt.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)}),_r=(0,Pt.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)}),zd=(0,Pt.createSlice)({name:"customMessages",initialState:Hd,reducers:{onCustomMessage(t,e){Array.isArray(e.payload)?t.list=e.payload:t.list=[e.payload]}},extraReducers:t=>{t.addCase(En.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(En.rejected,e=>{e.fetchState="error"}).addCase(En.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload||[]}).addCase(Sr.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.errorSuggestions=e.errorSuggestions.filter(n=>o.meta.arg.suggestion.text!==n)}).addCase(Sr.rejected,(e,o)=>{let n=e.sentSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1))}).addCase(_r.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.answeredSuggestions.push(o.meta.arg.suggestion.text)}).addCase(_r.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(M,()=>Hd)}}),jd=(0,Pt.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(zd.actions.onCustomMessage(r))})}),Vd=(0,Pt.createAsyncThunk)("customMessages/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),qd=zd.reducer;var kn=require("@reduxjs/toolkit"),hh={token:null,accountUrl:null,interval:null},Wd=t=>e=>{let{passwordlessToken:{token:o,accountUrl:n}}=e;return o&&n?`${n}/apis/admin/session/passwordless/login/?token=${o}&redirect=${t}`:null},Qi=(0,kn.createAsyncThunk)("passwordlessToken/getTemporaryPasswordlessToken",async(t,e)=>{let{deepdeskAPI:o}=e.extra,n=await o.requestPasswordlessToken();return{accountUrl:o.client.baseUrl,token:n}}),Ji=(0,kn.createAsyncThunk)("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:o=1e3*60*10}=t,{dispatch:n}=e;return n(Qi()),setInterval(()=>n(Qi()),o)}),$d=(0,kn.createSlice)({name:"passwordlessToken",initialState:hh,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(Qi.fulfilled,(e,o)=>{e.token=o.payload.token,e.accountUrl=o.payload.accountUrl}),t.addCase(Ji.fulfilled,(e,o)=>{e.interval=o.payload})}}),{stopPollPasswordlessToken:Gd}=$d.actions,Xd=$d.reducer;function Zd(t){let{customMessages:e,autoflows:o}=t;return o.fetchState==="loading"&&o.isInitialRequest===!0||e.fetchState==="loading"&&e.isInitialRequest===!0}var ru=require("react"),iu=require("react-redux");var ou=k(require("classnames")),nu=require("react");var Jd=k(require("classnames"));var Qd={root:"_root_838fd_1"};var eu=require("react/jsx-runtime"),yh=({className:t,children:e})=>{let o=y("Unicode",Qd);return(0,eu.jsx)("span",{className:(0,Jd.default)(t,o.root),children:e})},Yd=yh;var tu={isDisabled:"_isDisabled_1rmfm_1",buttonStart:"_buttonStart_1rmfm_5",root:"_root_1rmfm_8",buttonStop:"_buttonStop_1rmfm_8",stateBadge:"_stateBadge_1rmfm_19",isCompleted:"_isCompleted_1rmfm_26",isStarted:"_isStarted_1rmfm_30",isAborted:"_isAborted_1rmfm_34"};var Yi={};$(Yi,{enUS:()=>vh,nlNL:()=>Sh});var vh={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"}]},Sh={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 fe=require("react/jsx-runtime"),xh=({disabled:t,state:e,displayName:o,description:n,onStartAutoflow:s,onStopAutoflow:r})=>{let i=y("Autoflow",tu),a=T(Yi),l=e==="Started"?"stop":"start",c=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return(0,fe.jsxs)(L,{className:(0,ou.default)(i.root,{[i.isDisabled]:t,[i.isCompleted]:e==="Completed",[i.isAborted]:e==="Aborted",[i.isStarted]:e==="Started"}),children:[(0,fe.jsx)(D,{children:(0,fe.jsxs)(D.Content,{children:[(0,fe.jsxs)(D.Title,{children:[e&&(0,fe.jsx)("span",{className:i.stateBadge,children:a(e)}),o]}),(0,fe.jsx)("span",{children:n})]})}),(0,fe.jsx)(L.Actions,{fixed:e==="Started",children:(0,fe.jsx)(L.ActionButton,{primary:!0,className:l==="start"?i.buttonStart:i.buttonStop,onClick:e==="Started"?r:s,disabled:t,label:(0,fe.jsxs)(nu.Fragment,{children:[(0,fe.jsx)(Yd,{children:c})," ",(0,fe.jsx)("span",{children:a(l)})]})})})]})},su=xh;var ea=require("react/jsx-runtime"),bh=(t,e)=>{let o=e.filter(n=>n.state==="Started");return o.length>0?o.indexOf(t)===-1:!1},Ch=({autoflows:t,onStartAutoflow:e,onStopAutoflow:o,platformSessionId:n})=>(0,ea.jsx)(ru.Fragment,{children:t.map(s=>(0,ea.jsx)(su,{displayName:s.displayName,description:s.description,disabled:s.isBusy||bh(s,t),state:s.state,onStartAutoflow:()=>e({platformSessionId:n,triggerPayload:s.triggerPayload}),onStopAutoflow:()=>o({platformSessionId:n,triggerPayload:s.triggerPayload})},s.displayName))}),wh=({autoflows:t,conversation:e})=>{var o;return{autoflows:t.list,platformSessionId:(o=e.current)==null?void 0:o.sessionId}},Th={onStartAutoflow:Xi,onStopAutoflow:Zi},au=(0,iu.connect)(wh,Th)(Ch);var lu=k(require("classnames")),ta=require("react"),Jt=require("react-redux");var dt={root:"_root_1e6ej_1",title:"_title_1e6ej_8",isUsed:"_isUsed_1e6ej_13",quickReplies:"_quickReplies_1e6ej_22",quickReply:"_quickReply_1e6ej_29",hasError:"_hasError_1e6ej_39",label:"_label_1e6ej_43",errorIcon:"_errorIcon_1e6ej_48"};var pe=require("react/jsx-runtime"),Eh=({suggestion:t})=>{let e=T(Ut),o=(0,Jt.useDispatch)(),n=(0,Jt.useSelector)(Fd(t.text)),s=(0,Jt.useSelector)(Kd(t.text)),r=(0,Jt.useSelector)(Ud(t.text)),i=(0,Jt.useSelector)(Gn),{replyOptions:a}=t,l=(0,ta.useCallback)(p=>{p.preventDefault(),p.stopPropagation(),!(n||!i)&&o(Sr({platformSessionId:i,suggestion:t}))},[t,n,o,i]),c=(0,ta.useCallback)(p=>{if(p.preventDefault(),p.stopPropagation(),!i||!a)return;let d=parseInt(p.target.dataset.index,10),g=a[d];o(_r({platformSessionId:i,reply:g,suggestion:t}))},[t,n,o,i]);return(0,pe.jsxs)(L,{onClick:l,className:(0,lu.default)(dt.root,{[dt.isUsed]:n,[dt.hasError]:r}),children:[(0,pe.jsx)(D,{children:(0,pe.jsxs)(D.Content,{children:[(0,pe.jsxs)(D.Title,{className:dt.title,children:[t.text," ",(0,pe.jsx)(Vn,{className:dt.label,children:"analyse tool"})," ",r&&(0,pe.jsx)("span",{className:dt.errorIcon,role:"img","aria-label":e("sendingError"),title:e("sendingError"),children:"!"})]}),a&&a.length>0&&(0,pe.jsx)("ul",{className:dt.quickReplies,children:a.map(p=>(0,pe.jsx)("li",{className:dt.quickReply,children:p.title},p.title))})]})}),(0,pe.jsxs)(L.Actions,{fixed:r||n,children:[a&&a.length>0&&(0,pe.jsx)(L.DropdownButton,{label:e("answer"),disabled:s,children:a.map((p,d)=>(0,pe.jsx)(L.DropdownItem,{index:d,label:p.title,onClick:c},p.title))}),(0,pe.jsx)(L.ActionButton,{primary:!0,disabled:n,onClick:l,label:e(n?"suggestionSent":r?"tryAgain":"sendSuggestion")})]})]})},cu=Eh;var xr=require("react"),du=require("react-redux"),sa=k(require("classnames"));var oa=require("react/jsx-runtime"),na=()=>(0,oa.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,oa.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 pu={root:"_root_rjdyr_1",entity:"_entity_rjdyr_10",entityText:"_entityText_rjdyr_46",iconWrapper:"_iconWrapper_rjdyr_53",icon:"_icon_rjdyr_53",iconClicked:"_iconClicked_rjdyr_67"};var Ve=require("react/jsx-runtime"),kh=({entities:t})=>{let e=y("EntitiesWidgetList",pu),[o,n]=(0,xr.useState)(void 0),s=(0,du.useDispatch)(),r=()=>{n(void 0)},i=a=>{t&&(n(t.indexOf(a)),mn(a.text),s(Q({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,xr.useEffect)(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[o]),!t||t.length===0?null:(0,Ve.jsx)("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,l)=>(0,Ve.jsxs)("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[(0,Ve.jsx)("span",{className:e.entityText,children:a.text}),(0,Ve.jsxs)("span",{className:e.iconWrapper,children:[(0,Ve.jsx)("span",{className:(0,sa.default)(e.icon),children:(0,Ve.jsx)(na,{})}),(0,Ve.jsx)("span",{className:(0,sa.default)(e.icon,o===l&&e.iconClicked),children:(0,Ve.jsx)(na,{})})]})]},a.text))})},uu=kh;var ra=require("react/jsx-runtime"),gu=()=>(0,ra.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,ra.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 ia=require("react/jsx-runtime"),mu=()=>(0,ia.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,ia.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 aa=require("react/jsx-runtime"),fu=()=>(0,aa.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,aa.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 br=require("react");var la={};$(la,{enUS:()=>Ih,nlNL:()=>Rh});var Ih={copyCue:[{type:0,value:"Copy"}],copiedCue:[{type:0,value:"Copied!"}],removeCue:[{type:0,value:"Close"}]},Rh={copyCue:[{type:0,value:"Kopieer"}],copiedCue:[{type:0,value:"Gekopieerd!"}],removeCue:[{type:0,value:"Sluiten"}]};var ut=require("react/jsx-runtime"),Ph=({cue:t,onRemove:e,onCopy:o})=>{let n=T(la),[s,r]=(0,br.useState)(!1),i=l=>{l.preventDefault(),l.stopPropagation(),o&&(o(t.text),r(!0))},a=l=>{l.preventDefault(),l.stopPropagation(),e&&e(t.id)};return(0,br.useEffect)(()=>{if(!s)return;let l=setTimeout(()=>{r(!1)},1e3);return()=>{clearTimeout(l)}},[s]),(0,ut.jsx)(L,{"data-testid":"cue",children:(0,ut.jsxs)(D,{children:[(0,ut.jsxs)(D.Content,{children:[t.title&&(0,ut.jsx)(D.Title,{"data-testid":"widget-cue-title",children:t.title}),t.text]}),(0,ut.jsx)(L.Actions,{children:o&&(0,ut.jsx)(L.ActionButton,{primary:!0,onClick:i,label:n(s?"copiedCue":"copyCue")})}),(0,ut.jsx)(D.CloseIcon,{title:n("removeCue"),onClick:a})]})})},hu=Ph;var In=require("react/jsx-runtime"),Ah=({cues:t,onCopyCue:e,onRemoveCue:o})=>(0,In.jsx)(In.Fragment,{children:t.map(n=>(0,In.jsx)(hu,{cue:n,onRemove:o,onCopy:e},`${n.id}_${n.timestamp}`))}),yu=Ah;var _u=require("react-redux");var vu=require("react");var he=require("react/jsx-runtime"),Lh=({suggestion:t,lines:e,onEdit:o,onUse:n})=>{var g;let s=t.text||t.url||t.message,r=Os(s),i=T(Ut),a=C("showImages"),l=C("fallbackImage"),c=u=>{u.preventDefault(),u.stopPropagation(),n(s)},p=u=>{u.preventDefault(),u.stopPropagation(),o(t)},d=(0,vu.useCallback)(u=>{window.open(r,"_blank"),u.stopPropagation(),u.preventDefault()},[r]);return(0,he.jsxs)(L,{onClick:c,"data-testid":"edit-suggestion",children:[(0,he.jsxs)(D,{children:[a&&t.image&&(0,he.jsx)(D.Image,{src:fr(t,"small",l||void 0),title:t.title}),(0,he.jsxs)(D.Content,{children:[t.title&&(0,he.jsx)(D.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((g=t.searchKeywords)==null?void 0:g.length)>0&&(0,he.jsx)(L.Labels,{labels:t.searchKeywords}),(0,he.jsx)(D.Content,{cropText:e==="single",lineClamp:e==="multiple",children:s})]})]}),(0,he.jsxs)(L.Actions,{children:[r&&(0,he.jsx)(L.ActionButton,{onClick:d,label:i("visitUrl")}),(0,he.jsx)(L.ActionButton,{primary:!0,onClick:p,label:i("preview")}),(0,he.jsx)(L.ActionButton,{primary:!0,onClick:c,label:i("useSuggestion")})]})]})},Su=Lh;var Rn=require("react/jsx-runtime"),Mh=({contentType:t,lines:e,suggestions:o})=>{let n=be(),s=(0,_u.useSelector)(xt),r=a=>{n.send(wi,{state:s,suggestion:a,contentType:t})},i=(a,l)=>{n.send(ot,{text:a,suggestion:{...l,source:l.source,sourceText:l.text}})};return(0,Rn.jsx)(Rn.Fragment,{children:o.map(a=>(0,Rn.jsx)(Su,{suggestion:a,lines:e,onEdit:l=>r(l),onUse:l=>i(l,a)},a.text||a.url||a.message))})},xu=Mh;var ca={};$(ca,{enUS:()=>Nh,nlNL:()=>Oh});var Nh={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"}]},Oh={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 bu={root:"_root_x0pwe_1",loginText:"_loginText_x0pwe_7",stateText:"_stateText_x0pwe_8",sectionList:"_sectionList_x0pwe_20",shortcutList:"_shortcutList_x0pwe_24",shortcut:"_shortcut_x0pwe_24",link:"_link_x0pwe_52"};var R=require("react/jsx-runtime"),Cr=(t,e)=>{let o=(0,X.useSelector)(ne);(0,wu.useEffect)(()=>o?e.every(n=>!!n)?t():()=>{}:()=>{},[...e,o])},Dh=({onLogIn:t})=>{let e=T(ca),o=(0,X.useDispatch)(),n=C("isEmbedded"),s=y("Widget",bu),r=C("showAutoflows"),i=C("showCustomMessages"),a=C("showSummaryCommand"),l=C("showKnowledgeSearch"),c=C("showSearch"),p=(0,X.useSelector)(wt),d=(0,X.useSelector)(Js),g=(0,X.useSelector)(Md),u=(0,X.useSelector)(Gc),m=(0,X.useSelector)($s),f=(0,X.useSelector)(Bd),h=(0,X.useSelector)(Xn),E=(0,X.useSelector)(ao),x=(0,X.useSelector)(ne),_=(0,X.useSelector)(Gn),b=(0,X.useSelector)(Zd),v=(0,X.useSelector)(xt),A=be(),O=(0,X.useSelector)(bc),K=(0,X.useSelector)(Wd("/admin/")),H=C("adminUrl"),W=C("productName");if(Cr(()=>(o(En(_)),o(jd(_)),()=>{o(Vd(_))}),[o,E,i,_]),Cr(()=>(o(pt(_)),o(Nd(_)),()=>{o(Od(_))}),[o,E,r,_]),Cr(()=>{d.forEach(({type:I})=>{o(I==="entities"?Ne():Le(I))})},[o,E,h,p]),Cr(()=>(o(Ji()),()=>{o(Gd())}),[o]),E===!1)return(0,R.jsx)("div",{className:s.stateText,children:(0,R.jsx)("div",{children:(0,R.jsx)("p",{children:e("notSupported")})})},"supported");if(x===!1)return(0,R.jsx)("div",{className:s.loginText,children:(0,R.jsx)("div",{children:(0,R.jsx)(sr,{isEmbedded:n,loginUrl:H,onLogIn:t})})},"login");if(!p||!_||x===null||O||b)return(0,R.jsx)("div",{className:s.stateText,children:(0,R.jsx)("div",{children:(0,R.jsx)("p",{children:e("waiting")})})},"waiting");let z=c||a||l||K;return(0,R.jsx)("div",{className:(0,Cu.default)(s.root),"data-testid":"widget",children:(0,R.jsxs)(qn,{className:s.sectionList,children:[z&&(0,R.jsx)(We,{title:e("actions"),type:"shortcuts",children:(0,R.jsxs)("div",{className:s.shortcutList,children:[c&&(0,R.jsxs)("button",{className:s.shortcut,"data-testid":"shortcut-search",onClick:()=>A.send("ShowCommandPalette",{isOpen:!0}),children:[(0,R.jsx)(_o,{}),e("linkSearch")]}),a&&(0,R.jsxs)("button",{className:s.shortcut,"data-testid":"shortcut-summary",onClick:()=>A.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,R.jsx)(fu,{}),e("linkSummary")]}),l&&(0,R.jsxs)("button",{className:s.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>A.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,R.jsx)(mu,{}),e("linkKnowledgeSearch")]}),K&&(0,R.jsxs)("a",{className:s.shortcut,target:"_blank",href:K,"data-testid":"shortcut-studio-login",rel:"noreferrer",children:[(0,R.jsx)(gu,{}),e("linkStudioLogin",{productName:W})]})]})}),i&&f.length>0&&(0,R.jsx)(We,{type:"custom-messages","data-testid":"custom-messages",children:(0,R.jsx)(ue,{withDivider:!0,children:f.map(I=>(0,R.jsx)(cu,{suggestion:I},I.text))})}),r&&g.length>0&&(0,R.jsx)(We,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:(0,R.jsx)(ue,{withDivider:!0,children:(0,R.jsx)(au,{})})}),d.map(({type:I,title:ye,amount:Mr,lines:Fo})=>{var Ko;switch(I){case"entities":return m&&m.length>0&&(0,R.jsx)(We,{type:I,title:ye,"data-testid":`type-${I}`,children:(0,R.jsx)(uu,{entities:m})},I);case"cues":return u&&u.length>0&&(0,R.jsx)(We,{type:I,title:ye,"data-testid":`type-${I}`,children:(0,R.jsx)(ue,{withDivider:!0,children:(0,R.jsx)(yu,{cues:u,onRemoveCue:to=>o(Zc({id:to}))})})},I);default:return((Ko=v[I])==null?void 0:Ko.fetchState)==="done"&&v[I].suggestions.length>0&&(0,R.jsx)(We,{type:I,title:ye,"data-testid":`type-${I}`,children:(0,R.jsx)(ue,{withDivider:!0,children:(0,R.jsx)(xu,{lines:Fo,contentType:I,suggestions:v[I].suggestions.slice(0,Mr)||[]})})},I)}})]})})},Tu=Dh;function Do(t){let e=new Range;return e.selectNodeContents(t),e}function Eu(t,e,o){try{return At(t,e,o),!0}catch{return!1}}function wr(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function Tr(t){return"tagName"in t&&t.tagName==="BR"}var Pn=/[\u200B-\u200D\uFEFF]/g;function At(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,c){let p=-1,d=/[\u200B-\u200D\uFEFF]/;if(!d.test(l))return c;for(let g=0;g<=l.length;g++)if(d.test(l[g])||p++,p===c)return g;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let c=l.textContent,p=c.replace(Pn,""),d=s+p.length,g=e>=s&&e<=d,u=o>=s&&o<=d;if(g){let m=i(c,e-s);m===0&&!u?n.setStartBefore(l):n.setStart(l,m)}u&&(n.setEnd(l,i(c,o-s)),r=!0),s=d;break}case Node.ELEMENT_NODE:{if(Tr(l)&&(s===e&&n.setStartBefore(l),s++,s===o)){n.setEndAfter(l),r=!0;return}for(let p=0;p<l.childNodes.length&&(a(l.childNodes[p]),!r);p++);let c=l.lastChild;wr(l)&&c&&!wr(c)&&!Tr(c)&&s++;break}default:break}}if(a(t),n.startContainer===document)throw new Error("Offsets out of bound");return n}function An(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,c=0;function p(d){let g=d===o,u=d===s;switch(d.nodeType){case Node.TEXT_NODE:{let m=d.textContent;g&&(a=c+m.substring(0,n).replace(Pn,"").length),u&&(l=c+m.substring(0,r).replace(Pn,"").length),c+=m.replace(Pn,"").length;break}case Node.ELEMENT_NODE:{let m=d.nextSibling===null;Tr(d)&&!m&&c++;for(let f=0;f<d.childNodes.length;f++){let h=g&&f===n,E=u&&f===r;if(h&&(a=c),E&&(l=c),l!==void 0||((!h||!i)&&p(d.childNodes[f]),u&&f===r-1&&(l=c),l!==void 0))break}!u&&wr(d)&&!m&&c++,u&&(l=c);break}default:break}}if(p(t),l===void 0)throw new Error("Could not determine start and end");return{start:a??l,end:l}}function Ln(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(c){let p=c===o,d=c===s;switch(p&&i++,c.nodeType){case Node.TEXT_NODE:{if(i!==0)return;let g=p?n:0,u=d?r:void 0,m=c.textContent.replace(Pn,"");g===0&&u===void 0?a+=m:a+=m.substring(g,u);break}case Node.ELEMENT_NODE:{let g=c.nextSibling===null;i===0&&Tr(c)&&!g&&(a+=`
8
8
  `);for(let u=p?n:0;u<(d?Math.min(r,c.childNodes.length):c.childNodes.length)&&(l(c.childNodes[u]),i!==1);u++);!d&&i===0&&wr(c)&&!g&&(a+=`
9
- `);break}default:break}d&&i++}return l(t),a}function ku(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var Yt=class extends Xe{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),Ln(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!ku(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!ku(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return An(this.element,e);let o=this.lastKnownSelection;if(o&&Eu(this.element,o.start,o.end))return o;let n=Do(this.element);return n.collapse(!1),An(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return Ln(this.element,At(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(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let e=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==e&&(e=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};function Iu(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}var pa=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()}},da=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=Iu(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()}},ua=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(),w.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 da(e,this.deepdeskUrl,{debug:!0}):new pa(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=typeof s.data=="string"?JSON.parse(s.data):s.data;r.type==="event"&&r.channel===e&&(w.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;w.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)}},Ru=ua;var Ho=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var ga=t=>new Promise(e=>{setTimeout(e,t)});var Bo=class extends Ho{name="ClientError"},ma=class extends Ho{name="ServerError"},De=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,{abortLatest:l=!1,attempts:c=1,retryDelay:p=500,refreshTokenOn401:d=!0,retryOnError:g=b=>b instanceof TypeError,retryOnResponse:u=b=>b.status>=500,version:m="v1",...f}=o,h={credentials:"include",...f,headers:{"Content-Type":"application/json",...f.headers}};o.method!==void 0&&o.method!=="GET"&&this.csrfToken&&(h.headers={...h.headers,"X-CSRFToken":this.csrfToken}),typeof m=="string"&&(h.headers={...h.headers,"X-Deepdesk-API-Version":m});let E=c,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&l&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let _=async()=>(E--,a(i,h).then(async b=>u(b)&&!r.isAborted&&E>0?(await ga(p),_()):b.status===401&&d===!0&&x===!1?(x=!0,await this.refreshToken(),_()):b).catch(async b=>{if(g(b)&&!r.isAborted&&E>0)return await ga(p),_();throw b}));_().then(b=>b.json().catch(()=>null).then(v=>{b.status>=500?s(new ma("Server Error",v)):b.status===401?s(new Bo("Unauthorized",v)):b.status===403?s(new Bo("Forbidden",v)):b.status===404?s(new Bo("Not Found",v)):b.status>=400&&s(new Bo("Bad Request",v)),delete this.latestRequestByUrl[i],n(v)})).catch(b=>{s(b)})})}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 Hh;(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||={})})(Hh||={});function Er(t){return{...N(t),tags:t.tags}}var gt=class t{constructor(e,o={}){this.options=o;this.client=new De(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(),w.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...G(e),tags:e.tags},{version:"v2"});return Er(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null});return N(o)}async getKnowledgeAssistant(e){let o=await this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{version:null});return N(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null});return N(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null});return N(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(),w.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 w.info(`Successfully retrieved conversation ${r.id} for session ${e}`),Er(r)}async isConversationSupported(e,o={}){w.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=G(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return Er(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...G(s),tags:s.tags})),{version:"v2"})).map(s=>Er(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",G({...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:G({...o,...n})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e.filter(n=>n.text)})).entities}async getSummary(e,o={}){return(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})).summary}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 w.warn(`Invalid token '${e}'`),o})}async authenticateWithKey(e,o){await this.client.post("/apis/admin/session/api-key/",G(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}`,G(o),{abortLatest:!0})).map(r=>({...N(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`,G(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 N(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",G(e),{abortLatest:!0});return N(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,G(e),{version:"v2"});return N(o)}async knowledgeAssist(e,o,n,s={}){let r=await this.client.post(`/api/knowledge-assist/assistants/${n}/search`,G({question:e.question,promptInstruction:e.promptInstruction,chatHistory:o.map(i=>({question:i.question,answer:i.answer.answer})),agentId:s.agentId,conversationId:s.conversationId}),{version:"v2"});return N(r)}async requestLoginByEmail(e){let o=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return N(o)}async requestPasswordlessToken(){let e=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return N(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 N(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 N(i.cues)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(Ka);if(!o||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&o&&a!==o&&w.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(o)}`),this.latestReceivedDeepdeskVersions[i]=o})}};var Mn=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(hi(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,N(s))}catch{w.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 Bh;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(Bh||={});var Nn=class{constructor(e,o={}){this.apiUrl=e;this.client=new De(e,o)}client;streams={};logger=w;async getCustomMessages(e){let o=await this.client.get(`/sessions/${e}/suggestions`);return N(o.suggestions)}async sendCustomMessage(e,o){let n=await this.client.post(`/sessions/${e}/messages`,G(o));return N(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,G(o))}async getAutoflows(e){let o=await this.client.get(`/sessions/${e}/autoflows`);return N(o.autoflows)}async startAutoflowSession(e){let o=await this.client.post("/autoflow-sessions",G(e));return N(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new Mn(`${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 Pr=require("@reduxjs/toolkit");var Au=require("@reduxjs/toolkit");var Pu={startTime:null,stopTime:null},Lu=(0,Au.createSlice)({name:"handlingTime",initialState:Pu,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(M,()=>Pu)}}),{handlingTimeStart:Mu,handlingTimeStop:kr,handlingTimeReset:Nu}=Lu.actions,Ou=Lu.reducer;var Du=(t={})=>{let e={onAuthError:wo(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};var Rr=require("@reduxjs/toolkit");var Ir={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var eo=(0,Rr.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 Ir.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),Fh=(0,Rr.createSlice)({name:"styleSuggestions",initialState:Ir,reducers:{},extraReducers:t=>{t.addCase(eo.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(eo.rejected,e=>{e.fetchState="error"}).addCase(eo.fulfilled,(e,o)=>{e.fetchState="done",ft(e.list,o.payload)||(e.list=o.payload)}).addCase(Nt,e=>{e.list=Ir.list}).addCase(M,()=>Ir)}}),Hu=Fh.reducer;var Bu=(t={})=>{let e,o=!0,n={getStyleSuggestions:eo,debounce:500,...t};return s=>r=>i=>{var u;let a=s.getState().input.text,l=r(i),c=s.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:p}=c.settings;if(!((u=c.conversation.current)==null?void 0:u.id)||!p)return l;let{text:g}=c.input;return g===a&&!o||(clearTimeout(e),g==="")||(e=setTimeout(()=>{o=!1,s.dispatch(n.getStyleSuggestions({text:g}))},t.debounce)),l}};function Kh(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var Fu=(t={})=>{let e={getTextSuggestions:Le,getAutocompleteSuggestions:an,debounce:200,check:Lo,...t},o;return n=>s=>r=>{var f;let{input:{userCommitted:i}}=n.getState(),a=s(r),l=n.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:p}=l.settings,d=(f=l.conversation.current)==null?void 0:f.id,g=r.type===Us.toString();if(!d||!c&&!p)return a;let{input:{userCommitted:u}}=l;return Kh(u,i)&&!g||(clearTimeout(o),!e.check(l))||(o=setTimeout(()=>{let h=lo(l);h===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(h))},g?0:e.debounce)),a}};var Ku=eo.fulfilled.toString();function Uh(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 Uu=t=>e=>o=>n=>{var c;if(n.type!==Ku){o(n);return}let s=e.getState().styleSuggestions.list;o(n);let r=e.getState(),i=r.styleSuggestions.list,a=(c=r.conversation)==null?void 0:c.current;if(s===i)return;let l=Uh(s,i);n.type===Ku&&l.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var zh=(0,Pr.combineReducers)({activeSuggestion:Mc,answer:kp,auth:$c,autoflows:Dd,conversation:Ga,contentTypes:cp,customMessages:qd,passwordlessToken:Xd,entities:gp,knowledgeAssistant:wp,handlingTime:Ou,info:ic,input:Ur.reducer,overlayInput:ae.reducer,settings:Va,profile:Pp,search:gc,summary:Sp,styleSuggestions:Hu,ui:Bc,rules:Qc,textSuggestions:kc});function zu(t){return(0,Pr.configureStore)({reducer:zh,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),Du(),Fu({debounce:200}),Bu({debounce:500}),Uu(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var jh=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},Vh=t=>e=>o=>n=>{var a;let s=e.getState(),r=Hr("inlineSuggestions")(s);switch(n.type){case Ye.toString():{let l=Ks(n.payload.contentType)(e.getState()),c=l.indexOf(n.payload.suggestion);t.emit("edit-suggestion",{contentType:n.payload.contentType,index:c,suggestions:l});break}case wo.toString():{!n.payload&&t.emit("logout",void 0);break}case Re.toString():{let{start:l,end:c}=s.input.selection;t.emit("select-suggestion",{type:jh(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case os.toString():{let{start:l,end:c}=s.input.selection;t.emit("replace",{...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case $o.toString():{let l=e.getState(),{text:c,selection:p}=l.input.userCommitted;t.emit("reset",{text:c,selectionAfter:p},{mayApplyChanges:!0});break}case is.toString():t.emit("select-image",n.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:s.conversation.current.id,data:{path:n.payload.suggestion.image,title:n.payload.suggestion.title}});break;case Ne.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:n.payload}});break;case nt.fulfilled.toString():t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{summary:n.payload.summary}});break;case Q.toString():t.sendEvent(n.payload.name,{conversationId:((a=n.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:n.payload.data});break;case ns.toString():t.handleKeyDown(n.payload);break;case Nt.toString():t.logSendMessage(n.payload);break;case ss.toString():t.logSendEditSuggestionMessage(n.payload);break;case rs.toString():t.handleInputChanged(n.payload);break;case tt.fulfilled.toString():t.broadcast(Ti,n.payload,!1),t.emit("cues",n.payload);break;default:break}let i=o(n);switch(n.type){case Nt.toString():t.handleAfterSendMessage(n.payload);break;case ln.toString():t.onUpdateShowTabHint(n.payload);break;case kr.toString():t.logHandlingTime();break;case Re.toString():{r&&(e.dispatch(Be([])),e.dispatch($e()));break}case Be.toString():{r&&n.payload.length>0&&e.dispatch(yt(0));break}default:break}return i},ju=Vh;function fa(t){return t.toISOString().replace("T"," ").replace("Z","")}function Vu(t,e){var s,r,i;let{startTime:o,stopTime:n}=t.handlingTime;if(!o||!n)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:t.conversation.current.id,clientVersion:e.version,agentId:(s=t.info.agentInfo)==null?void 0:s.agentId,agentName:(r=t.info.agentInfo)==null?void 0:r.agentName,agentEmail:(i=t.info.agentInfo)==null?void 0:i.agentEmail,timeStart:fa(o),timeStop:fa(n)}}function ha(t,e,o){var O,K,H;let{text:n,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:d,cuts:g,deletions:u,textSuggestions:m,offeredTextSuggestions:f}}=e[t],h=n.length,x=m.reduce((W,{text:z,searchTerm:I})=>W+z.length-(I?I.length:0),0),_=c??Date.now(),b=(Date.now()-_)/1e3+(p||0),v=s/b,A=m.reduce((W,{searchTerm:z})=>W+(z?z.length:0),0);return{conversationId:e.conversation.current.id,source:"agent",text:n,clientVersion:o.version,pastes:d,cuts:g,deletions:u,lenTextTyped:s+A,lenTextTotal:h,lenTextAssisted:x,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:b,charsPerSecond:v,numPastes:l,textSuggestionsV2:m,suggestionsCounters:[{source:"gpt",countOffered:f.filter(W=>W.source==="gpt").length}],agentId:(O=e.info.agentInfo)==null?void 0:O.agentId,agentName:(K=e.info.agentInfo)==null?void 0:K.agentName,agentEmail:(H=e.info.agentInfo)==null?void 0:H.agentEmail}}function ya(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return ya(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?ya(s,e):null}function qu(t,e){return ya(t,e)}function Wu(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function qh(t){return typeof t=="object"&&t!==null&&"tagName"in t}function Ar(t){return qh(t)&&(Et(t)||Cs(t))}var $u=(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{w.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function Wh(t){return t.offsetParent!==null}function Gu(t){if(!Wh(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 Lr(t,e,o=100){let n=Gu(t);e({isVisible:n});let s=setInterval(()=>{let r=Gu(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}var q=require("react/jsx-runtime");var Xu=$u("showTabHint",!0),On=class t{static version="10.12.1-beta.6";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 c=e.replace(/\/api$/,"");this.deepdeskApi=new gt(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[ju({broadcast:(d,g,u)=>{this.broadcastEvents.send(d,g,u)},emit:(d,g,u)=>this.emit(d,g,u),handleAfterSendMessage:d=>this.handleAfterSendMessage(d),handleInputChanged:d=>this.handleInputChanged(d),handleKeyDown:d=>this.handleKeyDown(d),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:d=>this.logSendMessage(d),logSendEditSuggestionMessage:d=>this.logSendEditMessage(d),onUpdateShowTabHint:d=>Xu.update(d),sendEvent:(d,g)=>this.deepdeskApi.sendEvent(d,g)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new Nn(o)}),this.store=zu(p),this.broadcastEvents=new Ru({debug:!0,deepdeskUrl:c,eventMap:Jc(this.store),createCustomChannel:l}),this.store.dispatch(ln(Xu.value())),this.store.dispatch($n({locale:s,adminUrl:c,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?(w.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(w.warn("Profile has not been loaded (yet)"),!0):(w.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(wo(null)),this.store.dispatch(et()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();ne(n)&&Uc(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(et())).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){w.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(Fr({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Zn(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Qn({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Kr(e))).payload}async postMessages(e){return(await this.store.dispatch(Yn(e))).payload}async updateConversation(e){return(await this.store.dispatch(Jn(e))).payload}resetConversation(){this.store.dispatch(M()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(nt());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch($n(e))}setVisitorInfo(e){this.store.dispatch(rc(e))}async setAgentInfo(e){await this.store.dispatch(on(e))}async setAgentSettings(e){await this.store.dispatch(yi(e))}async getAgentSettings(){return(await this.store.dispatch(vi())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(Us()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(rs(e))}notifyKeyDown(e){this.store.dispatch(ns(e))}notifyPaste(e,o){this.store.dispatch(al({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(rl(e))}notifyExternalSuggestion(e){this.store.dispatch(Re(e)),this.store.dispatch($e())}notifyEditSuggestion(e){this.store.dispatch(Tc(e.contentType,e.suggestions)),this.store.dispatch(Ye({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}async evaluateRule(e,o={}){let{payload:n,error:s}=await this.store.dispatch(tt({label:e,params:o}));if(s)throw s;return n}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(bt({collapse:!1})),this.inputMediator&&this.store.dispatch(Ya({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(Be([])))}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(il(ts(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(ol()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(sl()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch($o()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(e.key){case"Up":case"ArrowUp":i?p():c();return;case"Down":case"ArrowDown":{i?c():p();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(yt(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(yt(-1)),this.store.dispatch($o()),e.preventDefault()):o||(this.store.dispatch(bt({collapse:!0})),this.store.dispatch(Dc(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:d}=this.state.input,g=d.text.substring(0,d.selection.end),{tabCompletionSuggestion:u}=this.state.input;this.store.dispatch(ln(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&u&&u.text.startsWith(g)&&(this.store.dispatch(Re({text:u.text,suggestion:u,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(ll()),this.store.dispatch(Be([]))}handlingTimeStart(){this.state.handlingTime.startTime||(w.info("Start handling time"),this.store.dispatch(Mu()))}handlingTimeStop(){this.state.handlingTime.startTime&&(w.info("Stop handling time"),this.store.dispatch(kr()))}logSendMessage(e){let o=ha("input",this.state,{version:this.version});e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logSendEditMessage(e){let o=ha("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(tl(this.state.overlayInput.metrics))}logHandlingTime(){let e=Vu(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Nu())}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(Re({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){w.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),w.error(i)}})};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]=Ht(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{(0,Te.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]=Ht(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{(0,Te.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 Dt(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,Te.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),w.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()?(w.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(pl(n.metrics))):w.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(!Ar(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:c,showSuggestionsAfterPattern:p,isEmbedded:d,detectSubmit:g,insertLink:u,inputMediator:m,closestScrollSelector:f,appendOverlayTo:h,inlineSuggestions:E,floatingMenu:x}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:u,isEmbedded:d,inlineSuggestions:E,floatingMenu:!!x}),o.automaticHandlingTime&&this.setupHandlingTime(e),Dt(e),this.inputMediator=m||(Et(e)?new Ze(e):new Yt(e)),this.inputMediator.on("change",({plainText:v})=>{this.notifyInputChanged(v)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(cl({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",v=>{this.notifyKeyDown(v)}),this.inputMediator.on("paste",({pastedText:v,selectionText:A})=>{this.notifyPaste(v,A)}),this.inputMediator.on("cut",({selectionText:v})=>{this.notifyCut(v)});let _=f&&qu(e,f)||void 0;if(E){let{customStyles:v,appendOverlayTo:A}=o;if(Et(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let O=this.createInlineContainer(e,"deepdesk-caret");(0,Te.render)((0,q.jsx)(Qt,{store:this.store,customStyles:v,children:(0,q.jsx)(Wt,{broadcastEvents:this.broadcastEvents,children:(0,q.jsx)(Jp,{})})}),O),this.inputMediator.on("caret",H=>{this.store.dispatch(Be([])),H?(O.style.display="block",O.style.top=`${H.top}px`,O.style.left=`${H.left}px`):O.style.display="none"});let K=this.overlayContainerFactory("floating-menu",_||e,{appendTo:typeof x=="object"&&"appendOverlayTo"in x?x.appendOverlayTo:A},v==null?void 0:v.floatingMenuRootNode);(0,Te.render)((0,q.jsx)(Qt,{store:this.store,customStyles:v,children:(0,q.jsx)(Wt,{broadcastEvents:this.broadcastEvents,children:(0,q.jsx)(qp,{onLogIn:()=>this.loginViaPopup().catch(H=>w.warn(H.message))})})}),K)}else{let v=this.overlayContainerFactory("deepdesk-tab-completion",_||e,{appendTo:h,closestScrollElement:_,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),A=this.overlayContainerFactory("deepdesk-suggestions-overlay",_||e,{appendTo:h},n==null?void 0:n.suggestionsRootNode);(0,Te.render)((0,q.jsx)(Qt,{store:this.store,customStyles:n,children:(0,q.jsx)(Wt,{broadcastEvents:this.broadcastEvents,children:(0,q.jsx)(Pd,{inputElement:e})})}),v),(0,Te.render)((0,q.jsx)(Qt,{store:this.store,customStyles:n,children:(0,q.jsx)(Wt,{broadcastEvents:this.broadcastEvents,children:(0,q.jsx)(ld,{onLogIn:()=>this.loginViaPopup().catch(O=>w.warn(O.message))})})}),A)}(0,Te.render)((0,q.jsx)(Qt,{store:this.store,customStyles:n,children:(0,q.jsx)(Wt,{broadcastEvents:this.broadcastEvents,children:(0,q.jsx)(Bp,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",v=>{clearTimeout(b),v===null?b=setTimeout(()=>{v!==null&&this.store.dispatch(zr(v))},500):this.store.dispatch(zr(v))}),this.inputMediator.on("disabled",()=>{var v;(v=this.inputMediator)==null||v.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{g&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(bo(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(bo(!0))),this.store.dispatch(el({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 v;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((v=this.state.conversation.current)==null?void 0:v.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&&w.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,Te.render)((0,q.jsx)(Qt,{store:this.store,customStyles:n,children:(0,q.jsx)(Wt,{broadcastEvents:this.broadcastEvents,children:(0,q.jsx)(Tu,{onLogIn:()=>this.loginViaPopup().catch(i=>w.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,Te.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=Lr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Wu(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(xn());let e=wt(this.state);e&&(await this.store.dispatch(vn()),this.store.dispatch($n({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,c=()=>{p&&!p.closed&&p.close(),window.removeEventListener("message",d),clearInterval(g)};r.onmessage=async u=>{var m,f;if((m=u.data)!=null&&m.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((f=u.data)==null?void 0:f.jwt),await this.isLoggedIn(),this.broadcastEvents.send(dn),l=!0,s.port1.close(),o()}catch(h){console.error(h),n(h)}finally{l=!0,c()}};let p=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");p===null&&n(new Error("Popup blocked by browser"));let d=async u=>{var m;if(u.origin===a.origin)switch((m=u.data)==null?void 0:m.type){case"deepdesk-popup-loaded":{try{let f=JSON.stringify({type:"deepdesk-popup-create-channel"});p==null||p.postMessage(f,a.origin,[s.port2])}catch(f){w.error("Error posting message to popup",f),n(f)}break}case"deepdesk-popup-error":{c(),u.data.message==="Timeout"&&w.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(u.data.message));break}}};window.addEventListener("message",d);let g=setInterval(()=>{p&&!p.closed||(c(),l||n(new Error("Popup closed by user")))},200);this.unmountHandlers.push(c)})}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(w.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;w.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=Js(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(Ne()):this.store.dispatch(Le(n))})}catch(n){this.handleError(n)}}};async function Zu(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 Qu(t,e,o={}){let n=o.replace?At(t,o.replace.start,o.replace.end):Do(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(`
9
+ `);break}default:break}d&&i++}return l(t),a}function ku(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var Yt=class extends Xe{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),Ln(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!ku(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!ku(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return An(this.element,e);let o=this.lastKnownSelection;if(o&&Eu(this.element,o.start,o.end))return o;let n=Do(this.element);return n.collapse(!1),An(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return Ln(this.element,At(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(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let e=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==e&&(e=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};function Iu(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}var pa=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()}},da=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=Iu(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()}},ua=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(),w.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 da(e,this.deepdeskUrl,{debug:!0}):new pa(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=typeof s.data=="string"?JSON.parse(s.data):s.data;r.type==="event"&&r.channel===e&&(w.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;w.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)}},Ru=ua;var Ho=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var ga=t=>new Promise(e=>{setTimeout(e,t)});var Bo=class extends Ho{name="ClientError"},ma=class extends Ho{name="ServerError"},De=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,{abortLatest:l=!1,attempts:c=1,retryDelay:p=500,refreshTokenOn401:d=!0,retryOnError:g=b=>b instanceof TypeError,retryOnResponse:u=b=>b.status>=500,version:m="v1",...f}=o,h={credentials:"include",...f,headers:{"Content-Type":"application/json",...f.headers}};o.method!==void 0&&o.method!=="GET"&&this.csrfToken&&(h.headers={...h.headers,"X-CSRFToken":this.csrfToken}),typeof m=="string"&&(h.headers={...h.headers,"X-Deepdesk-API-Version":m});let E=c,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&l&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let _=async()=>(E--,a(i,h).then(async b=>u(b)&&!r.isAborted&&E>0?(await ga(p),_()):b.status===401&&d===!0&&x===!1?(x=!0,await this.refreshToken(),_()):b).catch(async b=>{if(g(b)&&!r.isAborted&&E>0)return await ga(p),_();throw b}));_().then(b=>b.json().catch(()=>null).then(v=>{b.status>=500?s(new ma("Server Error",v)):b.status===401?s(new Bo("Unauthorized",v)):b.status===403?s(new Bo("Forbidden",v)):b.status===404?s(new Bo("Not Found",v)):b.status>=400&&s(new Bo("Bad Request",v)),delete this.latestRequestByUrl[i],n(v)})).catch(b=>{s(b)})})}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 Hh;(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||={})})(Hh||={});function Er(t){return{...N(t),tags:t.tags}}var gt=class t{constructor(e,o={}){this.options=o;this.client=new De(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(),w.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...G(e),tags:e.tags},{version:"v2"});return Er(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null});return N(o)}async getKnowledgeAssistant(e){let o=await this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{version:null});return N(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null});return N(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null});return N(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(),w.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 w.info(`Successfully retrieved conversation ${r.id} for session ${e}`),Er(r)}async isConversationSupported(e,o={}){w.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=G(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return Er(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...G(s),tags:s.tags})),{version:"v2"})).map(s=>Er(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",G({...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:G({...o,...n})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e.filter(n=>n.text)})).entities}async getSummary(e,o={}){return(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})).summary}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 w.warn(`Invalid token '${e}'`),o})}async authenticateWithKey(e,o){await this.client.post("/apis/admin/session/api-key/",G(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}`,G(o),{abortLatest:!0})).map(r=>({...N(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`,G(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 N(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",G(e),{abortLatest:!0});return N(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,G(e),{version:"v2"});return N(o)}async knowledgeAssist(e,o,n,s={}){let r=await this.client.post(`/api/knowledge-assist/assistants/${n}/search`,G({question:e.question,promptInstruction:e.promptInstruction,chatHistory:o.map(i=>({question:i.question,answer:i.answer.answer})),agentId:s.agentId,conversationId:s.conversationId}),{version:"v2"});return N(r)}async requestLoginByEmail(e){let o=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return N(o)}async requestPasswordlessToken(){let e=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return N(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 N(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 N(i.cues)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(Ka);if(!o||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&o&&a!==o&&w.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(o)}`),this.latestReceivedDeepdeskVersions[i]=o})}};var Mn=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(hi(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,N(s))}catch{w.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 Bh;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(Bh||={});var Nn=class{constructor(e,o={}){this.apiUrl=e;this.client=new De(e,o)}client;streams={};logger=w;async getCustomMessages(e){let o=await this.client.get(`/sessions/${e}/suggestions`);return N(o.suggestions)}async sendCustomMessage(e,o){let n=await this.client.post(`/sessions/${e}/messages`,G(o));return N(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,G(o))}async getAutoflows(e){let o=await this.client.get(`/sessions/${e}/autoflows`);return N(o.autoflows)}async startAutoflowSession(e){let o=await this.client.post("/autoflow-sessions",G(e));return N(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new Mn(`${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 Pr=require("@reduxjs/toolkit");var Au=require("@reduxjs/toolkit");var Pu={startTime:null,stopTime:null},Lu=(0,Au.createSlice)({name:"handlingTime",initialState:Pu,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(M,()=>Pu)}}),{handlingTimeStart:Mu,handlingTimeStop:kr,handlingTimeReset:Nu}=Lu.actions,Ou=Lu.reducer;var Du=(t={})=>{let e={onAuthError:wo(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};var Rr=require("@reduxjs/toolkit");var Ir={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var eo=(0,Rr.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 Ir.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),Fh=(0,Rr.createSlice)({name:"styleSuggestions",initialState:Ir,reducers:{},extraReducers:t=>{t.addCase(eo.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(eo.rejected,e=>{e.fetchState="error"}).addCase(eo.fulfilled,(e,o)=>{e.fetchState="done",ft(e.list,o.payload)||(e.list=o.payload)}).addCase(Nt,e=>{e.list=Ir.list}).addCase(M,()=>Ir)}}),Hu=Fh.reducer;var Bu=(t={})=>{let e,o=!0,n={getStyleSuggestions:eo,debounce:500,...t};return s=>r=>i=>{var u;let a=s.getState().input.text,l=r(i),c=s.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:p}=c.settings;if(!((u=c.conversation.current)==null?void 0:u.id)||!p)return l;let{text:g}=c.input;return g===a&&!o||(clearTimeout(e),g==="")||(e=setTimeout(()=>{o=!1,s.dispatch(n.getStyleSuggestions({text:g}))},t.debounce)),l}};function Kh(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var Fu=(t={})=>{let e={getTextSuggestions:Le,getAutocompleteSuggestions:an,debounce:200,check:Lo,...t},o;return n=>s=>r=>{var f;let{input:{userCommitted:i}}=n.getState(),a=s(r),l=n.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:p}=l.settings,d=(f=l.conversation.current)==null?void 0:f.id,g=r.type===Us.toString();if(!d||!c&&!p)return a;let{input:{userCommitted:u}}=l;return Kh(u,i)&&!g||(clearTimeout(o),!e.check(l))||(o=setTimeout(()=>{let h=lo(l);h===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(h))},g?0:e.debounce)),a}};var Ku=eo.fulfilled.toString();function Uh(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 Uu=t=>e=>o=>n=>{var c;if(n.type!==Ku){o(n);return}let s=e.getState().styleSuggestions.list;o(n);let r=e.getState(),i=r.styleSuggestions.list,a=(c=r.conversation)==null?void 0:c.current;if(s===i)return;let l=Uh(s,i);n.type===Ku&&l.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var zh=(0,Pr.combineReducers)({activeSuggestion:Mc,answer:kp,auth:$c,autoflows:Dd,conversation:Ga,contentTypes:cp,customMessages:qd,passwordlessToken:Xd,entities:gp,knowledgeAssistant:wp,handlingTime:Ou,info:ic,input:Ur.reducer,overlayInput:ae.reducer,settings:Va,profile:Pp,search:gc,summary:Sp,styleSuggestions:Hu,ui:Bc,rules:Qc,textSuggestions:kc});function zu(t){return(0,Pr.configureStore)({reducer:zh,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),Du(),Fu({debounce:200}),Bu({debounce:500}),Uu(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var jh=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},Vh=t=>e=>o=>n=>{var a;let s=e.getState(),r=Hr("inlineSuggestions")(s);switch(n.type){case Ye.toString():{let l=Ks(n.payload.contentType)(e.getState()),c=l.indexOf(n.payload.suggestion);t.emit("edit-suggestion",{contentType:n.payload.contentType,index:c,suggestions:l});break}case wo.toString():{!n.payload&&t.emit("logout",void 0);break}case Re.toString():{let{start:l,end:c}=s.input.selection;t.emit("select-suggestion",{type:jh(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case os.toString():{let{start:l,end:c}=s.input.selection;t.emit("replace",{...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case $o.toString():{let l=e.getState(),{text:c,selection:p}=l.input.userCommitted;t.emit("reset",{text:c,selectionAfter:p},{mayApplyChanges:!0});break}case is.toString():t.emit("select-image",n.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:s.conversation.current.id,data:{path:n.payload.suggestion.image,title:n.payload.suggestion.title}});break;case Ne.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:n.payload}});break;case nt.fulfilled.toString():t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{summary:n.payload.summary}});break;case Q.toString():t.sendEvent(n.payload.name,{conversationId:((a=n.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:n.payload.data});break;case ns.toString():t.handleKeyDown(n.payload);break;case Nt.toString():t.logSendMessage(n.payload);break;case ss.toString():t.logSendEditSuggestionMessage(n.payload);break;case rs.toString():t.handleInputChanged(n.payload);break;case tt.fulfilled.toString():t.broadcast(Ti,n.payload,!1),t.emit("cues",n.payload);break;default:break}let i=o(n);switch(n.type){case Nt.toString():t.handleAfterSendMessage(n.payload);break;case ln.toString():t.onUpdateShowTabHint(n.payload);break;case kr.toString():t.logHandlingTime();break;case Re.toString():{r&&(e.dispatch(Be([])),e.dispatch($e()));break}case Be.toString():{r&&n.payload.length>0&&e.dispatch(yt(0));break}default:break}return i},ju=Vh;function fa(t){return t.toISOString().replace("T"," ").replace("Z","")}function Vu(t,e){var s,r,i;let{startTime:o,stopTime:n}=t.handlingTime;if(!o||!n)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:t.conversation.current.id,clientVersion:e.version,agentId:(s=t.info.agentInfo)==null?void 0:s.agentId,agentName:(r=t.info.agentInfo)==null?void 0:r.agentName,agentEmail:(i=t.info.agentInfo)==null?void 0:i.agentEmail,timeStart:fa(o),timeStop:fa(n)}}function ha(t,e,o){var O,K,H;let{text:n,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:d,cuts:g,deletions:u,textSuggestions:m,offeredTextSuggestions:f}}=e[t],h=n.length,x=m.reduce((W,{text:z,searchTerm:I})=>W+z.length-(I?I.length:0),0),_=c??Date.now(),b=(Date.now()-_)/1e3+(p||0),v=s/b,A=m.reduce((W,{searchTerm:z})=>W+(z?z.length:0),0);return{conversationId:e.conversation.current.id,source:"agent",text:n,clientVersion:o.version,pastes:d,cuts:g,deletions:u,lenTextTyped:s+A,lenTextTotal:h,lenTextAssisted:x,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:b,charsPerSecond:v,numPastes:l,textSuggestionsV2:m,suggestionsCounters:[{source:"gpt",countOffered:f.filter(W=>W.source==="gpt").length}],agentId:(O=e.info.agentInfo)==null?void 0:O.agentId,agentName:(K=e.info.agentInfo)==null?void 0:K.agentName,agentEmail:(H=e.info.agentInfo)==null?void 0:H.agentEmail}}function ya(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return ya(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?ya(s,e):null}function qu(t,e){return ya(t,e)}function Wu(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function qh(t){return typeof t=="object"&&t!==null&&"tagName"in t}function Ar(t){return qh(t)&&(Et(t)||Cs(t))}var $u=(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{w.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function Wh(t){return t.offsetParent!==null}function Gu(t){if(!Wh(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 Lr(t,e,o=100){let n=Gu(t);e({isVisible:n});let s=setInterval(()=>{let r=Gu(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}var q=require("react/jsx-runtime");var Xu=$u("showTabHint",!0),On=class t{static version="10.12.1-beta.7";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 c=e.replace(/\/api$/,"");this.deepdeskApi=new gt(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[ju({broadcast:(d,g,u)=>{this.broadcastEvents.send(d,g,u)},emit:(d,g,u)=>this.emit(d,g,u),handleAfterSendMessage:d=>this.handleAfterSendMessage(d),handleInputChanged:d=>this.handleInputChanged(d),handleKeyDown:d=>this.handleKeyDown(d),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:d=>this.logSendMessage(d),logSendEditSuggestionMessage:d=>this.logSendEditMessage(d),onUpdateShowTabHint:d=>Xu.update(d),sendEvent:(d,g)=>this.deepdeskApi.sendEvent(d,g)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new Nn(o)}),this.store=zu(p),this.broadcastEvents=new Ru({debug:!0,deepdeskUrl:c,eventMap:Jc(this.store),createCustomChannel:l}),this.store.dispatch(ln(Xu.value())),this.store.dispatch($n({locale:s,adminUrl:c,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?(w.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(w.warn("Profile has not been loaded (yet)"),!0):(w.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(wo(null)),this.store.dispatch(et()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();ne(n)&&Uc(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(et())).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){w.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(Fr({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Zn(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Qn({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Kr(e))).payload}async postMessages(e){return(await this.store.dispatch(Yn(e))).payload}async updateConversation(e){return(await this.store.dispatch(Jn(e))).payload}resetConversation(){this.store.dispatch(M()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(nt());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch($n(e))}setVisitorInfo(e){this.store.dispatch(rc(e))}async setAgentInfo(e){await this.store.dispatch(on(e))}async setAgentSettings(e){await this.store.dispatch(yi(e))}async getAgentSettings(){return(await this.store.dispatch(vi())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(Us()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(rs(e))}notifyKeyDown(e){this.store.dispatch(ns(e))}notifyPaste(e,o){this.store.dispatch(al({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(rl(e))}notifyExternalSuggestion(e){this.store.dispatch(Re(e)),this.store.dispatch($e())}notifyEditSuggestion(e){this.store.dispatch(Tc(e.contentType,e.suggestions)),this.store.dispatch(Ye({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}async evaluateRule(e,o={}){let{payload:n,error:s}=await this.store.dispatch(tt({label:e,params:o}));if(s)throw s;return n}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(bt({collapse:!1})),this.inputMediator&&this.store.dispatch(Ya({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(Be([])))}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(il(ts(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(ol()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(sl()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch($o()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(e.key){case"Up":case"ArrowUp":i?p():c();return;case"Down":case"ArrowDown":{i?c():p();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(yt(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(yt(-1)),this.store.dispatch($o()),e.preventDefault()):o||(this.store.dispatch(bt({collapse:!0})),this.store.dispatch(Dc(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:d}=this.state.input,g=d.text.substring(0,d.selection.end),{tabCompletionSuggestion:u}=this.state.input;this.store.dispatch(ln(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&u&&u.text.startsWith(g)&&(this.store.dispatch(Re({text:u.text,suggestion:u,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(ll()),this.store.dispatch(Be([]))}handlingTimeStart(){this.state.handlingTime.startTime||(w.info("Start handling time"),this.store.dispatch(Mu()))}handlingTimeStop(){this.state.handlingTime.startTime&&(w.info("Stop handling time"),this.store.dispatch(kr()))}logSendMessage(e){let o=ha("input",this.state,{version:this.version});e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logSendEditMessage(e){let o=ha("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(tl(this.state.overlayInput.metrics))}logHandlingTime(){let e=Vu(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Nu())}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(Re({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){w.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),w.error(i)}})};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]=Ht(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{(0,Te.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]=Ht(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{(0,Te.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 Dt(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,Te.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),w.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()?(w.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(pl(n.metrics))):w.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(!Ar(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:c,showSuggestionsAfterPattern:p,isEmbedded:d,detectSubmit:g,insertLink:u,inputMediator:m,closestScrollSelector:f,appendOverlayTo:h,inlineSuggestions:E,floatingMenu:x}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:u,isEmbedded:d,inlineSuggestions:E,floatingMenu:!!x}),o.automaticHandlingTime&&this.setupHandlingTime(e),Dt(e),this.inputMediator=m||(Et(e)?new Ze(e):new Yt(e)),this.inputMediator.on("change",({plainText:v})=>{this.notifyInputChanged(v)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(cl({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",v=>{this.notifyKeyDown(v)}),this.inputMediator.on("paste",({pastedText:v,selectionText:A})=>{this.notifyPaste(v,A)}),this.inputMediator.on("cut",({selectionText:v})=>{this.notifyCut(v)});let _=f&&qu(e,f)||void 0;if(E){let{customStyles:v,appendOverlayTo:A}=o;if(Et(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let O=this.createInlineContainer(e,"deepdesk-caret");(0,Te.render)((0,q.jsx)(Qt,{store:this.store,customStyles:v,children:(0,q.jsx)(Wt,{broadcastEvents:this.broadcastEvents,children:(0,q.jsx)(Jp,{})})}),O),this.inputMediator.on("caret",H=>{this.store.dispatch(Be([])),H?(O.style.display="block",O.style.top=`${H.top}px`,O.style.left=`${H.left}px`):O.style.display="none"});let K=this.overlayContainerFactory("floating-menu",_||e,{appendTo:typeof x=="object"&&"appendOverlayTo"in x?x.appendOverlayTo:A},v==null?void 0:v.floatingMenuRootNode);(0,Te.render)((0,q.jsx)(Qt,{store:this.store,customStyles:v,children:(0,q.jsx)(Wt,{broadcastEvents:this.broadcastEvents,children:(0,q.jsx)(qp,{onLogIn:()=>this.loginViaPopup().catch(H=>w.warn(H.message))})})}),K)}else{let v=this.overlayContainerFactory("deepdesk-tab-completion",_||e,{appendTo:h,closestScrollElement:_,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),A=this.overlayContainerFactory("deepdesk-suggestions-overlay",_||e,{appendTo:h},n==null?void 0:n.suggestionsRootNode);(0,Te.render)((0,q.jsx)(Qt,{store:this.store,customStyles:n,children:(0,q.jsx)(Wt,{broadcastEvents:this.broadcastEvents,children:(0,q.jsx)(Pd,{inputElement:e})})}),v),(0,Te.render)((0,q.jsx)(Qt,{store:this.store,customStyles:n,children:(0,q.jsx)(Wt,{broadcastEvents:this.broadcastEvents,children:(0,q.jsx)(ld,{onLogIn:()=>this.loginViaPopup().catch(O=>w.warn(O.message))})})}),A)}(0,Te.render)((0,q.jsx)(Qt,{store:this.store,customStyles:n,children:(0,q.jsx)(Wt,{broadcastEvents:this.broadcastEvents,children:(0,q.jsx)(Bp,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",v=>{clearTimeout(b),v===null?b=setTimeout(()=>{v!==null&&this.store.dispatch(zr(v))},500):this.store.dispatch(zr(v))}),this.inputMediator.on("disabled",()=>{var v;(v=this.inputMediator)==null||v.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{g&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(bo(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(bo(!0))),this.store.dispatch(el({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 v;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((v=this.state.conversation.current)==null?void 0:v.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&&w.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,Te.render)((0,q.jsx)(Qt,{store:this.store,customStyles:n,children:(0,q.jsx)(Wt,{broadcastEvents:this.broadcastEvents,children:(0,q.jsx)(Tu,{onLogIn:()=>this.loginViaPopup().catch(i=>w.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,Te.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=Lr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Wu(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(xn());let e=wt(this.state);e&&(await this.store.dispatch(vn()),this.store.dispatch($n({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,c=()=>{p&&!p.closed&&p.close(),window.removeEventListener("message",d),clearInterval(g)};r.onmessage=async u=>{var m,f;if((m=u.data)!=null&&m.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((f=u.data)==null?void 0:f.jwt),await this.isLoggedIn(),this.broadcastEvents.send(dn),l=!0,s.port1.close(),o()}catch(h){console.error(h),n(h)}finally{l=!0,c()}};let p=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");p===null&&n(new Error("Popup blocked by browser"));let d=async u=>{var m;if(u.origin===a.origin)switch((m=u.data)==null?void 0:m.type){case"deepdesk-popup-loaded":{try{let f=JSON.stringify({type:"deepdesk-popup-create-channel"});p==null||p.postMessage(f,a.origin,[s.port2])}catch(f){w.error("Error posting message to popup",f),n(f)}break}case"deepdesk-popup-error":{c(),u.data.message==="Timeout"&&w.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(u.data.message));break}}};window.addEventListener("message",d);let g=setInterval(()=>{p&&!p.closed||(c(),l||n(new Error("Popup closed by user")))},200);this.unmountHandlers.push(c)})}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(w.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;w.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=Js(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(Ne()):this.store.dispatch(Le(n))})}catch(n){this.handleError(n)}}};async function Zu(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 Qu(t,e,o={}){let n=o.replace?At(t,o.replace.start,o.replace.end):Do(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
10
  `).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?At(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 $h(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 Gh(t){let e=document.createDocumentFragment();return t.split(`
11
11
  `).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 Ju(t,e){return!t.contains(e)||e===t?null:e.parentNode===t?e:Ju(t,e.parentNode)}async function Yu(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 c=n?$h(e):Gh(e);if(o){let p=l.startContainer===t?t.childNodes[l.startOffset]:l.startContainer,d=Ju(t,p)??t.firstChild;t.insertBefore(c,(d==null?void 0:d.nextSibling)??null)}else l.insertNode(c),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 eg(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function tg(t,e,o){await new gt(t).authenticateWithKey(e,o)}async function og(t){let o=await new De(t).get("/platform/config/",{version:null});return N(o)}async function Xh(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 ng(t,e){let o=await Xh(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,useStyles,waitForElementVisibilityChange});
package/dist/index.esm.js CHANGED
@@ -6,6 +6,6 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
6
6
  c6.8-6.8,15.4-10.2,24.7-10.2h11.9v-70c0-44.4,16.2-82.8,47.8-115.2S212.1,0,256.4,0s82.8,16.2,115.2,47.8
7
7
  c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});import{jsx as kc}from"react/jsx-runtime";var wh={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},Ic=({className:t,color:e})=>kc("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:kc("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:wh[e||"pink"]})});var Rc={root:"_root_1tvv4_1",text:"_text_1tvv4_18",isLoggedIn:"_isLoggedIn_1tvv4_25",isLoggedOut:"_isLoggedOut_1tvv4_29",icon:"_icon_1tvv4_39",logo:"_logo_1tvv4_44",lock:"_lock_1tvv4_49"};var Ar={};V(Ar,{enUS:()=>Th,nlNL:()=>Eh});var Th={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},Eh={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};import{useDispatch as Rh}from"react-redux";import{jsx as Lr,jsxs as Pc}from"react/jsx-runtime";var Ac=({onLogIn:t})=>{let e=T(Ar),o=C("floatingMenu"),n=C("productName"),s=Rh(),r=Ih(Z),i=y("FloatingMenu",Rc);if(r===null||o===!1)return null;let a=()=>{r===!0?s(G(!0)):t()};return Pc("button",{className:kh(i.root,{[i.isLoggedIn]:r,[i.isLoggedOut]:!r}),onClick:a,children:[Lr("div",{className:i.text,children:e(r?"search":"signin",{productName:n})}),Pc("div",{className:i.icon,children:[Lr(Ic,{className:i.logo,color:"pink"}),r===!1&&Lr(Ec,{className:i.lock})]})]})};import{useEffect as Wh,useRef as $h}from"react";import{connect as Gh,useDispatch as Xh,useSelector as Fn}from"react-redux";function Ot(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}import{Fragment as jh,useMemo as Vh}from"react";import{Interweave as Lh}from"interweave";import{useEffect as Mh,useMemo as Nh,useRef as Oh}from"react";import{useDispatch as Dh,useSelector as Hh}from"react-redux";import{useEffect as Ph}from"react";function Lc(t,e,o){Ph(()=>{let n=t.current;return n?(n.addEventListener(e,o),()=>{n.removeEventListener(e,o)}):()=>{}},[t,e,o])}var Mc={root:"_root_4u430_1",actions:"_actions_4u430_8",badge:"_badge_4u430_15",formattedText:"_formattedText_4u430_19"};import{jsx as Hn,jsxs as zh}from"react/jsx-runtime";var Bh=["search","personal-collection-search","search-autocomplete"];function Fh(t,e,o,n={}){let s="";return Bh.includes(e)?s=wa(Vs(t,o,{stripAgentPart:!0}),n.searchKeywords??[o]):s=Vs(t,o,n),n.placeholders===!0&&(s=Ta(s)),s}var Kh=()=>{},Uh=({index:t,selected:e,suggestion:o,onFeedback:n})=>{let s=C("inlineSuggestions"),r=Hh(St),i=Dh(),a=y("TextSuggestion",Mc),l=Oh(null);Mh(()=>{let p=setTimeout(()=>{i(Hi({text:o.text,suggestion:o}))},500);return()=>{clearTimeout(p)}},[o]),Lc(l,"click",()=>{i(Be(t)),i(le({suggestion:o,text:o.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let c=Nh(()=>Fh(o.text,o.source,r,{stripAgentPart:s,placeholders:!0,searchKeywords:o.searchKeywords}),[s,o.text,o.source,r,o.searchKeywords]);return o.source==="gpt"&&!s?null:zh("div",{className:a.root,onMouseEnter:()=>i(Be(t)),children:[Hn(M,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:Kh,children:Hn(Lh,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:c})}),e&&n&&Hn("div",{className:a.actions,children:Hn(Sn,{onFeedback:()=>n(o),suggestion:o.text})})]})},Nc=Uh;import{jsx as Oc}from"react/jsx-runtime";var qh=({onFeedback:t,suggestions:e,selectedIndex:o,reverse:n})=>{let s=Vh(()=>{let r=e.map((i,a)=>Oc(Nc,{index:a,selected:a===o,suggestion:i,onFeedback:t},`${i.text}-${i.source}`));return n?r.reverse():r},[e,o,n]);return Oc(jh,{children:s})},Bn=qh;var Dc={root:"_root_otdbu_1",paper:"_paper_otdbu_11"};import{jsx as Kn}from"react/jsx-runtime";var Zh=({textSuggestions:t,selectedIndex:e})=>{let o=$h(null),n=y("InlineSuggestionsOverlay",Dc),s=Fn(Ot),r=Xh(),i=Fn(Z),a=Fn(vt),l=Fn(Rn),c=C("showTextSuggestions");return bt(()=>{setTimeout(()=>{r(Ve({collapse:!0,skipWhenInputFocus:!0}))})}),Wh(()=>{let p=o.current;if(!p||!p.parentElement)return;p.parentElement.style.left="0px";let d=p.getBoundingClientRect();p.parentElement.style.left=`${Math.min(window.innerWidth-4-d.right,0)}px`}),l||!s||!c||t.length===0||i!==!0||a===!1?null:Kn("div",{className:n.root,"data-variant":"inline",children:Kn("div",{ref:o,className:n.paper,children:Kn(re,{children:Kn(Bn,{suggestions:t,selectedIndex:e})})})})},Qh=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),Hc=Gh(Qh)(Zh);import{Provider as Jh}from"react-redux";import{jsx as Un}from"react/jsx-runtime";var Yh=({children:t})=>{let o=C("locale").replace("-","");return Un(Hs.Provider,{value:o,children:t})},ey=({store:t,customStyles:e={},children:o})=>Un(Jh,{store:t,children:Un(Yh,{children:Un(qt.Provider,{value:e,children:o})})}),rt=ey;import Hr from"classnames";import{useEffect as uy,useRef as gy,useState as my}from"react";import{connect as fy,useDispatch as hy,useSelector as vo}from"react-redux";import{useState as ty}from"react";function Bc(t,e){let[o,n]=ty(()=>{if(typeof window>"u")return e;try{let r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return w.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){w.error(i)}}]}import sy from"classnames";import{Fragment as ry,useCallback as Nr,useMemo as Kc}from"react";var Mr={};V(Mr,{enUS:()=>oy,nlNL:()=>ny});var oy={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"}]}]},ny={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:"_root_1vfca_1",anchor:"_anchor_1vfca_6",anchorButton:"_anchorButton_1vfca_11"};import{jsx as zn,jsxs as Uc}from"react/jsx-runtime";var Or=(t,e,o)=>n=>zn("button",{className:t.anchorButton,type:"button",value:e,onClick:o,children:n},e),iy=({className:t,loginUrl:e,isEmbedded:o,onSnooze:n,onLogIn:s})=>{let r=T(Mr),i=ie(),a=y("Login",Fc),l=C("productName"),c=Nr(h=>{h.preventDefault(),n&&n(parseInt(h.target.value,10))},[]),p=Nr(h=>{h.preventDefault(),i.send(At,!0)},[e]),d=Kc(()=>h=>zn("a",{onClick:x=>{x.preventDefault(),s()},href:e,className:a.anchor,target:"_blank",rel:"noreferrer",children:h},"login"),[e]),g=Nr(h=>zn("button",{type:"button",className:a.anchorButton,onClick:p,children:h},"prompt"),[p]),{min:u,hour:m,day:f}=Kc(()=>({min:Or(a,60*10,c),hour:Or(a,60*60,c),day:Or(a,60*60*12,c)}),[]);return Uc("div",{className:sy(t,a.root),children:[r("loginPlease",{login:o?g:d,productName:l}),n&&Uc(ry,{children:[zn("br",{}),r("snooze",{min:u,hour:m,day:f})]})]})},jn=iy;import{useDispatch as ay}from"react-redux";var zc={root:"_root_1g8fi_1",text:"_text_1g8fi_19"};import{jsx as jc,jsxs as cy}from"react/jsx-runtime";var ly=({title:t})=>{let e=y("SearchTrigger",zc),o=ay();return cy("button",{type:"button",className:e.root,onClick:()=>o(G(!0)),children:[jc(kt,{}),jc("span",{className:e.text,children:t})]})},Vc=ly;var Dr={};V(Dr,{enUS:()=>py,nlNL:()=>dy});var py={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"}]},dy={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 qc={root:"_root_onpov_1",isInline:"_isInline_onpov_14",toggleButton:"_toggleButton_onpov_21",toggleButtonWrapper:"_toggleButtonWrapper_onpov_25",toggleButtonWrapperHidden:"_toggleButtonWrapperHidden_onpov_32",isCollapsed:"_isCollapsed_onpov_36",collapsible:"_collapsible_onpov_36",hints:"_hints_onpov_44",hintsHidden:"_hintsHidden_onpov_51",triggers:"_triggers_onpov_56",triggersRight:"_triggersRight_onpov_71"};import{jsx as q,jsxs as So}from"react/jsx-runtime";var yy=({textSuggestions:t,selectedIndex:e,onLogIn:o})=>{let n=y("SuggestionsOverlay",qc),s=T(Dr),r=vo(Ot),i=Li(),a=hy(),l=gy(null),c=C("searchTriggerKey"),p=C("productName"),d=vo(Rn),g=vo(Z),u=vo(vt),[m,f]=my(null),h=C("showSearch"),E=C("showTextSuggestions"),x=C("adminUrl"),_=C("isEmbedded"),[b,v]=Bc("dd-snooze-until-ms",0),R=d||b>Date.now(),N=vo(k=>k.input.text),B=t.filter(k=>k.source!=="gpt").length,D=()=>{R&&v(0),a(Tl(!R))},U=k=>{a(W({name:"suggestion feedback",data:{text:k.text,source:"overlay",context:N},options:{includeConversationData:!0}}))},F=k=>{let ne=Date.now()+k*1e3;v(ne),w.info(`Snooze until: ${new Date(ne)}`),a(Ve({collapse:!0}))};return uy(()=>{B===0&&f(null)},[t,B]),bt(()=>{a(Ve({collapse:!0,skipWhenInputFocus:!0}))}),g===null||u===!1?null:g===!1?So("div",{ref:l,className:Hr(n.root,{[n.isCollapsed]:R}),children:[!R&&So("div",{className:n.triggers,children:[q("div",{style:{flex:1}}),q("div",{className:n.triggersRight,children:q(ft,{className:n.toggleButton,title:s("collapse"),onClick:D,isCollapsed:!1})})]}),q("div",{className:n.toggleButtonWrapper,children:q(ft,{className:n.toggleButton,title:s("open",{productName:p}),onClick:D,isCollapsed:!0})}),q("div",{className:n.collapsible,children:q(jn,{loginUrl:x,isEmbedded:_,onLogIn:o,onSnooze:F})})]}):!i||!r?null:So("div",{ref:l,className:Hr(n.root,{[n.isCollapsed]:R}),children:[!R&&So("div",{className:n.triggers,children:[q("div",{style:{flex:1},children:h&&q("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>f(s(wn()?"searchHintMac":"searchHintWindows",{searchTriggerKey:c.toUpperCase()})),onMouseLeave:()=>f(null),children:q(Vc,{title:s("search")})})}),So("div",{className:n.triggersRight,onFocus:()=>{},children:[q("div",{className:Hr(!m&&n.hintsHidden,n.hints),children:m}),q(ft,{className:n.toggleButton,title:s("collapse"),onClick:D,isCollapsed:!1})]})]}),q("div",{className:n.toggleButtonWrapper,children:q(ft,{className:n.toggleButton,title:s("open",{productName:p}),onClick:D,isCollapsed:!0})}),B>0&&E&&q("div",{className:n.collapsible,onFocus:()=>{},children:q(re,{children:q(Bn,{onFeedback:U,suggestions:t,selectedIndex:e,reverse:!0})})})]})},vy=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),Wc=fy(vy)(yy);import Gr from"classnames";import{Interweave as rv}from"interweave";import{useCallback as iv,useEffect as av,useMemo as up,useRef as lv}from"react";import{connect as cv}from"react-redux";import{cloneElement as Sy}from"react";var _y=["div","span","mark","strong","b","i","u","em"];function Br(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(_y.includes(s)){let i=Array.isArray(n.props.children)?n.props.children:[n.props.children];return[...t.slice(0,t.length-1),Sy(n,{children:Br(i,e,o+1)})]}return[...t,...e]}function We(t){return t.tagName.toLowerCase()==="textarea"}var $c={root:"_root_81non_1",container:"_container_81non_3",agentText:"_agentText_81non_5",tabText:"_tabText_81non_6",hint:"_hint_81non_6",matchSelection:"_matchSelection_81non_10",focus:"_focus_81non_16",resetIndent:"_resetIndent_81non_20",matchKeyword:"_matchKeyword_81non_24",matchPlaceholder:"_matchPlaceholder_81non_25",hover:"_hover_81non_31",hintText:"_hintText_81non_64",popover:"_popover_81non_72",popoverRoot:"_popoverRoot_81non_77",popoverContentContainer:"_popoverContentContainer_81non_81",popoverContent:"_popoverContent_81non_81",selectionOptions:"_selectionOptions_81non_107",selectionOptionsIsHidden:"_selectionOptionsIsHidden_81non_112",selectionOptionsButton:"_selectionOptionsButton_81non_116",caret:"_caret_81non_132",popoverSuggestionsRoot:"_popoverSuggestionsRoot_81non_136",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_81non_141"};import Hy from"classnames";import{Matcher as By}from"interweave";import{useEffect as Fy,useMemo as Ky}from"react";function Gc(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Vn(t){return e=>{t.forEach(o=>{typeof o=="function"?o(e):o!=null&&(o.current=e)})}}function Xc(t){return t!=null}import ep from"classnames";import{createRef as Py,useCallback as Kr,useMemo as Ay,useRef as Ly,useState as My}from"react";import{useState as xy,useLayoutEffect as by}from"react";var Cy=["bottom","height","left","right","top","width"],wy=(t={},e={})=>Cy.some(o=>t[o]!==e[o]),Ae=new Map,Zc,Qc=()=>{let t=[],e=[];Ae.forEach((o,n)=>{if(n instanceof Element&&!n.isConnected){e.push(n);return}let s=n.getBoundingClientRect();wy(s,o.rect)&&(o.rect=s,t.push(o))}),e.forEach(o=>{Ae.delete(o)}),t.forEach(o=>{o.callbacks.forEach(n=>n(o.rect))}),Zc=window.requestAnimationFrame(Qc)};function Ty(t,e){return{observe(){let o=Ae.size===0;if(Ae.has(t)){let n=Ae.get(t);n.callbacks.push(e),n.rect&&e(n.rect)}else Ae.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});o&&Qc()},unobserve(){let o=Ae.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||Ae.delete(t),Ae.size||cancelAnimationFrame(Zc)}}}}function Fr(t){let[e,o]=xy(null);return by(()=>{if(!t.current)return;let n=Ty(t.current,s=>{o(s)});return n.observe(),()=>{n.unobserve()}},[t]),e}import{useContext as Ey,useLayoutEffect as ky,useState as Iy}from"react";import{createPortal as Ry}from"react-dom";var Jc={root:"_root_1jq08_1"};var Yc=({children:t})=>{let[e,o]=Iy(null),n=Ey(qt);return ky(()=>{let s=document.createElement("div");return Ye(s),s.classList.add(Jc.root),n!=null&&n.portalRootNode&&s.classList.add(n==null?void 0:n.portalRootNode),document.body.appendChild(s),o(s),()=>{s.isConnected&&document.body.removeChild(s)}},[]),e?Ry(t,e):null};var ye={ref:"_ref_1rcyi_1",root:"_root_1rcyi_7",positionAbove:"_positionAbove_1rcyi_13",positionBelow:"_positionBelow_1rcyi_17",positionLeft:"_positionLeft_1rcyi_21",positionRight:"_positionRight_1rcyi_25",alignStart:"_alignStart_1rcyi_29",alignCenter:"_alignCenter_1rcyi_34",alignEnd:"_alignEnd_1rcyi_40"};import{jsx as Ur}from"react/jsx-runtime";var qn=(t=!1)=>{let[e,o]=My(t),n=Kr(()=>o(!0),[]),s=Kr(()=>o(!1),[]),r=Kr(()=>o(a=>!a),[]),i=Ly(null);return{opened:e,open:n,close:s,toggle:r,triggerRef:i}};function zr(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 Wn=({className:t,triggerRef:e,boundaryRef:o=Py(),position:n="above",align:s="center",children:r,toStyle:i=zr,...a})=>{let l=Fr(e),c=Fr(o),p=Ay(()=>i(l,c,0),[l,c]);return Ur(Yc,{children:Ur("div",{className:ep(ye.ref,{[ye.positionAbove]:n==="above",[ye.positionBelow]:n==="below",[ye.positionLeft]:n==="left",[ye.positionRight]:n==="right",[ye.alignStart]:s==="start",[ye.alignCenter]:s==="center",[ye.alignEnd]:s==="end"}),style:p,...a,role:"dialog",children:Ur("div",{className:ep(t,ye.root),children:r})})})};import Ny from"classnames";import{forwardRef as Oy,useRef as Dy}from"react";import{jsx as tp}from"react/jsx-runtime";var $n=Oy(({className:t,children:e,...o},n)=>{let s=Dy(null),r=y("TabCompletion",be);return tp("div",{ref:Vn([s,n]),className:Ny(t,r.popoverContentContainer),...o,children:tp("div",{className:r.popoverContent,children:e})})});import{jsx as _o,jsxs as jy}from"react/jsx-runtime";var Uy=t=>e=>{let o=zr(e);return"top"in o&&(o.width=t.width-(e.left-t.left)-10),o},zy=({inputElement:t,boundaryRef:e,inputStyle:o,children:n,suggestion:s})=>{let r=y("TabCompletion",be),i=qn(),a=Ky(()=>Uy(t.getBoundingClientRect()),[t]),[l,c]=un(t);return Fy(()=>{c?i.open():i.close()},[c]),jy("span",{children:[_o("mark",{ref:Vn([l,i.triggerRef]),className:Hy(r.matchKeyword,{[r.hover]:c}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:n}),i.opened&&_o(Wn,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:_o($n,{style:o,children:_o("div",{className:r.hintText,children:s})})})]})},Gn=class extends By{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${Gc(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(Xc);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 _o(zy,{inputElement:o.inputElement,suggestion:o.suggestion,inputStyle:o.inputStyle,boundaryRef:o.boundaryRef,children:e},`keyword_${o.matchString}_${o.key}`)}asTag(){return"mark"}};import $r from"classnames";import{Matcher as Jy}from"interweave";import{createRef as Yy,forwardRef as ev,useCallback as tv,useEffect as cp,useRef as pp,useState as dp}from"react";import{useDispatch as ov}from"react-redux";import{jsx as op}from"react/jsx-runtime";var np=()=>op("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:op("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"})});import{useCallback as Vy,useEffect as rp,useState as ip}from"react";import{useDispatch as qy,useSelector as ap}from"react-redux";import Wy from"lodash.debounce";var sp={root:"_root_1muu8_1",content:"_content_1muu8_7"};function Xn(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 jr(t){return t.replace("https://www.","").replace("https://","")}import{jsx as it,jsxs as Vr}from"react/jsx-runtime";var $y=3,Gy=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),Xy=({onSelectLink:t,onDismiss:e,placeholder:o,visitUrlText:n,linkCount:s=$y})=>{let r=y("LinkSearch",sp),[i,a]=ip(""),l=qy(),c=ap(kn("url")),p=ap(Qa("URL",Gy)),[d,g]=ip(p.length-1),u=C("fallbackImage"),m=x=>{let _=x.target;a(_.value)},f=(x,_)=>{x.stopPropagation(),x.preventDefault(),window.open(_,"_blank")},h=x=>{var v;let _=d-1<0?p.length-1:d-1,b=d+1===p.length?0:d+1;x.code==="Escape"&&(a(""),e()),x.code==="ArrowUp"&&g(_),x.code==="ArrowDown"&&g(b),x.code==="Enter"&&t(((v=p[d])==null?void 0:v.text)||i)},E=Vy(Wy(x=>{l(tt({query:x,type:"URL",tags:["link-search"]}))},300),[]);return rp(()=>{i&&E(i)},[i]),rp(()=>()=>{l(bn())},[]),Vr("div",{className:r.root,children:[it(re,{withDivider:!0,children:(i?p:c).slice(0,s).map((x,_)=>it(M,{selected:d===_,onClick:()=>t(x.text),"data-testid":"linksearch-suggestion",children:Vr(O,{children:[it(O.Image,{src:Xn(x,"small",u||void 0),title:x.title||x.text}),Vr(O.Content,{className:r.content,cropText:!0,children:[it(O.Title,{children:x.title||jr(x.text)}),x.title&&jr(x.text)]}),it(M.Actions,{children:it(M.ActionButton,{label:n,onClick:b=>f(b,x.text)})})]})},x.text))}),it(po,{value:i,onChange:m,autoFocus:!0,placeholder:o,onKeyUp:h})]})},lp=Xy;var qr={};V(qr,{enUS:()=>Zy,nlNL:()=>Qy});var Zy={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},Qy={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};import{jsx as ve,jsxs as Wr}from"react/jsx-runtime";var nv=ev((t,e)=>{let o=y("TabCompletion",be);return ve("mark",{ref:e,className:$r(o.matchSelection)},"selection-start")}),sv=({startRef:t,boundaryRef:e,inputStyle:o,inputElement:n,children:s})=>{let r=T(qr),i=y("TabCompletion",be),a=pp(null),l=pp(null),[c,p]=dp(null),d=ov(),g=qn(document.activeElement===n),[u]=dp(()=>document.createRange());g.triggerRef.current=u,cp(()=>()=>u.detach(),[]),cp(()=>{let f=t.current,h=a.current;!f||!h||(u.setStart(f,0),u.setEnd(h,0))},[t.current,a.current]),bt(()=>{g.close()});let m=tv(f=>{let h=u.toString(),E=/^http(s?):\/\//.test(f)?f:`https://${f}`;d(Wo({text:`[${h}](${E})`,replace:"selection"}))},[]);return Wr("span",{children:[ve("mark",{ref:a,className:$r(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":g.opened?"true":"false",children:s}),g.opened&&ve(Wn,{className:i.popoverRoot,triggerRef:g.triggerRef,boundaryRef:e,position:"above",align:"start",children:Wr($n,{style:o,ref:l,children:[ve("div",{className:$r(i.selectionOptions,{[i.selectionOptionsIsHidden]:c!==null}),children:Wr("button",{type:"button",tabIndex:c===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>p("insertLink"),children:[ve(np,{}),ve("span",{children:"\xA0"}),ve("span",{children:r("insertLink")})]})}),c==="insertLink"&&ve(lp,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:m,onDismiss:()=>{p(null),g.close()}})]})})]},"selection-end")},Zn=class extends Jy{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(e,o){return this.props=o,this.charCount=0,this.startRef=Yy(),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?ve(nv,{ref:this.startRef}):ve(sv,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};import{useSelector as pv}from"react-redux";import{jsx as Dt,jsxs as gv}from"react/jsx-runtime";var dv=({enabled:t,content:e,tabText:o,showTabHint:n,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:l})=>{let c=y("TabCompletion",$c),p=C("insertLink"),d=C("showMidSentenceSuggestions"),g=C("inlineSuggestions"),u=mn(a),m=lv(null),f=pv(Z);av(()=>{We(a)&&u&&fn(a,u)},[u]);let h=iv(_=>{if(!s||!o)return _;let b=[Dt("span",{className:c.resetIndent,children:"\u200B"},"u200B"),Dt("span",{"data-testid":"tab-completion",className:Gr(c.tabText,c.resetIndent),"data-source":l,children:o},"tabText")];return n&&b.push(Dt("span",{className:Gr(c.hint,c.resetIndent),children:Dt(hs,{keyCode:"tab"},"tabHint")})),Br(_,b)},[s,o,n]),E=up(()=>{let _=[];return p&&_.push(new Zn("selection")),_.push(new xt("placeholders")),r&&_.push(new Gn("keywords")),_},[g,p,r]),x=up(()=>{let _=window.getComputedStyle(a);return{"--dd-color":_.color,"--dd-font-size":_.fontSize,"--dd-font-family":_.fontFamily,"--dd-font-variant":_.fontVariant}},[]);return!t||!f?null:gv("div",{ref:_=>{_!=null&&_.parentElement&&(m.current=_==null?void 0:_.parentElement)},className:c.root,style:x,children:[Dt(rv,{tagName:"span",containerTagName:"div",className:Gr(c.container,c.agentText),disableLineBreaks:We(a),content:e||"\u200B",onAfterParse:h,matchers:E,selection:u,keywordMatches:i,inputElement:a,inputStyle:x,boundaryRef:m,inlineSuggestionsOnlyAtEnd:!d}),Dt("br",{})]})},uv=({input:t,ui:e,settings:o,styleSuggestions:n,conversation:s})=>{var f;let{tabCompletionSuggestion:r}=t,i=(r==null?void 0:r.text)||"",a=(r==null?void 0:r.source)||"",l=t.html??eo(t.text),c=i.indexOf(t.text)===0?i.slice(t.text.length):"",{showTabHint:p}=e,{isSupported:d}=s,{showTabCompletion:g,visible:u,showStyleSuggestions:m}=o;return{showTabHint:p,showStyleSuggestions:m,showTabCompletion:g,content:l,tabText:c,source:a,keywordMatches:((f=n.list)==null?void 0:f.keywordMatches)??[],enabled:u&&d!==!1}},gp=cv(uv)(dv);import tS from"classnames";import{useEffect as oS}from"react";import{useDispatch as nS,useSelector as Q}from"react-redux";import{createAsyncThunk as xo,createSlice as mv}from"@reduxjs/toolkit";var mp={list:[],fetchState:"idle",isInitialRequest:null},hp=t=>t.autoflows.list||[],fp=t=>e=>{var o;return(o=e.list)==null?void 0:o.find(n=>n.triggerPayload===t)},Le=xo("autoflows/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getAutoflows(t)}),Xr=xo("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(Le(t.platformSessionId))}),Zr=xo("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(Le(t.platformSessionId))}),fv=mv({name:"autoflows",initialState:mp,reducers:{},extraReducers:t=>{t.addCase(Xr.pending,(e,o)=>{let n=fp(o.meta.arg.triggerPayload)(e);n.state="Started",n.isBusy=!0}),t.addCase(Zr.pending,(e,o)=>{let n=fp(o.meta.arg.triggerPayload)(e);n.state="Aborted",n.isBusy=!0}),t.addCase(Le.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}),t.addCase(Le.rejected,e=>{e.fetchState="error"}),t.addCase(Le.fulfilled,(e,o)=>{e.list=o.payload,e.fetchState="done"}),t.addCase(P,()=>mp)}}),yp=xo("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(Le(t))}),s.on("sessionCompleted",()=>{o(Le(t))})}),vp=xo("autoflows/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),Sp=fv.reducer;import{createAsyncThunk as Co,createSlice as hv}from"@reduxjs/toolkit";var _p={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},xp=t=>t.customMessages.list,bp=t=>e=>!!e.customMessages.sentSuggestions.find(o=>o===t),Cp=t=>e=>!!e.customMessages.answeredSuggestions.find(o=>o===t),wp=t=>e=>!!e.customMessages.errorSuggestions.find(o=>o===t),bo=Co("customMessages/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getCustomMessages(t)}),Qn=Co("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)}),Jn=Co("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)}),Tp=hv({name:"customMessages",initialState:_p,reducers:{onCustomMessage(t,e){Array.isArray(e.payload)?t.list=e.payload:t.list=[e.payload]}},extraReducers:t=>{t.addCase(bo.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(bo.rejected,e=>{e.fetchState="error"}).addCase(bo.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload||[]}).addCase(Qn.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.errorSuggestions=e.errorSuggestions.filter(n=>o.meta.arg.suggestion.text!==n)}).addCase(Qn.rejected,(e,o)=>{let n=e.sentSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1))}).addCase(Jn.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.answeredSuggestions.push(o.meta.arg.suggestion.text)}).addCase(Jn.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(P,()=>_p)}}),Ep=Co("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(Tp.actions.onCustomMessage(r))})}),kp=Co("customMessages/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),Ip=Tp.reducer;import{createAsyncThunk as Rp,createSlice as yv}from"@reduxjs/toolkit";var vv={token:null,accountUrl:null,interval:null},Pp=t=>e=>{let{passwordlessToken:{token:o,accountUrl:n}}=e;return o&&n?`${n}/apis/admin/session/passwordless/login/?token=${o}&redirect=${t}`:null},Qr=Rp("passwordlessToken/getTemporaryPasswordlessToken",async(t,e)=>{let{deepdeskAPI:o}=e.extra,n=await o.requestPasswordlessToken();return{accountUrl:o.client.baseUrl,token:n}}),Jr=Rp("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:o=1e3*60*10}=t,{dispatch:n}=e;return n(Qr()),setInterval(()=>n(Qr()),o)}),Ap=yv({name:"passwordlessToken",initialState:vv,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(Qr.fulfilled,(e,o)=>{e.token=o.payload.token,e.accountUrl=o.payload.accountUrl}),t.addCase(Jr.fulfilled,(e,o)=>{e.interval=o.payload})}}),{stopPollPasswordlessToken:Lp}=Ap.actions,Mp=Ap.reducer;function Np(t){let{customMessages:e,autoflows:o}=t;return o.fetchState==="loading"&&o.isInitialRequest===!0||e.fetchState==="loading"&&e.isInitialRequest===!0}import{Fragment as Iv}from"react";import{connect as Rv}from"react-redux";import Tv from"classnames";import{Fragment as Ev}from"react";import Sv from"classnames";var Op={root:"_root_838fd_1"};import{jsx as xv}from"react/jsx-runtime";var _v=({className:t,children:e})=>{let o=y("Unicode",Op);return xv("span",{className:Sv(t,o.root),children:e})},Dp=_v;var Hp={isDisabled:"_isDisabled_1rmfm_1",buttonStart:"_buttonStart_1rmfm_5",root:"_root_1rmfm_8",buttonStop:"_buttonStop_1rmfm_8",stateBadge:"_stateBadge_1rmfm_19",isCompleted:"_isCompleted_1rmfm_26",isStarted:"_isStarted_1rmfm_30",isAborted:"_isAborted_1rmfm_34"};var Yr={};V(Yr,{enUS:()=>bv,nlNL:()=>Cv});var bv={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"}]},Cv={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"}]};import{jsx as at,jsxs as Yn}from"react/jsx-runtime";var kv=({disabled:t,state:e,displayName:o,description:n,onStartAutoflow:s,onStopAutoflow:r})=>{let i=y("Autoflow",Hp),a=T(Yr),l=e==="Started"?"stop":"start",c=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return Yn(M,{className:Tv(i.root,{[i.isDisabled]:t,[i.isCompleted]:e==="Completed",[i.isAborted]:e==="Aborted",[i.isStarted]:e==="Started"}),children:[at(O,{children:Yn(O.Content,{children:[Yn(O.Title,{children:[e&&at("span",{className:i.stateBadge,children:a(e)}),o]}),at("span",{children:n})]})}),at(M.Actions,{fixed:e==="Started",children:at(M.ActionButton,{primary:!0,className:l==="start"?i.buttonStart:i.buttonStop,onClick:e==="Started"?r:s,disabled:t,label:Yn(Ev,{children:[at(Dp,{children:c})," ",at("span",{children:a(l)})]})})})]})},Bp=kv;import{jsx as Fp}from"react/jsx-runtime";var Pv=(t,e)=>{let o=e.filter(n=>n.state==="Started");return o.length>0?o.indexOf(t)===-1:!1},Av=({autoflows:t,onStartAutoflow:e,onStopAutoflow:o,platformSessionId:n})=>Fp(Iv,{children:t.map(s=>Fp(Bp,{displayName:s.displayName,description:s.description,disabled:s.isBusy||Pv(s,t),state:s.state,onStartAutoflow:()=>e({platformSessionId:n,triggerPayload:s.triggerPayload}),onStopAutoflow:()=>o({platformSessionId:n,triggerPayload:s.triggerPayload})},s.displayName))}),Lv=({autoflows:t,conversation:e})=>{var o;return{autoflows:t.list,platformSessionId:(o=e.current)==null?void 0:o.sessionId}},Mv={onStartAutoflow:Xr,onStopAutoflow:Zr},Kp=Rv(Lv,Mv)(Av);import Nv from"classnames";import{useCallback as Up}from"react";import{useDispatch as Ov,useSelector as es}from"react-redux";var Me={root:"_root_1e6ej_1",title:"_title_1e6ej_8",isUsed:"_isUsed_1e6ej_13",quickReplies:"_quickReplies_1e6ej_22",quickReply:"_quickReply_1e6ej_29",hasError:"_hasError_1e6ej_39",label:"_label_1e6ej_43",errorIcon:"_errorIcon_1e6ej_48"};import{jsx as $e,jsxs as ts}from"react/jsx-runtime";var Dv=({suggestion:t})=>{let e=T(et),o=Ov(),n=es(bp(t.text)),s=es(Cp(t.text)),r=es(wp(t.text)),i=es(Bo),{replyOptions:a}=t,l=Up(p=>{p.preventDefault(),p.stopPropagation(),!(n||!i)&&o(Qn({platformSessionId:i,suggestion:t}))},[t,n,o,i]),c=Up(p=>{if(p.preventDefault(),p.stopPropagation(),!i||!a)return;let d=parseInt(p.target.dataset.index,10),g=a[d];o(Jn({platformSessionId:i,reply:g,suggestion:t}))},[t,n,o,i]);return ts(M,{onClick:l,className:Nv(Me.root,{[Me.isUsed]:n,[Me.hasError]:r}),children:[$e(O,{children:ts(O.Content,{children:[ts(O.Title,{className:Me.title,children:[t.text," ",$e(ys,{className:Me.label,children:"analyse tool"})," ",r&&$e("span",{className:Me.errorIcon,role:"img","aria-label":e("sendingError"),title:e("sendingError"),children:"!"})]}),a&&a.length>0&&$e("ul",{className:Me.quickReplies,children:a.map(p=>$e("li",{className:Me.quickReply,children:p.title},p.title))})]})}),ts(M.Actions,{fixed:r||n,children:[a&&a.length>0&&$e(M.DropdownButton,{label:e("answer"),disabled:s,children:a.map((p,d)=>$e(M.DropdownItem,{index:d,label:p.title,onClick:c},p.title))}),$e(M.ActionButton,{primary:!0,disabled:n,onClick:l,label:e(n?"suggestionSent":r?"tryAgain":"sendSuggestion")})]})]})},zp=Dv;import{useEffect as Hv,useState as Bv}from"react";import{useDispatch as Fv}from"react-redux";import qp from"classnames";import{jsx as jp}from"react/jsx-runtime";var ei=()=>jp("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:jp("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 Vp={root:"_root_rjdyr_1",entity:"_entity_rjdyr_10",entityText:"_entityText_rjdyr_46",iconWrapper:"_iconWrapper_rjdyr_53",icon:"_icon_rjdyr_53",iconClicked:"_iconClicked_rjdyr_67"};import{jsx as Ht,jsxs as Wp}from"react/jsx-runtime";var Kv=({entities:t})=>{let e=y("EntitiesWidgetList",Vp),[o,n]=Bv(void 0),s=Fv(),r=()=>{n(void 0)},i=a=>{t&&(n(t.indexOf(a)),go(a.text),s(W({name:"entity copied",data:{entity:a,type:"copy"}})))};return Hv(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[o]),!t||t.length===0?null:Ht("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,l)=>Wp("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[Ht("span",{className:e.entityText,children:a.text}),Wp("span",{className:e.iconWrapper,children:[Ht("span",{className:qp(e.icon),children:Ht(ei,{})}),Ht("span",{className:qp(e.icon,o===l&&e.iconClicked),children:Ht(ei,{})})]})]},a.text))})},$p=Kv;import{jsx as Gp}from"react/jsx-runtime";var Xp=()=>Gp("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:Gp("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});import{jsx as Zp}from"react/jsx-runtime";var Qp=()=>Zp("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:Zp("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"})});import{jsx as Jp}from"react/jsx-runtime";var Yp=()=>Jp("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:Jp("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"})});import{useEffect as jv,useState as Vv}from"react";var ti={};V(ti,{enUS:()=>Uv,nlNL:()=>zv});var Uv={copyCue:[{type:0,value:"Copy"}],copiedCue:[{type:0,value:"Copied!"}],removeCue:[{type:0,value:"Close"}]},zv={copyCue:[{type:0,value:"Kopieer"}],copiedCue:[{type:0,value:"Gekopieerd!"}],removeCue:[{type:0,value:"Sluiten"}]};import{jsx as wo,jsxs as ed}from"react/jsx-runtime";var qv=({cue:t,onRemove:e,onCopy:o})=>{let n=T(ti),[s,r]=Vv(!1),i=l=>{l.preventDefault(),l.stopPropagation(),o&&(o(t.text),r(!0))},a=l=>{l.preventDefault(),l.stopPropagation(),e&&e(t.id)};return jv(()=>{if(!s)return;let l=setTimeout(()=>{r(!1)},1e3);return()=>{clearTimeout(l)}},[s]),wo(M,{"data-testid":"cue",children:ed(O,{children:[ed(O.Content,{children:[t.title&&wo(O.Title,{"data-testid":"widget-cue-title",children:t.title}),t.text]}),wo(M.Actions,{children:o&&wo(M.ActionButton,{primary:!0,onClick:i,label:n(s?"copiedCue":"copyCue")})}),wo(O.CloseIcon,{title:n("removeCue"),onClick:a})]})})},td=qv;import{Fragment as $v,jsx as od}from"react/jsx-runtime";var Wv=({cues:t,onCopyCue:e,onRemoveCue:o})=>od($v,{children:t.map(n=>od(td,{cue:n,onRemove:o,onCopy:e},`${n.id}_${n.timestamp}`))}),nd=Wv;import{useSelector as Zv}from"react-redux";import{useCallback as Gv}from"react";import{jsx as lt,jsxs as os}from"react/jsx-runtime";var Xv=({suggestion:t,lines:e,onEdit:o,onUse:n})=>{var g;let s=t.text||t.url||t.message,r=Cn(s),i=T(et),a=C("showImages"),l=C("fallbackImage"),c=u=>{u.preventDefault(),u.stopPropagation(),n(s)},p=u=>{u.preventDefault(),u.stopPropagation(),o(t)},d=Gv(u=>{window.open(r,"_blank"),u.stopPropagation(),u.preventDefault()},[r]);return os(M,{onClick:c,"data-testid":"edit-suggestion",children:[os(O,{children:[a&&t.image&&lt(O.Image,{src:Xn(t,"small",l||void 0),title:t.title}),os(O.Content,{children:[t.title&&lt(O.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((g=t.searchKeywords)==null?void 0:g.length)>0&&lt(M.Labels,{labels:t.searchKeywords}),lt(O.Content,{cropText:e==="single",lineClamp:e==="multiple",children:s})]})]}),os(M.Actions,{children:[r&&lt(M.ActionButton,{onClick:d,label:i("visitUrl")}),lt(M.ActionButton,{primary:!0,onClick:p,label:i("preview")}),lt(M.ActionButton,{primary:!0,onClick:c,label:i("useSuggestion")})]})]})},sd=Xv;import{Fragment as Jv,jsx as rd}from"react/jsx-runtime";var Qv=({contentType:t,lines:e,suggestions:o})=>{let n=ie(),s=Zv(je),r=a=>{n.send(mr,{state:s,suggestion:a,contentType:t})},i=(a,l)=>{n.send(Ie,{text:a,suggestion:{...l,source:l.source,sourceText:l.text}})};return rd(Jv,{children:o.map(a=>rd(sd,{suggestion:a,lines:e,onEdit:l=>r(l),onUse:l=>i(l,a)},a.text||a.url||a.message))})},id=Qv;var oi={};V(oi,{enUS:()=>Yv,nlNL:()=>eS});var Yv={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"}]},eS={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 ad={root:"_root_x0pwe_1",loginText:"_loginText_x0pwe_7",stateText:"_stateText_x0pwe_8",sectionList:"_sectionList_x0pwe_20",shortcutList:"_shortcutList_x0pwe_24",shortcut:"_shortcut_x0pwe_24",link:"_link_x0pwe_52"};import{jsx as L,jsxs as Bt}from"react/jsx-runtime";var ns=(t,e)=>{let o=Q(Z);oS(()=>o?e.every(n=>!!n)?t():()=>{}:()=>{},[...e,o])},sS=({onLogIn:t})=>{let e=T(oi),o=nS(),n=C("isEmbedded"),s=y("Widget",ad),r=C("showAutoflows"),i=C("showCustomMessages"),a=C("showSummaryCommand"),l=C("showKnowledgeSearch"),c=C("showSearch"),p=Q(qe),d=Q(Nn),g=Q(hp),u=Q(Dl),m=Q(An),f=Q(xp),h=Q(Fo),E=Q(vt),x=Q(Z),_=Q(Bo),b=Q(Np),v=Q(je),R=ie(),N=Q(ul),B=Q(Pp("/admin/")),D=C("adminUrl"),U=C("productName");if(ns(()=>(o(bo(_)),o(Ep(_)),()=>{o(kp(_))}),[o,E,i,_]),ns(()=>(o(Le(_)),o(yp(_)),()=>{o(vp(_))}),[o,E,r,_]),ns(()=>{d.forEach(({type:k})=>{o(k==="entities"?ue():de(k))})},[o,E,h,p]),ns(()=>(o(Jr()),()=>{o(Lp())}),[o]),E===!1)return L("div",{className:s.stateText,children:L("div",{children:L("p",{children:e("notSupported")})})},"supported");if(x===!1)return L("div",{className:s.loginText,children:L("div",{children:L(jn,{isEmbedded:n,loginUrl:D,onLogIn:t})})},"login");if(!p||!_||x===null||N||b)return L("div",{className:s.stateText,children:L("div",{children:L("p",{children:e("waiting")})})},"waiting");let F=c||a||l||B;return L("div",{className:tS(s.root),"data-testid":"widget",children:Bt(Ss,{className:s.sectionList,children:[F&&L(Oe,{title:e("actions"),type:"shortcuts",children:Bt("div",{className:s.shortcutList,children:[c&&Bt("button",{className:s.shortcut,"data-testid":"shortcut-search",onClick:()=>R.send("ShowCommandPalette",{isOpen:!0}),children:[L(kt,{}),e("linkSearch")]}),a&&Bt("button",{className:s.shortcut,"data-testid":"shortcut-summary",onClick:()=>R.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[L(Yp,{}),e("linkSummary")]}),l&&Bt("button",{className:s.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>R.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[L(Qp,{}),e("linkKnowledgeSearch")]}),B&&Bt("a",{className:s.shortcut,target:"_blank",href:B,"data-testid":"shortcut-studio-login",rel:"noreferrer",children:[L(Xp,{}),e("linkStudioLogin",{productName:U})]})]})}),i&&f.length>0&&L(Oe,{type:"custom-messages","data-testid":"custom-messages",children:L(re,{withDivider:!0,children:f.map(k=>L(zp,{suggestion:k},k.text))})}),r&&g.length>0&&L(Oe,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:L(re,{withDivider:!0,children:L(Kp,{})})}),d.map(({type:k,title:ne,amount:gs,lines:jt})=>{var Vt;switch(k){case"entities":return m&&m.length>0&&L(Oe,{type:k,title:ne,"data-testid":`type-${k}`,children:L($p,{entities:m})},k);case"cues":return u&&u.length>0&&L(Oe,{type:k,title:ne,"data-testid":`type-${k}`,children:L(re,{withDivider:!0,children:L(nd,{cues:u,onRemoveCue:dt=>o(Bl({id:dt}))})})},k);default:return((Vt=v[k])==null?void 0:Vt.fetchState)==="done"&&v[k].suggestions.length>0&&L(Oe,{type:k,title:ne,"data-testid":`type-${k}`,children:L(re,{withDivider:!0,children:L(id,{lines:jt,contentType:k,suggestions:v[k].suggestions.slice(0,gs)||[]})})},k)}})]})})},ld=sS;function Eo(t){let e=new Range;return e.selectNodeContents(t),e}function cd(t,e,o){try{return ct(t,e,o),!0}catch{return!1}}function ss(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function rs(t){return"tagName"in t&&t.tagName==="BR"}var To=/[\u200B-\u200D\uFEFF]/g;function ct(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,c){let p=-1,d=/[\u200B-\u200D\uFEFF]/;if(!d.test(l))return c;for(let g=0;g<=l.length;g++)if(d.test(l[g])||p++,p===c)return g;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let c=l.textContent,p=c.replace(To,""),d=s+p.length,g=e>=s&&e<=d,u=o>=s&&o<=d;if(g){let m=i(c,e-s);m===0&&!u?n.setStartBefore(l):n.setStart(l,m)}u&&(n.setEnd(l,i(c,o-s)),r=!0),s=d;break}case Node.ELEMENT_NODE:{if(rs(l)&&(s===e&&n.setStartBefore(l),s++,s===o)){n.setEndAfter(l),r=!0;return}for(let p=0;p<l.childNodes.length&&(a(l.childNodes[p]),!r);p++);let c=l.lastChild;ss(l)&&c&&!ss(c)&&!rs(c)&&s++;break}default:break}}if(a(t),n.startContainer===document)throw new Error("Offsets out of bound");return n}function is(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,c=0;function p(d){let g=d===o,u=d===s;switch(d.nodeType){case Node.TEXT_NODE:{let m=d.textContent;g&&(a=c+m.substring(0,n).replace(To,"").length),u&&(l=c+m.substring(0,r).replace(To,"").length),c+=m.replace(To,"").length;break}case Node.ELEMENT_NODE:{let m=d.nextSibling===null;rs(d)&&!m&&c++;for(let f=0;f<d.childNodes.length;f++){let h=g&&f===n,E=u&&f===r;if(h&&(a=c),E&&(l=c),l!==void 0||((!h||!i)&&p(d.childNodes[f]),u&&f===r-1&&(l=c),l!==void 0))break}!u&&ss(d)&&!m&&c++,u&&(l=c);break}default:break}}if(p(t),l===void 0)throw new Error("Could not determine start and end");return{start:a??l,end:l}}function as(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(c){let p=c===o,d=c===s;switch(p&&i++,c.nodeType){case Node.TEXT_NODE:{if(i!==0)return;let g=p?n:0,u=d?r:void 0,m=c.textContent.replace(To,"");g===0&&u===void 0?a+=m:a+=m.substring(g,u);break}case Node.ELEMENT_NODE:{let g=c.nextSibling===null;i===0&&rs(c)&&!g&&(a+=`
8
8
  `);for(let u=p?n:0;u<(d?Math.min(r,c.childNodes.length):c.childNodes.length)&&(l(c.childNodes[u]),i!==1);u++);!d&&i===0&&ss(c)&&!g&&(a+=`
9
- `);break}default:break}d&&i++}return l(t),a}function pd(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var Ft=class extends Fe{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),as(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!pd(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!pd(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return is(this.element,e);let o=this.lastKnownSelection;if(o&&cd(this.element,o.start,o.end))return o;let n=Eo(this.element);return n.collapse(!1),is(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return as(this.element,ct(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(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let e=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==e&&(e=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};function dd(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}var ni=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()}},si=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=dd(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()}},ri=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(),w.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 si(e,this.deepdeskUrl,{debug:!0}):new ni(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=typeof s.data=="string"?JSON.parse(s.data):s.data;r.type==="event"&&r.channel===e&&(w.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;w.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)}},ud=ri;var Kt=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var ii=t=>new Promise(e=>{setTimeout(e,t)});var Ut=class extends Kt{name="ClientError"},ai=class extends Kt{name="ServerError"},Se=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,{abortLatest:l=!1,attempts:c=1,retryDelay:p=500,refreshTokenOn401:d=!0,retryOnError:g=b=>b instanceof TypeError,retryOnResponse:u=b=>b.status>=500,version:m="v1",...f}=o,h={credentials:"include",...f,headers:{"Content-Type":"application/json",...f.headers}};o.method!==void 0&&o.method!=="GET"&&this.csrfToken&&(h.headers={...h.headers,"X-CSRFToken":this.csrfToken}),typeof m=="string"&&(h.headers={...h.headers,"X-Deepdesk-API-Version":m});let E=c,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&l&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let _=async()=>(E--,a(i,h).then(async b=>u(b)&&!r.isAborted&&E>0?(await ii(p),_()):b.status===401&&d===!0&&x===!1?(x=!0,await this.refreshToken(),_()):b).catch(async b=>{if(g(b)&&!r.isAborted&&E>0)return await ii(p),_();throw b}));_().then(b=>b.json().catch(()=>null).then(v=>{b.status>=500?s(new ai("Server Error",v)):b.status===401?s(new Ut("Unauthorized",v)):b.status===403?s(new Ut("Forbidden",v)):b.status===404?s(new Ut("Not Found",v)):b.status>=400&&s(new Ut("Bad Request",v)),delete this.latestRequestByUrl[i],n(v)})).catch(b=>{s(b)})})}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 rS;(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||={})})(rS||={});function ls(t){return{...A(t),tags:t.tags}}var Ge=class t{constructor(e,o={}){this.options=o;this.client=new Se(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(),w.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...z(e),tags:e.tags},{version:"v2"});return ls(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null});return A(o)}async getKnowledgeAssistant(e){let o=await this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{version:null});return A(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null});return A(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null});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(),w.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 w.info(`Successfully retrieved conversation ${r.id} for session ${e}`),ls(r)}async isConversationSupported(e,o={}){w.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=z(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return ls(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...z(s),tags:s.tags})),{version:"v2"})).map(s=>ls(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",z({...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:z({...o,...n})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e.filter(n=>n.text)})).entities}async getSummary(e,o={}){return(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})).summary}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 w.warn(`Invalid token '${e}'`),o})}async authenticateWithKey(e,o){await this.client.post("/apis/admin/session/api-key/",z(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}`,z(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`,z(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",z(e),{abortLatest:!0});return A(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,z(e),{version:"v2"});return A(o)}async knowledgeAssist(e,o,n,s={}){let r=await this.client.post(`/api/knowledge-assist/assistants/${n}/search`,z({question:e.question,promptInstruction:e.promptInstruction,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)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(wi);if(!o||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&o&&a!==o&&w.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(o)}`),this.latestReceivedDeepdeskVersions[i]=o})}};var ko=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(sr(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,A(s))}catch{w.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 iS;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(iS||={});var Io=class{constructor(e,o={}){this.apiUrl=e;this.client=new Se(e,o)}client;streams={};logger=w;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`,z(o));return A(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,z(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",z(e));return A(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new ko(`${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])}};import{combineReducers as gS,configureStore as mS}from"@reduxjs/toolkit";import{createSlice as aS}from"@reduxjs/toolkit";var gd={startTime:null,stopTime:null},md=aS({name:"handlingTime",initialState:gd,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(P,()=>gd)}}),{handlingTimeStart:fd,handlingTimeStop:cs,handlingTimeReset:hd}=md.actions,yd=md.reducer;var vd=(t={})=>{let e={onAuthError:Pt(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};import{createAsyncThunk as lS,createSlice as cS}from"@reduxjs/toolkit";var ps={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var pt=lS("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 ps.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),pS=cS({name:"styleSuggestions",initialState:ps,reducers:{},extraReducers:t=>{t.addCase(pt.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(pt.rejected,e=>{e.fetchState="error"}).addCase(pt.fulfilled,(e,o)=>{e.fetchState="done",De(e.list,o.payload)||(e.list=o.payload)}).addCase(Qe,e=>{e.list=ps.list}).addCase(P,()=>ps)}}),Sd=pS.reducer;var _d=(t={})=>{let e,o=!0,n={getStyleSuggestions:pt,debounce:500,...t};return s=>r=>i=>{var u;let a=s.getState().input.text,l=r(i),c=s.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:p}=c.settings;if(!((u=c.conversation.current)==null?void 0:u.id)||!p)return l;let{text:g}=c.input;return g===a&&!o||(clearTimeout(e),g==="")||(e=setTimeout(()=>{o=!1,s.dispatch(n.getStyleSuggestions({text:g}))},t.debounce)),l}};function dS(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var xd=(t={})=>{let e={getTextSuggestions:de,getAutocompleteSuggestions:io,debounce:200,check:Ot,...t},o;return n=>s=>r=>{var f;let{input:{userCommitted:i}}=n.getState(),a=s(r),l=n.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:p}=l.settings,d=(f=l.conversation.current)==null?void 0:f.id,g=r.type===In.toString();if(!d||!c&&!p)return a;let{input:{userCommitted:u}}=l;return dS(u,i)&&!g||(clearTimeout(o),!e.check(l))||(o=setTimeout(()=>{let h=St(l);h===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(h))},g?0:e.debounce)),a}};var bd=pt.fulfilled.toString();function uS(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 Cd=t=>e=>o=>n=>{var c;if(n.type!==bd){o(n);return}let s=e.getState().styleSuggestions.list;o(n);let r=e.getState(),i=r.styleSuggestions.list,a=(c=r.conversation)==null?void 0:c.current;if(s===i)return;let l=uS(s,i);n.type===bd&&l.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var fS=gS({activeSuggestion:bl,answer:fc,auth:Ol,autoflows:Sp,conversation:Pi,contentTypes:Zl,customMessages:Ip,passwordlessToken:Mp,entities:Yl,knowledgeAssistant:uc,handlingTime:yd,info:Wa,input:ks.reducer,overlayInput:J.reducer,settings:Ei,profile:_c,search:Ya,summary:ic,styleSuggestions:Sd,ui:El,rules:Fl,textSuggestions:yl});function wd(t){return mS({reducer:fS,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),vd(),xd({debounce:200}),_d({debounce:500}),Cd(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var hS=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},yS=t=>e=>o=>n=>{var a;let s=e.getState(),r=Cs("inlineSuggestions")(s);switch(n.type){case Te.toString():{let l=kn(n.payload.contentType)(e.getState()),c=l.indexOf(n.payload.suggestion);t.emit("edit-suggestion",{contentType:n.payload.contentType,index:c,suggestions:l});break}case Pt.toString():{!n.payload&&t.emit("logout",void 0);break}case le.toString():{let{start:l,end:c}=s.input.selection;t.emit("select-suggestion",{type:hS(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case Wo.toString():{let{start:l,end:c}=s.input.selection;t.emit("replace",{...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case Xt.toString():{let l=e.getState(),{text:c,selection:p}=l.input.userCommitted;t.emit("reset",{text:c,selectionAfter:p},{mayApplyChanges:!0});break}case Zo.toString():t.emit("select-image",n.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:s.conversation.current.id,data:{path:n.payload.suggestion.image,title:n.payload.suggestion.title}});break;case ue.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:n.payload}});break;case Re.fulfilled.toString():t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{summary:n.payload.summary}});break;case W.toString():t.sendEvent(n.payload.name,{conversationId:((a=n.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:n.payload.data});break;case $o.toString():t.handleKeyDown(n.payload);break;case Qe.toString():t.logSendMessage(n.payload);break;case Go.toString():t.logSendEditSuggestionMessage(n.payload);break;case Xo.toString():t.handleInputChanged(n.payload);break;case ke.fulfilled.toString():t.broadcast(fr,n.payload,!1),t.emit("cues",n.payload);break;default:break}let i=o(n);switch(n.type){case Qe.toString():t.handleAfterSendMessage(n.payload);break;case ao.toString():t.onUpdateShowTabHint(n.payload);break;case cs.toString():t.logHandlingTime();break;case le.toString():{r&&(e.dispatch(me([])),e.dispatch(xe()));break}case me.toString():{r&&n.payload.length>0&&e.dispatch(Be(0));break}default:break}return i},Td=yS;function li(t){return t.toISOString().replace("T"," ").replace("Z","")}function Ed(t,e){var s,r,i;let{startTime:o,stopTime:n}=t.handlingTime;if(!o||!n)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:t.conversation.current.id,clientVersion:e.version,agentId:(s=t.info.agentInfo)==null?void 0:s.agentId,agentName:(r=t.info.agentInfo)==null?void 0:r.agentName,agentEmail:(i=t.info.agentInfo)==null?void 0:i.agentEmail,timeStart:li(o),timeStop:li(n)}}function ci(t,e,o){var N,B,D;let{text:n,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:d,cuts:g,deletions:u,textSuggestions:m,offeredTextSuggestions:f}}=e[t],h=n.length,x=m.reduce((U,{text:F,searchTerm:k})=>U+F.length-(k?k.length:0),0),_=c??Date.now(),b=(Date.now()-_)/1e3+(p||0),v=s/b,R=m.reduce((U,{searchTerm:F})=>U+(F?F.length:0),0);return{conversationId:e.conversation.current.id,source:"agent",text:n,clientVersion:o.version,pastes:d,cuts:g,deletions:u,lenTextTyped:s+R,lenTextTotal:h,lenTextAssisted:x,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:b,charsPerSecond:v,numPastes:l,textSuggestionsV2:m,suggestionsCounters:[{source:"gpt",countOffered:f.filter(U=>U.source==="gpt").length}],agentId:(N=e.info.agentInfo)==null?void 0:N.agentId,agentName:(B=e.info.agentInfo)==null?void 0:B.agentName,agentEmail:(D=e.info.agentInfo)==null?void 0:D.agentEmail}}function pi(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return pi(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?pi(s,e):null}function kd(t,e){return pi(t,e)}function Id(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function vS(t){return typeof t=="object"&&t!==null&&"tagName"in t}function di(t){return vS(t)&&(We(t)||gn(t))}var Rd=(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{w.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function SS(t){return t.offsetParent!==null}function Pd(t){if(!SS(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 ui(t,e,o=100){let n=Pd(t);e({isVisible:n});let s=setInterval(()=>{let r=Pd(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}import{jsx as j}from"react/jsx-runtime";var Ad=Rd("showTabHint",!0),us=class t{static version="10.12.1-beta.6";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 c=e.replace(/\/api$/,"");this.deepdeskApi=new Ge(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Td({broadcast:(d,g,u)=>{this.broadcastEvents.send(d,g,u)},emit:(d,g,u)=>this.emit(d,g,u),handleAfterSendMessage:d=>this.handleAfterSendMessage(d),handleInputChanged:d=>this.handleInputChanged(d),handleKeyDown:d=>this.handleKeyDown(d),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:d=>this.logSendMessage(d),logSendEditSuggestionMessage:d=>this.logSendEditMessage(d),onUpdateShowTabHint:d=>Ad.update(d),sendEvent:(d,g)=>this.deepdeskApi.sendEvent(d,g)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new Io(o)}),this.store=wd(p),this.broadcastEvents=new ud({debug:!0,deepdeskUrl:c,eventMap:Kl(this.store),createCustomChannel:l}),this.store.dispatch(ao(Ad.value())),this.store.dispatch(Ho({locale:s,adminUrl:c,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?(w.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(w.warn("Profile has not been loaded (yet)"),!0):(w.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Pt(null)),this.store.dispatch(Ee()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();Z(n)&&Rl(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(Ee())).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){w.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(Ts({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Ko(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Uo({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Es(e))).payload}async postMessages(e){return(await this.store.dispatch(jo(e))).payload}async updateConversation(e){return(await this.store.dispatch(zo(e))).payload}resetConversation(){this.store.dispatch(P()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Re());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(Ho(e))}setVisitorInfo(e){this.store.dispatch(qa(e))}async setAgentInfo(e){await this.store.dispatch(no(e))}async setAgentSettings(e){await this.store.dispatch(ir(e))}async getAgentSettings(){return(await this.store.dispatch(ar())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(In()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Xo(e))}notifyKeyDown(e){this.store.dispatch($o(e))}notifyPaste(e,o){this.store.dispatch(Ui({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Fi(e))}notifyExternalSuggestion(e){this.store.dispatch(le(e)),this.store.dispatch(xe())}notifyEditSuggestion(e){this.store.dispatch(fl(e.contentType,e.suggestions)),this.store.dispatch(Te({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}async evaluateRule(e,o={}){let{payload:n,error:s}=await this.store.dispatch(ke({label:e,params:o}));if(s)throw s;return n}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(Ve({collapse:!1})),this.inputMediator&&this.store.dispatch(Mi({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(me([])))}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(Ki(qo(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Di()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(Bi()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Xt()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(e.key){case"Up":case"ArrowUp":i?p():c();return;case"Down":case"ArrowDown":{i?c():p();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(Be(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Be(-1)),this.store.dispatch(Xt()),e.preventDefault()):o||(this.store.dispatch(Ve({collapse:!0})),this.store.dispatch(wl(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:d}=this.state.input,g=d.text.substring(0,d.selection.end),{tabCompletionSuggestion:u}=this.state.input;this.store.dispatch(ao(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&u&&u.text.startsWith(g)&&(this.store.dispatch(le({text:u.text,suggestion:u,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(xe())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(zi()),this.store.dispatch(me([]))}handlingTimeStart(){this.state.handlingTime.startTime||(w.info("Start handling time"),this.store.dispatch(fd()))}handlingTimeStop(){this.state.handlingTime.startTime&&(w.info("Stop handling time"),this.store.dispatch(cs()))}logSendMessage(e){let o=ci("input",this.state,{version:this.version});e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logSendEditMessage(e){let o=ci("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Oi(this.state.overlayInput.metrics))}logHandlingTime(){let e=Ed(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(hd())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(xe()),this.store.dispatch(Qe(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(le({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){w.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),w.error(i)}})};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]=wt(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{ds(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]=wt(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{ds(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Ye(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(()=>{ds(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),w.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()?(w.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Vi(n.metrics))):w.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(!di(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:c,showSuggestionsAfterPattern:p,isEmbedded:d,detectSubmit:g,insertLink:u,inputMediator:m,closestScrollSelector:f,appendOverlayTo:h,inlineSuggestions:E,floatingMenu:x}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:u,isEmbedded:d,inlineSuggestions:E,floatingMenu:!!x}),o.automaticHandlingTime&&this.setupHandlingTime(e),Ye(e),this.inputMediator=m||(We(e)?new Ke(e):new Ft(e)),this.inputMediator.on("change",({plainText:v})=>{this.notifyInputChanged(v)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(ji({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",v=>{this.notifyKeyDown(v)}),this.inputMediator.on("paste",({pastedText:v,selectionText:R})=>{this.notifyPaste(v,R)}),this.inputMediator.on("cut",({selectionText:v})=>{this.notifyCut(v)});let _=f&&kd(e,f)||void 0;if(E){let{customStyles:v,appendOverlayTo:R}=o;if(We(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let N=this.createInlineContainer(e,"deepdesk-caret");zt(j(rt,{store:this.store,customStyles:v,children:j(nt,{broadcastEvents:this.broadcastEvents,children:j(Hc,{})})}),N),this.inputMediator.on("caret",D=>{this.store.dispatch(me([])),D?(N.style.display="block",N.style.top=`${D.top}px`,N.style.left=`${D.left}px`):N.style.display="none"});let B=this.overlayContainerFactory("floating-menu",_||e,{appendTo:typeof x=="object"&&"appendOverlayTo"in x?x.appendOverlayTo:R},v==null?void 0:v.floatingMenuRootNode);zt(j(rt,{store:this.store,customStyles:v,children:j(nt,{broadcastEvents:this.broadcastEvents,children:j(Ac,{onLogIn:()=>this.loginViaPopup().catch(D=>w.warn(D.message))})})}),B)}else{let v=this.overlayContainerFactory("deepdesk-tab-completion",_||e,{appendTo:h,closestScrollElement:_,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),R=this.overlayContainerFactory("deepdesk-suggestions-overlay",_||e,{appendTo:h},n==null?void 0:n.suggestionsRootNode);zt(j(rt,{store:this.store,customStyles:n,children:j(nt,{broadcastEvents:this.broadcastEvents,children:j(gp,{inputElement:e})})}),v),zt(j(rt,{store:this.store,customStyles:n,children:j(nt,{broadcastEvents:this.broadcastEvents,children:j(Wc,{onLogIn:()=>this.loginViaPopup().catch(N=>w.warn(N.message))})})}),R)}zt(j(rt,{store:this.store,customStyles:n,children:j(nt,{broadcastEvents:this.broadcastEvents,children:j(Tc,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",v=>{clearTimeout(b),v===null?b=setTimeout(()=>{v!==null&&this.store.dispatch(Is(v))},500):this.store.dispatch(Is(v))}),this.inputMediator.on("disabled",()=>{var v;(v=this.inputMediator)==null||v.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{g&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Rt(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Rt(!0))),this.store.dispatch(Ni({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(xe()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var v;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((v=this.state.conversation.current)==null?void 0:v.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&&w.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}),zt(j(rt,{store:this.store,customStyles:n,children:j(nt,{broadcastEvents:this.broadcastEvents,children:j(ld,{onLogIn:()=>this.loginViaPopup().catch(i=>w.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&ds(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=ui(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Id(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(ho());let e=qe(this.state);e&&(await this.store.dispatch(fo()),this.store.dispatch(Ho({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,c=()=>{p&&!p.closed&&p.close(),window.removeEventListener("message",d),clearInterval(g)};r.onmessage=async u=>{var m,f;if((m=u.data)!=null&&m.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((f=u.data)==null?void 0:f.jwt),await this.isLoggedIn(),this.broadcastEvents.send(co),l=!0,s.port1.close(),o()}catch(h){console.error(h),n(h)}finally{l=!0,c()}};let p=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");p===null&&n(new Error("Popup blocked by browser"));let d=async u=>{var m;if(u.origin===a.origin)switch((m=u.data)==null?void 0:m.type){case"deepdesk-popup-loaded":{try{let f=JSON.stringify({type:"deepdesk-popup-create-channel"});p==null||p.postMessage(f,a.origin,[s.port2])}catch(f){w.error("Error posting message to popup",f),n(f)}break}case"deepdesk-popup-error":{c(),u.data.message==="Timeout"&&w.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(u.data.message));break}}};window.addEventListener("message",d);let g=setInterval(()=>{p&&!p.closed||(c(),l||n(new Error("Popup closed by user")))},200);this.unmountHandlers.push(c)})}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(w.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;w.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=Nn(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(ue()):this.store.dispatch(de(n))})}catch(n){this.handleError(n)}}};async function _S(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 xS(t,e,o={}){let n=o.replace?ct(t,o.replace.start,o.replace.end):Eo(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(`
9
+ `);break}default:break}d&&i++}return l(t),a}function pd(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var Ft=class extends Fe{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),as(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!pd(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!pd(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return is(this.element,e);let o=this.lastKnownSelection;if(o&&cd(this.element,o.start,o.end))return o;let n=Eo(this.element);return n.collapse(!1),is(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return as(this.element,ct(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(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let e=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==e&&(e=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};function dd(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}var ni=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()}},si=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=dd(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()}},ri=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(),w.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 si(e,this.deepdeskUrl,{debug:!0}):new ni(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=typeof s.data=="string"?JSON.parse(s.data):s.data;r.type==="event"&&r.channel===e&&(w.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;w.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)}},ud=ri;var Kt=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var ii=t=>new Promise(e=>{setTimeout(e,t)});var Ut=class extends Kt{name="ClientError"},ai=class extends Kt{name="ServerError"},Se=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,{abortLatest:l=!1,attempts:c=1,retryDelay:p=500,refreshTokenOn401:d=!0,retryOnError:g=b=>b instanceof TypeError,retryOnResponse:u=b=>b.status>=500,version:m="v1",...f}=o,h={credentials:"include",...f,headers:{"Content-Type":"application/json",...f.headers}};o.method!==void 0&&o.method!=="GET"&&this.csrfToken&&(h.headers={...h.headers,"X-CSRFToken":this.csrfToken}),typeof m=="string"&&(h.headers={...h.headers,"X-Deepdesk-API-Version":m});let E=c,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&l&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let _=async()=>(E--,a(i,h).then(async b=>u(b)&&!r.isAborted&&E>0?(await ii(p),_()):b.status===401&&d===!0&&x===!1?(x=!0,await this.refreshToken(),_()):b).catch(async b=>{if(g(b)&&!r.isAborted&&E>0)return await ii(p),_();throw b}));_().then(b=>b.json().catch(()=>null).then(v=>{b.status>=500?s(new ai("Server Error",v)):b.status===401?s(new Ut("Unauthorized",v)):b.status===403?s(new Ut("Forbidden",v)):b.status===404?s(new Ut("Not Found",v)):b.status>=400&&s(new Ut("Bad Request",v)),delete this.latestRequestByUrl[i],n(v)})).catch(b=>{s(b)})})}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 rS;(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||={})})(rS||={});function ls(t){return{...A(t),tags:t.tags}}var Ge=class t{constructor(e,o={}){this.options=o;this.client=new Se(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(),w.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...z(e),tags:e.tags},{version:"v2"});return ls(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null});return A(o)}async getKnowledgeAssistant(e){let o=await this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{version:null});return A(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null});return A(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null});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(),w.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 w.info(`Successfully retrieved conversation ${r.id} for session ${e}`),ls(r)}async isConversationSupported(e,o={}){w.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=z(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return ls(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...z(s),tags:s.tags})),{version:"v2"})).map(s=>ls(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",z({...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:z({...o,...n})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e.filter(n=>n.text)})).entities}async getSummary(e,o={}){return(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})).summary}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 w.warn(`Invalid token '${e}'`),o})}async authenticateWithKey(e,o){await this.client.post("/apis/admin/session/api-key/",z(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}`,z(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`,z(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",z(e),{abortLatest:!0});return A(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,z(e),{version:"v2"});return A(o)}async knowledgeAssist(e,o,n,s={}){let r=await this.client.post(`/api/knowledge-assist/assistants/${n}/search`,z({question:e.question,promptInstruction:e.promptInstruction,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)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(wi);if(!o||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&o&&a!==o&&w.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(o)}`),this.latestReceivedDeepdeskVersions[i]=o})}};var ko=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(sr(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,A(s))}catch{w.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 iS;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(iS||={});var Io=class{constructor(e,o={}){this.apiUrl=e;this.client=new Se(e,o)}client;streams={};logger=w;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`,z(o));return A(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,z(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",z(e));return A(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new ko(`${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])}};import{combineReducers as gS,configureStore as mS}from"@reduxjs/toolkit";import{createSlice as aS}from"@reduxjs/toolkit";var gd={startTime:null,stopTime:null},md=aS({name:"handlingTime",initialState:gd,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(P,()=>gd)}}),{handlingTimeStart:fd,handlingTimeStop:cs,handlingTimeReset:hd}=md.actions,yd=md.reducer;var vd=(t={})=>{let e={onAuthError:Pt(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};import{createAsyncThunk as lS,createSlice as cS}from"@reduxjs/toolkit";var ps={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var pt=lS("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 ps.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),pS=cS({name:"styleSuggestions",initialState:ps,reducers:{},extraReducers:t=>{t.addCase(pt.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(pt.rejected,e=>{e.fetchState="error"}).addCase(pt.fulfilled,(e,o)=>{e.fetchState="done",De(e.list,o.payload)||(e.list=o.payload)}).addCase(Qe,e=>{e.list=ps.list}).addCase(P,()=>ps)}}),Sd=pS.reducer;var _d=(t={})=>{let e,o=!0,n={getStyleSuggestions:pt,debounce:500,...t};return s=>r=>i=>{var u;let a=s.getState().input.text,l=r(i),c=s.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:p}=c.settings;if(!((u=c.conversation.current)==null?void 0:u.id)||!p)return l;let{text:g}=c.input;return g===a&&!o||(clearTimeout(e),g==="")||(e=setTimeout(()=>{o=!1,s.dispatch(n.getStyleSuggestions({text:g}))},t.debounce)),l}};function dS(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var xd=(t={})=>{let e={getTextSuggestions:de,getAutocompleteSuggestions:io,debounce:200,check:Ot,...t},o;return n=>s=>r=>{var f;let{input:{userCommitted:i}}=n.getState(),a=s(r),l=n.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:p}=l.settings,d=(f=l.conversation.current)==null?void 0:f.id,g=r.type===In.toString();if(!d||!c&&!p)return a;let{input:{userCommitted:u}}=l;return dS(u,i)&&!g||(clearTimeout(o),!e.check(l))||(o=setTimeout(()=>{let h=St(l);h===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(h))},g?0:e.debounce)),a}};var bd=pt.fulfilled.toString();function uS(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 Cd=t=>e=>o=>n=>{var c;if(n.type!==bd){o(n);return}let s=e.getState().styleSuggestions.list;o(n);let r=e.getState(),i=r.styleSuggestions.list,a=(c=r.conversation)==null?void 0:c.current;if(s===i)return;let l=uS(s,i);n.type===bd&&l.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var fS=gS({activeSuggestion:bl,answer:fc,auth:Ol,autoflows:Sp,conversation:Pi,contentTypes:Zl,customMessages:Ip,passwordlessToken:Mp,entities:Yl,knowledgeAssistant:uc,handlingTime:yd,info:Wa,input:ks.reducer,overlayInput:J.reducer,settings:Ei,profile:_c,search:Ya,summary:ic,styleSuggestions:Sd,ui:El,rules:Fl,textSuggestions:yl});function wd(t){return mS({reducer:fS,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),vd(),xd({debounce:200}),_d({debounce:500}),Cd(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var hS=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},yS=t=>e=>o=>n=>{var a;let s=e.getState(),r=Cs("inlineSuggestions")(s);switch(n.type){case Te.toString():{let l=kn(n.payload.contentType)(e.getState()),c=l.indexOf(n.payload.suggestion);t.emit("edit-suggestion",{contentType:n.payload.contentType,index:c,suggestions:l});break}case Pt.toString():{!n.payload&&t.emit("logout",void 0);break}case le.toString():{let{start:l,end:c}=s.input.selection;t.emit("select-suggestion",{type:hS(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case Wo.toString():{let{start:l,end:c}=s.input.selection;t.emit("replace",{...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case Xt.toString():{let l=e.getState(),{text:c,selection:p}=l.input.userCommitted;t.emit("reset",{text:c,selectionAfter:p},{mayApplyChanges:!0});break}case Zo.toString():t.emit("select-image",n.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:s.conversation.current.id,data:{path:n.payload.suggestion.image,title:n.payload.suggestion.title}});break;case ue.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:n.payload}});break;case Re.fulfilled.toString():t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{summary:n.payload.summary}});break;case W.toString():t.sendEvent(n.payload.name,{conversationId:((a=n.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:n.payload.data});break;case $o.toString():t.handleKeyDown(n.payload);break;case Qe.toString():t.logSendMessage(n.payload);break;case Go.toString():t.logSendEditSuggestionMessage(n.payload);break;case Xo.toString():t.handleInputChanged(n.payload);break;case ke.fulfilled.toString():t.broadcast(fr,n.payload,!1),t.emit("cues",n.payload);break;default:break}let i=o(n);switch(n.type){case Qe.toString():t.handleAfterSendMessage(n.payload);break;case ao.toString():t.onUpdateShowTabHint(n.payload);break;case cs.toString():t.logHandlingTime();break;case le.toString():{r&&(e.dispatch(me([])),e.dispatch(xe()));break}case me.toString():{r&&n.payload.length>0&&e.dispatch(Be(0));break}default:break}return i},Td=yS;function li(t){return t.toISOString().replace("T"," ").replace("Z","")}function Ed(t,e){var s,r,i;let{startTime:o,stopTime:n}=t.handlingTime;if(!o||!n)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:t.conversation.current.id,clientVersion:e.version,agentId:(s=t.info.agentInfo)==null?void 0:s.agentId,agentName:(r=t.info.agentInfo)==null?void 0:r.agentName,agentEmail:(i=t.info.agentInfo)==null?void 0:i.agentEmail,timeStart:li(o),timeStop:li(n)}}function ci(t,e,o){var N,B,D;let{text:n,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:d,cuts:g,deletions:u,textSuggestions:m,offeredTextSuggestions:f}}=e[t],h=n.length,x=m.reduce((U,{text:F,searchTerm:k})=>U+F.length-(k?k.length:0),0),_=c??Date.now(),b=(Date.now()-_)/1e3+(p||0),v=s/b,R=m.reduce((U,{searchTerm:F})=>U+(F?F.length:0),0);return{conversationId:e.conversation.current.id,source:"agent",text:n,clientVersion:o.version,pastes:d,cuts:g,deletions:u,lenTextTyped:s+R,lenTextTotal:h,lenTextAssisted:x,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:b,charsPerSecond:v,numPastes:l,textSuggestionsV2:m,suggestionsCounters:[{source:"gpt",countOffered:f.filter(U=>U.source==="gpt").length}],agentId:(N=e.info.agentInfo)==null?void 0:N.agentId,agentName:(B=e.info.agentInfo)==null?void 0:B.agentName,agentEmail:(D=e.info.agentInfo)==null?void 0:D.agentEmail}}function pi(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return pi(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?pi(s,e):null}function kd(t,e){return pi(t,e)}function Id(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function vS(t){return typeof t=="object"&&t!==null&&"tagName"in t}function di(t){return vS(t)&&(We(t)||gn(t))}var Rd=(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{w.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function SS(t){return t.offsetParent!==null}function Pd(t){if(!SS(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 ui(t,e,o=100){let n=Pd(t);e({isVisible:n});let s=setInterval(()=>{let r=Pd(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}import{jsx as j}from"react/jsx-runtime";var Ad=Rd("showTabHint",!0),us=class t{static version="10.12.1-beta.7";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 c=e.replace(/\/api$/,"");this.deepdeskApi=new Ge(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Td({broadcast:(d,g,u)=>{this.broadcastEvents.send(d,g,u)},emit:(d,g,u)=>this.emit(d,g,u),handleAfterSendMessage:d=>this.handleAfterSendMessage(d),handleInputChanged:d=>this.handleInputChanged(d),handleKeyDown:d=>this.handleKeyDown(d),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:d=>this.logSendMessage(d),logSendEditSuggestionMessage:d=>this.logSendEditMessage(d),onUpdateShowTabHint:d=>Ad.update(d),sendEvent:(d,g)=>this.deepdeskApi.sendEvent(d,g)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new Io(o)}),this.store=wd(p),this.broadcastEvents=new ud({debug:!0,deepdeskUrl:c,eventMap:Kl(this.store),createCustomChannel:l}),this.store.dispatch(ao(Ad.value())),this.store.dispatch(Ho({locale:s,adminUrl:c,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?(w.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(w.warn("Profile has not been loaded (yet)"),!0):(w.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Pt(null)),this.store.dispatch(Ee()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();Z(n)&&Rl(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(Ee())).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){w.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(Ts({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Ko(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Uo({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Es(e))).payload}async postMessages(e){return(await this.store.dispatch(jo(e))).payload}async updateConversation(e){return(await this.store.dispatch(zo(e))).payload}resetConversation(){this.store.dispatch(P()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Re());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(Ho(e))}setVisitorInfo(e){this.store.dispatch(qa(e))}async setAgentInfo(e){await this.store.dispatch(no(e))}async setAgentSettings(e){await this.store.dispatch(ir(e))}async getAgentSettings(){return(await this.store.dispatch(ar())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(In()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Xo(e))}notifyKeyDown(e){this.store.dispatch($o(e))}notifyPaste(e,o){this.store.dispatch(Ui({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Fi(e))}notifyExternalSuggestion(e){this.store.dispatch(le(e)),this.store.dispatch(xe())}notifyEditSuggestion(e){this.store.dispatch(fl(e.contentType,e.suggestions)),this.store.dispatch(Te({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}async evaluateRule(e,o={}){let{payload:n,error:s}=await this.store.dispatch(ke({label:e,params:o}));if(s)throw s;return n}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(Ve({collapse:!1})),this.inputMediator&&this.store.dispatch(Mi({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(me([])))}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(Ki(qo(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Di()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(Bi()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Xt()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(e.key){case"Up":case"ArrowUp":i?p():c();return;case"Down":case"ArrowDown":{i?c():p();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(Be(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Be(-1)),this.store.dispatch(Xt()),e.preventDefault()):o||(this.store.dispatch(Ve({collapse:!0})),this.store.dispatch(wl(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:d}=this.state.input,g=d.text.substring(0,d.selection.end),{tabCompletionSuggestion:u}=this.state.input;this.store.dispatch(ao(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&u&&u.text.startsWith(g)&&(this.store.dispatch(le({text:u.text,suggestion:u,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(xe())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(zi()),this.store.dispatch(me([]))}handlingTimeStart(){this.state.handlingTime.startTime||(w.info("Start handling time"),this.store.dispatch(fd()))}handlingTimeStop(){this.state.handlingTime.startTime&&(w.info("Stop handling time"),this.store.dispatch(cs()))}logSendMessage(e){let o=ci("input",this.state,{version:this.version});e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logSendEditMessage(e){let o=ci("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Oi(this.state.overlayInput.metrics))}logHandlingTime(){let e=Ed(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(hd())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(xe()),this.store.dispatch(Qe(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(le({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){w.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),w.error(i)}})};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]=wt(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{ds(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]=wt(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{ds(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Ye(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(()=>{ds(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),w.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()?(w.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Vi(n.metrics))):w.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(!di(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:c,showSuggestionsAfterPattern:p,isEmbedded:d,detectSubmit:g,insertLink:u,inputMediator:m,closestScrollSelector:f,appendOverlayTo:h,inlineSuggestions:E,floatingMenu:x}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:u,isEmbedded:d,inlineSuggestions:E,floatingMenu:!!x}),o.automaticHandlingTime&&this.setupHandlingTime(e),Ye(e),this.inputMediator=m||(We(e)?new Ke(e):new Ft(e)),this.inputMediator.on("change",({plainText:v})=>{this.notifyInputChanged(v)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(ji({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",v=>{this.notifyKeyDown(v)}),this.inputMediator.on("paste",({pastedText:v,selectionText:R})=>{this.notifyPaste(v,R)}),this.inputMediator.on("cut",({selectionText:v})=>{this.notifyCut(v)});let _=f&&kd(e,f)||void 0;if(E){let{customStyles:v,appendOverlayTo:R}=o;if(We(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let N=this.createInlineContainer(e,"deepdesk-caret");zt(j(rt,{store:this.store,customStyles:v,children:j(nt,{broadcastEvents:this.broadcastEvents,children:j(Hc,{})})}),N),this.inputMediator.on("caret",D=>{this.store.dispatch(me([])),D?(N.style.display="block",N.style.top=`${D.top}px`,N.style.left=`${D.left}px`):N.style.display="none"});let B=this.overlayContainerFactory("floating-menu",_||e,{appendTo:typeof x=="object"&&"appendOverlayTo"in x?x.appendOverlayTo:R},v==null?void 0:v.floatingMenuRootNode);zt(j(rt,{store:this.store,customStyles:v,children:j(nt,{broadcastEvents:this.broadcastEvents,children:j(Ac,{onLogIn:()=>this.loginViaPopup().catch(D=>w.warn(D.message))})})}),B)}else{let v=this.overlayContainerFactory("deepdesk-tab-completion",_||e,{appendTo:h,closestScrollElement:_,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),R=this.overlayContainerFactory("deepdesk-suggestions-overlay",_||e,{appendTo:h},n==null?void 0:n.suggestionsRootNode);zt(j(rt,{store:this.store,customStyles:n,children:j(nt,{broadcastEvents:this.broadcastEvents,children:j(gp,{inputElement:e})})}),v),zt(j(rt,{store:this.store,customStyles:n,children:j(nt,{broadcastEvents:this.broadcastEvents,children:j(Wc,{onLogIn:()=>this.loginViaPopup().catch(N=>w.warn(N.message))})})}),R)}zt(j(rt,{store:this.store,customStyles:n,children:j(nt,{broadcastEvents:this.broadcastEvents,children:j(Tc,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",v=>{clearTimeout(b),v===null?b=setTimeout(()=>{v!==null&&this.store.dispatch(Is(v))},500):this.store.dispatch(Is(v))}),this.inputMediator.on("disabled",()=>{var v;(v=this.inputMediator)==null||v.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{g&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Rt(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Rt(!0))),this.store.dispatch(Ni({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(xe()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var v;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((v=this.state.conversation.current)==null?void 0:v.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&&w.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}),zt(j(rt,{store:this.store,customStyles:n,children:j(nt,{broadcastEvents:this.broadcastEvents,children:j(ld,{onLogIn:()=>this.loginViaPopup().catch(i=>w.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&ds(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=ui(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Id(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(ho());let e=qe(this.state);e&&(await this.store.dispatch(fo()),this.store.dispatch(Ho({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,c=()=>{p&&!p.closed&&p.close(),window.removeEventListener("message",d),clearInterval(g)};r.onmessage=async u=>{var m,f;if((m=u.data)!=null&&m.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((f=u.data)==null?void 0:f.jwt),await this.isLoggedIn(),this.broadcastEvents.send(co),l=!0,s.port1.close(),o()}catch(h){console.error(h),n(h)}finally{l=!0,c()}};let p=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");p===null&&n(new Error("Popup blocked by browser"));let d=async u=>{var m;if(u.origin===a.origin)switch((m=u.data)==null?void 0:m.type){case"deepdesk-popup-loaded":{try{let f=JSON.stringify({type:"deepdesk-popup-create-channel"});p==null||p.postMessage(f,a.origin,[s.port2])}catch(f){w.error("Error posting message to popup",f),n(f)}break}case"deepdesk-popup-error":{c(),u.data.message==="Timeout"&&w.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(u.data.message));break}}};window.addEventListener("message",d);let g=setInterval(()=>{p&&!p.closed||(c(),l||n(new Error("Popup closed by user")))},200);this.unmountHandlers.push(c)})}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(w.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;w.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=Nn(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(ue()):this.store.dispatch(de(n))})}catch(n){this.handleError(n)}}};async function _S(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 xS(t,e,o={}){let n=o.replace?ct(t,o.replace.start,o.replace.end):Eo(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
10
  `).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?ct(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 bS(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 CS(t){let e=document.createDocumentFragment();return t.split(`
11
11
  `).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 Ld(t,e){return!t.contains(e)||e===t?null:e.parentNode===t?e:Ld(t,e.parentNode)}async function wS(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 c=n?bS(e):CS(e);if(o){let p=l.startContainer===t?t.childNodes[l.startOffset]:l.startContainer,d=Ld(t,p)??t.firstChild;t.insertBefore(c,(d==null?void 0:d.nextSibling)??null)}else l.insertNode(c),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 TS(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function ES(t,e,o){await new Ge(t).authenticateWithKey(e,o)}async function kS(t){let o=await new Se(t).get("/platform/config/",{version:null});return A(o)}async function IS(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 RS(t,e){let o=await IS(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}}export{O as Card,Ft as ContentEditableInput,Ge as DeepdeskAPI,us as DeepdeskSDK,Se as HTTPClient,Fe as InputMediator,Xe as InputType,hs as KeyboardHint,ys as Label,Do as Locale,Oe as Section,Ss as SectionList,ge as Sources,M as Suggestion,re as SuggestionList,Ke as TextAreaInput,ft as ToggleButton,RS as attachFile,ES as authenticateWithKey,Eo as createFullRange,wt as createOverlayContainer,ct as createRangeFromOffsets,eo as escapeHTML,kS as fetchPlatformConfig,TS as formatTextMarkup,is as getRangeOffsets,as as getRangeText,wS as insertCKEditor,Tt as isHTML,di as isSupportedInputElement,xS as updateContentEditable,_S as updateTextArea,y as useStyles,ui as waitForElementVisibilityChange};
@@ -22,7 +22,7 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
22
22
  c6.8-6.8,15.4-10.2,24.7-10.2h11.9v-70c0-44.4,16.2-82.8,47.8-115.2S212.1,0,256.4,0s82.8,16.2,115.2,47.8
23
23
  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 ah=S(C()),DL={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},G1=({className:e,color:t})=>(0,ah.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,ah.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:DL[t||"pink"]})});var X1={root:"_root_1tvv4_1",text:"_text_1tvv4_18",isLoggedIn:"_isLoggedIn_1tvv4_25",isLoggedOut:"_isLoggedOut_1tvv4_29",icon:"_icon_1tvv4_39",logo:"_logo_1tvv4_44",lock:"_lock_1tvv4_49"};var lh={};Ee(lh,{enUS:()=>FL,nlNL:()=>jL});var FL={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},jL={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var wo=S(C()),Y1=({onLogIn:e})=>{let t=H(lh),n=M("floatingMenu"),r=M("productName"),o=U(),i=R(Xe),s=k("FloatingMenu",X1);if(i===null||n===!1)return null;let a=()=>{i===!0?o(qe(!0)):e()};return(0,wo.jsxs)("button",{className:(0,Q1.default)(s.root,{[s.isLoggedIn]:i,[s.isLoggedOut]:!i}),onClick:a,children:[(0,wo.jsx)("div",{className:s.text,children:t(i?"search":"signin",{productName:r})}),(0,wo.jsxs)("div",{className:s.icon,children:[(0,wo.jsx)(G1,{className:s.logo,color:"pink"}),i===!1&&(0,wo.jsx)(q1,{className:s.lock})]})]})};var yd=S(O());function Bi(e){let{showMidSentenceSuggestions:t,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:r}=e.settings,{text:o,selection:i}=e.input.userCommitted;return i.start!==i.end?!1:i.end>=o.length?!0:t?n&&new RegExp(n).test(o.substring(i.end))||r&&new RegExp(r).test(o.substring(0,i.end))?!0:n===!1&&r===!1:!1}var gd=S(O());var zi=S(O());var Z1=S(O());function J1(e,t,n){(0,Z1.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var eC={root:"_root_4u430_1",actions:"_actions_4u430_8",badge:"_badge_4u430_15",formattedText:"_formattedText_4u430_19"};var Co=S(C()),BL=["search","personal-collection-search","search-autocomplete"];function zL(e,t,n,r={}){let o="";return BL.includes(t)?o=X_(Og(e,n,{stripAgentPart:!0}),r.searchKeywords??[n]):o=Og(e,n,r),r.placeholders===!0&&(o=Q_(o)),o}var UL=()=>{},KL=({index:e,selected:t,suggestion:n,onFeedback:r})=>{let o=M("inlineSuggestions"),i=R(wi),s=U(),a=k("TextSuggestion",eC),l=(0,zi.useRef)(null);(0,zi.useEffect)(()=>{let c=setTimeout(()=>{s(u_({text:n.text,suggestion:n}))},500);return()=>{clearTimeout(c)}},[n]),J1(l,"click",()=>{s(br(e)),s(zt({suggestion:n,text:n.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let u=(0,zi.useMemo)(()=>zL(n.text,n.source,i,{stripAgentPart:o,placeholders:!0,searchKeywords:n.searchKeywords}),[o,n.text,n.source,i,n.searchKeywords]);return n.source==="gpt"&&!o?null:(0,Co.jsxs)("div",{className:a.root,onMouseEnter:()=>s(br(e)),children:[(0,Co.jsx)(Q,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:t,onClick:UL,children:(0,Co.jsx)(Pn,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:u})}),t&&r&&(0,Co.jsx)("div",{className:a.actions,children:(0,Co.jsx)(ed,{onFeedback:()=>r(n),suggestion:n.text})})]})},tC=KL;var uh=S(C()),VL=({onFeedback:e,suggestions:t,selectedIndex:n,reverse:r})=>{let o=(0,gd.useMemo)(()=>{let i=t.map((s,a)=>(0,uh.jsx)(tC,{index:a,selected:a===n,suggestion:s,onFeedback:e},`${s.text}-${s.source}`));return r?i.reverse():i},[t,n,r]);return(0,uh.jsx)(gd.Fragment,{children:o})},hd=VL;var nC={root:"_root_otdbu_1",paper:"_paper_otdbu_11"};var Ua=S(C()),WL=({textSuggestions:e,selectedIndex:t})=>{let n=(0,yd.useRef)(null),r=k("InlineSuggestionsOverlay",nC),o=R(Bi),i=U(),s=R(Xe),a=R(_i),l=R(cd),u=M("showTextSuggestions");return Pi(()=>{setTimeout(()=>{i(Rr({collapse:!0,skipWhenInputFocus:!0}))})}),(0,yd.useEffect)(()=>{let c=n.current;if(!c||!c.parentElement)return;c.parentElement.style.left="0px";let p=c.getBoundingClientRect();c.parentElement.style.left=`${Math.min(window.innerWidth-4-p.right,0)}px`}),l||!o||!u||e.length===0||s!==!0||a===!1?null:(0,Ua.jsx)("div",{className:r.root,"data-variant":"inline",children:(0,Ua.jsx)("div",{ref:n,className:r.paper,children:(0,Ua.jsx)(ut,{children:(0,Ua.jsx)(hd,{suggestions:e,selectedIndex:t})})})})},$L=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),rC=Cn($L)(WL);var Ka=S(C()),qL=({children:e})=>{let n=M("locale").replace("-","");return(0,Ka.jsx)(hg.Provider,{value:n,children:e})},GL=({store:e,customStyles:t={},children:n})=>(0,Ka.jsx)(Ym,{store:e,children:(0,Ka.jsx)(qL,{children:(0,Ka.jsx)(Ji.Provider,{value:t,children:n})})}),bo=GL;var Sd=S(q()),Ui=S(O());var oC=S(O());function iC(e,t){let[n,r]=(0,oC.useState)(()=>{if(typeof window>"u")return t;try{let i=window.localStorage.getItem(e);return i?JSON.parse(i):t}catch(i){return j.error(i),t}});return[n,i=>{try{let s=i instanceof Function?i(n):i;r(s),typeof window<"u"&&window.localStorage.setItem(e,JSON.stringify(s))}catch(s){j.error(s)}}]}var aC=S(q()),Bn=S(O());var ch={};Ee(ch,{enUS:()=>XL,nlNL:()=>QL});var XL={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"}]}]},QL={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 sC={root:"_root_1vfca_1",anchor:"_anchor_1vfca_6",anchorButton:"_anchorButton_1vfca_11"};var Or=S(C()),dh=(e,t,n)=>r=>(0,Or.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),YL=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r,onLogIn:o})=>{let i=H(ch),s=At(),a=k("Login",sC),l=M("productName"),u=(0,Bn.useCallback)(m=>{m.preventDefault(),r&&r(parseInt(m.target.value,10))},[]),c=(0,Bn.useCallback)(m=>{m.preventDefault(),s.send(Di,!0)},[t]),p=(0,Bn.useMemo)(()=>m=>(0,Or.jsx)("a",{onClick:h=>{h.preventDefault(),o()},href:t,className:a.anchor,target:"_blank",rel:"noreferrer",children:m},"login"),[t]),d=(0,Bn.useCallback)(m=>(0,Or.jsx)("button",{type:"button",className:a.anchorButton,onClick:c,children:m},"prompt"),[c]),{min:f,hour:y,day:v}=(0,Bn.useMemo)(()=>({min:dh(a,60*10,u),hour:dh(a,60*60,u),day:dh(a,60*60*12,u)}),[]);return(0,Or.jsxs)("div",{className:(0,aC.default)(e,a.root),children:[i("loginPlease",{login:n?d:p,productName:l}),r&&(0,Or.jsxs)(Bn.Fragment,{children:[(0,Or.jsx)("br",{}),i("snooze",{min:f,hour:y,day:v})]})]})},vd=YL;var lC={root:"_root_1g8fi_1",text:"_text_1g8fi_19"};var Va=S(C()),ZL=({title:e})=>{let t=k("SearchTrigger",lC),n=U();return(0,Va.jsxs)("button",{type:"button",className:t.root,onClick:()=>n(qe(!0)),children:[(0,Va.jsx)(Ai,{}),(0,Va.jsx)("span",{className:t.text,children:e})]})},uC=ZL;var ph={};Ee(ph,{enUS:()=>JL,nlNL:()=>eA});var JL={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"}]},eA={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 cC={root:"_root_onpov_1",isInline:"_isInline_onpov_14",toggleButton:"_toggleButton_onpov_21",toggleButtonWrapper:"_toggleButtonWrapper_onpov_25",toggleButtonWrapperHidden:"_toggleButtonWrapperHidden_onpov_32",isCollapsed:"_isCollapsed_onpov_36",collapsible:"_collapsible_onpov_36",hints:"_hints_onpov_44",hintsHidden:"_hintsHidden_onpov_51",triggers:"_triggers_onpov_56",triggersRight:"_triggersRight_onpov_71"};var pe=S(C()),tA=({textSuggestions:e,selectedIndex:t,onLogIn:n})=>{let r=k("SuggestionsOverlay",cC),o=H(ph),i=R(Bi),s=o_(),a=U(),l=(0,Ui.useRef)(null),u=M("searchTriggerKey"),c=M("productName"),p=R(cd),d=R(Xe),f=R(_i),[y,v]=(0,Ui.useState)(null),m=M("showSearch"),g=M("showTextSuggestions"),h=M("adminUrl"),x=M("isEmbedded"),[_,w]=iC("dd-snooze-until-ms",0),b=p||_>Date.now(),E=R(N=>N.input.text),P=e.filter(N=>N.source!=="gpt").length,I=()=>{b&&w(0),a(Kw(!b))},z=N=>{a(ze({name:"suggestion feedback",data:{text:N.text,source:"overlay",context:E},options:{includeConversationData:!0}}))},V=N=>{let le=Date.now()+N*1e3;w(le),j.info(`Snooze until: ${new Date(le)}`),a(Rr({collapse:!0}))};return(0,Ui.useEffect)(()=>{P===0&&v(null)},[e,P]),Pi(()=>{a(Rr({collapse:!0,skipWhenInputFocus:!0}))}),d===null||f===!1?null:d===!1?(0,pe.jsxs)("div",{ref:l,className:(0,Sd.default)(r.root,{[r.isCollapsed]:b}),children:[!b&&(0,pe.jsxs)("div",{className:r.triggers,children:[(0,pe.jsx)("div",{style:{flex:1}}),(0,pe.jsx)("div",{className:r.triggersRight,children:(0,pe.jsx)(zr,{className:r.toggleButton,title:o("collapse"),onClick:I,isCollapsed:!1})})]}),(0,pe.jsx)("div",{className:r.toggleButtonWrapper,children:(0,pe.jsx)(zr,{className:r.toggleButton,title:o("open",{productName:c}),onClick:I,isCollapsed:!0})}),(0,pe.jsx)("div",{className:r.collapsible,children:(0,pe.jsx)(vd,{loginUrl:h,isEmbedded:x,onLogIn:n,onSnooze:V})})]}):!s||!i?null:(0,pe.jsxs)("div",{ref:l,className:(0,Sd.default)(r.root,{[r.isCollapsed]:b}),children:[!b&&(0,pe.jsxs)("div",{className:r.triggers,children:[(0,pe.jsx)("div",{style:{flex:1},children:m&&(0,pe.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>v(o(id()?"searchHintMac":"searchHintWindows",{searchTriggerKey:u.toUpperCase()})),onMouseLeave:()=>v(null),children:(0,pe.jsx)(uC,{title:o("search")})})}),(0,pe.jsxs)("div",{className:r.triggersRight,onFocus:()=>{},children:[(0,pe.jsx)("div",{className:(0,Sd.default)(!y&&r.hintsHidden,r.hints),children:y}),(0,pe.jsx)(zr,{className:r.toggleButton,title:o("collapse"),onClick:I,isCollapsed:!1})]})]}),(0,pe.jsx)("div",{className:r.toggleButtonWrapper,children:(0,pe.jsx)(zr,{className:r.toggleButton,title:o("open",{productName:c}),onClick:I,isCollapsed:!0})}),P>0&&g&&(0,pe.jsx)("div",{className:r.collapsible,onFocus:()=>{},children:(0,pe.jsx)(ut,{children:(0,pe.jsx)(hd,{onFeedback:z,suggestions:e,selectedIndex:t,reverse:!0})})})]})},nA=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),dC=Cn(nA)(tA);var Ad=S(q());var Kn=S(O());var pC=S(O()),rA=["div","span","mark","strong","b","i","u","em"];function fh(e,t,n=0){var i;let r=e[e.length-1],o=typeof r=="object"&&r!==null?(i=r.props)==null?void 0:i.tagName:void 0;if(o==="br")return e.pop(),[...e,...t,r];if(rA.includes(o)){let s=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,pC.cloneElement)(r,{children:fh(s,t,n+1)})]}return[...e,...t]}function Nr(e){return e.tagName.toLowerCase()==="textarea"}var fC={root:"_root_81non_1",container:"_container_81non_3",agentText:"_agentText_81non_5",tabText:"_tabText_81non_6",hint:"_hint_81non_6",matchSelection:"_matchSelection_81non_10",focus:"_focus_81non_16",resetIndent:"_resetIndent_81non_20",matchKeyword:"_matchKeyword_81non_24",matchPlaceholder:"_matchPlaceholder_81non_25",hover:"_hover_81non_31",hintText:"_hintText_81non_64",popover:"_popover_81non_72",popoverRoot:"_popoverRoot_81non_77",popoverContentContainer:"_popoverContentContainer_81non_81",popoverContent:"_popoverContent_81non_81",selectionOptions:"_selectionOptions_81non_107",selectionOptionsIsHidden:"_selectionOptionsIsHidden_81non_112",selectionOptionsButton:"_selectionOptionsButton_81non_116",caret:"_caret_81non_132",popoverSuggestionsRoot:"_popoverSuggestionsRoot_81non_136",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_81non_141"};var wC=S(q());var Pd=S(O());function mC(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function xd(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function gC(e){return e!=null}var gh=S(q()),Ot=S(O());var _d=S(O()),oA=["bottom","height","left","right","top","width"],iA=(e={},t={})=>oA.some(n=>e[n]!==t[n]),zn=new Map,hC,yC=()=>{let e=[],t=[];zn.forEach((n,r)=>{if(r instanceof Element&&!r.isConnected){t.push(r);return}let o=r.getBoundingClientRect();iA(o,n.rect)&&(n.rect=o,e.push(n))}),t.forEach(n=>{zn.delete(n)}),e.forEach(n=>{n.callbacks.forEach(r=>r(n.rect))}),hC=window.requestAnimationFrame(yC)};function sA(e,t){return{observe(){let n=zn.size===0;if(zn.has(e)){let r=zn.get(e);r.callbacks.push(t),r.rect&&t(r.rect)}else zn.set(e,{rect:void 0,hasRectChanged:!1,callbacks:[t]});n&&yC()},unobserve(){let n=zn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||zn.delete(e),zn.size||cancelAnimationFrame(hC)}}}}function mh(e){let[t,n]=(0,_d.useState)(null);return(0,_d.useLayoutEffect)(()=>{if(!e.current)return;let r=sA(e.current,o=>{n(o)});return r.observe(),()=>{r.unobserve()}},[e]),t}var Ki=S(O()),SC=S(ku());var vC={root:"_root_1jq08_1"};var xC=({children:e})=>{let[t,n]=(0,Ki.useState)(null),r=(0,Ki.useContext)(Ji);return(0,Ki.useLayoutEffect)(()=>{let o=document.createElement("div");return uo(o),o.classList.add(vC.root),r!=null&&r.portalRootNode&&o.classList.add(r==null?void 0:r.portalRootNode),document.body.appendChild(o),n(o),()=>{o.isConnected&&document.body.removeChild(o)}},[]),t?(0,SC.createPortal)(e,t):null};var cn={ref:"_ref_1rcyi_1",root:"_root_1rcyi_7",positionAbove:"_positionAbove_1rcyi_13",positionBelow:"_positionBelow_1rcyi_17",positionLeft:"_positionLeft_1rcyi_21",positionRight:"_positionRight_1rcyi_25",alignStart:"_alignStart_1rcyi_29",alignCenter:"_alignCenter_1rcyi_34",alignEnd:"_alignEnd_1rcyi_40"};var wd=S(C()),Cd=(e=!1)=>{let[t,n]=(0,Ot.useState)(e),r=(0,Ot.useCallback)(()=>n(!0),[]),o=(0,Ot.useCallback)(()=>n(!1),[]),i=(0,Ot.useCallback)(()=>n(a=>!a),[]),s=(0,Ot.useRef)(null);return{opened:t,open:r,close:o,toggle:i,triggerRef:s}};function hh(e,t=null,n=0){if(!e)return{display:"none"};let r=t?e.top-t.top<0||e.top<t.top-n?t.top-n:e.top+e.height>t.top+t.height+n?t.top+t.height+n-e.height:e.top:e.top,o=t?e.left<t.left-n?t.left-n:e.left+e.width>t.left+t.width+n?t.left+t.width+n-e.width:e.left:e.left;return{top:r,left:o,height:e.height,width:e.width}}var bd=({className:e,triggerRef:t,boundaryRef:n=(0,Ot.createRef)(),position:r="above",align:o="center",children:i,toStyle:s=hh,...a})=>{let l=mh(t),u=mh(n),c=(0,Ot.useMemo)(()=>s(l,u,0),[l,u]);return(0,wd.jsx)(xC,{children:(0,wd.jsx)("div",{className:(0,gh.default)(cn.ref,{[cn.positionAbove]:r==="above",[cn.positionBelow]:r==="below",[cn.positionLeft]:r==="left",[cn.positionRight]:r==="right",[cn.alignStart]:o==="start",[cn.alignCenter]:o==="center",[cn.alignEnd]:o==="end"}),style:c,...a,role:"dialog",children:(0,wd.jsx)("div",{className:(0,gh.default)(e,cn.root),children:i})})})};var _C=S(q()),Ed=S(O());var yh=S(C()),Td=(0,Ed.forwardRef)(({className:e,children:t,...n},r)=>{let o=(0,Ed.useRef)(null),i=k("TabCompletion",In);return(0,yh.jsx)("div",{ref:xd([o,r]),className:(0,_C.default)(e,i.popoverContentContainer),...n,children:(0,yh.jsx)("div",{className:i.popoverContent,children:t})})});var Mr=S(C()),aA=e=>t=>{let n=hh(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},lA=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let i=k("TabCompletion",In),s=Cd(),a=(0,Pd.useMemo)(()=>aA(e.getBoundingClientRect()),[e]),[l,u]=$c(e);return(0,Pd.useEffect)(()=>{u?s.open():s.close()},[u]),(0,Mr.jsxs)("span",{children:[(0,Mr.jsx)("mark",{ref:xd([l,s.triggerRef]),className:(0,wC.default)(i.matchKeyword,{[i.hover]:u}),"aria-haspopup":"dialog","aria-expanded":s.opened?"true":"false",children:r}),s.opened&&(0,Mr.jsx)(bd,{className:i.popover,triggerRef:s.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,Mr.jsx)(Td,{style:n,children:(0,Mr.jsx)("div",{className:i.hintText,children:o})})})]})},kd=class extends Tn{keywordMatches=[];preparedKeywordMatches=[];usedKeywordMatches=new Set;onBeforeParse(t,n){return n.keywordMatches&&n.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=n.keywordMatches.map(r=>({...r,keywordRegex:new RegExp(`\\b${mC(r.keyword)}\\b`,"i")})),this.keywordMatches=n.keywordMatches),this.usedKeywordMatches.clear(),t}match(t){let n=this.preparedKeywordMatches.map(o=>{if(this.usedKeywordMatches.has(o))return null;let i=t.match(o.keywordRegex);if(!i)return null;let s=t.charAt(i.index-1),a=t.charAt(i.index+o.keyword.length);return s==="{"&&a==="}"?null:{index:i.index,length:i[0].length,match:i[0],matchString:i[0],suggestion:o.suggestion,preparedKeywordMatch:o,valid:!0}}).filter(gC);if(n.length===0)return null;let r=n.reduce((o,i)=>i.index<o.index?i:o);return this.usedKeywordMatches.add(r.preparedKeywordMatch),r}replaceWith(t,n){return(0,Mr.jsx)(lA,{inputElement:n.inputElement,suggestion:n.suggestion,inputStyle:n.inputStyle,boundaryRef:n.boundaryRef,children:t},`keyword_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var Rd=S(q());var Ze=S(O());var vh=S(C()),CC=()=>(0,vh.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,vh.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 Dr=S(O());var EC=S(nh());var bC={root:"_root_1muu8_1",content:"_content_1muu8_7"};function Id(e,t,n){var o;let r=((o=e.imageSizes)==null?void 0:o[t])||e.image||n;if(!r)return null;try{return new URL(r).toString()}catch{return null}}function Sh(e){return e.replace("https://www.","").replace("https://","")}var Nt=S(C()),uA=3,cA=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),dA=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=uA})=>{let i=k("LinkSearch",bC),[s,a]=(0,Dr.useState)(""),l=U(),u=R(ld("url")),c=R(Sw("URL",cA)),[p,d]=(0,Dr.useState)(c.length-1),f=M("fallbackImage"),y=h=>{let x=h.target;a(x.value)},v=(h,x)=>{h.stopPropagation(),h.preventDefault(),window.open(x,"_blank")},m=h=>{var w;let x=p-1<0?c.length-1:p-1,_=p+1===c.length?0:p+1;h.code==="Escape"&&(a(""),t()),h.code==="ArrowUp"&&d(x),h.code==="ArrowDown"&&d(_),h.code==="Enter"&&e(((w=c[p])==null?void 0:w.text)||s)},g=(0,Dr.useCallback)((0,EC.default)(h=>{l(yo({query:h,type:"URL",tags:["link-search"]}))},300),[]);return(0,Dr.useEffect)(()=>{s&&g(s)},[s]),(0,Dr.useEffect)(()=>()=>{l(rd())},[]),(0,Nt.jsxs)("div",{className:i.root,children:[(0,Nt.jsx)(ut,{withDivider:!0,children:(s?c:u).slice(0,o).map((h,x)=>(0,Nt.jsx)(Q,{selected:p===x,onClick:()=>e(h.text),"data-testid":"linksearch-suggestion",children:(0,Nt.jsxs)(oe,{children:[(0,Nt.jsx)(oe.Image,{src:Id(h,"small",f||void 0),title:h.title||h.text}),(0,Nt.jsxs)(oe.Content,{className:i.content,cropText:!0,children:[(0,Nt.jsx)(oe.Title,{children:h.title||Sh(h.text)}),h.title&&Sh(h.text)]}),(0,Nt.jsx)(Q.Actions,{children:(0,Nt.jsx)(Q.ActionButton,{label:r,onClick:_=>v(_,h.text)})})]})},h.text))}),(0,Nt.jsx)(Na,{value:s,onChange:y,autoFocus:!0,placeholder:n,onKeyUp:m})]})},TC=dA;var xh={};Ee(xh,{enUS:()=>pA,nlNL:()=>fA});var pA={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},fA={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var Ye=S(C()),mA=(0,Ze.forwardRef)((e,t)=>{let n=k("TabCompletion",In);return(0,Ye.jsx)("mark",{ref:t,className:(0,Rd.default)(n.matchSelection)},"selection-start")}),gA=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let i=H(xh),s=k("TabCompletion",In),a=(0,Ze.useRef)(null),l=(0,Ze.useRef)(null),[u,c]=(0,Ze.useState)(null),p=U(),d=Cd(document.activeElement===r),[f]=(0,Ze.useState)(()=>document.createRange());d.triggerRef.current=f,(0,Ze.useEffect)(()=>()=>f.detach(),[]),(0,Ze.useEffect)(()=>{let v=e.current,m=a.current;!v||!m||(f.setStart(v,0),f.setEnd(m,0))},[e.current,a.current]),Pi(()=>{d.close()});let y=(0,Ze.useCallback)(v=>{let m=f.toString(),g=/^http(s?):\/\//.test(v)?v:`https://${v}`;p(Sc({text:`[${m}](${g})`,replace:"selection"}))},[]);return(0,Ye.jsxs)("span",{children:[(0,Ye.jsx)("mark",{ref:a,className:(0,Rd.default)(s.matchSelection),"aria-haspopup":"dialog","aria-expanded":d.opened?"true":"false",children:o}),d.opened&&(0,Ye.jsx)(bd,{className:s.popoverRoot,triggerRef:d.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,Ye.jsxs)(Td,{style:n,ref:l,children:[(0,Ye.jsx)("div",{className:(0,Rd.default)(s.selectionOptions,{[s.selectionOptionsIsHidden]:u!==null}),children:(0,Ye.jsxs)("button",{type:"button",tabIndex:u===null?-1:void 0,className:s.selectionOptionsButton,onClick:()=>c("insertLink"),children:[(0,Ye.jsx)(CC,{}),(0,Ye.jsx)("span",{children:"\xA0"}),(0,Ye.jsx)("span",{children:i("insertLink")})]})}),u==="insertLink"&&(0,Ye.jsx)(TC,{placeholder:i("linkInputPlaceholder"),visitUrlText:i("visitUrl"),onSelectLink:y,onDismiss:()=>{c(null),d.close()}})]})})]},"selection-end")},Ld=class extends Tn{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(t,n){return this.props=n,this.charCount=0,this.startRef=(0,Ze.createRef)(),this.foundIndex=0,t}match(t){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[n,r]=this.props.selection;if(n===r)return null;let o=this.foundIndex===0?n:r,i=o>=this.charCount&&o<=this.charCount+t.length?{index:o-this.charCount,length:0,match:"",valid:!0}:null;i&&this.foundIndex++;let s=this.foundIndex===1;return i&&s?this.charCount+=o-this.charCount:this.charCount+=t.length,i?{isStart:s,...i}:null}replaceWith(t,n){return n.isStart?(0,Ye.jsx)(mA,{ref:this.startRef}):(0,Ye.jsx)(gA,{inputElement:n.inputElement,startRef:this.startRef,boundaryRef:n.boundaryRef,inputStyle:n.inputStyle})}asTag(){return"mark"}};var Un=S(C()),hA=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:i,keywordMatches:s,inputElement:a,source:l})=>{let u=k("TabCompletion",fC),c=M("insertLink"),p=M("showMidSentenceSuggestions"),d=M("inlineSuggestions"),f=Gc(a),y=(0,Kn.useRef)(null),v=R(Xe);(0,Kn.useEffect)(()=>{Nr(a)&&f&&Xc(a,f)},[f]);let m=(0,Kn.useCallback)(x=>{if(!o||!n)return x;let _=[(0,Un.jsx)("span",{className:u.resetIndent,children:"\u200B"},"u200B"),(0,Un.jsx)("span",{"data-testid":"tab-completion",className:(0,Ad.default)(u.tabText,u.resetIndent),"data-source":l,children:n},"tabText")];return r&&_.push((0,Un.jsx)("span",{className:(0,Ad.default)(u.hint,u.resetIndent),children:(0,Un.jsx)(dl,{keyCode:"tab"},"tabHint")})),fh(x,_)},[o,n,r]),g=(0,Kn.useMemo)(()=>{let x=[];return c&&x.push(new Ld("selection")),x.push(new Ti("placeholders")),i&&x.push(new kd("keywords")),x},[d,c,i]),h=(0,Kn.useMemo)(()=>{let x=window.getComputedStyle(a);return{"--dd-color":x.color,"--dd-font-size":x.fontSize,"--dd-font-family":x.fontFamily,"--dd-font-variant":x.fontVariant}},[]);return!e||!v?null:(0,Un.jsxs)("div",{ref:x=>{x!=null&&x.parentElement&&(y.current=x==null?void 0:x.parentElement)},className:u.root,style:h,children:[(0,Un.jsx)(Pn,{tagName:"span",containerTagName:"div",className:(0,Ad.default)(u.container,u.agentText),disableLineBreaks:Nr(a),content:t||"\u200B",onAfterParse:m,matchers:g,selection:f,keywordMatches:s,inputElement:a,inputStyle:h,boundaryRef:y,inlineSuggestionsOnlyAtEnd:!p}),(0,Un.jsx)("br",{})]})},yA=({input:e,ui:t,settings:n,styleSuggestions:r,conversation:o})=>{var v;let{tabCompletionSuggestion:i}=e,s=(i==null?void 0:i.text)||"",a=(i==null?void 0:i.source)||"",l=e.html??Ri(e.text),u=s.indexOf(e.text)===0?s.slice(e.text.length):"",{showTabHint:c}=t,{isSupported:p}=o,{showTabCompletion:d,visible:f,showStyleSuggestions:y}=n;return{showTabHint:c,showStyleSuggestions:y,showTabCompletion:d,content:l,tabText:u,source:a,keywordMatches:((v=r.list)==null?void 0:v.keywordMatches)??[],enabled:f&&p!==!1}},kC=Cn(yA)(hA);var yb=S(q()),vb=S(O());var PC={list:[],fetchState:"idle",isInitialRequest:null},RC=e=>e.autoflows.list||[],IC=e=>t=>{var n;return(n=t.list)==null?void 0:n.find(r=>r.triggerPayload===e)},Vn=D("autoflows/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getAutoflows(e)}),_h=D("autoflows/start",async(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");await r.startAutoflowSession(e),await n(Vn(e.platformSessionId))}),wh=D("autoflows/stop",async(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");await r.stopAutoflowSession(e.platformSessionId),await n(Vn(e.platformSessionId))}),vA=B({name:"autoflows",initialState:PC,reducers:{},extraReducers:e=>{e.addCase(_h.pending,(t,n)=>{let r=IC(n.meta.arg.triggerPayload)(t);r.state="Started",r.isBusy=!0}),e.addCase(wh.pending,(t,n)=>{let r=IC(n.meta.arg.triggerPayload)(t);r.state="Aborted",r.isBusy=!0}),e.addCase(Vn.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}),e.addCase(Vn.rejected,t=>{t.fetchState="error"}),e.addCase(Vn.fulfilled,(t,n)=>{t.list=n.payload,t.fetchState="done"}),e.addCase(J,()=>PC)}}),LC=D("autoflows/openStream",(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");let o=r.openStream(e);o.on("sessionAborted",()=>{n(Vn(e))}),o.on("sessionCompleted",()=>{n(Vn(e))})}),AC=D("autoflows/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),OC=vA.reducer;var NC={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},MC=e=>e.customMessages.list,DC=e=>t=>!!t.customMessages.sentSuggestions.find(n=>n===e),FC=e=>t=>!!t.customMessages.answeredSuggestions.find(n=>n===e),jC=e=>t=>!!t.customMessages.errorSuggestions.find(n=>n===e),Wa=D("customMessages/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getCustomMessages(e)}),Od=D("customMessages/send",async(e,t)=>{let{platformSessionId:n,suggestion:r}=e,{deepdeskBrokerAPI:o}=t.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.sendCustomMessage(n,r)}),Nd=D("customMessages/answer",async(e,t)=>{let{platformSessionId:n,reply:r}=e,{deepdeskBrokerAPI:o}=t.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.answerCustomMessage(n,r)}),HC=B({name:"customMessages",initialState:NC,reducers:{onCustomMessage(e,t){Array.isArray(t.payload)?e.list=t.payload:e.list=[t.payload]}},extraReducers:e=>{e.addCase(Wa.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(Wa.rejected,t=>{t.fetchState="error"}).addCase(Wa.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload||[]}).addCase(Od.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.errorSuggestions=t.errorSuggestions.filter(r=>n.meta.arg.suggestion.text!==r)}).addCase(Od.rejected,(t,n)=>{let r=t.sentSuggestions.indexOf(n.meta.arg.suggestion.text);t.errorSuggestions.push(...t.sentSuggestions.splice(r,1))}).addCase(Nd.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.answeredSuggestions.push(n.meta.arg.suggestion.text)}).addCase(Nd.rejected,(t,n)=>{let r=t.answeredSuggestions.indexOf(n.meta.arg.suggestion.text);t.errorSuggestions.push(...t.sentSuggestions.splice(r,1)),t.answeredSuggestions.splice(r,1)}).addCase(J,()=>NC)}}),BC=D("customMessages/openStream",(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");r.openStream(e).on("customMessageSuggestion",i=>{n(HC.actions.onCustomMessage(i))})}),zC=D("customMessages/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),UC=HC.reducer;var SA={token:null,accountUrl:null,interval:null},KC=e=>t=>{let{passwordlessToken:{token:n,accountUrl:r}}=t;return n&&r?`${r}/apis/admin/session/passwordless/login/?token=${n}&redirect=${e}`:null},Ch=D("passwordlessToken/getTemporaryPasswordlessToken",async(e,t)=>{let{deepdeskAPI:n}=t.extra,r=await n.requestPasswordlessToken();return{accountUrl:n.client.baseUrl,token:r}}),bh=D("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(Ch()),setInterval(()=>r(Ch()),n)}),VC=B({name:"passwordlessToken",initialState:SA,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(Ch.fulfilled,(t,n)=>{t.token=n.payload.token,t.accountUrl=n.payload.accountUrl}),e.addCase(bh.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:WC}=VC.actions,$C=VC.reducer;function qC(e){let{customMessages:t,autoflows:n}=e;return n.fetchState==="loading"&&n.isInitialRequest===!0||t.fetchState==="loading"&&t.isInitialRequest===!0}var nb=S(O());var JC=S(q()),eb=S(O());var XC=S(q());var GC={root:"_root_838fd_1"};var YC=S(C()),xA=({className:e,children:t})=>{let n=k("Unicode",GC);return(0,YC.jsx)("span",{className:(0,XC.default)(e,n.root),children:t})},QC=xA;var ZC={isDisabled:"_isDisabled_1rmfm_1",buttonStart:"_buttonStart_1rmfm_5",root:"_root_1rmfm_8",buttonStop:"_buttonStop_1rmfm_8",stateBadge:"_stateBadge_1rmfm_19",isCompleted:"_isCompleted_1rmfm_26",isStarted:"_isStarted_1rmfm_30",isAborted:"_isAborted_1rmfm_34"};var Eh={};Ee(Eh,{enUS:()=>_A,nlNL:()=>wA});var _A={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"}]},wA={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 ht=S(C()),bA=({disabled:e,state:t,displayName:n,description:r,onStartAutoflow:o,onStopAutoflow:i})=>{let s=k("Autoflow",ZC),a=H(Eh),l=t==="Started"?"stop":"start",u=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return(0,ht.jsxs)(Q,{className:(0,JC.default)(s.root,{[s.isDisabled]:e,[s.isCompleted]:t==="Completed",[s.isAborted]:t==="Aborted",[s.isStarted]:t==="Started"}),children:[(0,ht.jsx)(oe,{children:(0,ht.jsxs)(oe.Content,{children:[(0,ht.jsxs)(oe.Title,{children:[t&&(0,ht.jsx)("span",{className:s.stateBadge,children:a(t)}),n]}),(0,ht.jsx)("span",{children:r})]})}),(0,ht.jsx)(Q.Actions,{fixed:t==="Started",children:(0,ht.jsx)(Q.ActionButton,{primary:!0,className:l==="start"?s.buttonStart:s.buttonStop,onClick:t==="Started"?i:o,disabled:e,label:(0,ht.jsxs)(eb.Fragment,{children:[(0,ht.jsx)(QC,{children:u})," ",(0,ht.jsx)("span",{children:a(l)})]})})})]})},tb=bA;var Th=S(C()),EA=(e,t)=>{let n=t.filter(r=>r.state==="Started");return n.length>0?n.indexOf(e)===-1:!1},TA=({autoflows:e,onStartAutoflow:t,onStopAutoflow:n,platformSessionId:r})=>(0,Th.jsx)(nb.Fragment,{children:e.map(o=>(0,Th.jsx)(tb,{displayName:o.displayName,description:o.description,disabled:o.isBusy||EA(o,e),state:o.state,onStartAutoflow:()=>t({platformSessionId:r,triggerPayload:o.triggerPayload}),onStopAutoflow:()=>n({platformSessionId:r,triggerPayload:o.triggerPayload})},o.displayName))}),kA=({autoflows:e,conversation:t})=>{var n;return{autoflows:e.list,platformSessionId:(n=t.current)==null?void 0:n.sessionId}},PA={onStartAutoflow:_h,onStopAutoflow:wh},rb=Cn(kA,PA)(TA);var ob=S(q()),kh=S(O());var Wn={root:"_root_1e6ej_1",title:"_title_1e6ej_8",isUsed:"_isUsed_1e6ej_13",quickReplies:"_quickReplies_1e6ej_22",quickReply:"_quickReply_1e6ej_29",hasError:"_hasError_1e6ej_39",label:"_label_1e6ej_43",errorIcon:"_errorIcon_1e6ej_48"};var at=S(C()),IA=({suggestion:e})=>{let t=H(go),n=U(),r=R(DC(e.text)),o=R(FC(e.text)),i=R(jC(e.text)),s=R(dc),{replyOptions:a}=e,l=(0,kh.useCallback)(c=>{c.preventDefault(),c.stopPropagation(),!(r||!s)&&n(Od({platformSessionId:s,suggestion:e}))},[e,r,n,s]),u=(0,kh.useCallback)(c=>{if(c.preventDefault(),c.stopPropagation(),!s||!a)return;let p=parseInt(c.target.dataset.index,10),d=a[p];n(Nd({platformSessionId:s,reply:d,suggestion:e}))},[e,r,n,s]);return(0,at.jsxs)(Q,{onClick:l,className:(0,ob.default)(Wn.root,{[Wn.isUsed]:r,[Wn.hasError]:i}),children:[(0,at.jsx)(oe,{children:(0,at.jsxs)(oe.Content,{children:[(0,at.jsxs)(oe.Title,{className:Wn.title,children:[e.text," ",(0,at.jsx)(pl,{className:Wn.label,children:"analyse tool"})," ",i&&(0,at.jsx)("span",{className:Wn.errorIcon,role:"img","aria-label":t("sendingError"),title:t("sendingError"),children:"!"})]}),a&&a.length>0&&(0,at.jsx)("ul",{className:Wn.quickReplies,children:a.map(c=>(0,at.jsx)("li",{className:Wn.quickReply,children:c.title},c.title))})]})}),(0,at.jsxs)(Q.Actions,{fixed:i||r,children:[a&&a.length>0&&(0,at.jsx)(Q.DropdownButton,{label:t("answer"),disabled:o,children:a.map((c,p)=>(0,at.jsx)(Q.DropdownItem,{index:p,label:c.title,onClick:u},c.title))}),(0,at.jsx)(Q.ActionButton,{primary:!0,disabled:r,onClick:l,label:t(r?"suggestionSent":i?"tryAgain":"sendSuggestion")})]})]})},ib=IA;var Md=S(O());var Rh=S(q());var Ph=S(C()),Ih=()=>(0,Ph.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,Ph.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 sb={root:"_root_rjdyr_1",entity:"_entity_rjdyr_10",entityText:"_entityText_rjdyr_46",iconWrapper:"_iconWrapper_rjdyr_53",icon:"_icon_rjdyr_53",iconClicked:"_iconClicked_rjdyr_67"};var dn=S(C()),RA=({entities:e})=>{let t=k("EntitiesWidgetList",sb),[n,r]=(0,Md.useState)(void 0),o=U(),i=()=>{r(void 0)},s=a=>{e&&(r(e.indexOf(a)),Da(a.text),o(ze({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,Md.useEffect)(()=>{let a=setTimeout(i,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,dn.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,dn.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>s(a),children:[(0,dn.jsx)("span",{className:t.entityText,children:a.text}),(0,dn.jsxs)("span",{className:t.iconWrapper,children:[(0,dn.jsx)("span",{className:(0,Rh.default)(t.icon),children:(0,dn.jsx)(Ih,{})}),(0,dn.jsx)("span",{className:(0,Rh.default)(t.icon,n===l&&t.iconClicked),children:(0,dn.jsx)(Ih,{})})]})]},a.text))})},ab=RA;var Lh=S(C()),lb=()=>(0,Lh.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,Lh.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 Ah=S(C()),ub=()=>(0,Ah.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Ah.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 Oh=S(C()),cb=()=>(0,Oh.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Oh.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 Dd=S(O());var Nh={};Ee(Nh,{enUS:()=>LA,nlNL:()=>AA});var LA={copyCue:[{type:0,value:"Copy"}],copiedCue:[{type:0,value:"Copied!"}],removeCue:[{type:0,value:"Close"}]},AA={copyCue:[{type:0,value:"Kopieer"}],copiedCue:[{type:0,value:"Gekopieerd!"}],removeCue:[{type:0,value:"Sluiten"}]};var $n=S(C()),OA=({cue:e,onRemove:t,onCopy:n})=>{let r=H(Nh),[o,i]=(0,Dd.useState)(!1),s=l=>{l.preventDefault(),l.stopPropagation(),n&&(n(e.text),i(!0))},a=l=>{l.preventDefault(),l.stopPropagation(),t&&t(e.id)};return(0,Dd.useEffect)(()=>{if(!o)return;let l=setTimeout(()=>{i(!1)},1e3);return()=>{clearTimeout(l)}},[o]),(0,$n.jsx)(Q,{"data-testid":"cue",children:(0,$n.jsxs)(oe,{children:[(0,$n.jsxs)(oe.Content,{children:[e.title&&(0,$n.jsx)(oe.Title,{"data-testid":"widget-cue-title",children:e.title}),e.text]}),(0,$n.jsx)(Q.Actions,{children:n&&(0,$n.jsx)(Q.ActionButton,{primary:!0,onClick:s,label:r(o?"copiedCue":"copyCue")})}),(0,$n.jsx)(oe.CloseIcon,{title:r("removeCue"),onClick:a})]})})},db=OA;var $a=S(C()),NA=({cues:e,onCopyCue:t,onRemoveCue:n})=>(0,$a.jsx)($a.Fragment,{children:e.map(r=>(0,$a.jsx)(db,{cue:r,onRemove:n,onCopy:t},`${r.id}_${r.timestamp}`))}),pb=NA;var fb=S(O());var yt=S(C()),MA=({suggestion:e,lines:t,onEdit:n,onUse:r})=>{var d;let o=e.text||e.url||e.message,i=od(o),s=H(go),a=M("showImages"),l=M("fallbackImage"),u=f=>{f.preventDefault(),f.stopPropagation(),r(o)},c=f=>{f.preventDefault(),f.stopPropagation(),n(e)},p=(0,fb.useCallback)(f=>{window.open(i,"_blank"),f.stopPropagation(),f.preventDefault()},[i]);return(0,yt.jsxs)(Q,{onClick:u,"data-testid":"edit-suggestion",children:[(0,yt.jsxs)(oe,{children:[a&&e.image&&(0,yt.jsx)(oe.Image,{src:Id(e,"small",l||void 0),title:e.title}),(0,yt.jsxs)(oe.Content,{children:[e.title&&(0,yt.jsx)(oe.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((d=e.searchKeywords)==null?void 0:d.length)>0&&(0,yt.jsx)(Q.Labels,{labels:e.searchKeywords}),(0,yt.jsx)(oe.Content,{cropText:t==="single",lineClamp:t==="multiple",children:o})]})]}),(0,yt.jsxs)(Q.Actions,{children:[i&&(0,yt.jsx)(Q.ActionButton,{onClick:p,label:s("visitUrl")}),(0,yt.jsx)(Q.ActionButton,{primary:!0,onClick:c,label:s("preview")}),(0,yt.jsx)(Q.ActionButton,{primary:!0,onClick:u,label:s("useSuggestion")})]})]})},mb=MA;var qa=S(C()),DA=({contentType:e,lines:t,suggestions:n})=>{let r=At(),o=R(Ir),i=a=>{r.send(Xg,{state:o,suggestion:a,contentType:e})},s=(a,l)=>{r.send(Fn,{text:a,suggestion:{...l,source:l.source,sourceText:l.text}})};return(0,qa.jsx)(qa.Fragment,{children:n.map(a=>(0,qa.jsx)(mb,{suggestion:a,lines:t,onEdit:l=>i(l),onUse:l=>s(l,a)},a.text||a.url||a.message))})},gb=DA;var Mh={};Ee(Mh,{enUS:()=>FA,nlNL:()=>jA});var FA={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"}]},jA={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 hb={root:"_root_x0pwe_1",loginText:"_loginText_x0pwe_7",stateText:"_stateText_x0pwe_8",sectionList:"_sectionList_x0pwe_20",shortcutList:"_shortcutList_x0pwe_24",shortcut:"_shortcut_x0pwe_24",link:"_link_x0pwe_52"};var K=S(C()),Fd=(e,t)=>{let n=R(Xe);(0,vb.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},HA=({onLogIn:e})=>{let t=H(Mh),n=U(),r=M("isEmbedded"),o=k("Widget",hb),i=M("showAutoflows"),s=M("showCustomMessages"),a=M("showSummaryCommand"),l=M("showKnowledgeSearch"),u=M("showSearch"),c=R(Ar),p=R(fd),d=R(RC),f=R(e1),y=R(pd),v=R(MC),m=R(pc),g=R(_i),h=R(Xe),x=R(dc),_=R(qC),w=R(Ir),b=At(),E=R(Rw),P=R(KC("/admin/")),I=M("adminUrl"),z=M("productName");if(Fd(()=>(n(Wa(x)),n(BC(x)),()=>{n(zC(x))}),[n,g,s,x]),Fd(()=>(n(Vn(x)),n(LC(x)),()=>{n(AC(x))}),[n,g,i,x]),Fd(()=>{p.forEach(({type:N})=>{n(N==="entities"?qt():Wt(N))})},[n,g,m,c]),Fd(()=>(n(bh()),()=>{n(WC())}),[n]),g===!1)return(0,K.jsx)("div",{className:o.stateText,children:(0,K.jsx)("div",{children:(0,K.jsx)("p",{children:t("notSupported")})})},"supported");if(h===!1)return(0,K.jsx)("div",{className:o.loginText,children:(0,K.jsx)("div",{children:(0,K.jsx)(vd,{isEmbedded:r,loginUrl:I,onLogIn:e})})},"login");if(!c||!x||h===null||E||_)return(0,K.jsx)("div",{className:o.stateText,children:(0,K.jsx)("div",{children:(0,K.jsx)("p",{children:t("waiting")})})},"waiting");let V=u||a||l||P;return(0,K.jsx)("div",{className:(0,yb.default)(o.root),"data-testid":"widget",children:(0,K.jsxs)(fl,{className:o.sectionList,children:[V&&(0,K.jsx)(mn,{title:t("actions"),type:"shortcuts",children:(0,K.jsxs)("div",{className:o.shortcutList,children:[u&&(0,K.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-search",onClick:()=>b.send("ShowCommandPalette",{isOpen:!0}),children:[(0,K.jsx)(Ai,{}),t("linkSearch")]}),a&&(0,K.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-summary",onClick:()=>b.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,K.jsx)(cb,{}),t("linkSummary")]}),l&&(0,K.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>b.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,K.jsx)(ub,{}),t("linkKnowledgeSearch")]}),P&&(0,K.jsxs)("a",{className:o.shortcut,target:"_blank",href:P,"data-testid":"shortcut-studio-login",rel:"noreferrer",children:[(0,K.jsx)(lb,{}),t("linkStudioLogin",{productName:z})]})]})}),s&&v.length>0&&(0,K.jsx)(mn,{type:"custom-messages","data-testid":"custom-messages",children:(0,K.jsx)(ut,{withDivider:!0,children:v.map(N=>(0,K.jsx)(ib,{suggestion:N},N.text))})}),i&&d.length>0&&(0,K.jsx)(mn,{type:"autoflows",title:t("titleAutoflows"),"data-testid":"autoflows",children:(0,K.jsx)(ut,{withDivider:!0,children:(0,K.jsx)(rb,{})})}),p.map(({type:N,title:le,amount:qi,lines:Je})=>{var Gn;switch(N){case"entities":return y&&y.length>0&&(0,K.jsx)(mn,{type:N,title:le,"data-testid":`type-${N}`,children:(0,K.jsx)(ab,{entities:y})},N);case"cues":return f&&f.length>0&&(0,K.jsx)(mn,{type:N,title:le,"data-testid":`type-${N}`,children:(0,K.jsx)(ut,{withDivider:!0,children:(0,K.jsx)(pb,{cues:f,onRemoveCue:Qt=>n(n1({id:Qt}))})})},N);default:return((Gn=w[N])==null?void 0:Gn.fetchState)==="done"&&w[N].suggestions.length>0&&(0,K.jsx)(mn,{type:N,title:le,"data-testid":`type-${N}`,children:(0,K.jsx)(ut,{withDivider:!0,children:(0,K.jsx)(gb,{lines:Je,contentType:N,suggestions:w[N].suggestions.slice(0,qi)||[]})})},N)}})]})})},Sb=HA;function Vi(e){let t=new Range;return t.selectNodeContents(e),t}function xb(e,t,n){try{return Fr(e,t,n),!0}catch{return!1}}function jd(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function Hd(e){return"tagName"in e&&e.tagName==="BR"}var Ga=/[\u200B-\u200D\uFEFF]/g;function Fr(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,i=!1;function s(l,u){let c=-1,p=/[\u200B-\u200D\uFEFF]/;if(!p.test(l))return u;for(let d=0;d<=l.length;d++)if(p.test(l[d])||c++,c===u)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let u=l.textContent,c=u.replace(Ga,""),p=o+c.length,d=t>=o&&t<=p,f=n>=o&&n<=p;if(d){let y=s(u,t-o);y===0&&!f?r.setStartBefore(l):r.setStart(l,y)}f&&(r.setEnd(l,s(u,n-o)),i=!0),o=p;break}case Node.ELEMENT_NODE:{if(Hd(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),i=!0;return}for(let c=0;c<l.childNodes.length&&(a(l.childNodes[c]),!i);c++);let u=l.lastChild;jd(l)&&u&&!jd(u)&&!Hd(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function Xa(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a,l,u=0;function c(p){let d=p===n,f=p===o;switch(p.nodeType){case Node.TEXT_NODE:{let y=p.textContent;d&&(a=u+y.substring(0,r).replace(Ga,"").length),f&&(l=u+y.substring(0,i).replace(Ga,"").length),u+=y.replace(Ga,"").length;break}case Node.ELEMENT_NODE:{let y=p.nextSibling===null;Hd(p)&&!y&&u++;for(let v=0;v<p.childNodes.length;v++){let m=d&&v===r,g=f&&v===i;if(m&&(a=u),g&&(l=u),l!==void 0||((!m||!s)&&c(p.childNodes[v]),f&&v===i-1&&(l=u),l!==void 0))break}!f&&jd(p)&&!y&&u++,f&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a??l,end:l}}function Qa(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i}=t,s=-1,a="";function l(u){let c=u===n,p=u===o;switch(c&&s++,u.nodeType){case Node.TEXT_NODE:{if(s!==0)return;let d=c?r:0,f=p?i:void 0,y=u.textContent.replace(Ga,"");d===0&&f===void 0?a+=y:a+=y.substring(d,f);break}case Node.ELEMENT_NODE:{let d=u.nextSibling===null;s===0&&Hd(u)&&!d&&(a+=`
24
24
  `);for(let f=c?r:0;f<(p?Math.min(i,u.childNodes.length):u.childNodes.length)&&(l(u.childNodes[f]),s!==1);f++);!p&&s===0&&jd(u)&&!d&&(a+=`
25
- `);break}default:break}p&&s++}return l(e),a}function _b(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Eo=class extends Rn{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),Qa(this.element,t)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let t=this.getRootNode();if(t.activeElement!==this.element)return null;let n="getSelection"in t?t.getSelection():window.getSelection();if(!n)return null;let r="getComposedRanges"in n&&t instanceof ShadowRoot?(i=n.getComposedRanges(t))==null?void 0:i[0]:n.rangeCount>0?n.getRangeAt(0):null;if(!r)return null;let o=this.element.ownerDocument.createRange();return o.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),o.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!o||!this.element.contains(o.startContainer)||!this.element.contains(o.endContainer)?null:o}getCaretPosition(){let t=this.getRange();if(!t||!t.collapsed||!("getBoundingClientRect"in t))return null;let n=t.getBoundingClientRect();return!_b(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!_b(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return Xa(this.element,t);let n=this.lastKnownSelection;if(n&&xb(this.element,n.start,n.end))return n;let r=Vi(this.element);return r.collapse(!1),Xa(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return Qa(this.element,Fr(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let t=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==t&&(t=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()}};function wb(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}var Dh=class{constructor(t){this.name=t;this.broadcastChannel=new BroadcastChannel(t)}broadcastChannel;disposeHandlers=[];onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Fh=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=wb(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},jh=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.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(t){this.sessionId!==t&&(this.cleanup(),j.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Fh(t,this.deepdeskUrl,{debug:!0}):new Dh(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=typeof o.data=="string"?JSON.parse(o.data):o.data;i.type==="event"&&i.channel===t&&(j.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;j.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage({...o,channel:this.sessionId})}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},Cb=jh;var Wi=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var Hh=e=>new Promise(t=>{setTimeout(t,e)});var $i=class extends Wi{name="ClientError"},Bh=class extends Wi{name="ServerError"},Xt=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,{abortLatest:l=!1,attempts:u=1,retryDelay:c=500,refreshTokenOn401:p=!0,retryOnError:d=_=>_ instanceof TypeError,retryOnResponse:f=_=>_.status>=500,version:y="v1",...v}=n,m={credentials:"include",...v,headers:{"Content-Type":"application/json",...v.headers}};n.method!==void 0&&n.method!=="GET"&&this.csrfToken&&(m.headers={...m.headers,"X-CSRFToken":this.csrfToken}),typeof y=="string"&&(m.headers={...m.headers,"X-Deepdesk-API-Version":y});let g=u,h=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&l&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let x=async()=>(g--,a(s,m).then(async _=>f(_)&&!i.isAborted&&g>0?(await Hh(c),x()):_.status===401&&p===!0&&h===!1?(h=!0,await this.refreshToken(),x()):_).catch(async _=>{if(d(_)&&!i.isAborted&&g>0)return await Hh(c),x();throw _}));x().then(_=>_.json().catch(()=>null).then(w=>{_.status>=500?o(new Bh("Server Error",w)):_.status===401?o(new $i("Unauthorized",w)):_.status===403?o(new $i("Forbidden",w)):_.status===404?o(new $i("Not Found",w)):_.status>=400&&o(new $i("Bad Request",w)),delete this.latestRequestByUrl[s],r(w)})).catch(_=>{o(_)})})}async validateToken(){let{has_valid_access_token:t}=await this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return e.refreshingToken||(e.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{e.refreshingToken=null},1e3*60)})),e.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,{method:"POST",body:JSON.stringify(n),...r})}patch(t,n,r){return this.request(t,{method:"PATCH",body:JSON.stringify(n),...r})}put(t,n,r){return this.request(t,{method:"PUT",body:JSON.stringify(n),...r})}delete(t,n){return this.request(t,{method:"DELETE",...n})}};var BA;(t=>{let e;(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"))(e=t.EventType||={})})(BA||={});function Bd(e){return{...ee(e),tags:e.tags}}var qn=class e{constructor(t,n={}){this.options=n;this.client=new Xt(t,{fetch:n.fetch}),this.client.patchFetch(r=>async(o,i)=>{let s=await r(o,i);return this.handleDeepdeskVersionHeaders(s),s})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=await this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(e.exchangeTokenPromise||(e.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),e.exchangeTokenPromise):Promise.resolve()}async createConversation(t){await this.preflight(),j.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...Pe(t),tags:t.tags},{version:"v2"});return Bd(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null});return ee(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null});return ee(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null});return ee(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null});return ee(t)}async checkUserExists(t){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n}async getConversationBySessionId(t,n={}){await this.preflight(),j.info(`Getting conversation for session ${t}`);let{attempts:r=1,retryDelay:o=1e3}=n,i=await this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"});return j.info(`Successfully retrieved conversation ${i.id} for session ${t}`),Bd(i)}async isConversationSupported(t,n={}){j.info(`Check if conversation for session ${t} is supported`);let{attempts:r=1,retryDelay:o=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"})).has_active_profile}async updateConversation(t,n){let r=Pe(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Bd(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...Pe(o),tags:o.tags})),{version:"v2"})).map(o=>Bd(o))}async sendEvent(t,n){let{data:r,...o}=n,i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[a,l])=>({...s,[a]:l}),{});return this.client.post("/api/events",Pe({...i,...o,data:r,name:t}),{version:"v2"})}async sendEventV1(t,n){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>({...o,[i]:s}),{});return this.client.post("/api/events",{event:t,data:Pe({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){return(await this.client.post("/api/summary",{conversation:{messages:t.filter(o=>o.text&&o.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(t){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw j.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.client.post("/apis/admin/session/api-key/",Pe(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})}async getTextSuggestions(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(await this.client.post(`/api/conversations/${t}/recommend/${r}`,Pe(n),{abortLatest:!0})).map(i=>({...ee(i),text:i.text||i.url||i.message,source:r,type:r})).filter((i,s,a)=>s===a.findIndex(l=>l.text===i.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(t,n){return(await this.client.post(`/api/conversations/${t}/autocomplete`,Pe(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))}async getPinnedMessages(t){let n=await this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return ee(n).map(r=>({...r,text:r.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(t){let n=await this.client.post("/api/style-suggestions",Pe(t),{abortLatest:!0});return ee(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,Pe(t),{version:"v2"});return ee(n)}async knowledgeAssist(t,n,r,o={}){let i=await this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Pe({question:t.question,promptInstruction:t.promptInstruction,chatHistory:n.map(s=>({question:s.question,answer:s.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return ee(i)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return ee(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return ee(t.token)}async getCsrfToken(){let{token:t}=await this.client.get("/apis/admin/session/csrf/",{version:null});return t}async verifyLoginToken(t){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return ee(n)}async evaluateRule(t,n,r,o={}){let i=new URLSearchParams;o.raiseForFailingConditions&&i.set("raise_for_failing_conditions","true");let s=await this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${i.toString()}`,r,{version:"v2"});return ee(s.cues)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Ny);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&j.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var Ya=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(zg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,ee(o))}catch{j.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var zA;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(zA||={});var Za=class{constructor(t,n={}){this.apiUrl=t;this.client=new Xt(t,n)}client;streams={};logger=j;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return ee(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,Pe(n));return ee(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,Pe(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return ee(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",Pe(t));return ee(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new Ya(`${this.apiUrl}/sessions/${t}/events`),this.streams[t].connect()),this.streams[t]}closeStream(t){this.streams[t]||(this.streams[t].disconnect(),delete this.streams[t])}};var bb={startTime:null,stopTime:null},Eb=B({name:"handlingTime",initialState:bb,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(J,()=>bb)}}),{handlingTimeStart:Tb,handlingTimeStop:zd,handlingTimeReset:kb}=Eb.actions,Pb=Eb.reducer;var Ib=(e={})=>{let t={onAuthError:Mi(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Ud={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var To=D("styleSuggestions/getAll",async({text:e},t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),{showStyleSuggestions:o}=r.settings,i=(s=r.conversation.current)==null?void 0:s.profileCode;if(!o)return Ud.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),UA=B({name:"styleSuggestions",initialState:Ud,reducers:{},extraReducers:e=>{e.addCase(To.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(To.rejected,t=>{t.fetchState="error"}).addCase(To.fulfilled,(t,n)=>{t.fetchState="done",wr(t.list,n.payload)||(t.list=n.payload)}).addCase(oo,t=>{t.list=Ud.list}).addCase(J,()=>Ud)}}),Rb=UA.reducer;var Lb=(e={})=>{let t,n=!0,r={getStyleSuggestions:To,debounce:500,...e};return o=>i=>s=>{var f;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((f=u.conversation.current)==null?void 0:f.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function KA(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var Ab=(e={})=>{let t={getTextSuggestions:Wt,getAutocompleteSuggestions:Ia,debounce:200,check:Bi,...e},n;return r=>o=>i=>{var v;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,p=(v=l.conversation.current)==null?void 0:v.id,d=i.type===ud.toString();if(!p||!u&&!c)return a;let{input:{userCommitted:f}}=l;return KA(f,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let m=wi(l);m===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(m))},d?0:t.debounce)),a}};var Ob=To.fulfilled.toString();function VA(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var Nb=e=>t=>n=>r=>{var u;if(r.type!==Ob){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=VA(o,s);r.type===Ob&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var WA=Nu({activeSuggestion:Bw,answer:D1,auth:Jw,autoflows:OC,conversation:n_,contentTypes:v1,customMessages:UC,passwordlessToken:$C,entities:w1,knowledgeAssistant:O1,handlingTime:Pb,info:mw,input:ig.reducer,overlayInput:ot.reducer,settings:qx,profile:H1,search:_w,summary:P1,styleSuggestions:Rb,ui:Vw,rules:r1,textSuggestions:Mw});function Mb(e){return J0({reducer:WA,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),Ib(),Ab({debounce:200}),Lb({debounce:500}),Nb(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var $A=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},qA=e=>t=>n=>r=>{var a;let o=t.getState(),i=Jm("inlineSuggestions")(o);switch(r.type){case Nn.toString():{let l=ld(r.payload.contentType)(t.getState()),u=l.indexOf(r.payload.suggestion);e.emit("edit-suggestion",{contentType:r.payload.contentType,index:u,suggestions:l});break}case Mi.toString():{!r.payload&&e.emit("logout",void 0);break}case zt.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",{type:$A(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case Sc.toString():{let{start:l,end:u}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case pa.toString():{let l=t.getState(),{text:u,selection:c}=l.input.userCommitted;e.emit("reset",{text:u,selectionAfter:c},{mayApplyChanges:!0});break}case Cc.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:o.conversation.current.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case qt.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:o.conversation.current.id,data:{entities:r.payload}});break;case jn.fulfilled.toString():e.sendEvent("conversation summarized",{conversationId:o.conversation.current.id,data:{summary:r.payload.summary}});break;case ze.toString():e.sendEvent(r.payload.name,{conversationId:((a=r.payload.options)==null?void 0:a.includeConversationData)&&o.conversation.current.id,data:r.payload.data});break;case xc.toString():e.handleKeyDown(r.payload);break;case oo.toString():e.logSendMessage(r.payload);break;case _c.toString():e.logSendEditSuggestionMessage(r.payload);break;case wc.toString():e.handleInputChanged(r.payload);break;case Dn.fulfilled.toString():e.broadcast(Qg,r.payload,!1),e.emit("cues",r.payload);break;default:break}let s=n(r);switch(r.type){case oo.toString():e.handleAfterSendMessage(r.payload);break;case Ra.toString():e.onUpdateShowTabHint(r.payload);break;case zd.toString():e.logHandlingTime();break;case zt.toString():{i&&(t.dispatch(an([])),t.dispatch(En()));break}case an.toString():{i&&r.payload.length>0&&t.dispatch(br(0));break}default:break}return s},Db=qA;function zh(e){return e.toISOString().replace("T"," ").replace("Z","")}function Fb(e,t){var o,i,s;let{startTime:n,stopTime:r}=e.handlingTime;if(!n||!r)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:e.conversation.current.id,clientVersion:t.version,agentId:(o=e.info.agentInfo)==null?void 0:o.agentId,agentName:(i=e.info.agentInfo)==null?void 0:i.agentName,agentEmail:(s=e.info.agentInfo)==null?void 0:s.agentEmail,timeStart:zh(n),timeStop:zh(r)}}function Uh(e,t,n){var E,P,I;let{text:r,metrics:{numCharsTyped:o,numCharsPasted:i,numCharsCut:s,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:u,externalTimeTotalSeconds:c,pastes:p,cuts:d,deletions:f,textSuggestions:y,offeredTextSuggestions:v}}=t[e],m=r.length,h=y.reduce((z,{text:V,searchTerm:N})=>z+V.length-(N?N.length:0),0),x=u??Date.now(),_=(Date.now()-x)/1e3+(c||0),w=o/_,b=y.reduce((z,{searchTerm:V})=>z+(V?V.length:0),0);return{conversationId:t.conversation.current.id,source:"agent",text:r,clientVersion:n.version,pastes:p,cuts:d,deletions:f,lenTextTyped:o+b,lenTextTotal:m,lenTextAssisted:h,lenTextPasted:i,lenTextCut:s,lenTextDeleted:a,timeTotalSeconds:_,charsPerSecond:w,numPastes:l,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:v.filter(z=>z.source==="gpt").length}],agentId:(E=t.info.agentInfo)==null?void 0:E.agentId,agentName:(P=t.info.agentInfo)==null?void 0:P.agentName,agentEmail:(I=t.info.agentInfo)==null?void 0:I.agentEmail}}function Kh(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Kh(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Kh(o,t):null}function jb(e,t){return Kh(e,t)}function Hb(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function GA(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Kd(e){return GA(e)&&(Nr(e)||qc(e))}var Bb=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch{return t}}catch{return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch{j.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function XA(e){return e.offsetParent!==null}function zb(e){if(!XA(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function Vd(e,t,n=100){let r=zb(e);t({isVisible:r});let o=setInterval(()=>{let i=zb(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Ce=S(C());var Ub=Bb("showTabHint",!0),Ja=class e{static version="10.12.1-beta.6";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new qn(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Db({broadcast:(p,d,f)=>{this.broadcastEvents.send(p,d,f)},emit:(p,d,f)=>this.emit(p,d,f),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),logSendEditSuggestionMessage:p=>this.logSendEditMessage(p),onUpdateShowTabHint:p=>Ub.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Za(n)}),this.store=Mb(c),this.broadcastEvents=new Cb({debug:!0,deepdeskUrl:u,eventMap:o1(this.store),createCustomChannel:l}),this.store.dispatch(Ra(Ub.value())),this.store.dispatch(uc({locale:o,adminUrl:u,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?(j.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(j.warn("Profile has not been loaded (yet)"),!0):(j.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Mi(null)),this.store.dispatch(Mn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();Xe(r)&&qw(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(Mn())).payload}async setPlatformAgentId(t){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:t}),version:null})}catch(n){j.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(rg({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(fc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(mc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(og(t))).payload}async postMessages(t){return(await this.store.dispatch(hc(t))).payload}async updateConversation(t){return(await this.store.dispatch(gc(t))).payload}resetConversation(){this.store.dispatch(J()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(jn());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(uc(t))}setVisitorInfo(t){this.store.dispatch(fw(t))}async setAgentInfo(t){await this.store.dispatch(Ea(t))}async setAgentSettings(t){await this.store.dispatch(Ug(t))}async getAgentSettings(){return(await this.store.dispatch(Kg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(ud()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(wc(t))}notifyKeyDown(t){this.store.dispatch(xc(t))}notifyPaste(t,n){this.store.dispatch(f_({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(d_(t))}notifyExternalSuggestion(t){this.store.dispatch(zt(t)),this.store.dispatch(En())}notifyEditSuggestion(t){this.store.dispatch(Ow(t.contentType,t.suggestions)),this.store.dispatch(Nn({contentType:t.contentType,suggestion:typeof t.index=="number"?t.suggestions[t.index]:null}))}async evaluateRule(t,n={}){let{payload:r,error:o}=await this.store.dispatch(Dn({label:t,params:n}));if(o)throw o;return r}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(Rr({collapse:!1})),this.inputMediator&&this.store.dispatch(i_({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(an([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(p_(vc(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(l_()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(c_()),t.preventDefault(),!s&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(pa()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(br(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(br(-1)),this.store.dispatch(pa()),t.preventDefault()):n||(this.store.dispatch(Rr({collapse:!0})),this.store.dispatch(Uw(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:f}=this.state.input;this.store.dispatch(Ra(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&f&&f.text.startsWith(d)&&(this.store.dispatch(zt({text:f.text,suggestion:f,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(En())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(m_()),this.store.dispatch(an([]))}handlingTimeStart(){this.state.handlingTime.startTime||(j.info("Start handling time"),this.store.dispatch(Tb()))}handlingTimeStop(){this.state.handlingTime.startTime&&(j.info("Stop handling time"),this.store.dispatch(zd()))}logSendMessage(t){let n=Uh("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logSendEditMessage(t){let n=Uh("overlayInput",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.store.dispatch(a_(this.state.overlayInput.metrics))}logHandlingTime(){let t=Fb(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(kb())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(En()),this.store.dispatch(oo(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(zt({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){j.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),j.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=co(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Mt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=co(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,Mt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return uo(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,Mt.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),j.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(j.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(h_(r.metrics))):j.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Kd(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:d,insertLink:f,inputMediator:y,closestScrollSelector:v,appendOverlayTo:m,inlineSuggestions:g,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:f,isEmbedded:p,inlineSuggestions:g,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),uo(t),this.inputMediator=y||(Nr(t)?new Ln(t):new Eo(t)),this.inputMediator.on("change",({plainText:w})=>{this.notifyInputChanged(w)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(g_({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:b})=>{this.notifyPaste(w,b)}),this.inputMediator.on("cut",({selectionText:w})=>{this.notifyCut(w)});let x=v&&jb(t,v)||void 0;if(g){let{customStyles:w,appendOverlayTo:b}=n;if(Nr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let E=this.createInlineContainer(t,"deepdesk-caret");(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:w,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)(rC,{})})}),E),this.inputMediator.on("caret",I=>{this.store.dispatch(an([])),I?(E.style.display="block",E.style.top=`${I.top}px`,E.style.left=`${I.left}px`):E.style.display="none"});let P=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:b},w==null?void 0:w.floatingMenuRootNode);(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:w,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)(Y1,{onLogIn:()=>this.loginViaPopup().catch(I=>j.warn(I.message))})})}),P)}else{let w=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:m,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),b=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:m},r==null?void 0:r.suggestionsRootNode);(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:r,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)(kC,{inputElement:t})})}),w),(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:r,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)(dC,{onLogIn:()=>this.loginViaPopup().catch(E=>j.warn(E.message))})})}),b)}(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:r,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)($1,{})})}),this.createContainer("deepdesk-overlays"));let _;this.inputMediator.on("selection",w=>{clearTimeout(_),w===null?_=setTimeout(()=>{w!==null&&this.store.dispatch(sg(w))},500):this.store.dispatch(sg(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",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Ni(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Ni(!0))),this.store.dispatch(s_({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(En()),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 t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&j.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:r,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)(Sb,{onLogIn:()=>this.loginViaPopup().catch(s=>j.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Mt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Vd(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){Hb(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(za());let t=Ar(this.state);t&&(await this.store.dispatch(Ha()),this.store.dispatch(uc({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(t){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};i.onmessage=async f=>{var y,v;if((y=f.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=f.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Oa),l=!0,o.port1.close(),n()}catch(m){console.error(m),r(m)}finally{l=!0,u()}};let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let p=async f=>{var y;if(f.origin===a.origin)switch((y=f.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){j.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),f.data.message==="Timeout"&&j.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(f.data.message));break}}};window.addEventListener("message",p);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(j.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;j.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=fd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(qt()):this.store.dispatch(Wt(r))})}catch(r){this.handleError(r)}}};async function Kb(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function Vb(e,t,n={}){let r=n.replace?Fr(e,n.replace.start,n.replace.end):Vi(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
25
+ `);break}default:break}p&&s++}return l(e),a}function _b(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Eo=class extends Rn{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),Qa(this.element,t)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let t=this.getRootNode();if(t.activeElement!==this.element)return null;let n="getSelection"in t?t.getSelection():window.getSelection();if(!n)return null;let r="getComposedRanges"in n&&t instanceof ShadowRoot?(i=n.getComposedRanges(t))==null?void 0:i[0]:n.rangeCount>0?n.getRangeAt(0):null;if(!r)return null;let o=this.element.ownerDocument.createRange();return o.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),o.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!o||!this.element.contains(o.startContainer)||!this.element.contains(o.endContainer)?null:o}getCaretPosition(){let t=this.getRange();if(!t||!t.collapsed||!("getBoundingClientRect"in t))return null;let n=t.getBoundingClientRect();return!_b(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!_b(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return Xa(this.element,t);let n=this.lastKnownSelection;if(n&&xb(this.element,n.start,n.end))return n;let r=Vi(this.element);return r.collapse(!1),Xa(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return Qa(this.element,Fr(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let t=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==t&&(t=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()}};function wb(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}var Dh=class{constructor(t){this.name=t;this.broadcastChannel=new BroadcastChannel(t)}broadcastChannel;disposeHandlers=[];onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Fh=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=wb(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},jh=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.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(t){this.sessionId!==t&&(this.cleanup(),j.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Fh(t,this.deepdeskUrl,{debug:!0}):new Dh(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=typeof o.data=="string"?JSON.parse(o.data):o.data;i.type==="event"&&i.channel===t&&(j.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;j.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage({...o,channel:this.sessionId})}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},Cb=jh;var Wi=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var Hh=e=>new Promise(t=>{setTimeout(t,e)});var $i=class extends Wi{name="ClientError"},Bh=class extends Wi{name="ServerError"},Xt=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,{abortLatest:l=!1,attempts:u=1,retryDelay:c=500,refreshTokenOn401:p=!0,retryOnError:d=_=>_ instanceof TypeError,retryOnResponse:f=_=>_.status>=500,version:y="v1",...v}=n,m={credentials:"include",...v,headers:{"Content-Type":"application/json",...v.headers}};n.method!==void 0&&n.method!=="GET"&&this.csrfToken&&(m.headers={...m.headers,"X-CSRFToken":this.csrfToken}),typeof y=="string"&&(m.headers={...m.headers,"X-Deepdesk-API-Version":y});let g=u,h=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&l&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let x=async()=>(g--,a(s,m).then(async _=>f(_)&&!i.isAborted&&g>0?(await Hh(c),x()):_.status===401&&p===!0&&h===!1?(h=!0,await this.refreshToken(),x()):_).catch(async _=>{if(d(_)&&!i.isAborted&&g>0)return await Hh(c),x();throw _}));x().then(_=>_.json().catch(()=>null).then(w=>{_.status>=500?o(new Bh("Server Error",w)):_.status===401?o(new $i("Unauthorized",w)):_.status===403?o(new $i("Forbidden",w)):_.status===404?o(new $i("Not Found",w)):_.status>=400&&o(new $i("Bad Request",w)),delete this.latestRequestByUrl[s],r(w)})).catch(_=>{o(_)})})}async validateToken(){let{has_valid_access_token:t}=await this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return e.refreshingToken||(e.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{e.refreshingToken=null},1e3*60)})),e.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,{method:"POST",body:JSON.stringify(n),...r})}patch(t,n,r){return this.request(t,{method:"PATCH",body:JSON.stringify(n),...r})}put(t,n,r){return this.request(t,{method:"PUT",body:JSON.stringify(n),...r})}delete(t,n){return this.request(t,{method:"DELETE",...n})}};var BA;(t=>{let e;(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"))(e=t.EventType||={})})(BA||={});function Bd(e){return{...ee(e),tags:e.tags}}var qn=class e{constructor(t,n={}){this.options=n;this.client=new Xt(t,{fetch:n.fetch}),this.client.patchFetch(r=>async(o,i)=>{let s=await r(o,i);return this.handleDeepdeskVersionHeaders(s),s})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=await this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(e.exchangeTokenPromise||(e.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),e.exchangeTokenPromise):Promise.resolve()}async createConversation(t){await this.preflight(),j.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...Pe(t),tags:t.tags},{version:"v2"});return Bd(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null});return ee(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null});return ee(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null});return ee(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null});return ee(t)}async checkUserExists(t){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n}async getConversationBySessionId(t,n={}){await this.preflight(),j.info(`Getting conversation for session ${t}`);let{attempts:r=1,retryDelay:o=1e3}=n,i=await this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"});return j.info(`Successfully retrieved conversation ${i.id} for session ${t}`),Bd(i)}async isConversationSupported(t,n={}){j.info(`Check if conversation for session ${t} is supported`);let{attempts:r=1,retryDelay:o=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"})).has_active_profile}async updateConversation(t,n){let r=Pe(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Bd(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...Pe(o),tags:o.tags})),{version:"v2"})).map(o=>Bd(o))}async sendEvent(t,n){let{data:r,...o}=n,i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[a,l])=>({...s,[a]:l}),{});return this.client.post("/api/events",Pe({...i,...o,data:r,name:t}),{version:"v2"})}async sendEventV1(t,n){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>({...o,[i]:s}),{});return this.client.post("/api/events",{event:t,data:Pe({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){return(await this.client.post("/api/summary",{conversation:{messages:t.filter(o=>o.text&&o.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(t){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw j.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.client.post("/apis/admin/session/api-key/",Pe(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})}async getTextSuggestions(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(await this.client.post(`/api/conversations/${t}/recommend/${r}`,Pe(n),{abortLatest:!0})).map(i=>({...ee(i),text:i.text||i.url||i.message,source:r,type:r})).filter((i,s,a)=>s===a.findIndex(l=>l.text===i.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(t,n){return(await this.client.post(`/api/conversations/${t}/autocomplete`,Pe(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))}async getPinnedMessages(t){let n=await this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return ee(n).map(r=>({...r,text:r.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(t){let n=await this.client.post("/api/style-suggestions",Pe(t),{abortLatest:!0});return ee(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,Pe(t),{version:"v2"});return ee(n)}async knowledgeAssist(t,n,r,o={}){let i=await this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Pe({question:t.question,promptInstruction:t.promptInstruction,chatHistory:n.map(s=>({question:s.question,answer:s.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return ee(i)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return ee(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return ee(t.token)}async getCsrfToken(){let{token:t}=await this.client.get("/apis/admin/session/csrf/",{version:null});return t}async verifyLoginToken(t){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return ee(n)}async evaluateRule(t,n,r,o={}){let i=new URLSearchParams;o.raiseForFailingConditions&&i.set("raise_for_failing_conditions","true");let s=await this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${i.toString()}`,r,{version:"v2"});return ee(s.cues)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Ny);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&j.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var Ya=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(zg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,ee(o))}catch{j.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var zA;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(zA||={});var Za=class{constructor(t,n={}){this.apiUrl=t;this.client=new Xt(t,n)}client;streams={};logger=j;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return ee(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,Pe(n));return ee(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,Pe(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return ee(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",Pe(t));return ee(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new Ya(`${this.apiUrl}/sessions/${t}/events`),this.streams[t].connect()),this.streams[t]}closeStream(t){this.streams[t]||(this.streams[t].disconnect(),delete this.streams[t])}};var bb={startTime:null,stopTime:null},Eb=B({name:"handlingTime",initialState:bb,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(J,()=>bb)}}),{handlingTimeStart:Tb,handlingTimeStop:zd,handlingTimeReset:kb}=Eb.actions,Pb=Eb.reducer;var Ib=(e={})=>{let t={onAuthError:Mi(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Ud={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var To=D("styleSuggestions/getAll",async({text:e},t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),{showStyleSuggestions:o}=r.settings,i=(s=r.conversation.current)==null?void 0:s.profileCode;if(!o)return Ud.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),UA=B({name:"styleSuggestions",initialState:Ud,reducers:{},extraReducers:e=>{e.addCase(To.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(To.rejected,t=>{t.fetchState="error"}).addCase(To.fulfilled,(t,n)=>{t.fetchState="done",wr(t.list,n.payload)||(t.list=n.payload)}).addCase(oo,t=>{t.list=Ud.list}).addCase(J,()=>Ud)}}),Rb=UA.reducer;var Lb=(e={})=>{let t,n=!0,r={getStyleSuggestions:To,debounce:500,...e};return o=>i=>s=>{var f;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((f=u.conversation.current)==null?void 0:f.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function KA(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var Ab=(e={})=>{let t={getTextSuggestions:Wt,getAutocompleteSuggestions:Ia,debounce:200,check:Bi,...e},n;return r=>o=>i=>{var v;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,p=(v=l.conversation.current)==null?void 0:v.id,d=i.type===ud.toString();if(!p||!u&&!c)return a;let{input:{userCommitted:f}}=l;return KA(f,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let m=wi(l);m===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(m))},d?0:t.debounce)),a}};var Ob=To.fulfilled.toString();function VA(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var Nb=e=>t=>n=>r=>{var u;if(r.type!==Ob){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=VA(o,s);r.type===Ob&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var WA=Nu({activeSuggestion:Bw,answer:D1,auth:Jw,autoflows:OC,conversation:n_,contentTypes:v1,customMessages:UC,passwordlessToken:$C,entities:w1,knowledgeAssistant:O1,handlingTime:Pb,info:mw,input:ig.reducer,overlayInput:ot.reducer,settings:qx,profile:H1,search:_w,summary:P1,styleSuggestions:Rb,ui:Vw,rules:r1,textSuggestions:Mw});function Mb(e){return J0({reducer:WA,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),Ib(),Ab({debounce:200}),Lb({debounce:500}),Nb(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var $A=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},qA=e=>t=>n=>r=>{var a;let o=t.getState(),i=Jm("inlineSuggestions")(o);switch(r.type){case Nn.toString():{let l=ld(r.payload.contentType)(t.getState()),u=l.indexOf(r.payload.suggestion);e.emit("edit-suggestion",{contentType:r.payload.contentType,index:u,suggestions:l});break}case Mi.toString():{!r.payload&&e.emit("logout",void 0);break}case zt.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",{type:$A(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case Sc.toString():{let{start:l,end:u}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case pa.toString():{let l=t.getState(),{text:u,selection:c}=l.input.userCommitted;e.emit("reset",{text:u,selectionAfter:c},{mayApplyChanges:!0});break}case Cc.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:o.conversation.current.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case qt.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:o.conversation.current.id,data:{entities:r.payload}});break;case jn.fulfilled.toString():e.sendEvent("conversation summarized",{conversationId:o.conversation.current.id,data:{summary:r.payload.summary}});break;case ze.toString():e.sendEvent(r.payload.name,{conversationId:((a=r.payload.options)==null?void 0:a.includeConversationData)&&o.conversation.current.id,data:r.payload.data});break;case xc.toString():e.handleKeyDown(r.payload);break;case oo.toString():e.logSendMessage(r.payload);break;case _c.toString():e.logSendEditSuggestionMessage(r.payload);break;case wc.toString():e.handleInputChanged(r.payload);break;case Dn.fulfilled.toString():e.broadcast(Qg,r.payload,!1),e.emit("cues",r.payload);break;default:break}let s=n(r);switch(r.type){case oo.toString():e.handleAfterSendMessage(r.payload);break;case Ra.toString():e.onUpdateShowTabHint(r.payload);break;case zd.toString():e.logHandlingTime();break;case zt.toString():{i&&(t.dispatch(an([])),t.dispatch(En()));break}case an.toString():{i&&r.payload.length>0&&t.dispatch(br(0));break}default:break}return s},Db=qA;function zh(e){return e.toISOString().replace("T"," ").replace("Z","")}function Fb(e,t){var o,i,s;let{startTime:n,stopTime:r}=e.handlingTime;if(!n||!r)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:e.conversation.current.id,clientVersion:t.version,agentId:(o=e.info.agentInfo)==null?void 0:o.agentId,agentName:(i=e.info.agentInfo)==null?void 0:i.agentName,agentEmail:(s=e.info.agentInfo)==null?void 0:s.agentEmail,timeStart:zh(n),timeStop:zh(r)}}function Uh(e,t,n){var E,P,I;let{text:r,metrics:{numCharsTyped:o,numCharsPasted:i,numCharsCut:s,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:u,externalTimeTotalSeconds:c,pastes:p,cuts:d,deletions:f,textSuggestions:y,offeredTextSuggestions:v}}=t[e],m=r.length,h=y.reduce((z,{text:V,searchTerm:N})=>z+V.length-(N?N.length:0),0),x=u??Date.now(),_=(Date.now()-x)/1e3+(c||0),w=o/_,b=y.reduce((z,{searchTerm:V})=>z+(V?V.length:0),0);return{conversationId:t.conversation.current.id,source:"agent",text:r,clientVersion:n.version,pastes:p,cuts:d,deletions:f,lenTextTyped:o+b,lenTextTotal:m,lenTextAssisted:h,lenTextPasted:i,lenTextCut:s,lenTextDeleted:a,timeTotalSeconds:_,charsPerSecond:w,numPastes:l,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:v.filter(z=>z.source==="gpt").length}],agentId:(E=t.info.agentInfo)==null?void 0:E.agentId,agentName:(P=t.info.agentInfo)==null?void 0:P.agentName,agentEmail:(I=t.info.agentInfo)==null?void 0:I.agentEmail}}function Kh(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Kh(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Kh(o,t):null}function jb(e,t){return Kh(e,t)}function Hb(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function GA(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Kd(e){return GA(e)&&(Nr(e)||qc(e))}var Bb=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch{return t}}catch{return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch{j.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function XA(e){return e.offsetParent!==null}function zb(e){if(!XA(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function Vd(e,t,n=100){let r=zb(e);t({isVisible:r});let o=setInterval(()=>{let i=zb(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Ce=S(C());var Ub=Bb("showTabHint",!0),Ja=class e{static version="10.12.1-beta.7";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new qn(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Db({broadcast:(p,d,f)=>{this.broadcastEvents.send(p,d,f)},emit:(p,d,f)=>this.emit(p,d,f),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),logSendEditSuggestionMessage:p=>this.logSendEditMessage(p),onUpdateShowTabHint:p=>Ub.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Za(n)}),this.store=Mb(c),this.broadcastEvents=new Cb({debug:!0,deepdeskUrl:u,eventMap:o1(this.store),createCustomChannel:l}),this.store.dispatch(Ra(Ub.value())),this.store.dispatch(uc({locale:o,adminUrl:u,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?(j.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(j.warn("Profile has not been loaded (yet)"),!0):(j.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Mi(null)),this.store.dispatch(Mn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();Xe(r)&&qw(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(Mn())).payload}async setPlatformAgentId(t){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:t}),version:null})}catch(n){j.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(rg({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(fc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(mc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(og(t))).payload}async postMessages(t){return(await this.store.dispatch(hc(t))).payload}async updateConversation(t){return(await this.store.dispatch(gc(t))).payload}resetConversation(){this.store.dispatch(J()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(jn());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(uc(t))}setVisitorInfo(t){this.store.dispatch(fw(t))}async setAgentInfo(t){await this.store.dispatch(Ea(t))}async setAgentSettings(t){await this.store.dispatch(Ug(t))}async getAgentSettings(){return(await this.store.dispatch(Kg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(ud()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(wc(t))}notifyKeyDown(t){this.store.dispatch(xc(t))}notifyPaste(t,n){this.store.dispatch(f_({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(d_(t))}notifyExternalSuggestion(t){this.store.dispatch(zt(t)),this.store.dispatch(En())}notifyEditSuggestion(t){this.store.dispatch(Ow(t.contentType,t.suggestions)),this.store.dispatch(Nn({contentType:t.contentType,suggestion:typeof t.index=="number"?t.suggestions[t.index]:null}))}async evaluateRule(t,n={}){let{payload:r,error:o}=await this.store.dispatch(Dn({label:t,params:n}));if(o)throw o;return r}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(Rr({collapse:!1})),this.inputMediator&&this.store.dispatch(i_({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(an([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(p_(vc(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(l_()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(c_()),t.preventDefault(),!s&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(pa()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(br(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(br(-1)),this.store.dispatch(pa()),t.preventDefault()):n||(this.store.dispatch(Rr({collapse:!0})),this.store.dispatch(Uw(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:f}=this.state.input;this.store.dispatch(Ra(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&f&&f.text.startsWith(d)&&(this.store.dispatch(zt({text:f.text,suggestion:f,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(En())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(m_()),this.store.dispatch(an([]))}handlingTimeStart(){this.state.handlingTime.startTime||(j.info("Start handling time"),this.store.dispatch(Tb()))}handlingTimeStop(){this.state.handlingTime.startTime&&(j.info("Stop handling time"),this.store.dispatch(zd()))}logSendMessage(t){let n=Uh("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logSendEditMessage(t){let n=Uh("overlayInput",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.store.dispatch(a_(this.state.overlayInput.metrics))}logHandlingTime(){let t=Fb(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(kb())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(En()),this.store.dispatch(oo(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(zt({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){j.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),j.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=co(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Mt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=co(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,Mt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return uo(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,Mt.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),j.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(j.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(h_(r.metrics))):j.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Kd(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:d,insertLink:f,inputMediator:y,closestScrollSelector:v,appendOverlayTo:m,inlineSuggestions:g,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:f,isEmbedded:p,inlineSuggestions:g,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),uo(t),this.inputMediator=y||(Nr(t)?new Ln(t):new Eo(t)),this.inputMediator.on("change",({plainText:w})=>{this.notifyInputChanged(w)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(g_({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:b})=>{this.notifyPaste(w,b)}),this.inputMediator.on("cut",({selectionText:w})=>{this.notifyCut(w)});let x=v&&jb(t,v)||void 0;if(g){let{customStyles:w,appendOverlayTo:b}=n;if(Nr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let E=this.createInlineContainer(t,"deepdesk-caret");(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:w,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)(rC,{})})}),E),this.inputMediator.on("caret",I=>{this.store.dispatch(an([])),I?(E.style.display="block",E.style.top=`${I.top}px`,E.style.left=`${I.left}px`):E.style.display="none"});let P=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:b},w==null?void 0:w.floatingMenuRootNode);(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:w,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)(Y1,{onLogIn:()=>this.loginViaPopup().catch(I=>j.warn(I.message))})})}),P)}else{let w=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:m,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),b=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:m},r==null?void 0:r.suggestionsRootNode);(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:r,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)(kC,{inputElement:t})})}),w),(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:r,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)(dC,{onLogIn:()=>this.loginViaPopup().catch(E=>j.warn(E.message))})})}),b)}(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:r,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)($1,{})})}),this.createContainer("deepdesk-overlays"));let _;this.inputMediator.on("selection",w=>{clearTimeout(_),w===null?_=setTimeout(()=>{w!==null&&this.store.dispatch(sg(w))},500):this.store.dispatch(sg(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",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Ni(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Ni(!0))),this.store.dispatch(s_({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(En()),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 t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&j.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:r,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)(Sb,{onLogIn:()=>this.loginViaPopup().catch(s=>j.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Mt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Vd(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){Hb(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(za());let t=Ar(this.state);t&&(await this.store.dispatch(Ha()),this.store.dispatch(uc({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(t){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};i.onmessage=async f=>{var y,v;if((y=f.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=f.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Oa),l=!0,o.port1.close(),n()}catch(m){console.error(m),r(m)}finally{l=!0,u()}};let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let p=async f=>{var y;if(f.origin===a.origin)switch((y=f.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){j.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),f.data.message==="Timeout"&&j.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(f.data.message));break}}};window.addEventListener("message",p);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(j.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;j.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=fd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(qt()):this.store.dispatch(Wt(r))})}catch(r){this.handleError(r)}}};async function Kb(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function Vb(e,t,n={}){let r=n.replace?Fr(e,n.replace.start,n.replace.end):Vi(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
26
26
  `).reverse().forEach((s,a)=>{a>0&&r.insertNode(document.createElement("br")),r.insertNode(document.createTextNode(s))}):r.insertNode(document.createTextNode(t))};return Promise.resolve(i()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let s=n.selectionAfter?Fr(e,n.selectionAfter.start,n.selectionAfter.end):(r.collapse(!1),r),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(s)}if(!o)return;o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function QA(e){let t=document.createElement("template");return t.innerHTML=e.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),t.content}function YA(e){let t=document.createDocumentFragment();return e.split(`
27
27
  `).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},i=0;for(;o=n.slice(i).match(/(\[([^\]]+)])\(([^)]+)\)/);){let s=document.createElement("a");s.href=o[3],s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer"),s.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(i,i+o.index))),t.appendChild(s),i=i+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(i)))}),t}function Wb(e,t){return!e.contains(t)||t===e?null:t.parentNode===e?t:Wb(e,t.parentNode)}async function $b(e,t,{isBlock:n,isHTML:r}={}){let o;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let i=()=>{let s=e.ownerDocument.defaultView??window,a=s.getSelection();if((!a||a.rangeCount===0)&&(e.focus(),a=s.getSelection()),!a||a.rangeCount===0)return;let l=a.getRangeAt(0);if(!l)return;o=document.createElement("span"),l.insertNode(o);let u=r?QA(t):YA(t);if(n){let c=l.startContainer===e?e.childNodes[l.startOffset]:l.startContainer,p=Wb(e,c)??e.firstChild;e.insertBefore(u,(p==null?void 0:p.nextSibling)??null)}else l.insertNode(u),l.collapse(!1)};return Promise.resolve(i()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!o)try{o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function qb(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function Gb(e,t,n){await new qn(e).authenticateWithKey(t,n)}async function Xb(e){let n=await new Xt(e).get("/platform/config/",{version:null});return ee(n)}async function ZA(e){let n=await(e.fetch??window.fetch)(e.url),r=await n.blob();return new File([r],e.name,{type:e.mimeType??n.headers.get("Content-Type")??"image/jpeg"})}async function Qb(e,t){let n=await ZA(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}}return oE(JA);})();
28
28
  /*! Bundled license information:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepdesk/deepdesk-sdk",
3
- "version": "10.12.1-beta.6",
3
+ "version": "10.12.1-beta.7",
4
4
  "description": "Deepdesk SDK",
5
5
  "author": "Lukas Batteau",
6
6
  "license": "ISC",