@deepdesk/deepdesk-sdk 11.2.1-beta.1 → 11.2.1-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.d.mts +36 -24
- package/dist/index.d.ts +36 -24
- package/dist/index.esm.js +1 -1
- package/dist/index.iife.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -7,6 +7,6 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
|
7
7
|
c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});var jr=require("react/jsx-runtime"),Gm={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},Rc=({className:t,color:e})=>(0,jr.jsx)("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,jr.jsx)("path",{d:"M172.03 0.0199966H0V86.03C47.5 86.03 86 124.54 86 172.04C86 124.54 124.51 86.03 172.01 86.03C219.51 86.03 258.03 124.54 258.03 172.04C258.03 219.54 219.52 258.05 172.01 258.05C124.5 258.05 86 219.54 86 172.04C86 219.54 47.5 258.05 0 258.05V344.06H172.03C267.04 344.06 344.06 267.04 344.06 172.03C344.06 77.02 267.04 0 172.03 0V0.0199966Z",fill:Gm[e||"pink"]})});var Pc={root:"j",text:"Y",isLoggedIn:"ei",isLoggedOut:"no",icon:"ii",logo:"ri",lock:"ti"};var Wr={};Y(Wr,{enUS:()=>Wm,nlNL:()=>Xm});var Wm={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},Xm={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Ac=require("react-redux"),Bt=require("react/jsx-runtime"),Mc=({onLogIn:t})=>{let e=P(Wr),o=b("floatingMenu"),n=b("productName"),s=(0,Ac.useDispatch)(),r=(0,Lc.useSelector)(te),i=h("FloatingMenu",Pc);if(r===null||o===!1)return null;let a=()=>{r===!0?s(ce(!0)):t()};return(0,Bt.jsxs)("button",{className:(0,Ic.default)(i.root,{[i.isLoggedIn]:r,[i.isLoggedOut]:!r}),onClick:a,children:[(0,Bt.jsx)("div",{className:i.text,children:e(r?"search":"signin",{productName:n})}),(0,Bt.jsxs)("div",{className:i.icon,children:[(0,Bt.jsx)(Rc,{className:i.logo,color:"pink"}),r===!1&&(0,Bt.jsx)(kc,{className:i.lock})]})]})};var Rs=require("react"),We=require("react-redux");var Nc=require("react");function po(t){(0,Nc.useEffect)(()=>{let e=o=>{o.isWithinRoot||t(o)};return document.body.addEventListener("mouseup",e),()=>{document.body.removeEventListener("mouseup",e)}},[t])}function Kt(t){t.addEventListener("mouseup",e=>{e.isWithinRoot=!0},!0)}function go(t){let{showMidSentenceSuggestions:e,showSuggestionsBeforePattern:o,showSuggestionsAfterPattern:n}=t.settings,{text:s,selection:r}=t.input.userCommitted;return r.start!==r.end?!1:r.end>=s.length?!0:e?o&&new RegExp(o).test(s.substring(r.end))||n&&new RegExp(n).test(s.substring(0,r.end))?!0:o===!1&&n===!1:!1}var Oc=require("@reduxjs/toolkit"),Zm={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var ws=({ui:t})=>t.overlayCollapsed;var _c=(0,Oc.createSlice)({name:"ui",initialState:Zm,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:Yo,setInputHasFocus:Xr,setOverlayCollapsed:pt,setOpenOverlayWhenTyping:Dc,setOverlayCollapsedUserOverwrite:Hc}=_c.actions,Fc=_c.reducer;var Es=require("react");var zc=require("interweave"),mo=require("react"),Ts=require("react-redux");var Bc=require("react");function Kc(t,e,o){(0,Bc.useEffect)(()=>{let n=t.current;return n?(n.addEventListener(e,o),()=>{n.removeEventListener(e,o)}):()=>{}},[t,e,o])}var Uc={root:"ni",actions:"ai",badge:"pi",formattedText:"ao"};var Ut=require("react/jsx-runtime"),Ym=["search","personal-collection-search","search-autocomplete"];function ef(t,e,o,n={}){let s="";return Ym.includes(e)?s=kl(_r(t,o,{stripAgentPart:!0}),n.searchKeywords??[o]):s=_r(t,o,n),n.placeholders===!0&&(s=Rl(s)),s}var tf=()=>{},of=({index:t,selected:e,suggestion:o,onFeedback:n})=>{let s=b("inlineSuggestions"),r=(0,Ts.useSelector)(eo),i=(0,Ts.useDispatch)(),a=h("TextSuggestion",Uc),c=(0,mo.useRef)(null);(0,mo.useEffect)(()=>{let d=setTimeout(()=>{i(Oa({text:o.text,suggestion:o}))},500);return()=>{clearTimeout(d)}},[o]),Kc(c,"click",()=>{i(it(t)),i(Ne({suggestion:o,text:o.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let l=(0,mo.useMemo)(()=>ef(o.text,o.source,r,{stripAgentPart:s,placeholders:!0,searchKeywords:o.searchKeywords}),[s,o.text,o.source,r,o.searchKeywords]);return o.source==="gpt"&&!s?null:(0,Ut.jsxs)("div",{className:a.root,onMouseEnter:()=>i(it(t)),children:[(0,Ut.jsx)(N,{ref:c,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:tf,children:(0,Ut.jsx)(zc.Interweave,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:l})}),e&&n&&(0,Ut.jsx)("div",{className:a.actions,children:(0,Ut.jsx)(ds,{onFeedback:()=>n(o),suggestion:o.text})})]})},Vc=of;var Zr=require("react/jsx-runtime"),nf=({onFeedback:t,suggestions:e,selectedIndex:o,reverse:n})=>{let s=(0,Es.useMemo)(()=>{let r=e.map((i,a)=>(0,Zr.jsx)(Vc,{index:a,selected:a===o,suggestion:i,onFeedback:t},`${i.text}-${i.source}`));return n?r.reverse():r},[e,o,n]);return(0,Zr.jsx)(Es.Fragment,{children:s})},ks=nf;var $c={root:"di",paper:"li"};var en=require("react/jsx-runtime"),rf=({textSuggestions:t,selectedIndex:e})=>{let o=(0,Rs.useRef)(null),n=h("InlineSuggestionsOverlay",$c),s=(0,We.useSelector)(go),r=(0,We.useDispatch)(),i=(0,We.useSelector)(te),a=(0,We.useSelector)(Yt),c=(0,We.useSelector)(ws),l=b("showTextSuggestions");return po(()=>{setTimeout(()=>{r(pt({collapse:!0,skipWhenInputFocus:!0}))})}),(0,Rs.useEffect)(()=>{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:(0,en.jsx)("div",{className:n.root,"data-variant":"inline",children:(0,en.jsx)("div",{ref:o,className:n.paper,children:(0,en.jsx)(le,{children:(0,en.jsx)(ks,{suggestions:t,selectedIndex:e})})})})},af=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),qc=(0,We.connect)(af)(rf);var Gc=require("react-redux");var tn=require("react/jsx-runtime"),lf=({children:t})=>{let o=b("locale").replace("-","");return(0,tn.jsx)(Lr.Provider,{value:o,children:t})},cf=({store:t,customStyles:e={},children:o})=>(0,tn.jsx)(Gc.Provider,{store:t,children:(0,tn.jsx)(lf,{children:(0,tn.jsx)(Ro.Provider,{value:e,children:o})})}),zt=cf;var Is=k(require("classnames")),fo=require("react"),_e=require("react-redux");var jc=require("react");function Wc(t,e){let[o,n]=(0,jc.useState)(()=>{if(typeof window>"u")return e;try{let r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return w.error(r),e}});return[o,r=>{try{let i=r instanceof Function?r(o):r;n(i),typeof window<"u"&&window.localStorage.setItem(t,JSON.stringify(i))}catch(i){w.error(i)}}]}var Xc=()=>/Mac/i.test(navigator.platform);var Qc=k(require("classnames")),Xe=require("react");var Qr={};Y(Qr,{enUS:()=>df,nlNL:()=>uf});var df={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"}]}]},uf={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 Zc={root:"si",anchor:"ci",anchorButton:"xi"};var gt=require("react/jsx-runtime"),Jr=(t,e,o)=>n=>(0,gt.jsx)("button",{className:t.anchorButton,type:"button",value:e,onClick:o,children:n},e),gf=({className:t,loginUrl:e,isEmbedded:o,onSnooze:n,onLogIn:s})=>{let r=P(Qr),i=he(),a=h("Login",Zc),c=b("productName"),l=(0,Xe.useCallback)(y=>{y.preventDefault(),n&&n(parseInt(y.target.value,10))},[]),d=(0,Xe.useCallback)(y=>{y.preventDefault(),i.send(oo,!0)},[e]),u=(0,Xe.useMemo)(()=>y=>(0,gt.jsx)("a",{onClick:S=>{S.preventDefault(),s()},href:e,className:a.anchor,target:"_blank",rel:"noreferrer",children:y},"login"),[e]),p=(0,Xe.useCallback)(y=>(0,gt.jsx)("button",{type:"button",className:a.anchorButton,onClick:d,children:y},"prompt"),[d]),{min:g,hour:f,day:m}=(0,Xe.useMemo)(()=>({min:Jr(a,60*10,l),hour:Jr(a,60*60,l),day:Jr(a,60*60*12,l)}),[]);return(0,gt.jsxs)("div",{className:(0,Qc.default)(t,a.root),children:[r("loginPlease",{login:o?p:u,productName:c}),n&&(0,gt.jsxs)(Xe.Fragment,{children:[(0,gt.jsx)("br",{}),r("snooze",{min:g,hour:f,day:m})]})]})},Ps=gf;var Yc=require("react-redux");var Jc={root:"po",text:"fi"};var on=require("react/jsx-runtime"),ff=({title:t})=>{let e=h("SearchTrigger",Jc),o=(0,Yc.useDispatch)();return(0,on.jsxs)("button",{type:"button",className:e.root,onClick:()=>o(ce(!0)),children:[(0,on.jsx)(so,{}),(0,on.jsx)("span",{className:e.text,children:t})]})},ed=ff;var Yr={};Y(Yr,{enUS:()=>hf,nlNL:()=>yf});var hf={arrowHint:[{type:0,value:"Tip: use arrow keys to navigate suggestions"}],searchHintWindows:[{type:0,value:"Press CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],searchHintMac:[{type:0,value:"Press CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Close"}],search:[{type:0,value:"Search"}]},yf={arrowHint:[{type:0,value:"Tip: Selecteer suggesties met pijltoetsen"}],searchHintWindows:[{type:0,value:"Druk CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],searchHintMac:[{type:0,value:"Druk CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Sluiten"}],search:[{type:0,value:"Zoeken"}]};var td={root:"gi",isInline:"q",toggleButton:"bi",toggleButtonWrapper:"C",toggleButtonWrapperHidden:"hi",isCollapsed:"do",collapsible:"mi",hints:"lo",hintsHidden:"ui",triggers:"so",triggersRight:"yi"};var B=require("react/jsx-runtime"),Sf=({textSuggestions:t,selectedIndex:e,onLogIn:o})=>{let n=h("SuggestionsOverlay",td),s=P(Yr),r=(0,_e.useSelector)(go),i=La(),a=(0,_e.useDispatch)(),c=(0,fo.useRef)(null),l=b("searchTriggerKey"),d=b("productName"),u=(0,_e.useSelector)(ws),p=(0,_e.useSelector)(te),g=(0,_e.useSelector)(Yt),[f,m]=(0,fo.useState)(null),y=b("showSearch"),E=b("showTextSuggestions"),S=b("adminUrl"),v=b("isEmbedded"),[R,x]=Wc("dd-snooze-until-ms",0),T=u||R>Date.now(),O=(0,_e.useSelector)(I=>I.input.text),q=t.filter(I=>I.source!=="gpt").length,K=()=>{T&&x(0),a(Hc(!T))},A=I=>{a(Q({name:"suggestion feedback",data:{text:I.text,source:"overlay",context:O},options:{includeConversationData:!0}}))},_=I=>{let X=Date.now()+I*1e3;x(X),w.info(`Snooze until: ${new Date(X)}`),a(pt({collapse:!0}))};return(0,fo.useEffect)(()=>{q===0&&m(null)},[t,q]),po(()=>{a(pt({collapse:!0,skipWhenInputFocus:!0}))}),p===null||g===!1?null:p===!1?(0,B.jsxs)("div",{ref:c,className:(0,Is.default)(n.root,{[n.isCollapsed]:T}),children:[!T&&(0,B.jsxs)("div",{className:n.triggers,children:[(0,B.jsx)("div",{style:{flex:1}}),(0,B.jsx)("div",{className:n.triggersRight,children:(0,B.jsx)(Et,{className:n.toggleButton,title:s("collapse"),onClick:K,isCollapsed:!1})})]}),(0,B.jsx)("div",{className:n.toggleButtonWrapper,children:(0,B.jsx)(Et,{className:n.toggleButton,title:s("open",{productName:d}),onClick:K,isCollapsed:!0})}),(0,B.jsx)("div",{className:n.collapsible,children:(0,B.jsx)(Ps,{loginUrl:S,isEmbedded:v,onLogIn:o,onSnooze:_})})]}):!i||!r?null:(0,B.jsxs)("div",{ref:c,className:(0,Is.default)(n.root,{[n.isCollapsed]:T}),children:[!T&&(0,B.jsxs)("div",{className:n.triggers,children:[(0,B.jsx)("div",{style:{flex:1},children:y&&(0,B.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>m(s(Xc()?"searchHintMac":"searchHintWindows",{searchTriggerKey:l.toUpperCase()})),onMouseLeave:()=>m(null),children:(0,B.jsx)(ed,{title:s("search")})})}),(0,B.jsxs)("div",{className:n.triggersRight,onFocus:()=>{},children:[(0,B.jsx)("div",{className:(0,Is.default)(!f&&n.hintsHidden,n.hints),children:f}),(0,B.jsx)(Et,{className:n.toggleButton,title:s("collapse"),onClick:K,isCollapsed:!1})]})]}),(0,B.jsx)("div",{className:n.toggleButtonWrapper,children:(0,B.jsx)(Et,{className:n.toggleButton,title:s("open",{productName:d}),onClick:K,isCollapsed:!0})}),q>0&&E&&(0,B.jsx)("div",{className:n.collapsible,onFocus:()=>{},children:(0,B.jsx)(le,{children:(0,B.jsx)(ks,{onFeedback:A,suggestions:t,selectedIndex:e,reverse:!0})})})]})},xf=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),od=(0,_e.connect)(xf)(Sf);var $s=k(require("classnames")),kd=require("interweave"),Je=require("react"),Rd=require("react-redux");var ho=require("react");function Ls(t){return t.contentEditable==="true"}function bf(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 nd(t){let{selectionStart:e,selectionEnd:o}=Ls(t)?bf(t):t;return[e,o]}function sd(t){let[,e]=(0,ho.useState)(),o=(0,ho.useRef)(null);return o.current=nd(t),(0,ho.useEffect)(()=>{let n=()=>{let[s,r]=o.current??[],i=nd(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 rd(t,e){if(!e)return;let o=t,{value:n}=o,[s,r]=e,i=n.match(kn);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)})}var id=require("react"),Cf=["div","span","mark","strong","b","i","u","em"];function ei(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(Cf.includes(s)){let i=Array.isArray(n.props.children)?n.props.children:[n.props.children];return[...t.slice(0,t.length-1),(0,id.cloneElement)(n,{children:ei(i,e,o+1)})]}return[...t,...e]}function mt(t){return t.tagName.toLowerCase()==="textarea"}var Le={root:"wi",container:"vi",agentText:"co",tabText:"xo",hint:"S",matchSelection:"fo",focus:"ki",resetIndent:"zi",matchKeyword:"p",matchPlaceholder:"d",hover:"go",hintText:"ji",popover:"Yi",popoverRoot:"qi",popoverContentContainer:"bo",popoverContent:"Ci",selectionOptions:"Si",selectionOptionsIsHidden:"Ei",selectionOptionsButton:"Gi",caret:"Ni",popoverSuggestionsRoot:"Ai",suggestionsOverlayInputStyles:"Fi"};var hd=k(require("classnames")),yd=require("interweave"),Bs=require("react");var yo=require("react");function ad(t,e){let o;return[(...n)=>{window.cancelAnimationFrame(o);let s=e?e(...n):n;o=window.requestAnimationFrame(()=>{t(...s)})},()=>window.cancelAnimationFrame(o)]}function As(t){let e=(0,yo.useRef)(null),[o,n]=(0,yo.useState)(!1);return(0,yo.useEffect)(()=>{let s=!1,r=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[i,a]=ad((d,u)=>{let p=e.current;if(!p)return;let g=d/r,f=u/r,m=p.getBoundingClientRect(),y=g>m.x&&g<m.x+m.width&&f>m.y&&f<m.y+m.height;y&&!s?(s=!0,n(!0)):!y&&s&&(s=!1,n(!1))},({clientX:d,clientY:u})=>[d,u]),[c,l]=ad(()=>{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 ld(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Ms(t){return e=>{t.forEach(o=>{typeof o=="function"?o(e):o!=null&&(o.current=e)})}}function cd(t){return t!=null}var oi=k(require("classnames")),ve=require("react");var Ns=require("react"),Tf=["bottom","height","left","right","top","width"],Ef=(t={},e={})=>Tf.some(o=>t[o]!==e[o]),Ze=new Map,dd,ud=()=>{let t=[],e=[];Ze.forEach((o,n)=>{if(n instanceof Element&&!n.isConnected){e.push(n);return}let s=n.getBoundingClientRect();Ef(s,o.rect)&&(o.rect=s,t.push(o))}),e.forEach(o=>{Ze.delete(o)}),t.forEach(o=>{o.callbacks.forEach(n=>n(o.rect))}),dd=window.requestAnimationFrame(ud)};function kf(t,e){return{observe(){let o=Ze.size===0;if(Ze.has(t)){let n=Ze.get(t);n.callbacks.push(e),n.rect&&e(n.rect)}else Ze.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});o&&ud()},unobserve(){let o=Ze.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||Ze.delete(t),Ze.size||cancelAnimationFrame(dd)}}}}function ti(t){let[e,o]=(0,Ns.useState)(null);return(0,Ns.useLayoutEffect)(()=>{if(!t.current)return;let n=kf(t.current,s=>{o(s)});return n.observe(),()=>{n.unobserve()}},[t]),e}var vo=require("react"),gd=require("react-dom");var pd={root:"Hi"};var md=({children:t,parentNode:e})=>{let[o,n]=(0,vo.useState)(null),s=(0,vo.useContext)(Ro);return(0,vo.useLayoutEffect)(()=>{let r=document.createElement("div");return Kt(r),r.classList.add(pd.root),s!=null&&s.portalRootNode&&r.classList.add(s==null?void 0:s.portalRootNode),(e||document.body).appendChild(r),n(r),()=>{r.isConnected&&r.remove()}},[]),o?(0,gd.createPortal)(t,o):null};var De={ref:"Li",root:"o",positionAbove:"l",positionBelow:"s",positionLeft:"c",positionRight:"x",alignStart:"f",alignCenter:"g",alignEnd:"b"};var Os=require("react/jsx-runtime"),_s=(t=!1)=>{let[e,o]=(0,ve.useState)(t),n=(0,ve.useCallback)(()=>o(!0),[]),s=(0,ve.useCallback)(()=>o(!1),[]),r=(0,ve.useCallback)(()=>o(a=>!a),[]),i=(0,ve.useRef)(null);return{opened:e,open:n,close:s,toggle:r,triggerRef:i}};function ni(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 So=({className:t,triggerRef:e,boundaryRef:o=(0,ve.createRef)(),position:n="above",align:s="center",children:r,toStyle:i=ni,parentNode:a,...c})=>{let l=ti(e),d=ti(o),u=(0,ve.useMemo)(()=>i(l,d,0),[l,d]);return(0,Os.jsx)(md,{parentNode:a,children:(0,Os.jsx)("div",{className:(0,oi.default)(De.ref,{[De.positionAbove]:n==="above",[De.positionBelow]:n==="below",[De.positionLeft]:n==="left",[De.positionRight]:n==="right",[De.alignStart]:s==="start",[De.alignCenter]:s==="center",[De.alignEnd]:s==="end"}),style:u,...c,role:"dialog",children:(0,Os.jsx)("div",{className:(0,oi.default)(t,De.root),children:r})})})};var fd=k(require("classnames")),Ds=require("react");var si=require("react/jsx-runtime"),Hs=(0,Ds.forwardRef)(({className:t,children:e,...o},n)=>{let s=(0,Ds.useRef)(null),r=h("TabCompletion",Le);return(0,si.jsx)("div",{ref:Ms([s,n]),className:(0,fd.default)(t,r.popoverContentContainer),...o,children:(0,si.jsx)("div",{className:r.popoverContent,children:e})})});var ft=require("react/jsx-runtime"),If=t=>e=>{let o=ni(e);return"top"in o&&(o.width=t.width-(e.left-t.left)-10),o},Lf=({inputElement:t,boundaryRef:e,inputStyle:o,children:n,suggestion:s})=>{let r=h("TabCompletion",Le),i=_s(),a=(0,Bs.useMemo)(()=>If(t.getBoundingClientRect()),[t]),[c,l]=As(t);return(0,Bs.useEffect)(()=>{l?i.open():i.close()},[l]),(0,ft.jsxs)("span",{children:[(0,ft.jsx)("mark",{ref:Ms([c,i.triggerRef]),className:(0,hd.default)(r.matchKeyword,{[r.hover]:l}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:n}),i.opened&&(0,ft.jsx)(So,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:(0,ft.jsx)(Hs,{style:o,children:(0,ft.jsx)("div",{className:r.hintText,children:s})})})]})},Fs=class extends yd.Matcher{keywordMatches=[];preparedKeywordMatches=[];usedKeywordMatches=new Set;onBeforeParse(e,o){return o.keywordMatches&&o.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=o.keywordMatches.map(n=>({...n,keywordRegex:new RegExp(`\\b${ld(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(cd);if(o.length===0)return null;let n=o.reduce((s,r)=>r.index<s.index?r:s);return this.usedKeywordMatches.add(n.preparedKeywordMatch),n}replaceWith(e,o){return(0,ft.jsx)(Lf,{inputElement:o.inputElement,suggestion:o.suggestion,inputStyle:o.inputStyle,boundaryRef:o.boundaryRef,children:e},`keyword_${o.matchString}_${o.key}`)}asTag(){return"mark"}};var vd=require("interweave"),Sd=k(require("classnames"));var ri=require("react/jsx-runtime"),Af=({inputElement:t,children:e})=>{let o=h("TabCompletion",Le),[n,s]=As(t);return(0,ri.jsx)("mark",{ref:n,className:(0,Sd.default)(o.matchPlaceholder,{[o.hover]:s}),children:e})},Ks=class extends vd.Matcher{match(e){let o=e.match(/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\}(?!\}))/);return o?{index:o.index,length:o[0].length,match:o[0],matchString:o[0],valid:!0}:null}replaceWith(e,o){return(0,ri.jsx)(Af,{inputElement:o.inputElement,children:e},`placeholder_${o.matchString}_${o.key}`)}asTag(){return"mark"}};var zs=k(require("classnames")),Td=require("interweave"),ne=require("react"),Ed=require("react-redux");var ii=require("react/jsx-runtime"),xd=()=>(0,ii.jsx)("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:(0,ii.jsx)("path",{fill:"currentColor",d:"M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"})});var ht=require("react"),nn=require("react-redux"),Cd=k(require("lodash.debounce"));var bd={root:"Mi",content:"Ri"};function Us(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 ai(t){return t.replace("https://www.","").replace("https://","")}var Se=require("react/jsx-runtime"),Nf=3,Of=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),_f=({onSelectLink:t,onDismiss:e,placeholder:o,visitUrlText:n,linkCount:s=Nf})=>{let r=h("LinkSearch",bd),[i,a]=(0,ht.useState)(""),c=(0,nn.useDispatch)(),l=(0,nn.useSelector)(gc("url")),d=(0,nn.useSelector)(Qa("URL",Of)),[u,p]=(0,ht.useState)(d.length-1),g=b("fallbackImage"),f=S=>{let v=S.target;a(v.value)},m=(S,v)=>{S.stopPropagation(),S.preventDefault(),window.open(v,"_blank")},y=S=>{var x;let v=u-1<0?d.length-1:u-1,R=u+1===d.length?0:u+1;S.code==="Escape"&&(a(""),e()),S.code==="ArrowUp"&&p(v),S.code==="ArrowDown"&&p(R),S.code==="Enter"&&t(((x=d[u])==null?void 0:x.text)||i)},E=(0,ht.useCallback)((0,Cd.default)(S=>{c(Pt({query:S,type:"URL",tags:["link-search"]}))},300),[]);return(0,ht.useEffect)(()=>{i&&E(i)},[i]),(0,ht.useEffect)(()=>()=>{c(Un())},[]),(0,Se.jsxs)("div",{className:r.root,children:[(0,Se.jsx)(le,{withDivider:!0,children:(i?d:l).slice(0,s).map((S,v)=>(0,Se.jsx)(N,{selected:u===v,onClick:()=>t(S.text),"data-testid":"linksearch-suggestion",children:(0,Se.jsxs)(H,{children:[(0,Se.jsx)(H.Image,{src:Us(S,"small",g||void 0),title:S.title||S.text}),(0,Se.jsxs)(H.Content,{className:r.content,cropText:!0,children:[(0,Se.jsx)(H.Title,{children:S.title||ai(S.text)}),S.title&&ai(S.text)]}),(0,Se.jsx)(N.Actions,{children:(0,Se.jsx)(N.ActionButton,{label:n,onClick:R=>m(R,S.text)})})]})},S.text))}),(0,Se.jsx)(Bo,{value:i,onChange:f,autoFocus:!0,placeholder:o,onKeyUp:y})]})},wd=_f;var li={};Y(li,{enUS:()=>Df,nlNL:()=>Hf});var Df={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},Hf={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var oe=require("react/jsx-runtime"),Ff=(0,ne.forwardRef)((t,e)=>{let o=h("TabCompletion",Le);return(0,oe.jsx)("mark",{ref:e,className:(0,zs.default)(o.matchSelection)},"selection-start")}),Bf=({startRef:t,boundaryRef:e,inputStyle:o,inputElement:n,children:s})=>{let r=P(li),i=h("TabCompletion",Le),a=(0,ne.useRef)(null),c=(0,ne.useRef)(null),[l,d]=(0,ne.useState)(null),u=(0,Ed.useDispatch)(),p=_s(document.activeElement===n),[g]=(0,ne.useState)(()=>document.createRange());p.triggerRef.current=g,(0,ne.useEffect)(()=>()=>g.detach(),[]),(0,ne.useEffect)(()=>{let m=t.current,y=a.current;!m||!y||(g.setStart(m,0),g.setEnd(y,0))},[t.current,a.current]),po(()=>{p.close()});let f=(0,ne.useCallback)(m=>{let y=g.toString(),E=/^http(s?):\/\//.test(m)?m:`https://${m}`;u(_n({text:`[${y}](${E})`,replace:"selection"}))},[]);return(0,oe.jsxs)("span",{children:[(0,oe.jsx)("mark",{ref:a,className:(0,zs.default)(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":p.opened?"true":"false",children:s}),p.opened&&(0,oe.jsx)(So,{className:i.popoverRoot,triggerRef:p.triggerRef,boundaryRef:e,position:"above",align:"start",children:(0,oe.jsxs)(Hs,{style:o,ref:c,children:[(0,oe.jsx)("div",{className:(0,zs.default)(i.selectionOptions,{[i.selectionOptionsIsHidden]:l!==null}),children:(0,oe.jsxs)("button",{type:"button",tabIndex:l===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>d("insertLink"),children:[(0,oe.jsx)(xd,{}),(0,oe.jsx)("span",{children:"\xA0"}),(0,oe.jsx)("span",{children:r("insertLink")})]})}),l==="insertLink"&&(0,oe.jsx)(wd,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:f,onDismiss:()=>{d(null),p.close()}})]})})]},"selection-end")},Vs=class extends Td.Matcher{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(e,o){return this.props=o,this.charCount=0,this.startRef=(0,ne.createRef)(),this.foundIndex=0,e}match(e){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[o,n]=this.props.selection;if(o===n)return null;let s=this.foundIndex===0?o:n,r=s>=this.charCount&&s<=this.charCount+e.length?{index:s-this.charCount,length:0,match:"",valid:!0}:null;r&&this.foundIndex++;let i=this.foundIndex===1;return r&&i?this.charCount+=s-this.charCount:this.charCount+=e.length,r?{isStart:i,...r}:null}replaceWith(e,o){return o.isStart?(0,oe.jsx)(Ff,{ref:this.startRef}):(0,oe.jsx)(Bf,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};var Pd=require("react-redux");var Qe=require("react/jsx-runtime"),Kf=({enabled:t,content:e,tabText:o,showTabHint:n,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:c})=>{let l=h("TabCompletion",Le),d=b("insertLink"),u=b("showMidSentenceSuggestions"),p=b("inlineSuggestions"),g=sd(a),f=(0,Je.useRef)(null),m=(0,Pd.useSelector)(te);(0,Je.useEffect)(()=>{mt(a)&&g&&rd(a,g)},[g]);let y=(0,Je.useCallback)(v=>{if(!s||!o)return v;let R=[(0,Qe.jsx)("span",{className:l.resetIndent,children:"\u200B"},"u200B"),(0,Qe.jsx)("span",{"data-testid":"tab-completion",className:(0,$s.default)(l.tabText,l.resetIndent),"data-source":c,children:o},"tabText")];return n&&R.push((0,Qe.jsx)("span",{className:(0,$s.default)(l.hint,l.resetIndent),children:(0,Qe.jsx)(Cn,{keyCode:"tab"},"tabHint")})),ei(v,R)},[s,o,n]),E=(0,Je.useMemo)(()=>{let v=[];return d&&v.push(new Vs("selection")),v.push(new Ks("placeholders")),r&&v.push(new Fs("keywords")),v},[p,d,r]),S=(0,Je.useMemo)(()=>{let v=window.getComputedStyle(a);return{"--dd-color":v.color,"--dd-font-size":v.fontSize,"--dd-font-family":v.fontFamily,"--dd-font-variant":v.fontVariant}},[]);return!t||!m?null:(0,Qe.jsxs)("div",{ref:v=>{v!=null&&v.parentElement&&(f.current=v==null?void 0:v.parentElement)},className:l.root,style:S,children:[(0,Qe.jsx)(kd.Interweave,{tagName:"span",containerTagName:"div",className:(0,$s.default)(l.container,l.agentText),disableLineBreaks:mt(a),content:e||"\u200B",onAfterParse:y,matchers:E,selection:g,keywordMatches:i,inputElement:a,inputStyle:S,boundaryRef:f,inlineSuggestionsOnlyAtEnd:!u}),(0,Qe.jsx)("br",{})]})},Uf=({input:t,ui:e,settings:o,styleSuggestions:n,conversation:s})=>{var m;let{tabCompletionSuggestion:r}=t,i=(r==null?void 0:r.text)||"",a=(r==null?void 0:r.source)||"",c=t.html??no(t.text),l=i.indexOf(t.text)===0?i.slice(t.text.length):"",{showTabHint:d}=e,{isSupported:u}=s,{showTabCompletion:p,visible:g,showStyleSuggestions:f}=o;return{showTabHint:d,showStyleSuggestions:f,showTabCompletion:p,content:c,tabText:l,source:a,keywordMatches:((m=n.list)==null?void 0:m.keywordMatches)??[],enabled:g&&u!==!1}},Id=(0,Rd.connect)(Uf)(Kf);var Fu=k(require("classnames")),Bu=require("react"),G=require("react-redux");var yt=require("@reduxjs/toolkit");var Ld={list:[],fetchState:"idle",isInitialRequest:null},Md=t=>t.autoflows.list||[],Ad=t=>e=>{var o;return(o=e.list)==null?void 0:o.find(n=>n.triggerPayload===t)},Ye=(0,yt.createAsyncThunk)("autoflows/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getAutoflows(t)}),ci=(0,yt.createAsyncThunk)("autoflows/start",async(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");await n.startAutoflowSession(t),await o(Ye(t.platformSessionId))}),di=(0,yt.createAsyncThunk)("autoflows/stop",async(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");await n.stopAutoflowSession(t.platformSessionId),await o(Ye(t.platformSessionId))}),zf=(0,yt.createSlice)({name:"autoflows",initialState:Ld,reducers:{},extraReducers:t=>{t.addCase(ci.pending,(e,o)=>{let n=Ad(o.meta.arg.triggerPayload)(e);n.state="Started",n.isBusy=!0}),t.addCase(di.pending,(e,o)=>{let n=Ad(o.meta.arg.triggerPayload)(e);n.state="Aborted",n.isBusy=!0}),t.addCase(Ye.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}),t.addCase(Ye.rejected,e=>{e.fetchState="error"}),t.addCase(Ye.fulfilled,(e,o)=>{e.list=o.payload,e.fetchState="done"}),t.addCase(D,()=>Ld)}}),Nd=(0,yt.createAsyncThunk)("autoflows/openStream",(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");let s=n.openStream(t);s.on("sessionAborted",()=>{o(Ye(t))}),s.on("sessionCompleted",()=>{o(Ye(t))})}),Od=(0,yt.createAsyncThunk)("autoflows/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),_d=zf.reducer;var vt=require("@reduxjs/toolkit");var Dd={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},Hd=t=>t.customMessages.list,Fd=t=>e=>!!e.customMessages.sentSuggestions.find(o=>o===t),Bd=t=>e=>!!e.customMessages.answeredSuggestions.find(o=>o===t),Kd=t=>e=>!!e.customMessages.errorSuggestions.find(o=>o===t),sn=(0,vt.createAsyncThunk)("customMessages/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getCustomMessages(t)}),qs=(0,vt.createAsyncThunk)("customMessages/send",async(t,e)=>{let{platformSessionId:o,suggestion:n}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.sendCustomMessage(o,n)}),Gs=(0,vt.createAsyncThunk)("customMessages/answer",async(t,e)=>{let{platformSessionId:o,reply:n}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.answerCustomMessage(o,n)}),Ud=(0,vt.createSlice)({name:"customMessages",initialState:Dd,reducers:{onCustomMessage(t,e){Array.isArray(e.payload)?t.list=e.payload:t.list=[e.payload]}},extraReducers:t=>{t.addCase(sn.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(sn.rejected,e=>{e.fetchState="error"}).addCase(sn.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload||[]}).addCase(qs.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.errorSuggestions=e.errorSuggestions.filter(n=>o.meta.arg.suggestion.text!==n)}).addCase(qs.rejected,(e,o)=>{let n=e.sentSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1))}).addCase(Gs.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.answeredSuggestions.push(o.meta.arg.suggestion.text)}).addCase(Gs.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(D,()=>Dd)}}),zd=(0,vt.createAsyncThunk)("customMessages/openStream",(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.openStream(t).on("customMessageSuggestion",r=>{o(Ud.actions.onCustomMessage(r))})}),Vd=(0,vt.createAsyncThunk)("customMessages/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),$d=Ud.reducer;var rn=require("@reduxjs/toolkit"),Vf={token:null,accountUrl:null,interval:null},qd=t=>e=>{let{passwordlessToken:{token:o,accountUrl:n}}=e;return o&&n?`${n}/apis/admin/session/passwordless/login/?token=${o}&redirect=${t}`:null},ui=(0,rn.createAsyncThunk)("passwordlessToken/getTemporaryPasswordlessToken",async(t,e)=>{let{deepdeskAPI:o}=e.extra,n=await o.requestPasswordlessToken();return{accountUrl:o.client.baseUrl,token:n}}),pi=(0,rn.createAsyncThunk)("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:o=1e3*60*10}=t,{dispatch:n}=e;return n(ui()),setInterval(()=>n(ui()),o)}),Gd=(0,rn.createSlice)({name:"passwordlessToken",initialState:Vf,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(ui.fulfilled,(e,o)=>{e.token=o.payload.token,e.accountUrl=o.payload.accountUrl}),t.addCase(pi.fulfilled,(e,o)=>{e.interval=o.payload})}}),{stopPollPasswordlessToken:jd}=Gd.actions,Wd=Gd.reducer;var xo=require("@reduxjs/toolkit");var gi={cues:[],fetchState:"idle"},Xd=t=>{var e;return(e=t.rules)==null?void 0:e.cues},$f=(0,xo.createAction)("rules/resetCues"),Vt=(0,xo.createAsyncThunk)("rules/evaluate",async(t,e)=>{var o,n;try{let{deepdeskAPI:s}=e.extra,r=e.getState(),i=(o=r.conversation.current)==null?void 0:o.id;if(!i)throw new Error("No current conversation to evaluate rules");if(!(await s.getAccount()).ruleEngine)throw new Error("Rule engine is not enabled for this account");if(!(await s.getRules()).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),[]}}),Zd=(0,xo.createSlice)({name:"answer",initialState:gi,reducers:{removeCue(t,e){t.cues=t.cues.filter(o=>o.rule.id!==e.payload.id)}},extraReducers:t=>{t.addCase(Vt.pending,e=>{e.fetchState="loading"}).addCase(Vt.rejected,e=>{e.fetchState="error"}).addCase(Vt.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(D,()=>gi).addCase($f.toString(),()=>gi)}}),{removeCue:Qd}=Zd.actions,Jd=Zd.reducer;function Yd(t){let{customMessages:e,autoflows:o}=t;return o.fetchState==="loading"&&o.isInitialRequest===!0||e.fetchState==="loading"&&e.isInitialRequest===!0}var lu=require("react"),cu=require("react-redux");var ru=k(require("classnames")),iu=require("react");var tu=k(require("classnames"));var eu={root:"Ti"};var nu=require("react/jsx-runtime"),Gf=({className:t,children:e})=>{let o=h("Unicode",eu);return(0,nu.jsx)("span",{className:(0,tu.default)(t,o.root),children:e})},ou=Gf;var su={isDisabled:"Ui",buttonStart:"Bi",root:"Di",buttonStop:"ho",stateBadge:"h",isCompleted:"Ii",isStarted:"Oi",isAborted:"Xi"};var mi={};Y(mi,{enUS:()=>Wf,nlNL:()=>Xf});var Wf={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"}]},Xf={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]};var ge=require("react/jsx-runtime"),Qf=({disabled:t,state:e,displayName:o,description:n,onStartAutoflow:s,onStopAutoflow:r})=>{let i=h("Autoflow",su),a=P(mi),c=e==="Started"?"stop":"start",l=c==="start"?"\u25B6":c==="stop"?"\u25FC":"";return(0,ge.jsxs)(N,{className:(0,ru.default)(i.root,{[i.isDisabled]:t,[i.isCompleted]:e==="Completed",[i.isAborted]:e==="Aborted",[i.isStarted]:e==="Started"}),children:[(0,ge.jsx)(H,{children:(0,ge.jsxs)(H.Content,{children:[(0,ge.jsxs)(H.Title,{children:[e&&(0,ge.jsx)("span",{className:i.stateBadge,children:a(e)}),o]}),(0,ge.jsx)("span",{children:n})]})}),(0,ge.jsx)(N.Actions,{fixed:e==="Started",children:(0,ge.jsx)(N.ActionButton,{primary:!0,className:c==="start"?i.buttonStart:i.buttonStop,onClick:e==="Started"?r:s,disabled:t,label:(0,ge.jsxs)(iu.Fragment,{children:[(0,ge.jsx)(ou,{children:l})," ",(0,ge.jsx)("span",{children:a(c)})]})})})]})},au=Qf;var fi=require("react/jsx-runtime"),Jf=(t,e)=>{let o=e.filter(n=>n.state==="Started");return o.length>0?o.indexOf(t)===-1:!1},Yf=({autoflows:t,onStartAutoflow:e,onStopAutoflow:o,platformSessionId:n})=>(0,fi.jsx)(lu.Fragment,{children:t.map(s=>(0,fi.jsx)(au,{displayName:s.displayName,description:s.description,disabled:s.isBusy||Jf(s,t),state:s.state,onStartAutoflow:()=>e({platformSessionId:n,triggerPayload:s.triggerPayload}),onStopAutoflow:()=>o({platformSessionId:n,triggerPayload:s.triggerPayload})},s.displayName))}),eh=({autoflows:t,conversation:e})=>{var o;return{autoflows:t.list,platformSessionId:(o=e.current)==null?void 0:o.sessionId}},th={onStartAutoflow:ci,onStopAutoflow:di},du=(0,cu.connect)(eh,th)(Yf);var uu=k(require("classnames")),hi=require("react"),$t=require("react-redux");var et={root:"mo",title:"uo",isUsed:"Ji",quickReplies:"Ki",quickReply:"Pi",hasError:"Qi",label:"Vi",errorIcon:"Wi"};var ie=require("react/jsx-runtime"),nh=({suggestion:t})=>{let e=P(_t),o=(0,$t.useDispatch)(),n=(0,$t.useSelector)(Fd(t.text)),s=(0,$t.useSelector)(Bd(t.text)),r=(0,$t.useSelector)(Kd(t.text)),i=(0,$t.useSelector)(Pn),{replyOptions:a}=t,c=(0,hi.useCallback)(d=>{d.preventDefault(),d.stopPropagation(),!(n||!i)&&o(qs({platformSessionId:i,suggestion:t}))},[t,n,o,i]),l=(0,hi.useCallback)(d=>{if(d.preventDefault(),d.stopPropagation(),!i||!a)return;let u=parseInt(d.target.dataset.index,10),p=a[u];o(Gs({platformSessionId:i,reply:p,suggestion:t}))},[t,n,o,i]);return(0,ie.jsxs)(N,{onClick:c,className:(0,uu.default)(et.root,{[et.isUsed]:n,[et.hasError]:r}),children:[(0,ie.jsx)(H,{children:(0,ie.jsxs)(H.Content,{children:[(0,ie.jsxs)(H.Title,{className:et.title,children:[t.text," ",(0,ie.jsx)(wn,{className:et.label,children:"analyse tool"})," ",r&&(0,ie.jsx)("span",{className:et.errorIcon,role:"img","aria-label":e("sendingError"),title:e("sendingError"),children:"!"})]}),a&&a.length>0&&(0,ie.jsx)("ul",{className:et.quickReplies,children:a.map(d=>(0,ie.jsx)("li",{className:et.quickReply,children:d.title},d.title))})]})}),(0,ie.jsxs)(N.Actions,{fixed:r||n,children:[a&&a.length>0&&(0,ie.jsx)(N.DropdownButton,{label:e("answer"),disabled:s,children:a.map((d,u)=>(0,ie.jsx)(N.DropdownItem,{index:u,label:d.title,onClick:l},d.title))}),(0,ie.jsx)(N.ActionButton,{primary:!0,disabled:n,onClick:c,label:e(n?"suggestionSent":r?"tryAgain":"sendSuggestion")})]})]})},pu=nh;var js=require("react"),mu=require("react-redux"),Si=k(require("classnames"));var yi=require("react/jsx-runtime"),vi=()=>(0,yi.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,yi.jsx)("path",{d:"M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"})});var gu={root:"Zi",entity:"r",entityText:"_i",iconWrapper:"or",icon:"er",iconClicked:"ir"};var He=require("react/jsx-runtime"),rh=({entities:t})=>{let e=h("EntitiesWidgetList",gu),[o,n]=(0,js.useState)(void 0),s=(0,mu.useDispatch)(),r=()=>{n(void 0)},i=a=>{t&&(n(t.indexOf(a)),At(a.text),s(Q({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,js.useEffect)(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[o]),!t||t.length===0?null:(0,He.jsx)("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,c)=>(0,He.jsxs)("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[(0,He.jsx)("span",{className:e.entityText,children:a.text}),(0,He.jsxs)("span",{className:e.iconWrapper,children:[(0,He.jsx)("span",{className:(0,Si.default)(e.icon),children:(0,He.jsx)(vi,{})}),(0,He.jsx)("span",{className:(0,Si.default)(e.icon,o===c&&e.iconClicked),children:(0,He.jsx)(vi,{})})]})]},a.text))})},fu=rh;var xi=require("react/jsx-runtime"),hu=()=>(0,xi.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,xi.jsx)("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});var bi=require("react/jsx-runtime"),yu=()=>(0,bi.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,bi.jsx)("path",{d:"M543-340q16.595 0 28.798-12.202Q584-364.405 584-381t-12.202-28.798Q559.595-422 543-422t-28.798 12.202Q502-397.595 502-381t12.202 28.798Q526.405-340 543-340Zm-25-126h47q2-29 8.5-43t32.5-39q27-26 37.5-45.395Q654-612.79 654-639q0-45.882-31.5-74.941Q591-743 540-743q-38 0-68 20.5T428-665l45 19q11-25 27.5-38t39.5-13q29.778 0 48.389 17Q607-663 607-637q0 20-9 35t-32 32q-32 29-40 46.5t-8 57.5ZM260-200q-24 0-42-18t-18-42v-560q0-24 18-42t42-18h560q24 0 42 18t18 42v560q0 24-18 42t-42 18H260Zm0-60h560v-560H260v560ZM140-80q-24 0-42-18t-18-42v-620h60v620h620v60H140Zm120-740v560-560Z"})});var Ci=require("react/jsx-runtime"),vu=()=>(0,Ci.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Ci.jsx)("path",{d:"M319-250h322v-60H319v60Zm0-170h322v-60H319v60ZM220-80q-24 0-42-18t-18-42v-680q0-24 18-42t42-18h361l219 219v521q0 24-18 42t-42 18H220Zm331-554v-186H220v680h520v-494H551ZM220-820v186-186 680-680Z"})});var Au=require("react-redux");var bu=require("react-redux");var Su=require("@reduxjs/toolkit");function xu(t){return(0,Su.createAsyncThunk)("analytics/logEvent",(e,o)=>{var r,i,a;let n=(i=(r=o.getState())==null?void 0:r.conversation.current)==null?void 0:i.id,s=(a=o.getState())==null?void 0:a.info.agentInfo;return o.extra.deepdeskAPI.sendEvent(e.name,{conversationId:n,...s,data:e.data})})(t)}function Ws(){let t=(0,bu.useDispatch)();return async(e,o)=>{await t(xu({name:e,data:o}))}}var Ri=k(require("classnames")),Xs=require("react");var an=require("react/jsx-runtime"),Cu=({className:t})=>(0,an.jsxs)("svg",{viewBox:"0 0 12 12",version:"1.1",xmlns:"http://www.w3.org/2000/svg",className:t,children:[(0,an.jsx)("line",{x1:"2",y1:"10",x2:"10",y2:"2",stroke:"black",strokeWidth:"1"}),(0,an.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10",stroke:"black",strokeWidth:"1"})]});var wi=require("react/jsx-runtime"),wu=t=>(0,wi.jsx)("svg",{width:"16",height:"16",fill:"#000000",...t,viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,wi.jsx)("path",{fillRule:"evenodd",d:"M6.57086468,14.9173453 C6.38997052,14.9711236 6.19835748,15 6,15 L4,15 C2.8954305,15 2,14.1045695 2,13 L2,4 C2,2.8954305 2.8954305,2 4,2 L6,2 C6.68685475,2 7.29284112,2.34623869 7.65294381,2.87370078 C7.95642355,2.67736738 8.29504785,2.51351337 8.66312366,2.3818197 C9.50544052,2.08044754 10.3408482,1.9879107 10.9989281,1.99971266 C11.0150698,2.00005426 13.3487605,2.00015005 18,2 C20.7551411,2 22,6.05643086 22,12 C22,13.6824804 20.8695981,15 19,15 L15.9269768,15 C15.9359266,15.0245465 15.9451954,15.0497804 15.9547911,15.0757271 C16.007193,15.2174219 16.2391583,15.8256341 16.2970775,15.9810953 C16.4872151,16.4914441 16.6259612,16.9026411 16.7382242,17.3098712 C16.9079007,17.9253665 17,18.4798886 17,19 C17,20.4720069 16.091867,21.3862822 14.748281,21.777514 C14.1422801,21.9539723 13.6147967,22.0000922 13.0076976,22.0000008 L12.5204954,22 L12.2202699,21.6261158 C11.2556275,20.4248034 7.64562469,16.4822788 6.57086468,14.9173453 Z M8,13 C8,13.2401953 8.04443154,13.4528921 8.14171093,13.6800176 C8.40663864,14.2985643 11.914268,18.1371493 13.4599624,19.9848695 C13.7113931,19.9660111 13.9483736,19.9273712 14.1891338,19.8572655 C14.7621788,19.6904035 15,19.4509737 15,19 C15,18.6834183 14.9359344,18.2976852 14.8101464,17.8413935 C14.7161494,17.500423 14.5944107,17.1396301 14.4229225,16.6793379 C14.3689242,16.5344009 14.1358033,15.923159 14.0789589,15.7694517 C13.9489218,15.4178313 13.8632547,15.1589343 13.8046536,14.9236885 C13.5555377,13.9236468 13.8054549,13 15,13 L19,13 C19.6912225,13 20,12.6401099 20,12 C20,7.20925475 19.015127,4 18,4 C15.9322103,4 15.9322103,4 10.9655994,3.99940813 C10.5253746,3.99154158 9.91062406,4.05963657 9.33687634,4.2649175 C8.45196659,4.58152894 8,5.09776992 8,6 L8,13 Z M4,4 L4,13 L6,13 L6,4 L4,4 Z"})});var Ti=require("react/jsx-runtime"),Tu=t=>(0,Ti.jsx)("svg",{width:"16",height:"16",fill:"#000000",...t,viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,Ti.jsx)("path",{fillRule:"evenodd",d:"M7.65336736,21.1256786 C7.2933164,21.6534897 6.68712411,22 6,22 L4,22 C2.8954305,22 2,21.1045695 2,20 L2,11 C2,9.8954305 2.8954305,9 4,9 L6,9 C6.198171,9 6.38961023,9.02882212 6.57035446,9.08250314 C7.6444817,7.51807482 11.2554748,3.57449216 12.2202699,2.37298955 L12.5204954,1.99910538 L13,1.99910538 C13.6147967,1.99901314 14.1422801,2.04513312 14.748281,2.22159137 C16.091867,2.61282321 17,3.52709845 17,4.99910538 C17,5.51921677 16.9079007,6.07373891 16.7382242,6.68923415 C16.6259612,7.09646424 16.4872151,7.50766133 16.2970775,8.01801005 C16.2391583,8.17347129 16.007193,8.78168345 15.9547911,8.92337824 C15.9451954,8.94932503 15.9359266,8.9745589 15.9269768,8.99910538 L19,8.99910538 C20.8695981,8.99910538 22,10.316625 22,11.9991054 C22,17.9426745 20.7551411,21.9991054 18,21.9991054 L11.0344006,21.9985135 C10.3408482,22.0111947 9.50544052,21.9186578 8.66312366,21.6172857 C8.29521907,21.4856533 7.9567386,21.3218904 7.65336736,21.1256786 Z M8,17.9991054 C8,18.9013355 8.45196659,19.4175764 9.33687634,19.7341879 C9.91062406,19.9394688 10.5253746,20.0075638 10.963066,19.9997143 C10.9703499,19.9995545 10.9703499,19.9995545 11,19.9991054 L18,19.9991054 C19.015127,19.9991054 20,16.7898506 20,11.9991054 C20,11.3589955 19.6912225,10.9991054 19,10.9991054 L15,10.9991054 C13.8054549,10.9991054 13.5555377,10.0754586 13.8046536,9.07541689 C13.8632547,8.84017106 13.9489218,8.5812741 14.0789589,8.22965366 C14.1358033,8.07594642 14.3689242,7.46470447 14.4229225,7.31976744 C14.5944107,6.85947528 14.7161494,6.4986824 14.8101464,6.1577119 C14.9359344,5.70142019 15,5.31568707 15,4.99910538 C15,4.54813166 14.7621788,4.30870189 14.1891338,4.1418399 C13.9483736,4.07173418 13.7113931,4.0330943 13.4599624,4.01423587 C11.914268,5.86195611 8.40663864,9.70054105 8.14171093,10.3190878 C8.04443154,10.5462133 8,10.7589101 8,10.9991054 L8,17.9991054 Z M4,11 L4,20 L6,20 L6,11 L4,11 Z"})});function bo(t,e){var n;let o=t.cloneNode(!0);o.style.top=`${t.offsetTop}px`,o.style.left=`${t.offsetLeft}px`,o.style.position="absolute",o.classList.add(e),o.addEventListener("animationend",()=>o.remove()),(n=t.parentElement)==null||n.appendChild(o)}var ku=k(require("dompurify")),St=require("react"),Ru=k(require("snarkdown"));var Eu={fadeup:"E",root:"i",popover:"rr",options:"yo",copyIcon:"G",option:"wo",divider:"tr"};var tt=require("react/jsx-runtime");function ah(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 Ei(t){let e=t.cloneNode(!0);return e.querySelectorAll("div,button").forEach(o=>o.remove()),e.textContent??""}function lh(t){return t.replace(/\r\n/g,`
|
|
8
8
|
`)}var ch=({content:t,useLabel:e,copyLabel:o,onCopy:n,onUse:s})=>{let r=h("Markdown",Eu),i=(0,St.useRef)(null),[a,c]=(0,St.useState)(null),l=(0,St.useMemo)(()=>{let f=(0,Ru.default)(lh(t));return ku.default.sanitize(f).replace(/<\/code>/g,`${ah(r.copyIcon)}</code>`)},[t]),d=f=>{var E;let m=f.target,y=!!((E=i.current)!=null&&E.querySelector("code"));a||y&&m.tagName!=="CODE"||!y&&m!==i.current||(m.addEventListener("mouseleave",()=>c(null),{once:!0}),c(m))},u=()=>{if(!a)return;c(null);let f=a.querySelector("button");f&&(bo(f,r.fadeup),n(Ei(a)))},p=f=>{f.target.tagName.toLowerCase()==="button"&&(bo(f.target,r.fadeup),n(Ei(f.target.parentElement)))},g=()=>{a&&(c(null),s(Ei(a)))};return(0,tt.jsxs)(St.Fragment,{children:[a&&(0,tt.jsx)(So,{triggerRef:{current:a},parentNode:a,className:r.popover,children:(0,tt.jsxs)("div",{className:r.options,children:[(0,tt.jsx)("button",{type:"button",className:r.option,onClick:u,children:o}),(0,tt.jsx)("div",{className:r.divider}),(0,tt.jsx)("button",{type:"button",className:r.option,onClick:g,children:e})]})}),(0,tt.jsx)("div",{ref:i,className:r.root,dangerouslySetInnerHTML:{__html:l},onMouseOver:d,onClick:p})]})},Pu=ch;var ki={};Y(ki,{enUS:()=>dh,nlNL:()=>uh});var dh={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"}]},uh={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 Iu={fadeup:"N",fadedown:"A",selected:"vo",thumbsUp:"nr",thumbsDown:"ar"};var me=require("react/jsx-runtime"),gh=({cue:t,onRemove:e,onCopy:o,onUse:n,onThumbsUp:s,onThumbsDown:r})=>{let i=h("WidgetCue",Iu),a=P(ki),c=Ws(),[l,d]=(0,Xs.useState)(null),u=y=>{o&&o(y,t)},p=y=>{n&&n(y,t)},g=y=>{y.preventDefault(),y.stopPropagation(),e(t)},f=y=>{y.preventDefault(),y.stopPropagation(),bo(y.target,i.fadeup),d("up"),s(t)},m=y=>{y.preventDefault(),y.stopPropagation(),bo(y.target,i.fadedown),d("down"),r(t)};return(0,Xs.useEffect)(()=>{c("Assistant response displayed",{name:t.rule.name,description:t.rule.description,group:t.rule.label})},[]),(0,me.jsxs)(N,{"data-testid":"cue",children:[(0,me.jsx)(H,{children:(0,me.jsxs)(H.Content,{children:[t.title&&(0,me.jsx)(H.Title,{"data-testid":"widget-cue-title",children:t.title}),(0,me.jsx)(Pu,{content:t.text,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:u,onUse:p})]})}),(0,me.jsx)(N.IconButton,{title:a("thumbsUp"),onClick:f,icon:(0,me.jsx)(Tu,{}),className:(0,Ri.default)(i.thumbsUp,l==="up"&&i.selected),disabled:!!l}),(0,me.jsx)(N.IconButton,{title:a("thumbsDown"),onClick:m,icon:(0,me.jsx)(wu,{}),className:(0,Ri.default)(i.thumbsDown,l==="down"&&i.selected),disabled:!!l}),(0,me.jsx)(N.IconButton,{title:a("removeCue"),onClick:g,icon:(0,me.jsx)(Cu,{})})]})},Lu=gh;var ln=require("react/jsx-runtime"),mh=({cues:t})=>{let e=(0,Au.useDispatch)(),o=he(),n=Ws(),s=l=>{e(Qd({id:l.rule.id})),n("Assistant response closed",{name:l.rule.name,group:l.rule.label,description:l.rule.description})},r=(l,d)=>{At(l),n("Assistant response copied",{name:d.rule.name,group:d.rule.label,description:d.rule.description,copiedText:l})},i=(l,d)=>{o.send(at,{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(0,ln.jsx)(ln.Fragment,{children:t.map(l=>(0,ln.jsx)(Lu,{cue:l,onRemove:s,onCopy:r,onUse:i,onThumbsDown:c,onThumbsUp:a},l.rule.id))})},Mu=mh;var Ou=require("react");var fh=/(https?:\/\/[^\s]+)/,Nu=t=>t.split(" ").find(e=>fh.test(e));var xe=require("react/jsx-runtime"),hh=({suggestion:t,lines:e,onUse:o})=>{var d;let n=t.text||t.url||t.message,s=Nu(n),r=P(_t),i=b("showImages"),a=b("fallbackImage"),c=u=>{u.preventDefault(),u.stopPropagation(),o(n)},l=(0,Ou.useCallback)(u=>{window.open(s,"_blank"),u.stopPropagation(),u.preventDefault()},[s]);return(0,xe.jsxs)(N,{onClick:c,"data-testid":"edit-suggestion",children:[(0,xe.jsxs)(H,{children:[i&&t.image&&(0,xe.jsx)(H.Image,{src:Us(t,"small",a||void 0),title:t.title}),(0,xe.jsxs)(H.Content,{children:[t.title&&(0,xe.jsx)(H.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((d=t.searchKeywords)==null?void 0:d.length)>0&&(0,xe.jsx)(N.Labels,{labels:t.searchKeywords}),(0,xe.jsx)(H.Content,{cropText:e==="single",lineClamp:e==="multiple",children:n})]})]}),(0,xe.jsxs)(N.Actions,{children:[s&&(0,xe.jsx)(N.ActionButton,{onClick:l,label:r("visitUrl")}),(0,xe.jsx)(N.ActionButton,{primary:!0,onClick:c,label:r("useSuggestion")})]})]})},_u=hh;var cn=require("react/jsx-runtime"),yh=({lines:t,suggestions:e})=>{let o=he(),n=(s,r)=>{o.send(at,{text:s,suggestion:{...r,source:r.source,sourceText:r.text}})};return(0,cn.jsx)(cn.Fragment,{children:e.map(s=>(0,cn.jsx)(_u,{suggestion:s,lines:t,onUse:r=>n(r,s)},s.text||s.url||s.message))})},Du=yh;var Pi={};Y(Pi,{enUS:()=>vh,nlNL:()=>Sh});var vh={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"}]},Sh={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 Hu={root:"pr",loginText:"dr",stateText:"ko",sectionList:"lr",shortcutList:"sr",shortcut:"cr",link:"zo"};var L=require("react/jsx-runtime"),Zs=(t,e)=>{let o=(0,G.useSelector)(te);(0,Bu.useEffect)(()=>o?e.every(n=>!!n)?t():()=>{}:()=>{},[...e,o])},bh=({onLogIn:t})=>{let e=P(Pi),o=(0,G.useDispatch)(),n=b("isEmbedded"),s=h("Widget",Hu),r=b("showAutoflows"),i=b("showCustomMessages"),a=b("showSummaryCommand"),c=b("showKnowledgeSearch"),l=b("showSearch"),d=(0,G.useSelector)(ut),u=(0,G.useSelector)(Ss),p=(0,G.useSelector)(Md),g=(0,G.useSelector)(Xd),f=(0,G.useSelector)(ms),m=(0,G.useSelector)(Hd),y=(0,G.useSelector)(In),E=(0,G.useSelector)(Yt),S=(0,G.useSelector)(te),v=(0,G.useSelector)(Pn),R=(0,G.useSelector)(Yd),x=(0,G.useSelector)(xs),T=he(),O=(0,G.useSelector)(mc),q=(0,G.useSelector)(qd("/admin/")),K=b("adminUrl"),A=b("productName");if(Zs(()=>(o(sn(v)),o(zd(v)),()=>{o(Vd(v))}),[o,E,i,v]),Zs(()=>(o(Ye(v)),o(Nd(v)),()=>{o(Od(v))}),[o,E,r,v]),Zs(()=>{u.forEach(({type:I})=>{o(I==="entities"?Re():Ie(I))})},[o,E,y,d]),Zs(()=>(o(pi()),()=>{o(jd())}),[o]),E===!1)return(0,L.jsx)("div",{className:s.stateText,children:(0,L.jsx)("div",{children:(0,L.jsx)("p",{children:e("notSupported")})})},"supported");if(S===!1)return(0,L.jsx)("div",{className:s.loginText,children:(0,L.jsx)("div",{children:(0,L.jsx)(Ps,{isEmbedded:n,loginUrl:K,onLogIn:t})})},"login");if(!d||!v||S===null||O||R)return(0,L.jsx)("div",{className:s.stateText,children:(0,L.jsx)("div",{children:(0,L.jsx)("p",{children:e("waiting")})})},"waiting");let _=l||a||c||q;return(0,L.jsx)("div",{className:(0,Fu.default)(s.root),"data-testid":"widget",children:(0,L.jsxs)(Tn,{className:s.sectionList,children:[_&&(0,L.jsx)(Ke,{title:e("actions"),type:"shortcuts",children:(0,L.jsxs)("div",{className:s.shortcutList,children:[l&&(0,L.jsxs)("button",{className:s.shortcut,"data-testid":"shortcut-search",onClick:()=>T.send("ShowCommandPalette",{isOpen:!0}),children:[(0,L.jsx)(so,{}),e("linkSearch")]}),a&&(0,L.jsxs)("button",{className:s.shortcut,"data-testid":"shortcut-summary",onClick:()=>T.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,L.jsx)(vu,{}),e("linkSummary")]}),c&&(0,L.jsxs)("button",{className:s.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>T.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,L.jsx)(yu,{}),e("linkKnowledgeSearch")]}),q&&(0,L.jsxs)("a",{className:s.shortcut,target:"_blank",href:q,"data-testid":"shortcut-studio-login",rel:"noreferrer",children:[(0,L.jsx)(hu,{}),e("linkStudioLogin",{productName:A})]})]})}),i&&m.length>0&&(0,L.jsx)(Ke,{type:"custom-messages","data-testid":"custom-messages",children:(0,L.jsx)(le,{withDivider:!0,children:m.map(I=>(0,L.jsx)(pu,{suggestion:I},I.text))})}),r&&p.length>0&&(0,L.jsx)(Ke,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:(0,L.jsx)(le,{withDivider:!0,children:(0,L.jsx)(du,{})})}),u.map(({type:I,title:X,amount:lr,lines:cr})=>{var Wt;switch(I){case"entities":return f&&f.length>0&&(0,L.jsx)(Ke,{type:I,title:X,"data-testid":`type-${I}`,children:(0,L.jsx)(fu,{entities:f})},I);case"cues":return g&&g.length>0&&(0,L.jsx)(Ke,{type:I,title:X,"data-testid":`type-${I}`,children:(0,L.jsx)(le,{withDivider:!0,children:(0,L.jsx)(Mu,{cues:g})})},I);default:return((Wt=x[I])==null?void 0:Wt.fetchState)==="done"&&x[I].suggestions.length>0&&(0,L.jsx)(Ke,{type:I,title:X,"data-testid":`type-${I}`,children:(0,L.jsx)(le,{withDivider:!0,children:(0,L.jsx)(Du,{lines:cr,contentType:I,suggestions:x[I].suggestions.slice(0,lr)||[]})})},I)}})]})})},Ku=bh;function Co(t){let e=new Range;return e.selectNodeContents(t),e}function Uu(t,e,o){try{return xt(t,e,o),!0}catch{return!1}}function Qs(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function Js(t){return"tagName"in t&&t.tagName==="BR"}var dn=/[\u200B-\u200D\uFEFF]/g;function xt(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(dn,""),u=s+d.length,p=e>=s&&e<=u,g=o>=s&&o<=u;if(p){let f=i(l,e-s);f===0&&!g?n.setStartBefore(c):n.setStart(c,f)}g&&(n.setEnd(c,i(l,o-s)),r=!0),s=u;break}case Node.ELEMENT_NODE:{if(Js(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;Qs(c)&&l&&!Qs(l)&&!Js(l)&&s++;break}default:break}}if(a(t),n.startContainer===document)throw new Error("Offsets out of bound");return n}function un(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:o,startOffset:n,endContainer:s,endOffset:r,collapsed:i}=e,a,c,l=0;function d(u){let p=u===o,g=u===s;switch(u.nodeType){case Node.TEXT_NODE:{let f=u.textContent;p&&(a=l+f.substring(0,n).replace(dn,"").length),g&&(c=l+f.substring(0,r).replace(dn,"").length),l+=f.replace(dn,"").length;break}case Node.ELEMENT_NODE:{let f=u.nextSibling===null;Js(u)&&!f&&l++;for(let m=0;m<u.childNodes.length;m++){let y=p&&m===n,E=g&&m===r;if(y&&(a=l),E&&(c=l),c!==void 0||((!y||!i)&&d(u.childNodes[m]),g&&m===r-1&&(c=l),c!==void 0))break}!g&&Qs(u)&&!f&&l++,g&&(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 pn(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,g=u?r:void 0,f=l.textContent.replace(dn,"");p===0&&g===void 0?a+=f:a+=f.substring(p,g);break}case Node.ELEMENT_NODE:{let p=l.nextSibling===null;i===0&&Js(l)&&!p&&(a+=`
|
|
9
9
|
`);for(let g=d?n:0;g<(u?Math.min(r,l.childNodes.length):l.childNodes.length)&&(c(l.childNodes[g]),i!==1);g++);!u&&i===0&&Qs(l)&&!p&&(a+=`
|
|
10
|
-
`);break}default:break}u&&i++}return c(t),a}var zu=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(zu||{}),ot=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();st(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(zu).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 Vu(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var qt=class extends ot{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),pn(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!Vu(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!Vu(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return un(this.element,e);let o=this.lastKnownSelection;if(o&&Uu(this.element,o.start,o.end))return o;let n=Co(this.element);return n.collapse(!1),un(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return pn(this.element,xt(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 Gt=class extends ot{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 $u(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 Ch(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}var Ii=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()}},Li=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=$u(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()}},Ai=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 Li(e,this.deepdeskUrl,{debug:!0}):new Ii(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=Ch(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)}},qu=Ai;var wo=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var Mi=t=>new Promise(e=>{setTimeout(e,t)});var To=class extends wo{name="ClientError"},Oi=class extends wo{name="ServerError"},Ni=new Map,Ae=class t{constructor(e="",o={}){this.baseUrl=e;this.options=o;o.fetch&&(this.fetch=o.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,o={}){return new Promise((n,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,c=o.method===void 0||o.method.toLowerCase()==="get",{useCache:l=!1,abortLatest:d=!1,attempts:u=1,retryDelay:p=500,refreshTokenOn401:g=!0,retryOnError:f=T=>T instanceof TypeError,retryOnResponse:m=T=>T.status>=500,version:y="v1",...E}=o;if(l)if(c){if(Ni.has(i)){n(Ni.get(i));return}}else throw new Error(`Can't use 'useCache' for ${o.method}`);let S={credentials:"include",...E,headers:{"Content-Type":"application/json",...E.headers}};!c&&this.csrfToken&&(S.headers={...S.headers,"X-CSRFToken":this.csrfToken}),typeof y=="string"&&(S.headers={...S.headers,"X-Deepdesk-API-Version":y});let v=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()=>(v--,a(i,S).then(async T=>m(T)&&!r.isAborted&&v>0?(await Mi(p),x()):T.status===401&&g===!0&&R===!1?(R=!0,await this.refreshToken(),x()):T).catch(async T=>{if(f(T)&&!r.isAborted&&v>0)return await Mi(p),x();throw T}));x().then(T=>T.json().catch(()=>null).then(O=>{T.status>=500?s(new Oi("Server Error",O)):T.status===401?s(new To("Unauthorized",O)):T.status===403?s(new To("Forbidden",O)):T.status===404?s(new To("Not Found",O)):T.status>=400&&s(new To("Bad Request",O)),delete this.latestRequestByUrl[i],l&&Ni.set(i,O),n(O)})).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 wh;(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||={})})(wh||={});function Ys(t){return{...M(t),tags:t.tags}}var nt=class t{constructor(e,o={}){this.options=o;this.client=new Ae(e,{fetch:o.fetch}),this.client.patchFetch(n=>async(s,r)=>{let i=await n(s,r);return this.handleDeepdeskVersionHeaders(i),i})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=await this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(t.exchangeTokenPromise||(t.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),t.exchangeTokenPromise):Promise.resolve()}async createConversation(e){await this.preflight(),w.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...V(e),tags:e.tags},{version:"v2"});return Ys(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null,useCache:!0});return M(o)}async getKnowledgeAssistant(e){let o=await this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{version:null,useCache:!0});return M(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return M(e)}async getAccount(){let e=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return M(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null,useCache:!0});return M(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}`),Ys(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=V(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return Ys(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...V(s),tags:s.tags})),{version:"v2"})).map(s=>Ys(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",V({...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:V({...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 M(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/",V(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}`,V(o),{abortLatest:!0})).map(r=>({...M(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`,V(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 M(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",V(e),{abortLatest:!0});return M(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,V(e),{version:"v2"});return M(o)}async knowledgeAssist(e,o,n,s={}){let r=await this.client.post(`/api/knowledge-assist/assistants/${n}/search`,V({question:e.question,promptInstruction:e.promptInstruction,chatHistory:o.map(i=>({question:i.question,answer:i.answer.answer})),agentId:s.agentId,conversationId:s.conversationId}),{version:"v2"});return M(r)}async requestLoginByEmail(e){let o=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return M(o)}async requestPasswordlessToken(){let e=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return M(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 M(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 M(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 M(o)}async translateMessages(e){let o=await this.client.post("/api/translate",V(e),{version:"v2"});return M(o)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(da);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 gn=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(vr(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,M(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 Th;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(Th||={});var mn=class{constructor(e,o={}){this.apiUrl=e;this.client=new Ae(e,o)}client;streams={};logger=w;async getCustomMessages(e){let o=await this.client.get(`/sessions/${e}/suggestions`);return M(o.suggestions)}async sendCustomMessage(e,o){let n=await this.client.post(`/sessions/${e}/messages`,V(o));return M(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,V(o))}async getAutoflows(e){let o=await this.client.get(`/sessions/${e}/autoflows`);return M(o.autoflows)}async startAutoflowSession(e){let o=await this.client.post("/autoflow-sessions",V(e));return M(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new gn(`${this.apiUrl}/sessions/${e}/events`),this.streams[e].connect()),this.streams[e]}closeStream(e){this.streams[e]||(this.streams[e].disconnect(),delete this.streams[e])}};var nr=require("@reduxjs/toolkit");var ju=require("@reduxjs/toolkit");var Gu={startTime:null,stopTime:null},Wu=(0,ju.createSlice)({name:"handlingTime",initialState:Gu,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(D,()=>Gu)}}),{handlingTimeStart:Xu,handlingTimeStop:er,handlingTimeReset:Zu}=Wu.actions,Qu=Wu.reducer;var Ju=(t={})=>{let e={onAuthError:Jt(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};var or=require("@reduxjs/toolkit");var tr={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var jt=(0,or.createAsyncThunk)("styleSuggestions/getAll",async({text:t},e)=>{var i;let{deepdeskAPI:o}=e.extra,n=e.getState(),{showStyleSuggestions:s}=n.settings,r=(i=n.conversation.current)==null?void 0:i.profileCode;if(!s)return tr.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),Eh=(0,or.createSlice)({name:"styleSuggestions",initialState:tr,reducers:{},extraReducers:t=>{t.addCase(jt.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(jt.rejected,e=>{e.fetchState="error"}).addCase(jt.fulfilled,(e,o)=>{e.fetchState="done",st(e.list,o.payload)||(e.list=o.payload)}).addCase(Rt,e=>{e.list=tr.list}).addCase(D,()=>tr)}}),Yu=Eh.reducer;var ep=(t={})=>{let e,o=!0,n={getStyleSuggestions:jt,debounce:500,...t};return s=>r=>i=>{var g;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(!((g=l.conversation.current)==null?void 0:g.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 kh(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var tp=(t={})=>{let e={getTextSuggestions:Ie,getAutocompleteSuggestions:Qo,debounce:200,check:go,...t},o;return n=>s=>r=>{var m;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=(m=c.conversation.current)==null?void 0:m.id,p=r.type===bs.toString();if(!u||!l&&!d)return a;let{input:{userCommitted:g}}=c;return kh(g,i)&&!p||(clearTimeout(o),!e.check(c))||(o=setTimeout(()=>{let y=eo(c);y===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(y))},p?0:e.debounce)),a}};var op=jt.fulfilled.toString();function Rh(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 np=t=>e=>o=>n=>{var l;if(n.type!==op){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=Rh(s,i);n.type===op&&c.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:c}})};var Ph=(0,nr.combineReducers)({answer:rc,auth:ba,autoflows:_d,conversation:Ea,contentTypes:bl,customMessages:$d,passwordlessToken:Wd,entities:$l,knowledgeAssistant:oc,handlingTime:Qu,info:Ga,input:za,settings:ma,profile:lc,search:Ya,summary:Ql,styleSuggestions:Yu,ui:Fc,rules:Jd,textSuggestions:yc});function sp(t){return(0,nr.configureStore)({reducer:Ph,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),Ju(),tp({debounce:200}),ep({debounce:500}),np(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var Ih=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},Lh=t=>e=>o=>n=>{var a;let s=e.getState(),r=gr("inlineSuggestions")(s);switch(n.type){case Jt.toString():{!n.payload&&t.emit("logout",void 0);break}case Re.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:n.payload}});break;case Q.toString():t.sendEvent(n.payload.name,{conversationId:((a=n.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:n.payload.data});break;case Dn.toString():t.handleKeyDown(n.payload);break;case Rt.toString():t.logSendMessage(n.payload);break;case Hn.toString():t.handleInputChanged(n.payload);break;case Vt.fulfilled.toString():n.isBroadcasted||t.broadcast(br,n,!1),t.emit("cues",n.payload);break;default:break}let i=o(n);switch(n.type){case Rt.toString():t.handleAfterSendMessage(n.payload);break;case Yo.toString():t.onUpdateShowTabHint(n.payload);break;case er.toString():t.logHandlingTime();break;case Ne.toString():{let{start:c,end:l}=s.input.selection;t.emit("select-suggestion",{type:Ih(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:c,end:l}:{start:0,end:l}},{mayApplyChanges:!0}),r&&(e.dispatch(Me([])),e.dispatch($e()));break}case _n.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 Lo.toString():{let c=e.getState(),{text:l,selection:d}=c.input.userCommitted;t.emit("reset",{text:l,selectionAfter:d},{mayApplyChanges:!0});break}case Fn.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 Me.toString():{r&&n.payload.length>0&&e.dispatch(it(0));break}case Ge.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},rp=Lh;function _i(t){return t.toISOString().replace("T"," ").replace("Z","")}function ip(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:_i(o),timeStop:_i(n)}}function ap(t,e,o){var O,q,K;let{text:n,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:c,agentStartedTypingTimestamp:l,externalTimeTotalSeconds:d,pastes:u,cuts:p,deletions:g,textSuggestions:f,offeredTextSuggestions:m}}=e[t],y=n.length,S=f.reduce((A,{text:_,searchTerm:I})=>A+_.length-(I?I.length:0),0),v=l??Date.now(),R=(Date.now()-v)/1e3+(d||0),x=s/R,T=f.reduce((A,{searchTerm:_})=>A+(_?_.length:0),0);return{conversationId:e.conversation.current.id,source:"agent",text:n,clientVersion:o.version,pastes:u,cuts:p,deletions:g,lenTextTyped:s+T,lenTextTotal:y,lenTextAssisted:S,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:R,charsPerSecond:x,numPastes:c,textSuggestionsV2:f,suggestionsCounters:[{source:"gpt",countOffered:m.filter(A=>A.source==="gpt").length}],agentId:(O=e.info.agentInfo)==null?void 0:O.agentId,agentName:(q=e.info.agentInfo)==null?void 0:q.agentName,agentEmail:(K=e.info.agentInfo)==null?void 0:K.agentEmail}}function Di(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return Di(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?Di(s,e):null}function lp(t,e){return Di(t,e)}function cp(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function Ah(t){return typeof t=="object"&&t!==null&&"tagName"in t}function sr(t){return Ah(t)&&(mt(t)||Ls(t))}var dp,Fe=new Map,Mh=["bottom","height","left","right","top","width"],Nh=(t={},e={})=>Mh.some(o=>t[o]!==e[o]);function up(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,...up(e)]:[]}function pp(t,e){return!t||!e?null:{...t,top:t.top+e.top,left:t.left+e.left}}var rr=!1,gp=()=>{rr=!0;let t=[];if(Fe.forEach((e,o)=>{if(!o.isConnected){e.rect=null,t.push(e),Fe.delete(o);return}let n=o.getBoundingClientRect();Nh(n,e.rect)&&(e.rect=n,t.push(e))}),t.forEach(e=>{let o=e.parentRects?e.parentRects.reduce(pp,e.rect):e.rect;e.callbacks.forEach(n=>n(o))}),Fe.size===0){rr=!1;return}dp=window.requestAnimationFrame(gp)};function Hi(t,e){let o=up(t),n=[],s=o.map((r,i)=>Hi(r,a=>{n[i]=a;let c=Fe.get(t);if(!c)return;let l=n.reduce(pp,c.rect);c.callbacks.forEach(d=>d(l))}));return{observe(r=!0){if(s.forEach(i=>i.observe(!1)),Fe.has(t)){let i=Fe.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else Fe.set(t,{rect:void 0,callbacks:[e],parentRects:n});r&&!rr&&gp()},unobserve(){s.forEach(i=>i.unobserve());let r=Fe.get(t);if(r){let i=r.callbacks.indexOf(e);i>=0&&r.callbacks.splice(i,1),r.callbacks.length||Fe.delete(t),Fe.size||(cancelAnimationFrame(dp),rr=!1)}}}}var mp,Be=new Map,fp=()=>{Be.forEach((t,e)=>{if(!e.isConnected){Be.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)))}),Be.size!==0&&(mp=window.requestAnimationFrame(fp))};function hp(t,e){return{observe(){let o=Be.size===0;Be.has(t)?Be.get(t).callbacks.push(e):Be.set(t,{visible:void 0,callbacks:[e]}),o&&fp()},unobserve(){let o=Be.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||Be.delete(t),Be.size||cancelAnimationFrame(mp)}}}}var Fi=["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 Bi(t,e,o){return o.forEach(n=>{e.style[n]=t[n]})}function Eo(t){return parseFloat(t)}function ir(t){return Math.round(t*1e6)}function yp(t){return t/1e6}function Ki(t,e,o){if(t.boxSizing==="content-box")return;let{clientWidth:n}=e,s=Eo(t.width),r=Eo(t.borderLeftWidth),i=Eo(t.borderRightWidth),a=Eo(t.paddingRight),c=yp(ir(s)-ir(r)-ir(i)),l=yp(ir(n));if(c-l>2){let d=c-l;o.style.paddingRight=`${a+d}px`}}function fn(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",Kt(o);let n=window.getComputedStyle(t),s=!0,r=()=>{o.scrollTop=t.scrollTop};Bi(n,o,Fi),Ki(n,t,o),e.mirrorOverflow&&(o.style.overflow="hidden",t.addEventListener("scroll",r));let i=hp(t,()=>{Bi(n,o,Fi),Ki(n,t,o),r(),setTimeout(r,0)}),a,c=!0,l=Hi(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(Bi(n,o,Fi),Ki(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(),g=window.getComputedStyle(e.closestScrollElement),f=Eo(g.borderTopWidth),m=Eo(g.borderBottomWidth),y=p.top+f-u.top,E=u.top+u.height+-(p.top+p.height-m);o.style.clipPath=`inset(${y}px 0px ${E}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 vp=(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 Oh(t){return t.offsetParent!==null}function Sp(t){if(!Oh(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 ar(t,e,o=100){let n=Sp(t);e({isVisible:n});let s=setInterval(()=>{let r=Sp(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}var $=require("react/jsx-runtime");var xp=vp("showTabHint",!0),hn=class t{static version="11.2.1-beta.1";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 nt(l,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let d={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[rp({broadcast:(u,p,g)=>{this.broadcastEvents.send(u,p,g)},emit:(u,p,g)=>this.emit(u,p,g),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=>xp.update(u),sendEvent:(u,p)=>this.deepdeskApi.sendEvent(u,p)})]};o&&Object.assign(d,{deepdeskBrokerAPI:new mn(o)}),this.store=sp(d),this.broadcastEvents=new qu({debug:!0,deepdeskUrl:l,eventMap:el(this.store),createCustomChannel:c}),this.store.dispatch(Yo(xp.value())),this.store.dispatch(Rn({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(Jt(null)),this.store.dispatch(ze()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();te(n)&&fa(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(ze())).payload}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(o){w.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(fr({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Ln(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(An({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(hr(e))).payload}async postMessages(e){return(await this.store.dispatch(Nn(e))).payload}async updateConversation(e){return(await this.store.dispatch(Mn(e))).payload}resetConversation(){this.store.dispatch(D()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Ge());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(Rn(e))}setVisitorInfo(e){this.store.dispatch(qa(e))}async setAgentInfo(e){await this.store.dispatch(Ao(e))}async setAgentSettings(e){await this.store.dispatch(Sr(e))}async getAgentSettings(){return(await this.store.dispatch(xr())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(bs()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Hn(e))}notifyKeyDown(e){this.store.dispatch(Dn(e))}notifyPaste(e,o){this.store.dispatch(Fa({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Da(e))}notifyExternalSuggestion(e){this.store.dispatch(Ne(e)),this.store.dispatch($e())}async evaluateRule(e,o={}){let{payload:n,error:s}=await this.store.dispatch(Vt({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(pt({collapse:!1})),this.inputMediator&&this.store.dispatch(Aa({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(Me([])))}handleKeyDown(e){let{overlayCollapsed:o}=this.state.ui,{textSuggestions:n,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=n.length>0,c=s!==-1;if(this.store.dispatch(Ha(Pa(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let l=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Na()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},d=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(_a()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Lo()):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(it(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(it(-1)),this.store.dispatch(Lo()),e.preventDefault()):o||(this.store.dispatch(pt({collapse:!0})),this.store.dispatch(Dc(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:u}=this.state.input,p=u.text.substring(0,u.selection.end),{tabCompletionSuggestion:g}=this.state.input;this.store.dispatch(Yo(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&g&&g.text.startsWith(p)&&(this.store.dispatch(Ne({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch($e())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Ba()),this.store.dispatch(Me([]))}handlingTimeStart(){this.state.handlingTime.startTime||(w.info("Start handling time"),this.store.dispatch(Xu()))}handlingTimeStop(){this.state.handlingTime.startTime&&(w.info("Stop handling time"),this.store.dispatch(er()))}logSendMessage(e){let o=ap("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=ip(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Zu())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch($e()),this.store.dispatch(Rt(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(Ne({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]=fn(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{(0,be.unmountComponentAtNode)(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,c]=fn(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{(0,be.unmountComponentAtNode)(s),c()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Kt(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{(0,be.unmountComponentAtNode)(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),w.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(w.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Ua(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(!sr(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:g,inputMediator:f,closestScrollSelector:m,appendOverlayTo:y,inlineSuggestions:E,floatingMenu:S}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:c,showSuggestionsBeforePattern:l,showSuggestionsAfterPattern:d,showTextSuggestions:i,insertLink:g,isEmbedded:u,inlineSuggestions:E,floatingMenu:!!S}),o.automaticHandlingTime&&this.setupHandlingTime(e),Kt(e),this.inputMediator=f||(mt(e)?new Gt(e):new qt(e)),this.inputMediator.on("change",({plainText:x})=>{this.notifyInputChanged(x)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Ka({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 v=m&&lp(e,m)||void 0;if(E){let{customStyles:x,appendOverlayTo:T}=o;if(mt(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let O=this.createInlineContainer(e,"deepdesk-caret");(0,be.render)((0,$.jsx)(zt,{store:this.store,customStyles:x,children:(0,$.jsx)(It,{broadcastEvents:this.broadcastEvents,children:(0,$.jsx)(qc,{})})}),O),this.inputMediator.on("caret",K=>{this.store.dispatch(Me([])),K?(O.style.display="block",O.style.top=`${K.top}px`,O.style.left=`${K.left}px`):O.style.display="none"});let q=this.overlayContainerFactory("floating-menu",v||e,{appendTo:typeof S=="object"&&"appendOverlayTo"in S?S.appendOverlayTo:T},x==null?void 0:x.floatingMenuRootNode);(0,be.render)((0,$.jsx)(zt,{store:this.store,customStyles:x,children:(0,$.jsx)(It,{broadcastEvents:this.broadcastEvents,children:(0,$.jsx)(Mc,{onLogIn:()=>this.loginViaPopup().catch(K=>w.warn(K.message))})})}),q)}else{let x=this.overlayContainerFactory("deepdesk-tab-completion",v||e,{appendTo:y,closestScrollElement:v,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),T=this.overlayContainerFactory("deepdesk-suggestions-overlay",v||e,{appendTo:y},n==null?void 0:n.suggestionsRootNode);(0,be.render)((0,$.jsx)(zt,{store:this.store,customStyles:n,children:(0,$.jsx)(It,{broadcastEvents:this.broadcastEvents,children:(0,$.jsx)(Id,{inputElement:e})})}),x),(0,be.render)((0,$.jsx)(zt,{store:this.store,customStyles:n,children:(0,$.jsx)(It,{broadcastEvents:this.broadcastEvents,children:(0,$.jsx)(od,{onLogIn:()=>this.loginViaPopup().catch(O=>w.warn(O.message))})})}),T)}(0,be.render)((0,$.jsx)(zt,{store:this.store,customStyles:n,children:(0,$.jsx)(It,{broadcastEvents:this.broadcastEvents,children:(0,$.jsx)(Ec,{})})}),this.createContainer("deepdesk-overlays"));let R;this.inputMediator.on("selection",x=>{clearTimeout(R),x===null?R=setTimeout(()=>{x!==null&&this.store.dispatch(yr(x))},500):this.store.dispatch(yr(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(Xr(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Xr(!0))),this.store.dispatch(Ma({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch($e()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var 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}),(0,be.render)((0,$.jsx)(zt,{store:this.store,customStyles:n,children:(0,$.jsx)(It,{broadcastEvents:this.broadcastEvents,children:(0,$.jsx)(Ku,{onLogIn:()=>this.loginViaPopup().catch(i=>w.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&(0,be.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=ar(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){cp(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Zo());let e=ut(this.state);e&&(await this.store.dispatch(jo()),this.store.dispatch(Rn({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 g=>{var f,m;if((f=g.data)!=null&&f.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((m=g.data)==null?void 0:m.jwt),await this.isLoggedIn(),this.broadcastEvents.send(No),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 g=>{var f;if(g.origin===a.origin)switch((f=g.data)==null?void 0:f.type){case"deepdesk-popup-loaded":{try{let m=JSON.stringify({type:"deepdesk-popup-create-channel"});d==null||d.postMessage(m,a.origin,[s.port2])}catch(m){w.error("Error posting message to popup",m),n(m)}break}case"deepdesk-popup-error":{l(),g.data.message==="Timeout"&&w.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(g.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=Ss(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(Re()):this.store.dispatch(Ie(n))})}catch(n){this.handleError(n)}}};async function bp(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 Cp(t,e,o={}){let n=o.replace?xt(t,o.replace.start,o.replace.end):Co(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 zu=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(zu||{}),ot=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();st(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(zu).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 Vu(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var qt=class extends ot{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),pn(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!Vu(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!Vu(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return un(this.element,e);let o=this.lastKnownSelection;if(o&&Uu(this.element,o.start,o.end))return o;let n=Co(this.element);return n.collapse(!1),un(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return pn(this.element,xt(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 Gt=class extends ot{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 $u(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 Ch(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}var Ii=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()}},Li=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=$u(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()}},Ai=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 Li(e,this.deepdeskUrl,{debug:!0}):new Ii(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=Ch(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)}},qu=Ai;var wo=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var Mi=t=>new Promise(e=>{setTimeout(e,t)});var To=class extends wo{name="ClientError"},Oi=class extends wo{name="ServerError"},Ni=new Map,Ae=class t{constructor(e="",o={}){this.baseUrl=e;this.options=o;o.fetch&&(this.fetch=o.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,o={}){return new Promise((n,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,c=o.method===void 0||o.method.toLowerCase()==="get",{useCache:l=!1,abortLatest:d=!1,attempts:u=1,retryDelay:p=500,refreshTokenOn401:g=!0,retryOnError:f=T=>T instanceof TypeError,retryOnResponse:m=T=>T.status>=500,version:y="v1",...E}=o;if(l)if(c){if(Ni.has(i)){n(Ni.get(i));return}}else throw new Error(`Can't use 'useCache' for ${o.method}`);let S={credentials:"include",...E,headers:{"Content-Type":"application/json",...E.headers}};!c&&this.csrfToken&&(S.headers={...S.headers,"X-CSRFToken":this.csrfToken}),typeof y=="string"&&(S.headers={...S.headers,"X-Deepdesk-API-Version":y});let v=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()=>(v--,a(i,S).then(async T=>m(T)&&!r.isAborted&&v>0?(await Mi(p),x()):T.status===401&&g===!0&&R===!1?(R=!0,await this.refreshToken(),x()):T).catch(async T=>{if(f(T)&&!r.isAborted&&v>0)return await Mi(p),x();throw T}));x().then(T=>T.json().catch(()=>null).then(O=>{T.status>=500?s(new Oi("Server Error",O)):T.status===401?s(new To("Unauthorized",O)):T.status===403?s(new To("Forbidden",O)):T.status===404?s(new To("Not Found",O)):T.status>=400&&s(new To("Bad Request",O)),delete this.latestRequestByUrl[i],l&&Ni.set(i,O),n(O)})).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 wh;(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||={})})(wh||={});function Ys(t){return{...M(t),tags:t.tags}}var nt=class t{constructor(e,o={}){this.options=o;this.client=new Ae(e,{fetch:o.fetch}),this.client.patchFetch(n=>async(s,r)=>{let i=await n(s,r);return this.handleDeepdeskVersionHeaders(i),i})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=await this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(t.exchangeTokenPromise||(t.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),t.exchangeTokenPromise):Promise.resolve()}async createConversation(e){await this.preflight(),w.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...V(e),tags:e.tags},{version:"v2"});return Ys(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null,useCache:!0});return M(o)}async getKnowledgeAssistant(e){let o=await this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{version:null,useCache:!0});return M(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return M(e)}async getAccount(){let e=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return M(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null,useCache:!0});return M(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}`),Ys(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=V(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return Ys(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...V(s),tags:s.tags})),{version:"v2"})).map(s=>Ys(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",V({...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:V({...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 M(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/",V(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}`,V(o),{abortLatest:!0})).map(r=>({...M(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`,V(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 M(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",V(e),{abortLatest:!0});return M(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,V(e),{version:"v2"});return M(o)}async knowledgeAssist(e,o,n,s={}){let r=await this.client.post(`/api/knowledge-assist/assistants/${n}/search`,V({question:e.question,promptInstruction:e.promptInstruction,chatHistory:o.map(i=>({question:i.question,answer:i.answer.answer})),agentId:s.agentId,conversationId:s.conversationId}),{version:"v2"});return M(r)}async requestLoginByEmail(e){let o=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return M(o)}async requestPasswordlessToken(){let e=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return M(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 M(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 M(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 M(o)}async translateMessages(e){let o=await this.client.post("/api/translate",V(e),{version:"v2"});return M(o)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(da);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 gn=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(vr(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,M(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 Th;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(Th||={});var mn=class{constructor(e,o={}){this.apiUrl=e;this.client=new Ae(e,o)}client;streams={};logger=w;async getCustomMessages(e){let o=await this.client.get(`/sessions/${e}/suggestions`);return M(o.suggestions)}async sendCustomMessage(e,o){let n=await this.client.post(`/sessions/${e}/messages`,V(o));return M(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,V(o))}async getAutoflows(e){let o=await this.client.get(`/sessions/${e}/autoflows`);return M(o.autoflows)}async startAutoflowSession(e){let o=await this.client.post("/autoflow-sessions",V(e));return M(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new gn(`${this.apiUrl}/sessions/${e}/events`),this.streams[e].connect()),this.streams[e]}closeStream(e){this.streams[e]||(this.streams[e].disconnect(),delete this.streams[e])}};var nr=require("@reduxjs/toolkit");var ju=require("@reduxjs/toolkit");var Gu={startTime:null,stopTime:null},Wu=(0,ju.createSlice)({name:"handlingTime",initialState:Gu,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(D,()=>Gu)}}),{handlingTimeStart:Xu,handlingTimeStop:er,handlingTimeReset:Zu}=Wu.actions,Qu=Wu.reducer;var Ju=(t={})=>{let e={onAuthError:Jt(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};var or=require("@reduxjs/toolkit");var tr={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var jt=(0,or.createAsyncThunk)("styleSuggestions/getAll",async({text:t},e)=>{var i;let{deepdeskAPI:o}=e.extra,n=e.getState(),{showStyleSuggestions:s}=n.settings,r=(i=n.conversation.current)==null?void 0:i.profileCode;if(!s)return tr.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),Eh=(0,or.createSlice)({name:"styleSuggestions",initialState:tr,reducers:{},extraReducers:t=>{t.addCase(jt.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(jt.rejected,e=>{e.fetchState="error"}).addCase(jt.fulfilled,(e,o)=>{e.fetchState="done",st(e.list,o.payload)||(e.list=o.payload)}).addCase(Rt,e=>{e.list=tr.list}).addCase(D,()=>tr)}}),Yu=Eh.reducer;var ep=(t={})=>{let e,o=!0,n={getStyleSuggestions:jt,debounce:500,...t};return s=>r=>i=>{var g;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(!((g=l.conversation.current)==null?void 0:g.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 kh(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var tp=(t={})=>{let e={getTextSuggestions:Ie,getAutocompleteSuggestions:Qo,debounce:200,check:go,...t},o;return n=>s=>r=>{var m;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=(m=c.conversation.current)==null?void 0:m.id,p=r.type===bs.toString();if(!u||!l&&!d)return a;let{input:{userCommitted:g}}=c;return kh(g,i)&&!p||(clearTimeout(o),!e.check(c))||(o=setTimeout(()=>{let y=eo(c);y===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(y))},p?0:e.debounce)),a}};var op=jt.fulfilled.toString();function Rh(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 np=t=>e=>o=>n=>{var l;if(n.type!==op){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=Rh(s,i);n.type===op&&c.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:c}})};var Ph=(0,nr.combineReducers)({answer:rc,auth:ba,autoflows:_d,conversation:Ea,contentTypes:bl,customMessages:$d,passwordlessToken:Wd,entities:$l,knowledgeAssistant:oc,handlingTime:Qu,info:Ga,input:za,settings:ma,profile:lc,search:Ya,summary:Ql,styleSuggestions:Yu,ui:Fc,rules:Jd,textSuggestions:yc});function sp(t){return(0,nr.configureStore)({reducer:Ph,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),Ju(),tp({debounce:200}),ep({debounce:500}),np(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var Ih=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},Lh=t=>e=>o=>n=>{var a;let s=e.getState(),r=gr("inlineSuggestions")(s);switch(n.type){case Jt.toString():{!n.payload&&t.emit("logout",void 0);break}case Re.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:n.payload}});break;case Q.toString():t.sendEvent(n.payload.name,{conversationId:((a=n.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:n.payload.data});break;case Dn.toString():t.handleKeyDown(n.payload);break;case Rt.toString():t.logSendMessage(n.payload);break;case Hn.toString():t.handleInputChanged(n.payload);break;case Vt.fulfilled.toString():n.isBroadcasted||t.broadcast(br,n,!1),t.emit("cues",n.payload);break;default:break}let i=o(n);switch(n.type){case Rt.toString():t.handleAfterSendMessage(n.payload);break;case Yo.toString():t.onUpdateShowTabHint(n.payload);break;case er.toString():t.logHandlingTime();break;case Ne.toString():{let{start:c,end:l}=s.input.selection;t.emit("select-suggestion",{type:Ih(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:c,end:l}:{start:0,end:l}},{mayApplyChanges:!0}),r&&(e.dispatch(Me([])),e.dispatch($e()));break}case _n.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 Lo.toString():{let c=e.getState(),{text:l,selection:d}=c.input.userCommitted;t.emit("reset",{text:l,selectionAfter:d},{mayApplyChanges:!0});break}case Fn.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 Me.toString():{r&&n.payload.length>0&&e.dispatch(it(0));break}case Ge.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},rp=Lh;function _i(t){return t.toISOString().replace("T"," ").replace("Z","")}function ip(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:_i(o),timeStop:_i(n)}}function ap(t,e,o){var O,q,K;let{text:n,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:c,agentStartedTypingTimestamp:l,externalTimeTotalSeconds:d,pastes:u,cuts:p,deletions:g,textSuggestions:f,offeredTextSuggestions:m}}=e[t],y=n.length,S=f.reduce((A,{text:_,searchTerm:I})=>A+_.length-(I?I.length:0),0),v=l??Date.now(),R=(Date.now()-v)/1e3+(d||0),x=s/R,T=f.reduce((A,{searchTerm:_})=>A+(_?_.length:0),0);return{conversationId:e.conversation.current.id,source:"agent",text:n,clientVersion:o.version,pastes:u,cuts:p,deletions:g,lenTextTyped:s+T,lenTextTotal:y,lenTextAssisted:S,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:R,charsPerSecond:x,numPastes:c,textSuggestionsV2:f,suggestionsCounters:[{source:"gpt",countOffered:m.filter(A=>A.source==="gpt").length}],agentId:(O=e.info.agentInfo)==null?void 0:O.agentId,agentName:(q=e.info.agentInfo)==null?void 0:q.agentName,agentEmail:(K=e.info.agentInfo)==null?void 0:K.agentEmail}}function Di(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return Di(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?Di(s,e):null}function lp(t,e){return Di(t,e)}function cp(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function Ah(t){return typeof t=="object"&&t!==null&&"tagName"in t}function sr(t){return Ah(t)&&(mt(t)||Ls(t))}var dp,Fe=new Map,Mh=["bottom","height","left","right","top","width"],Nh=(t={},e={})=>Mh.some(o=>t[o]!==e[o]);function up(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,...up(e)]:[]}function pp(t,e){return!t||!e?null:{...t,top:t.top+e.top,left:t.left+e.left}}var rr=!1,gp=()=>{rr=!0;let t=[];if(Fe.forEach((e,o)=>{if(!o.isConnected){e.rect=null,t.push(e),Fe.delete(o);return}let n=o.getBoundingClientRect();Nh(n,e.rect)&&(e.rect=n,t.push(e))}),t.forEach(e=>{let o=e.parentRects?e.parentRects.reduce(pp,e.rect):e.rect;e.callbacks.forEach(n=>n(o))}),Fe.size===0){rr=!1;return}dp=window.requestAnimationFrame(gp)};function Hi(t,e){let o=up(t),n=[],s=o.map((r,i)=>Hi(r,a=>{n[i]=a;let c=Fe.get(t);if(!c)return;let l=n.reduce(pp,c.rect);c.callbacks.forEach(d=>d(l))}));return{observe(r=!0){if(s.forEach(i=>i.observe(!1)),Fe.has(t)){let i=Fe.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else Fe.set(t,{rect:void 0,callbacks:[e],parentRects:n});r&&!rr&&gp()},unobserve(){s.forEach(i=>i.unobserve());let r=Fe.get(t);if(r){let i=r.callbacks.indexOf(e);i>=0&&r.callbacks.splice(i,1),r.callbacks.length||Fe.delete(t),Fe.size||(cancelAnimationFrame(dp),rr=!1)}}}}var mp,Be=new Map,fp=()=>{Be.forEach((t,e)=>{if(!e.isConnected){Be.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)))}),Be.size!==0&&(mp=window.requestAnimationFrame(fp))};function hp(t,e){return{observe(){let o=Be.size===0;Be.has(t)?Be.get(t).callbacks.push(e):Be.set(t,{visible:void 0,callbacks:[e]}),o&&fp()},unobserve(){let o=Be.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||Be.delete(t),Be.size||cancelAnimationFrame(mp)}}}}var Fi=["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 Bi(t,e,o){return o.forEach(n=>{e.style[n]=t[n]})}function Eo(t){return parseFloat(t)}function ir(t){return Math.round(t*1e6)}function yp(t){return t/1e6}function Ki(t,e,o){if(t.boxSizing==="content-box")return;let{clientWidth:n}=e,s=Eo(t.width),r=Eo(t.borderLeftWidth),i=Eo(t.borderRightWidth),a=Eo(t.paddingRight),c=yp(ir(s)-ir(r)-ir(i)),l=yp(ir(n));if(c-l>2){let d=c-l;o.style.paddingRight=`${a+d}px`}}function fn(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",Kt(o);let n=window.getComputedStyle(t),s=!0,r=()=>{o.scrollTop=t.scrollTop};Bi(n,o,Fi),Ki(n,t,o),e.mirrorOverflow&&(o.style.overflow="hidden",t.addEventListener("scroll",r));let i=hp(t,()=>{Bi(n,o,Fi),Ki(n,t,o),r(),setTimeout(r,0)}),a,c=!0,l=Hi(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(Bi(n,o,Fi),Ki(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(),g=window.getComputedStyle(e.closestScrollElement),f=Eo(g.borderTopWidth),m=Eo(g.borderBottomWidth),y=p.top+f-u.top,E=u.top+u.height+-(p.top+p.height-m);o.style.clipPath=`inset(${y}px 0px ${E}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 vp=(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 Oh(t){return t.offsetParent!==null}function Sp(t){if(!Oh(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 ar(t,e,o=100){let n=Sp(t);e({isVisible:n});let s=setInterval(()=>{let r=Sp(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}var $=require("react/jsx-runtime");var xp=vp("showTabHint",!0),hn=class t{static version="11.2.1-beta.2";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:c}){let l=e.replace(/\/api$/,"");this.deepdeskApi=new nt(l,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let d={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[rp({broadcast:(u,p,g)=>{this.broadcastEvents.send(u,p,g)},emit:(u,p,g)=>this.emit(u,p,g),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=>xp.update(u),sendEvent:(u,p)=>this.deepdeskApi.sendEvent(u,p)})]};o&&Object.assign(d,{deepdeskBrokerAPI:new mn(o)}),this.store=sp(d),this.broadcastEvents=new qu({debug:!0,deepdeskUrl:l,eventMap:el(this.store),createCustomChannel:c}),this.store.dispatch(Yo(xp.value())),this.store.dispatch(Rn({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(Jt(null)),this.store.dispatch(ze()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();te(n)&&fa(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(ze())).payload}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(o){w.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(fr({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Ln(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(An({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(hr(e))).payload}async postMessages(e){return(await this.store.dispatch(Nn(e))).payload}async updateConversation(e){return(await this.store.dispatch(Mn(e))).payload}resetConversation(){this.store.dispatch(D()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Ge());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(Rn(e))}setVisitorInfo(e){this.store.dispatch(qa(e))}async setAgentInfo(e){await this.store.dispatch(Ao(e))}async setAgentSettings(e){await this.store.dispatch(Sr(e))}async getAgentSettings(){return(await this.store.dispatch(xr())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(bs()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Hn(e))}notifyKeyDown(e){this.store.dispatch(Dn(e))}notifyPaste(e,o){this.store.dispatch(Fa({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Da(e))}notifyExternalSuggestion(e){this.store.dispatch(Ne(e)),this.store.dispatch($e())}async evaluateRule(e,o={}){let{payload:n,error:s}=await this.store.dispatch(Vt({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(pt({collapse:!1})),this.inputMediator&&this.store.dispatch(Aa({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(Me([])))}handleKeyDown(e){let{overlayCollapsed:o}=this.state.ui,{textSuggestions:n,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=n.length>0,c=s!==-1;if(this.store.dispatch(Ha(Pa(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let l=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Na()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},d=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(_a()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Lo()):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(it(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(it(-1)),this.store.dispatch(Lo()),e.preventDefault()):o||(this.store.dispatch(pt({collapse:!0})),this.store.dispatch(Dc(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:u}=this.state.input,p=u.text.substring(0,u.selection.end),{tabCompletionSuggestion:g}=this.state.input;this.store.dispatch(Yo(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&g&&g.text.startsWith(p)&&(this.store.dispatch(Ne({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch($e())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Ba()),this.store.dispatch(Me([]))}handlingTimeStart(){this.state.handlingTime.startTime||(w.info("Start handling time"),this.store.dispatch(Xu()))}handlingTimeStop(){this.state.handlingTime.startTime&&(w.info("Stop handling time"),this.store.dispatch(er()))}logSendMessage(e){let o=ap("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=ip(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Zu())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch($e()),this.store.dispatch(Rt(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(Ne({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]=fn(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{(0,be.unmountComponentAtNode)(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,c]=fn(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{(0,be.unmountComponentAtNode)(s),c()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Kt(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{(0,be.unmountComponentAtNode)(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),w.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(w.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Ua(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(!sr(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:g,inputMediator:f,closestScrollSelector:m,appendOverlayTo:y,inlineSuggestions:E,floatingMenu:S}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:c,showSuggestionsBeforePattern:l,showSuggestionsAfterPattern:d,showTextSuggestions:i,insertLink:g,isEmbedded:u,inlineSuggestions:E,floatingMenu:!!S}),o.automaticHandlingTime&&this.setupHandlingTime(e),Kt(e),this.inputMediator=f||(mt(e)?new Gt(e):new qt(e)),this.inputMediator.on("change",({plainText:x})=>{this.notifyInputChanged(x)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Ka({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 v=m&&lp(e,m)||void 0;if(E){let{customStyles:x,appendOverlayTo:T}=o;if(mt(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let O=this.createInlineContainer(e,"deepdesk-caret");(0,be.render)((0,$.jsx)(zt,{store:this.store,customStyles:x,children:(0,$.jsx)(It,{broadcastEvents:this.broadcastEvents,children:(0,$.jsx)(qc,{})})}),O),this.inputMediator.on("caret",K=>{this.store.dispatch(Me([])),K?(O.style.display="block",O.style.top=`${K.top}px`,O.style.left=`${K.left}px`):O.style.display="none"});let q=this.overlayContainerFactory("floating-menu",v||e,{appendTo:typeof S=="object"&&"appendOverlayTo"in S?S.appendOverlayTo:T},x==null?void 0:x.floatingMenuRootNode);(0,be.render)((0,$.jsx)(zt,{store:this.store,customStyles:x,children:(0,$.jsx)(It,{broadcastEvents:this.broadcastEvents,children:(0,$.jsx)(Mc,{onLogIn:()=>this.loginViaPopup().catch(K=>w.warn(K.message))})})}),q)}else{let x=this.overlayContainerFactory("deepdesk-tab-completion",v||e,{appendTo:y,closestScrollElement:v,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),T=this.overlayContainerFactory("deepdesk-suggestions-overlay",v||e,{appendTo:y},n==null?void 0:n.suggestionsRootNode);(0,be.render)((0,$.jsx)(zt,{store:this.store,customStyles:n,children:(0,$.jsx)(It,{broadcastEvents:this.broadcastEvents,children:(0,$.jsx)(Id,{inputElement:e})})}),x),(0,be.render)((0,$.jsx)(zt,{store:this.store,customStyles:n,children:(0,$.jsx)(It,{broadcastEvents:this.broadcastEvents,children:(0,$.jsx)(od,{onLogIn:()=>this.loginViaPopup().catch(O=>w.warn(O.message))})})}),T)}(0,be.render)((0,$.jsx)(zt,{store:this.store,customStyles:n,children:(0,$.jsx)(It,{broadcastEvents:this.broadcastEvents,children:(0,$.jsx)(Ec,{})})}),this.createContainer("deepdesk-overlays"));let R;this.inputMediator.on("selection",x=>{clearTimeout(R),x===null?R=setTimeout(()=>{x!==null&&this.store.dispatch(yr(x))},500):this.store.dispatch(yr(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(Xr(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Xr(!0))),this.store.dispatch(Ma({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch($e()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var 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}),(0,be.render)((0,$.jsx)(zt,{store:this.store,customStyles:n,children:(0,$.jsx)(It,{broadcastEvents:this.broadcastEvents,children:(0,$.jsx)(Ku,{onLogIn:()=>this.loginViaPopup().catch(i=>w.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&(0,be.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=ar(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){cp(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Zo());let e=ut(this.state);e&&(await this.store.dispatch(jo()),this.store.dispatch(Rn({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 g=>{var f,m;if((f=g.data)!=null&&f.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((m=g.data)==null?void 0:m.jwt),await this.isLoggedIn(),this.broadcastEvents.send(No),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 g=>{var f;if(g.origin===a.origin)switch((f=g.data)==null?void 0:f.type){case"deepdesk-popup-loaded":{try{let m=JSON.stringify({type:"deepdesk-popup-create-channel"});d==null||d.postMessage(m,a.origin,[s.port2])}catch(m){w.error("Error posting message to popup",m),n(m)}break}case"deepdesk-popup-error":{l(),g.data.message==="Timeout"&&w.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(g.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=Ss(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(Re()):this.store.dispatch(Ie(n))})}catch(n){this.handleError(n)}}};async function bp(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 Cp(t,e,o={}){let n=o.replace?xt(t,o.replace.start,o.replace.end):Co(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?xt(t,o.selectionAfter.start,o.selectionAfter.end):(n.collapse(!1),n),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(i)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}function _h(t){let e=document.createElement("template");return e.innerHTML=t.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),e.content}function Dh(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 wp(t,e){return!t.contains(e)||e===t?null:e.parentNode===t?e:wp(t,e.parentNode)}async function Tp(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?_h(e):Dh(e);if(o){let d=c.startContainer===t?t.childNodes[c.startOffset]:c.startContainer,u=wp(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 Ep(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function kp(t,e,o){await new nt(t).authenticateWithKey(e,o)}async function Rp(t){let o=await new Ae(t).get("/platform/config/",{version:null,useCache:!0});return M(o)}async function Hh(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 Pp(t,e){let o=await Hh(e),n=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[o]}),t.dispatchEvent(n)}finally{Object.hasOwn(t,"files")&&delete t.files}}0&&(module.exports={Card,ContentEditableInput,DeepdeskAPI,DeepdeskSDK,HTTPClient,InputMediator,InputType,KeyboardHint,Label,Locale,Section,SectionList,Sources,Suggestion,SuggestionList,TextAreaInput,ToggleButton,attachFile,authenticateWithKey,createFullRange,createOverlayContainer,createRangeFromOffsets,escapeHTML,fetchPlatformConfig,formatTextMarkup,getRangeOffsets,getRangeText,insertCKEditor,isHTML,isSupportedInputElement,updateContentEditable,updateTextArea,useStyles,waitForElementVisibilityChange});
|