@deepdesk/deepdesk-sdk 11.2.1-beta.9 → 11.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -5,8 +5,8 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
5
5
  c-6.8,6.8-15.4,10.2-24.7,10.2h-349c-9.4,0-17.9-3.4-24.7-10.2c-6.8-6.8-10.2-15.4-10.2-24.7V267.9c0-9.4,3.4-17.9,10.2-24.7
6
6
  c6.8-6.8,15.4-10.2,24.7-10.2h11.9v-70c0-44.4,16.2-82.8,47.8-115.2S212.1,0,256.4,0s82.8,16.2,115.2,47.8
7
7
  c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});import{jsx as Tl}from"react/jsx-runtime";var wf={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},El=({className:t,color:e})=>Tl("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:Tl("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:wf[e||"pink"]})});var kl={root:"q",text:"C",isLoggedIn:"di",isLoggedOut:"po",icon:"li",logo:"si",lock:"ci"};var Ys={};q(Ys,{enUS:()=>Ef,nlNL:()=>kf});var Ef={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},kf={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};import{useDispatch as If}from"react-redux";import{jsx as er,jsxs as Rl}from"react/jsx-runtime";var Pl=({onLogIn:t})=>{let e=E(Ys),o=b("floatingMenu"),n=b("productName"),s=If(),r=Pf(X),i=h("FloatingMenu",kl);if(r===null||o===!1)return null;let a=()=>{r===!0?s(J(!0)):t()};return Rl("button",{className:Rf(i.root,{[i.isLoggedIn]:r,[i.isLoggedOut]:!r}),onClick:a,children:[er("div",{className:i.text,children:e(r?"search":"signin",{productName:n})}),Rl("div",{className:i.icon,children:[er(El,{className:i.logo,color:"pink"}),r===!1&&er(wl,{className:i.lock})]})]})};import{useEffect as Qf,useRef as Jf}from"react";import{connect as Yf,useDispatch as eh,useSelector as mn}from"react-redux";import{useEffect as Lf}from"react";function Ct(t){Lf(()=>{let e=o=>{o.isWithinRoot||t(o)};return document.body.addEventListener("mouseup",e),()=>{document.body.removeEventListener("mouseup",e)}},[t])}function Qe(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 Af}from"@reduxjs/toolkit";var Mf={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var dn=({ui:t})=>t.overlayCollapsed;var Il=Af({name:"ui",initialState:Mf,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:to,setInputHasFocus:tr,setOverlayCollapsed:De,setOpenOverlayWhenTyping:Ll,setOverlayCollapsedUserOverwrite:Al}=Il.actions,Ml=Il.reducer;import{Fragment as jf,useMemo as qf}from"react";import{Interweave as Df}from"interweave";import{useEffect as Hf,useMemo as Ff,useRef as Bf}from"react";import{useDispatch as Kf,useSelector as Uf}from"react-redux";import{useEffect as Nf}from"react";function Nl(t,e,o){Nf(()=>{let n=t.current;return n?(n.addEventListener(e,o),()=>{n.removeEventListener(e,o)}):()=>{}},[t,e,o])}var Ol={root:"xi",actions:"fi",badge:"gi",formattedText:"do"};import{jsx as un,jsxs as Gf}from"react/jsx-runtime";var zf=["search","personal-collection-search","search-autocomplete"];function Vf(t,e,o,n={}){let s="";return zf.includes(e)?s=da(Is(t,o,{stripAgentPart:!0}),n.searchKeywords??[o]):s=Is(t,o,n),n.placeholders===!0&&(s=ua(s)),s}var $f=()=>{},Wf=({index:t,selected:e,suggestion:o,onFeedback:n})=>{let s=b("inlineSuggestions"),r=Uf(mt),i=Kf(),a=h("TextSuggestion",Ol),c=Bf(null);Hf(()=>{let d=setTimeout(()=>{i(xi({text:o.text,suggestion:o}))},500);return()=>{clearTimeout(d)}},[o]),Nl(c,"click",()=>{i(Me(t)),i(me({suggestion:o,text:o.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let l=Ff(()=>Vf(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:Gf("div",{className:a.root,onMouseEnter:()=>i(Me(t)),children:[un(A,{ref:c,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:$f,children:un(Df,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:l})}),e&&n&&un("div",{className:a.actions,children:un(Qo,{onFeedback:()=>n(o),suggestion:o.text})})]})},_l=Wf;import{jsx as Dl}from"react/jsx-runtime";var Xf=({onFeedback:t,suggestions:e,selectedIndex:o,reverse:n})=>{let s=qf(()=>{let r=e.map((i,a)=>Dl(_l,{index:a,selected:a===o,suggestion:i,onFeedback:t},`${i.text}-${i.source}`));return n?r.reverse():r},[e,o,n]);return Dl(jf,{children:s})},pn=Xf;var Hl={root:"bi",paper:"hi"};import{jsx as gn}from"react/jsx-runtime";var th=({textSuggestions:t,selectedIndex:e})=>{let o=Jf(null),n=h("InlineSuggestionsOverlay",Hl),s=mn(wt),r=eh(),i=mn(X),a=mn(ut),c=mn(dn),l=b("showTextSuggestions");return Ct(()=>{setTimeout(()=>{r(De({collapse:!0,skipWhenInputFocus:!0}))})}),Qf(()=>{let d=o.current;if(!d||!d.parentElement)return;d.parentElement.style.left="0px";let u=d.getBoundingClientRect();d.parentElement.style.left=`${Math.min(window.innerWidth-4-u.right,0)}px`}),c||!s||!l||t.length===0||i!==!0||a===!1?null:gn("div",{className:n.root,"data-variant":"inline",children:gn("div",{ref:o,className:n.paper,children:gn(te,{children:gn(pn,{suggestions:t,selectedIndex:e})})})})},oh=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),Fl=Yf(oh)(th);import{Provider as nh}from"react-redux";import{jsx as fn}from"react/jsx-runtime";var sh=({children:t})=>{let o=b("locale").replace("-","");return fn(Cs.Provider,{value:o,children:t})},rh=({store:t,customStyles:e={},children:o})=>fn(nh,{store:t,children:fn(sh,{children:fn(Dt.Provider,{value:e,children:o})})}),Je=rh;import ir from"classnames";import{useEffect as xh,useRef as bh,useState as Ch}from"react";import{connect as wh,useDispatch as Th,useSelector as oo}from"react-redux";import{useState as ih}from"react";function Bl(t,e){let[o,n]=ih(()=>{if(typeof window>"u")return e;try{let r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return w.error(r),e}});return[o,r=>{try{let i=r instanceof Function?r(o):r;n(i),typeof window<"u"&&window.localStorage.setItem(t,JSON.stringify(i))}catch(i){w.error(i)}}]}var Kl=()=>/Mac/i.test(navigator.platform);import dh from"classnames";import{Fragment as uh,useCallback as nr,useMemo as zl}from"react";var or={};q(or,{enUS:()=>ah,nlNL:()=>lh});var ah={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"}]}]},lh={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 Ul={root:"mi",anchor:"ui",anchorButton:"yi"};import{jsx as hn,jsxs as Vl}from"react/jsx-runtime";var sr=(t,e,o)=>n=>hn("button",{className:t.anchorButton,type:"button",value:e,onClick:o,children:n},e),ph=({className:t,loginUrl:e,isEmbedded:o,onSnooze:n,onLogIn:s})=>{let r=E(or),i=oe(),a=h("Login",Ul),c=b("productName"),l=nr(y=>{y.preventDefault(),n&&n(parseInt(y.target.value,10))},[]),d=nr(y=>{y.preventDefault(),i.send(gt,!0)},[e]),u=zl(()=>y=>hn("a",{onClick:v=>{v.preventDefault(),s()},href:e,className:a.anchor,target:"_blank",rel:"noreferrer",children:y},"login"),[e]),p=nr(y=>hn("button",{type:"button",className:a.anchorButton,onClick:d,children:y},"prompt"),[d]),{min:m,hour:g,day:f}=zl(()=>({min:sr(a,60*10,l),hour:sr(a,60*60,l),day:sr(a,60*60*12,l)}),[]);return Vl("div",{className:dh(t,a.root),children:[r("loginPlease",{login:o?p:u,productName:c}),n&&Vl(uh,{children:[hn("br",{}),r("snooze",{min:m,hour:g,day:f})]})]})},yn=ph;import{useDispatch as gh}from"react-redux";var $l={root:"lo",text:"wi"};import{jsx as Wl,jsxs as hh}from"react/jsx-runtime";var fh=({title:t})=>{let e=h("SearchTrigger",$l),o=gh();return hh("button",{type:"button",className:e.root,onClick:()=>o(J(!0)),children:[Wl(ft,{}),Wl("span",{className:e.text,children:t})]})},Gl=fh;var rr={};q(rr,{enUS:()=>yh,nlNL:()=>vh});var yh={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"}]},vh={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 jl={root:"vi",isInline:"S",toggleButton:"ki",toggleButtonWrapper:"E",toggleButtonWrapperHidden:"zi",isCollapsed:"so",collapsible:"ji",hints:"co",hintsHidden:"Yi",triggers:"xo",triggersRight:"qi"};import{jsx as U,jsxs as no}from"react/jsx-runtime";var Eh=({textSuggestions:t,selectedIndex:e,onLogIn:o})=>{let n=h("SuggestionsOverlay",jl),s=E(rr),r=oo(wt),i=hi(),a=Th(),c=bh(null),l=b("searchTriggerKey"),d=b("productName"),u=oo(dn),p=oo(X),m=oo(ut),[g,f]=Ch(null),y=b("showSearch"),k=b("showTextSuggestions"),v=b("adminUrl"),S=b("isEmbedded"),[R,x]=Bl("dd-snooze-until-ms",0),T=u||R>Date.now(),N=oo(V=>V.input.text),z=t.filter(V=>V.source!=="gpt").length,F=()=>{T&&x(0),a(Al(!T))},I=V=>{a(W({name:"suggestion feedback",data:{text:V.text,source:"overlay",context:N},options:{includeConversationData:!0}}))},O=V=>{let ee=Date.now()+V*1e3;x(ee),w.info(`Snooze until: ${new Date(ee)}`),a(De({collapse:!0}))};return xh(()=>{z===0&&f(null)},[t,z]),Ct(()=>{a(De({collapse:!0,skipWhenInputFocus:!0}))}),p===null||m===!1?null:p===!1?no("div",{ref:c,className:ir(n.root,{[n.isCollapsed]:T}),children:[!T&&no("div",{className:n.triggers,children:[U("div",{style:{flex:1}}),U("div",{className:n.triggersRight,children:U(it,{className:n.toggleButton,title:s("collapse"),onClick:F,isCollapsed:!1})})]}),U("div",{className:n.toggleButtonWrapper,children:U(it,{className:n.toggleButton,title:s("open",{productName:d}),onClick:F,isCollapsed:!0})}),U("div",{className:n.collapsible,children:U(yn,{loginUrl:v,isEmbedded:S,onLogIn:o,onSnooze:O})})]}):!i||!r?null:no("div",{ref:c,className:ir(n.root,{[n.isCollapsed]:T}),children:[!T&&no("div",{className:n.triggers,children:[U("div",{style:{flex:1},children:y&&U("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>f(s(Kl()?"searchHintMac":"searchHintWindows",{searchTriggerKey:l.toUpperCase()})),onMouseLeave:()=>f(null),children:U(Gl,{title:s("search")})})}),no("div",{className:n.triggersRight,onFocus:()=>{},children:[U("div",{className:ir(!g&&n.hintsHidden,n.hints),children:g}),U(it,{className:n.toggleButton,title:s("collapse"),onClick:F,isCollapsed:!1})]})]}),U("div",{className:n.toggleButtonWrapper,children:U(it,{className:n.toggleButton,title:s("open",{productName:d}),onClick:F,isCollapsed:!0})}),z>0&&k&&U("div",{className:n.collapsible,onFocus:()=>{},children:U(te,{children:U(pn,{onFeedback:I,suggestions:t,selectedIndex:e,reverse:!0})})})]})},kh=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),ql=wh(kh)(Eh);import yr from"classnames";import{Interweave as Ry}from"interweave";import{useCallback as Py,useEffect as Iy,useMemo as vc,useRef as Ly}from"react";import{connect as Ay}from"react-redux";import{useEffect as Rh,useRef as Ph,useState as Ih}from"react";function vn(t){return t.contentEditable==="true"}function Lh(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 Xl(t){let{selectionStart:e,selectionEnd:o}=vn(t)?Lh(t):t;return[e,o]}function Zl(t){let[,e]=Ih(),o=Ph(null);return o.current=Xl(t),Rh(()=>{let n=()=>{let[s,r]=o.current??[],i=Xl(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 Ql(t,e){if(!e)return;let o=t,{value:n}=o,[s,r]=e,i=n.match(xo);if(!i||i.length===0)return;let a=0;i.find(c=>{let l=n.indexOf(c,a);return s>l&&r<l+c.length?(o.selectionStart=l,o.selectionEnd=l+c.length,!0):(a=l+c.length,!1)})}import{cloneElement as Ah}from"react";var Mh=["div","span","mark","strong","b","i","u","em"];function ar(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(Mh.includes(s)){let i=Array.isArray(n.props.children)?n.props.children:[n.props.children];return[...t.slice(0,t.length-1),Ah(n,{children:ar(i,e,o+1)})]}return[...t,...e]}function He(t){return t.tagName.toLowerCase()==="textarea"}var de={root:"Ci",container:"Si",agentText:"fo",tabText:"go",hint:"G",matchSelection:"bo",focus:"Ei",resetIndent:"Gi",matchKeyword:"p",matchPlaceholder:"d",hover:"ho",hintText:"Ni",popover:"Ai",popoverRoot:"Fi",popoverContentContainer:"mo",popoverContent:"Hi",selectionOptions:"Li",selectionOptionsIsHidden:"Mi",selectionOptionsButton:"Ri",caret:"Ti",popoverSuggestionsRoot:"Ui",suggestionsOverlayInputStyles:"Bi"};import ty from"classnames";import{Matcher as oy}from"interweave";import{useEffect as ny,useMemo as sy}from"react";import{useEffect as Oh,useRef as _h,useState as Dh}from"react";function Jl(t,e){let o;return[(...n)=>{window.cancelAnimationFrame(o);let s=e?e(...n):n;o=window.requestAnimationFrame(()=>{t(...s)})},()=>window.cancelAnimationFrame(o)]}function Sn(t){let e=_h(null),[o,n]=Dh(!1);return Oh(()=>{let s=!1,r=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[i,a]=Jl((d,u)=>{let p=e.current;if(!p)return;let m=d/r,g=u/r,f=p.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:d,clientY:u})=>[d,u]),[c,l]=Jl(()=>{s=!1,n(!1)});return t.addEventListener("mousemove",i),t.addEventListener("mouseleave",c),()=>{a(),l(),t.removeEventListener("mousemove",i),t.removeEventListener("mouseleave",c)}},[e]),[e,o]}function Yl(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function xn(t){return e=>{t.forEach(o=>{typeof o=="function"?o(e):o!=null&&(o.current=e)})}}function ec(t){return t!=null}import rc from"classnames";import{createRef as qh,useCallback as cr,useMemo as Xh,useRef as Zh,useState as Qh}from"react";import{useState as Hh,useLayoutEffect as Fh}from"react";var Bh=["bottom","height","left","right","top","width"],Kh=(t={},e={})=>Bh.some(o=>t[o]!==e[o]),Te=new Map,tc,oc=()=>{let t=[],e=[];Te.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=>{Te.delete(o)}),t.forEach(o=>{o.callbacks.forEach(n=>n(o.rect))}),tc=window.requestAnimationFrame(oc)};function Uh(t,e){return{observe(){let o=Te.size===0;if(Te.has(t)){let n=Te.get(t);n.callbacks.push(e),n.rect&&e(n.rect)}else Te.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});o&&oc()},unobserve(){let o=Te.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||Te.delete(t),Te.size||cancelAnimationFrame(tc)}}}}function lr(t){let[e,o]=Hh(null);return Fh(()=>{if(!t.current)return;let n=Uh(t.current,s=>{o(s)});return n.observe(),()=>{n.unobserve()}},[t]),e}import{useContext as Vh,useLayoutEffect as $h,useState as Wh}from"react";import{createPortal as Gh}from"react-dom";var nc={root:"Di"};var sc=({children:t,parentNode:e})=>{let[o,n]=Wh(null),s=Vh(Dt);return $h(()=>{let r=document.createElement("div");return Qe(r),r.classList.add(nc.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?Gh(t,o):null};var ge={ref:"Ii",root:"o",positionAbove:"l",positionBelow:"s",positionLeft:"c",positionRight:"x",alignStart:"f",alignCenter:"g",alignEnd:"b"};import{jsx as dr}from"react/jsx-runtime";var bn=(t=!1)=>{let[e,o]=Qh(t),n=cr(()=>o(!0),[]),s=cr(()=>o(!1),[]),r=cr(()=>o(a=>!a),[]),i=Zh(null);return{opened:e,open:n,close:s,toggle:r,triggerRef:i}};function ur(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=qh(),position:n="above",align:s="center",children:r,toStyle:i=ur,parentNode:a,...c})=>{let l=lr(e),d=lr(o),u=Xh(()=>i(l,d,0),[l,d]);return dr(sc,{parentNode:a,children:dr("div",{className:rc(ge.ref,{[ge.positionAbove]:n==="above",[ge.positionBelow]:n==="below",[ge.positionLeft]:n==="left",[ge.positionRight]:n==="right",[ge.alignStart]:s==="start",[ge.alignCenter]:s==="center",[ge.alignEnd]:s==="end"}),style:u,...c,role:"dialog",children:dr("div",{className:rc(t,ge.root),children:r})})})};import Jh from"classnames";import{forwardRef as Yh,useRef as ey}from"react";import{jsx as ic}from"react/jsx-runtime";var Cn=Yh(({className:t,children:e,...o},n)=>{let s=ey(null),r=h("TabCompletion",de);return ic("div",{ref:xn([s,n]),className:Jh(t,r.popoverContentContainer),...o,children:ic("div",{className:r.popoverContent,children:e})})});import{jsx as so,jsxs as ay}from"react/jsx-runtime";var ry=t=>e=>{let o=ur(e);return"top"in o&&(o.width=t.width-(e.left-t.left)-10),o},iy=({inputElement:t,boundaryRef:e,inputStyle:o,children:n,suggestion:s})=>{let r=h("TabCompletion",de),i=bn(),a=sy(()=>ry(t.getBoundingClientRect()),[t]),[c,l]=Sn(t);return ny(()=>{l?i.open():i.close()},[l]),ay("span",{children:[so("mark",{ref:xn([c,i.triggerRef]),className:ty(r.matchKeyword,{[r.hover]:l}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:n}),i.opened&&so(Tt,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:so(Cn,{style:o,children:so("div",{className:r.hintText,children:s})})})]})},wn=class extends oy{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${Yl(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(ec);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 so(iy,{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 ly}from"interweave";import cy from"classnames";import{jsx as ac}from"react/jsx-runtime";var dy=({inputElement:t,children:e})=>{let o=h("TabCompletion",de),[n,s]=Sn(t);return ac("mark",{ref:n,className:cy(o.matchPlaceholder,{[o.hover]:s}),children:e})},Tn=class extends ly{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 ac(dy,{inputElement:o.inputElement,children:e},`placeholder_${o.matchString}_${o.key}`)}asTag(){return"mark"}};import hr from"classnames";import{Matcher as xy}from"interweave";import{createRef as by,forwardRef as Cy,useCallback as wy,useEffect as fc,useRef as hc,useState as yc}from"react";import{useDispatch as Ty}from"react-redux";import{jsx as lc}from"react/jsx-runtime";var cc=()=>lc("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:lc("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 py,useEffect as uc,useState as pc}from"react";import{useDispatch as my,useSelector as mc}from"react-redux";import gy from"lodash.debounce";var dc={root:"Oi",content:"Xi"};function En(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 pr(t){return t.replace("https://www.","").replace("https://","")}import{jsx as Ye,jsxs as mr}from"react/jsx-runtime";var fy=3,hy=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),yy=({onSelectLink:t,onDismiss:e,placeholder:o,visitUrlText:n,linkCount:s=fy})=>{let r=h("LinkSearch",dc),[i,a]=pc(""),c=my(),l=mc(ml("url")),d=mc(Hi("URL",hy)),[u,p]=pc(d.length-1),m=b("fallbackImage"),g=v=>{let S=v.target;a(S.value)},f=(v,S)=>{v.stopPropagation(),v.preventDefault(),window.open(S,"_blank")},y=v=>{var x;let S=u-1<0?d.length-1:u-1,R=u+1===d.length?0:u+1;v.code==="Escape"&&(a(""),e()),v.code==="ArrowUp"&&p(S),v.code==="ArrowDown"&&p(R),v.code==="Enter"&&t(((x=d[u])==null?void 0:x.text)||i)},k=py(gy(v=>{c($e({query:v,type:"URL",tags:["link-search"]}))},300),[]);return uc(()=>{i&&k(i)},[i]),uc(()=>()=>{c(Oo())},[]),mr("div",{className:r.root,children:[Ye(te,{withDivider:!0,children:(i?d:l).slice(0,s).map((v,S)=>Ye(A,{selected:u===S,onClick:()=>t(v.text),"data-testid":"linksearch-suggestion",children:mr(D,{children:[Ye(D.Image,{src:En(v,"small",m||void 0),title:v.title||v.text}),mr(D.Content,{className:r.content,cropText:!0,children:[Ye(D.Title,{children:v.title||pr(v.text)}),v.title&&pr(v.text)]}),Ye(A.Actions,{children:Ye(A.ActionButton,{label:n,onClick:R=>f(R,v.text)})})]})},v.text))}),Ye(jt,{value:i,onChange:g,autoFocus:!0,placeholder:o,onKeyUp:y})]})},gc=yy;var gr={};q(gr,{enUS:()=>vy,nlNL:()=>Sy});var vy={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},Sy={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};import{jsx as fe,jsxs as fr}from"react/jsx-runtime";var Ey=Cy((t,e)=>{let o=h("TabCompletion",de);return fe("mark",{ref:e,className:hr(o.matchSelection)},"selection-start")}),ky=({startRef:t,boundaryRef:e,inputStyle:o,inputElement:n,children:s})=>{let r=E(gr),i=h("TabCompletion",de),a=hc(null),c=hc(null),[l,d]=yc(null),u=Ty(),p=bn(document.activeElement===n),[m]=yc(()=>document.createRange());p.triggerRef.current=m,fc(()=>()=>m.detach(),[]),fc(()=>{let f=t.current,y=a.current;!f||!y||(m.setStart(f,0),m.setEnd(y,0))},[t.current,a.current]),Ct(()=>{p.close()});let g=wy(f=>{let y=m.toString(),k=/^http(s?):\/\//.test(f)?f:`https://${f}`;u(Io({text:`[${y}](${k})`,replace:"selection"}))},[]);return fr("span",{children:[fe("mark",{ref:a,className:hr(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":p.opened?"true":"false",children:s}),p.opened&&fe(Tt,{className:i.popoverRoot,triggerRef:p.triggerRef,boundaryRef:e,position:"above",align:"start",children:fr(Cn,{style:o,ref:c,children:[fe("div",{className:hr(i.selectionOptions,{[i.selectionOptionsIsHidden]:l!==null}),children:fr("button",{type:"button",tabIndex:l===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>d("insertLink"),children:[fe(cc,{}),fe("span",{children:"\xA0"}),fe("span",{children:r("insertLink")})]})}),l==="insertLink"&&fe(gc,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:g,onDismiss:()=>{d(null),p.close()}})]})})]},"selection-end")},kn=class extends xy{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(e,o){return this.props=o,this.charCount=0,this.startRef=by(),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?fe(Ey,{ref:this.startRef}):fe(ky,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};import{useSelector as My}from"react-redux";import{jsx as Et,jsxs as _y}from"react/jsx-runtime";var Ny=({enabled:t,content:e,tabText:o,showTabHint:n,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:c})=>{let l=h("TabCompletion",de),d=b("insertLink"),u=b("showMidSentenceSuggestions"),p=b("inlineSuggestions"),m=Zl(a),g=Ly(null),f=My(X);Iy(()=>{He(a)&&m&&Ql(a,m)},[m]);let y=Py(S=>{if(!s||!o)return S;let R=[Et("span",{className:l.resetIndent,children:"\u200B"},"u200B"),Et("span",{"data-testid":"tab-completion",className:yr(l.tabText,l.resetIndent),"data-source":c,children:o},"tabText")];return n&&R.push(Et("span",{className:yr(l.hint,l.resetIndent),children:Et(Zn,{keyCode:"tab"},"tabHint")})),ar(S,R)},[s,o,n]),k=vc(()=>{let S=[];return d&&S.push(new kn("selection")),S.push(new Tn("placeholders")),r&&S.push(new wn("keywords")),S},[p,d,r]),v=vc(()=>{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:_y("div",{ref:S=>{S!=null&&S.parentElement&&(g.current=S==null?void 0:S.parentElement)},className:l.root,style:v,children:[Et(Ry,{tagName:"span",containerTagName:"div",className:yr(l.container,l.agentText),disableLineBreaks:He(a),content:e||"\u200B",onAfterParse:y,matchers:k,selection:m,keywordMatches:i,inputElement:a,inputStyle:v,boundaryRef:g,inlineSuggestionsOnlyAtEnd:!u}),Et("br",{})]})},Oy=({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)||"",c=t.html??Zt(t.text),l=i.indexOf(t.text)===0?i.slice(t.text.length):"",{showTabHint:d}=e,{isSupported:u}=s,{showTabCompletion:p,visible:m,showStyleSuggestions:g}=o;return{showTabHint:d,showStyleSuggestions:g,showTabCompletion:p,content:c,tabText:l,source:a,keywordMatches:((f=n.list)==null?void 0:f.keywordMatches)??[],enabled:m&&u!==!1}},Sc=Ay(Oy)(Ny);import Wv from"classnames";import{Fragment as Gv,useEffect as jv}from"react";import{useDispatch as Nn,useSelector as j}from"react-redux";import{createAsyncThunk as ro,createSlice as Dy}from"@reduxjs/toolkit";var xc={list:[],fetchState:"idle"},Cc=t=>t.autoflows.list||[],bc=t=>e=>{var o;return(o=e.list)==null?void 0:o.find(n=>n.triggerPayload===t)},Ee=ro("autoflows/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getAutoflows(t)}),vr=ro("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(Ee(t.platformSessionId))}),Sr=ro("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(Ee(t.platformSessionId))}),Hy=Dy({name:"autoflows",initialState:xc,reducers:{},extraReducers:t=>{t.addCase(vr.pending,(e,o)=>{let n=bc(o.meta.arg.triggerPayload)(e);n.state="Started",n.isBusy=!0}),t.addCase(Sr.pending,(e,o)=>{let n=bc(o.meta.arg.triggerPayload)(e);n.state="Aborted",n.isBusy=!0}),t.addCase(Ee.pending,e=>{e.fetchState="loading"}),t.addCase(Ee.rejected,e=>{e.fetchState="error"}),t.addCase(Ee.fulfilled,(e,o)=>{e.list=o.payload,e.fetchState="done"}),t.addCase(M,()=>xc)}}),wc=ro("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(Ee(t))}),s.on("sessionCompleted",()=>{o(Ee(t))})}),Tc=ro("autoflows/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),Ec=Hy.reducer;import{createAsyncThunk as ao,createSlice as Fy}from"@reduxjs/toolkit";var kc={list:[],fetchState:"idle",sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},Rc=t=>t.customMessages.list,Pc=t=>e=>!!e.customMessages.sentSuggestions.find(o=>o===t),Ic=t=>e=>!!e.customMessages.answeredSuggestions.find(o=>o===t),Lc=t=>e=>!!e.customMessages.errorSuggestions.find(o=>o===t),io=ao("customMessages/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getCustomMessages(t)}),Rn=ao("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)}),Pn=ao("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)}),Ac=Fy({name:"customMessages",initialState:kc,reducers:{onCustomMessage(t,e){Array.isArray(e.payload)?t.list=e.payload:t.list=[e.payload]}},extraReducers:t=>{t.addCase(io.pending,e=>{e.fetchState="loading"}).addCase(io.rejected,e=>{e.fetchState="error"}).addCase(io.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload||[]}).addCase(Rn.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.errorSuggestions=e.errorSuggestions.filter(n=>o.meta.arg.suggestion.text!==n)}).addCase(Rn.rejected,(e,o)=>{let n=e.sentSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1))}).addCase(Pn.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.answeredSuggestions.push(o.meta.arg.suggestion.text)}).addCase(Pn.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,()=>kc)}}),Mc=ao("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(Ac.actions.onCustomMessage(r))})}),Nc=ao("customMessages/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),Oc=Ac.reducer;import{createAsyncThunk as _c,createSlice as By}from"@reduxjs/toolkit";var Ky={token:null,accountUrl:null,interval:null},Dc=t=>e=>{let{passwordlessToken:{token:o,accountUrl:n}}=e;return o&&n?`${n}/apis/admin/session/passwordless/login/?token=${o}&redirect=${t}`:null},xr=_c("passwordlessToken/getTemporaryPasswordlessToken",async(t,e)=>{let{deepdeskAPI:o}=e.extra,n=await o.requestPasswordlessToken();return{accountUrl:o.client.baseUrl,token:n}}),br=_c("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:o=1e3*60*10}=t,{dispatch:n}=e;return n(xr()),setInterval(()=>n(xr()),o)}),Hc=By({name:"passwordlessToken",initialState:Ky,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(xr.fulfilled,(e,o)=>{e.token=o.payload.token,e.accountUrl=o.payload.accountUrl}),t.addCase(br.fulfilled,(e,o)=>{e.interval=o.payload})}}),{stopPollPasswordlessToken:Fc}=Hc.actions,Bc=Hc.reducer;import{createAction as Uy,createAsyncThunk as zy,createSlice as Vy}from"@reduxjs/toolkit";var Cr={cues:[],fetchState:"idle"},Kc=t=>{var e;return(e=t.rules)==null?void 0:e.cues},$y=Uy("rules/resetCues"),et=zy("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(d=>d.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 w.info(s.message),[]}}),Uc=Vy({name:"answer",initialState:Cr,reducers:{removeCue(t,e){t.cues=t.cues.filter(o=>o.rule.id!==e.payload.id)}},extraReducers:t=>{t.addCase(et.pending,e=>{e.fetchState="loading"}).addCase(et.rejected,e=>{e.fetchState="error"}).addCase(et.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,()=>Cr).addCase($y.toString(),()=>Cr)}}),{removeCue:zc}=Uc.actions,Vc=Uc.reducer;import{Fragment as ov}from"react";import{connect as nv}from"react-redux";import Yy from"classnames";import{Fragment as ev}from"react";import Gy from"classnames";var $c={root:"Ji"};import{jsx as qy}from"react/jsx-runtime";var jy=({className:t,children:e})=>{let o=h("Unicode",$c);return qy("span",{className:Gy(t,o.root),children:e})},Wc=jy;var Gc={isDisabled:"Ki",buttonStart:"Pi",root:"Qi",buttonStop:"uo",stateBadge:"h",isCompleted:"Vi",isStarted:"Wi",isAborted:"Zi"};var wr={};q(wr,{enUS:()=>Zy,nlNL:()=>Qy});var Zy={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"}]},Qy={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 tt,jsxs as In}from"react/jsx-runtime";var tv=({disabled:t,state:e,displayName:o,description:n,onStartAutoflow:s,onStopAutoflow:r})=>{let i=h("Autoflow",Gc),a=E(wr),c=e==="Started"?"stop":"start",l=c==="start"?"\u25B6":c==="stop"?"\u25FC":"";return In(A,{className:Yy(i.root,{[i.isDisabled]:t,[i.isCompleted]:e==="Completed",[i.isAborted]:e==="Aborted",[i.isStarted]:e==="Started"}),children:[tt(D,{children:In(D.Content,{children:[In(D.Title,{children:[e&&tt("span",{className:i.stateBadge,children:a(e)}),o]}),tt("span",{children:n})]})}),tt(A.Actions,{fixed:e==="Started",children:tt(A.ActionButton,{primary:!0,className:c==="start"?i.buttonStart:i.buttonStop,onClick:e==="Started"?r:s,disabled:t,label:In(ev,{children:[tt(Wc,{children:l})," ",tt("span",{children:a(c)})]})})})]})},jc=tv;import{jsx as qc}from"react/jsx-runtime";var sv=(t,e)=>{let o=e.filter(n=>n.state==="Started");return o.length>0?o.indexOf(t)===-1:!1},rv=({autoflows:t,onStartAutoflow:e,onStopAutoflow:o,platformSessionId:n})=>qc(ov,{children:t.map(s=>qc(jc,{displayName:s.displayName,description:s.description,disabled:s.isBusy||sv(s,t),state:s.state,onStartAutoflow:()=>e({platformSessionId:n,triggerPayload:s.triggerPayload}),onStopAutoflow:()=>o({platformSessionId:n,triggerPayload:s.triggerPayload})},s.displayName))}),iv=({autoflows:t,conversation:e})=>{var o;return{autoflows:t.list,platformSessionId:(o=e.current)==null?void 0:o.sessionId}},av={onStartAutoflow:vr,onStopAutoflow:Sr},Xc=nv(iv,av)(rv);import cv from"classnames";import{useCallback as Zc}from"react";import{useDispatch as dv,useSelector as Ln}from"react-redux";var ke={root:"yo",title:"wo",isUsed:"_i",quickReplies:"or",quickReply:"er",hasError:"ir",label:"rr",errorIcon:"tr"};import{jsx as Fe,jsxs as An}from"react/jsx-runtime";var uv=({suggestion:t})=>{let e=E(Xe),o=dv(),n=Ln(Pc(t.text)),s=Ln(Ic(t.text)),r=Ln(Lc(t.text)),i=Ln(dt),{replyOptions:a}=t,c=Zc(d=>{d.preventDefault(),d.stopPropagation(),!(n||!i)&&o(Rn({platformSessionId:i,suggestion:t}))},[t,n,o,i]),l=Zc(d=>{if(d.preventDefault(),d.stopPropagation(),!i||!a)return;let u=parseInt(d.target.dataset.index,10),p=a[u];o(Pn({platformSessionId:i,reply:p,suggestion:t}))},[t,n,o,i]);return An(A,{onClick:c,className:cv(ke.root,{[ke.isUsed]:n,[ke.hasError]:r}),children:[Fe(D,{children:An(D.Content,{children:[An(D.Title,{className:ke.title,children:[t.text," ",Fe(Qn,{className:ke.label,children:"analyse tool"})," ",r&&Fe("span",{className:ke.errorIcon,role:"img","aria-label":e("sendingError"),title:e("sendingError"),children:"!"})]}),a&&a.length>0&&Fe("ul",{className:ke.quickReplies,children:a.map(d=>Fe("li",{className:ke.quickReply,children:d.title},d.title))})]})}),An(A.Actions,{fixed:r||n,children:[a&&a.length>0&&Fe(A.DropdownButton,{label:e("answer"),disabled:s,children:a.map((d,u)=>Fe(A.DropdownItem,{index:u,label:d.title,onClick:l},d.title))}),Fe(A.ActionButton,{primary:!0,disabled:n,onClick:c,label:e(n?"suggestionSent":r?"tryAgain":"sendSuggestion")})]})]})},Qc=uv;import{useEffect as mv,useState as gv}from"react";import{useDispatch as fv}from"react-redux";import ed from"classnames";import{jsx as Jc}from"react/jsx-runtime";var Tr=()=>Jc("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:Jc("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 Yc={root:"nr",entity:"r",entityText:"ar",iconWrapper:"pr",icon:"dr",iconClicked:"lr"};import{jsx as kt,jsxs as td}from"react/jsx-runtime";var hv=({entities:t})=>{let e=h("EntitiesWidgetList",Yc),[o,n]=gv(void 0),s=fv(),r=()=>{n(void 0)},i=a=>{t&&(n(t.indexOf(a)),je(a.text),s(W({name:"entity copied",data:{entity:a,type:"copy"}})))};return mv(()=>{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,c)=>td("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[kt("span",{className:e.entityText,children:a.text}),td("span",{className:e.iconWrapper,children:[kt("span",{className:ed(e.icon),children:kt(Tr,{})}),kt("span",{className:ed(e.icon,o===c&&e.iconClicked),children:kt(Tr,{})})]})]},a.text))})},od=hv;import{jsx as nd}from"react/jsx-runtime";var sd=()=>nd("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:nd("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 rd}from"react/jsx-runtime";var id=()=>rd("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:rd("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 ad}from"react/jsx-runtime";var ld=()=>ad("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:ad("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 Ov}from"react-redux";import fd from"classnames";import{useEffect as Av,useState as Mv}from"react";import{jsx as cd,jsxs as yv}from"react/jsx-runtime";var dd=({className:t})=>yv("svg",{viewBox:"0 0 12 12",version:"1.1",xmlns:"http://www.w3.org/2000/svg",className:t,children:[cd("line",{x1:"2",y1:"10",x2:"10",y2:"2",stroke:"black",strokeWidth:"1"}),cd("line",{x1:"2",y1:"2",x2:"10",y2:"10",stroke:"black",strokeWidth:"1"})]});import Sv from"dompurify";import{Fragment as xv,useMemo as bv,useRef as Cv,useState as wv}from"react";import Tv from"snarkdown";var ud={fadeup:"N",root:"i",popover:"sr",options:"vo",copyIcon:"A",option:"ko",divider:"cr"};import{jsx as lo,jsxs as pd}from"react/jsx-runtime";function Ev(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 Er(t){let e=t.cloneNode(!0);return e.querySelectorAll("div,button").forEach(o=>o.remove()),e.textContent??""}function kv(t){return t.replace(/\r\n/g,`
8
- `)}var Rv=({content:t,useLabel:e,copyLabel:o,onCopy:n,onUse:s})=>{let r=h("Markdown",ud),i=Cv(null),[a,c]=wv(null),l=bv(()=>{let g=Tv(kv(t));return Sv.sanitize(g).replace(/<\/code>/g,`${Ev(r.copyIcon)}</code>`)},[t]),d=g=>{var k;let f=g.target,y=!!((k=i.current)!=null&&k.querySelector("code"));a||y&&f.tagName!=="CODE"||!y&&f!==i.current||(f.addEventListener("mouseleave",()=>c(null),{once:!0}),c(f))},u=()=>{if(!a)return;c(null);let g=a.querySelector("button");g&&(Ce(g,r.fadeup),n(Er(a)))},p=g=>{g.target.tagName.toLowerCase()==="button"&&(Ce(g.target,r.fadeup),n(Er(g.target.parentElement)))},m=()=>{a&&(c(null),s(Er(a)))};return pd(xv,{children:[a&&lo(Tt,{triggerRef:{current:a},parentNode:a,className:r.popover,children:pd("div",{className:r.options,children:[lo("button",{type:"button",className:r.option,onClick:u,children:o}),lo("div",{className:r.divider}),lo("button",{type:"button",className:r.option,onClick:m,children:e})]})}),lo("div",{ref:i,className:r.root,dangerouslySetInnerHTML:{__html:l},onMouseOver:d,onClick:p})]})},md=Rv;var kr={};q(kr,{enUS:()=>Pv,nlNL:()=>Iv});var Pv={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"}]},Iv={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 gd={fadeup:"F",fadedown:"H",selected:"zo",thumbsUp:"xr",thumbsDown:"fr"};import{jsx as Re,jsxs as hd}from"react/jsx-runtime";var Nv=({cue:t,onRemove:e,onCopy:o,onUse:n,onThumbsUp:s,onThumbsDown:r})=>{let i=h("WidgetCue",gd),a=E(kr),c=vt(),[l,d]=Mv(null),u=y=>{o&&o(y,t)},p=y=>{n&&n(y,t)},m=y=>{y.preventDefault(),y.stopPropagation(),e(t)},g=y=>{y.preventDefault(),y.stopPropagation(),Ce(y.target,i.fadeup),d("up"),s(t)},f=y=>{y.preventDefault(),y.stopPropagation(),Ce(y.target,i.fadedown),d("down"),r(t)};return Av(()=>{c("Assistant response displayed",{name:t.rule.name,description:t.rule.description,group:t.rule.label})},[]),hd(A,{"data-testid":"cue",children:[Re(D,{children:hd(D.Content,{children:[t.title&&Re(D.Title,{"data-testid":"widget-cue-title",children:t.title}),Re(md,{content:t.text,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:u,onUse:p})]})}),Re(A.IconButton,{title:a("thumbsUp"),onClick:g,icon:Re(tn,{}),className:fd(i.thumbsUp,l==="up"&&i.selected),disabled:!!l}),Re(A.IconButton,{title:a("thumbsDown"),onClick:f,icon:Re(en,{}),className:fd(i.thumbsDown,l==="down"&&i.selected),disabled:!!l}),Re(A.IconButton,{title:a("removeCue"),onClick:m,icon:Re(dd,{})})]})},yd=Nv;import{Fragment as Dv,jsx as vd}from"react/jsx-runtime";var _v=({cues:t})=>{let e=Ov(),o=oe(),n=vt(),s=l=>{e(zc({id:l.rule.id})),n("Assistant response closed",{name:l.rule.name,group:l.rule.label,description:l.rule.description})},r=(l,d)=>{je(l),n("Assistant response copied",{name:d.rule.name,group:d.rule.label,description:d.rule.description,copiedText:l})},i=(l,d)=>{o.send(Ne,{text:l,suggestion:{source:"cue",sourceText:l}}),n("Assistant response used",{name:d.rule.name,group:d.rule.label,description:d.rule.description,usedText:l})},a=l=>{n("Assistant response feedback",{name:l.rule.name,group:l.rule.label,description:l.rule.description,thumb:"up"})},c=l=>{n("Assistant response feedback",{name:l.rule.name,group:l.rule.label,description:l.rule.description,thumb:"down"})};return vd(Dv,{children:t.map(l=>vd(yd,{cue:l,onRemove:s,onCopy:r,onUse:i,onThumbsDown:c,onThumbsUp:a},l.rule.id))})},Sd=_v;import{useCallback as Fv}from"react";var Hv=/(https?:\/\/[^\s]+)/,xd=t=>t.split(" ").find(e=>Hv.test(e));import{jsx as Rt,jsxs as Mn}from"react/jsx-runtime";var Bv=({suggestion:t,lines:e,onUse:o})=>{var d;let n=t.text||t.url||t.message,s=xd(n),r=E(Xe),i=b("showImages"),a=b("fallbackImage"),c=u=>{u.preventDefault(),u.stopPropagation(),o(n)},l=Fv(u=>{window.open(s,"_blank"),u.stopPropagation(),u.preventDefault()},[s]);return Mn(A,{onClick:c,"data-testid":"edit-suggestion",children:[Mn(D,{children:[i&&t.image&&Rt(D.Image,{src:En(t,"small",a||void 0),title:t.title}),Mn(D.Content,{children:[t.title&&Rt(D.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((d=t.searchKeywords)==null?void 0:d.length)>0&&Rt(A.Labels,{labels:t.searchKeywords}),Rt(D.Content,{cropText:e==="single",lineClamp:e==="multiple",children:n})]})]}),Mn(A.Actions,{children:[s&&Rt(A.ActionButton,{onClick:l,label:r("visitUrl")}),Rt(A.ActionButton,{primary:!0,onClick:c,label:r("useSuggestion")})]})]})},bd=Bv;import{Fragment as Uv,jsx as Cd}from"react/jsx-runtime";var Kv=({lines:t,suggestions:e})=>{let o=oe(),n=(s,r)=>{o.send(Ne,{text:s,suggestion:{...r,source:r.source,sourceText:r.text}})};return Cd(Uv,{children:e.map(s=>Cd(bd,{suggestion:s,lines:t,onUse:r=>n(r,s)},s.text||s.url||s.message))})},wd=Kv;var co={};q(co,{enUS:()=>zv,nlNL:()=>Vv});var zv={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"}]},Vv={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 uo={root:"gr",loginText:"br",stateText:"jo",sectionList:"hr",shortcutList:"mr",shortcut:"ur",link:"Yo"};import{jsx as P,jsxs as Pt}from"react/jsx-runtime";var On=(t,e)=>{let o=j(X);jv(()=>o?e.every(n=>!!n)?t():()=>{}:()=>{},[...e,o])},qv=({onLogIn:t})=>{let e=h("Widget",uo),o=b("isEmbedded"),n=b("adminUrl");return P("div",{className:e.loginText,children:P("div",{children:P(yn,{isEmbedded:o,loginUrl:n,onLogIn:t})})},"login")},Td=({text:t})=>{let e=h("Widget",uo);return P("div",{className:e.stateText,children:P("div",{children:P("p",{children:t})})},"notification")},Xv=()=>{let t=E(co),e=Nn(),o=h("Widget",uo),n=b("showSearch"),s=b("showSummaryCommand"),r=b("showKnowledgeSearch"),i=j(Dc("/admin/")),a=oe(),c=b("productName"),l=n||s||r||i;return On(()=>(e(br()),()=>{e(Fc())}),[e]),l?P(Pe,{title:t("actions"),type:"shortcuts",children:Pt("div",{className:o.shortcutList,children:[n&&Pt("button",{className:o.shortcut,"data-testid":"shortcut-search",onClick:()=>a.send("ShowCommandPalette",{isOpen:!0}),children:[P(ft,{}),t("linkSearch")]}),s&&Pt("button",{className:o.shortcut,"data-testid":"shortcut-summary",onClick:()=>a.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[P(ld,{}),t("linkSummary")]}),r&&Pt("button",{className:o.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>a.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[P(id,{}),t("linkKnowledgeSearch")]}),i&&Pt("a",{className:o.shortcut,target:"_blank",href:i,"data-testid":"shortcut-studio-login",rel:"noreferrer",children:[P(sd,{}),t("linkStudioLogin",{productName:c})]})]})}):null},Zv=()=>{let t=Nn(),e=b("showCustomMessages"),o=j(Rc),n=j(dt);return On(()=>(t(io(n)),t(Mc(n)),()=>{t(Nc(n))}),[t,e,n]),!e||o.length===0?null:P(Pe,{type:"custom-messages","data-testid":"custom-messages",children:P(te,{withDivider:!0,children:o.map(s=>P(Qc,{suggestion:s},s.text))})})},Qv=()=>{let t=E(co),e=Nn(),o=b("showAutoflows"),n=j(Cc),s=j(dt);return On(()=>(e(Ee(s)),e(wc(s)),()=>{e(Tc(s))}),[e,o,s]),!o||n.length===0?null:P(Pe,{type:"autoflows",title:t("titleAutoflows"),"data-testid":"autoflows",children:P(te,{withDivider:!0,children:P(Xc,{})})})},Jv=()=>{let t=Nn(),e=j(rn),o=j(Kc),n=j(Yo),s=j(an),r=j(we),i=j(wo);return On(()=>{e.forEach(({type:a})=>{a==="entities"?t(ae()):["cues"].includes(a)||t(ce(a))})},[t,i,r]),P(Gv,{children:e.map(({type:a,title:c,amount:l,lines:d})=>{var u,p;switch(a){case"entities":return n&&n.length>0&&P(Pe,{type:a,title:c,"data-testid":`type-${a}`,children:P(od,{entities:n})},a);case"cues":return o&&o.length>0&&P(Pe,{type:a,title:c,"data-testid":`type-${a}`,children:P(te,{withDivider:!0,children:P(Sd,{cues:o})})},a);default:return((p=(u=s[a])==null?void 0:u.suggestions)==null?void 0:p.length)>0&&P(Pe,{type:a,title:c,"data-testid":`type-${a}`,children:P(te,{withDivider:!0,children:P(wd,{lines:d,contentType:a,suggestions:s[a].suggestions.slice(0,l)||[]})})},a)}})})},Yv=({onLogIn:t})=>{let e=E(co),o=h("Widget",uo),n=j(ut),s=j(X),r=j(dt),i=j(we);return n===!1?P(Td,{text:e("notSupported")}):s===!1?P(qv,{onLogIn:t}):!i||!r||s===null?P(Td,{text:e("waiting")}):P("div",{className:Wv(o.root),"data-testid":"widget",children:Pt(Yn,{className:o.sectionList,children:[P(Xv,{}),P(Zv,{}),P(Qv,{}),P(Jv,{})]})})},Ed=Yv;function mo(t){let e=new Range;return e.selectNodeContents(t),e}function kd(t,e,o){try{return ot(t,e,o),!0}catch{return!1}}function _n(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function Dn(t){return"tagName"in t&&t.tagName==="BR"}var po=/[\u200B-\u200D\uFEFF]/g;function ot(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(c,l){let d=-1,u=/[\u200B-\u200D\uFEFF]/;if(!u.test(c))return l;for(let p=0;p<=c.length;p++)if(u.test(c[p])||d++,d===l)return p;throw new Error("Offset out of range")}function a(c){switch(c.nodeType){case Node.TEXT_NODE:{let l=c.textContent,d=l.replace(po,""),u=s+d.length,p=e>=s&&e<=u,m=o>=s&&o<=u;if(p){let g=i(l,e-s);g===0&&!m?n.setStartBefore(c):n.setStart(c,g)}m&&(n.setEnd(c,i(l,o-s)),r=!0),s=u;break}case Node.ELEMENT_NODE:{if(Dn(c)&&(s===e&&n.setStartBefore(c),s++,s===o)){n.setEndAfter(c),r=!0;return}for(let d=0;d<c.childNodes.length&&(a(c.childNodes[d]),!r);d++);let l=c.lastChild;_n(c)&&l&&!_n(l)&&!Dn(l)&&s++;break}default:break}}if(a(t),n.startContainer===document)throw new Error("Offsets out of bound");return n}function Hn(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,c,l=0;function d(u){let p=u===o,m=u===s;switch(u.nodeType){case Node.TEXT_NODE:{let g=u.textContent;p&&(a=l+g.substring(0,n).replace(po,"").length),m&&(c=l+g.substring(0,r).replace(po,"").length),l+=g.replace(po,"").length;break}case Node.ELEMENT_NODE:{let g=u.nextSibling===null;Dn(u)&&!g&&l++;for(let f=0;f<u.childNodes.length;f++){let y=p&&f===n,k=m&&f===r;if(y&&(a=l),k&&(c=l),c!==void 0||((!y||!i)&&d(u.childNodes[f]),m&&f===r-1&&(c=l),c!==void 0))break}!m&&_n(u)&&!g&&l++,m&&(c=l);break}default:break}}if(d(t),c===void 0)throw new Error("Could not determine start and end");return{start:a??c,end:c}}function Fn(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 c(l){let d=l===o,u=l===s;switch(d&&i++,l.nodeType){case Node.TEXT_NODE:{if(i!==0)return;let p=d?n:0,m=u?r:void 0,g=l.textContent.replace(po,"");p===0&&m===void 0?a+=g:a+=g.substring(p,m);break}case Node.ELEMENT_NODE:{let p=l.nextSibling===null;i===0&&Dn(l)&&!p&&(a+=`
8
+ `)}var Rv=({content:t,useLabel:e,copyLabel:o,onCopy:n,onUse:s})=>{let r=h("Markdown",ud),i=Cv(null),[a,c]=wv(null),l=bv(()=>{let g=Tv(kv(t));return Sv.sanitize(g).replace(/<\/code>/g,`${Ev(r.copyIcon)}</code>`)},[t]),d=g=>{var k;let f=g.target,y=!!((k=i.current)!=null&&k.querySelector("code"));a||y&&f.tagName!=="CODE"||!y&&f!==i.current||(f.addEventListener("mouseleave",()=>c(null),{once:!0}),c(f))},u=()=>{if(!a)return;c(null);let g=a.querySelector("button");g&&(Ce(g,r.fadeup),n(Er(a)))},p=g=>{g.target.tagName.toLowerCase()==="button"&&(Ce(g.target,r.fadeup),n(Er(g.target.parentElement)))},m=()=>{a&&(c(null),s(Er(a)))};return pd(xv,{children:[a&&lo(Tt,{triggerRef:{current:a},parentNode:a,className:r.popover,children:pd("div",{className:r.options,children:[lo("button",{type:"button",className:r.option,onClick:u,children:o}),lo("div",{className:r.divider}),lo("button",{type:"button",className:r.option,onClick:m,children:e})]})}),lo("div",{ref:i,className:r.root,dangerouslySetInnerHTML:{__html:l},onMouseOver:d,onClick:p})]})},md=Rv;var kr={};q(kr,{enUS:()=>Pv,nlNL:()=>Iv});var Pv={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"}]},Iv={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 gd={fadeup:"F",fadedown:"H",selected:"zo",thumbsUp:"xr",thumbsDown:"fr"};import{jsx as Re,jsxs as hd}from"react/jsx-runtime";var Nv=({cue:t,onRemove:e,onCopy:o,onUse:n,onThumbsUp:s,onThumbsDown:r})=>{let i=h("WidgetCue",gd),a=E(kr),c=vt(),[l,d]=Mv(null),u=y=>{o&&o(y,t)},p=y=>{n&&n(y,t)},m=y=>{y.preventDefault(),y.stopPropagation(),e(t)},g=y=>{y.preventDefault(),y.stopPropagation(),Ce(y.target,i.fadeup),d("up"),s(t)},f=y=>{y.preventDefault(),y.stopPropagation(),Ce(y.target,i.fadedown),d("down"),r(t)};return Av(()=>{c("Assistant response displayed",{name:t.rule.name,description:t.rule.description,group:t.rule.label})},[]),hd(A,{"data-testid":"cue",children:[Re(D,{children:hd(D.Content,{children:[t.title&&Re(D.Title,{"data-testid":"widget-cue-title",children:t.title}),Re(md,{content:t.text,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:u,onUse:p})]})}),Re(A.IconButton,{title:a("thumbsUp"),onClick:g,icon:Re(tn,{}),className:fd(i.thumbsUp,l==="up"&&i.selected),disabled:!!l}),Re(A.IconButton,{title:a("thumbsDown"),onClick:f,icon:Re(en,{}),className:fd(i.thumbsDown,l==="down"&&i.selected),disabled:!!l}),Re(A.IconButton,{title:a("removeCue"),onClick:m,icon:Re(dd,{})})]})},yd=Nv;import{Fragment as Dv,jsx as vd}from"react/jsx-runtime";var _v=({cues:t})=>{let e=Ov(),o=oe(),n=vt(),s=l=>{e(zc({id:l.rule.id})),n("Assistant response closed",{name:l.rule.name,group:l.rule.label,description:l.rule.description})},r=(l,d)=>{je(l),n("Assistant response copied",{name:d.rule.name,group:d.rule.label,description:d.rule.description,copiedText:l})},i=(l,d)=>{o.send(Ne,{text:l,suggestion:{source:"cue",sourceText:l}}),n("Assistant response used",{name:d.rule.name,group:d.rule.label,description:d.rule.description,usedText:l})},a=l=>{n("Assistant response feedback",{name:l.rule.name,group:l.rule.label,description:l.rule.description,thumb:"up"})},c=l=>{n("Assistant response feedback",{name:l.rule.name,group:l.rule.label,description:l.rule.description,thumb:"down"})};return vd(Dv,{children:t.map(l=>vd(yd,{cue:l,onRemove:s,onCopy:r,onUse:i,onThumbsDown:c,onThumbsUp:a},l.rule.id))})},Sd=_v;import{useCallback as Fv}from"react";var Hv=/(https?:\/\/[^\s]+)/,xd=t=>t.split(" ").find(e=>Hv.test(e));import{jsx as Rt,jsxs as Mn}from"react/jsx-runtime";var Bv=({suggestion:t,lines:e,onUse:o})=>{var d;let n=t.text||t.url||t.message,s=xd(n),r=E(Xe),i=b("showImages"),a=b("fallbackImage"),c=u=>{u.preventDefault(),u.stopPropagation(),o(n)},l=Fv(u=>{window.open(s,"_blank"),u.stopPropagation(),u.preventDefault()},[s]);return Mn(A,{onClick:c,"data-testid":"edit-suggestion",children:[Mn(D,{children:[i&&t.image&&Rt(D.Image,{src:En(t,"small",a||void 0),title:t.title}),Mn(D.Content,{children:[t.title&&Rt(D.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((d=t.searchKeywords)==null?void 0:d.length)>0&&Rt(A.Labels,{labels:t.searchKeywords}),Rt(D.Content,{cropText:e==="single",lineClamp:e==="multiple",children:n})]})]}),Mn(A.Actions,{children:[s&&Rt(A.ActionButton,{onClick:l,label:r("visitUrl")}),Rt(A.ActionButton,{primary:!0,onClick:c,label:r("useSuggestion")})]})]})},bd=Bv;import{Fragment as Uv,jsx as Cd}from"react/jsx-runtime";var Kv=({lines:t,suggestions:e})=>{let o=oe(),n=(s,r)=>{o.send(Ne,{text:s,suggestion:{...r,source:r.source,sourceText:r.text}})};return Cd(Uv,{children:e.map(s=>Cd(bd,{suggestion:s,lines:t,onUse:r=>n(r,s)},s.text||s.url||s.message))})},wd=Kv;var co={};q(co,{enUS:()=>zv,nlNL:()=>Vv});var zv={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"}]},Vv={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 uo={root:"gr",loginText:"br",stateText:"jo",sectionList:"hr",shortcutList:"mr",shortcut:"ur",link:"Yo"};import{jsx as P,jsxs as Pt}from"react/jsx-runtime";var On=(t,e)=>{let o=j(X);jv(()=>o?e.every(n=>!!n)?t():()=>{}:()=>{},[...e,o])},qv=({onLogIn:t})=>{let e=h("Widget",uo),o=b("isEmbedded"),n=b("adminUrl");return P("div",{className:e.loginText,children:P("div",{children:P(yn,{isEmbedded:o,loginUrl:n,onLogIn:t})})},"login")},Td=({text:t})=>{let e=h("Widget",uo);return P("div",{className:e.stateText,children:P("div",{children:P("p",{children:t})})},"notification")},Xv=()=>{let t=E(co),e=Nn(),o=h("Widget",uo),n=b("showSearch"),s=b("showSummaryCommand"),r=b("showKnowledgeSearch"),i=j(Dc("/admin/")),a=oe(),c=b("productName"),l=n||s||r||i;return On(()=>(e(br()),()=>{e(Fc())}),[e]),l?P(Pe,{title:t("actions"),type:"shortcuts",children:Pt("div",{className:o.shortcutList,children:[n&&Pt("button",{type:"button",className:o.shortcut,"data-testid":"shortcut-search",title:t("linkSearch"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0}),children:[P(ft,{}),t("linkSearch")]}),s&&Pt("button",{type:"button",className:o.shortcut,"data-testid":"shortcut-summary",title:t("linkSummary"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[P(ld,{}),t("linkSummary")]}),r&&Pt("button",{type:"button",className:o.shortcut,"data-testid":"shortcut-knowledge-assist",title:t("linkKnowledgeSearch"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[P(id,{}),t("linkKnowledgeSearch")]}),i&&Pt("a",{className:o.shortcut,target:"_blank",href:i,"data-testid":"shortcut-studio-login",title:t("linkStudioLogin",{productName:c}),rel:"noreferrer",children:[P(sd,{}),t("linkStudioLogin",{productName:c})]})]})}):null},Zv=()=>{let t=Nn(),e=b("showCustomMessages"),o=j(Rc),n=j(dt);return On(()=>(t(io(n)),t(Mc(n)),()=>{t(Nc(n))}),[t,e,n]),!e||o.length===0?null:P(Pe,{type:"custom-messages","data-testid":"custom-messages",children:P(te,{withDivider:!0,children:o.map(s=>P(Qc,{suggestion:s},s.text))})})},Qv=()=>{let t=E(co),e=Nn(),o=b("showAutoflows"),n=j(Cc),s=j(dt);return On(()=>(e(Ee(s)),e(wc(s)),()=>{e(Tc(s))}),[e,o,s]),!o||n.length===0?null:P(Pe,{type:"autoflows",title:t("titleAutoflows"),"data-testid":"autoflows",children:P(te,{withDivider:!0,children:P(Xc,{})})})},Jv=()=>{let t=Nn(),e=j(rn),o=j(Kc),n=j(Yo),s=j(an),r=j(we),i=j(wo);return On(()=>{e.forEach(({type:a})=>{a==="entities"?t(ae()):["cues"].includes(a)||t(ce(a))})},[t,i,r]),P(Gv,{children:e.map(({type:a,title:c,amount:l,lines:d})=>{var u,p;switch(a){case"entities":return n&&n.length>0&&P(Pe,{type:a,title:c,"data-testid":`type-${a}`,children:P(od,{entities:n})},a);case"cues":return o&&o.length>0&&P(Pe,{type:a,title:c,"data-testid":`type-${a}`,children:P(te,{withDivider:!0,children:P(Sd,{cues:o})})},a);default:return((p=(u=s[a])==null?void 0:u.suggestions)==null?void 0:p.length)>0&&P(Pe,{type:a,title:c,"data-testid":`type-${a}`,children:P(te,{withDivider:!0,children:P(wd,{lines:d,contentType:a,suggestions:s[a].suggestions.slice(0,l)||[]})})},a)}})})},Yv=({onLogIn:t})=>{let e=E(co),o=h("Widget",uo),n=j(ut),s=j(X),r=j(dt),i=j(we);return n===!1?P(Td,{text:e("notSupported")}):s===!1?P(qv,{onLogIn:t}):!i||!r||s===null?P(Td,{text:e("waiting")}):P("div",{className:Wv(o.root),"data-testid":"widget",children:Pt(Yn,{className:o.sectionList,children:[P(Xv,{}),P(Zv,{}),P(Qv,{}),P(Jv,{})]})})},Ed=Yv;function mo(t){let e=new Range;return e.selectNodeContents(t),e}function kd(t,e,o){try{return ot(t,e,o),!0}catch{return!1}}function _n(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function Dn(t){return"tagName"in t&&t.tagName==="BR"}var po=/[\u200B-\u200D\uFEFF]/g;function ot(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(c,l){let d=-1,u=/[\u200B-\u200D\uFEFF]/;if(!u.test(c))return l;for(let p=0;p<=c.length;p++)if(u.test(c[p])||d++,d===l)return p;throw new Error("Offset out of range")}function a(c){switch(c.nodeType){case Node.TEXT_NODE:{let l=c.textContent,d=l.replace(po,""),u=s+d.length,p=e>=s&&e<=u,m=o>=s&&o<=u;if(p){let g=i(l,e-s);g===0&&!m?n.setStartBefore(c):n.setStart(c,g)}m&&(n.setEnd(c,i(l,o-s)),r=!0),s=u;break}case Node.ELEMENT_NODE:{if(Dn(c)&&(s===e&&n.setStartBefore(c),s++,s===o)){n.setEndAfter(c),r=!0;return}for(let d=0;d<c.childNodes.length&&(a(c.childNodes[d]),!r);d++);let l=c.lastChild;_n(c)&&l&&!_n(l)&&!Dn(l)&&s++;break}default:break}}if(a(t),n.startContainer===document)throw new Error("Offsets out of bound");return n}function Hn(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,c,l=0;function d(u){let p=u===o,m=u===s;switch(u.nodeType){case Node.TEXT_NODE:{let g=u.textContent;p&&(a=l+g.substring(0,n).replace(po,"").length),m&&(c=l+g.substring(0,r).replace(po,"").length),l+=g.replace(po,"").length;break}case Node.ELEMENT_NODE:{let g=u.nextSibling===null;Dn(u)&&!g&&l++;for(let f=0;f<u.childNodes.length;f++){let y=p&&f===n,k=m&&f===r;if(y&&(a=l),k&&(c=l),c!==void 0||((!y||!i)&&d(u.childNodes[f]),m&&f===r-1&&(c=l),c!==void 0))break}!m&&_n(u)&&!g&&l++,m&&(c=l);break}default:break}}if(d(t),c===void 0)throw new Error("Could not determine start and end");return{start:a??c,end:c}}function Fn(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 c(l){let d=l===o,u=l===s;switch(d&&i++,l.nodeType){case Node.TEXT_NODE:{if(i!==0)return;let p=d?n:0,m=u?r:void 0,g=l.textContent.replace(po,"");p===0&&m===void 0?a+=g:a+=g.substring(p,m);break}case Node.ELEMENT_NODE:{let p=l.nextSibling===null;i===0&&Dn(l)&&!p&&(a+=`
9
9
  `);for(let m=d?n:0;m<(u?Math.min(r,l.childNodes.length):l.childNodes.length)&&(c(l.childNodes[m]),i!==1);m++);!u&&i===0&&_n(l)&&!p&&(a+=`
10
- `);break}default:break}u&&i++}return c(t),a}var Rd=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(Rd||{}),Be=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(Rd).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 Pd(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var It=class extends Be{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),Fn(this.element,e)}getHTML(){return this.element.innerHTML||""}getRange(){var r;let e=this.getRootNode();if(e.activeElement!==this.element)return null;let o="getSelection"in e?e.getSelection():window.getSelection();if(!o)return null;let n="getComposedRanges"in o&&e instanceof ShadowRoot?(r=o.getComposedRanges(e))==null?void 0:r[0]:o.rangeCount>0?o.getRangeAt(0):null;if(!n)return null;let s=this.element.ownerDocument.createRange();return s.setStart(n==null?void 0:n.startContainer,n==null?void 0:n.startOffset),s.setEnd(n==null?void 0:n.endContainer,n==null?void 0:n.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let e=this.getRange();if(!e||!e.collapsed||!("getBoundingClientRect"in e))return null;let o=e.getBoundingClientRect();return!Pd(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!Pd(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return Hn(this.element,e);let o=this.lastKnownSelection;if(o&&kd(this.element,o.start,o.end))return o;let n=mo(this.element);return n.collapse(!1),Hn(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return Fn(this.element,ot(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 Lt=class extends Be{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 Id(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,c])=>{i.searchParams.append(a,c)}),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 eS(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}var Rr=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()}},Pr=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=Id(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()}},Ir=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(e){this.sessionId!==e&&(this.cleanup(),w.info("Set sessionId",e),this.sessionId=e,this.channel=this.createChannel(e))}createChannel(e){let o=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new Pr(e,this.deepdeskUrl,{debug:!0}):new Rr(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=eS(s.data);typeof r!="object"||r.type!=="event"||r.channel!==e||(w.info("Received broadcast event",this.sessionId,s),(a=(i=this.eventMap)[r.name])==null||a.call(i,r.payload))};return o.onMessage(n),o}send(e,o,n){var i,a;w.info("Broadcast event",{sessionId:this.sessionId,name:e,payload:o});let s={type:"event",name:e,payload:o};n!==!1&&((a=(i=this.eventMap)[e])==null||a.call(i,o));let r=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;r==null||r.postMessage({...s,channel:this.sessionId})}cleanup(e=!1){var o,n;(o=this.channel)==null||o.close(),delete this.channel,e&&((n=this.defaultChannel)==null||n.close(),delete this.defaultChannel)}},Ld=Ir;var At=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var Lr=t=>new Promise(e=>{setTimeout(e,t)});var Mt=class extends At{name="ClientError"},Mr=class extends At{name="ServerError"},Ar=new Map;function tS(t){return t.status===204||["0",null].includes(t.headers.get("content-length"))}var he=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,c=o.method===void 0||o.method.toLowerCase()==="get",{useCache:l=!1,abortLatest:d=!1,attempts:u=1,retryDelay:p=500,refreshTokenOn401:m=!0,retryOnError:g=T=>T instanceof TypeError,retryOnResponse:f=T=>T.status>=500,version:y="v1",...k}=o;if(l)if(c){if(Ar.has(i)){n(Ar.get(i));return}}else throw new Error(`Can't use 'useCache' for ${o.method}`);let v={credentials:"include",...k,headers:{"Content-Type":"application/json",...k.headers}};!c&&this.csrfToken&&(v.headers={...v.headers,"X-CSRFToken":this.csrfToken}),typeof y=="string"&&(v.headers={...v.headers,"X-Deepdesk-API-Version":y});let S=u,R=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&d&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let x=async()=>(S--,a(i,v).then(async T=>f(T)&&!r.isAborted&&S>0?(await Lr(p),x()):T.status===401&&m===!0&&R===!1?(R=!0,await this.refreshToken(),x()):T).catch(async T=>{if(g(T)&&!r.isAborted&&S>0)return await Lr(p),x();throw T}));x().then(async T=>{let N=await T.json().catch(z=>{if(tS(T))return null;throw z});if(delete this.latestRequestByUrl[i],T.status>=500){s(new Mr("Server Error",N));return}else if(T.status===401){s(new Mt("Unauthorized",N));return}else if(T.status===403){s(new Mt("Forbidden",N));return}else if(T.status===404){s(new Mt("Not Found",N));return}else if(T.status>=400){s(new Mt("Bad Request",N));return}l&&Ar.set(i,N),n(N)}).catch(T=>{s(T)})})}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 oS;(e=>{let t;(c=>(c.SEND_MESSAGE="Send Message",c.HANDLING_TIME="Handling Time",c.START_AUTOFLOW="Start Autoflow",c.ABORT_AUTOFLOW="Abort Autoflow",c.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",c.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||={})})(oS||={});function Bn(t){return{...L(t),tags:t.tags}}var Ke=class t{constructor(e,o={}){this.options=o;this.client=new he(e,{fetch:o.fetch}),this.client.patchFetch(n=>async(s,r)=>{let i=await n(s,r);return this.handleDeepdeskVersionHeaders(i),i})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=await this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(t.exchangeTokenPromise||(t.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),t.exchangeTokenPromise):Promise.resolve()}async createConversation(e){await this.preflight(),w.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...H(e),tags:e.tags},{version:"v2"});return Bn(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null,useCache:!0});return L(o)}async getKnowledgeAssistant(e){let o=await this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{version:null,useCache:!0});return L(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return L(e)}async getAccount(){let e=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return L(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null,useCache:!0});return L(e)}async checkUserExists(e){let{exists:o}=await this.client.get(`/apis/admin/users/exists?external_id=${e}`);return o}async getConversationBySessionId(e,o={}){await this.preflight(),w.info(`Getting conversation for session ${e}`);let{attempts:n=1,retryDelay:s=1e3}=o,r=await this.client.get(`/api/conversations/by_session_id/${e}`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"});return w.info(`Successfully retrieved conversation ${r.id} for session ${e}`),Bn(r)}async isConversationSupported(e,o={}){w.info(`Check if conversation for session ${e} is supported`);let{attempts:n=1,retryDelay:s=1e3}=o;return(await this.client.get(`/api/conversations/by_session_id/${e}/active_profile`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"})).has_active_profile}async updateConversation(e,o){let n=H(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return Bn(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=>Bn(s))}async sendEvent(e,o){let{data:n,...s}=o,r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((i,[a,c])=>({...i,[a]:c}),{});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 L(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 w.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=>({...L(r),text:r.text||r.url||r.message,source:n,type:n})).filter((r,i,a)=>i===a.findIndex(c=>c.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 L(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 L(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,H(e),{version:"v2"});return L(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 L(r)}async requestLoginByEmail(e){let o=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return L(o)}async requestPasswordlessToken(){let e=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return L(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 L(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 L(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 L(o)}async translateMessages(e){let o=await this.client.post("/api/translate",H(e),{version:"v2"});return L(o)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(ei);if(!o||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&o&&a!==o&&w.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(o)}`),this.latestReceivedDeepdeskVersions[i]=o})}};var go=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(cs(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,L(s))}catch{w.warn(`Invalid JSON for ${e}: ${n}`)}})}connect(){clearTimeout(this.timeoutTimer);let e=new EventSource(this.url,{withCredentials:!0});this.eventSource=e;let o=!1;e.onopen=()=>{o=!0},e.onerror=()=>{o&&e.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{e.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(n=>{this.proxyEvent(n)})}disconnect(){var e;clearTimeout(this.timeoutTimer),this.eventListeners={},(e=this.eventSource)==null||e.close()}emit(e,o){this.eventListeners[e]&&this.eventListeners[e].forEach(n=>n(o))}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),this.proxyEvent(e),()=>{this.off(e,o)}}off(e,o){let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}};var nS;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(nS||={});var fo=class{constructor(e,o={}){this.apiUrl=e;this.client=new he(e,o)}client;streams={};logger=w;async getCustomMessages(e){let o=await this.client.get(`/sessions/${e}/suggestions`);return L(o.suggestions)}async sendCustomMessage(e,o){let n=await this.client.post(`/sessions/${e}/messages`,H(o));return L(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 L(o.autoflows)}async startAutoflowSession(e){let o=await this.client.post("/autoflow-sessions",H(e));return L(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new go(`${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 dS,configureStore as uS}from"@reduxjs/toolkit";import{createSlice as sS}from"@reduxjs/toolkit";var Ad={startTime:null,stopTime:null},Md=sS({name:"handlingTime",initialState:Ad,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,()=>Ad)}}),{handlingTimeStart:Nd,handlingTimeStop:Kn,handlingTimeReset:Od}=Md.actions,_d=Md.reducer;var Dd=(t={})=>{let e={onAuthError:lt(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};import{createAsyncThunk as rS,createSlice as iS}from"@reduxjs/toolkit";var Un={list:{keywordMatches:[]},fetchState:"idle"};var nt=rS("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 Un.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),aS=iS({name:"styleSuggestions",initialState:Un,reducers:{},extraReducers:t=>{t.addCase(nt.pending,e=>{e.fetchState="loading"}).addCase(nt.rejected,e=>{e.fetchState="error"}).addCase(nt.fulfilled,(e,o)=>{e.fetchState="done",Le(e.list,o.payload)||(e.list=o.payload)}).addCase(Ve,e=>{e.list=Un.list}).addCase(M,()=>Un)}}),Hd=aS.reducer;var Fd=(t={})=>{let e,o=!0,n={getStyleSuggestions:nt,debounce:500,...t};return s=>r=>i=>{var m;let a=s.getState().input.text,c=r(i),l=s.getState();if(l.auth.isLoggedIn!==!0)return c;let{showStyleSuggestions:d}=l.settings;if(!((m=l.conversation.current)==null?void 0:m.id)||!d)return c;let{text:p}=l.input;return p===a&&!o||(clearTimeout(e),p==="")||(e=setTimeout(()=>{o=!1,s.dispatch(n.getStyleSuggestions({text:p}))},t.debounce)),c}};function lS(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var Bd=(t={})=>{let e={getTextSuggestions:ce,getAutocompleteSuggestions:eo,debounce:200,check:wt,...t},o;return n=>s=>r=>{var f;let{input:{userCommitted:i}}=n.getState(),a=s(r),c=n.getState();if(c.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:l,showTabCompletion:d}=c.settings,u=(f=c.conversation.current)==null?void 0:f.id,p=r.type===ln.toString();if(!u||!l&&!d)return a;let{input:{userCommitted:m}}=c;return lS(m,i)&&!p||(clearTimeout(o),!e.check(c))||(o=setTimeout(()=>{let y=mt(c);y===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(y))},p?0:e.debounce)),a}};var Kd=nt.fulfilled.toString();function cS(t,e){let o=new Set([...e.keywordMatches.map(s=>s.keyword)]),n=[];return o.forEach(s=>{let r=t.keywordMatches.filter(c=>c.keyword===s),i=e.keywordMatches.filter(c=>c.keyword===s),a=i.length-r.length;a<=0||n.push(...i.slice(0,a))}),n}var Ud=t=>e=>o=>n=>{var l;if(n.type!==Kd){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 c=cS(s,i);n.type===Kd&&c.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:c}})};var pS=dS({answer:tl,auth:ci,autoflows:Ec,conversation:mi,contentTypes:aa,customMessages:Oc,passwordlessToken:Bc,entities:Na,knowledgeAssistant:Ja,handlingTime:_d,info:Mi,input:Pi,settings:oi,profile:al,search:Bi,summary:Ua,styleSuggestions:Hd,ui:Ml,rules:Vc,textSuggestions:hl});function zd(t){return uS({reducer:pS,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),Dd(),Bd({debounce:200}),Fd({debounce:500}),Ud(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var mS=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},gS=t=>e=>o=>n=>{var a;let s=e.getState(),r=ns("inlineSuggestions")(s);switch(n.type){case lt.toString():{!n.payload&&t.emit("logout",void 0);break}case ae.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:n.payload}});break;case W.toString():t.sendEvent(n.payload.name,{conversationId:((a=n.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:n.payload.data});break;case Lo.toString():t.handleKeyDown(n.payload);break;case Ve.toString():t.logSendMessage(n.payload);break;case Ao.toString():t.handleInputChanged(n.payload);break;case et.fulfilled.toString():n.isBroadcasted||t.broadcast(ms,n,!1),t.emit("cues",n.payload);break;default:break}let i=o(n);switch(n.type){case Ve.toString():t.handleAfterSendMessage(n.payload);break;case to.toString():t.onUpdateShowTabHint(n.payload);break;case Kn.toString():t.logHandlingTime();break;case"analytics/logEvent/fulfilled":{t.emit("event",n.meta.arg);break}case me.toString():{let{start:c,end:l}=s.input.selection;t.emit("select-suggestion",{type:mS(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:c,end:l}:{start:0,end:l}},{mayApplyChanges:!0}),r&&(e.dispatch(pe([])),e.dispatch(xe()));break}case Io.toString():{let{start:c,end:l}=s.input.selection;t.emit("replace",{...n.payload,replace:n.payload.replace==="selection"?{start:c,end:l}:{start:0,end:l}},{mayApplyChanges:!0});break}case Bt.toString():{let c=e.getState(),{text:l,selection:d}=c.input.userCommitted;t.emit("reset",{text:l,selectionAfter:d},{mayApplyChanges:!0});break}case Mo.toString():t.emit("select-image",n.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:s.conversation.current.id,data:{path:n.payload.suggestion.image,title:n.payload.suggestion.title}});break;case pe.toString():{r&&n.payload.length>0&&e.dispatch(Me(0));break}case be.fulfilled.toString():{t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{summary:n.payload.summary,model:e.getState().summary.model}});break}default:break}return i},Vd=gS;function Nr(t){return t.toISOString().replace("T"," ").replace("Z","")}function $d(t,e){var s,r,i;let{startTime:o,stopTime:n}=t.handlingTime;if(!o||!n)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:t.conversation.current.id,clientVersion:e.version,agentId:(s=t.info.agentInfo)==null?void 0:s.agentId,agentName:(r=t.info.agentInfo)==null?void 0:r.agentName,agentEmail:(i=t.info.agentInfo)==null?void 0:i.agentEmail,timeStart:Nr(o),timeStop:Nr(n)}}function Wd(t,e,o){var N,z,F;let{text:n,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:c,agentStartedTypingTimestamp:l,externalTimeTotalSeconds:d,pastes:u,cuts:p,deletions:m,textSuggestions:g,offeredTextSuggestions:f}}=e[t],y=n.length,v=g.reduce((I,{text:O,searchTerm:V})=>I+O.length-(V?V.length:0),0),S=l??Date.now(),R=(Date.now()-S)/1e3+(d||0),x=s/R,T=g.reduce((I,{searchTerm:O})=>I+(O?O.length:0),0);return{conversationId:e.conversation.current.id,source:"agent",text:n,clientVersion:o.version,pastes:u,cuts:p,deletions:m,lenTextTyped:s+T,lenTextTotal:y,lenTextAssisted:v,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:R,charsPerSecond:x,numPastes:c,textSuggestionsV2:g,suggestionsCounters:[{source:"gpt",countOffered:f.filter(I=>I.source==="gpt").length}],agentId:(N=e.info.agentInfo)==null?void 0:N.agentId,agentName:(z=e.info.agentInfo)==null?void 0:z.agentName,agentEmail:(F=e.info.agentInfo)==null?void 0:F.agentEmail}}function Or(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return Or(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?Or(s,e):null}function Gd(t,e){return Or(t,e)}function jd(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function fS(t){return typeof t=="object"&&t!==null&&"tagName"in t}function _r(t){return fS(t)&&(He(t)||vn(t))}var qd,ye=new Map,hS=["bottom","height","left","right","top","width"],yS=(t={},e={})=>hS.some(o=>t[o]!==e[o]);function Xd(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,...Xd(e)]:[]}function Zd(t,e){return!t||!e?null:{...t,top:t.top+e.top,left:t.left+e.left}}var zn=!1,Qd=()=>{zn=!0;let t=[];if(ye.forEach((e,o)=>{if(!o.isConnected){e.rect=null,t.push(e),ye.delete(o);return}let n=o.getBoundingClientRect();yS(n,e.rect)&&(e.rect=n,t.push(e))}),t.forEach(e=>{let o=e.parentRects?e.parentRects.reduce(Zd,e.rect):e.rect;e.callbacks.forEach(n=>n(o))}),ye.size===0){zn=!1;return}qd=window.requestAnimationFrame(Qd)};function Dr(t,e){let o=Xd(t),n=[],s=o.map((r,i)=>Dr(r,a=>{n[i]=a;let c=ye.get(t);if(!c)return;let l=n.reduce(Zd,c.rect);c.callbacks.forEach(d=>d(l))}));return{observe(r=!0){if(s.forEach(i=>i.observe(!1)),ye.has(t)){let i=ye.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else ye.set(t,{rect:void 0,callbacks:[e],parentRects:n});r&&!zn&&Qd()},unobserve(){s.forEach(i=>i.unobserve());let r=ye.get(t);if(r){let i=r.callbacks.indexOf(e);i>=0&&r.callbacks.splice(i,1),r.callbacks.length||ye.delete(t),ye.size||(cancelAnimationFrame(qd),zn=!1)}}}}var Jd,ve=new Map,Yd=()=>{ve.forEach((t,e)=>{if(!e.isConnected){ve.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)))}),ve.size!==0&&(Jd=window.requestAnimationFrame(Yd))};function eu(t,e){return{observe(){let o=ve.size===0;ve.has(t)?ve.get(t).callbacks.push(e):ve.set(t,{visible:void 0,callbacks:[e]}),o&&Yd()},unobserve(){let o=ve.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||ve.delete(t),ve.size||cancelAnimationFrame(Jd)}}}}var Hr=["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 Fr(t,e,o){return o.forEach(n=>{e.style[n]=t[n]})}function Nt(t){return parseFloat(t)}function Vn(t){return Math.round(t*1e6)}function tu(t){return t/1e6}function Br(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),c=tu(Vn(s)-Vn(r)-Vn(i)),l=tu(Vn(n));if(c-l>2){let d=c-l;o.style.paddingRight=`${a+d}px`}}function $n(t,e={}){var d;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",Qe(o);let n=window.getComputedStyle(t),s=!0,r=()=>{o.scrollTop=t.scrollTop};Fr(n,o,Hr),Br(n,t,o),e.mirrorOverflow&&(o.style.overflow="hidden",t.addEventListener("scroll",r));let i=eu(t,()=>{Fr(n,o,Hr),Br(n,t,o),r(),setTimeout(r,0)}),a,c=!0,l=Dr(t,u=>{if(u===null){e.onRemove&&e.onRemove(),o.remove();return}if(!c&&e.onMoveStart&&(Promise.resolve().then(()=>e.onMoveStart()),c=!0),clearTimeout(a),a=setTimeout(()=>{e.onMoveEnd&&e.onMoveEnd(),c=!1},200),u.height===0&&u.width===0){if(s===!0)return;e.onHide&&e.onHide(),o.style.display="none",s=!0;return}if(Fr(n,o,Hr),Br(n,t,o),r(),o.style.top=`${u.top}px`,o.style.left=`${u.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let p=e.closestScrollElement.getBoundingClientRect(),m=window.getComputedStyle(e.closestScrollElement),g=Nt(m.borderTopWidth),f=Nt(m.borderBottomWidth),y=p.top+g-u.top,k=u.top+u.height+-(p.top+p.height-f);o.style.clipPath=`inset(${y}px 0px ${k}px 0px)`}s&&(o.style.display="block",e.onShow&&e.onShow(),s=!1)});return e.appendTo?e.appendTo.appendChild(o):(d=t.parentElement)==null||d.appendChild(o),l.observe(),i.observe(),[o,()=>{t.removeEventListener("scroll",r),l.unobserve(),i.unobserve()}]}var ou=(t,e)=>({value(){try{let o=sessionStorage.getItem(`dd-${t}`);if(!o)return e;try{return JSON.parse(o)}catch{return e}}catch{return e}},update(o){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(o))}catch{w.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function vS(t){return t.offsetParent!==null}function nu(t){if(!vS(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 Kr(t,e,o=100){let n=nu(t);e({isVisible:n});let s=setInterval(()=>{let r=nu(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}import{jsx as B}from"react/jsx-runtime";var su=ou("showTabHint",!0),Gn=class t{static version="11.2.1-beta.9";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:c}){let l=e.replace(/\/api$/,"");this.deepdeskApi=new Ke(l,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let d={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Vd({broadcast:(u,p,m)=>{this.broadcastEvents.send(u,p,m)},emit:(u,p,m)=>this.emit(u,p,m),handleAfterSendMessage:u=>this.handleAfterSendMessage(u),handleInputChanged:u=>this.handleInputChanged(u),handleKeyDown:u=>this.handleKeyDown(u),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:u=>this.logSendMessage(u),onUpdateShowTabHint:u=>su.update(u),sendEvent:(u,p)=>this.deepdeskApi.sendEvent(u,p)})]};o&&Object.assign(d,{deepdeskBrokerAPI:new fo(o)}),this.store=zd(d),this.broadcastEvents=new Ld({debug:!0,deepdeskUrl:l,eventMap:Ki(this.store),createCustomChannel:c}),this.store.dispatch(to(su.value())),this.store.dispatch(Co({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?(w.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(w.warn("Profile has not been loaded (yet)"),!0):(w.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(lt(null)),this.store.dispatch(Se()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();X(n)&&ni(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){w.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(is({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(To(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Eo({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(as(e))).payload}async postMessages(e){return(await this.store.dispatch(Ro(e))).payload}async updateConversation(e){return(await this.store.dispatch(ko(e))).payload}resetConversation(){this.store.dispatch(M()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(be());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(Co(e))}setVisitorInfo(e){this.store.dispatch(Ai(e))}async setAgentInfo(e){await this.store.dispatch(Kt(e))}async setAgentSettings(e){await this.store.dispatch(us(e))}async getAgentSettings(){return(await this.store.dispatch(ps())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(ln()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Ao(e))}notifyKeyDown(e){this.store.dispatch(Lo(e))}notifyPaste(e,o){this.store.dispatch(Ti({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Ci(e))}notifyExternalSuggestion(e){this.store.dispatch(me(e)),this.store.dispatch(xe())}async evaluateRule(e,o={}){let{payload:n,error:s}=await this.store.dispatch(et({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(De({collapse:!1})),this.inputMediator&&this.store.dispatch(yi({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(pe([])))}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,c=s!==-1;if(this.store.dispatch(wi(gi(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let l=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Si()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},d=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(bi()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Bt()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(e.key){case"Up":case"ArrowUp":i?d():l();return;case"Down":case"ArrowDown":{i?l():d();return}case"Esc":case"Escape":{i&&c&&this.store.dispatch(Me(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Me(-1)),this.store.dispatch(Bt()),e.preventDefault()):o||(this.store.dispatch(De({collapse:!0})),this.store.dispatch(Ll(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:u}=this.state.input,p=u.text.substring(0,u.selection.end),{tabCompletionSuggestion:m}=this.state.input;this.store.dispatch(to(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&m&&m.text.startsWith(p)&&(this.store.dispatch(me({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(Ei()),this.store.dispatch(pe([]))}handlingTimeStart(){this.state.handlingTime.startTime||(w.info("Start handling time"),this.store.dispatch(Nd()))}handlingTimeStop(){this.state.handlingTime.startTime&&(w.info("Stop handling time"),this.store.dispatch(Kn()))}logSendMessage(e){let o=Wd("input",this.state,{version:this.version});e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logHandlingTime(){let e=$d(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Od())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(xe()),this.store.dispatch(Ve(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(me({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){w.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),w.error(i)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=$n(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{Wn(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,c]=$n(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{Wn(s),c()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Qe(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(()=>{Wn(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),w.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(w.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Ri(n.metrics))):w.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch{}}mount(e,o={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!_r(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:c,showSuggestionsBeforePattern:l,showSuggestionsAfterPattern:d,isEmbedded:u,detectSubmit:p,insertLink:m,inputMediator:g,closestScrollSelector:f,appendOverlayTo:y,inlineSuggestions:k,floatingMenu:v}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:c,showSuggestionsBeforePattern:l,showSuggestionsAfterPattern:d,showTextSuggestions:i,insertLink:m,isEmbedded:u,inlineSuggestions:k,floatingMenu:!!v}),o.automaticHandlingTime&&this.setupHandlingTime(e),Qe(e),this.inputMediator=g||(He(e)?new Lt(e):new It(e)),this.inputMediator.on("change",({plainText:x})=>{this.notifyInputChanged(x)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(ki({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",x=>{this.notifyKeyDown(x)}),this.inputMediator.on("paste",({pastedText:x,selectionText:T})=>{this.notifyPaste(x,T)}),this.inputMediator.on("cut",({selectionText:x})=>{this.notifyCut(x)});let S=f&&Gd(e,f)||void 0;if(k){let{customStyles:x,appendOverlayTo:T}=o;if(He(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let N=this.createInlineContainer(e,"deepdesk-caret");Ot(B(Je,{store:this.store,customStyles:x,children:B(We,{broadcastEvents:this.broadcastEvents,children:B(Fl,{})})}),N),this.inputMediator.on("caret",F=>{this.store.dispatch(pe([])),F?(N.style.display="block",N.style.top=`${F.top}px`,N.style.left=`${F.left}px`):N.style.display="none"});let z=this.overlayContainerFactory("floating-menu",S||e,{appendTo:typeof v=="object"&&"appendOverlayTo"in v?v.appendOverlayTo:T},x==null?void 0:x.floatingMenuRootNode);Ot(B(Je,{store:this.store,customStyles:x,children:B(We,{broadcastEvents:this.broadcastEvents,children:B(Pl,{onLogIn:()=>this.loginViaPopup().catch(F=>w.warn(F.message))})})}),z)}else{let x=this.overlayContainerFactory("deepdesk-tab-completion",S||e,{appendTo:y,closestScrollElement:S,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),T=this.overlayContainerFactory("deepdesk-suggestions-overlay",S||e,{appendTo:y},n==null?void 0:n.suggestionsRootNode);Ot(B(Je,{store:this.store,customStyles:n,children:B(We,{broadcastEvents:this.broadcastEvents,children:B(Sc,{inputElement:e})})}),x),Ot(B(Je,{store:this.store,customStyles:n,children:B(We,{broadcastEvents:this.broadcastEvents,children:B(ql,{onLogIn:()=>this.loginViaPopup().catch(N=>w.warn(N.message))})})}),T)}Ot(B(Je,{store:this.store,customStyles:n,children:B(We,{broadcastEvents:this.broadcastEvents,children:B(Cl,{})})}),this.createContainer("deepdesk-overlays"));let R;this.inputMediator.on("selection",x=>{clearTimeout(R),x===null?R=setTimeout(()=>{x!==null&&this.store.dispatch(ls(x))},500):this.store.dispatch(ls(x))}),this.inputMediator.on("disabled",()=>{var x;(x=this.inputMediator)==null||x.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{p&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(tr(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(tr(!0))),this.store.dispatch(vi({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 x;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((x=this.state.conversation.current)==null?void 0:x.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(o=>o()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,o={}){if(this.widgetRoot&&w.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:n,showImages:s,isEmbedded:r}=o;this.widgetRoot=e,this.configure({showImages:s,isEmbedded:r}),Ot(B(Je,{store:this.store,customStyles:n,children:B(We,{broadcastEvents:this.broadcastEvents,children:B(Ed,{onLogIn:()=>this.loginViaPopup().catch(i=>w.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&Wn(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=Kr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){jd(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Yt());let e=we(this.state);e&&(await this.store.dispatch(Jt()),this.store.dispatch(Co({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 c=!1,l=()=>{d&&!d.closed&&d.close(),window.removeEventListener("message",u),clearInterval(p)};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),c=!0,s.port1.close(),o()}catch(y){console.error(y),n(y)}finally{c=!0,l()}};let d=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");d===null&&n(new Error("Popup blocked by browser"));let u=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"});d==null||d.postMessage(f,a.origin,[s.port2])}catch(f){w.error("Error posting message to popup",f),n(f)}break}case"deepdesk-popup-error":{l(),m.data.message==="Timeout"&&w.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(m.data.message));break}}};window.addEventListener("message",u);let p=setInterval(()=>{d&&!d.closed||(l(),c||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(w.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(o){let{message:n}=o;w.info(n),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let o=rn(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(ae()):["cues"].includes(n)||this.store.dispatch(ce(n))})}catch(n){this.handleError(n)}}};async function SS(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},c=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(c()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function xS(t,e,o={}){let n=o.replace?ot(t,o.replace.start,o.replace.end):mo(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}u&&i++}return c(t),a}var Rd=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(Rd||{}),Be=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(Rd).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 Pd(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var It=class extends Be{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),Fn(this.element,e)}getHTML(){return this.element.innerHTML||""}getRange(){var r;let e=this.getRootNode();if(e.activeElement!==this.element)return null;let o="getSelection"in e?e.getSelection():window.getSelection();if(!o)return null;let n="getComposedRanges"in o&&e instanceof ShadowRoot?(r=o.getComposedRanges(e))==null?void 0:r[0]:o.rangeCount>0?o.getRangeAt(0):null;if(!n)return null;let s=this.element.ownerDocument.createRange();return s.setStart(n==null?void 0:n.startContainer,n==null?void 0:n.startOffset),s.setEnd(n==null?void 0:n.endContainer,n==null?void 0:n.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let e=this.getRange();if(!e||!e.collapsed||!("getBoundingClientRect"in e))return null;let o=e.getBoundingClientRect();return!Pd(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!Pd(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return Hn(this.element,e);let o=this.lastKnownSelection;if(o&&kd(this.element,o.start,o.end))return o;let n=mo(this.element);return n.collapse(!1),Hn(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return Fn(this.element,ot(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 Lt=class extends Be{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 Id(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,c])=>{i.searchParams.append(a,c)}),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 eS(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}var Rr=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()}},Pr=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=Id(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()}},Ir=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(e){this.sessionId!==e&&(this.cleanup(),w.info("Set sessionId",e),this.sessionId=e,this.channel=this.createChannel(e))}createChannel(e){let o=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new Pr(e,this.deepdeskUrl,{debug:!0}):new Rr(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=eS(s.data);typeof r!="object"||r.type!=="event"||r.channel!==e||(w.info("Received broadcast event",this.sessionId,s),(a=(i=this.eventMap)[r.name])==null||a.call(i,r.payload))};return o.onMessage(n),o}send(e,o,n){var i,a;w.info("Broadcast event",{sessionId:this.sessionId,name:e,payload:o});let s={type:"event",name:e,payload:o};n!==!1&&((a=(i=this.eventMap)[e])==null||a.call(i,o));let r=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;r==null||r.postMessage({...s,channel:this.sessionId})}cleanup(e=!1){var o,n;(o=this.channel)==null||o.close(),delete this.channel,e&&((n=this.defaultChannel)==null||n.close(),delete this.defaultChannel)}},Ld=Ir;var At=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var Lr=t=>new Promise(e=>{setTimeout(e,t)});var Mt=class extends At{name="ClientError"},Mr=class extends At{name="ServerError"},Ar=new Map;function tS(t){return t.status===204||["0",null].includes(t.headers.get("content-length"))}var he=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,c=o.method===void 0||o.method.toLowerCase()==="get",{useCache:l=!1,abortLatest:d=!1,attempts:u=1,retryDelay:p=500,refreshTokenOn401:m=!0,retryOnError:g=T=>T instanceof TypeError,retryOnResponse:f=T=>T.status>=500,version:y="v1",...k}=o;if(l)if(c){if(Ar.has(i)){n(Ar.get(i));return}}else throw new Error(`Can't use 'useCache' for ${o.method}`);let v={credentials:"include",...k,headers:{"Content-Type":"application/json",...k.headers}};!c&&this.csrfToken&&(v.headers={...v.headers,"X-CSRFToken":this.csrfToken}),typeof y=="string"&&(v.headers={...v.headers,"X-Deepdesk-API-Version":y});let S=u,R=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&d&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let x=async()=>(S--,a(i,v).then(async T=>f(T)&&!r.isAborted&&S>0?(await Lr(p),x()):T.status===401&&m===!0&&R===!1?(R=!0,await this.refreshToken(),x()):T).catch(async T=>{if(g(T)&&!r.isAborted&&S>0)return await Lr(p),x();throw T}));x().then(async T=>{let N=await T.json().catch(z=>{if(tS(T))return null;throw z});if(delete this.latestRequestByUrl[i],T.status>=500){s(new Mr("Server Error",N));return}else if(T.status===401){s(new Mt("Unauthorized",N));return}else if(T.status===403){s(new Mt("Forbidden",N));return}else if(T.status===404){s(new Mt("Not Found",N));return}else if(T.status>=400){s(new Mt("Bad Request",N));return}l&&Ar.set(i,N),n(N)}).catch(T=>{s(T)})})}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 oS;(e=>{let t;(c=>(c.SEND_MESSAGE="Send Message",c.HANDLING_TIME="Handling Time",c.START_AUTOFLOW="Start Autoflow",c.ABORT_AUTOFLOW="Abort Autoflow",c.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",c.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||={})})(oS||={});function Bn(t){return{...L(t),tags:t.tags}}var Ke=class t{constructor(e,o={}){this.options=o;this.client=new he(e,{fetch:o.fetch}),this.client.patchFetch(n=>async(s,r)=>{let i=await n(s,r);return this.handleDeepdeskVersionHeaders(i),i})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=await this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(t.exchangeTokenPromise||(t.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),t.exchangeTokenPromise):Promise.resolve()}async createConversation(e){await this.preflight(),w.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...H(e),tags:e.tags},{version:"v2"});return Bn(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null,useCache:!0});return L(o)}async getKnowledgeAssistant(e){let o=await this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{version:null,useCache:!0});return L(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return L(e)}async getAccount(){let e=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return L(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null,useCache:!0});return L(e)}async checkUserExists(e){let{exists:o}=await this.client.get(`/apis/admin/users/exists?external_id=${e}`);return o}async getConversationBySessionId(e,o={}){await this.preflight(),w.info(`Getting conversation for session ${e}`);let{attempts:n=1,retryDelay:s=1e3}=o,r=await this.client.get(`/api/conversations/by_session_id/${e}`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"});return w.info(`Successfully retrieved conversation ${r.id} for session ${e}`),Bn(r)}async isConversationSupported(e,o={}){w.info(`Check if conversation for session ${e} is supported`);let{attempts:n=1,retryDelay:s=1e3}=o;return(await this.client.get(`/api/conversations/by_session_id/${e}/active_profile`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"})).has_active_profile}async updateConversation(e,o){let n=H(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return Bn(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=>Bn(s))}async sendEvent(e,o){let{data:n,...s}=o,r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((i,[a,c])=>({...i,[a]:c}),{});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 L(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 w.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=>({...L(r),text:r.text||r.url||r.message,source:n,type:n})).filter((r,i,a)=>i===a.findIndex(c=>c.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 L(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 L(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,H(e),{version:"v2"});return L(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 L(r)}async requestLoginByEmail(e){let o=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return L(o)}async requestPasswordlessToken(){let e=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return L(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 L(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 L(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 L(o)}async translateMessages(e){let o=await this.client.post("/api/translate",H(e),{version:"v2"});return L(o)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(ei);if(!o||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&o&&a!==o&&w.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(o)}`),this.latestReceivedDeepdeskVersions[i]=o})}};var go=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(cs(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,L(s))}catch{w.warn(`Invalid JSON for ${e}: ${n}`)}})}connect(){clearTimeout(this.timeoutTimer);let e=new EventSource(this.url,{withCredentials:!0});this.eventSource=e;let o=!1;e.onopen=()=>{o=!0},e.onerror=()=>{o&&e.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{e.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(n=>{this.proxyEvent(n)})}disconnect(){var e;clearTimeout(this.timeoutTimer),this.eventListeners={},(e=this.eventSource)==null||e.close()}emit(e,o){this.eventListeners[e]&&this.eventListeners[e].forEach(n=>n(o))}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),this.proxyEvent(e),()=>{this.off(e,o)}}off(e,o){let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}};var nS;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(nS||={});var fo=class{constructor(e,o={}){this.apiUrl=e;this.client=new he(e,o)}client;streams={};logger=w;async getCustomMessages(e){let o=await this.client.get(`/sessions/${e}/suggestions`);return L(o.suggestions)}async sendCustomMessage(e,o){let n=await this.client.post(`/sessions/${e}/messages`,H(o));return L(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 L(o.autoflows)}async startAutoflowSession(e){let o=await this.client.post("/autoflow-sessions",H(e));return L(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new go(`${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 dS,configureStore as uS}from"@reduxjs/toolkit";import{createSlice as sS}from"@reduxjs/toolkit";var Ad={startTime:null,stopTime:null},Md=sS({name:"handlingTime",initialState:Ad,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,()=>Ad)}}),{handlingTimeStart:Nd,handlingTimeStop:Kn,handlingTimeReset:Od}=Md.actions,_d=Md.reducer;var Dd=(t={})=>{let e={onAuthError:lt(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};import{createAsyncThunk as rS,createSlice as iS}from"@reduxjs/toolkit";var Un={list:{keywordMatches:[]},fetchState:"idle"};var nt=rS("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 Un.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),aS=iS({name:"styleSuggestions",initialState:Un,reducers:{},extraReducers:t=>{t.addCase(nt.pending,e=>{e.fetchState="loading"}).addCase(nt.rejected,e=>{e.fetchState="error"}).addCase(nt.fulfilled,(e,o)=>{e.fetchState="done",Le(e.list,o.payload)||(e.list=o.payload)}).addCase(Ve,e=>{e.list=Un.list}).addCase(M,()=>Un)}}),Hd=aS.reducer;var Fd=(t={})=>{let e,o=!0,n={getStyleSuggestions:nt,debounce:500,...t};return s=>r=>i=>{var m;let a=s.getState().input.text,c=r(i),l=s.getState();if(l.auth.isLoggedIn!==!0)return c;let{showStyleSuggestions:d}=l.settings;if(!((m=l.conversation.current)==null?void 0:m.id)||!d)return c;let{text:p}=l.input;return p===a&&!o||(clearTimeout(e),p==="")||(e=setTimeout(()=>{o=!1,s.dispatch(n.getStyleSuggestions({text:p}))},t.debounce)),c}};function lS(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var Bd=(t={})=>{let e={getTextSuggestions:ce,getAutocompleteSuggestions:eo,debounce:200,check:wt,...t},o;return n=>s=>r=>{var f;let{input:{userCommitted:i}}=n.getState(),a=s(r),c=n.getState();if(c.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:l,showTabCompletion:d}=c.settings,u=(f=c.conversation.current)==null?void 0:f.id,p=r.type===ln.toString();if(!u||!l&&!d)return a;let{input:{userCommitted:m}}=c;return lS(m,i)&&!p||(clearTimeout(o),!e.check(c))||(o=setTimeout(()=>{let y=mt(c);y===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(y))},p?0:e.debounce)),a}};var Kd=nt.fulfilled.toString();function cS(t,e){let o=new Set([...e.keywordMatches.map(s=>s.keyword)]),n=[];return o.forEach(s=>{let r=t.keywordMatches.filter(c=>c.keyword===s),i=e.keywordMatches.filter(c=>c.keyword===s),a=i.length-r.length;a<=0||n.push(...i.slice(0,a))}),n}var Ud=t=>e=>o=>n=>{var l;if(n.type!==Kd){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 c=cS(s,i);n.type===Kd&&c.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:c}})};var pS=dS({answer:tl,auth:ci,autoflows:Ec,conversation:mi,contentTypes:aa,customMessages:Oc,passwordlessToken:Bc,entities:Na,knowledgeAssistant:Ja,handlingTime:_d,info:Mi,input:Pi,settings:oi,profile:al,search:Bi,summary:Ua,styleSuggestions:Hd,ui:Ml,rules:Vc,textSuggestions:hl});function zd(t){return uS({reducer:pS,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),Dd(),Bd({debounce:200}),Fd({debounce:500}),Ud(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var mS=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},gS=t=>e=>o=>n=>{var a;let s=e.getState(),r=ns("inlineSuggestions")(s);switch(n.type){case lt.toString():{!n.payload&&t.emit("logout",void 0);break}case ae.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:n.payload}});break;case W.toString():t.sendEvent(n.payload.name,{conversationId:((a=n.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:n.payload.data});break;case Lo.toString():t.handleKeyDown(n.payload);break;case Ve.toString():t.logSendMessage(n.payload);break;case Ao.toString():t.handleInputChanged(n.payload);break;case et.fulfilled.toString():n.isBroadcasted||t.broadcast(ms,n,!1),t.emit("cues",n.payload);break;default:break}let i=o(n);switch(n.type){case Ve.toString():t.handleAfterSendMessage(n.payload);break;case to.toString():t.onUpdateShowTabHint(n.payload);break;case Kn.toString():t.logHandlingTime();break;case"analytics/logEvent/fulfilled":{t.emit("event",n.meta.arg);break}case me.toString():{let{start:c,end:l}=s.input.selection;t.emit("select-suggestion",{type:mS(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:c,end:l}:{start:0,end:l}},{mayApplyChanges:!0}),r&&(e.dispatch(pe([])),e.dispatch(xe()));break}case Io.toString():{let{start:c,end:l}=s.input.selection;t.emit("replace",{...n.payload,replace:n.payload.replace==="selection"?{start:c,end:l}:{start:0,end:l}},{mayApplyChanges:!0});break}case Bt.toString():{let c=e.getState(),{text:l,selection:d}=c.input.userCommitted;t.emit("reset",{text:l,selectionAfter:d},{mayApplyChanges:!0});break}case Mo.toString():t.emit("select-image",n.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:s.conversation.current.id,data:{path:n.payload.suggestion.image,title:n.payload.suggestion.title}});break;case pe.toString():{r&&n.payload.length>0&&e.dispatch(Me(0));break}case be.fulfilled.toString():{t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{summary:n.payload.summary,model:e.getState().summary.model}});break}default:break}return i},Vd=gS;function Nr(t){return t.toISOString().replace("T"," ").replace("Z","")}function $d(t,e){var s,r,i;let{startTime:o,stopTime:n}=t.handlingTime;if(!o||!n)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:t.conversation.current.id,clientVersion:e.version,agentId:(s=t.info.agentInfo)==null?void 0:s.agentId,agentName:(r=t.info.agentInfo)==null?void 0:r.agentName,agentEmail:(i=t.info.agentInfo)==null?void 0:i.agentEmail,timeStart:Nr(o),timeStop:Nr(n)}}function Wd(t,e,o){var N,z,F;let{text:n,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:c,agentStartedTypingTimestamp:l,externalTimeTotalSeconds:d,pastes:u,cuts:p,deletions:m,textSuggestions:g,offeredTextSuggestions:f}}=e[t],y=n.length,v=g.reduce((I,{text:O,searchTerm:V})=>I+O.length-(V?V.length:0),0),S=l??Date.now(),R=(Date.now()-S)/1e3+(d||0),x=s/R,T=g.reduce((I,{searchTerm:O})=>I+(O?O.length:0),0);return{conversationId:e.conversation.current.id,source:"agent",text:n,clientVersion:o.version,pastes:u,cuts:p,deletions:m,lenTextTyped:s+T,lenTextTotal:y,lenTextAssisted:v,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:R,charsPerSecond:x,numPastes:c,textSuggestionsV2:g,suggestionsCounters:[{source:"gpt",countOffered:f.filter(I=>I.source==="gpt").length}],agentId:(N=e.info.agentInfo)==null?void 0:N.agentId,agentName:(z=e.info.agentInfo)==null?void 0:z.agentName,agentEmail:(F=e.info.agentInfo)==null?void 0:F.agentEmail}}function Or(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return Or(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?Or(s,e):null}function Gd(t,e){return Or(t,e)}function jd(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function fS(t){return typeof t=="object"&&t!==null&&"tagName"in t}function _r(t){return fS(t)&&(He(t)||vn(t))}var qd,ye=new Map,hS=["bottom","height","left","right","top","width"],yS=(t={},e={})=>hS.some(o=>t[o]!==e[o]);function Xd(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,...Xd(e)]:[]}function Zd(t,e){return!t||!e?null:{...t,top:t.top+e.top,left:t.left+e.left}}var zn=!1,Qd=()=>{zn=!0;let t=[];if(ye.forEach((e,o)=>{if(!o.isConnected){e.rect=null,t.push(e),ye.delete(o);return}let n=o.getBoundingClientRect();yS(n,e.rect)&&(e.rect=n,t.push(e))}),t.forEach(e=>{let o=e.parentRects?e.parentRects.reduce(Zd,e.rect):e.rect;e.callbacks.forEach(n=>n(o))}),ye.size===0){zn=!1;return}qd=window.requestAnimationFrame(Qd)};function Dr(t,e){let o=Xd(t),n=[],s=o.map((r,i)=>Dr(r,a=>{n[i]=a;let c=ye.get(t);if(!c)return;let l=n.reduce(Zd,c.rect);c.callbacks.forEach(d=>d(l))}));return{observe(r=!0){if(s.forEach(i=>i.observe(!1)),ye.has(t)){let i=ye.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else ye.set(t,{rect:void 0,callbacks:[e],parentRects:n});r&&!zn&&Qd()},unobserve(){s.forEach(i=>i.unobserve());let r=ye.get(t);if(r){let i=r.callbacks.indexOf(e);i>=0&&r.callbacks.splice(i,1),r.callbacks.length||ye.delete(t),ye.size||(cancelAnimationFrame(qd),zn=!1)}}}}var Jd,ve=new Map,Yd=()=>{ve.forEach((t,e)=>{if(!e.isConnected){ve.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)))}),ve.size!==0&&(Jd=window.requestAnimationFrame(Yd))};function eu(t,e){return{observe(){let o=ve.size===0;ve.has(t)?ve.get(t).callbacks.push(e):ve.set(t,{visible:void 0,callbacks:[e]}),o&&Yd()},unobserve(){let o=ve.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||ve.delete(t),ve.size||cancelAnimationFrame(Jd)}}}}var Hr=["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 Fr(t,e,o){return o.forEach(n=>{e.style[n]=t[n]})}function Nt(t){return parseFloat(t)}function Vn(t){return Math.round(t*1e6)}function tu(t){return t/1e6}function Br(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),c=tu(Vn(s)-Vn(r)-Vn(i)),l=tu(Vn(n));if(c-l>2){let d=c-l;o.style.paddingRight=`${a+d}px`}}function $n(t,e={}){var d;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",Qe(o);let n=window.getComputedStyle(t),s=!0,r=()=>{o.scrollTop=t.scrollTop};Fr(n,o,Hr),Br(n,t,o),e.mirrorOverflow&&(o.style.overflow="hidden",t.addEventListener("scroll",r));let i=eu(t,()=>{Fr(n,o,Hr),Br(n,t,o),r(),setTimeout(r,0)}),a,c=!0,l=Dr(t,u=>{if(u===null){e.onRemove&&e.onRemove(),o.remove();return}if(!c&&e.onMoveStart&&(Promise.resolve().then(()=>e.onMoveStart()),c=!0),clearTimeout(a),a=setTimeout(()=>{e.onMoveEnd&&e.onMoveEnd(),c=!1},200),u.height===0&&u.width===0){if(s===!0)return;e.onHide&&e.onHide(),o.style.display="none",s=!0;return}if(Fr(n,o,Hr),Br(n,t,o),r(),o.style.top=`${u.top}px`,o.style.left=`${u.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let p=e.closestScrollElement.getBoundingClientRect(),m=window.getComputedStyle(e.closestScrollElement),g=Nt(m.borderTopWidth),f=Nt(m.borderBottomWidth),y=p.top+g-u.top,k=u.top+u.height+-(p.top+p.height-f);o.style.clipPath=`inset(${y}px 0px ${k}px 0px)`}s&&(o.style.display="block",e.onShow&&e.onShow(),s=!1)});return e.appendTo?e.appendTo.appendChild(o):(d=t.parentElement)==null||d.appendChild(o),l.observe(),i.observe(),[o,()=>{t.removeEventListener("scroll",r),l.unobserve(),i.unobserve()}]}var ou=(t,e)=>({value(){try{let o=sessionStorage.getItem(`dd-${t}`);if(!o)return e;try{return JSON.parse(o)}catch{return e}}catch{return e}},update(o){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(o))}catch{w.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function vS(t){return t.offsetParent!==null}function nu(t){if(!vS(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 Kr(t,e,o=100){let n=nu(t);e({isVisible:n});let s=setInterval(()=>{let r=nu(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}import{jsx as B}from"react/jsx-runtime";var su=ou("showTabHint",!0),Gn=class t{static version="11.3.0";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:c}){let l=e.replace(/\/api$/,"");this.deepdeskApi=new Ke(l,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let d={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Vd({broadcast:(u,p,m)=>{this.broadcastEvents.send(u,p,m)},emit:(u,p,m)=>this.emit(u,p,m),handleAfterSendMessage:u=>this.handleAfterSendMessage(u),handleInputChanged:u=>this.handleInputChanged(u),handleKeyDown:u=>this.handleKeyDown(u),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:u=>this.logSendMessage(u),onUpdateShowTabHint:u=>su.update(u),sendEvent:(u,p)=>this.deepdeskApi.sendEvent(u,p)})]};o&&Object.assign(d,{deepdeskBrokerAPI:new fo(o)}),this.store=zd(d),this.broadcastEvents=new Ld({debug:!0,deepdeskUrl:l,eventMap:Ki(this.store),createCustomChannel:c}),this.store.dispatch(to(su.value())),this.store.dispatch(Co({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?(w.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(w.warn("Profile has not been loaded (yet)"),!0):(w.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(lt(null)),this.store.dispatch(Se()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();X(n)&&ni(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){w.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(is({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(To(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Eo({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(as(e))).payload}async postMessages(e){return(await this.store.dispatch(Ro(e))).payload}async updateConversation(e){return(await this.store.dispatch(ko(e))).payload}resetConversation(){this.store.dispatch(M()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(be());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(Co(e))}setVisitorInfo(e){this.store.dispatch(Ai(e))}async setAgentInfo(e){await this.store.dispatch(Kt(e))}async setAgentSettings(e){await this.store.dispatch(us(e))}async getAgentSettings(){return(await this.store.dispatch(ps())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(ln()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Ao(e))}notifyKeyDown(e){this.store.dispatch(Lo(e))}notifyPaste(e,o){this.store.dispatch(Ti({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Ci(e))}notifyExternalSuggestion(e){this.store.dispatch(me(e)),this.store.dispatch(xe())}async evaluateRule(e,o={}){let{payload:n,error:s}=await this.store.dispatch(et({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(De({collapse:!1})),this.inputMediator&&this.store.dispatch(yi({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(pe([])))}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,c=s!==-1;if(this.store.dispatch(wi(gi(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let l=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Si()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},d=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(bi()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Bt()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(e.key){case"Up":case"ArrowUp":i?d():l();return;case"Down":case"ArrowDown":{i?l():d();return}case"Esc":case"Escape":{i&&c&&this.store.dispatch(Me(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Me(-1)),this.store.dispatch(Bt()),e.preventDefault()):o||(this.store.dispatch(De({collapse:!0})),this.store.dispatch(Ll(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:u}=this.state.input,p=u.text.substring(0,u.selection.end),{tabCompletionSuggestion:m}=this.state.input;this.store.dispatch(to(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&m&&m.text.startsWith(p)&&(this.store.dispatch(me({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(Ei()),this.store.dispatch(pe([]))}handlingTimeStart(){this.state.handlingTime.startTime||(w.info("Start handling time"),this.store.dispatch(Nd()))}handlingTimeStop(){this.state.handlingTime.startTime&&(w.info("Stop handling time"),this.store.dispatch(Kn()))}logSendMessage(e){let o=Wd("input",this.state,{version:this.version});e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logHandlingTime(){let e=$d(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Od())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(xe()),this.store.dispatch(Ve(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(me({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){w.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),w.error(i)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=$n(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{Wn(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,c]=$n(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{Wn(s),c()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Qe(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(()=>{Wn(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),w.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(w.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Ri(n.metrics))):w.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch{}}mount(e,o={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!_r(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:c,showSuggestionsBeforePattern:l,showSuggestionsAfterPattern:d,isEmbedded:u,detectSubmit:p,insertLink:m,inputMediator:g,closestScrollSelector:f,appendOverlayTo:y,inlineSuggestions:k,floatingMenu:v}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:c,showSuggestionsBeforePattern:l,showSuggestionsAfterPattern:d,showTextSuggestions:i,insertLink:m,isEmbedded:u,inlineSuggestions:k,floatingMenu:!!v}),o.automaticHandlingTime&&this.setupHandlingTime(e),Qe(e),this.inputMediator=g||(He(e)?new Lt(e):new It(e)),this.inputMediator.on("change",({plainText:x})=>{this.notifyInputChanged(x)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(ki({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",x=>{this.notifyKeyDown(x)}),this.inputMediator.on("paste",({pastedText:x,selectionText:T})=>{this.notifyPaste(x,T)}),this.inputMediator.on("cut",({selectionText:x})=>{this.notifyCut(x)});let S=f&&Gd(e,f)||void 0;if(k){let{customStyles:x,appendOverlayTo:T}=o;if(He(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let N=this.createInlineContainer(e,"deepdesk-caret");Ot(B(Je,{store:this.store,customStyles:x,children:B(We,{broadcastEvents:this.broadcastEvents,children:B(Fl,{})})}),N),this.inputMediator.on("caret",F=>{this.store.dispatch(pe([])),F?(N.style.display="block",N.style.top=`${F.top}px`,N.style.left=`${F.left}px`):N.style.display="none"});let z=this.overlayContainerFactory("floating-menu",S||e,{appendTo:typeof v=="object"&&"appendOverlayTo"in v?v.appendOverlayTo:T},x==null?void 0:x.floatingMenuRootNode);Ot(B(Je,{store:this.store,customStyles:x,children:B(We,{broadcastEvents:this.broadcastEvents,children:B(Pl,{onLogIn:()=>this.loginViaPopup().catch(F=>w.warn(F.message))})})}),z)}else{let x=this.overlayContainerFactory("deepdesk-tab-completion",S||e,{appendTo:y,closestScrollElement:S,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),T=this.overlayContainerFactory("deepdesk-suggestions-overlay",S||e,{appendTo:y},n==null?void 0:n.suggestionsRootNode);Ot(B(Je,{store:this.store,customStyles:n,children:B(We,{broadcastEvents:this.broadcastEvents,children:B(Sc,{inputElement:e})})}),x),Ot(B(Je,{store:this.store,customStyles:n,children:B(We,{broadcastEvents:this.broadcastEvents,children:B(ql,{onLogIn:()=>this.loginViaPopup().catch(N=>w.warn(N.message))})})}),T)}Ot(B(Je,{store:this.store,customStyles:n,children:B(We,{broadcastEvents:this.broadcastEvents,children:B(Cl,{})})}),this.createContainer("deepdesk-overlays"));let R;this.inputMediator.on("selection",x=>{clearTimeout(R),x===null?R=setTimeout(()=>{x!==null&&this.store.dispatch(ls(x))},500):this.store.dispatch(ls(x))}),this.inputMediator.on("disabled",()=>{var x;(x=this.inputMediator)==null||x.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{p&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(tr(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(tr(!0))),this.store.dispatch(vi({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 x;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((x=this.state.conversation.current)==null?void 0:x.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(o=>o()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,o={}){if(this.widgetRoot&&w.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:n,showImages:s,isEmbedded:r}=o;this.widgetRoot=e,this.configure({showImages:s,isEmbedded:r}),Ot(B(Je,{store:this.store,customStyles:n,children:B(We,{broadcastEvents:this.broadcastEvents,children:B(Ed,{onLogIn:()=>this.loginViaPopup().catch(i=>w.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&Wn(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=Kr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){jd(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Yt());let e=we(this.state);e&&(await this.store.dispatch(Jt()),this.store.dispatch(Co({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 c=!1,l=()=>{d&&!d.closed&&d.close(),window.removeEventListener("message",u),clearInterval(p)};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),c=!0,s.port1.close(),o()}catch(y){console.error(y),n(y)}finally{c=!0,l()}};let d=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");d===null&&n(new Error("Popup blocked by browser"));let u=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"});d==null||d.postMessage(f,a.origin,[s.port2])}catch(f){w.error("Error posting message to popup",f),n(f)}break}case"deepdesk-popup-error":{l(),m.data.message==="Timeout"&&w.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(m.data.message));break}}};window.addEventListener("message",u);let p=setInterval(()=>{d&&!d.closed||(l(),c||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(w.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(o){let{message:n}=o;w.info(n),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let o=rn(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(ae()):["cues"].includes(n)||this.store.dispatch(ce(n))})}catch(n){this.handleError(n)}}};async function SS(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},c=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(c()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function xS(t,e,o={}){let n=o.replace?ot(t,o.replace.start,o.replace.end):mo(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?ot(t,o.selectionAfter.start,o.selectionAfter.end):(n.collapse(!1),n),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(i)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}function bS(t){let e=document.createElement("template");return e.innerHTML=t.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),e.content}function CS(t){let e=document.createDocumentFragment();return t.split(`
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 ru(t,e){return!t.contains(e)||e===t?null:e.parentNode===t?e:ru(t,e.parentNode)}async function wS(t,e,{isBlock:o,isHTML:n}={}){let s;t.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0}));let r=()=>{let i=t.ownerDocument.defaultView??window,a=i.getSelection();if((!a||a.rangeCount===0)&&(t.focus(),a=i.getSelection()),!a||a.rangeCount===0)return;let c=a.getRangeAt(0);if(!c)return;s=document.createElement("span"),c.insertNode(s);let l=n?bS(e):CS(e);if(o){let d=c.startContainer===t?t.childNodes[c.startOffset]:c.startContainer,u=ru(t,d)??t.firstChild;t.insertBefore(l,(u==null?void 0:u.nextSibling)??null)}else c.insertNode(l),c.collapse(!1)};return Promise.resolve(r()).then(()=>{if(t.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0})),t.focus(),!!s)try{s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}function TS(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function ES(t,e,o){await new Ke(t).authenticateWithKey(e,o)}async function kS(t){let o=await new he(t).get("/platform/config/",{version:null,useCache:!0});return L(o)}async function RS(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 PS(t,e){let o=await RS(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,Ke as DeepdeskAPI,Gn as DeepdeskSDK,he as HTTPClient,Be as InputMediator,at as InputType,Zn as KeyboardHint,Qn as Label,bo as Locale,Pe as Section,Yn as SectionList,Ie as Sources,A as Suggestion,te as SuggestionList,Lt as TextAreaInput,it as ToggleButton,PS as attachFile,ES as authenticateWithKey,mo as createFullRange,$n as createOverlayContainer,ot as createRangeFromOffsets,Zt as escapeHTML,kS as fetchPlatformConfig,TS as formatTextMarkup,Hn as getRangeOffsets,Fn as getRangeText,wS as insertCKEditor,Ls as isHTML,_r as isSupportedInputElement,xS as updateContentEditable,SS as updateTextArea,h as useStyles,Kr as waitForElementVisibilityChange};