@deepdesk/deepdesk-sdk 11.5.2 → 11.5.3

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.esm.js CHANGED
@@ -4,9 +4,9 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
4
4
  c-17.9,17.9-27.3,40.1-27.3,65.7C163.4,163,163.4,233,163.4,233z M465.5,267.9V477c0,9.4-3.4,17.9-10.2,24.7
5
5
  c-6.8,6.8-15.4,10.2-24.7,10.2h-349c-9.4,0-17.9-3.4-24.7-10.2c-6.8-6.8-10.2-15.4-10.2-24.7V267.9c0-9.4,3.4-17.9,10.2-24.7
6
6
  c6.8-6.8,15.4-10.2,24.7-10.2h11.9v-70c0-44.4,16.2-82.8,47.8-115.2S212.1,0,256.4,0s82.8,16.2,115.2,47.8
7
- 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 Ll}from"react/jsx-runtime";var hf={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},Ml=({className:t,color:e})=>Ll("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:Ll("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:hf[e||"pink"]})});var Nl={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var nr={};j(nr,{enUS:()=>yf,nlNL:()=>vf});var yf={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},vf={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};import{useDispatch as bf}from"react-redux";import{jsx as sr,jsxs as Ol}from"react/jsx-runtime";var Dl=({onLogIn:t})=>{let e=k(nr),o=w("floatingMenu"),n=w("productName"),s=bf(),r=xf(X),i=h("FloatingMenu",Nl);if(r===null||o===!1)return null;let a=()=>{r===!0?s(ee(!0)):t()};return Ol("button",{className:Sf(i.root,{[i.isLoggedIn]:r,[i.isLoggedOut]:!r}),onClick:a,children:[sr("div",{className:i.text,children:e(r?"search":"signin",{productName:n})}),Ol("div",{className:i.icon,children:[sr(Ml,{className:i.logo,color:"pink"}),r===!1&&sr(Al,{className:i.lock})]})]})};import{useEffect as Uf,useRef as zf}from"react";import{connect as Vf,useDispatch as Wf,useSelector as yn}from"react-redux";import{useEffect as Cf}from"react";function Ze(t){Cf(()=>{let e=o=>{o.isWithinRoot||t(o)};return document.body.addEventListener("mouseup",e),()=>{document.body.removeEventListener("mouseup",e)}},[t])}function Je(t){t.addEventListener("mouseup",e=>{e.isWithinRoot=!0},!0)}function wt(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{createSlice as wf}from"@reduxjs/toolkit";var Tf={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var gn=({ui:t})=>t.overlayCollapsed;var _l=wf({name:"ui",initialState:Tf,reducers:{setShowTabHint(t,e){t.showTabHint=e.payload},setInputHasFocus(t,e){t.overlayCollapsedUserOverwrite!==!0&&(e.payload===!0&&(t.overlayCollapsed=!1),t.inputHasFocus=e.payload)},setOverlayCollapsed(t,e){e.payload.collapse===!1&&(t.openOverlayWhenTyping=!1),!(e.payload.skipWhenInputFocus&&t.inputHasFocus)&&(t.overlayCollapsed=e.payload.collapse)},setOpenOverlayWhenTyping(t,e){t.openOverlayWhenTyping=e.payload},setOverlayCollapsedUserOverwrite(t,e){t.overlayCollapsedUserOverwrite=e.payload,t.overlayCollapsed=e.payload}}}),{setShowTabHint:oo,setInputHasFocus:rr,setOverlayCollapsed:Fe,setOpenOverlayWhenTyping:Fl,setOverlayCollapsedUserOverwrite:Hl}=_l.actions,Bl=_l.reducer;import{Fragment as Hf,useMemo as Bf}from"react";import{Interweave as Rf}from"interweave";import{useEffect as Pf,useMemo as If,useRef as Af}from"react";import{useDispatch as Lf,useSelector as Mf}from"react-redux";import{useEffect as Ef}from"react";function Kl(t,e,o){Ef(()=>{let n=t.current;return n?(n.addEventListener(e,o),()=>{n.removeEventListener(e,o)}):()=>{}},[t,e,o])}var Ul={root:"dd-1MBCO",actions:"dd--x4cy",badge:"dd-4Fpkz",formattedText:"dd-EzvTB"};import{jsx as fn,jsxs as Ff}from"react/jsx-runtime";var Nf=["search","personal-collection-search","search-autocomplete"];function Of(t,e,o,n={}){let s="";return Nf.includes(e)?s=fa(Ns(t,o,{stripAgentPart:!0}),n.searchKeywords??[o]):s=Ns(t,o,n),n.placeholders===!0&&(s=ha(s)),s}var Df=()=>{},_f=({index:t,selected:e,suggestion:o,onFeedback:n})=>{let s=w("inlineSuggestions"),r=Mf(ft),i=Lf(),a=h("TextSuggestion",Ul),d=Af(null);Pf(()=>{let c=setTimeout(()=>{i(wi({text:o.text,suggestion:o}))},500);return()=>{clearTimeout(c)}},[o]),Kl(d,"click",()=>{i(Ne(t)),i(pe({suggestion:o,text:o.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let l=If(()=>Of(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:Ff("div",{className:a.root,onMouseEnter:()=>i(Ne(t)),children:[fn(A,{ref:d,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:Df,children:fn(Rf,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:l})}),e&&n&&fn("div",{className:a.actions,children:fn(tn,{onFeedback:()=>n(o),suggestion:o.text})})]})},zl=_f;import{jsx as Vl}from"react/jsx-runtime";var Kf=({onFeedback:t,suggestions:e,selectedIndex:o,reverse:n})=>{let s=Bf(()=>{let r=e.map((i,a)=>Vl(zl,{index:a,selected:a===o,suggestion:i,onFeedback:t},`${i.text}-${i.source}`));return n?r.reverse():r},[e,o,n]);return Vl(Hf,{children:s})},hn=Kf;var Wl={root:"dd-PfvRI",paper:"dd-HYlyY"};import{jsx as vn}from"react/jsx-runtime";var qf=({textSuggestions:t,selectedIndex:e})=>{let o=zf(null),n=h("InlineSuggestionsOverlay",Wl),s=yn(wt),r=Wf(),i=yn(X),a=yn(mt),d=yn(gn),l=w("showTextSuggestions");return Ze(()=>{setTimeout(()=>{r(Fe({collapse:!0,skipWhenInputFocus:!0}))})}),Uf(()=>{let c=o.current;if(!c||!c.parentElement)return;c.parentElement.style.left="0px";let p=c.getBoundingClientRect();c.parentElement.style.left=`${Math.min(window.innerWidth-4-p.right,0)}px`}),d||!s||!l||t.length===0||i!==!0||a===!1?null:vn("div",{className:n.root,"data-variant":"inline",children:vn("div",{ref:o,className:n.paper,children:vn(Y,{children:vn(hn,{suggestions:t,selectedIndex:e})})})})},Gf=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),ql=Vf(Gf)(qf);import{Provider as $f}from"react-redux";import{jsx as Sn}from"react/jsx-runtime";var jf=({children:t})=>{let o=w("locale").replace("-","");return Sn(ks.Provider,{value:o,children:t})},Xf=({store:t,customStyles:e={},children:o})=>Sn($f,{store:t,children:Sn(jf,{children:Sn(_t.Provider,{value:e,children:o})})}),Ye=Xf;import cr from"classnames";import{useEffect as ah,useRef as lh,useState as dh}from"react";import{connect as ch,useDispatch as uh,useSelector as no}from"react-redux";import{useState as Qf}from"react";function Gl(t,e){let[o,n]=Qf(()=>{if(typeof window>"u")return e;try{let r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return x.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){x.error(i)}}]}var $l=()=>/Mac/i.test(navigator.platform);import Yf from"classnames";import{Fragment as eh,useCallback as ar,useMemo as Xl}from"react";var ir={};j(ir,{enUS:()=>Zf,nlNL:()=>Jf});var Zf={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"}]}]},Jf={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 jl={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};import{jsx as xn,jsxs as Ql}from"react/jsx-runtime";var lr=(t,e,o)=>n=>xn("button",{className:t.anchorButton,type:"button",value:e,onClick:o,children:n},e),th=({className:t,loginUrl:e,isEmbedded:o,onSnooze:n,onLogIn:s})=>{let r=k(ir),i=oe(),a=h("Login",jl),d=w("productName"),l=ar(y=>{y.preventDefault(),n&&n(parseInt(y.target.value,10))},[]),c=ar(y=>{y.preventDefault(),i.send(ht,!0)},[e]),p=Xl(()=>y=>xn("a",{onClick:v=>{v.preventDefault(),s()},href:e,className:a.anchor,target:"_blank",rel:"noreferrer",children:y},"login"),[e]),u=ar(y=>xn("button",{type:"button",className:a.anchorButton,onClick:c,children:y},"prompt"),[c]),{min:m,hour:g,day:f}=Xl(()=>({min:lr(a,60*10,l),hour:lr(a,60*60,l),day:lr(a,60*60*12,l)}),[]);return Ql("div",{className:Yf(t,a.root),children:[r("loginPlease",{login:o?u:p,productName:d}),n&&Ql(eh,{children:[xn("br",{}),r("snooze",{min:m,hour:g,day:f})]})]})},bn=th;import{useDispatch as oh}from"react-redux";var Zl={root:"dd-DoQhb",text:"dd-Jwnev"};import{jsx as Jl,jsxs as sh}from"react/jsx-runtime";var nh=({title:t})=>{let e=h("SearchTrigger",Zl),o=oh();return sh("button",{type:"button",className:e.root,onClick:()=>o(ee(!0)),children:[Jl(yt,{}),Jl("span",{className:e.text,children:t})]})},Yl=nh;var dr={};j(dr,{enUS:()=>rh,nlNL:()=>ih});var rh={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"}]},ih={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 ed={root:"dd-oa7Vc",isInline:"dd-bwk31",toggleButton:"dd-MSB8Z",toggleButtonWrapper:"dd-ZkCzT",toggleButtonWrapperHidden:"dd-Sq66c",isCollapsed:"dd-vkrPk",collapsible:"dd-CWQJe",hints:"dd-IOoo3",hintsHidden:"dd-psVuT",triggers:"dd-toIoo",triggersRight:"dd-mc4l2"};import{jsx as W,jsxs as so}from"react/jsx-runtime";var ph=({textSuggestions:t,selectedIndex:e,onLogIn:o})=>{let n=h("SuggestionsOverlay",ed),s=k(dr),r=no(wt),i=Si(),a=uh(),d=lh(null),l=w("searchTriggerKey"),c=w("productName"),p=no(gn),u=no(X),m=no(mt),[g,f]=dh(null),y=w("showSearch"),b=w("showTextSuggestions"),v=w("adminUrl"),S=w("isEmbedded"),[R,C]=Gl("dd-snooze-until-ms",0),E=p||R>Date.now(),O=no(F=>F.input.text),Q=t.filter(F=>F.source!=="gpt").length,B=()=>{E&&C(0),a(Hl(!E))},L=F=>{a(G({name:"suggestion feedback",data:{text:F.text,source:"overlay",context:O},options:{includeConversationData:!0}}))},_=F=>{let z=Date.now()+F*1e3;C(z),x.info(`Snooze until: ${new Date(z)}`),a(Fe({collapse:!0}))};return ah(()=>{Q===0&&f(null)},[t,Q]),Ze(()=>{a(Fe({collapse:!0,skipWhenInputFocus:!0}))}),u===null||m===!1?null:u===!1?so("div",{ref:d,className:cr(n.root,{[n.isCollapsed]:E}),children:[!E&&so("div",{className:n.triggers,children:[W("div",{style:{flex:1}}),W("div",{className:n.triggersRight,children:W(lt,{className:n.toggleButton,title:s("collapse"),onClick:B,isCollapsed:!1})})]}),W("div",{className:n.toggleButtonWrapper,children:W(lt,{className:n.toggleButton,title:s("open",{productName:c}),onClick:B,isCollapsed:!0})}),W("div",{className:n.collapsible,children:W(bn,{loginUrl:v,isEmbedded:S,onLogIn:o,onSnooze:_})})]}):!i||!r?null:so("div",{ref:d,className:cr(n.root,{[n.isCollapsed]:E}),children:[!E&&so("div",{className:n.triggers,children:[W("div",{style:{flex:1},children:y&&W("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>f(s($l()?"searchHintMac":"searchHintWindows",{searchTriggerKey:l.toUpperCase()})),onMouseLeave:()=>f(null),children:W(Yl,{title:s("search")})})}),so("div",{className:n.triggersRight,onFocus:()=>{},children:[W("div",{className:cr(!g&&n.hintsHidden,n.hints),children:g}),W(lt,{className:n.toggleButton,title:s("collapse"),onClick:B,isCollapsed:!1})]})]}),W("div",{className:n.toggleButtonWrapper,children:W(lt,{className:n.toggleButton,title:s("open",{productName:c}),onClick:B,isCollapsed:!0})}),Q>0&&b&&W("div",{className:n.collapsible,onFocus:()=>{},children:W(Y,{children:W(hn,{onFeedback:L,suggestions:t,selectedIndex:e,reverse:!0})})})]})},mh=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),td=ch(mh)(ph);import br from"classnames";import{Interweave as cy}from"interweave";import{useCallback as uy,useEffect as py,useMemo as kd,useRef as my}from"react";import{connect as gy}from"react-redux";import{useEffect as gh,useRef as fh,useState as hh}from"react";function Cn(t){return t.contentEditable==="true"}function yh(t){let e=0,o=0,n=window.getSelection();if(n.rangeCount!==0){let s=n.getRangeAt(0),r=s.cloneRange();r.selectNodeContents(t),r.setEnd(s.endContainer,s.endOffset),o=r.toString().length,r.selectNodeContents(t),r.setEnd(s.startContainer,s.startOffset),e=r.toString().length}return{selectionStart:e,selectionEnd:o}}function od(t){let{selectionStart:e,selectionEnd:o}=Cn(t)?yh(t):t;return[e,o]}function nd(t){let[,e]=hh(),o=fh(null);return o.current=od(t),gh(()=>{let n=()=>{let[s,r]=o.current??[],i=od(t);(!i||s!==i[0]||r!==i[1])&&(o.current=i,e({}))};return t.addEventListener("keyup",n),t.addEventListener("click",n),t.addEventListener("focus",n),document.addEventListener("selectionchange",n),()=>{t.removeEventListener("keyup",n),t.removeEventListener("click",n),t.removeEventListener("focus",n),document.removeEventListener("selectionchange",n)}},[t]),o.current}function sd(t,e){if(!e)return;let o=t,{value:n}=o,[s,r]=e,i=n.match(wo);if(!i||i.length===0)return;let a=0;i.find(d=>{let l=n.indexOf(d,a);return s>l&&r<l+d.length?(o.selectionStart=l,o.selectionEnd=l+d.length,!0):(a=l+d.length,!1)})}import{cloneElement as vh}from"react";var Sh=["div","span","mark","strong","b","i","u","em"];function ur(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(Sh.includes(s)){let i=Array.isArray(n.props.children)?n.props.children:[n.props.children];return[...t.slice(0,t.length-1),vh(n,{children:ur(i,e,o+1)})]}return[...t,...e]}function He(t){return t.tagName.toLowerCase()==="textarea"}var rd={agentText:"dd-qnW-V",tabText:"dd-cUHUr",hint:"dd-v7fSg",matchSelection:"dd-8cr8y",focus:"dd-3tr9l",resetIndent:"dd-TvQfZ",matchKeyword:"dd-oJkRD",matchPlaceholder:"dd-QvNoo",hover:"dd--wi0R",hintText:"dd-7gQQh",popover:"dd-xbRu-",popoverRoot:"dd-rA2x8",popoverContentContainer:"dd-JHICl",popoverContent:"dd--mfkC",selectionOptions:"dd-p52wn",selectionOptionsIsHidden:"dd-sSTDp",selectionOptionsButton:"dd-Q6kRY",caret:"dd-jIhc8",popoverSuggestionsRoot:"dd-iFDbL",suggestionsOverlayInputStyles:"dd-zzENA"};import Bh from"classnames";import{Matcher as Kh}from"interweave";import{useEffect as Uh,useMemo as zh}from"react";import{useEffect as xh,useRef as bh,useState as Ch}from"react";function id(t,e){let o;return[(...n)=>{window.cancelAnimationFrame(o);let s=e?e(...n):n;o=window.requestAnimationFrame(()=>{t(...s)})},()=>window.cancelAnimationFrame(o)]}function wn(t){let e=bh(null),[o,n]=Ch(!1);return xh(()=>{let s=!1,r=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[i,a]=id((c,p)=>{let u=e.current;if(!u)return;let m=c/r,g=p/r,f=u.getBoundingClientRect(),y=m>f.x&&m<f.x+f.width&&g>f.y&&g<f.y+f.height;y&&!s?(s=!0,n(!0)):!y&&s&&(s=!1,n(!1))},({clientX:c,clientY:p})=>[c,p]),[d,l]=id(()=>{s=!1,n(!1)});return t.addEventListener("mousemove",i),t.addEventListener("mouseleave",d),()=>{a(),l(),t.removeEventListener("mousemove",i),t.removeEventListener("mouseleave",d)}},[e]),[e,o]}function ad(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Tn(t){return e=>{t.forEach(o=>{typeof o=="function"?o(e):o!=null&&(o.current=e)})}}function ld(t){return t!=null}import md from"classnames";import{createRef as Mh,useCallback as mr,useMemo as Nh,useRef as Oh,useState as Dh}from"react";import{useState as wh,useLayoutEffect as Th}from"react";var Eh=["bottom","height","left","right","top","width"],kh=(t={},e={})=>Eh.some(o=>t[o]!==e[o]),Ee=new Map,dd,cd=()=>{let t=[],e=[];Ee.forEach((o,n)=>{if(n instanceof Element&&!n.isConnected){e.push(n);return}let s=n.getBoundingClientRect();kh(s,o.rect)&&(o.rect=s,t.push(o))}),e.forEach(o=>{Ee.delete(o)}),t.forEach(o=>{o.callbacks.forEach(n=>n(o.rect))}),dd=window.requestAnimationFrame(cd)};function Rh(t,e){return{observe(){let o=Ee.size===0;if(Ee.has(t)){let n=Ee.get(t);n.callbacks.push(e),n.rect&&e(n.rect)}else Ee.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});o&&cd()},unobserve(){let o=Ee.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||Ee.delete(t),Ee.size||cancelAnimationFrame(dd)}}}}function pr(t){let[e,o]=wh(null);return Th(()=>{if(!t.current)return;let n=Rh(t.current,s=>{o(s)});return n.observe(),()=>{n.unobserve()}},[t]),e}import{useContext as Ph,useLayoutEffect as Ih,useState as Ah}from"react";import{createPortal as Lh}from"react-dom";var ud={root:"dd-r-dgo"};var pd=({children:t,parentNode:e})=>{let[o,n]=Ah(null),s=Ph(_t);return Ih(()=>{let r=document.createElement("div");return Je(r),r.classList.add(ud.root),s!=null&&s.portalRootNode&&r.classList.add(s==null?void 0:s.portalRootNode),(e||document.body).appendChild(r),n(r),()=>{r.isConnected&&r.remove()}},[]),o?Lh(t,o):null};var me={ref:"dd-iz-KP",root:"dd-vEMon",positionAbove:"dd-mUCxM",positionBelow:"dd-7oZI7",positionLeft:"dd-BiWvD",positionRight:"dd-JIWea",alignStart:"dd-5ivu6",alignCenter:"dd-rnVkP",alignEnd:"dd-gZBp4"};import{jsx as gr}from"react/jsx-runtime";var En=(t=!1)=>{let[e,o]=Dh(t),n=mr(()=>o(!0),[]),s=mr(()=>o(!1),[]),r=mr(()=>o(a=>!a),[]),i=Oh(null);return{opened:e,open:n,close:s,toggle:r,triggerRef:i}};function fr(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 Tt=({className:t,triggerRef:e,boundaryRef:o=Mh(),position:n="above",align:s="center",children:r,toStyle:i=fr,parentNode:a,...d})=>{let l=pr(e),c=pr(o),p=Nh(()=>i(l,c,0),[l,c]);return gr(pd,{parentNode:a,children:gr("div",{className:md(me.ref,{[me.positionAbove]:n==="above",[me.positionBelow]:n==="below",[me.positionLeft]:n==="left",[me.positionRight]:n==="right",[me.alignStart]:s==="start",[me.alignCenter]:s==="center",[me.alignEnd]:s==="end"}),style:p,...d,role:"dialog",children:gr("div",{className:md(t,me.root),children:r})})})};import _h from"classnames";import{forwardRef as Fh,useRef as Hh}from"react";var ke={agentText:"dd-qnW-V",tabText:"dd-cUHUr",hint:"dd-v7fSg",matchSelection:"dd-8cr8y",focus:"dd-3tr9l",resetIndent:"dd-TvQfZ",matchKeyword:"dd-oJkRD",matchPlaceholder:"dd-QvNoo",hover:"dd--wi0R",hintText:"dd-7gQQh",popover:"dd-xbRu-",popoverRoot:"dd-rA2x8",popoverContentContainer:"dd-JHICl",popoverContent:"dd--mfkC",selectionOptions:"dd-p52wn",selectionOptionsIsHidden:"dd-sSTDp",selectionOptionsButton:"dd-Q6kRY",caret:"dd-jIhc8",popoverSuggestionsRoot:"dd-iFDbL",suggestionsOverlayInputStyles:"dd-zzENA"};import{jsx as gd}from"react/jsx-runtime";var kn=Fh(({className:t,children:e,...o},n)=>{let s=Hh(null),r=h("TabCompletion",ke);return gd("div",{ref:Tn([s,n]),className:_h(t,r.popoverContentContainer),...o,children:gd("div",{className:r.popoverContent,children:e})})});import{jsx as ro,jsxs as qh}from"react/jsx-runtime";var Vh=t=>e=>{let o=fr(e);return"top"in o&&(o.width=t.width-(e.left-t.left)-10),o},Wh=({inputElement:t,boundaryRef:e,inputStyle:o,children:n,suggestion:s})=>{let r=h("TabCompletion",ke),i=En(),a=zh(()=>Vh(t.getBoundingClientRect()),[t]),[d,l]=wn(t);return Uh(()=>{l?i.open():i.close()},[l]),qh("span",{children:[ro("mark",{ref:Tn([d,i.triggerRef]),className:Bh(r.matchKeyword,{[r.hover]:l}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:n}),i.opened&&ro(Tt,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:ro(kn,{style:o,children:ro("div",{className:r.hintText,children:s})})})]})},Rn=class extends Kh{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${ad(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(ld);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 ro(Wh,{inputElement:o.inputElement,suggestion:o.suggestion,inputStyle:o.inputStyle,boundaryRef:o.boundaryRef,children:e},`keyword_${o.matchString}_${o.key}`)}asTag(){return"mark"}};import{Matcher as Gh}from"interweave";import $h from"classnames";import{jsx as fd}from"react/jsx-runtime";var jh=({inputElement:t,children:e})=>{let o=h("TabCompletion",ke),[n,s]=wn(t);return fd("mark",{ref:n,className:$h(o.matchPlaceholder,{[o.hover]:s}),children:e})},Pn=class extends Gh{match(e){let o=e.match(/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\}(?!\}))/);return o?{index:o.index,length:o[0].length,match:o[0],matchString:o[0],valid:!0}:null}replaceWith(e,o){return fd(jh,{inputElement:o.inputElement,children:e},`placeholder_${o.matchString}_${o.key}`)}asTag(){return"mark"}};import xr from"classnames";import{Matcher as ny}from"interweave";import{createRef as sy,forwardRef as ry,useCallback as iy,useEffect as wd,useRef as Td,useState as Ed}from"react";import{useDispatch as ay}from"react-redux";import{jsx as hd}from"react/jsx-runtime";var yd=()=>hd("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:hd("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 Xh,useEffect as Sd,useState as xd}from"react";import{useDispatch as Qh,useSelector as bd}from"react-redux";import Zh from"lodash.debounce";var vd={root:"dd-ky-Bv",content:"dd-kV5e1"};function In(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 hr(t){return t.replace("https://www.","").replace("https://","")}import{jsx as et,jsxs as yr}from"react/jsx-runtime";var Jh=3,Yh=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),ey=({onSelectLink:t,onDismiss:e,placeholder:o,visitUrlText:n,linkCount:s=Jh})=>{let r=h("LinkSearch",vd),[i,a]=xd(""),d=Qh(),l=bd(xl("url")),c=bd(zi("URL",Yh)),[p,u]=xd(c.length-1),m=w("fallbackImage"),g=v=>{let S=v.target;a(S.value)},f=(v,S)=>{v.stopPropagation(),v.preventDefault(),window.open(S,"_blank")},y=v=>{var C;let S=p-1<0?c.length-1:p-1,R=p+1===c.length?0:p+1;v.code==="Escape"&&(a(""),e()),v.code==="ArrowUp"&&u(S),v.code==="ArrowDown"&&u(R),v.code==="Enter"&&t(((C=c[p])==null?void 0:C.text)||i)},b=Xh(Zh(v=>{d(qe({query:v,type:"URL",tags:["link-search"]}))},300),[]);return Sd(()=>{i&&b(i)},[i]),Sd(()=>()=>{d(Ho())},[]),yr("div",{className:r.root,children:[et(Y,{withDivider:!0,children:(i?c:l).slice(0,s).map((v,S)=>et(A,{selected:p===S,onClick:()=>t(v.text),"data-testid":"linksearch-suggestion",children:yr(D,{children:[et(D.Image,{src:In(v,"small",m||void 0),title:v.title||v.text}),yr(D.Content,{className:r.content,cropText:!0,children:[et(D.Title,{children:v.title||hr(v.text)}),v.title&&hr(v.text)]}),et(A.Actions,{children:et(A.ActionButton,{label:n,onClick:R=>f(R,v.text)})})]})},v.text))}),et($t,{value:i,onChange:g,autoFocus:!0,placeholder:o,onKeyUp:y})]})},Cd=ey;var vr={};j(vr,{enUS:()=>ty,nlNL:()=>oy});var ty={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},oy={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};import{jsx as ge,jsxs as Sr}from"react/jsx-runtime";var ly=ry((t,e)=>{let o=h("TabCompletion",ke);return ge("mark",{ref:e,className:xr(o.matchSelection)},"selection-start")}),dy=({startRef:t,boundaryRef:e,inputStyle:o,inputElement:n,children:s})=>{let r=k(vr),i=h("TabCompletion",ke),a=Td(null),d=Td(null),[l,c]=Ed(null),p=ay(),u=En(document.activeElement===n),[m]=Ed(()=>document.createRange());u.triggerRef.current=m,wd(()=>()=>m.detach(),[]),wd(()=>{let f=t.current,y=a.current;!f||!y||(m.setStart(f,0),m.setEnd(y,0))},[t.current,a.current]),Ze(()=>{u.close()});let g=iy(f=>{let y=m.toString(),b=/^http(s?):\/\//.test(f)?f:`https://${f}`;p(No({text:`[${y}](${b})`,replace:"selection"}))},[]);return Sr("span",{children:[ge("mark",{ref:a,className:xr(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":u.opened?"true":"false",children:s}),u.opened&&ge(Tt,{className:i.popoverRoot,triggerRef:u.triggerRef,boundaryRef:e,position:"above",align:"start",children:Sr(kn,{style:o,ref:d,children:[ge("div",{className:xr(i.selectionOptions,{[i.selectionOptionsIsHidden]:l!==null}),children:Sr("button",{type:"button",tabIndex:l===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>c("insertLink"),children:[ge(yd,{}),ge("span",{children:"\xA0"}),ge("span",{children:r("insertLink")})]})}),l==="insertLink"&&ge(Cd,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:g,onDismiss:()=>{c(null),u.close()}})]})})]},"selection-end")},An=class extends ny{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(e,o){return this.props=o,this.charCount=0,this.startRef=sy(),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?ge(ly,{ref:this.startRef}):ge(dy,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};import{useSelector as fy}from"react-redux";import{jsx as Et,jsxs as vy}from"react/jsx-runtime";var hy=({enabled:t,content:e,tabText:o,showTabHint:n,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:d})=>{let l=h("TabCompletion",rd),c=w("insertLink"),p=w("showMidSentenceSuggestions"),u=w("inlineSuggestions"),m=nd(a),g=my(null),f=fy(X);py(()=>{He(a)&&m&&sd(a,m)},[m]);let y=uy(S=>{if(!s||!o)return S;let R=[Et("span",{className:l.resetIndent,children:"\u200B"},"u200B"),Et("span",{"data-testid":"tab-completion",className:br(l.tabText,l.resetIndent),"data-source":d,children:o},"tabText")];return n&&R.push(Et("span",{className:br(l.hint,l.resetIndent),children:Et(es,{keyCode:"tab"},"tabHint")})),ur(S,R)},[s,o,n]),b=kd(()=>{let S=[];return c&&S.push(new An("selection")),S.push(new Pn("placeholders")),r&&S.push(new Rn("keywords")),S},[u,c,r]),v=kd(()=>{let S=window.getComputedStyle(a);return{"--dd-color":S.color,"--dd-font-size":S.fontSize,"--dd-font-family":S.fontFamily,"--dd-font-variant":S.fontVariant}},[]);return!t||!f?null:vy("div",{ref:S=>{S!=null&&S.parentElement&&(g.current=S==null?void 0:S.parentElement)},className:l.root,style:v,children:[Et(cy,{tagName:"span",containerTagName:"div",className:br(l.container,l.agentText),disableLineBreaks:He(a),content:e||"\u200B",onAfterParse:y,matchers:b,selection:m,keywordMatches:i,inputElement:a,inputStyle:v,boundaryRef:g,inlineSuggestionsOnlyAtEnd:!p}),Et("br",{})]})},yy=({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)||"",d=t.html??Qt(t.text),l=i.indexOf(t.text)===0?i.slice(t.text.length):"",{showTabHint:c}=e,{isSupported:p}=s,{showTabCompletion:u,visible:m,showStyleSuggestions:g}=o;return{showTabHint:c,showStyleSuggestions:g,showTabCompletion:u,content:d,tabText:l,source:a,keywordMatches:((f=n.list)==null?void 0:f.keywordMatches)??[],enabled:m&&p!==!1}},Rd=gy(yy)(hy);import Tv from"classnames";import{Fragment as Ev,useEffect as _c}from"react";import{useDispatch as Fn,useSelector as K}from"react-redux";import{createAsyncThunk as io,createSlice as Sy}from"@reduxjs/toolkit";var Pd={list:[],fetchState:"idle"},Ad=t=>t.autoflows.list||[],Id=t=>e=>{var o;return(o=e.list)==null?void 0:o.find(n=>n.triggerPayload===t)},Re=io("autoflows/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getAutoflows(t)}),Cr=io("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(Re(t.platformSessionId))}),wr=io("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(Re(t.platformSessionId))}),xy=Sy({name:"autoflows",initialState:Pd,reducers:{},extraReducers:t=>{t.addCase(Cr.pending,(e,o)=>{let n=Id(o.meta.arg.triggerPayload)(e);n.state="Started",n.isBusy=!0}),t.addCase(wr.pending,(e,o)=>{let n=Id(o.meta.arg.triggerPayload)(e);n.state="Aborted",n.isBusy=!0}),t.addCase(Re.pending,e=>{e.fetchState="loading"}),t.addCase(Re.rejected,e=>{e.fetchState="error"}),t.addCase(Re.fulfilled,(e,o)=>{e.list=o.payload,e.fetchState="done"}),t.addCase(M,()=>Pd)}}),Ld=io("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(Re(t))}),s.on("sessionCompleted",()=>{o(Re(t))})}),Md=io("autoflows/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),Nd=xy.reducer;import{createAsyncThunk as lo,createSlice as by}from"@reduxjs/toolkit";var Od={list:[],fetchState:"idle",sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},Dd=t=>t.customMessages.list,_d=t=>e=>!!e.customMessages.sentSuggestions.find(o=>o===t),Fd=t=>e=>!!e.customMessages.answeredSuggestions.find(o=>o===t),Hd=t=>e=>!!e.customMessages.errorSuggestions.find(o=>o===t),ao=lo("customMessages/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getCustomMessages(t)}),Ln=lo("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)}),Mn=lo("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)}),Bd=by({name:"customMessages",initialState:Od,reducers:{onCustomMessage(t,e){Array.isArray(e.payload)?t.list=e.payload:t.list=[e.payload]}},extraReducers:t=>{t.addCase(ao.pending,e=>{e.fetchState="loading"}).addCase(ao.rejected,e=>{e.fetchState="error"}).addCase(ao.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload||[]}).addCase(Ln.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.errorSuggestions=e.errorSuggestions.filter(n=>o.meta.arg.suggestion.text!==n)}).addCase(Ln.rejected,(e,o)=>{let n=e.sentSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1))}).addCase(Mn.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.answeredSuggestions.push(o.meta.arg.suggestion.text)}).addCase(Mn.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,()=>Od)}}),Kd=lo("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(Bd.actions.onCustomMessage(r))})}),Ud=lo("customMessages/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),zd=Bd.reducer;var Vd=t=>e=>{let{passwordlessToken:{token:o},settings:{isEmbedded:n,adminUrl:s}}=e;return s?n?o?`${s}/apis/admin/session/passwordless/login/?token=${o}&redirect=${t}`:null:`${s}${t}`:null};import{createAsyncThunk as Wd,createSlice as Cy}from"@reduxjs/toolkit";var wy={token:null,interval:null},Tr=Wd("passwordlessToken/getTemporaryPasswordlessToken",async(t,e)=>{let{deepdeskAPI:o}=e.extra;return{token:await o.requestPasswordlessToken()}}),Er=Wd("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:o=1e3*60*10}=t,{dispatch:n}=e;return n(Tr()),setInterval(()=>n(Tr()),o)}),qd=Cy({name:"passwordlessToken",initialState:wy,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(Tr.fulfilled,(e,o)=>{e.token=o.payload.token}),t.addCase(Er.fulfilled,(e,o)=>{e.interval=o.payload})}}),{stopPollPasswordlessToken:Gd}=qd.actions,$d=qd.reducer;import{createAction as Ty,createAsyncThunk as Ey,createSlice as ky}from"@reduxjs/toolkit";var kr={cues:[],fetchState:"idle"},jd=t=>{var e;return(e=t.rules)==null?void 0:e.cues},Ry=Ty("rules/resetCues"),tt=Ey("rules/evaluate",async(t,e)=>{var o,n;try{let{deepdeskAPI:s}=e.extra,r=e.getState(),i=(o=r.conversation.current)==null?void 0:o.id;if(!i)throw new Error("No current conversation to evaluate rules");if(!(await s.getAccount()).ruleEngine)throw new Error("Rule engine is not enabled for this account");if(!(await s.getRules()).some(c=>c.label===t.label))throw new Error(`No rules found with label: ${t.label}`);return await s.evaluateRule(t.label,i,{tags:((n=r.conversation.current)==null?void 0:n.tags)||void 0,...t.params})}catch(s){return x.info(s.message),[]}}),Xd=ky({name:"answer",initialState:kr,reducers:{removeCue(t,e){t.cues=t.cues.filter(o=>o.rule.id!==e.payload.id)}},extraReducers:t=>{t.addCase(tt.pending,e=>{e.fetchState="loading"}).addCase(tt.rejected,e=>{e.fetchState="error"}).addCase(tt.fulfilled,(e,o)=>{let n=o.payload.map(r=>r.rule.id),s=e.cues.filter(r=>!n.includes(r.rule.id));e.fetchState="done",e.cues=[...o.payload,...s]}).addCase(M,()=>kr).addCase(Ry.toString(),()=>kr)}}),{removeCue:Qd}=Xd.actions,Zd=Xd.reducer;import{Fragment as Fy}from"react";import{connect as Hy}from"react-redux";import Oy from"classnames";import{Fragment as Dy}from"react";import Py from"classnames";var Jd={root:"dd-uszkm"};import{jsx as Ay}from"react/jsx-runtime";var Iy=({className:t,children:e})=>{let o=h("Unicode",Jd);return Ay("span",{className:Py(t,o.root),children:e})},Yd=Iy;var ec={isDisabled:"dd-Sp--t",root:"dd-maqTG",buttonStop:"dd-rcq8w",stateBadge:"dd-zOnkT",isCompleted:"dd-GA-rt",isStarted:"dd-PZwtX",isAborted:"dd-PAXSE"};var Rr={};j(Rr,{enUS:()=>Ly,nlNL:()=>My});var Ly={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"}]},My={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 ot,jsxs as Nn}from"react/jsx-runtime";var _y=({disabled:t,state:e,displayName:o,description:n,onStartAutoflow:s,onStopAutoflow:r})=>{let i=h("Autoflow",ec),a=k(Rr),d=e==="Started"?"stop":"start",l=d==="start"?"\u25B6":d==="stop"?"\u25FC":"";return Nn(A,{className:Oy(i.root,{[i.isDisabled]:t,[i.isCompleted]:e==="Completed",[i.isAborted]:e==="Aborted",[i.isStarted]:e==="Started"}),children:[ot(D,{children:Nn(D.Content,{children:[Nn(D.Title,{children:[e&&ot("span",{className:i.stateBadge,children:a(e)}),o]}),ot("span",{children:n})]})}),ot(A.Actions,{fixed:e==="Started",children:ot(A.ActionButton,{primary:!0,className:d==="start"?i.buttonStart:i.buttonStop,onClick:e==="Started"?r:s,disabled:t,label:Nn(Dy,{children:[ot(Yd,{children:l})," ",ot("span",{children:a(d)})]})})})]})},tc=_y;import{jsx as oc}from"react/jsx-runtime";var By=(t,e)=>{let o=e.filter(n=>n.state==="Started");return o.length>0?o.indexOf(t)===-1:!1},Ky=({autoflows:t,onStartAutoflow:e,onStopAutoflow:o,platformSessionId:n})=>oc(Fy,{children:t.map(s=>oc(tc,{displayName:s.displayName,description:s.description,disabled:s.isBusy||By(s,t),state:s.state,onStartAutoflow:()=>e({platformSessionId:n,triggerPayload:s.triggerPayload}),onStopAutoflow:()=>o({platformSessionId:n,triggerPayload:s.triggerPayload})},s.displayName))}),Uy=({autoflows:t,conversation:e})=>{var o;return{autoflows:t.list,platformSessionId:(o=e.current)==null?void 0:o.sessionId}},zy={onStartAutoflow:Cr,onStopAutoflow:wr},nc=Hy(Uy,zy)(Ky);import Vy from"classnames";import{useCallback as sc}from"react";import{useDispatch as Wy,useSelector as On}from"react-redux";var Pe={root:"dd-ERsBr",title:"dd-b36p6",isUsed:"dd-fp2IX",quickReplies:"dd--VrvP",quickReply:"dd-wFhWh",label:"dd-R9sND",errorIcon:"dd-8cdcH"};import{jsx as Be,jsxs as Dn}from"react/jsx-runtime";var qy=({suggestion:t})=>{let e=k(Xe),o=Wy(),n=On(_d(t.text)),s=On(Fd(t.text)),r=On(Hd(t.text)),i=On(pt),{replyOptions:a}=t,d=sc(c=>{c.preventDefault(),c.stopPropagation(),!(n||!i)&&o(Ln({platformSessionId:i,suggestion:t}))},[t,n,o,i]),l=sc(c=>{if(c.preventDefault(),c.stopPropagation(),!i||!a)return;let p=parseInt(c.target.dataset.index,10),u=a[p];o(Mn({platformSessionId:i,reply:u,suggestion:t}))},[t,n,o,i]);return Dn(A,{onClick:d,className:Vy(Pe.root,{[Pe.isUsed]:n,[Pe.hasError]:r}),children:[Be(D,{children:Dn(D.Content,{children:[Dn(D.Title,{className:Pe.title,children:[t.text," ",Be(ts,{className:Pe.label,children:"analyse tool"})," ",r&&Be("span",{className:Pe.errorIcon,role:"img","aria-label":e("sendingError"),title:e("sendingError"),children:"!"})]}),a&&a.length>0&&Be("ul",{className:Pe.quickReplies,children:a.map(c=>Be("li",{className:Pe.quickReply,children:c.title},c.title))})]})}),Dn(A.Actions,{fixed:r||n,children:[a&&a.length>0&&Be(A.DropdownButton,{label:e("answer"),disabled:s,children:a.map((c,p)=>Be(A.DropdownItem,{index:p,label:c.title,onClick:l},c.title))}),Be(A.ActionButton,{primary:!0,disabled:n,onClick:d,label:e(n?"suggestionSent":r?"tryAgain":"sendSuggestion")})]})]})},rc=qy;import{useEffect as Gy,useState as $y}from"react";import{useDispatch as jy}from"react-redux";import lc from"classnames";import{jsx as ic}from"react/jsx-runtime";var co=()=>ic("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:ic("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 ac={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};import{jsx as kt,jsxs as dc}from"react/jsx-runtime";var Xy=({entities:t})=>{let e=h("EntitiesWidgetList",ac),[o,n]=$y(void 0),s=jy(),r=()=>{n(void 0)},i=a=>{t&&(n(t.indexOf(a)),be(a.text),s(G({name:"entity copied",data:{entity:a,type:"copy"}})))};return Gy(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[o]),!t||t.length===0?null:kt("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,d)=>dc("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[kt("span",{className:e.entityText,children:a.text}),dc("span",{className:e.iconWrapper,children:[kt("span",{className:lc(e.icon),children:kt(co,{})}),kt("span",{className:lc(e.icon,o===d&&e.iconClicked),children:kt(co,{})})]})]},a.text))})},cc=Xy;import{jsx as uc}from"react/jsx-runtime";var pc=()=>uc("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:uc("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 mc}from"react/jsx-runtime";var gc=()=>mc("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:mc("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 fc}from"react/jsx-runtime";var hc=()=>fc("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:fc("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{useDispatch as uv}from"react-redux";import wc from"classnames";import{useEffect as lv,useState as dv}from"react";import{jsx as yc,jsxs as Qy}from"react/jsx-runtime";var vc=({className:t})=>Qy("svg",{viewBox:"0 0 12 12",version:"1.1",xmlns:"http://www.w3.org/2000/svg",className:t,children:[yc("line",{x1:"2",y1:"10",x2:"10",y2:"2",stroke:"black",strokeWidth:"1"}),yc("line",{x1:"2",y1:"2",x2:"10",y2:"10",stroke:"black",strokeWidth:"1"})]});import Zy from"dompurify";import{Fragment as Jy,useMemo as Yy,useRef as ev,useState as tv}from"react";import ov from"snarkdown";var Sc={root:"dd-L7b3z",popover:"dd-OQOTB",options:"dd-Y12RE",copyIcon:"dd-6xOsH",option:"dd-9oFX4",divider:"dd-aiZf8",fadeup:"dd-Jq9pd"};import{jsx as uo,jsxs as xc}from"react/jsx-runtime";function nv(t){return`<button type="button" class=${t}><svg version="1.1" x="0px" y="0px" viewBox="0 0 115.77 122.88" width="10px" height="10px" fill="black"><g><path d="M89.62,13.96v7.73h12.19h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02v0.02 v73.27v0.01h-0.02c-0.01,3.84-1.57,7.33-4.1,9.86c-2.51,2.5-5.98,4.06-9.82,4.07v0.02h-0.02h-61.7H40.1v-0.02 c-3.84-0.01-7.34-1.57-9.86-4.1c-2.5-2.51-4.06-5.98-4.07-9.82h-0.02v-0.02V92.51H13.96h-0.01v-0.02c-3.84-0.01-7.34-1.57-9.86-4.1 c-2.5-2.51-4.06-5.98-4.07-9.82H0v-0.02V13.96v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07V0h0.02h61.7 h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02V13.96L89.62,13.96z M79.04,21.69v-7.73v-0.02h0.02 c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v64.59v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h12.19V35.65 v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07v-0.02h0.02H79.04L79.04,21.69z M105.18,108.92V35.65v-0.02 h0.02c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v73.27v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h61.7h0.02 v0.02c0.91,0,1.75-0.39,2.37-1.01c0.61-0.61,1-1.46,1-2.37h-0.02V108.92L105.18,108.92z"/></g></svg></button>`}function Pr(t){let e=t.cloneNode(!0);return e.querySelectorAll("div,button").forEach(o=>o.remove()),e.textContent??""}function sv(t){return t.replace(/\r\n/g,`
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 Ll}from"react/jsx-runtime";var hf={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},Ml=({className:t,color:e})=>Ll("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:Ll("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:hf[e||"pink"]})});var Nl={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedIn:"dd-XvHAn",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var nr={};j(nr,{enUS:()=>yf,nlNL:()=>vf});var yf={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},vf={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};import{useDispatch as bf}from"react-redux";import{jsx as sr,jsxs as Ol}from"react/jsx-runtime";var Dl=({onLogIn:t})=>{let e=k(nr),o=w("floatingMenu"),n=w("productName"),s=bf(),r=xf(X),i=h("FloatingMenu",Nl);if(r===null||o===!1)return null;let a=()=>{r===!0?s(ee(!0)):t()};return Ol("button",{className:Sf(i.root,{[i.isLoggedIn]:r,[i.isLoggedOut]:!r}),onClick:a,children:[sr("div",{className:i.text,children:e(r?"search":"signin",{productName:n})}),Ol("div",{className:i.icon,children:[sr(Ml,{className:i.logo,color:"pink"}),r===!1&&sr(Al,{className:i.lock})]})]})};import{useEffect as Uf,useRef as zf}from"react";import{connect as Vf,useDispatch as Wf,useSelector as yn}from"react-redux";import{useEffect as Cf}from"react";function Ze(t){Cf(()=>{let e=o=>{o.isWithinRoot||t(o)};return document.body.addEventListener("mouseup",e),()=>{document.body.removeEventListener("mouseup",e)}},[t])}function Je(t){t.addEventListener("mouseup",e=>{e.isWithinRoot=!0},!0)}function wt(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{createSlice as wf}from"@reduxjs/toolkit";var Tf={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var gn=({ui:t})=>t.overlayCollapsed;var _l=wf({name:"ui",initialState:Tf,reducers:{setShowTabHint(t,e){t.showTabHint=e.payload},setInputHasFocus(t,e){t.overlayCollapsedUserOverwrite!==!0&&(e.payload===!0&&(t.overlayCollapsed=!1),t.inputHasFocus=e.payload)},setOverlayCollapsed(t,e){e.payload.collapse===!1&&(t.openOverlayWhenTyping=!1),!(e.payload.skipWhenInputFocus&&t.inputHasFocus)&&(t.overlayCollapsed=e.payload.collapse)},setOpenOverlayWhenTyping(t,e){t.openOverlayWhenTyping=e.payload},setOverlayCollapsedUserOverwrite(t,e){t.overlayCollapsedUserOverwrite=e.payload,t.overlayCollapsed=e.payload}}}),{setShowTabHint:oo,setInputHasFocus:rr,setOverlayCollapsed:Fe,setOpenOverlayWhenTyping:Fl,setOverlayCollapsedUserOverwrite:Hl}=_l.actions,Bl=_l.reducer;import{Fragment as Hf,useMemo as Bf}from"react";import{Interweave as Rf}from"interweave";import{useEffect as Pf,useMemo as If,useRef as Af}from"react";import{useDispatch as Lf,useSelector as Mf}from"react-redux";import{useEffect as Ef}from"react";function Kl(t,e,o){Ef(()=>{let n=t.current;return n?(n.addEventListener(e,o),()=>{n.removeEventListener(e,o)}):()=>{}},[t,e,o])}var Ul={root:"dd-1MBCO",actions:"dd--x4cy",badge:"dd-4Fpkz",formattedText:"dd-EzvTB"};import{jsx as fn,jsxs as Ff}from"react/jsx-runtime";var Nf=["search","personal-collection-search","search-autocomplete"];function Of(t,e,o,n={}){let s="";return Nf.includes(e)?s=fa(Ns(t,o,{stripAgentPart:!0}),n.searchKeywords??[o]):s=Ns(t,o,n),n.placeholders===!0&&(s=ha(s)),s}var Df=()=>{},_f=({index:t,selected:e,suggestion:o,onFeedback:n})=>{let s=w("inlineSuggestions"),r=Mf(ft),i=Lf(),a=h("TextSuggestion",Ul),d=Af(null);Pf(()=>{let c=setTimeout(()=>{i(wi({text:o.text,suggestion:o}))},500);return()=>{clearTimeout(c)}},[o]),Kl(d,"click",()=>{i(Ne(t)),i(pe({suggestion:o,text:o.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let l=If(()=>Of(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:Ff("div",{className:a.root,onMouseEnter:()=>i(Ne(t)),children:[fn(A,{ref:d,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:Df,children:fn(Rf,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:l})}),e&&n&&fn("div",{className:a.actions,children:fn(tn,{onFeedback:()=>n(o),suggestion:o.text})})]})},zl=_f;import{jsx as Vl}from"react/jsx-runtime";var Kf=({onFeedback:t,suggestions:e,selectedIndex:o,reverse:n})=>{let s=Bf(()=>{let r=e.map((i,a)=>Vl(zl,{index:a,selected:a===o,suggestion:i,onFeedback:t},`${i.text}-${i.source}`));return n?r.reverse():r},[e,o,n]);return Vl(Hf,{children:s})},hn=Kf;var Wl={root:"dd-PfvRI",paper:"dd-HYlyY"};import{jsx as vn}from"react/jsx-runtime";var qf=({textSuggestions:t,selectedIndex:e})=>{let o=zf(null),n=h("InlineSuggestionsOverlay",Wl),s=yn(wt),r=Wf(),i=yn(X),a=yn(mt),d=yn(gn),l=w("showTextSuggestions");return Ze(()=>{setTimeout(()=>{r(Fe({collapse:!0,skipWhenInputFocus:!0}))})}),Uf(()=>{let c=o.current;if(!c||!c.parentElement)return;c.parentElement.style.left="0px";let p=c.getBoundingClientRect();c.parentElement.style.left=`${Math.min(window.innerWidth-4-p.right,0)}px`}),d||!s||!l||t.length===0||i!==!0||a===!1?null:vn("div",{className:n.root,"data-variant":"inline",children:vn("div",{ref:o,className:n.paper,children:vn(Y,{children:vn(hn,{suggestions:t,selectedIndex:e})})})})},Gf=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),ql=Vf(Gf)(qf);import{Provider as $f}from"react-redux";import{jsx as Sn}from"react/jsx-runtime";var jf=({children:t})=>{let o=w("locale").replace("-","");return Sn(ks.Provider,{value:o,children:t})},Xf=({store:t,customStyles:e={},children:o})=>Sn($f,{store:t,children:Sn(jf,{children:Sn(_t.Provider,{value:e,children:o})})}),Ye=Xf;import cr from"classnames";import{useEffect as ah,useRef as lh,useState as dh}from"react";import{connect as ch,useDispatch as uh,useSelector as no}from"react-redux";import{useState as Qf}from"react";function Gl(t,e){let[o,n]=Qf(()=>{if(typeof window>"u")return e;try{let r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return x.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){x.error(i)}}]}var $l=()=>/Mac/i.test(navigator.platform);import Yf from"classnames";import{Fragment as eh,useCallback as ar,useMemo as Xl}from"react";var ir={};j(ir,{enUS:()=>Zf,nlNL:()=>Jf});var Zf={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"}]}]},Jf={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 jl={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};import{jsx as xn,jsxs as Ql}from"react/jsx-runtime";var lr=(t,e,o)=>n=>xn("button",{className:t.anchorButton,type:"button",value:e,onClick:o,children:n},e),th=({className:t,loginUrl:e,isEmbedded:o,onSnooze:n,onLogIn:s})=>{let r=k(ir),i=oe(),a=h("Login",jl),d=w("productName"),l=ar(y=>{y.preventDefault(),n&&n(parseInt(y.target.value,10))},[]),c=ar(y=>{y.preventDefault(),i.send(ht,!0)},[e]),p=Xl(()=>y=>xn("a",{onClick:v=>{v.preventDefault(),s()},href:e,className:a.anchor,target:"_blank",rel:"noreferrer",children:y},"login"),[e]),u=ar(y=>xn("button",{type:"button",className:a.anchorButton,onClick:c,children:y},"prompt"),[c]),{min:m,hour:g,day:f}=Xl(()=>({min:lr(a,60*10,l),hour:lr(a,60*60,l),day:lr(a,60*60*12,l)}),[]);return Ql("div",{className:Yf(t,a.root),children:[r("loginPlease",{login:o?u:p,productName:d}),n&&Ql(eh,{children:[xn("br",{}),r("snooze",{min:m,hour:g,day:f})]})]})},bn=th;import{useDispatch as oh}from"react-redux";var Zl={root:"dd-DoQhb",text:"dd-Jwnev"};import{jsx as Jl,jsxs as sh}from"react/jsx-runtime";var nh=({title:t})=>{let e=h("SearchTrigger",Zl),o=oh();return sh("button",{type:"button",className:e.root,onClick:()=>o(ee(!0)),children:[Jl(yt,{}),Jl("span",{className:e.text,children:t})]})},Yl=nh;var dr={};j(dr,{enUS:()=>rh,nlNL:()=>ih});var rh={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"}]},ih={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 ed={root:"dd-oa7Vc",isInline:"dd-bwk31",toggleButton:"dd-MSB8Z",toggleButtonWrapper:"dd-ZkCzT",toggleButtonWrapperHidden:"dd-Sq66c",isCollapsed:"dd-vkrPk",collapsible:"dd-CWQJe",hints:"dd-IOoo3",hintsHidden:"dd-psVuT",triggers:"dd-toIoo",triggersRight:"dd-mc4l2"};import{jsx as W,jsxs as so}from"react/jsx-runtime";var ph=({textSuggestions:t,selectedIndex:e,onLogIn:o})=>{let n=h("SuggestionsOverlay",ed),s=k(dr),r=no(wt),i=Si(),a=uh(),d=lh(null),l=w("searchTriggerKey"),c=w("productName"),p=no(gn),u=no(X),m=no(mt),[g,f]=dh(null),y=w("showSearch"),b=w("showTextSuggestions"),v=w("adminUrl"),S=w("isEmbedded"),[R,C]=Gl("dd-snooze-until-ms",0),E=p||R>Date.now(),O=no(F=>F.input.text),Q=t.filter(F=>F.source!=="gpt").length,B=()=>{E&&C(0),a(Hl(!E))},L=F=>{a(G({name:"suggestion feedback",data:{text:F.text,source:"overlay",context:O},options:{includeConversationData:!0}}))},_=F=>{let z=Date.now()+F*1e3;C(z),x.info(`Snooze until: ${new Date(z)}`),a(Fe({collapse:!0}))};return ah(()=>{Q===0&&f(null)},[t,Q]),Ze(()=>{a(Fe({collapse:!0,skipWhenInputFocus:!0}))}),u===null||m===!1?null:u===!1?so("div",{ref:d,className:cr(n.root,{[n.isCollapsed]:E}),children:[!E&&so("div",{className:n.triggers,children:[W("div",{style:{flex:1}}),W("div",{className:n.triggersRight,children:W(lt,{className:n.toggleButton,title:s("collapse"),onClick:B,isCollapsed:!1})})]}),W("div",{className:n.toggleButtonWrapper,children:W(lt,{className:n.toggleButton,title:s("open",{productName:c}),onClick:B,isCollapsed:!0})}),W("div",{className:n.collapsible,children:W(bn,{loginUrl:v,isEmbedded:S,onLogIn:o,onSnooze:_})})]}):!i||!r?null:so("div",{ref:d,className:cr(n.root,{[n.isCollapsed]:E}),children:[!E&&so("div",{className:n.triggers,children:[W("div",{style:{flex:1},children:y&&W("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>f(s($l()?"searchHintMac":"searchHintWindows",{searchTriggerKey:l.toUpperCase()})),onMouseLeave:()=>f(null),children:W(Yl,{title:s("search")})})}),so("div",{className:n.triggersRight,onFocus:()=>{},children:[W("div",{className:cr(!g&&n.hintsHidden,n.hints),children:g}),W(lt,{className:n.toggleButton,title:s("collapse"),onClick:B,isCollapsed:!1})]})]}),W("div",{className:n.toggleButtonWrapper,children:W(lt,{className:n.toggleButton,title:s("open",{productName:c}),onClick:B,isCollapsed:!0})}),Q>0&&b&&W("div",{className:n.collapsible,onFocus:()=>{},children:W(Y,{children:W(hn,{onFeedback:L,suggestions:t,selectedIndex:e,reverse:!0})})})]})},mh=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),td=ch(mh)(ph);import br from"classnames";import{Interweave as cy}from"interweave";import{useCallback as uy,useEffect as py,useMemo as kd,useRef as my}from"react";import{connect as gy}from"react-redux";import{useEffect as gh,useRef as fh,useState as hh}from"react";function Cn(t){return t.contentEditable==="true"}function yh(t){let e=0,o=0,n=window.getSelection();if(n.rangeCount!==0){let s=n.getRangeAt(0),r=s.cloneRange();r.selectNodeContents(t),r.setEnd(s.endContainer,s.endOffset),o=r.toString().length,r.selectNodeContents(t),r.setEnd(s.startContainer,s.startOffset),e=r.toString().length}return{selectionStart:e,selectionEnd:o}}function od(t){let{selectionStart:e,selectionEnd:o}=Cn(t)?yh(t):t;return[e,o]}function nd(t){let[,e]=hh(),o=fh(null);return o.current=od(t),gh(()=>{let n=()=>{let[s,r]=o.current??[],i=od(t);(!i||s!==i[0]||r!==i[1])&&(o.current=i,e({}))};return t.addEventListener("keyup",n),t.addEventListener("click",n),t.addEventListener("focus",n),document.addEventListener("selectionchange",n),()=>{t.removeEventListener("keyup",n),t.removeEventListener("click",n),t.removeEventListener("focus",n),document.removeEventListener("selectionchange",n)}},[t]),o.current}function sd(t,e){if(!e)return;let o=t,{value:n}=o,[s,r]=e,i=n.match(wo);if(!i||i.length===0)return;let a=0;i.find(d=>{let l=n.indexOf(d,a);return s>l&&r<l+d.length?(o.selectionStart=l,o.selectionEnd=l+d.length,!0):(a=l+d.length,!1)})}import{cloneElement as vh}from"react";var Sh=["div","span","mark","strong","b","i","u","em"];function ur(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(Sh.includes(s)){let i=Array.isArray(n.props.children)?n.props.children:[n.props.children];return[...t.slice(0,t.length-1),vh(n,{children:ur(i,e,o+1)})]}return[...t,...e]}function He(t){return t.tagName.toLowerCase()==="textarea"}var rd={root:"dd-7-cgW",container:"dd-PsRQ8",agentText:"dd-qnW-V",tabText:"dd-cUHUr",hint:"dd-v7fSg",matchSelection:"dd-8cr8y",focus:"dd-3tr9l",resetIndent:"dd-TvQfZ",matchKeyword:"dd-oJkRD",matchPlaceholder:"dd-QvNoo",hover:"dd--wi0R",hintText:"dd-7gQQh",popover:"dd-xbRu-",popoverRoot:"dd-rA2x8",popoverContentContainer:"dd-JHICl",popoverContent:"dd--mfkC",selectionOptions:"dd-p52wn",selectionOptionsIsHidden:"dd-sSTDp",selectionOptionsButton:"dd-Q6kRY",caret:"dd-jIhc8",popoverSuggestionsRoot:"dd-iFDbL",suggestionsOverlayInputStyles:"dd-zzENA"};import Bh from"classnames";import{Matcher as Kh}from"interweave";import{useEffect as Uh,useMemo as zh}from"react";import{useEffect as xh,useRef as bh,useState as Ch}from"react";function id(t,e){let o;return[(...n)=>{window.cancelAnimationFrame(o);let s=e?e(...n):n;o=window.requestAnimationFrame(()=>{t(...s)})},()=>window.cancelAnimationFrame(o)]}function wn(t){let e=bh(null),[o,n]=Ch(!1);return xh(()=>{let s=!1,r=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[i,a]=id((c,p)=>{let u=e.current;if(!u)return;let m=c/r,g=p/r,f=u.getBoundingClientRect(),y=m>f.x&&m<f.x+f.width&&g>f.y&&g<f.y+f.height;y&&!s?(s=!0,n(!0)):!y&&s&&(s=!1,n(!1))},({clientX:c,clientY:p})=>[c,p]),[d,l]=id(()=>{s=!1,n(!1)});return t.addEventListener("mousemove",i),t.addEventListener("mouseleave",d),()=>{a(),l(),t.removeEventListener("mousemove",i),t.removeEventListener("mouseleave",d)}},[e]),[e,o]}function ad(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Tn(t){return e=>{t.forEach(o=>{typeof o=="function"?o(e):o!=null&&(o.current=e)})}}function ld(t){return t!=null}import md from"classnames";import{createRef as Mh,useCallback as mr,useMemo as Nh,useRef as Oh,useState as Dh}from"react";import{useState as wh,useLayoutEffect as Th}from"react";var Eh=["bottom","height","left","right","top","width"],kh=(t={},e={})=>Eh.some(o=>t[o]!==e[o]),Ee=new Map,dd,cd=()=>{let t=[],e=[];Ee.forEach((o,n)=>{if(n instanceof Element&&!n.isConnected){e.push(n);return}let s=n.getBoundingClientRect();kh(s,o.rect)&&(o.rect=s,t.push(o))}),e.forEach(o=>{Ee.delete(o)}),t.forEach(o=>{o.callbacks.forEach(n=>n(o.rect))}),dd=window.requestAnimationFrame(cd)};function Rh(t,e){return{observe(){let o=Ee.size===0;if(Ee.has(t)){let n=Ee.get(t);n.callbacks.push(e),n.rect&&e(n.rect)}else Ee.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});o&&cd()},unobserve(){let o=Ee.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||Ee.delete(t),Ee.size||cancelAnimationFrame(dd)}}}}function pr(t){let[e,o]=wh(null);return Th(()=>{if(!t.current)return;let n=Rh(t.current,s=>{o(s)});return n.observe(),()=>{n.unobserve()}},[t]),e}import{useContext as Ph,useLayoutEffect as Ih,useState as Ah}from"react";import{createPortal as Lh}from"react-dom";var ud={root:"dd-r-dgo"};var pd=({children:t,parentNode:e})=>{let[o,n]=Ah(null),s=Ph(_t);return Ih(()=>{let r=document.createElement("div");return Je(r),r.classList.add(ud.root),s!=null&&s.portalRootNode&&r.classList.add(s==null?void 0:s.portalRootNode),(e||document.body).appendChild(r),n(r),()=>{r.isConnected&&r.remove()}},[]),o?Lh(t,o):null};var me={ref:"dd-iz-KP",root:"dd-vEMon",positionAbove:"dd-mUCxM",positionBelow:"dd-7oZI7",positionLeft:"dd-BiWvD",positionRight:"dd-JIWea",alignStart:"dd-5ivu6",alignCenter:"dd-rnVkP",alignEnd:"dd-gZBp4"};import{jsx as gr}from"react/jsx-runtime";var En=(t=!1)=>{let[e,o]=Dh(t),n=mr(()=>o(!0),[]),s=mr(()=>o(!1),[]),r=mr(()=>o(a=>!a),[]),i=Oh(null);return{opened:e,open:n,close:s,toggle:r,triggerRef:i}};function fr(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 Tt=({className:t,triggerRef:e,boundaryRef:o=Mh(),position:n="above",align:s="center",children:r,toStyle:i=fr,parentNode:a,...d})=>{let l=pr(e),c=pr(o),p=Nh(()=>i(l,c,0),[l,c]);return gr(pd,{parentNode:a,children:gr("div",{className:md(me.ref,{[me.positionAbove]:n==="above",[me.positionBelow]:n==="below",[me.positionLeft]:n==="left",[me.positionRight]:n==="right",[me.alignStart]:s==="start",[me.alignCenter]:s==="center",[me.alignEnd]:s==="end"}),style:p,...d,role:"dialog",children:gr("div",{className:md(t,me.root),children:r})})})};import _h from"classnames";import{forwardRef as Fh,useRef as Hh}from"react";var ke={root:"dd-7-cgW",container:"dd-PsRQ8",agentText:"dd-qnW-V",tabText:"dd-cUHUr",hint:"dd-v7fSg",matchSelection:"dd-8cr8y",focus:"dd-3tr9l",resetIndent:"dd-TvQfZ",matchKeyword:"dd-oJkRD",matchPlaceholder:"dd-QvNoo",hover:"dd--wi0R",hintText:"dd-7gQQh",popover:"dd-xbRu-",popoverRoot:"dd-rA2x8",popoverContentContainer:"dd-JHICl",popoverContent:"dd--mfkC",selectionOptions:"dd-p52wn",selectionOptionsIsHidden:"dd-sSTDp",selectionOptionsButton:"dd-Q6kRY",caret:"dd-jIhc8",popoverSuggestionsRoot:"dd-iFDbL",suggestionsOverlayInputStyles:"dd-zzENA"};import{jsx as gd}from"react/jsx-runtime";var kn=Fh(({className:t,children:e,...o},n)=>{let s=Hh(null),r=h("TabCompletion",ke);return gd("div",{ref:Tn([s,n]),className:_h(t,r.popoverContentContainer),...o,children:gd("div",{className:r.popoverContent,children:e})})});import{jsx as ro,jsxs as qh}from"react/jsx-runtime";var Vh=t=>e=>{let o=fr(e);return"top"in o&&(o.width=t.width-(e.left-t.left)-10),o},Wh=({inputElement:t,boundaryRef:e,inputStyle:o,children:n,suggestion:s})=>{let r=h("TabCompletion",ke),i=En(),a=zh(()=>Vh(t.getBoundingClientRect()),[t]),[d,l]=wn(t);return Uh(()=>{l?i.open():i.close()},[l]),qh("span",{children:[ro("mark",{ref:Tn([d,i.triggerRef]),className:Bh(r.matchKeyword,{[r.hover]:l}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:n}),i.opened&&ro(Tt,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:ro(kn,{style:o,children:ro("div",{className:r.hintText,children:s})})})]})},Rn=class extends Kh{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${ad(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(ld);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 ro(Wh,{inputElement:o.inputElement,suggestion:o.suggestion,inputStyle:o.inputStyle,boundaryRef:o.boundaryRef,children:e},`keyword_${o.matchString}_${o.key}`)}asTag(){return"mark"}};import{Matcher as Gh}from"interweave";import $h from"classnames";import{jsx as fd}from"react/jsx-runtime";var jh=({inputElement:t,children:e})=>{let o=h("TabCompletion",ke),[n,s]=wn(t);return fd("mark",{ref:n,className:$h(o.matchPlaceholder,{[o.hover]:s}),children:e})},Pn=class extends Gh{match(e){let o=e.match(/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\}(?!\}))/);return o?{index:o.index,length:o[0].length,match:o[0],matchString:o[0],valid:!0}:null}replaceWith(e,o){return fd(jh,{inputElement:o.inputElement,children:e},`placeholder_${o.matchString}_${o.key}`)}asTag(){return"mark"}};import xr from"classnames";import{Matcher as ny}from"interweave";import{createRef as sy,forwardRef as ry,useCallback as iy,useEffect as wd,useRef as Td,useState as Ed}from"react";import{useDispatch as ay}from"react-redux";import{jsx as hd}from"react/jsx-runtime";var yd=()=>hd("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:hd("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 Xh,useEffect as Sd,useState as xd}from"react";import{useDispatch as Qh,useSelector as bd}from"react-redux";import Zh from"lodash.debounce";var vd={root:"dd-ky-Bv",content:"dd-kV5e1"};function In(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 hr(t){return t.replace("https://www.","").replace("https://","")}import{jsx as et,jsxs as yr}from"react/jsx-runtime";var Jh=3,Yh=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),ey=({onSelectLink:t,onDismiss:e,placeholder:o,visitUrlText:n,linkCount:s=Jh})=>{let r=h("LinkSearch",vd),[i,a]=xd(""),d=Qh(),l=bd(xl("url")),c=bd(zi("URL",Yh)),[p,u]=xd(c.length-1),m=w("fallbackImage"),g=v=>{let S=v.target;a(S.value)},f=(v,S)=>{v.stopPropagation(),v.preventDefault(),window.open(S,"_blank")},y=v=>{var C;let S=p-1<0?c.length-1:p-1,R=p+1===c.length?0:p+1;v.code==="Escape"&&(a(""),e()),v.code==="ArrowUp"&&u(S),v.code==="ArrowDown"&&u(R),v.code==="Enter"&&t(((C=c[p])==null?void 0:C.text)||i)},b=Xh(Zh(v=>{d(qe({query:v,type:"URL",tags:["link-search"]}))},300),[]);return Sd(()=>{i&&b(i)},[i]),Sd(()=>()=>{d(Ho())},[]),yr("div",{className:r.root,children:[et(Y,{withDivider:!0,children:(i?c:l).slice(0,s).map((v,S)=>et(A,{selected:p===S,onClick:()=>t(v.text),"data-testid":"linksearch-suggestion",children:yr(D,{children:[et(D.Image,{src:In(v,"small",m||void 0),title:v.title||v.text}),yr(D.Content,{className:r.content,cropText:!0,children:[et(D.Title,{children:v.title||hr(v.text)}),v.title&&hr(v.text)]}),et(A.Actions,{children:et(A.ActionButton,{label:n,onClick:R=>f(R,v.text)})})]})},v.text))}),et($t,{value:i,onChange:g,autoFocus:!0,placeholder:o,onKeyUp:y})]})},Cd=ey;var vr={};j(vr,{enUS:()=>ty,nlNL:()=>oy});var ty={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},oy={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};import{jsx as ge,jsxs as Sr}from"react/jsx-runtime";var ly=ry((t,e)=>{let o=h("TabCompletion",ke);return ge("mark",{ref:e,className:xr(o.matchSelection)},"selection-start")}),dy=({startRef:t,boundaryRef:e,inputStyle:o,inputElement:n,children:s})=>{let r=k(vr),i=h("TabCompletion",ke),a=Td(null),d=Td(null),[l,c]=Ed(null),p=ay(),u=En(document.activeElement===n),[m]=Ed(()=>document.createRange());u.triggerRef.current=m,wd(()=>()=>m.detach(),[]),wd(()=>{let f=t.current,y=a.current;!f||!y||(m.setStart(f,0),m.setEnd(y,0))},[t.current,a.current]),Ze(()=>{u.close()});let g=iy(f=>{let y=m.toString(),b=/^http(s?):\/\//.test(f)?f:`https://${f}`;p(No({text:`[${y}](${b})`,replace:"selection"}))},[]);return Sr("span",{children:[ge("mark",{ref:a,className:xr(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":u.opened?"true":"false",children:s}),u.opened&&ge(Tt,{className:i.popoverRoot,triggerRef:u.triggerRef,boundaryRef:e,position:"above",align:"start",children:Sr(kn,{style:o,ref:d,children:[ge("div",{className:xr(i.selectionOptions,{[i.selectionOptionsIsHidden]:l!==null}),children:Sr("button",{type:"button",tabIndex:l===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>c("insertLink"),children:[ge(yd,{}),ge("span",{children:"\xA0"}),ge("span",{children:r("insertLink")})]})}),l==="insertLink"&&ge(Cd,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:g,onDismiss:()=>{c(null),u.close()}})]})})]},"selection-end")},An=class extends ny{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(e,o){return this.props=o,this.charCount=0,this.startRef=sy(),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?ge(ly,{ref:this.startRef}):ge(dy,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};import{useSelector as fy}from"react-redux";import{jsx as Et,jsxs as vy}from"react/jsx-runtime";var hy=({enabled:t,content:e,tabText:o,showTabHint:n,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:d})=>{let l=h("TabCompletion",rd),c=w("insertLink"),p=w("showMidSentenceSuggestions"),u=w("inlineSuggestions"),m=nd(a),g=my(null),f=fy(X);py(()=>{He(a)&&m&&sd(a,m)},[m]);let y=uy(S=>{if(!s||!o)return S;let R=[Et("span",{className:l.resetIndent,children:"\u200B"},"u200B"),Et("span",{"data-testid":"tab-completion",className:br(l.tabText,l.resetIndent),"data-source":d,children:o},"tabText")];return n&&R.push(Et("span",{className:br(l.hint,l.resetIndent),children:Et(es,{keyCode:"tab"},"tabHint")})),ur(S,R)},[s,o,n]),b=kd(()=>{let S=[];return c&&S.push(new An("selection")),S.push(new Pn("placeholders")),r&&S.push(new Rn("keywords")),S},[u,c,r]),v=kd(()=>{let S=window.getComputedStyle(a);return{"--dd-color":S.color,"--dd-font-size":S.fontSize,"--dd-font-family":S.fontFamily,"--dd-font-variant":S.fontVariant}},[]);return!t||!f?null:vy("div",{ref:S=>{S!=null&&S.parentElement&&(g.current=S==null?void 0:S.parentElement)},className:l.root,style:v,children:[Et(cy,{tagName:"span",containerTagName:"div",className:br(l.container,l.agentText),disableLineBreaks:He(a),content:e||"\u200B",onAfterParse:y,matchers:b,selection:m,keywordMatches:i,inputElement:a,inputStyle:v,boundaryRef:g,inlineSuggestionsOnlyAtEnd:!p}),Et("br",{})]})},yy=({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)||"",d=t.html??Qt(t.text),l=i.indexOf(t.text)===0?i.slice(t.text.length):"",{showTabHint:c}=e,{isSupported:p}=s,{showTabCompletion:u,visible:m,showStyleSuggestions:g}=o;return{showTabHint:c,showStyleSuggestions:g,showTabCompletion:u,content:d,tabText:l,source:a,keywordMatches:((f=n.list)==null?void 0:f.keywordMatches)??[],enabled:m&&p!==!1}},Rd=gy(yy)(hy);import Tv from"classnames";import{Fragment as Ev,useEffect as _c}from"react";import{useDispatch as Fn,useSelector as K}from"react-redux";import{createAsyncThunk as io,createSlice as Sy}from"@reduxjs/toolkit";var Pd={list:[],fetchState:"idle"},Ad=t=>t.autoflows.list||[],Id=t=>e=>{var o;return(o=e.list)==null?void 0:o.find(n=>n.triggerPayload===t)},Re=io("autoflows/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getAutoflows(t)}),Cr=io("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(Re(t.platformSessionId))}),wr=io("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(Re(t.platformSessionId))}),xy=Sy({name:"autoflows",initialState:Pd,reducers:{},extraReducers:t=>{t.addCase(Cr.pending,(e,o)=>{let n=Id(o.meta.arg.triggerPayload)(e);n.state="Started",n.isBusy=!0}),t.addCase(wr.pending,(e,o)=>{let n=Id(o.meta.arg.triggerPayload)(e);n.state="Aborted",n.isBusy=!0}),t.addCase(Re.pending,e=>{e.fetchState="loading"}),t.addCase(Re.rejected,e=>{e.fetchState="error"}),t.addCase(Re.fulfilled,(e,o)=>{e.list=o.payload,e.fetchState="done"}),t.addCase(M,()=>Pd)}}),Ld=io("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(Re(t))}),s.on("sessionCompleted",()=>{o(Re(t))})}),Md=io("autoflows/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),Nd=xy.reducer;import{createAsyncThunk as lo,createSlice as by}from"@reduxjs/toolkit";var Od={list:[],fetchState:"idle",sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},Dd=t=>t.customMessages.list,_d=t=>e=>!!e.customMessages.sentSuggestions.find(o=>o===t),Fd=t=>e=>!!e.customMessages.answeredSuggestions.find(o=>o===t),Hd=t=>e=>!!e.customMessages.errorSuggestions.find(o=>o===t),ao=lo("customMessages/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getCustomMessages(t)}),Ln=lo("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)}),Mn=lo("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)}),Bd=by({name:"customMessages",initialState:Od,reducers:{onCustomMessage(t,e){Array.isArray(e.payload)?t.list=e.payload:t.list=[e.payload]}},extraReducers:t=>{t.addCase(ao.pending,e=>{e.fetchState="loading"}).addCase(ao.rejected,e=>{e.fetchState="error"}).addCase(ao.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload||[]}).addCase(Ln.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.errorSuggestions=e.errorSuggestions.filter(n=>o.meta.arg.suggestion.text!==n)}).addCase(Ln.rejected,(e,o)=>{let n=e.sentSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1))}).addCase(Mn.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.answeredSuggestions.push(o.meta.arg.suggestion.text)}).addCase(Mn.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,()=>Od)}}),Kd=lo("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(Bd.actions.onCustomMessage(r))})}),Ud=lo("customMessages/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),zd=Bd.reducer;var Vd=t=>e=>{let{passwordlessToken:{token:o},settings:{isEmbedded:n,adminUrl:s}}=e;return s?n?o?`${s}/apis/admin/session/passwordless/login/?token=${o}&redirect=${t}`:null:`${s}${t}`:null};import{createAsyncThunk as Wd,createSlice as Cy}from"@reduxjs/toolkit";var wy={token:null,interval:null},Tr=Wd("passwordlessToken/getTemporaryPasswordlessToken",async(t,e)=>{let{deepdeskAPI:o}=e.extra;return{token:await o.requestPasswordlessToken()}}),Er=Wd("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:o=1e3*60*10}=t,{dispatch:n}=e;return n(Tr()),setInterval(()=>n(Tr()),o)}),qd=Cy({name:"passwordlessToken",initialState:wy,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(Tr.fulfilled,(e,o)=>{e.token=o.payload.token}),t.addCase(Er.fulfilled,(e,o)=>{e.interval=o.payload})}}),{stopPollPasswordlessToken:Gd}=qd.actions,$d=qd.reducer;import{createAction as Ty,createAsyncThunk as Ey,createSlice as ky}from"@reduxjs/toolkit";var kr={cues:[],fetchState:"idle"},jd=t=>{var e;return(e=t.rules)==null?void 0:e.cues},Ry=Ty("rules/resetCues"),tt=Ey("rules/evaluate",async(t,e)=>{var o,n;try{let{deepdeskAPI:s}=e.extra,r=e.getState(),i=(o=r.conversation.current)==null?void 0:o.id;if(!i)throw new Error("No current conversation to evaluate rules");if(!(await s.getAccount()).ruleEngine)throw new Error("Rule engine is not enabled for this account");if(!(await s.getRules()).some(c=>c.label===t.label))throw new Error(`No rules found with label: ${t.label}`);return await s.evaluateRule(t.label,i,{tags:((n=r.conversation.current)==null?void 0:n.tags)||void 0,...t.params})}catch(s){return x.info(s.message),[]}}),Xd=ky({name:"answer",initialState:kr,reducers:{removeCue(t,e){t.cues=t.cues.filter(o=>o.rule.id!==e.payload.id)}},extraReducers:t=>{t.addCase(tt.pending,e=>{e.fetchState="loading"}).addCase(tt.rejected,e=>{e.fetchState="error"}).addCase(tt.fulfilled,(e,o)=>{let n=o.payload.map(r=>r.rule.id),s=e.cues.filter(r=>!n.includes(r.rule.id));e.fetchState="done",e.cues=[...o.payload,...s]}).addCase(M,()=>kr).addCase(Ry.toString(),()=>kr)}}),{removeCue:Qd}=Xd.actions,Zd=Xd.reducer;import{Fragment as Fy}from"react";import{connect as Hy}from"react-redux";import Oy from"classnames";import{Fragment as Dy}from"react";import Py from"classnames";var Jd={root:"dd-uszkm"};import{jsx as Ay}from"react/jsx-runtime";var Iy=({className:t,children:e})=>{let o=h("Unicode",Jd);return Ay("span",{className:Py(t,o.root),children:e})},Yd=Iy;var ec={isDisabled:"dd-Sp--t",root:"dd-maqTG",buttonStop:"dd-rcq8w",stateBadge:"dd-zOnkT",isCompleted:"dd-GA-rt",isStarted:"dd-PZwtX",isAborted:"dd-PAXSE"};var Rr={};j(Rr,{enUS:()=>Ly,nlNL:()=>My});var Ly={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"}]},My={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 ot,jsxs as Nn}from"react/jsx-runtime";var _y=({disabled:t,state:e,displayName:o,description:n,onStartAutoflow:s,onStopAutoflow:r})=>{let i=h("Autoflow",ec),a=k(Rr),d=e==="Started"?"stop":"start",l=d==="start"?"\u25B6":d==="stop"?"\u25FC":"";return Nn(A,{className:Oy(i.root,{[i.isDisabled]:t,[i.isCompleted]:e==="Completed",[i.isAborted]:e==="Aborted",[i.isStarted]:e==="Started"}),children:[ot(D,{children:Nn(D.Content,{children:[Nn(D.Title,{children:[e&&ot("span",{className:i.stateBadge,children:a(e)}),o]}),ot("span",{children:n})]})}),ot(A.Actions,{fixed:e==="Started",children:ot(A.ActionButton,{primary:!0,className:d==="start"?i.buttonStart:i.buttonStop,onClick:e==="Started"?r:s,disabled:t,label:Nn(Dy,{children:[ot(Yd,{children:l})," ",ot("span",{children:a(d)})]})})})]})},tc=_y;import{jsx as oc}from"react/jsx-runtime";var By=(t,e)=>{let o=e.filter(n=>n.state==="Started");return o.length>0?o.indexOf(t)===-1:!1},Ky=({autoflows:t,onStartAutoflow:e,onStopAutoflow:o,platformSessionId:n})=>oc(Fy,{children:t.map(s=>oc(tc,{displayName:s.displayName,description:s.description,disabled:s.isBusy||By(s,t),state:s.state,onStartAutoflow:()=>e({platformSessionId:n,triggerPayload:s.triggerPayload}),onStopAutoflow:()=>o({platformSessionId:n,triggerPayload:s.triggerPayload})},s.displayName))}),Uy=({autoflows:t,conversation:e})=>{var o;return{autoflows:t.list,platformSessionId:(o=e.current)==null?void 0:o.sessionId}},zy={onStartAutoflow:Cr,onStopAutoflow:wr},nc=Hy(Uy,zy)(Ky);import Vy from"classnames";import{useCallback as sc}from"react";import{useDispatch as Wy,useSelector as On}from"react-redux";var Pe={root:"dd-ERsBr",title:"dd-b36p6",isUsed:"dd-fp2IX",quickReplies:"dd--VrvP",quickReply:"dd-wFhWh",label:"dd-R9sND",errorIcon:"dd-8cdcH"};import{jsx as Be,jsxs as Dn}from"react/jsx-runtime";var qy=({suggestion:t})=>{let e=k(Xe),o=Wy(),n=On(_d(t.text)),s=On(Fd(t.text)),r=On(Hd(t.text)),i=On(pt),{replyOptions:a}=t,d=sc(c=>{c.preventDefault(),c.stopPropagation(),!(n||!i)&&o(Ln({platformSessionId:i,suggestion:t}))},[t,n,o,i]),l=sc(c=>{if(c.preventDefault(),c.stopPropagation(),!i||!a)return;let p=parseInt(c.target.dataset.index,10),u=a[p];o(Mn({platformSessionId:i,reply:u,suggestion:t}))},[t,n,o,i]);return Dn(A,{onClick:d,className:Vy(Pe.root,{[Pe.isUsed]:n,[Pe.hasError]:r}),children:[Be(D,{children:Dn(D.Content,{children:[Dn(D.Title,{className:Pe.title,children:[t.text," ",Be(ts,{className:Pe.label,children:"analyse tool"})," ",r&&Be("span",{className:Pe.errorIcon,role:"img","aria-label":e("sendingError"),title:e("sendingError"),children:"!"})]}),a&&a.length>0&&Be("ul",{className:Pe.quickReplies,children:a.map(c=>Be("li",{className:Pe.quickReply,children:c.title},c.title))})]})}),Dn(A.Actions,{fixed:r||n,children:[a&&a.length>0&&Be(A.DropdownButton,{label:e("answer"),disabled:s,children:a.map((c,p)=>Be(A.DropdownItem,{index:p,label:c.title,onClick:l},c.title))}),Be(A.ActionButton,{primary:!0,disabled:n,onClick:d,label:e(n?"suggestionSent":r?"tryAgain":"sendSuggestion")})]})]})},rc=qy;import{useEffect as Gy,useState as $y}from"react";import{useDispatch as jy}from"react-redux";import lc from"classnames";import{jsx as ic}from"react/jsx-runtime";var co=()=>ic("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:ic("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 ac={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};import{jsx as kt,jsxs as dc}from"react/jsx-runtime";var Xy=({entities:t})=>{let e=h("EntitiesWidgetList",ac),[o,n]=$y(void 0),s=jy(),r=()=>{n(void 0)},i=a=>{t&&(n(t.indexOf(a)),be(a.text),s(G({name:"entity copied",data:{entity:a,type:"copy"}})))};return Gy(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[o]),!t||t.length===0?null:kt("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,d)=>dc("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[kt("span",{className:e.entityText,children:a.text}),dc("span",{className:e.iconWrapper,children:[kt("span",{className:lc(e.icon),children:kt(co,{})}),kt("span",{className:lc(e.icon,o===d&&e.iconClicked),children:kt(co,{})})]})]},a.text))})},cc=Xy;import{jsx as uc}from"react/jsx-runtime";var pc=()=>uc("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:uc("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 mc}from"react/jsx-runtime";var gc=()=>mc("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:mc("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 fc}from"react/jsx-runtime";var hc=()=>fc("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:fc("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{useDispatch as uv}from"react-redux";import wc from"classnames";import{useEffect as lv,useState as dv}from"react";import{jsx as yc,jsxs as Qy}from"react/jsx-runtime";var vc=({className:t})=>Qy("svg",{viewBox:"0 0 12 12",version:"1.1",xmlns:"http://www.w3.org/2000/svg",className:t,children:[yc("line",{x1:"2",y1:"10",x2:"10",y2:"2",stroke:"black",strokeWidth:"1"}),yc("line",{x1:"2",y1:"2",x2:"10",y2:"10",stroke:"black",strokeWidth:"1"})]});import Zy from"dompurify";import{Fragment as Jy,useMemo as Yy,useRef as ev,useState as tv}from"react";import ov from"snarkdown";var Sc={root:"dd-L7b3z",popover:"dd-OQOTB",options:"dd-Y12RE",copyIcon:"dd-6xOsH",option:"dd-9oFX4",divider:"dd-aiZf8",fadeup:"dd-Jq9pd"};import{jsx as uo,jsxs as xc}from"react/jsx-runtime";function nv(t){return`<button type="button" class=${t}><svg version="1.1" x="0px" y="0px" viewBox="0 0 115.77 122.88" width="10px" height="10px" fill="black"><g><path d="M89.62,13.96v7.73h12.19h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02v0.02 v73.27v0.01h-0.02c-0.01,3.84-1.57,7.33-4.1,9.86c-2.51,2.5-5.98,4.06-9.82,4.07v0.02h-0.02h-61.7H40.1v-0.02 c-3.84-0.01-7.34-1.57-9.86-4.1c-2.5-2.51-4.06-5.98-4.07-9.82h-0.02v-0.02V92.51H13.96h-0.01v-0.02c-3.84-0.01-7.34-1.57-9.86-4.1 c-2.5-2.51-4.06-5.98-4.07-9.82H0v-0.02V13.96v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07V0h0.02h61.7 h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02V13.96L89.62,13.96z M79.04,21.69v-7.73v-0.02h0.02 c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v64.59v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h12.19V35.65 v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07v-0.02h0.02H79.04L79.04,21.69z M105.18,108.92V35.65v-0.02 h0.02c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v73.27v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h61.7h0.02 v0.02c0.91,0,1.75-0.39,2.37-1.01c0.61-0.61,1-1.46,1-2.37h-0.02V108.92L105.18,108.92z"/></g></svg></button>`}function Pr(t){let e=t.cloneNode(!0);return e.querySelectorAll("div,button").forEach(o=>o.remove()),e.textContent??""}function sv(t){return t.replace(/\r\n/g,`
8
8
  `)}var rv=({content:t,useLabel:e,copyLabel:o,onCopy:n,onUse:s})=>{let r=h("Markdown",Sc),i=ev(null),[a,d]=tv(null),l=Yy(()=>{let g=ov(sv(t));return Zy.sanitize(g).replace(/<\/code>/g,`${nv(r.copyIcon)}</code>`)},[t]),c=g=>{var b;let f=g.target,y=!!((b=i.current)!=null&&b.querySelector("code"));a||y&&f.tagName!=="CODE"||!y&&f!==i.current||(f.addEventListener("mouseleave",()=>d(null),{once:!0}),d(f))},p=()=>{if(!a)return;d(null);let g=a.querySelector("button");g&&(we(g,r.fadeup),n(Pr(a)))},u=g=>{g.target.tagName.toLowerCase()==="button"&&(we(g.target,r.fadeup),n(Pr(g.target.parentElement)))},m=()=>{a&&(d(null),s(Pr(a)))};return xc(Jy,{children:[a&&uo(Tt,{triggerRef:{current:a},parentNode:a,className:r.popover,children:xc("div",{className:r.options,children:[uo("button",{type:"button",className:r.option,onClick:p,children:o}),uo("div",{className:r.divider}),uo("button",{type:"button",className:r.option,onClick:m,children:e})]})}),uo("div",{ref:i,className:r.root,dangerouslySetInnerHTML:{__html:l},onMouseOver:c,onClick:u})]})},bc=rv;var Ir={};j(Ir,{enUS:()=>iv,nlNL:()=>av});var iv={useCue:[{type:0,value:"Use"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},av={useCue:[{type:0,value:"Gebruik"}],copyCue:[{type:0,value:"Kopieer"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var Cc={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",thumbsUp:"dd-6QwVx",thumbsDown:"dd-d3E8l"};import{jsx as Ie,jsxs as Tc}from"react/jsx-runtime";var cv=({cue:t,onRemove:e,onCopy:o,onUse:n,onThumbsUp:s,onThumbsDown:r})=>{let i=h("WidgetCue",Cc),a=k(Ir),d=xt(),[l,c]=dv(null),p=y=>{o&&o(y,t)},u=y=>{n&&n(y,t)},m=y=>{y.preventDefault(),y.stopPropagation(),e(t)},g=y=>{y.preventDefault(),y.stopPropagation(),we(y.target,i.fadeup),c("up"),s(t)},f=y=>{y.preventDefault(),y.stopPropagation(),we(y.target,i.fadedown),c("down"),r(t)};return lv(()=>{d("Assistant response displayed",{name:t.rule.name,description:t.rule.description,group:t.rule.label,cueText:t.text})},[]),Tc(A,{"data-testid":"cue",children:[Ie(D,{children:Tc(D.Content,{children:[t.title&&Ie(D.Title,{className:i.title,"data-testid":"widget-cue-title",children:t.title}),Ie(bc,{content:t.text,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:p,onUse:u})]})}),Ie(A.IconButton,{title:a("thumbsUp"),onClick:g,icon:Ie(rn,{}),className:wc(i.thumbsUp,l==="up"&&i.selected),disabled:!!l}),Ie(A.IconButton,{title:a("thumbsDown"),onClick:f,icon:Ie(sn,{}),className:wc(i.thumbsDown,l==="down"&&i.selected),disabled:!!l}),Ie(A.IconButton,{title:a("removeCue"),onClick:m,icon:Ie(vc,{})})]})},Ec=cv;import{Fragment as mv,jsx as kc}from"react/jsx-runtime";var pv=({cues:t})=>{let e=uv(),o=oe(),n=xt(),s=l=>{e(Qd({id:l.rule.id})),n("Assistant response closed",{name:l.rule.name,group:l.rule.label,description:l.rule.description,cueText:l.text})},r=(l,c)=>{be(l),n("Assistant response copied",{name:c.rule.name,group:c.rule.label,description:c.rule.description,copiedText:l})},i=(l,c)=>{o.send(Oe,{text:l,suggestion:{source:"cue",sourceText:l}}),n("Assistant response used",{name:c.rule.name,group:c.rule.label,description:c.rule.description,usedText:l})},a=l=>{n("Assistant response feedback",{name:l.rule.name,group:l.rule.label,description:l.rule.description,thumb:"up",cueText:l.text})},d=l=>{n("Assistant response feedback",{name:l.rule.name,group:l.rule.label,description:l.rule.description,thumb:"down",cueText:l.text})};return kc(mv,{children:t.map(l=>kc(Ec,{cue:l,onRemove:s,onCopy:r,onUse:i,onThumbsDown:d,onThumbsUp:a},l.rule.id))})},Rc=pv;import{Fragment as gv,useEffect as fv}from"react";var Pc={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};import{jsx as nt,jsxs as Ic}from"react/jsx-runtime";function hv(t,e){return e.split(".").reduce((o,n)=>!o||typeof o!="object"||!(n in o)?null:o[n],t)}var Ac=({data:t,schema:e})=>{let o=h("WidgetCustomData",Pc),n=s=>{be(s)};return fv(()=>{x.info("Custom data",t,e)},[t]),nt("dl",{className:o.root,children:e.map(s=>{let r=hv(t,s.path);return Ic(gv,{children:[nt("dt",{className:o.label,children:s.label}),nt("dd",{className:o.value,children:s.type==="boolean"&&r?nt("span",{className:o.isTrue,children:s.trueValue}):s.type==="boolean"&&!r?nt("span",{className:o.isFalse,children:s.falseValue}):r?Ic("button",{type:"button",onClick:()=>n(r),className:o.copyButton,children:[nt("span",{children:r}),nt(co,{})]}):"-"})]},s.label)})})};import{useCallback as vv}from"react";var yv=/(https?:\/\/[^\s]+)/,Lc=t=>t.split(" ").find(e=>yv.test(e));import{jsx as Rt,jsxs as _n}from"react/jsx-runtime";var Sv=({suggestion:t,lines:e,onUse:o})=>{var c;let n=t.text||t.url||t.message,s=Lc(n),r=k(Xe),i=w("showImages"),a=w("fallbackImage"),d=p=>{p.preventDefault(),p.stopPropagation(),o(n)},l=vv(p=>{window.open(s,"_blank"),p.stopPropagation(),p.preventDefault()},[s]);return _n(A,{onClick:d,"data-testid":"edit-suggestion",children:[_n(D,{children:[i&&t.image&&Rt(D.Image,{src:In(t,"small",a||void 0),title:t.title}),_n(D.Content,{children:[t.title&&Rt(D.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((c=t.searchKeywords)==null?void 0:c.length)>0&&Rt(A.Labels,{labels:t.searchKeywords}),Rt(D.Content,{cropText:e==="single",lineClamp:e==="multiple",children:n})]})]}),_n(A.Actions,{children:[s&&Rt(A.ActionButton,{onClick:l,label:r("visitUrl")}),Rt(A.ActionButton,{primary:!0,onClick:d,label:r("useSuggestion")})]})]})},Mc=Sv;import{Fragment as bv,jsx as Nc}from"react/jsx-runtime";var xv=({lines:t,suggestions:e})=>{let o=oe(),n=(s,r)=>{o.send(Oe,{text:s,suggestion:{...r,source:r.source,sourceText:r.text}})};return Nc(bv,{children:e.map(s=>Nc(Mc,{suggestion:s,lines:t,onUse:r=>n(r,s)},s.text||s.url||s.message))})},Oc=xv;var po={};j(po,{enUS:()=>Cv,nlNL:()=>wv});var Cv={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"}]},wv={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 mo={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",sectionList:"dd-bF9pF",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",link:"dd-DRo0x"};import{jsx as P,jsxs as Pt}from"react/jsx-runtime";var Hn=(t,e)=>{let o=K(X);_c(()=>o?e.every(n=>!!n)?t():()=>{}:()=>{},[...e,o])},kv=({onLogIn:t})=>{let e=h("Widget",mo),o=w("isEmbedded"),n=w("adminUrl");return P("div",{className:e.loginText,children:P("div",{children:P(bn,{isEmbedded:o,loginUrl:n,onLogIn:t})})},"login")},Dc=({text:t})=>{let e=h("Widget",mo);return P("div",{className:e.stateText,children:P("div",{children:P("p",{children:t})})},"notification")},Rv=()=>{let t=k(po),e=Fn(),o=h("Widget",mo),n=w("showSearch"),s=w("showSummaryCommand"),r=w("showKnowledgeSearch"),i=K(Vd("/admin/")),a=oe(),d=w("productName"),l=n||s||r||i;return Hn(()=>(e(Er()),()=>{e(Gd())}),[e]),l?P(ve,{title:t("actions"),type:"shortcuts",children:Pt("div",{className:o.shortcutList,children:[n&&Pt("button",{type:"button",className:o.shortcut,"data-testid":"shortcut-search","aria-label":t("linkSearch"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0}),children:[P(yt,{}),t("linkSearch")]}),s&&Pt("button",{type:"button",className:o.shortcut,"data-testid":"shortcut-summary","aria-label":t("linkSummary"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[P(hc,{}),t("linkSummary")]}),r&&Pt("button",{type:"button",className:o.shortcut,"data-testid":"shortcut-knowledge-assist","aria-label":t("linkKnowledgeSearch"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[P(gc,{}),t("linkKnowledgeSearch")]}),i&&Pt("a",{className:o.shortcut,target:"_blank",href:i,"data-testid":"shortcut-studio-login","aria-label":t("linkStudioLogin",{productName:d}),rel:"noreferrer",children:[P(pc,{}),t("linkStudioLogin",{productName:d})]})]})}):null},Pv=()=>{let t=Fn(),e=w("showCustomMessages"),o=K(Dd),n=K(pt);return Hn(()=>(t(ao(n)),t(Kd(n)),()=>{t(Ud(n))}),[t,e,n]),!e||o.length===0?null:P(ve,{type:"custom-messages","data-testid":"custom-messages",children:P(Y,{withDivider:!0,children:o.map(s=>P(rc,{suggestion:s},s.text))})})},Iv=()=>{let t=k(po),e=Fn(),o=w("showAutoflows"),n=K(Ad),s=K(pt);return Hn(()=>(e(Re(s)),e(Ld(s)),()=>{e(Md(s))}),[e,o,s]),!o||n.length===0?null:P(ve,{type:"autoflows",title:t("titleAutoflows"),"data-testid":"autoflows",children:P(Y,{withDivider:!0,children:P(nc,{})})})},Av=()=>{let t=Fn(),e=K(cn),o=K(ml),n=K(jd),s=K(Ni),r=K(nn),i=K(un),a=K(Te),d=K(Ro);return _c(()=>{!!s&&!o&&x.warn("Custom data provided, but no schema.")},[s,o]),Hn(()=>{e.forEach(({type:l})=>{l==="entities"?t(ae()):To.includes(l)||t(de(l))})},[t,d,a]),P(Ev,{children:e.map(({type:l,title:c,amount:p,lines:u,schema:m})=>{var g,f;switch(l){case"entities":return r&&r.length>0&&P(ve,{type:l,title:c,"data-testid":`type-${l}`,children:P(cc,{entities:r})},l);case"cues":return n&&n.length>0&&P(ve,{type:l,title:c,"data-testid":`type-${l}`,children:P(Y,{withDivider:!0,children:P(Rc,{cues:n})})},l);case"custom-data":return s&&m&&P(ve,{type:l,title:c,"data-testid":`type-${l}`,children:P(Y,{withDivider:!0,children:P(Ac,{data:s,schema:m})})},l);default:return((f=(g=i[l])==null?void 0:g.suggestions)==null?void 0:f.length)>0&&P(ve,{type:l,title:c,"data-testid":`type-${l}`,children:P(Y,{withDivider:!0,children:P(Oc,{lines:u,contentType:l,suggestions:i[l].suggestions.slice(0,p)||[]})})},l)}})})},Lv=({onLogIn:t})=>{let e=k(po),o=h("Widget",mo),n=K(mt),s=K(X),r=K(pt),i=K(Te);return n===!1?P(Dc,{text:e("notSupported")}):s===!1?P(kv,{onLogIn:t}):!i||!r||s===null?P(Dc,{text:e("waiting")}):P("div",{className:Tv(o.root),"data-testid":"widget",children:Pt(ns,{className:o.sectionList,children:[P(Rv,{}),P(Pv,{}),P(Iv,{}),P(Av,{})]})})},Fc=Lv;function fo(t){let e=new Range;return e.selectNodeContents(t),e}function Hc(t,e,o){try{return st(t,e,o),!0}catch{return!1}}function Bn(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function Kn(t){return"tagName"in t&&t.tagName==="BR"}var go=/[\u200B-\u200D\uFEFF]/g;function st(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(d,l){let c=-1,p=/[\u200B-\u200D\uFEFF]/;if(!p.test(d))return l;for(let u=0;u<=d.length;u++)if(p.test(d[u])||c++,c===l)return u;throw new Error("Offset out of range")}function a(d){switch(d.nodeType){case Node.TEXT_NODE:{let l=d.textContent,c=l.replace(go,""),p=s+c.length,u=e>=s&&e<=p,m=o>=s&&o<=p;if(u){let g=i(l,e-s);g===0&&!m?n.setStartBefore(d):n.setStart(d,g)}m&&(n.setEnd(d,i(l,o-s)),r=!0),s=p;break}case Node.ELEMENT_NODE:{if(Kn(d)&&(s===e&&n.setStartBefore(d),s++,s===o)){n.setEndAfter(d),r=!0;return}for(let c=0;c<d.childNodes.length&&(a(d.childNodes[c]),!r);c++);let l=d.lastChild;Bn(d)&&l&&!Bn(l)&&!Kn(l)&&s++;break}default:break}}if(a(t),n.startContainer===document)throw new Error("Offsets out of bound");return n}function Un(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,d,l=0;function c(p){let u=p===o,m=p===s;switch(p.nodeType){case Node.TEXT_NODE:{let g=p.textContent;u&&(a=l+g.substring(0,n).replace(go,"").length),m&&(d=l+g.substring(0,r).replace(go,"").length),l+=g.replace(go,"").length;break}case Node.ELEMENT_NODE:{let g=p.nextSibling===null;Kn(p)&&!g&&l++;for(let f=0;f<p.childNodes.length;f++){let y=u&&f===n,b=m&&f===r;if(y&&(a=l),b&&(d=l),d!==void 0||((!y||!i)&&c(p.childNodes[f]),m&&f===r-1&&(d=l),d!==void 0))break}!m&&Bn(p)&&!g&&l++,m&&(d=l);break}default:break}}if(c(t),d===void 0)throw new Error("Could not determine start and end");return{start:a??d,end:d}}function zn(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 d(l){let c=l===o,p=l===s;switch(c&&i++,l.nodeType){case Node.TEXT_NODE:{if(i!==0)return;let u=c?n:0,m=p?r:void 0,g=l.textContent.replace(go,"");u===0&&m===void 0?a+=g:a+=g.substring(u,m);break}case Node.ELEMENT_NODE:{let u=l.nextSibling===null;i===0&&Kn(l)&&!u&&(a+=`
9
9
  `);for(let m=c?n:0;m<(p?Math.min(r,l.childNodes.length):l.childNodes.length)&&(d(l.childNodes[m]),i!==1);m++);!p&&i===0&&Bn(l)&&!u&&(a+=`
10
- `);break}default:break}p&&i++}return d(t),a}var Bc=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(Bc||{}),Ke=class{constructor(e){this.element=e;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(e,o){let n=s=>{o(s)};this.element.addEventListener(e,n),this.disposeHandlers.push(()=>{this.element.removeEventListener(e,n)})}removeEventListener(e,o){this.element.removeEventListener(e,o)}triggerChange(){let e=this.getText(),o=this.getHTML(),n=e!==this.currentText;this.isActive&&(e===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&n&&!this.isSubmitting&&this.emit("change",{plainText:e}),n&&(this.currentSelection=this.getSelection()),this.currentText=e,this.isSubmitting=!1,(this.currentHTML!==o||o===null&&n)&&(this.emit("updated",{plainText:e}),this.triggerCaretPosition(),this.currentHTML=o))}triggerSelection(){let e=this.getSelection();(e.start!==this.currentSelection.start||e.end!==this.currentSelection.end)&&(this.currentSelection=e,this.emit("selection",e),this.triggerCaretPosition())}triggerCaretPosition(){let e=this.getCaretPosition();Le(e,this.currentCaret)||(this.currentCaret=e,this.emit("caret",e))}handleKeyUp(e){let{key:o,shiftKey:n}=e;(o==="Enter"&&n===!0||o==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(e){let{key:o,ctrlKey:n,metaKey:s}=e;this.isPossibleClearInputAction=Object.values(Bc).includes(o)||o.toLowerCase()==="z"&&(n||s),this.emit("keydown",e)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){var n,s;let o=((n=e.clipboardData)==null?void 0:n.getData("text"))||((s=e.clipboardData)==null?void 0:s.getData("text/plain"))||"";this.emit("paste",{pastedText:o,selectionText:this.getSelectedText()})}listen(e={shouldObserve:!0}){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let o=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});e!=null&&e.shouldObserve&&o.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{o.disconnect()}),this.currentSelection=this.getSelection()}focus(){this.element.focus()}emit(e,...o){this.isDisposed||this.eventListeners[e]&&this.eventListeners[e].forEach(n=>{n(...o)})}on(e,o){this.isDisposed||(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o))}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};function Kc(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var It=class extends Ke{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),zn(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!Kc(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!Kc(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return Un(this.element,e);let o=this.lastKnownSelection;if(o&&Hc(this.element,o.start,o.end))return o;let n=fo(this.element);return n.collapse(!1),Un(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return zn(this.element,st(this.element,e,o))}applyChanges(e){var s;if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return(s=this.observer)==null||s.takeRecords(),Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(e={shouldObserve:!0}){super.listen(e),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),e!=null&&e.shouldObserve&&this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let o=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==o&&(o=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>n.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var At=class extends Ke{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:e,selectionEnd:o}=this.element;return{start:e,end:o}}getSelectedText(){let e=this.getSelection();return e?this.getText().slice(e.start,e.end):""}getCaretPosition(){return null}applyChanges(e){if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let e=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=e==null?void 0:e.get)==null?void 0:s.call(this.element)},set:s=>{var r;(r=e==null?void 0:e.set)==null||r.call(this.element,s),this.triggerChange()}});let o=this.element.disabled,n=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>n.disconnect())}};function Uc(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,d])=>{i.searchParams.append(a,d)}),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=n,r.title=`iframe-${t}`,r.src=i.toString(),window.document.body.appendChild(r),r}function Mv(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}var Ar=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()}},Lr=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=Uc(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()}},Mr=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(),x.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 Lr(e,this.deepdeskUrl,{debug:!0}):new Ar(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=Mv(s.data);typeof r!="object"||r.type!=="event"||r.channel!==e||(x.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;x.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)}},zc=Mr;var Lt=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var Nr=t=>new Promise(e=>{setTimeout(e,t)});var Mt=class extends Lt{name="ClientError"},Dr=class extends Lt{name="ServerError"},Or=new Map;async function Nv(t){if(t.status===204)return t.text().catch(()=>{}),null;let e=t.headers.get("content-type");if(e&&e.includes("application/json"))return t.json();let o=await t.text();return o===""?null:(x.warn("Unexpected response body:",o.slice(0,20)),JSON.parse(o))}var fe=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,d=o.method===void 0||o.method.toLowerCase()==="get",{useCache:l=!1,abortLatest:c=!1,attempts:p=1,retryDelay:u=500,refreshTokenOn401:m=!0,retryOnError:g=E=>E instanceof TypeError,retryOnResponse:f=E=>E.status>=500,version:y="v1",...b}=o;if(l)if(d){if(Or.has(i)){n(Or.get(i));return}}else throw new Error(`Can't use 'useCache' for ${o.method}`);let v={credentials:"include",...b,headers:{"Content-Type":"application/json",...b.headers}};!d&&this.csrfToken&&(v.headers={...v.headers,"X-CSRFToken":this.csrfToken}),typeof y=="string"&&(v.headers={...v.headers,"X-Deepdesk-API-Version":y});let S=p,R=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let C=async()=>(S--,a(i,v).then(async E=>f(E)&&!r.isAborted&&S>0?(await Nr(u),C()):E.status===401&&m===!0&&R===!1?(R=!0,await this.refreshToken(),C()):E).catch(async E=>{if(g(E)&&!r.isAborted&&S>0)return await Nr(u),C();throw E}));C().then(async E=>{let O=await Nv(E);if(delete this.latestRequestByUrl[i],E.status>=500){s(new Dr("Server Error",O));return}else if(E.status===401){s(new Mt("Unauthorized",O));return}else if(E.status===403){s(new Mt("Forbidden",O));return}else if(E.status===404){s(new Mt("Not Found",O));return}else if(E.status>=400){s(new Mt("Bad Request",O));return}l&&Or.set(i,O),n(O)}).catch(E=>{s(E)})})}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 Ov;(e=>{let t;(d=>(d.SEND_MESSAGE="Send Message",d.HANDLING_TIME="Handling Time",d.START_AUTOFLOW="Start Autoflow",d.ABORT_AUTOFLOW="Abort Autoflow",d.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",d.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||={})})(Ov||={});function Vn(t){return{...I(t),tags:t.tags}}var Ue=class t{constructor(e,o={}){this.options=o;this.client=new fe(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(),x.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...H(e),tags:e.tags},{version:"v2"});return Vn(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null,useCache:!0});return I(o)}async getKnowledgeAssistant(e){let o=await this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{version:null,useCache:!0});return I(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return I(e)}async getAccount(){let e=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return I(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null,useCache:!0});return I(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(),x.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 x.info(`Successfully retrieved conversation ${r.id} for session ${e}`),Vn(r)}async isConversationSupported(e,o={}){x.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=H(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return Vn(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...H(s),tags:s.tags})),{version:"v2"})).map(s=>Vn(s))}async sendEvent(e,o){let{data:n,...s}=o,r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((i,[a,d])=>({...i,[a]:d}),{});return this.client.post("/api/events",H({...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:H({...o,...n})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e.filter(n=>n.text)})).entities}async getSummary(e,o={}){let n=await this.client.post("/api/summary",{conversation:{messages:e.filter(s=>s.text&&s.source),agent_id:o.agentId,id:o.externalConversationId},prompt_instruction:o.promptInstruction,model:o.model});return I(n)}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(e){return this.client.post("/apis/admin/session/jwt/",{jwt:e},{version:null}).catch(o=>{throw x.warn(`Invalid token '${e}'`),o})}async authenticateWithKey(e,o){await this.preflight(),await this.client.post("/apis/admin/session/api-key/",H(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}`,H(o),{abortLatest:!0})).map(r=>({...I(r),text:r.text||r.url||r.message,source:n,type:n})).filter((r,i,a)=>i===a.findIndex(d=>d.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`,H(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 I(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",H(e),{abortLatest:!0});return I(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,H(e),{version:"v2"});return I(o)}async knowledgeAssist(e,o,n,s={}){let r=await this.client.post(`/api/knowledge-assist/assistants/${n}/search`,H({question:e.question,doNotKnowAnswer:e.doNotKnowAnswer,customerInstruction:e.customerInstruction,chatHistory:o.map(i=>({question:i.question,answer:i.answer.answer})),agentId:s.agentId,conversationId:s.conversationId}),{version:"v2"});return I(r)}async requestLoginByEmail(e){let o=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return I(o)}async requestPasswordlessToken(){let e=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return I(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 I(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 I(i.cues)}async getRules(){let e=new URLSearchParams,o=await this.client.get(`/apis/admin/rule-engine/rules/?${e.toString()}`,{version:null,useCache:!0});return I(o)}async translateMessages(e){let o=await this.client.post("/api/translate",H(e),{version:"v2"});return I(o)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(ni);if(!o||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&o&&a!==o&&x.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(o)}`),this.latestReceivedDeepdeskVersions[i]=o})}};var ho=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(ms(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,I(s))}catch{x.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 Dv;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(Dv||={});var yo=class{constructor(e,o={}){this.apiUrl=e;this.client=new fe(e,o)}client;streams={};logger=x;async getCustomMessages(e){let o=await this.client.get(`/sessions/${e}/suggestions`);return I(o.suggestions)}async sendCustomMessage(e,o){let n=await this.client.post(`/sessions/${e}/messages`,H(o));return I(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,H(o))}async getAutoflows(e){let o=await this.client.get(`/sessions/${e}/autoflows`);return I(o.autoflows)}async startAutoflowSession(e){let o=await this.client.post("/autoflow-sessions",H(e));return I(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new ho(`${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 zv,configureStore as Vv}from"@reduxjs/toolkit";import{createSlice as _v}from"@reduxjs/toolkit";var Vc={startTime:null,stopTime:null},Wc=_v({name:"handlingTime",initialState:Vc,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,()=>Vc)}}),{handlingTimeStart:qc,handlingTimeStop:Wn,handlingTimeReset:Gc}=Wc.actions,$c=Wc.reducer;var jc=(t={})=>{let e={onAuthError:ct(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};import{createAsyncThunk as Fv,createSlice as Hv}from"@reduxjs/toolkit";var qn={list:{keywordMatches:[]},fetchState:"idle"};var rt=Fv("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 qn.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),Bv=Hv({name:"styleSuggestions",initialState:qn,reducers:{},extraReducers:t=>{t.addCase(rt.pending,e=>{e.fetchState="loading"}).addCase(rt.rejected,e=>{e.fetchState="error"}).addCase(rt.fulfilled,(e,o)=>{e.fetchState="done",Le(e.list,o.payload)||(e.list=o.payload)}).addCase(We,e=>{e.list=qn.list}).addCase(M,()=>qn)}}),Xc=Bv.reducer;var Qc=(t={})=>{let e,o=!0,n={getStyleSuggestions:rt,debounce:500,...t};return s=>r=>i=>{var m;let a=s.getState().input.text,d=r(i),l=s.getState();if(l.auth.isLoggedIn!==!0)return d;let{showStyleSuggestions:c}=l.settings;if(!((m=l.conversation.current)==null?void 0:m.id)||!c)return d;let{text:u}=l.input;return u===a&&!o||(clearTimeout(e),u==="")||(e=setTimeout(()=>{o=!1,s.dispatch(n.getStyleSuggestions({text:u}))},t.debounce)),d}};function Kv(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var Zc=(t={})=>{let e={getTextSuggestions:de,getAutocompleteSuggestions:to,debounce:200,check:wt,...t},o;return n=>s=>r=>{var f;let{input:{userCommitted:i}}=n.getState(),a=s(r),d=n.getState();if(d.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:l,showTabCompletion:c}=d.settings,p=(f=d.conversation.current)==null?void 0:f.id,u=r.type===pn.toString();if(!p||!l&&!c)return a;let{input:{userCommitted:m}}=d;return Kv(m,i)&&!u||(clearTimeout(o),!e.check(d))||(o=setTimeout(()=>{let y=ft(d);y===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(y))},u?0:e.debounce)),a}};var Jc=rt.fulfilled.toString();function Uv(t,e){let o=new Set([...e.keywordMatches.map(s=>s.keyword)]),n=[];return o.forEach(s=>{let r=t.keywordMatches.filter(d=>d.keyword===s),i=e.keywordMatches.filter(d=>d.keyword===s),a=i.length-r.length;a<=0||n.push(...i.slice(0,a))}),n}var Yc=t=>e=>o=>n=>{var l;if(n.type!==Jc){o(n);return}let s=e.getState().styleSuggestions.list;o(n);let r=e.getState(),i=r.styleSuggestions.list,a=(l=r.conversation)==null?void 0:l.current;if(s===i)return;let d=Uv(s,i);n.type===Jc&&d.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:d}})};var Wv=zv({answer:il,auth:pi,autoflows:Nd,conversation:hi,contentTypes:pa,customMessages:zd,passwordlessToken:$d,entities:Ha,knowledgeAssistant:nl,handlingTime:$c,info:Fi,input:Li,settings:ri,profile:gl,search:Wi,summary:Ga,styleSuggestions:Xc,ui:Bl,rules:Zd,textSuggestions:wl});function eu(t){return Vv({reducer:Wv,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),jc(),Zc({debounce:200}),Qc({debounce:500}),Yc(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var qv=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},Gv=t=>e=>o=>n=>{var a,d,l,c,p;let s=e.getState(),r=as("inlineSuggestions")(s);switch(n.type){case ct.toString():{!n.payload&&t.emit("logout",void 0);break}case ae.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:(a=s.conversation.current)==null?void 0:a.id,data:{entities:n.payload}});break;case G.toString():t.sendEvent(n.payload.name,{conversationId:((d=n.payload.options)==null?void 0:d.includeConversationData)&&((l=s.conversation.current)==null?void 0:l.id),data:n.payload.data});break;case Oo.toString():t.handleKeyDown(n.payload);break;case We.toString():t.logSendMessage(n.payload);break;case Do.toString():t.handleInputChanged(n.payload);break;case tt.fulfilled.toString():n.isBroadcasted||t.broadcast(ys,n,!1),t.emit("cues",n.payload);break;default:break}let i=o(n);switch(n.type){case We.toString():t.handleAfterSendMessage(n.payload);break;case oo.toString():t.onUpdateShowTabHint(n.payload);break;case Wn.toString():t.logHandlingTime();break;case"analytics/logEvent/fulfilled":{t.emit("event",n.meta.arg);break}case pe.toString():{let{start:u,end:m}=s.input.selection;t.emit("select-suggestion",{type:qv(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:u,end:m}:{start:0,end:m}},{mayApplyChanges:!0}),r&&(e.dispatch(ue([])),e.dispatch(xe()));break}case No.toString():{let{start:u,end:m}=s.input.selection;t.emit("replace",{...n.payload,replace:n.payload.replace==="selection"?{start:u,end:m}:{start:0,end:m}},{mayApplyChanges:!0});break}case Bt.toString():{let u=e.getState(),{text:m,selection:g}=u.input.userCommitted;t.emit("reset",{text:m,selectionAfter:g},{mayApplyChanges:!0});break}case _o.toString():t.emit("select-image",n.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:(c=s.conversation.current)==null?void 0:c.id,data:{path:n.payload.suggestion.image,title:n.payload.suggestion.title}});break;case ue.toString():{r&&n.payload.length>0&&e.dispatch(Ne(0));break}case Ce.fulfilled.toString():{t.sendEvent("conversation summarized",{conversationId:(p=s.conversation.current)==null?void 0:p.id,data:{summary:n.payload.summary,model:e.getState().summary.model}});break}default:break}return i},tu=Gv;function _r(t){return t.toISOString().replace("T"," ").replace("Z","")}function ou(t,e){var r,i,a,d;let o=(r=t.conversation.current)==null?void 0:r.id;if(!o)return x.warn("No conversationId for handling time metrics"),null;let{startTime:n,stopTime:s}=t.handlingTime;return!n||!s?(x.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:o,clientVersion:e.version,agentId:(i=t.info.agentInfo)==null?void 0:i.agentId,agentName:(a=t.info.agentInfo)==null?void 0:a.agentName,agentEmail:(d=t.info.agentInfo)==null?void 0:d.agentEmail,timeStart:_r(n),timeStop:_r(s)}}function nu(t,e,o){var Q,B,L,_;let n=(Q=e.conversation.current)==null?void 0:Q.id;if(!n)return x.warn("No conversationId for send message metrics"),null;let{text:s,metrics:{numCharsTyped:r,numCharsPasted:i,numCharsCut:a,numCharsDeleted:d,numPaste:l,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:u,cuts:m,deletions:g,textSuggestions:f,offeredTextSuggestions:y}}=e[t],b=s.length,S=f.reduce((F,{text:z,searchTerm:vo})=>F+z.length-(vo?vo.length:0),0),R=c??Date.now(),C=(Date.now()-R)/1e3+(p||0),E=r/C,O=f.reduce((F,{searchTerm:z})=>F+(z?z.length:0),0);return{conversationId:n,source:"agent",text:s,clientVersion:o.version,pastes:u,cuts:m,deletions:g,lenTextTyped:r+O,lenTextTotal:b,lenTextAssisted:S,lenTextPasted:i,lenTextCut:a,lenTextDeleted:d,timeTotalSeconds:C,charsPerSecond:E,numPastes:l,textSuggestionsV2:f,suggestionsCounters:[{source:"gpt",countOffered:y.filter(F=>F.source==="gpt").length}],agentId:(B=e.info.agentInfo)==null?void 0:B.agentId,agentName:(L=e.info.agentInfo)==null?void 0:L.agentName,agentEmail:(_=e.info.agentInfo)==null?void 0:_.agentEmail}}function Fr(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return Fr(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?Fr(s,e):null}function su(t,e){return Fr(t,e)}function ru(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function $v(t){return typeof t=="object"&&t!==null&&"tagName"in t}function Hr(t){return $v(t)&&(He(t)||Cn(t))}var au,he=new Map,jv=["bottom","height","left","right","top","width"],iu=(t,e)=>!t&&!e?!1:t&&!e||!t&&e?!0:jv.some(o=>t[o]!==e[o]);function lu(t){var o,n;if(t.ownerDocument===document)return[];let e=((n=(o=t.ownerDocument)==null?void 0:o.defaultView)==null?void 0:n.frameElement)??null;return e?[e,...lu(e)]:[]}function du(t,e){return!t||!e?null:{...t,top:t.top+e.top,left:t.left+e.left}}var Gn=!1,cu=()=>{Gn=!0;let t=[];if(he.forEach((e,o)=>{if(!o.isConnected){e.rect=null,t.push(e),he.delete(o);return}let n=o.getBoundingClientRect();iu(n,e.rect)&&(e.rect=n,t.push(e))}),t.forEach(e=>{let o=e.parentRects?e.parentRects.reduce(du,e.rect):e.rect;iu(o,e.totalRect)&&e.callbacks.forEach(n=>n(o)),e.totalRect=o}),he.size===0){Gn=!1;return}au=window.requestAnimationFrame(cu)};function Br(t,e){let o=lu(t),n=[],s=o.map((r,i)=>Br(r,a=>{n[i]=a;let d=he.get(t);if(!d)return;let l=n.reduce(du,d.rect);d.callbacks.forEach(c=>c(l))}));return{observe(r=!0){if(s.forEach(i=>i.observe(!1)),he.has(t)){let i=he.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else he.set(t,{rect:void 0,callbacks:[e],parentRects:n});r&&!Gn&&cu()},unobserve(){s.forEach(i=>i.unobserve());let r=he.get(t);if(r){let i=r.callbacks.indexOf(e);i>=0&&r.callbacks.splice(i,1),r.callbacks.length||he.delete(t),he.size||(cancelAnimationFrame(au),Gn=!1)}}}}var uu,ye=new Map,pu=()=>{ye.forEach((t,e)=>{if(!e.isConnected){ye.delete(e);return}let{clientHeight:o,scrollHeight:n}=e,s=n>o;t.visible!==s&&(t.visible=s,t.callbacks.forEach(r=>r(t.visible)))}),ye.size!==0&&(uu=window.requestAnimationFrame(pu))};function mu(t,e){return{observe(){let o=ye.size===0;ye.has(t)?ye.get(t).callbacks.push(e):ye.set(t,{visible:void 0,callbacks:[e]}),o&&pu()},unobserve(){let o=ye.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||ye.delete(t),ye.size||cancelAnimationFrame(uu)}}}}var Kr=["borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth","borderStyle","boxSizing","color","overflowWrap","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontWeight","fontKerning","lineHeight","letterSpacing","paddingLeft","paddingTop","paddingRight","paddingBottom","width","height","textIndent","whiteSpace","wordBreak","wordSpacing","wordWrap"];function Ur(t,e,o){return o.forEach(n=>{e.style[n]=t[n]})}function Nt(t){return parseFloat(t)}function $n(t){return Math.round(t*1e6)}function gu(t){return t/1e6}function zr(t,e,o){if(t.boxSizing==="content-box")return;let{clientWidth:n}=e,s=Nt(t.width),r=Nt(t.borderLeftWidth),i=Nt(t.borderRightWidth),a=Nt(t.paddingRight),d=gu($n(s)-$n(r)-$n(i)),l=gu($n(n));if(d-l>2){let c=d-l;o.style.paddingRight=`${a+c}px`}}function jn(t,e={}){var c;let o=e.overlayContainer||document.createElement("div");o.style.display="none",o.style.position=e.position??"fixed",o.style.pointerEvents="none",o.style.borderColor="transparent",Je(o);let n=window.getComputedStyle(t),s=!0,r=()=>{o.scrollTop=t.scrollTop};Ur(n,o,Kr),zr(n,t,o),e.mirrorOverflow&&(o.style.overflow="hidden",t.addEventListener("scroll",r));let i=mu(t,()=>{Ur(n,o,Kr),zr(n,t,o),r(),setTimeout(r,0)}),a,d=!0,l=Br(t,p=>{if(p===null){e.onRemove&&e.onRemove(),o.remove();return}if(!d&&e.onMoveStart&&(Promise.resolve().then(()=>e.onMoveStart()),d=!0),clearTimeout(a),a=setTimeout(()=>{e.onMoveEnd&&e.onMoveEnd(),d=!1},200),p.height===0&&p.width===0){if(s===!0)return;e.onHide&&e.onHide(),o.style.display="none",s=!0;return}if(Ur(n,o,Kr),zr(n,t,o),r(),o.style.top=`${p.top}px`,o.style.left=`${p.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let u=e.closestScrollElement.getBoundingClientRect(),m=window.getComputedStyle(e.closestScrollElement),g=Nt(m.borderTopWidth),f=Nt(m.borderBottomWidth),y=u.top+g-p.top,b=p.top+p.height+-(u.top+u.height-f);o.style.clipPath=`inset(${y}px 0px ${b}px 0px)`}s&&(o.style.display="block",e.onShow&&e.onShow(),s=!1)});return e.appendTo?e.appendTo.appendChild(o):(c=t.parentElement)==null||c.appendChild(o),l.observe(),i.observe(),[o,()=>{t.removeEventListener("scroll",r),l.unobserve(),i.unobserve()}]}var fu=(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{x.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function Xv(t){return t.offsetParent!==null}function hu(t){if(!Xv(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 Vr(t,e,o=100){let n=hu(t);e({isVisible:n});let s=setInterval(()=>{let r=hu(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}import{jsx as U}from"react/jsx-runtime";var yu=fu("showTabHint",!0),Qn=class t{static version="11.5.2";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:d}){let l=e.replace(/\/api$/,"");this.deepdeskApi=new Ue(l,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[tu({broadcast:(p,u,m)=>{this.broadcastEvents.send(p,u,m)},emit:(p,u,m)=>this.emit(p,u,m),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),onUpdateShowTabHint:p=>yu.update(p),sendEvent:(p,u)=>this.deepdeskApi.sendEvent(p,u)})]};o&&Object.assign(c,{deepdeskBrokerAPI:new yo(o)}),this.store=eu(c),this.broadcastEvents=new zc({debug:!0,deepdeskUrl:l,eventMap:qi(this.store),createCustomChannel:d}),this.store.dispatch(oo(yu.value())),this.store.dispatch(ko({locale:s,adminUrl:l,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?(x.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(x.warn("Profile has not been loaded (yet)"),!0):(x.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(ct(null)),this.store.dispatch(Se()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();X(n)&&ii(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(Se())).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){x.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(cs({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Po(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Io({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(us(e))).payload}async postMessages(e){return(await this.store.dispatch(Lo(e))).payload}async updateConversation(e){return(await this.store.dispatch(Ao(e))).payload}resetConversation(){this.store.dispatch(M()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Ce());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(ko(e))}setVisitorInfo(e){this.store.dispatch(Di(e))}setCustomData(e){this.store.dispatch(_i(e))}async setAgentInfo(e){await this.store.dispatch(Kt(e))}async setAgentSettings(e){await this.store.dispatch(fs(e))}async getAgentSettings(){return(await this.store.dispatch(hs())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(pn()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Do(e))}notifyKeyDown(e){this.store.dispatch(Oo(e))}notifyPaste(e,o){this.store.dispatch(Ri({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Ei(e))}notifyExternalSuggestion(e){this.store.dispatch(pe(e)),this.store.dispatch(xe())}async evaluateRule(e,o={}){let{payload:n,error:s}=await this.store.dispatch(tt({label:e,params:o}));if(s)throw new Error(s.message);return n}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(Fe({collapse:!1})),this.inputMediator&&this.store.dispatch(xi({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(ue([])))}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,d=s!==-1;if(this.store.dispatch(ki(yi(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let l=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Ci()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},c=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(Ti()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Bt()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(e.key){case"Up":case"ArrowUp":i?c():l();return;case"Down":case"ArrowDown":{i?l():c();return}case"Esc":case"Escape":{i&&d&&this.store.dispatch(Ne(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Ne(-1)),this.store.dispatch(Bt()),e.preventDefault()):o||(this.store.dispatch(Fe({collapse:!0})),this.store.dispatch(Fl(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,u=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:m}=this.state.input;this.store.dispatch(oo(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&m&&m.text.startsWith(u)&&(this.store.dispatch(pe({text:m.text,suggestion:m,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(Pi()),this.store.dispatch(ue([]))}handlingTimeStart(){this.state.handlingTime.startTime||(x.info("Start handling time"),this.store.dispatch(qc()))}handlingTimeStop(){this.state.handlingTime.startTime&&(x.info("Stop handling time"),this.store.dispatch(Wn()))}logSendMessage(e){let o=nu("input",this.state,{version:this.version});o&&(e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o))}logHandlingTime(){let e=ou(this.state,{version:this.version});e&&(this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Gc()))}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(xe()),this.store.dispatch(We(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(pe({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{let r=this.eventListeners[e];r&&r.forEach(i=>{try{i(o)}catch(a){x.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),x.error(a)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=jn(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{Xn(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,d]=jn(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{Xn(s),d()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Je(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(()=>{Xn(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),x.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()?(x.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Ai(n.metrics))):x.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(!Hr(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:d,showSuggestionsBeforePattern:l,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:u,insertLink:m,inputMediator:g,closestScrollSelector:f,appendOverlayTo:y,inlineSuggestions:b,floatingMenu:v}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:d,showSuggestionsBeforePattern:l,showSuggestionsAfterPattern:c,showTextSuggestions:i,insertLink:m,isEmbedded:p,inlineSuggestions:b,floatingMenu:!!v}),o.automaticHandlingTime&&this.setupHandlingTime(e),Je(e),this.inputMediator=g||(He(e)?new At(e):new It(e)),this.inputMediator.on("change",({plainText:C})=>{this.notifyInputChanged(C)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Ii({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",C=>{this.notifyKeyDown(C)}),this.inputMediator.on("paste",({pastedText:C,selectionText:E})=>{this.notifyPaste(C,E)}),this.inputMediator.on("cut",({selectionText:C})=>{this.notifyCut(C)});let S=f&&su(e,f)||void 0;if(b){let{customStyles:C,appendOverlayTo:E}=o;if(He(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let O=this.createInlineContainer(e,"deepdesk-caret");Ot(U(Ye,{store:this.store,customStyles:C,children:U(Ge,{broadcastEvents:this.broadcastEvents,children:U(ql,{})})}),O),this.inputMediator.on("caret",B=>{this.store.dispatch(ue([])),B?(O.style.display="block",O.style.top=`${B.top}px`,O.style.left=`${B.left}px`):O.style.display="none"});let Q=this.overlayContainerFactory("floating-menu",S||e,{appendTo:typeof v=="object"&&"appendOverlayTo"in v?v.appendOverlayTo:E},C==null?void 0:C.floatingMenuRootNode);Ot(U(Ye,{store:this.store,customStyles:C,children:U(Ge,{broadcastEvents:this.broadcastEvents,children:U(Dl,{onLogIn:()=>this.loginViaPopup().catch(B=>x.warn(B.message))})})}),Q)}else{let C=this.overlayContainerFactory("deepdesk-tab-completion",S||e,{appendTo:y,closestScrollElement:S,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),E=this.overlayContainerFactory("deepdesk-suggestions-overlay",S||e,{appendTo:y},n==null?void 0:n.suggestionsRootNode);Ot(U(Ye,{store:this.store,customStyles:n,children:U(Ge,{broadcastEvents:this.broadcastEvents,children:U(Rd,{inputElement:e})})}),C),Ot(U(Ye,{store:this.store,customStyles:n,children:U(Ge,{broadcastEvents:this.broadcastEvents,children:U(td,{onLogIn:()=>this.loginViaPopup().catch(O=>x.warn(O.message))})})}),E)}Ot(U(Ye,{store:this.store,customStyles:n,children:U(Ge,{broadcastEvents:this.broadcastEvents,children:U(Il,{})})}),this.createContainer("deepdesk-overlays"));let R;this.inputMediator.on("selection",C=>{clearTimeout(R),C===null?R=setTimeout(()=>{C!==null&&this.store.dispatch(ps(C))},500):this.store.dispatch(ps(C))}),this.inputMediator.on("disabled",()=>{var C;(C=this.inputMediator)==null||C.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{u&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(rr(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(rr(!0))),this.store.dispatch(bi({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 C;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((C=this.state.conversation.current)==null?void 0:C.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&&x.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}),Ot(U(Ye,{store:this.store,customStyles:n,children:U(Ge,{broadcastEvents:this.broadcastEvents,children:U(Fc,{onLogIn:()=>this.loginViaPopup().catch(i=>x.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&Xn(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=Vr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){ru(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(eo());let e=Te(this.state);e&&(await this.store.dispatch(Jt()),this.store.dispatch(ko({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 d=!1,l=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(u)};r.onmessage=async m=>{var g,f;if((g=m.data)!=null&&g.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((f=m.data)==null?void 0:f.jwt),await this.isLoggedIn(),this.broadcastEvents.send(zt),d=!0,s.port1.close(),o()}catch(y){console.error(y),n(y)}finally{d=!0,l()}};let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&n(new Error("Popup blocked by browser"));let p=async m=>{var g;if(m.origin===a.origin)switch((g=m.data)==null?void 0:g.type){case"deepdesk-popup-loaded":{try{let f=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(f,a.origin,[s.port2])}catch(f){x.error("Error posting message to popup",f),n(f)}break}case"deepdesk-popup-error":{l(),m.data.message==="Timeout"&&x.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(m.data.message));break}}};window.addEventListener("message",p);let u=setInterval(()=>{c&&!c.closed||(l(),d||n(new Error("Popup closed by user")))},200);this.unmountHandlers.push(l)})}translateMessages(e){return this.deepdeskApi.translateMessages(e)}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(x.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;x.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=cn(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(ae()):To.includes(n)||this.store.dispatch(de(n))})}catch(n){this.handleError(n)}}};async function Qv(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},d=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(d()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function Zv(t,e,o={}){let n=o.replace?st(t,o.replace.start,o.replace.end):fo(t),s,r=()=>{if(o.setRange)return o.setRange(n.cloneRange());n.deleteContents(),s=document.createElement("span"),n.insertNode(s),o.insertBRs!==!1?e.split(`
10
+ `);break}default:break}p&&i++}return d(t),a}var Bc=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(Bc||{}),Ke=class{constructor(e){this.element=e;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(e,o){let n=s=>{o(s)};this.element.addEventListener(e,n),this.disposeHandlers.push(()=>{this.element.removeEventListener(e,n)})}removeEventListener(e,o){this.element.removeEventListener(e,o)}triggerChange(){let e=this.getText(),o=this.getHTML(),n=e!==this.currentText;this.isActive&&(e===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&n&&!this.isSubmitting&&this.emit("change",{plainText:e}),n&&(this.currentSelection=this.getSelection()),this.currentText=e,this.isSubmitting=!1,(this.currentHTML!==o||o===null&&n)&&(this.emit("updated",{plainText:e}),this.triggerCaretPosition(),this.currentHTML=o))}triggerSelection(){let e=this.getSelection();(e.start!==this.currentSelection.start||e.end!==this.currentSelection.end)&&(this.currentSelection=e,this.emit("selection",e),this.triggerCaretPosition())}triggerCaretPosition(){let e=this.getCaretPosition();Le(e,this.currentCaret)||(this.currentCaret=e,this.emit("caret",e))}handleKeyUp(e){let{key:o,shiftKey:n}=e;(o==="Enter"&&n===!0||o==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(e){let{key:o,ctrlKey:n,metaKey:s}=e;this.isPossibleClearInputAction=Object.values(Bc).includes(o)||o.toLowerCase()==="z"&&(n||s),this.emit("keydown",e)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){var n,s;let o=((n=e.clipboardData)==null?void 0:n.getData("text"))||((s=e.clipboardData)==null?void 0:s.getData("text/plain"))||"";this.emit("paste",{pastedText:o,selectionText:this.getSelectedText()})}listen(e={shouldObserve:!0}){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let o=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});e!=null&&e.shouldObserve&&o.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{o.disconnect()}),this.currentSelection=this.getSelection()}focus(){this.element.focus()}emit(e,...o){this.isDisposed||this.eventListeners[e]&&this.eventListeners[e].forEach(n=>{n(...o)})}on(e,o){this.isDisposed||(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o))}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};function Kc(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var It=class extends Ke{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),zn(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!Kc(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!Kc(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return Un(this.element,e);let o=this.lastKnownSelection;if(o&&Hc(this.element,o.start,o.end))return o;let n=fo(this.element);return n.collapse(!1),Un(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return zn(this.element,st(this.element,e,o))}applyChanges(e){var s;if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return(s=this.observer)==null||s.takeRecords(),Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(e={shouldObserve:!0}){super.listen(e),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),e!=null&&e.shouldObserve&&this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let o=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==o&&(o=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>n.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var At=class extends Ke{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:e,selectionEnd:o}=this.element;return{start:e,end:o}}getSelectedText(){let e=this.getSelection();return e?this.getText().slice(e.start,e.end):""}getCaretPosition(){return null}applyChanges(e){if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let e=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=e==null?void 0:e.get)==null?void 0:s.call(this.element)},set:s=>{var r;(r=e==null?void 0:e.set)==null||r.call(this.element,s),this.triggerChange()}});let o=this.element.disabled,n=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>n.disconnect())}};function Uc(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,d])=>{i.searchParams.append(a,d)}),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=n,r.title=`iframe-${t}`,r.src=i.toString(),window.document.body.appendChild(r),r}function Mv(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}var Ar=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()}},Lr=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=Uc(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()}},Mr=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(),x.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 Lr(e,this.deepdeskUrl,{debug:!0}):new Ar(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=Mv(s.data);typeof r!="object"||r.type!=="event"||r.channel!==e||(x.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;x.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)}},zc=Mr;var Lt=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var Nr=t=>new Promise(e=>{setTimeout(e,t)});var Mt=class extends Lt{name="ClientError"},Dr=class extends Lt{name="ServerError"},Or=new Map;async function Nv(t){if(t.status===204)return t.text().catch(()=>{}),null;let e=t.headers.get("content-type");if(e&&e.includes("application/json"))return t.json();let o=await t.text();return o===""?null:(x.warn("Unexpected response body:",o.slice(0,20)),JSON.parse(o))}var fe=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,d=o.method===void 0||o.method.toLowerCase()==="get",{useCache:l=!1,abortLatest:c=!1,attempts:p=1,retryDelay:u=500,refreshTokenOn401:m=!0,retryOnError:g=E=>E instanceof TypeError,retryOnResponse:f=E=>E.status>=500,version:y="v1",...b}=o;if(l)if(d){if(Or.has(i)){n(Or.get(i));return}}else throw new Error(`Can't use 'useCache' for ${o.method}`);let v={credentials:"include",...b,headers:{"Content-Type":"application/json",...b.headers}};!d&&this.csrfToken&&(v.headers={...v.headers,"X-CSRFToken":this.csrfToken}),typeof y=="string"&&(v.headers={...v.headers,"X-Deepdesk-API-Version":y});let S=p,R=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let C=async()=>(S--,a(i,v).then(async E=>f(E)&&!r.isAborted&&S>0?(await Nr(u),C()):E.status===401&&m===!0&&R===!1?(R=!0,await this.refreshToken(),C()):E).catch(async E=>{if(g(E)&&!r.isAborted&&S>0)return await Nr(u),C();throw E}));C().then(async E=>{let O=await Nv(E);if(delete this.latestRequestByUrl[i],E.status>=500){s(new Dr("Server Error",O));return}else if(E.status===401){s(new Mt("Unauthorized",O));return}else if(E.status===403){s(new Mt("Forbidden",O));return}else if(E.status===404){s(new Mt("Not Found",O));return}else if(E.status>=400){s(new Mt("Bad Request",O));return}l&&Or.set(i,O),n(O)}).catch(E=>{s(E)})})}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 Ov;(e=>{let t;(d=>(d.SEND_MESSAGE="Send Message",d.HANDLING_TIME="Handling Time",d.START_AUTOFLOW="Start Autoflow",d.ABORT_AUTOFLOW="Abort Autoflow",d.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",d.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||={})})(Ov||={});function Vn(t){return{...I(t),tags:t.tags}}var Ue=class t{constructor(e,o={}){this.options=o;this.client=new fe(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(),x.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...H(e),tags:e.tags},{version:"v2"});return Vn(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null,useCache:!0});return I(o)}async getKnowledgeAssistant(e){let o=await this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{version:null,useCache:!0});return I(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return I(e)}async getAccount(){let e=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return I(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null,useCache:!0});return I(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(),x.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 x.info(`Successfully retrieved conversation ${r.id} for session ${e}`),Vn(r)}async isConversationSupported(e,o={}){x.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=H(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return Vn(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...H(s),tags:s.tags})),{version:"v2"})).map(s=>Vn(s))}async sendEvent(e,o){let{data:n,...s}=o,r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((i,[a,d])=>({...i,[a]:d}),{});return this.client.post("/api/events",H({...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:H({...o,...n})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e.filter(n=>n.text)})).entities}async getSummary(e,o={}){let n=await this.client.post("/api/summary",{conversation:{messages:e.filter(s=>s.text&&s.source),agent_id:o.agentId,id:o.externalConversationId},prompt_instruction:o.promptInstruction,model:o.model});return I(n)}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(e){return this.client.post("/apis/admin/session/jwt/",{jwt:e},{version:null}).catch(o=>{throw x.warn(`Invalid token '${e}'`),o})}async authenticateWithKey(e,o){await this.preflight(),await this.client.post("/apis/admin/session/api-key/",H(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}`,H(o),{abortLatest:!0})).map(r=>({...I(r),text:r.text||r.url||r.message,source:n,type:n})).filter((r,i,a)=>i===a.findIndex(d=>d.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`,H(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 I(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",H(e),{abortLatest:!0});return I(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,H(e),{version:"v2"});return I(o)}async knowledgeAssist(e,o,n,s={}){let r=await this.client.post(`/api/knowledge-assist/assistants/${n}/search`,H({question:e.question,doNotKnowAnswer:e.doNotKnowAnswer,customerInstruction:e.customerInstruction,chatHistory:o.map(i=>({question:i.question,answer:i.answer.answer})),agentId:s.agentId,conversationId:s.conversationId}),{version:"v2"});return I(r)}async requestLoginByEmail(e){let o=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return I(o)}async requestPasswordlessToken(){let e=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return I(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 I(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 I(i.cues)}async getRules(){let e=new URLSearchParams,o=await this.client.get(`/apis/admin/rule-engine/rules/?${e.toString()}`,{version:null,useCache:!0});return I(o)}async translateMessages(e){let o=await this.client.post("/api/translate",H(e),{version:"v2"});return I(o)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(ni);if(!o||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&o&&a!==o&&x.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(o)}`),this.latestReceivedDeepdeskVersions[i]=o})}};var ho=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(ms(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,I(s))}catch{x.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 Dv;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(Dv||={});var yo=class{constructor(e,o={}){this.apiUrl=e;this.client=new fe(e,o)}client;streams={};logger=x;async getCustomMessages(e){let o=await this.client.get(`/sessions/${e}/suggestions`);return I(o.suggestions)}async sendCustomMessage(e,o){let n=await this.client.post(`/sessions/${e}/messages`,H(o));return I(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,H(o))}async getAutoflows(e){let o=await this.client.get(`/sessions/${e}/autoflows`);return I(o.autoflows)}async startAutoflowSession(e){let o=await this.client.post("/autoflow-sessions",H(e));return I(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new ho(`${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 zv,configureStore as Vv}from"@reduxjs/toolkit";import{createSlice as _v}from"@reduxjs/toolkit";var Vc={startTime:null,stopTime:null},Wc=_v({name:"handlingTime",initialState:Vc,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,()=>Vc)}}),{handlingTimeStart:qc,handlingTimeStop:Wn,handlingTimeReset:Gc}=Wc.actions,$c=Wc.reducer;var jc=(t={})=>{let e={onAuthError:ct(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};import{createAsyncThunk as Fv,createSlice as Hv}from"@reduxjs/toolkit";var qn={list:{keywordMatches:[]},fetchState:"idle"};var rt=Fv("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 qn.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),Bv=Hv({name:"styleSuggestions",initialState:qn,reducers:{},extraReducers:t=>{t.addCase(rt.pending,e=>{e.fetchState="loading"}).addCase(rt.rejected,e=>{e.fetchState="error"}).addCase(rt.fulfilled,(e,o)=>{e.fetchState="done",Le(e.list,o.payload)||(e.list=o.payload)}).addCase(We,e=>{e.list=qn.list}).addCase(M,()=>qn)}}),Xc=Bv.reducer;var Qc=(t={})=>{let e,o=!0,n={getStyleSuggestions:rt,debounce:500,...t};return s=>r=>i=>{var m;let a=s.getState().input.text,d=r(i),l=s.getState();if(l.auth.isLoggedIn!==!0)return d;let{showStyleSuggestions:c}=l.settings;if(!((m=l.conversation.current)==null?void 0:m.id)||!c)return d;let{text:u}=l.input;return u===a&&!o||(clearTimeout(e),u==="")||(e=setTimeout(()=>{o=!1,s.dispatch(n.getStyleSuggestions({text:u}))},t.debounce)),d}};function Kv(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var Zc=(t={})=>{let e={getTextSuggestions:de,getAutocompleteSuggestions:to,debounce:200,check:wt,...t},o;return n=>s=>r=>{var f;let{input:{userCommitted:i}}=n.getState(),a=s(r),d=n.getState();if(d.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:l,showTabCompletion:c}=d.settings,p=(f=d.conversation.current)==null?void 0:f.id,u=r.type===pn.toString();if(!p||!l&&!c)return a;let{input:{userCommitted:m}}=d;return Kv(m,i)&&!u||(clearTimeout(o),!e.check(d))||(o=setTimeout(()=>{let y=ft(d);y===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(y))},u?0:e.debounce)),a}};var Jc=rt.fulfilled.toString();function Uv(t,e){let o=new Set([...e.keywordMatches.map(s=>s.keyword)]),n=[];return o.forEach(s=>{let r=t.keywordMatches.filter(d=>d.keyword===s),i=e.keywordMatches.filter(d=>d.keyword===s),a=i.length-r.length;a<=0||n.push(...i.slice(0,a))}),n}var Yc=t=>e=>o=>n=>{var l;if(n.type!==Jc){o(n);return}let s=e.getState().styleSuggestions.list;o(n);let r=e.getState(),i=r.styleSuggestions.list,a=(l=r.conversation)==null?void 0:l.current;if(s===i)return;let d=Uv(s,i);n.type===Jc&&d.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:d}})};var Wv=zv({answer:il,auth:pi,autoflows:Nd,conversation:hi,contentTypes:pa,customMessages:zd,passwordlessToken:$d,entities:Ha,knowledgeAssistant:nl,handlingTime:$c,info:Fi,input:Li,settings:ri,profile:gl,search:Wi,summary:Ga,styleSuggestions:Xc,ui:Bl,rules:Zd,textSuggestions:wl});function eu(t){return Vv({reducer:Wv,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),jc(),Zc({debounce:200}),Qc({debounce:500}),Yc(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var qv=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},Gv=t=>e=>o=>n=>{var a,d,l,c,p;let s=e.getState(),r=as("inlineSuggestions")(s);switch(n.type){case ct.toString():{!n.payload&&t.emit("logout",void 0);break}case ae.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:(a=s.conversation.current)==null?void 0:a.id,data:{entities:n.payload}});break;case G.toString():t.sendEvent(n.payload.name,{conversationId:((d=n.payload.options)==null?void 0:d.includeConversationData)&&((l=s.conversation.current)==null?void 0:l.id),data:n.payload.data});break;case Oo.toString():t.handleKeyDown(n.payload);break;case We.toString():t.logSendMessage(n.payload);break;case Do.toString():t.handleInputChanged(n.payload);break;case tt.fulfilled.toString():n.isBroadcasted||t.broadcast(ys,n,!1),t.emit("cues",n.payload);break;default:break}let i=o(n);switch(n.type){case We.toString():t.handleAfterSendMessage(n.payload);break;case oo.toString():t.onUpdateShowTabHint(n.payload);break;case Wn.toString():t.logHandlingTime();break;case"analytics/logEvent/fulfilled":{t.emit("event",n.meta.arg);break}case pe.toString():{let{start:u,end:m}=s.input.selection;t.emit("select-suggestion",{type:qv(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:u,end:m}:{start:0,end:m}},{mayApplyChanges:!0}),r&&(e.dispatch(ue([])),e.dispatch(xe()));break}case No.toString():{let{start:u,end:m}=s.input.selection;t.emit("replace",{...n.payload,replace:n.payload.replace==="selection"?{start:u,end:m}:{start:0,end:m}},{mayApplyChanges:!0});break}case Bt.toString():{let u=e.getState(),{text:m,selection:g}=u.input.userCommitted;t.emit("reset",{text:m,selectionAfter:g},{mayApplyChanges:!0});break}case _o.toString():t.emit("select-image",n.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:(c=s.conversation.current)==null?void 0:c.id,data:{path:n.payload.suggestion.image,title:n.payload.suggestion.title}});break;case ue.toString():{r&&n.payload.length>0&&e.dispatch(Ne(0));break}case Ce.fulfilled.toString():{t.sendEvent("conversation summarized",{conversationId:(p=s.conversation.current)==null?void 0:p.id,data:{summary:n.payload.summary,model:e.getState().summary.model}});break}default:break}return i},tu=Gv;function _r(t){return t.toISOString().replace("T"," ").replace("Z","")}function ou(t,e){var r,i,a,d;let o=(r=t.conversation.current)==null?void 0:r.id;if(!o)return x.warn("No conversationId for handling time metrics"),null;let{startTime:n,stopTime:s}=t.handlingTime;return!n||!s?(x.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:o,clientVersion:e.version,agentId:(i=t.info.agentInfo)==null?void 0:i.agentId,agentName:(a=t.info.agentInfo)==null?void 0:a.agentName,agentEmail:(d=t.info.agentInfo)==null?void 0:d.agentEmail,timeStart:_r(n),timeStop:_r(s)}}function nu(t,e,o){var Q,B,L,_;let n=(Q=e.conversation.current)==null?void 0:Q.id;if(!n)return x.warn("No conversationId for send message metrics"),null;let{text:s,metrics:{numCharsTyped:r,numCharsPasted:i,numCharsCut:a,numCharsDeleted:d,numPaste:l,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:u,cuts:m,deletions:g,textSuggestions:f,offeredTextSuggestions:y}}=e[t],b=s.length,S=f.reduce((F,{text:z,searchTerm:vo})=>F+z.length-(vo?vo.length:0),0),R=c??Date.now(),C=(Date.now()-R)/1e3+(p||0),E=r/C,O=f.reduce((F,{searchTerm:z})=>F+(z?z.length:0),0);return{conversationId:n,source:"agent",text:s,clientVersion:o.version,pastes:u,cuts:m,deletions:g,lenTextTyped:r+O,lenTextTotal:b,lenTextAssisted:S,lenTextPasted:i,lenTextCut:a,lenTextDeleted:d,timeTotalSeconds:C,charsPerSecond:E,numPastes:l,textSuggestionsV2:f,suggestionsCounters:[{source:"gpt",countOffered:y.filter(F=>F.source==="gpt").length}],agentId:(B=e.info.agentInfo)==null?void 0:B.agentId,agentName:(L=e.info.agentInfo)==null?void 0:L.agentName,agentEmail:(_=e.info.agentInfo)==null?void 0:_.agentEmail}}function Fr(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return Fr(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?Fr(s,e):null}function su(t,e){return Fr(t,e)}function ru(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function $v(t){return typeof t=="object"&&t!==null&&"tagName"in t}function Hr(t){return $v(t)&&(He(t)||Cn(t))}var au,he=new Map,jv=["bottom","height","left","right","top","width"],iu=(t,e)=>!t&&!e?!1:t&&!e||!t&&e?!0:jv.some(o=>t[o]!==e[o]);function lu(t){var o,n;if(t.ownerDocument===document)return[];let e=((n=(o=t.ownerDocument)==null?void 0:o.defaultView)==null?void 0:n.frameElement)??null;return e?[e,...lu(e)]:[]}function du(t,e){return!t||!e?null:{...t,top:t.top+e.top,left:t.left+e.left}}var Gn=!1,cu=()=>{Gn=!0;let t=[];if(he.forEach((e,o)=>{if(!o.isConnected){e.rect=null,t.push(e),he.delete(o);return}let n=o.getBoundingClientRect();iu(n,e.rect)&&(e.rect=n,t.push(e))}),t.forEach(e=>{let o=e.parentRects?e.parentRects.reduce(du,e.rect):e.rect;iu(o,e.totalRect)&&e.callbacks.forEach(n=>n(o)),e.totalRect=o}),he.size===0){Gn=!1;return}au=window.requestAnimationFrame(cu)};function Br(t,e){let o=lu(t),n=[],s=o.map((r,i)=>Br(r,a=>{n[i]=a;let d=he.get(t);if(!d)return;let l=n.reduce(du,d.rect);d.callbacks.forEach(c=>c(l))}));return{observe(r=!0){if(s.forEach(i=>i.observe(!1)),he.has(t)){let i=he.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else he.set(t,{rect:void 0,callbacks:[e],parentRects:n});r&&!Gn&&cu()},unobserve(){s.forEach(i=>i.unobserve());let r=he.get(t);if(r){let i=r.callbacks.indexOf(e);i>=0&&r.callbacks.splice(i,1),r.callbacks.length||he.delete(t),he.size||(cancelAnimationFrame(au),Gn=!1)}}}}var uu,ye=new Map,pu=()=>{ye.forEach((t,e)=>{if(!e.isConnected){ye.delete(e);return}let{clientHeight:o,scrollHeight:n}=e,s=n>o;t.visible!==s&&(t.visible=s,t.callbacks.forEach(r=>r(t.visible)))}),ye.size!==0&&(uu=window.requestAnimationFrame(pu))};function mu(t,e){return{observe(){let o=ye.size===0;ye.has(t)?ye.get(t).callbacks.push(e):ye.set(t,{visible:void 0,callbacks:[e]}),o&&pu()},unobserve(){let o=ye.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||ye.delete(t),ye.size||cancelAnimationFrame(uu)}}}}var Kr=["borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth","borderStyle","boxSizing","color","overflowWrap","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontWeight","fontKerning","lineHeight","letterSpacing","paddingLeft","paddingTop","paddingRight","paddingBottom","width","height","textIndent","whiteSpace","wordBreak","wordSpacing","wordWrap"];function Ur(t,e,o){return o.forEach(n=>{e.style[n]=t[n]})}function Nt(t){return parseFloat(t)}function $n(t){return Math.round(t*1e6)}function gu(t){return t/1e6}function zr(t,e,o){if(t.boxSizing==="content-box")return;let{clientWidth:n}=e,s=Nt(t.width),r=Nt(t.borderLeftWidth),i=Nt(t.borderRightWidth),a=Nt(t.paddingRight),d=gu($n(s)-$n(r)-$n(i)),l=gu($n(n));if(d-l>2){let c=d-l;o.style.paddingRight=`${a+c}px`}}function jn(t,e={}){var c;let o=e.overlayContainer||document.createElement("div");o.style.display="none",o.style.position=e.position??"fixed",o.style.pointerEvents="none",o.style.borderColor="transparent",Je(o);let n=window.getComputedStyle(t),s=!0,r=()=>{o.scrollTop=t.scrollTop};Ur(n,o,Kr),zr(n,t,o),e.mirrorOverflow&&(o.style.overflow="hidden",t.addEventListener("scroll",r));let i=mu(t,()=>{Ur(n,o,Kr),zr(n,t,o),r(),setTimeout(r,0)}),a,d=!0,l=Br(t,p=>{if(p===null){e.onRemove&&e.onRemove(),o.remove();return}if(!d&&e.onMoveStart&&(Promise.resolve().then(()=>e.onMoveStart()),d=!0),clearTimeout(a),a=setTimeout(()=>{e.onMoveEnd&&e.onMoveEnd(),d=!1},200),p.height===0&&p.width===0){if(s===!0)return;e.onHide&&e.onHide(),o.style.display="none",s=!0;return}if(Ur(n,o,Kr),zr(n,t,o),r(),o.style.top=`${p.top}px`,o.style.left=`${p.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let u=e.closestScrollElement.getBoundingClientRect(),m=window.getComputedStyle(e.closestScrollElement),g=Nt(m.borderTopWidth),f=Nt(m.borderBottomWidth),y=u.top+g-p.top,b=p.top+p.height+-(u.top+u.height-f);o.style.clipPath=`inset(${y}px 0px ${b}px 0px)`}s&&(o.style.display="block",e.onShow&&e.onShow(),s=!1)});return e.appendTo?e.appendTo.appendChild(o):(c=t.parentElement)==null||c.appendChild(o),l.observe(),i.observe(),[o,()=>{t.removeEventListener("scroll",r),l.unobserve(),i.unobserve()}]}var fu=(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{x.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function Xv(t){return t.offsetParent!==null}function hu(t){if(!Xv(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 Vr(t,e,o=100){let n=hu(t);e({isVisible:n});let s=setInterval(()=>{let r=hu(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}import{jsx as U}from"react/jsx-runtime";var yu=fu("showTabHint",!0),Qn=class t{static version="11.5.3";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:d}){let l=e.replace(/\/api$/,"");this.deepdeskApi=new Ue(l,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[tu({broadcast:(p,u,m)=>{this.broadcastEvents.send(p,u,m)},emit:(p,u,m)=>this.emit(p,u,m),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),onUpdateShowTabHint:p=>yu.update(p),sendEvent:(p,u)=>this.deepdeskApi.sendEvent(p,u)})]};o&&Object.assign(c,{deepdeskBrokerAPI:new yo(o)}),this.store=eu(c),this.broadcastEvents=new zc({debug:!0,deepdeskUrl:l,eventMap:qi(this.store),createCustomChannel:d}),this.store.dispatch(oo(yu.value())),this.store.dispatch(ko({locale:s,adminUrl:l,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?(x.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(x.warn("Profile has not been loaded (yet)"),!0):(x.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(ct(null)),this.store.dispatch(Se()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();X(n)&&ii(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(Se())).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){x.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(cs({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Po(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Io({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(us(e))).payload}async postMessages(e){return(await this.store.dispatch(Lo(e))).payload}async updateConversation(e){return(await this.store.dispatch(Ao(e))).payload}resetConversation(){this.store.dispatch(M()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Ce());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(ko(e))}setVisitorInfo(e){this.store.dispatch(Di(e))}setCustomData(e){this.store.dispatch(_i(e))}async setAgentInfo(e){await this.store.dispatch(Kt(e))}async setAgentSettings(e){await this.store.dispatch(fs(e))}async getAgentSettings(){return(await this.store.dispatch(hs())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(pn()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Do(e))}notifyKeyDown(e){this.store.dispatch(Oo(e))}notifyPaste(e,o){this.store.dispatch(Ri({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Ei(e))}notifyExternalSuggestion(e){this.store.dispatch(pe(e)),this.store.dispatch(xe())}async evaluateRule(e,o={}){let{payload:n,error:s}=await this.store.dispatch(tt({label:e,params:o}));if(s)throw new Error(s.message);return n}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(Fe({collapse:!1})),this.inputMediator&&this.store.dispatch(xi({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(ue([])))}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,d=s!==-1;if(this.store.dispatch(ki(yi(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let l=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Ci()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},c=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(Ti()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Bt()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(e.key){case"Up":case"ArrowUp":i?c():l();return;case"Down":case"ArrowDown":{i?l():c();return}case"Esc":case"Escape":{i&&d&&this.store.dispatch(Ne(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Ne(-1)),this.store.dispatch(Bt()),e.preventDefault()):o||(this.store.dispatch(Fe({collapse:!0})),this.store.dispatch(Fl(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,u=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:m}=this.state.input;this.store.dispatch(oo(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&m&&m.text.startsWith(u)&&(this.store.dispatch(pe({text:m.text,suggestion:m,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(Pi()),this.store.dispatch(ue([]))}handlingTimeStart(){this.state.handlingTime.startTime||(x.info("Start handling time"),this.store.dispatch(qc()))}handlingTimeStop(){this.state.handlingTime.startTime&&(x.info("Stop handling time"),this.store.dispatch(Wn()))}logSendMessage(e){let o=nu("input",this.state,{version:this.version});o&&(e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o))}logHandlingTime(){let e=ou(this.state,{version:this.version});e&&(this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Gc()))}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(xe()),this.store.dispatch(We(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(pe({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{let r=this.eventListeners[e];r&&r.forEach(i=>{try{i(o)}catch(a){x.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),x.error(a)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=jn(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{Xn(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,d]=jn(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{Xn(s),d()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Je(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(()=>{Xn(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),x.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()?(x.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Ai(n.metrics))):x.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(!Hr(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:d,showSuggestionsBeforePattern:l,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:u,insertLink:m,inputMediator:g,closestScrollSelector:f,appendOverlayTo:y,inlineSuggestions:b,floatingMenu:v}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:d,showSuggestionsBeforePattern:l,showSuggestionsAfterPattern:c,showTextSuggestions:i,insertLink:m,isEmbedded:p,inlineSuggestions:b,floatingMenu:!!v}),o.automaticHandlingTime&&this.setupHandlingTime(e),Je(e),this.inputMediator=g||(He(e)?new At(e):new It(e)),this.inputMediator.on("change",({plainText:C})=>{this.notifyInputChanged(C)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Ii({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",C=>{this.notifyKeyDown(C)}),this.inputMediator.on("paste",({pastedText:C,selectionText:E})=>{this.notifyPaste(C,E)}),this.inputMediator.on("cut",({selectionText:C})=>{this.notifyCut(C)});let S=f&&su(e,f)||void 0;if(b){let{customStyles:C,appendOverlayTo:E}=o;if(He(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let O=this.createInlineContainer(e,"deepdesk-caret");Ot(U(Ye,{store:this.store,customStyles:C,children:U(Ge,{broadcastEvents:this.broadcastEvents,children:U(ql,{})})}),O),this.inputMediator.on("caret",B=>{this.store.dispatch(ue([])),B?(O.style.display="block",O.style.top=`${B.top}px`,O.style.left=`${B.left}px`):O.style.display="none"});let Q=this.overlayContainerFactory("floating-menu",S||e,{appendTo:typeof v=="object"&&"appendOverlayTo"in v?v.appendOverlayTo:E},C==null?void 0:C.floatingMenuRootNode);Ot(U(Ye,{store:this.store,customStyles:C,children:U(Ge,{broadcastEvents:this.broadcastEvents,children:U(Dl,{onLogIn:()=>this.loginViaPopup().catch(B=>x.warn(B.message))})})}),Q)}else{let C=this.overlayContainerFactory("deepdesk-tab-completion",S||e,{appendTo:y,closestScrollElement:S,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),E=this.overlayContainerFactory("deepdesk-suggestions-overlay",S||e,{appendTo:y},n==null?void 0:n.suggestionsRootNode);Ot(U(Ye,{store:this.store,customStyles:n,children:U(Ge,{broadcastEvents:this.broadcastEvents,children:U(Rd,{inputElement:e})})}),C),Ot(U(Ye,{store:this.store,customStyles:n,children:U(Ge,{broadcastEvents:this.broadcastEvents,children:U(td,{onLogIn:()=>this.loginViaPopup().catch(O=>x.warn(O.message))})})}),E)}Ot(U(Ye,{store:this.store,customStyles:n,children:U(Ge,{broadcastEvents:this.broadcastEvents,children:U(Il,{})})}),this.createContainer("deepdesk-overlays"));let R;this.inputMediator.on("selection",C=>{clearTimeout(R),C===null?R=setTimeout(()=>{C!==null&&this.store.dispatch(ps(C))},500):this.store.dispatch(ps(C))}),this.inputMediator.on("disabled",()=>{var C;(C=this.inputMediator)==null||C.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{u&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(rr(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(rr(!0))),this.store.dispatch(bi({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 C;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((C=this.state.conversation.current)==null?void 0:C.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&&x.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}),Ot(U(Ye,{store:this.store,customStyles:n,children:U(Ge,{broadcastEvents:this.broadcastEvents,children:U(Fc,{onLogIn:()=>this.loginViaPopup().catch(i=>x.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&Xn(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=Vr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){ru(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(eo());let e=Te(this.state);e&&(await this.store.dispatch(Jt()),this.store.dispatch(ko({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 d=!1,l=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(u)};r.onmessage=async m=>{var g,f;if((g=m.data)!=null&&g.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((f=m.data)==null?void 0:f.jwt),await this.isLoggedIn(),this.broadcastEvents.send(zt),d=!0,s.port1.close(),o()}catch(y){console.error(y),n(y)}finally{d=!0,l()}};let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&n(new Error("Popup blocked by browser"));let p=async m=>{var g;if(m.origin===a.origin)switch((g=m.data)==null?void 0:g.type){case"deepdesk-popup-loaded":{try{let f=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(f,a.origin,[s.port2])}catch(f){x.error("Error posting message to popup",f),n(f)}break}case"deepdesk-popup-error":{l(),m.data.message==="Timeout"&&x.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(m.data.message));break}}};window.addEventListener("message",p);let u=setInterval(()=>{c&&!c.closed||(l(),d||n(new Error("Popup closed by user")))},200);this.unmountHandlers.push(l)})}translateMessages(e){return this.deepdeskApi.translateMessages(e)}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(x.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;x.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=cn(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(ae()):To.includes(n)||this.store.dispatch(de(n))})}catch(n){this.handleError(n)}}};async function Qv(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},d=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(d()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function Zv(t,e,o={}){let n=o.replace?st(t,o.replace.start,o.replace.end):fo(t),s,r=()=>{if(o.setRange)return o.setRange(n.cloneRange());n.deleteContents(),s=document.createElement("span"),n.insertNode(s),o.insertBRs!==!1?e.split(`
11
11
  `).reverse().forEach((i,a)=>{a>0&&n.insertNode(document.createElement("br")),n.insertNode(document.createTextNode(i))}):n.insertNode(document.createTextNode(e))};return Promise.resolve(r()).then(()=>{try{if(o.selectionAfter!==!1){t.focus();let i=o.selectionAfter?st(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 Jv(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 Yv(t){let e=document.createDocumentFragment();return t.split(`
12
12
  `).forEach((o,n)=>{n>0&&e.appendChild(document.createElement("br"));let s={index:0},r=0;for(;s=o.slice(r).match(/(\[([^\]]+)])\(([^)]+)\)/);){let i=document.createElement("a");i.href=s[3],i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),i.appendChild(document.createTextNode(s[2])),e.appendChild(document.createTextNode(o.slice(r,r+s.index))),e.appendChild(i),r=r+s.index+s[0].length}e.appendChild(document.createTextNode(o.slice(r)))}),e}function vu(t,e){let o=t.parentElement;if(!o){console.warn("No insert point found");return}let{display:n}=window.getComputedStyle(o);n.includes("block")||n==="table-cell"?o==null||o.insertBefore(e,t.nextSibling):vu(o,e)}async function eS(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 d=a.getRangeAt(0);if(!d)return;s=document.createElement("span"),d.insertNode(s);let l=n?Jv(e):Yv(e);o?vu(d.startContainer,l):(d.insertNode(l),d.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 oS(t,e,o){await new Ue(t).authenticateWithKey(e,o)}async function nS(t){let o=await new fe(t).get("/platform/config/",{version:null,useCache:!0});return I(o)}async function sS(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 sS(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{D as Card,It as ContentEditableInput,Ue as DeepdeskAPI,Qn as DeepdeskSDK,fe as HTTPClient,Ke as InputMediator,dt as InputType,es as KeyboardHint,ts as Label,Eo as Locale,ve as Section,ns as SectionList,Ae as Sources,A as Suggestion,Y as SuggestionList,At as TextAreaInput,lt as ToggleButton,rS as attachFile,oS as authenticateWithKey,fo as createFullRange,jn as createOverlayContainer,st as createRangeFromOffsets,Qt as escapeHTML,nS as fetchPlatformConfig,tS as formatTextMarkup,Un as getRangeOffsets,zn as getRangeText,eS as insertCKEditor,Os as isHTML,Hr as isSupportedInputElement,Zv as updateContentEditable,Qv as updateTextArea,Ze as useClickOutsideRoot,h as useStyles,Vr as waitForElementVisibilityChange};