@deepdesk/deepdesk-sdk 11.1.1-beta.4 → 11.1.1-beta.5
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 +6 -2
- package/dist/index.d.ts +6 -2
- package/dist/index.esm.js +1 -1
- package/dist/index.iife.js +1 -1
- package/package.json +1 -1
package/dist/index.iife.js
CHANGED
|
@@ -23,7 +23,7 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
|
23
23
|
c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});var wh=w(b()),XO={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},fC=({className:e,color:t})=>(0,wh.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,wh.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:XO[t||"pink"]})});var pC={root:"j",text:"Y",isLoggedIn:"ei",isLoggedOut:"no",icon:"ii",logo:"ri",lock:"ti"};var xh={};Qe(xh,{enUS:()=>ZO,nlNL:()=>JO});var ZO={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},JO={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Do=w(b()),gC=({onLogIn:e})=>{let t=G(xh),n=j("floatingMenu"),r=j("productName"),o=Y(),i=O(tt),s=A("FloatingMenu",pC);if(i===null||n===!1)return null;let a=()=>{i===!0?o(xt(!0)):e()};return(0,Do.jsxs)("button",{className:(0,mC.default)(s.root,{[s.isLoggedIn]:i,[s.isLoggedOut]:!i}),onClick:a,children:[(0,Do.jsx)("div",{className:s.text,children:t(i?"search":"signin",{productName:r})}),(0,Do.jsxs)("div",{className:s.icon,children:[(0,Do.jsx)(fC,{className:s.logo,color:"pink"}),i===!1&&(0,Do.jsx)(dC,{className:s.lock})]})]})};var Od=w(D());var hC=w(D());function Zi(e){(0,hC.useEffect)(()=>{let t=n=>{n.isWithinRoot||e(n)};return document.body.addEventListener("mouseup",t),()=>{document.body.removeEventListener("mouseup",t)}},[e])}function Fo(e){e.addEventListener("mouseup",t=>{t.isWithinRoot=!0},!0)}function Ji(e){let{showMidSentenceSuggestions:t,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:r}=e.settings,{text:o,selection:i}=e.input.userCommitted;return i.start!==i.end?!1:i.end>=o.length?!0:t?n&&new RegExp(n).test(o.substring(i.end))||r&&new RegExp(r).test(o.substring(0,i.end))?!0:n===!1&&r===!1:!1}var eN={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var Ad=({ui:e})=>e.overlayCollapsed;var yC=W({name:"ui",initialState:eN,reducers:{setShowTabHint(e,t){e.showTabHint=t.payload},setInputHasFocus(e,t){e.overlayCollapsedUserOverwrite!==!0&&(t.payload===!0&&(e.overlayCollapsed=!1),e.inputHasFocus=t.payload)},setOverlayCollapsed(e,t){t.payload.collapse===!1&&(e.openOverlayWhenTyping=!1),!(t.payload.skipWhenInputFocus&&e.inputHasFocus)&&(e.overlayCollapsed=t.payload.collapse)},setOpenOverlayWhenTyping(e,t){e.openOverlayWhenTyping=t.payload},setOverlayCollapsedUserOverwrite(e,t){e.overlayCollapsedUserOverwrite=t.payload,e.overlayCollapsed=t.payload}}}),{setShowTabHint:Za,setInputHasFocus:Eh,setOverlayCollapsed:zr,setOpenOverlayWhenTyping:vC,setOverlayCollapsedUserOverwrite:SC}=yC.actions,wC=yC.reducer;var Ld=w(D());var es=w(D());var xC=w(D());function EC(e,t,n){(0,xC.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var CC={root:"ni",actions:"ai",badge:"pi",formattedText:"ao"};var Ho=w(b()),rN=["search","personal-collection-search","search-autocomplete"];function oN(e,t,n,r={}){let o="";return rN.includes(t)?o=mE(uh(e,n,{stripAgentPart:!0}),r.searchKeywords??[n]):o=uh(e,n,r),r.placeholders===!0&&(o=gE(o)),o}var iN=()=>{},sN=({index:e,selected:t,suggestion:n,onFeedback:r})=>{let o=j("inlineSuggestions"),i=O(Vi),s=Y(),a=A("TextSuggestion",CC),l=(0,es.useRef)(null);(0,es.useEffect)(()=>{let c=setTimeout(()=>{s(m1({text:n.text,suggestion:n}))},500);return()=>{clearTimeout(c)}},[n]),EC(l,"click",()=>{s(_r(e)),s(Cn({suggestion:n,text:n.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let u=(0,es.useMemo)(()=>oN(n.text,n.source,i,{stripAgentPart:o,placeholders:!0,searchKeywords:n.searchKeywords}),[o,n.text,n.source,i,n.searchKeywords]);return n.source==="gpt"&&!o?null:(0,Ho.jsxs)("div",{className:a.root,onMouseEnter:()=>s(_r(e)),children:[(0,Ho.jsx)(oe,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:t,onClick:iN,children:(0,Ho.jsx)($i,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:u})}),t&&r&&(0,Ho.jsx)("div",{className:a.actions,children:(0,Ho.jsx)(xd,{onFeedback:()=>r(n),suggestion:n.text})})]})},bC=sN;var Ch=w(b()),aN=({onFeedback:e,suggestions:t,selectedIndex:n,reverse:r})=>{let o=(0,Ld.useMemo)(()=>{let i=t.map((s,a)=>(0,Ch.jsx)(bC,{index:a,selected:a===n,suggestion:s,onFeedback:e},`${s.text}-${s.source}`));return r?i.reverse():i},[t,n,r]);return(0,Ch.jsx)(Ld.Fragment,{children:o})},Id=aN;var TC={root:"di",paper:"li"};var Ja=w(b()),uN=({textSuggestions:e,selectedIndex:t})=>{let n=(0,Od.useRef)(null),r=A("InlineSuggestionsOverlay",TC),o=O(Ji),i=Y(),s=O(tt),a=O(zi),l=O(Ad),u=j("showTextSuggestions");return Zi(()=>{setTimeout(()=>{i(zr({collapse:!0,skipWhenInputFocus:!0}))})}),(0,Od.useEffect)(()=>{let c=n.current;if(!c||!c.parentElement)return;c.parentElement.style.left="0px";let f=c.getBoundingClientRect();c.parentElement.style.left=`${Math.min(window.innerWidth-4-f.right,0)}px`}),l||!o||!u||e.length===0||s!==!0||a===!1?null:(0,Ja.jsx)("div",{className:r.root,"data-variant":"inline",children:(0,Ja.jsx)("div",{ref:n,className:r.paper,children:(0,Ja.jsx)(ht,{children:(0,Ja.jsx)(Id,{suggestions:e,selectedIndex:t})})})})},cN=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),kC=jn(cN)(uN);var el=w(b()),dN=({children:e})=>{let n=j("locale").replace("-","");return(0,el.jsx)(Gg.Provider,{value:n,children:e})},fN=({store:e,customStyles:t={},children:n})=>(0,el.jsx)(Pg,{store:e,children:(0,el.jsx)(dN,{children:(0,el.jsx)(hs.Provider,{value:t,children:n})})}),Uo=fN;var Md=w(te()),ts=w(D());var PC=w(D());function RC(e,t){let[n,r]=(0,PC.useState)(()=>{if(typeof window>"u")return t;try{let i=window.localStorage.getItem(e);return i?JSON.parse(i):t}catch(i){return K.error(i),t}});return[n,i=>{try{let s=i instanceof Function?i(n):i;r(s),typeof window<"u"&&window.localStorage.setItem(e,JSON.stringify(s))}catch(s){K.error(s)}}]}var AC=()=>/Mac/i.test(navigator.platform);var IC=w(te()),Xn=w(D());var bh={};Qe(bh,{enUS:()=>pN,nlNL:()=>mN});var pN={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"}]}]},mN={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 LC={root:"si",anchor:"ci",anchorButton:"xi"};var Vr=w(b()),Th=(e,t,n)=>r=>(0,Vr.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),hN=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r,onLogIn:o})=>{let i=G(bh),s=zt(),a=A("Login",LC),l=j("productName"),u=(0,Xn.useCallback)(p=>{p.preventDefault(),r&&r(parseInt(p.target.value,10))},[]),c=(0,Xn.useCallback)(p=>{p.preventDefault(),s.send(Ki,!0)},[t]),f=(0,Xn.useMemo)(()=>p=>(0,Vr.jsx)("a",{onClick:h=>{h.preventDefault(),o()},href:t,className:a.anchor,target:"_blank",rel:"noreferrer",children:p},"login"),[t]),d=(0,Xn.useCallback)(p=>(0,Vr.jsx)("button",{type:"button",className:a.anchorButton,onClick:c,children:p},"prompt"),[c]),{min:m,hour:y,day:v}=(0,Xn.useMemo)(()=>({min:Th(a,60*10,u),hour:Th(a,60*60,u),day:Th(a,60*60*12,u)}),[]);return(0,Vr.jsxs)("div",{className:(0,IC.default)(e,a.root),children:[i("loginPlease",{login:n?d:f,productName:l}),r&&(0,Vr.jsxs)(Xn.Fragment,{children:[(0,Vr.jsx)("br",{}),i("snooze",{min:m,hour:y,day:v})]})]})},Nd=hN;var OC={root:"po",text:"fi"};var tl=w(b()),vN=({title:e})=>{let t=A("SearchTrigger",OC),n=Y();return(0,tl.jsxs)("button",{type:"button",className:t.root,onClick:()=>n(xt(!0)),children:[(0,tl.jsx)(qi,{}),(0,tl.jsx)("span",{className:t.text,children:e})]})},NC=vN;var kh={};Qe(kh,{enUS:()=>SN,nlNL:()=>wN});var SN={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"}]},wN={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 MC={root:"gi",isInline:"q",toggleButton:"bi",toggleButtonWrapper:"C",toggleButtonWrapperHidden:"hi",isCollapsed:"do",collapsible:"mi",hints:"lo",hintsHidden:"ui",triggers:"so",triggersRight:"yi"};var Se=w(b()),EN=({textSuggestions:e,selectedIndex:t,onLogIn:n})=>{let r=A("SuggestionsOverlay",MC),o=G(kh),i=O(Ji),s=c1(),a=Y(),l=(0,ts.useRef)(null),u=j("searchTriggerKey"),c=j("productName"),f=O(Ad),d=O(tt),m=O(zi),[y,v]=(0,ts.useState)(null),p=j("showSearch"),g=j("showTextSuggestions"),h=j("adminUrl"),S=j("isEmbedded"),[x,T]=RC("dd-snooze-until-ms",0),C=f||x>Date.now(),k=O(_=>_.input.text),L=e.filter(_=>_.source!=="gpt").length,I=()=>{C&&T(0),a(SC(!C))},N=_=>{a(Ye({name:"suggestion feedback",data:{text:_.text,source:"overlay",context:k},options:{includeConversationData:!0}}))},z=_=>{let J=Date.now()+_*1e3;T(J),K.info(`Snooze until: ${new Date(J)}`),a(zr({collapse:!0}))};return(0,ts.useEffect)(()=>{L===0&&v(null)},[e,L]),Zi(()=>{a(zr({collapse:!0,skipWhenInputFocus:!0}))}),d===null||m===!1?null:d===!1?(0,Se.jsxs)("div",{ref:l,className:(0,Md.default)(r.root,{[r.isCollapsed]:C}),children:[!C&&(0,Se.jsxs)("div",{className:r.triggers,children:[(0,Se.jsx)("div",{style:{flex:1}}),(0,Se.jsx)("div",{className:r.triggersRight,children:(0,Se.jsx)(ro,{className:r.toggleButton,title:o("collapse"),onClick:I,isCollapsed:!1})})]}),(0,Se.jsx)("div",{className:r.toggleButtonWrapper,children:(0,Se.jsx)(ro,{className:r.toggleButton,title:o("open",{productName:c}),onClick:I,isCollapsed:!0})}),(0,Se.jsx)("div",{className:r.collapsible,children:(0,Se.jsx)(Nd,{loginUrl:h,isEmbedded:S,onLogIn:n,onSnooze:z})})]}):!s||!i?null:(0,Se.jsxs)("div",{ref:l,className:(0,Md.default)(r.root,{[r.isCollapsed]:C}),children:[!C&&(0,Se.jsxs)("div",{className:r.triggers,children:[(0,Se.jsx)("div",{style:{flex:1},children:p&&(0,Se.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>v(o(AC()?"searchHintMac":"searchHintWindows",{searchTriggerKey:u.toUpperCase()})),onMouseLeave:()=>v(null),children:(0,Se.jsx)(NC,{title:o("search")})})}),(0,Se.jsxs)("div",{className:r.triggersRight,onFocus:()=>{},children:[(0,Se.jsx)("div",{className:(0,Md.default)(!y&&r.hintsHidden,r.hints),children:y}),(0,Se.jsx)(ro,{className:r.toggleButton,title:o("collapse"),onClick:I,isCollapsed:!1})]})]}),(0,Se.jsx)("div",{className:r.toggleButtonWrapper,children:(0,Se.jsx)(ro,{className:r.toggleButton,title:o("open",{productName:c}),onClick:I,isCollapsed:!0})}),L>0&&g&&(0,Se.jsx)("div",{className:r.collapsible,onFocus:()=>{},children:(0,Se.jsx)(ht,{children:(0,Se.jsx)(Id,{onFeedback:N,suggestions:e,selectedIndex:t,reverse:!0})})})]})},CN=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),_C=jn(CN)(EN);var Yd=w(te());var Jn=w(D());var ns=w(D());function _d(e){return e.contentEditable==="true"}function bN(e){let t=0,n=0,r=window.getSelection();if(r.rangeCount!==0){let o=r.getRangeAt(0),i=o.cloneRange();i.selectNodeContents(e),i.setEnd(o.endContainer,o.endOffset),n=i.toString().length,i.selectNodeContents(e),i.setEnd(o.startContainer,o.startOffset),t=i.toString().length}return{selectionStart:t,selectionEnd:n}}function DC(e){let{selectionStart:t,selectionEnd:n}=_d(e)?bN(e):e;return[t,n]}function FC(e){let[,t]=(0,ns.useState)(),n=(0,ns.useRef)(null);return n.current=DC(e),(0,ns.useEffect)(()=>{let r=()=>{let[o,i]=n.current??[],s=DC(e);(!s||o!==s[0]||i!==s[1])&&(n.current=s,t({}))};return e.addEventListener("keyup",r),e.addEventListener("click",r),e.addEventListener("focus",r),document.addEventListener("selectionchange",r),()=>{e.removeEventListener("keyup",r),e.removeEventListener("click",r),e.removeEventListener("focus",r),document.removeEventListener("selectionchange",r)}},[e]),n.current}function HC(e,t){if(!t)return;let n=e,{value:r}=n,[o,i]=t,s=r.match(Hl);if(!s||s.length===0)return;let a=0;s.find(l=>{let u=r.indexOf(l,a);return o>u&&i<u+l.length?(n.selectionStart=u,n.selectionEnd=u+l.length,!0):(a=u+l.length,!1)})}var UC=w(D()),TN=["div","span","mark","strong","b","i","u","em"];function Ph(e,t,n=0){var i;let r=e[e.length-1],o=typeof r=="object"&&r!==null?(i=r.props)==null?void 0:i.tagName:void 0;if(o==="br")return e.pop(),[...e,...t,r];if(TN.includes(o)){let s=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,UC.cloneElement)(r,{children:Ph(s,t,n+1)})]}return[...e,...t]}function Kr(e){return e.tagName.toLowerCase()==="textarea"}var cn={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 YC=w(te());var Kd=w(D());var rs=w(D());function BC(e,t){let n;return[(...r)=>{window.cancelAnimationFrame(n);let o=t?t(...r):r;n=window.requestAnimationFrame(()=>{e(...o)})},()=>window.cancelAnimationFrame(n)]}function Dd(e){let t=(0,rs.useRef)(null),[n,r]=(0,rs.useState)(!1);return(0,rs.useEffect)(()=>{let o=!1,i=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[s,a]=BC((c,f)=>{let d=t.current;if(!d)return;let m=c/i,y=f/i,v=d.getBoundingClientRect(),p=m>v.x&&m<v.x+v.width&&y>v.y&&y<v.y+v.height;p&&!o?(o=!0,r(!0)):!p&&o&&(o=!1,r(!1))},({clientX:c,clientY:f})=>[c,f]),[l,u]=BC(()=>{o=!1,r(!1)});return e.addEventListener("mousemove",s),e.addEventListener("mouseleave",l),()=>{a(),u(),e.removeEventListener("mousemove",s),e.removeEventListener("mouseleave",l)}},[t]),[t,n]}function jC(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Fd(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function zC(e){return e!=null}var Ah=w(te()),Kt=w(D());var Hd=w(D()),PN=["bottom","height","left","right","top","width"],RN=(e={},t={})=>PN.some(n=>e[n]!==t[n]),Qn=new Map,VC,KC=()=>{let e=[],t=[];Qn.forEach((n,r)=>{if(r instanceof Element&&!r.isConnected){t.push(r);return}let o=r.getBoundingClientRect();RN(o,n.rect)&&(n.rect=o,e.push(n))}),t.forEach(n=>{Qn.delete(n)}),e.forEach(n=>{n.callbacks.forEach(r=>r(n.rect))}),VC=window.requestAnimationFrame(KC)};function AN(e,t){return{observe(){let n=Qn.size===0;if(Qn.has(e)){let r=Qn.get(e);r.callbacks.push(t),r.rect&&t(r.rect)}else Qn.set(e,{rect:void 0,hasRectChanged:!1,callbacks:[t]});n&&KC()},unobserve(){let n=Qn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Qn.delete(e),Qn.size||cancelAnimationFrame(VC)}}}}function Rh(e){let[t,n]=(0,Hd.useState)(null);return(0,Hd.useLayoutEffect)(()=>{if(!e.current)return;let r=AN(e.current,o=>{n(o)});return r.observe(),()=>{r.unobserve()}},[e]),t}var os=w(D()),WC=w(Qu());var $C={root:"Hi"};var qC=({children:e,parentNode:t})=>{let[n,r]=(0,os.useState)(null),o=(0,os.useContext)(hs);return(0,os.useLayoutEffect)(()=>{let i=document.createElement("div");return Fo(i),i.classList.add($C.root),o!=null&&o.portalRootNode&&i.classList.add(o==null?void 0:o.portalRootNode),(t||document.body).appendChild(i),r(i),()=>{i.isConnected&&i.remove()}},[]),n?(0,WC.createPortal)(e,n):null};var bn={ref:"Li",root:"o",positionAbove:"l",positionBelow:"s",positionLeft:"c",positionRight:"x",alignStart:"f",alignCenter:"g",alignEnd:"b"};var Ud=w(b()),Bd=(e=!1)=>{let[t,n]=(0,Kt.useState)(e),r=(0,Kt.useCallback)(()=>n(!0),[]),o=(0,Kt.useCallback)(()=>n(!1),[]),i=(0,Kt.useCallback)(()=>n(a=>!a),[]),s=(0,Kt.useRef)(null);return{opened:t,open:r,close:o,toggle:i,triggerRef:s}};function Lh(e,t=null,n=0){if(!e)return{display:"none"};let r=t?e.top-t.top<0||e.top<t.top-n?t.top-n:e.top+e.height>t.top+t.height+n?t.top+t.height+n-e.height:e.top:e.top,o=t?e.left<t.left-n?t.left-n:e.left+e.width>t.left+t.width+n?t.left+t.width+n-e.width:e.left:e.left;return{top:r,left:o,height:e.height,width:e.width}}var is=({className:e,triggerRef:t,boundaryRef:n=(0,Kt.createRef)(),position:r="above",align:o="center",children:i,toStyle:s=Lh,parentNode:a,...l})=>{let u=Rh(t),c=Rh(n),f=(0,Kt.useMemo)(()=>s(u,c,0),[u,c]);return(0,Ud.jsx)(qC,{parentNode:a,children:(0,Ud.jsx)("div",{className:(0,Ah.default)(bn.ref,{[bn.positionAbove]:r==="above",[bn.positionBelow]:r==="below",[bn.positionLeft]:r==="left",[bn.positionRight]:r==="right",[bn.alignStart]:o==="start",[bn.alignCenter]:o==="center",[bn.alignEnd]:o==="end"}),style:f,...l,role:"dialog",children:(0,Ud.jsx)("div",{className:(0,Ah.default)(e,bn.root),children:i})})})};var GC=w(te()),jd=w(D());var Ih=w(b()),zd=(0,jd.forwardRef)(({className:e,children:t,...n},r)=>{let o=(0,jd.useRef)(null),i=A("TabCompletion",cn);return(0,Ih.jsx)("div",{ref:Fd([o,r]),className:(0,GC.default)(e,i.popoverContentContainer),...n,children:(0,Ih.jsx)("div",{className:i.popoverContent,children:t})})});var $r=w(b()),ON=e=>t=>{let n=Lh(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},NN=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let i=A("TabCompletion",cn),s=Bd(),a=(0,Kd.useMemo)(()=>ON(e.getBoundingClientRect()),[e]),[l,u]=Dd(e);return(0,Kd.useEffect)(()=>{u?s.open():s.close()},[u]),(0,$r.jsxs)("span",{children:[(0,$r.jsx)("mark",{ref:Fd([l,s.triggerRef]),className:(0,YC.default)(i.matchKeyword,{[i.hover]:u}),"aria-haspopup":"dialog","aria-expanded":s.opened?"true":"false",children:r}),s.opened&&(0,$r.jsx)(is,{className:i.popover,triggerRef:s.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,$r.jsx)(zd,{style:n,children:(0,$r.jsx)("div",{className:i.hintText,children:o})})})]})},Vd=class extends $n{keywordMatches=[];preparedKeywordMatches=[];usedKeywordMatches=new Set;onBeforeParse(t,n){return n.keywordMatches&&n.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=n.keywordMatches.map(r=>({...r,keywordRegex:new RegExp(`\\b${jC(r.keyword)}\\b`,"i")})),this.keywordMatches=n.keywordMatches),this.usedKeywordMatches.clear(),t}match(t){let n=this.preparedKeywordMatches.map(o=>{if(this.usedKeywordMatches.has(o))return null;let i=t.match(o.keywordRegex);if(!i)return null;let s=t.charAt(i.index-1),a=t.charAt(i.index+o.keyword.length);return s==="{"&&a==="}"?null:{index:i.index,length:i[0].length,match:i[0],matchString:i[0],suggestion:o.suggestion,preparedKeywordMatch:o,valid:!0}}).filter(zC);if(n.length===0)return null;let r=n.reduce((o,i)=>i.index<o.index?i:o);return this.usedKeywordMatches.add(r.preparedKeywordMatch),r}replaceWith(t,n){return(0,$r.jsx)(NN,{inputElement:n.inputElement,suggestion:n.suggestion,inputStyle:n.inputStyle,boundaryRef:n.boundaryRef,children:t},`keyword_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var XC=w(te());var Oh=w(b()),MN=({inputElement:e,children:t})=>{let n=A("TabCompletion",cn),[r,o]=Dd(e);return(0,Oh.jsx)("mark",{ref:r,className:(0,XC.default)(n.matchPlaceholder,{[n.hover]:o}),children:t})},$d=class extends $n{match(t){let n=t.match(/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\}(?!\}))/);return n?{index:n.index,length:n[0].length,match:n[0],matchString:n[0],valid:!0}:null}replaceWith(t,n){return(0,Oh.jsx)(MN,{inputElement:n.inputElement,children:t},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var qd=w(te());var rt=w(D());var Nh=w(b()),QC=()=>(0,Nh.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,Nh.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 Wr=w(D());var JC=w(Jg());var ZC={root:"Mi",content:"Ri"};function Wd(e,t,n){var o;let r=((o=e.imageSizes)==null?void 0:o[t])||e.image||n;if(!r)return null;try{return new URL(r).toString()}catch{return null}}function Mh(e){return e.replace("https://www.","").replace("https://","")}var $t=w(b()),DN=3,FN=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),HN=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=DN})=>{let i=A("LinkSearch",ZC),[s,a]=(0,Wr.useState)(""),l=Y(),u=O(JE("url")),c=O(I1("URL",FN)),[f,d]=(0,Wr.useState)(c.length-1),m=j("fallbackImage"),y=h=>{let S=h.target;a(S.value)},v=(h,S)=>{h.stopPropagation(),h.preventDefault(),window.open(S,"_blank")},p=h=>{var T;let S=f-1<0?c.length-1:f-1,x=f+1===c.length?0:f+1;h.code==="Escape"&&(a(""),t()),h.code==="ArrowUp"&&d(S),h.code==="ArrowDown"&&d(x),h.code==="Enter"&&e(((T=c[f])==null?void 0:T.text)||s)},g=(0,Wr.useCallback)((0,JC.default)(h=>{l(Co({query:h,type:"URL",tags:["link-search"]}))},300),[]);return(0,Wr.useEffect)(()=>{s&&g(s)},[s]),(0,Wr.useEffect)(()=>()=>{l(qc())},[]),(0,$t.jsxs)("div",{className:i.root,children:[(0,$t.jsx)(ht,{withDivider:!0,children:(s?c:u).slice(0,o).map((h,S)=>(0,$t.jsx)(oe,{selected:f===S,onClick:()=>e(h.text),"data-testid":"linksearch-suggestion",children:(0,$t.jsxs)(fe,{children:[(0,$t.jsx)(fe.Image,{src:Wd(h,"small",m||void 0),title:h.title||h.text}),(0,$t.jsxs)(fe.Content,{className:i.content,cropText:!0,children:[(0,$t.jsx)(fe.Title,{children:h.title||Mh(h.text)}),h.title&&Mh(h.text)]}),(0,$t.jsx)(oe.Actions,{children:(0,$t.jsx)(oe.ActionButton,{label:r,onClick:x=>v(x,h.text)})})]})},h.text))}),(0,$t.jsx)(_a,{value:s,onChange:y,autoFocus:!0,placeholder:n,onKeyUp:p})]})},eb=HN;var _h={};Qe(_h,{enUS:()=>UN,nlNL:()=>BN});var UN={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},BN={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var nt=w(b()),jN=(0,rt.forwardRef)((e,t)=>{let n=A("TabCompletion",cn);return(0,nt.jsx)("mark",{ref:t,className:(0,qd.default)(n.matchSelection)},"selection-start")}),zN=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let i=G(_h),s=A("TabCompletion",cn),a=(0,rt.useRef)(null),l=(0,rt.useRef)(null),[u,c]=(0,rt.useState)(null),f=Y(),d=Bd(document.activeElement===r),[m]=(0,rt.useState)(()=>document.createRange());d.triggerRef.current=m,(0,rt.useEffect)(()=>()=>m.detach(),[]),(0,rt.useEffect)(()=>{let v=e.current,p=a.current;!v||!p||(m.setStart(v,0),m.setEnd(p,0))},[e.current,a.current]),Zi(()=>{d.close()});let y=(0,rt.useCallback)(v=>{let p=m.toString(),g=/^http(s?):\/\//.test(v)?v:`https://${v}`;f(zc({text:`[${p}](${g})`,replace:"selection"}))},[]);return(0,nt.jsxs)("span",{children:[(0,nt.jsx)("mark",{ref:a,className:(0,qd.default)(s.matchSelection),"aria-haspopup":"dialog","aria-expanded":d.opened?"true":"false",children:o}),d.opened&&(0,nt.jsx)(is,{className:s.popoverRoot,triggerRef:d.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,nt.jsxs)(zd,{style:n,ref:l,children:[(0,nt.jsx)("div",{className:(0,qd.default)(s.selectionOptions,{[s.selectionOptionsIsHidden]:u!==null}),children:(0,nt.jsxs)("button",{type:"button",tabIndex:u===null?-1:void 0,className:s.selectionOptionsButton,onClick:()=>c("insertLink"),children:[(0,nt.jsx)(QC,{}),(0,nt.jsx)("span",{children:"\xA0"}),(0,nt.jsx)("span",{children:i("insertLink")})]})}),u==="insertLink"&&(0,nt.jsx)(eb,{placeholder:i("linkInputPlaceholder"),visitUrlText:i("visitUrl"),onSelectLink:y,onDismiss:()=>{c(null),d.close()}})]})})]},"selection-end")},Gd=class extends $n{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(t,n){return this.props=n,this.charCount=0,this.startRef=(0,rt.createRef)(),this.foundIndex=0,t}match(t){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[n,r]=this.props.selection;if(n===r)return null;let o=this.foundIndex===0?n:r,i=o>=this.charCount&&o<=this.charCount+t.length?{index:o-this.charCount,length:0,match:"",valid:!0}:null;i&&this.foundIndex++;let s=this.foundIndex===1;return i&&s?this.charCount+=o-this.charCount:this.charCount+=t.length,i?{isStart:s,...i}:null}replaceWith(t,n){return n.isStart?(0,nt.jsx)(jN,{ref:this.startRef}):(0,nt.jsx)(zN,{inputElement:n.inputElement,startRef:this.startRef,boundaryRef:n.boundaryRef,inputStyle:n.inputStyle})}asTag(){return"mark"}};var Zn=w(b()),VN=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:i,keywordMatches:s,inputElement:a,source:l})=>{let u=A("TabCompletion",cn),c=j("insertLink"),f=j("showMidSentenceSuggestions"),d=j("inlineSuggestions"),m=FC(a),y=(0,Jn.useRef)(null),v=O(tt);(0,Jn.useEffect)(()=>{Kr(a)&&m&&HC(a,m)},[m]);let p=(0,Jn.useCallback)(S=>{if(!o||!n)return S;let x=[(0,Zn.jsx)("span",{className:u.resetIndent,children:"\u200B"},"u200B"),(0,Zn.jsx)("span",{"data-testid":"tab-completion",className:(0,Yd.default)(u.tabText,u.resetIndent),"data-source":l,children:n},"tabText")];return r&&x.push((0,Zn.jsx)("span",{className:(0,Yd.default)(u.hint,u.resetIndent),children:(0,Zn.jsx)(Ml,{keyCode:"tab"},"tabHint")})),Ph(S,x)},[o,n,r]),g=(0,Jn.useMemo)(()=>{let S=[];return c&&S.push(new Gd("selection")),S.push(new $d("placeholders")),i&&S.push(new Vd("keywords")),S},[d,c,i]),h=(0,Jn.useMemo)(()=>{let S=window.getComputedStyle(a);return{"--dd-color":S.color,"--dd-font-size":S.fontSize,"--dd-font-family":S.fontFamily,"--dd-font-variant":S.fontVariant}},[]);return!e||!v?null:(0,Zn.jsxs)("div",{ref:S=>{S!=null&&S.parentElement&&(y.current=S==null?void 0:S.parentElement)},className:u.root,style:h,children:[(0,Zn.jsx)($i,{tagName:"span",containerTagName:"div",className:(0,Yd.default)(u.container,u.agentText),disableLineBreaks:Kr(a),content:t||"\u200B",onAfterParse:p,matchers:g,selection:m,keywordMatches:s,inputElement:a,inputStyle:h,boundaryRef:y,inlineSuggestionsOnlyAtEnd:!f}),(0,Zn.jsx)("br",{})]})},KN=({input:e,ui:t,settings:n,styleSuggestions:r,conversation:o})=>{var v;let{tabCompletionSuggestion:i}=e,s=(i==null?void 0:i.text)||"",a=(i==null?void 0:i.source)||"",l=e.html??Wi(e.text),u=s.indexOf(e.text)===0?s.slice(e.text.length):"",{showTabHint:c}=t,{isSupported:f}=o,{showTabCompletion:d,visible:m,showStyleSuggestions:y}=n;return{showTabHint:c,showStyleSuggestions:y,showTabCompletion:d,content:l,tabText:u,source:a,keywordMatches:((v=r.list)==null?void 0:v.keywordMatches)??[],enabled:m&&f!==!1}},tb=jn(KN)(VN);var yT=w(te()),vT=w(D());var nb={list:[],fetchState:"idle",isInitialRequest:null},ob=e=>e.autoflows.list||[],rb=e=>t=>{var n;return(n=t.list)==null?void 0:n.find(r=>r.triggerPayload===e)},er=B("autoflows/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getAutoflows(e)}),Dh=B("autoflows/start",async(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");await r.startAutoflowSession(e),await n(er(e.platformSessionId))}),Fh=B("autoflows/stop",async(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");await r.stopAutoflowSession(e.platformSessionId),await n(er(e.platformSessionId))}),$N=W({name:"autoflows",initialState:nb,reducers:{},extraReducers:e=>{e.addCase(Dh.pending,(t,n)=>{let r=rb(n.meta.arg.triggerPayload)(t);r.state="Started",r.isBusy=!0}),e.addCase(Fh.pending,(t,n)=>{let r=rb(n.meta.arg.triggerPayload)(t);r.state="Aborted",r.isBusy=!0}),e.addCase(er.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}),e.addCase(er.rejected,t=>{t.fetchState="error"}),e.addCase(er.fulfilled,(t,n)=>{t.list=n.payload,t.fetchState="done"}),e.addCase(le,()=>nb)}}),ib=B("autoflows/openStream",(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");let o=r.openStream(e);o.on("sessionAborted",()=>{n(er(e))}),o.on("sessionCompleted",()=>{n(er(e))})}),sb=B("autoflows/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),ab=$N.reducer;var lb={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},ub=e=>e.customMessages.list,cb=e=>t=>!!t.customMessages.sentSuggestions.find(n=>n===e),db=e=>t=>!!t.customMessages.answeredSuggestions.find(n=>n===e),fb=e=>t=>!!t.customMessages.errorSuggestions.find(n=>n===e),nl=B("customMessages/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getCustomMessages(e)}),Xd=B("customMessages/send",async(e,t)=>{let{platformSessionId:n,suggestion:r}=e,{deepdeskBrokerAPI:o}=t.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.sendCustomMessage(n,r)}),Qd=B("customMessages/answer",async(e,t)=>{let{platformSessionId:n,reply:r}=e,{deepdeskBrokerAPI:o}=t.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.answerCustomMessage(n,r)}),pb=W({name:"customMessages",initialState:lb,reducers:{onCustomMessage(e,t){Array.isArray(t.payload)?e.list=t.payload:e.list=[t.payload]}},extraReducers:e=>{e.addCase(nl.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(nl.rejected,t=>{t.fetchState="error"}).addCase(nl.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload||[]}).addCase(Xd.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.errorSuggestions=t.errorSuggestions.filter(r=>n.meta.arg.suggestion.text!==r)}).addCase(Xd.rejected,(t,n)=>{let r=t.sentSuggestions.indexOf(n.meta.arg.suggestion.text);t.errorSuggestions.push(...t.sentSuggestions.splice(r,1))}).addCase(Qd.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.answeredSuggestions.push(n.meta.arg.suggestion.text)}).addCase(Qd.rejected,(t,n)=>{let r=t.answeredSuggestions.indexOf(n.meta.arg.suggestion.text);t.errorSuggestions.push(...t.sentSuggestions.splice(r,1)),t.answeredSuggestions.splice(r,1)}).addCase(le,()=>lb)}}),mb=B("customMessages/openStream",(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");r.openStream(e).on("customMessageSuggestion",i=>{n(pb.actions.onCustomMessage(i))})}),gb=B("customMessages/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),hb=pb.reducer;var WN={token:null,accountUrl:null,interval:null},yb=e=>t=>{let{passwordlessToken:{token:n,accountUrl:r}}=t;return n&&r?`${r}/apis/admin/session/passwordless/login/?token=${n}&redirect=${e}`:null},Hh=B("passwordlessToken/getTemporaryPasswordlessToken",async(e,t)=>{let{deepdeskAPI:n}=t.extra,r=await n.requestPasswordlessToken();return{accountUrl:n.client.baseUrl,token:r}}),Uh=B("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(Hh()),setInterval(()=>r(Hh()),n)}),vb=W({name:"passwordlessToken",initialState:WN,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(Hh.fulfilled,(t,n)=>{t.token=n.payload.token,t.accountUrl=n.payload.accountUrl}),e.addCase(Uh.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:Sb}=vb.actions,wb=vb.reducer;var Bh={cues:[],fetchState:"idle"},xb=e=>{var t;return(t=e.rules)==null?void 0:t.cues},qN=we("rules/resetCues"),Bo=B("rules/evaluate",async(e,t)=>{var a;let{deepdeskAPI:n}=t.extra,r=(a=t.getState().conversation.current)==null?void 0:a.id;if(!r)throw new Error("No current conversation to evaluate rules");if(!(await n.getAccount()).ruleEngine)throw new Error("Rule engine is not enabled for this account");if(!(await n.getRules()).some(l=>l.label===e.label))throw new Error(`No rules found with label: ${e.label}`);return await n.evaluateRule(e.label,r,e.params)}),Eb=W({name:"answer",initialState:Bh,reducers:{removeCue(e,t){e.cues=e.cues.filter(n=>n.rule.id!==t.payload.id)}},extraReducers:e=>{e.addCase(Bo.pending,t=>{t.fetchState="loading"}).addCase(Bo.rejected,t=>{t.fetchState="error"}).addCase(Bo.fulfilled,(t,n)=>{let r=n.payload.map(i=>i.rule.id),o=t.cues.filter(i=>!r.includes(i.rule.id));t.fetchState="done",t.cues=[...n.payload,...o]}).addCase(le,()=>Bh).addCase(qN.toString(),()=>Bh)}}),{removeCue:Cb}=Eb.actions,bb=Eb.reducer;function Tb(e){let{customMessages:t,autoflows:n}=e;return n.fetchState==="loading"&&n.isInitialRequest===!0||t.fetchState==="loading"&&t.isInitialRequest===!0}var Mb=w(D());var Ib=w(te()),Ob=w(D());var Pb=w(te());var kb={root:"Ti"};var Ab=w(b()),YN=({className:e,children:t})=>{let n=A("Unicode",kb);return(0,Ab.jsx)("span",{className:(0,Pb.default)(e,n.root),children:t})},Rb=YN;var Lb={isDisabled:"Ui",buttonStart:"Bi",root:"Di",buttonStop:"ho",stateBadge:"h",isCompleted:"Ii",isStarted:"Oi",isAborted:"Xi"};var jh={};Qe(jh,{enUS:()=>QN,nlNL:()=>ZN});var QN={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"}]},ZN={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 Tt=w(b()),eM=({disabled:e,state:t,displayName:n,description:r,onStartAutoflow:o,onStopAutoflow:i})=>{let s=A("Autoflow",Lb),a=G(jh),l=t==="Started"?"stop":"start",u=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return(0,Tt.jsxs)(oe,{className:(0,Ib.default)(s.root,{[s.isDisabled]:e,[s.isCompleted]:t==="Completed",[s.isAborted]:t==="Aborted",[s.isStarted]:t==="Started"}),children:[(0,Tt.jsx)(fe,{children:(0,Tt.jsxs)(fe.Content,{children:[(0,Tt.jsxs)(fe.Title,{children:[t&&(0,Tt.jsx)("span",{className:s.stateBadge,children:a(t)}),n]}),(0,Tt.jsx)("span",{children:r})]})}),(0,Tt.jsx)(oe.Actions,{fixed:t==="Started",children:(0,Tt.jsx)(oe.ActionButton,{primary:!0,className:l==="start"?s.buttonStart:s.buttonStop,onClick:t==="Started"?i:o,disabled:e,label:(0,Tt.jsxs)(Ob.Fragment,{children:[(0,Tt.jsx)(Rb,{children:u})," ",(0,Tt.jsx)("span",{children:a(l)})]})})})]})},Nb=eM;var zh=w(b()),tM=(e,t)=>{let n=t.filter(r=>r.state==="Started");return n.length>0?n.indexOf(e)===-1:!1},nM=({autoflows:e,onStartAutoflow:t,onStopAutoflow:n,platformSessionId:r})=>(0,zh.jsx)(Mb.Fragment,{children:e.map(o=>(0,zh.jsx)(Nb,{displayName:o.displayName,description:o.description,disabled:o.isBusy||tM(o,e),state:o.state,onStartAutoflow:()=>t({platformSessionId:r,triggerPayload:o.triggerPayload}),onStopAutoflow:()=>n({platformSessionId:r,triggerPayload:o.triggerPayload})},o.displayName))}),rM=({autoflows:e,conversation:t})=>{var n;return{autoflows:e.list,platformSessionId:(n=t.current)==null?void 0:n.sessionId}},oM={onStartAutoflow:Dh,onStopAutoflow:Fh},_b=jn(rM,oM)(nM);var Db=w(te()),Vh=w(D());var tr={root:"mo",title:"uo",isUsed:"Ji",quickReplies:"Ki",quickReply:"Pi",hasError:"Qi",label:"Vi",errorIcon:"Wi"};var gt=w(b()),sM=({suggestion:e})=>{let t=G(No),n=Y(),r=O(cb(e.text)),o=O(db(e.text)),i=O(fb(e.text)),s=O(_c),{replyOptions:a}=e,l=(0,Vh.useCallback)(c=>{c.preventDefault(),c.stopPropagation(),!(r||!s)&&n(Xd({platformSessionId:s,suggestion:e}))},[e,r,n,s]),u=(0,Vh.useCallback)(c=>{if(c.preventDefault(),c.stopPropagation(),!s||!a)return;let f=parseInt(c.target.dataset.index,10),d=a[f];n(Qd({platformSessionId:s,reply:d,suggestion:e}))},[e,r,n,s]);return(0,gt.jsxs)(oe,{onClick:l,className:(0,Db.default)(tr.root,{[tr.isUsed]:r,[tr.hasError]:i}),children:[(0,gt.jsx)(fe,{children:(0,gt.jsxs)(fe.Content,{children:[(0,gt.jsxs)(fe.Title,{className:tr.title,children:[e.text," ",(0,gt.jsx)(_l,{className:tr.label,children:"analyse tool"})," ",i&&(0,gt.jsx)("span",{className:tr.errorIcon,role:"img","aria-label":t("sendingError"),title:t("sendingError"),children:"!"})]}),a&&a.length>0&&(0,gt.jsx)("ul",{className:tr.quickReplies,children:a.map(c=>(0,gt.jsx)("li",{className:tr.quickReply,children:c.title},c.title))})]})}),(0,gt.jsxs)(oe.Actions,{fixed:i||r,children:[a&&a.length>0&&(0,gt.jsx)(oe.DropdownButton,{label:t("answer"),disabled:o,children:a.map((c,f)=>(0,gt.jsx)(oe.DropdownItem,{index:f,label:c.title,onClick:u},c.title))}),(0,gt.jsx)(oe.ActionButton,{primary:!0,disabled:r,onClick:l,label:t(r?"suggestionSent":i?"tryAgain":"sendSuggestion")})]})]})},Fb=sM;var Zd=w(D());var Wh=w(te());var Kh=w(b()),$h=()=>(0,Kh.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,Kh.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 Hb={root:"Zi",entity:"r",entityText:"_i",iconWrapper:"or",icon:"er",iconClicked:"ir"};var Tn=w(b()),lM=({entities:e})=>{let t=A("EntitiesWidgetList",Hb),[n,r]=(0,Zd.useState)(void 0),o=Y(),i=()=>{r(void 0)},s=a=>{e&&(r(e.indexOf(a)),ko(a.text),o(Ye({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,Zd.useEffect)(()=>{let a=setTimeout(i,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,Tn.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,Tn.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>s(a),children:[(0,Tn.jsx)("span",{className:t.entityText,children:a.text}),(0,Tn.jsxs)("span",{className:t.iconWrapper,children:[(0,Tn.jsx)("span",{className:(0,Wh.default)(t.icon),children:(0,Tn.jsx)($h,{})}),(0,Tn.jsx)("span",{className:(0,Wh.default)(t.icon,n===l&&t.iconClicked),children:(0,Tn.jsx)($h,{})})]})]},a.text))})},Ub=lM;var qh=w(b()),Bb=()=>(0,qh.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,qh.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 Gh=w(b()),jb=()=>(0,Gh.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Gh.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 Yh=w(b()),zb=()=>(0,Yh.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Yh.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"})});function Vb(e){return B("analytics/logEvent",(t,n)=>{var i,s,a;let r=(s=(i=n.getState())==null?void 0:i.conversation.current)==null?void 0:s.id,o=(a=n.getState())==null?void 0:a.info.agentInfo;return n.extra.deepdeskAPI.sendEvent(t.name,{conversationId:r,...o,data:t.data})})(e)}function Jd(){let e=Y();return async(t,n)=>{await e(Vb({name:t,data:n}))}}var ay=w(te()),of=w(D());var rl=w(b()),Kb=({className:e})=>(0,rl.jsxs)("svg",{viewBox:"0 0 12 12",version:"1.1",xmlns:"http://www.w3.org/2000/svg",className:e,children:[(0,rl.jsx)("line",{x1:"2",y1:"10",x2:"10",y2:"2",stroke:"black",strokeWidth:"1"}),(0,rl.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10",stroke:"black",strokeWidth:"1"})]});var Xh=w(b()),$b=e=>(0,Xh.jsx)("svg",{width:"16",height:"16",fill:"#000000",...e,viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,Xh.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 Qh=w(b()),Wb=e=>(0,Qh.jsx)("svg",{width:"16",height:"16",fill:"#000000",...e,viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,Qh.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 ss(e,t){var r;let n=e.cloneNode(!0);n.style.top=`${e.offsetTop}px`,n.style.left=`${e.offsetLeft}px`,n.style.position="absolute",n.classList.add(t),n.addEventListener("animationend",()=>n.remove()),(r=e.parentElement)==null||r.appendChild(n)}var{entries:eT,setPrototypeOf:qb,isFrozen:uM,getPrototypeOf:cM,getOwnPropertyDescriptor:dM}=Object,{freeze:ot,seal:fn,create:tT}=Object,{apply:ry,construct:oy}=typeof Reflect<"u"&&Reflect;ot||(ot=function(t){return t});fn||(fn=function(t){return t});ry||(ry=function(t,n,r){return t.apply(n,r)});oy||(oy=function(t,n){return new t(...n)});var ef=Pt(Array.prototype.forEach),Gb=Pt(Array.prototype.pop),ol=Pt(Array.prototype.push),rf=Pt(String.prototype.toLowerCase),Zh=Pt(String.prototype.toString),fM=Pt(String.prototype.match),il=Pt(String.prototype.replace),pM=Pt(String.prototype.indexOf),mM=Pt(String.prototype.trim),dn=Pt(Object.prototype.hasOwnProperty),kt=Pt(RegExp.prototype.test),sl=gM(TypeError);function Pt(e){return function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return ry(e,t,r)}}function gM(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return oy(e,n)}}function X(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:rf;qb&&qb(e,null);let r=t.length;for(;r--;){let o=t[r];if(typeof o=="string"){let i=n(o);i!==o&&(uM(t)||(t[r]=i),o=i)}e[o]=!0}return e}function hM(e){for(let t=0;t<e.length;t++)dn(e,t)||(e[t]=null);return e}function jo(e){let t=tT(null);for(let[n,r]of eT(e))dn(e,n)&&(Array.isArray(r)?t[n]=hM(r):r&&typeof r=="object"&&r.constructor===Object?t[n]=jo(r):t[n]=r);return t}function tf(e,t){for(;e!==null;){let r=dM(e,t);if(r){if(r.get)return Pt(r.get);if(typeof r.value=="function")return Pt(r.value)}e=cM(e)}function n(){return null}return n}var Yb=ot(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Jh=ot(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),ey=ot(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),yM=ot(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),ty=ot(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),vM=ot(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Xb=ot(["#text"]),Qb=ot(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","xmlns","slot"]),ny=ot(["accent-height","accumulate","additive","alignment-baseline","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Zb=ot(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),nf=ot(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),SM=fn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),wM=fn(/<%[\w\W]*|[\w\W]*%>/gm),xM=fn(/\${[\w\W]*}/gm),EM=fn(/^data-[\-\w.\u00B7-\uFFFF]/),CM=fn(/^aria-[\-\w]+$/),nT=fn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),bM=fn(/^(?:\w+script|data):/i),TM=fn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),rT=fn(/^html$/i),Jb=Object.freeze({__proto__:null,MUSTACHE_EXPR:SM,ERB_EXPR:wM,TMPLIT_EXPR:xM,DATA_ATTR:EM,ARIA_ATTR:CM,IS_ALLOWED_URI:nT,IS_SCRIPT_OR_DATA:bM,ATTR_WHITESPACE:TM,DOCTYPE_NAME:rT}),kM=function(){return typeof window>"u"?null:window},PM=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let r=null,o="data-tt-policy-suffix";n&&n.hasAttribute(o)&&(r=n.getAttribute(o));let i="dompurify"+(r?"#"+r:"");try{return t.createPolicy(i,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}};function oT(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:kM(),t=U=>oT(U);if(t.version="3.0.9",t.removed=[],!e||!e.document||e.document.nodeType!==9)return t.isSupported=!1,t;let{document:n}=e,r=n,o=r.currentScript,{DocumentFragment:i,HTMLTemplateElement:s,Node:a,Element:l,NodeFilter:u,NamedNodeMap:c=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:f,DOMParser:d,trustedTypes:m}=e,y=l.prototype,v=tf(y,"cloneNode"),p=tf(y,"nextSibling"),g=tf(y,"childNodes"),h=tf(y,"parentNode");if(typeof s=="function"){let U=n.createElement("template");U.content&&U.content.ownerDocument&&(n=U.content.ownerDocument)}let S,x="",{implementation:T,createNodeIterator:C,createDocumentFragment:k,getElementsByTagName:L}=n,{importNode:I}=r,N={};t.isSupported=typeof eT=="function"&&typeof h=="function"&&T&&T.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:z,ERB_EXPR:_,TMPLIT_EXPR:J,DATA_ATTR:Yr,ARIA_ATTR:it,IS_SCRIPT_OR_DATA:Gt,ATTR_WHITESPACE:At}=Jb,{IS_ALLOWED_URI:H}=Jb,q=null,ir=X({},[...Yb,...Jh,...ey,...ty,...Xb]),he=null,sr=X({},[...Qb,...ny,...Zb,...nf]),$=Object.seal(tT(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ar=null,vl=null,$o=!0,Xr=!0,ds=!1,Sl=!0,Yt=!1,Xt=!1,wl=!1,st=!1,Lt=!1,xl=!1,El=!1,xy=!0,Ey=!1,ak="user-content-",hf=!0,fs=!1,Wo={},qo=null,Cy=X({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),by=null,Ty=X({},["audio","video","img","source","image","track"]),yf=null,ky=X({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Cl="http://www.w3.org/1998/Math/MathML",bl="http://www.w3.org/2000/svg",Rn="http://www.w3.org/1999/xhtml",Go=Rn,vf=!1,Sf=null,lk=X({},[Cl,bl,Rn],Zh),ps=null,uk=["application/xhtml+xml","text/html"],ck="text/html",Oe=null,Yo=null,dk=n.createElement("form"),Py=function(E){return E instanceof RegExp||E instanceof Function},wf=function(){let E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Yo&&Yo===E)){if((!E||typeof E!="object")&&(E={}),E=jo(E),ps=uk.indexOf(E.PARSER_MEDIA_TYPE)===-1?ck:E.PARSER_MEDIA_TYPE,Oe=ps==="application/xhtml+xml"?Zh:rf,q=dn(E,"ALLOWED_TAGS")?X({},E.ALLOWED_TAGS,Oe):ir,he=dn(E,"ALLOWED_ATTR")?X({},E.ALLOWED_ATTR,Oe):sr,Sf=dn(E,"ALLOWED_NAMESPACES")?X({},E.ALLOWED_NAMESPACES,Zh):lk,yf=dn(E,"ADD_URI_SAFE_ATTR")?X(jo(ky),E.ADD_URI_SAFE_ATTR,Oe):ky,by=dn(E,"ADD_DATA_URI_TAGS")?X(jo(Ty),E.ADD_DATA_URI_TAGS,Oe):Ty,qo=dn(E,"FORBID_CONTENTS")?X({},E.FORBID_CONTENTS,Oe):Cy,ar=dn(E,"FORBID_TAGS")?X({},E.FORBID_TAGS,Oe):{},vl=dn(E,"FORBID_ATTR")?X({},E.FORBID_ATTR,Oe):{},Wo=dn(E,"USE_PROFILES")?E.USE_PROFILES:!1,$o=E.ALLOW_ARIA_ATTR!==!1,Xr=E.ALLOW_DATA_ATTR!==!1,ds=E.ALLOW_UNKNOWN_PROTOCOLS||!1,Sl=E.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Yt=E.SAFE_FOR_TEMPLATES||!1,Xt=E.WHOLE_DOCUMENT||!1,Lt=E.RETURN_DOM||!1,xl=E.RETURN_DOM_FRAGMENT||!1,El=E.RETURN_TRUSTED_TYPE||!1,st=E.FORCE_BODY||!1,xy=E.SANITIZE_DOM!==!1,Ey=E.SANITIZE_NAMED_PROPS||!1,hf=E.KEEP_CONTENT!==!1,fs=E.IN_PLACE||!1,H=E.ALLOWED_URI_REGEXP||nT,Go=E.NAMESPACE||Rn,$=E.CUSTOM_ELEMENT_HANDLING||{},E.CUSTOM_ELEMENT_HANDLING&&Py(E.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&($.tagNameCheck=E.CUSTOM_ELEMENT_HANDLING.tagNameCheck),E.CUSTOM_ELEMENT_HANDLING&&Py(E.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&($.attributeNameCheck=E.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),E.CUSTOM_ELEMENT_HANDLING&&typeof E.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&($.allowCustomizedBuiltInElements=E.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Yt&&(Xr=!1),xl&&(Lt=!0),Wo&&(q=X({},Xb),he=[],Wo.html===!0&&(X(q,Yb),X(he,Qb)),Wo.svg===!0&&(X(q,Jh),X(he,ny),X(he,nf)),Wo.svgFilters===!0&&(X(q,ey),X(he,ny),X(he,nf)),Wo.mathMl===!0&&(X(q,ty),X(he,Zb),X(he,nf))),E.ADD_TAGS&&(q===ir&&(q=jo(q)),X(q,E.ADD_TAGS,Oe)),E.ADD_ATTR&&(he===sr&&(he=jo(he)),X(he,E.ADD_ATTR,Oe)),E.ADD_URI_SAFE_ATTR&&X(yf,E.ADD_URI_SAFE_ATTR,Oe),E.FORBID_CONTENTS&&(qo===Cy&&(qo=jo(qo)),X(qo,E.FORBID_CONTENTS,Oe)),hf&&(q["#text"]=!0),Xt&&X(q,["html","head","body"]),q.table&&(X(q,["tbody"]),delete ar.tbody),E.TRUSTED_TYPES_POLICY){if(typeof E.TRUSTED_TYPES_POLICY.createHTML!="function")throw sl('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof E.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw sl('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');S=E.TRUSTED_TYPES_POLICY,x=S.createHTML("")}else S===void 0&&(S=PM(m,o)),S!==null&&typeof x=="string"&&(x=S.createHTML(""));ot&&ot(E),Yo=E}},Ry=X({},["mi","mo","mn","ms","mtext"]),Ay=X({},["foreignobject","desc","title","annotation-xml"]),fk=X({},["title","style","font","a","script"]),Ly=X({},[...Jh,...ey,...yM]),Iy=X({},[...ty,...vM]),pk=function(E){let R=h(E);(!R||!R.tagName)&&(R={namespaceURI:Go,tagName:"template"});let F=rf(E.tagName),ce=rf(R.tagName);return Sf[E.namespaceURI]?E.namespaceURI===bl?R.namespaceURI===Rn?F==="svg":R.namespaceURI===Cl?F==="svg"&&(ce==="annotation-xml"||Ry[ce]):!!Ly[F]:E.namespaceURI===Cl?R.namespaceURI===Rn?F==="math":R.namespaceURI===bl?F==="math"&&Ay[ce]:!!Iy[F]:E.namespaceURI===Rn?R.namespaceURI===bl&&!Ay[ce]||R.namespaceURI===Cl&&!Ry[ce]?!1:!Iy[F]&&(fk[F]||!Ly[F]):!!(ps==="application/xhtml+xml"&&Sf[E.namespaceURI]):!1},Qr=function(E){ol(t.removed,{element:E});try{E.parentNode.removeChild(E)}catch{E.remove()}},xf=function(E,R){try{ol(t.removed,{attribute:R.getAttributeNode(E),from:R})}catch{ol(t.removed,{attribute:null,from:R})}if(R.removeAttribute(E),E==="is"&&!he[E])if(Lt||xl)try{Qr(R)}catch{}else try{R.setAttribute(E,"")}catch{}},Oy=function(E){let R=null,F=null;if(st)E="<remove></remove>"+E;else{let je=fM(E,/^[\r\n\t ]+/);F=je&&je[0]}ps==="application/xhtml+xml"&&Go===Rn&&(E='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+E+"</body></html>");let ce=S?S.createHTML(E):E;if(Go===Rn)try{R=new d().parseFromString(ce,ps)}catch{}if(!R||!R.documentElement){R=T.createDocument(Go,"template",null);try{R.documentElement.innerHTML=vf?x:ce}catch{}}let Be=R.body||R.documentElement;return E&&F&&Be.insertBefore(n.createTextNode(F),Be.childNodes[0]||null),Go===Rn?L.call(R,Xt?"html":"body")[0]:Xt?R.documentElement:Be},Ny=function(E){return C.call(E.ownerDocument||E,E,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT,null)},mk=function(E){return E instanceof f&&(typeof E.nodeName!="string"||typeof E.textContent!="string"||typeof E.removeChild!="function"||!(E.attributes instanceof c)||typeof E.removeAttribute!="function"||typeof E.setAttribute!="function"||typeof E.namespaceURI!="string"||typeof E.insertBefore!="function"||typeof E.hasChildNodes!="function")},My=function(E){return typeof a=="function"&&E instanceof a},An=function(E,R,F){N[E]&&ef(N[E],ce=>{ce.call(t,R,F,Yo)})},_y=function(E){let R=null;if(An("beforeSanitizeElements",E,null),mk(E))return Qr(E),!0;let F=Oe(E.nodeName);if(An("uponSanitizeElement",E,{tagName:F,allowedTags:q}),E.hasChildNodes()&&!My(E.firstElementChild)&&kt(/<[/\w]/g,E.innerHTML)&&kt(/<[/\w]/g,E.textContent))return Qr(E),!0;if(!q[F]||ar[F]){if(!ar[F]&&Fy(F)&&($.tagNameCheck instanceof RegExp&&kt($.tagNameCheck,F)||$.tagNameCheck instanceof Function&&$.tagNameCheck(F)))return!1;if(hf&&!qo[F]){let ce=h(E)||E.parentNode,Be=g(E)||E.childNodes;if(Be&&ce){let je=Be.length;for(let at=je-1;at>=0;--at)ce.insertBefore(v(Be[at],!0),p(E))}}return Qr(E),!0}return E instanceof l&&!pk(E)||(F==="noscript"||F==="noembed"||F==="noframes")&&kt(/<\/no(script|embed|frames)/i,E.innerHTML)?(Qr(E),!0):(Yt&&E.nodeType===3&&(R=E.textContent,ef([z,_,J],ce=>{R=il(R,ce," ")}),E.textContent!==R&&(ol(t.removed,{element:E.cloneNode()}),E.textContent=R)),An("afterSanitizeElements",E,null),!1)},Dy=function(E,R,F){if(xy&&(R==="id"||R==="name")&&(F in n||F in dk))return!1;if(!(Xr&&!vl[R]&&kt(Yr,R))){if(!($o&&kt(it,R))){if(!he[R]||vl[R]){if(!(Fy(E)&&($.tagNameCheck instanceof RegExp&&kt($.tagNameCheck,E)||$.tagNameCheck instanceof Function&&$.tagNameCheck(E))&&($.attributeNameCheck instanceof RegExp&&kt($.attributeNameCheck,R)||$.attributeNameCheck instanceof Function&&$.attributeNameCheck(R))||R==="is"&&$.allowCustomizedBuiltInElements&&($.tagNameCheck instanceof RegExp&&kt($.tagNameCheck,F)||$.tagNameCheck instanceof Function&&$.tagNameCheck(F))))return!1}else if(!yf[R]){if(!kt(H,il(F,At,""))){if(!((R==="src"||R==="xlink:href"||R==="href")&&E!=="script"&&pM(F,"data:")===0&&by[E])){if(!(ds&&!kt(Gt,il(F,At,"")))){if(F)return!1}}}}}}return!0},Fy=function(E){return E!=="annotation-xml"&&E.indexOf("-")>0},Hy=function(E){An("beforeSanitizeAttributes",E,null);let{attributes:R}=E;if(!R)return;let F={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:he},ce=R.length;for(;ce--;){let Be=R[ce],{name:je,namespaceURI:at,value:Zr}=Be,ms=Oe(je),lt=je==="value"?Zr:mM(Zr);if(F.attrName=ms,F.attrValue=lt,F.keepAttr=!0,F.forceKeepAttr=void 0,An("uponSanitizeAttribute",E,F),lt=F.attrValue,F.forceKeepAttr||(xf(je,E),!F.keepAttr))continue;if(!Sl&&kt(/\/>/i,lt)){xf(je,E);continue}Yt&&ef([z,_,J],By=>{lt=il(lt,By," ")});let Uy=Oe(E.nodeName);if(Dy(Uy,ms,lt)){if(Ey&&(ms==="id"||ms==="name")&&(xf(je,E),lt=ak+lt),S&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!at)switch(m.getAttributeType(Uy,ms)){case"TrustedHTML":{lt=S.createHTML(lt);break}case"TrustedScriptURL":{lt=S.createScriptURL(lt);break}}try{at?E.setAttributeNS(at,je,lt):E.setAttribute(je,lt),Gb(t.removed)}catch{}}}An("afterSanitizeAttributes",E,null)},gk=function U(E){let R=null,F=Ny(E);for(An("beforeSanitizeShadowDOM",E,null);R=F.nextNode();)An("uponSanitizeShadowNode",R,null),!_y(R)&&(R.content instanceof i&&U(R.content),Hy(R));An("afterSanitizeShadowDOM",E,null)};return t.sanitize=function(U){let E=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},R=null,F=null,ce=null,Be=null;if(vf=!U,vf&&(U="<!-->"),typeof U!="string"&&!My(U))if(typeof U.toString=="function"){if(U=U.toString(),typeof U!="string")throw sl("dirty is not a string, aborting")}else throw sl("toString is not a function");if(!t.isSupported)return U;if(wl||wf(E),t.removed=[],typeof U=="string"&&(fs=!1),fs){if(U.nodeName){let Zr=Oe(U.nodeName);if(!q[Zr]||ar[Zr])throw sl("root node is forbidden and cannot be sanitized in-place")}}else if(U instanceof a)R=Oy("<!---->"),F=R.ownerDocument.importNode(U,!0),F.nodeType===1&&F.nodeName==="BODY"||F.nodeName==="HTML"?R=F:R.appendChild(F);else{if(!Lt&&!Yt&&!Xt&&U.indexOf("<")===-1)return S&&El?S.createHTML(U):U;if(R=Oy(U),!R)return Lt?null:El?x:""}R&&st&&Qr(R.firstChild);let je=Ny(fs?U:R);for(;ce=je.nextNode();)_y(ce)||(ce.content instanceof i&&gk(ce.content),Hy(ce));if(fs)return U;if(Lt){if(xl)for(Be=k.call(R.ownerDocument);R.firstChild;)Be.appendChild(R.firstChild);else Be=R;return(he.shadowroot||he.shadowrootmode)&&(Be=I.call(r,Be,!0)),Be}let at=Xt?R.outerHTML:R.innerHTML;return Xt&&q["!doctype"]&&R.ownerDocument&&R.ownerDocument.doctype&&R.ownerDocument.doctype.name&&kt(rT,R.ownerDocument.doctype.name)&&(at="<!DOCTYPE "+R.ownerDocument.doctype.name+`>
|
|
24
24
|
`+at),Yt&&ef([z,_,J],Zr=>{at=il(at,Zr," ")}),S&&El?S.createHTML(at):at},t.setConfig=function(){let U=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};wf(U),wl=!0},t.clearConfig=function(){Yo=null,wl=!1},t.isValidAttribute=function(U,E,R){Yo||wf({});let F=Oe(U),ce=Oe(E);return Dy(F,ce,R)},t.addHook=function(U,E){typeof E=="function"&&(N[U]=N[U]||[],ol(N[U],E))},t.removeHook=function(U){if(N[U])return Gb(N[U])},t.removeHooks=function(U){N[U]&&(N[U]=[])},t.removeAllHooks=function(){N={}},t}var iT=oT();var qr=w(D());var RM={"":["<em>","</em>"],_:["<strong>","</strong>"],"*":["<strong>","</strong>"],"~":["<s>","</s>"],"\n":["<br />"]," ":["<br />"],"-":["<hr />"]};function sT(e){return e.replace(RegExp("^"+(e.match(/^(\t| )+/)||"")[0],"gm"),"")}function al(e){return(e+"").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function ll(e,t){var n,r,o,i,s,a=/((?:^|\n+)(?:\n---+|\* \*(?: \*)+)\n)|(?:^``` *(\w*)\n([\s\S]*?)\n```$)|((?:(?:^|\n+)(?:\t| {2,}).+)+\n*)|((?:(?:^|\n)([>*+-]|\d+\.)\s+.*)+)|(?:!\[([^\]]*?)\]\(([^)]+?)\))|(\[)|(\](?:\(([^)]+?)\))?)|(?:(?:^|\n+)([^\s].*)\n(-{3,}|={3,})(?:\n+|$))|(?:(?:^|\n+)(#{1,6})\s*(.+)(?:\n+|$))|(?:`([^`].*?)`)|( \n\n*|\n{2,}|__|\*\*|[_*]|~~)/gm,l=[],u="",c=t||{},f=0;function d(y){var v=RM[y[1]||""],p=l[l.length-1]==y;return v?v[1]?(p?l.pop():l.push(y),v[0|p]):v[0]:y}function m(){for(var y="";l.length;)y+=d(l[l.length-1]);return y}for(e=e.replace(/^\[(.+?)\]:\s*(.+)$/gm,function(y,v,p){return c[v.toLowerCase()]=p,""}).replace(/^\n+|\n+$/g,"");o=a.exec(e);)r=e.substring(f,o.index),f=a.lastIndex,n=o[0],r.match(/[^\\](\\\\)*\\$/)||((s=o[3]||o[4])?n='<pre class="code '+(o[4]?"poetry":o[2].toLowerCase())+'"><code'+(o[2]?' class="language-'+o[2].toLowerCase()+'"':"")+">"+sT(al(s).replace(/^\n+|\n+$/g,""))+"</code></pre>":(s=o[6])?(s.match(/\./)&&(o[5]=o[5].replace(/^\d+/gm,"")),i=ll(sT(o[5].replace(/^\s*[>*+.-]/gm,""))),s==">"?s="blockquote":(s=s.match(/\./)?"ol":"ul",i=i.replace(/^(.*)(\n|$)/gm,"<li>$1</li>")),n="<"+s+">"+i+"</"+s+">"):o[8]?n='<img src="'+al(o[8])+'" alt="'+al(o[7])+'">':o[10]?(u=u.replace("<a>",'<a href="'+al(o[11]||c[r.toLowerCase()])+'">'),n=m()+"</a>"):o[9]?n="<a>":o[12]||o[14]?n="<"+(s="h"+(o[14]?o[14].length:o[13]>"="?1:2))+">"+ll(o[12]||o[15],c)+"</"+s+">":o[16]?n="<code>"+al(o[16])+"</code>":(o[17]||o[1])&&(n=d(o[17]||"--"))),u+=r,u+=n;return(u+e.substring(f)+m()).replace(/^\n+|\n+$/g,"")}var aT={fadeup:"E",root:"i",popover:"rr",options:"yo",copyIcon:"G",option:"wo",divider:"tr"};var nr=w(b());function LM(e){return`<button type="button" class=${e}><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 iy(e){let t=e.cloneNode(!0);return t.querySelectorAll("div,button").forEach(n=>n.remove()),t.textContent??""}var IM=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let i=A("Markdown",aT),s=(0,qr.useRef)(null),[a,l]=(0,qr.useState)(null),u=(0,qr.useMemo)(()=>{let y=ll(e);return iT.sanitize(y).replace(/<\/code>/g,`${LM(i.copyIcon)}</code>`)},[e]),c=y=>{var g;let v=y.target,p=!!((g=s.current)!=null&&g.querySelector("code"));a||p&&v.tagName!=="CODE"||!p&&v!==s.current||(v.addEventListener("mouseleave",()=>l(null),{once:!0}),l(v))},f=()=>{if(!a)return;l(null);let y=a.querySelector("button");y&&(ss(y,i.fadeup),r(iy(a)))},d=y=>{y.target.tagName.toLowerCase()==="button"&&(ss(y.target,i.fadeup),r(iy(y.target.parentElement)))},m=()=>{a&&(l(null),o(iy(a)))};return(0,nr.jsxs)(qr.Fragment,{children:[a&&(0,nr.jsx)(is,{triggerRef:{current:a},parentNode:a,className:i.popover,children:(0,nr.jsxs)("div",{className:i.options,children:[(0,nr.jsx)("button",{type:"button",className:i.option,onClick:f,children:n}),(0,nr.jsx)("div",{className:i.divider}),(0,nr.jsx)("button",{type:"button",className:i.option,onClick:m,children:t})]})}),(0,nr.jsx)("div",{ref:s,className:i.root,dangerouslySetInnerHTML:{__html:u},onMouseOver:c,onClick:d})]})},lT=IM;var sy={};Qe(sy,{enUS:()=>OM,nlNL:()=>NM});var OM={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"}]},NM={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 uT={fadeup:"N",fadedown:"A",selected:"vo",thumbsUp:"nr",thumbsDown:"ar"};var Rt=w(b()),_M=({cue:e,onRemove:t,onCopy:n,onUse:r,onThumbsUp:o,onThumbsDown:i})=>{let s=A("WidgetCue",uT),a=G(sy),l=Jd(),[u,c]=(0,of.useState)(null),f=p=>{n&&n(p,e)},d=p=>{r&&r(p,e)},m=p=>{p.preventDefault(),p.stopPropagation(),t(e)},y=p=>{p.preventDefault(),p.stopPropagation(),ss(p.target,s.fadeup),c("up"),o(e)},v=p=>{p.preventDefault(),p.stopPropagation(),ss(p.target,s.fadedown),c("down"),i(e)};return(0,of.useEffect)(()=>{l("Assistant response displayed",{name:e.rule.name,description:e.rule.description,group:e.rule.label})},[]),(0,Rt.jsxs)(oe,{"data-testid":"cue",children:[(0,Rt.jsx)(fe,{children:(0,Rt.jsxs)(fe.Content,{children:[e.title&&(0,Rt.jsx)(fe.Title,{"data-testid":"widget-cue-title",children:e.title}),(0,Rt.jsx)(lT,{content:e.text,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:f,onUse:d})]})}),(0,Rt.jsx)(oe.IconButton,{title:a("thumbsUp"),onClick:y,icon:(0,Rt.jsx)(Wb,{}),className:(0,ay.default)(s.thumbsUp,u==="up"&&s.selected),disabled:!!u}),(0,Rt.jsx)(oe.IconButton,{title:a("thumbsDown"),onClick:v,icon:(0,Rt.jsx)($b,{}),className:(0,ay.default)(s.thumbsDown,u==="down"&&s.selected),disabled:!!u}),(0,Rt.jsx)(oe.IconButton,{title:a("removeCue"),onClick:m,icon:(0,Rt.jsx)(Kb,{})})]})},cT=_M;var ul=w(b()),DM=({cues:e})=>{let t=Y(),n=zt(),r=Jd(),o=u=>{t(Cb({id:u.rule.id})),r("Assistant response closed",{name:u.rule.name,group:u.rule.label,description:u.rule.description})},i=(u,c)=>{ko(u),r("Assistant response copied",{name:c.rule.name,group:c.rule.label,description:c.rule.description,copiedText:u})},s=(u,c)=>{n.send(Dr,{text:u,suggestion:{source:"cue",sourceText:u}}),r("Assistant response used",{name:c.rule.name,group:c.rule.label,description:c.rule.description,usedText:u})},a=u=>{r("Assistant response feedback",{name:u.rule.name,group:u.rule.label,description:u.rule.description,thumb:"up"})},l=u=>{r("Assistant response feedback",{name:u.rule.name,group:u.rule.label,description:u.rule.description,thumb:"down"})};return(0,ul.jsx)(ul.Fragment,{children:e.map(u=>(0,ul.jsx)(cT,{cue:u,onRemove:o,onCopy:i,onUse:s,onThumbsDown:l,onThumbsUp:a},u.rule.id))})},dT=DM;var pT=w(D());var FM=/(https?:\/\/[^\s]+)/,fT=e=>e.split(" ").find(t=>FM.test(t));var Wt=w(b()),HM=({suggestion:e,lines:t,onUse:n})=>{var c;let r=e.text||e.url||e.message,o=fT(r),i=G(No),s=j("showImages"),a=j("fallbackImage"),l=f=>{f.preventDefault(),f.stopPropagation(),n(r)},u=(0,pT.useCallback)(f=>{window.open(o,"_blank"),f.stopPropagation(),f.preventDefault()},[o]);return(0,Wt.jsxs)(oe,{onClick:l,"data-testid":"edit-suggestion",children:[(0,Wt.jsxs)(fe,{children:[s&&e.image&&(0,Wt.jsx)(fe.Image,{src:Wd(e,"small",a||void 0),title:e.title}),(0,Wt.jsxs)(fe.Content,{children:[e.title&&(0,Wt.jsx)(fe.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((c=e.searchKeywords)==null?void 0:c.length)>0&&(0,Wt.jsx)(oe.Labels,{labels:e.searchKeywords}),(0,Wt.jsx)(fe.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,Wt.jsxs)(oe.Actions,{children:[o&&(0,Wt.jsx)(oe.ActionButton,{onClick:u,label:i("visitUrl")}),(0,Wt.jsx)(oe.ActionButton,{primary:!0,onClick:l,label:i("useSuggestion")})]})]})},mT=HM;var cl=w(b()),UM=({lines:e,suggestions:t})=>{let n=zt(),r=(o,i)=>{n.send(Dr,{text:o,suggestion:{...i,source:i.source,sourceText:i.text}})};return(0,cl.jsx)(cl.Fragment,{children:t.map(o=>(0,cl.jsx)(mT,{suggestion:o,lines:e,onUse:i=>r(i,o)},o.text||o.url||o.message))})},gT=UM;var ly={};Qe(ly,{enUS:()=>BM,nlNL:()=>jM});var BM={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"}]},jM={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 hT={root:"pr",loginText:"dr",stateText:"ko",sectionList:"lr",shortcutList:"sr",shortcut:"cr",link:"zo"};var Q=w(b()),sf=(e,t)=>{let n=O(tt);(0,vT.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},VM=({onLogIn:e})=>{let t=G(ly),n=Y(),r=j("isEmbedded"),o=A("Widget",hT),i=j("showAutoflows"),s=j("showCustomMessages"),a=j("showSummaryCommand"),l=j("showKnowledgeSearch"),u=j("showSearch"),c=O(jr),f=O(Td),d=O(ob),m=O(xb),y=O(bd),v=O(ub),p=O(Dc),g=O(zi),h=O(tt),S=O(_c),x=O(Tb),T=O(kd),C=zt(),k=O(eC),L=O(yb("/admin/")),I=j("adminUrl"),N=j("productName");if(sf(()=>(n(nl(S)),n(mb(S)),()=>{n(gb(S))}),[n,g,s,S]),sf(()=>(n(er(S)),n(ib(S)),()=>{n(sb(S))}),[n,g,i,S]),sf(()=>{f.forEach(({type:_})=>{n(_==="entities"?an():un(_))})},[n,g,p,c]),sf(()=>(n(Uh()),()=>{n(Sb())}),[n]),g===!1)return(0,Q.jsx)("div",{className:o.stateText,children:(0,Q.jsx)("div",{children:(0,Q.jsx)("p",{children:t("notSupported")})})},"supported");if(h===!1)return(0,Q.jsx)("div",{className:o.loginText,children:(0,Q.jsx)("div",{children:(0,Q.jsx)(Nd,{isEmbedded:r,loginUrl:I,onLogIn:e})})},"login");if(!c||!S||h===null||k||x)return(0,Q.jsx)("div",{className:o.stateText,children:(0,Q.jsx)("div",{children:(0,Q.jsx)("p",{children:t("waiting")})})},"waiting");let z=u||a||l||L;return(0,Q.jsx)("div",{className:(0,yT.default)(o.root),"data-testid":"widget",children:(0,Q.jsxs)(Dl,{className:o.sectionList,children:[z&&(0,Q.jsx)(In,{title:t("actions"),type:"shortcuts",children:(0,Q.jsxs)("div",{className:o.shortcutList,children:[u&&(0,Q.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-search",onClick:()=>C.send("ShowCommandPalette",{isOpen:!0}),children:[(0,Q.jsx)(qi,{}),t("linkSearch")]}),a&&(0,Q.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-summary",onClick:()=>C.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,Q.jsx)(zb,{}),t("linkSummary")]}),l&&(0,Q.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>C.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,Q.jsx)(jb,{}),t("linkKnowledgeSearch")]}),L&&(0,Q.jsxs)("a",{className:o.shortcut,target:"_blank",href:L,"data-testid":"shortcut-studio-login",rel:"noreferrer",children:[(0,Q.jsx)(Bb,{}),t("linkStudioLogin",{productName:N})]})]})}),s&&v.length>0&&(0,Q.jsx)(In,{type:"custom-messages","data-testid":"custom-messages",children:(0,Q.jsx)(ht,{withDivider:!0,children:v.map(_=>(0,Q.jsx)(Fb,{suggestion:_},_.text))})}),i&&d.length>0&&(0,Q.jsx)(In,{type:"autoflows",title:t("titleAutoflows"),"data-testid":"autoflows",children:(0,Q.jsx)(ht,{withDivider:!0,children:(0,Q.jsx)(_b,{})})}),f.map(({type:_,title:J,amount:Yr,lines:it})=>{var Gt;switch(_){case"entities":return y&&y.length>0&&(0,Q.jsx)(In,{type:_,title:J,"data-testid":`type-${_}`,children:(0,Q.jsx)(Ub,{entities:y})},_);case"cues":return m&&m.length>0&&(0,Q.jsx)(In,{type:_,title:J,"data-testid":`type-${_}`,children:(0,Q.jsx)(ht,{withDivider:!0,children:(0,Q.jsx)(dT,{cues:m})})},_);default:return((Gt=T[_])==null?void 0:Gt.fetchState)==="done"&&T[_].suggestions.length>0&&(0,Q.jsx)(In,{type:_,title:J,"data-testid":`type-${_}`,children:(0,Q.jsx)(ht,{withDivider:!0,children:(0,Q.jsx)(gT,{lines:it,contentType:_,suggestions:T[_].suggestions.slice(0,Yr)||[]})})},_)}})]})})},ST=VM;function as(e){let t=new Range;return t.selectNodeContents(e),t}function wT(e,t,n){try{return Gr(e,t,n),!0}catch{return!1}}function af(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function lf(e){return"tagName"in e&&e.tagName==="BR"}var dl=/[\u200B-\u200D\uFEFF]/g;function Gr(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,i=!1;function s(l,u){let c=-1,f=/[\u200B-\u200D\uFEFF]/;if(!f.test(l))return u;for(let d=0;d<=l.length;d++)if(f.test(l[d])||c++,c===u)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let u=l.textContent,c=u.replace(dl,""),f=o+c.length,d=t>=o&&t<=f,m=n>=o&&n<=f;if(d){let y=s(u,t-o);y===0&&!m?r.setStartBefore(l):r.setStart(l,y)}m&&(r.setEnd(l,s(u,n-o)),i=!0),o=f;break}case Node.ELEMENT_NODE:{if(lf(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),i=!0;return}for(let c=0;c<l.childNodes.length&&(a(l.childNodes[c]),!i);c++);let u=l.lastChild;af(l)&&u&&!af(u)&&!lf(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function fl(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a,l,u=0;function c(f){let d=f===n,m=f===o;switch(f.nodeType){case Node.TEXT_NODE:{let y=f.textContent;d&&(a=u+y.substring(0,r).replace(dl,"").length),m&&(l=u+y.substring(0,i).replace(dl,"").length),u+=y.replace(dl,"").length;break}case Node.ELEMENT_NODE:{let y=f.nextSibling===null;lf(f)&&!y&&u++;for(let v=0;v<f.childNodes.length;v++){let p=d&&v===r,g=m&&v===i;if(p&&(a=u),g&&(l=u),l!==void 0||((!p||!s)&&c(f.childNodes[v]),m&&v===i-1&&(l=u),l!==void 0))break}!m&&af(f)&&!y&&u++,m&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a??l,end:l}}function pl(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i}=t,s=-1,a="";function l(u){let c=u===n,f=u===o;switch(c&&s++,u.nodeType){case Node.TEXT_NODE:{if(s!==0)return;let d=c?r:0,m=f?i:void 0,y=u.textContent.replace(dl,"");d===0&&m===void 0?a+=y:a+=y.substring(d,m);break}case Node.ELEMENT_NODE:{let d=u.nextSibling===null;s===0&&lf(u)&&!d&&(a+=`
|
|
25
25
|
`);for(let m=c?r:0;m<(f?Math.min(i,u.childNodes.length):u.childNodes.length)&&(l(u.childNodes[m]),s!==1);m++);!f&&s===0&&af(u)&&!d&&(a+=`
|
|
26
|
-
`);break}default:break}f&&s++}return l(e),a}var xT=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(xT||{}),rr=class{constructor(t){this.element=t;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(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}triggerChange(){let t=this.getText(),n=this.getHTML(),r=t!==this.currentText;this.isActive&&(t===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&r&&!this.isSubmitting&&this.emit("change",{plainText:t}),r&&(this.currentSelection=this.getSelection()),this.currentText=t,this.isSubmitting=!1,(this.currentHTML!==n||n===null&&r)&&(this.emit("updated",{plainText:t}),this.triggerCaretPosition(),this.currentHTML=n))}triggerSelection(){let t=this.getSelection();(t.start!==this.currentSelection.start||t.end!==this.currentSelection.end)&&(this.currentSelection=t,this.emit("selection",t),this.triggerCaretPosition())}triggerCaretPosition(){let t=this.getCaretPosition();Nr(t,this.currentCaret)||(this.currentCaret=t,this.emit("caret",t))}handleKeyUp(t){let{key:n,shiftKey:r}=t;(n==="Enter"&&r===!0||n==="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(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(xT).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){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 t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()}),this.currentSelection=this.getSelection()}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function ET(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var zo=class extends rr{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),pl(this.element,t)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let t=this.getRootNode();if(t.activeElement!==this.element)return null;let n="getSelection"in t?t.getSelection():window.getSelection();if(!n)return null;let r="getComposedRanges"in n&&t instanceof ShadowRoot?(i=n.getComposedRanges(t))==null?void 0:i[0]:n.rangeCount>0?n.getRangeAt(0):null;if(!r)return null;let o=this.element.ownerDocument.createRange();return o.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),o.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!o||!this.element.contains(o.startContainer)||!this.element.contains(o.endContainer)?null:o}getCaretPosition(){let t=this.getRange();if(!t||!t.collapsed||!("getBoundingClientRect"in t))return null;let n=t.getBoundingClientRect();return!ET(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!ET(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return fl(this.element,t);let n=this.lastKnownSelection;if(n&&wT(this.element,n.start,n.end))return n;let r=as(this.element);return r.collapse(!1),fl(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return pl(this.element,Gr(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let t=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==t&&(t=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>n.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var Vo=class extends rr{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:t,selectionEnd:n}=this.element;return{start:t,end:n}}getSelectedText(){let t=this.getSelection();return t?this.getText().slice(t.start,t.end):""}getCaretPosition(){return null}applyChanges(t){if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let t=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var o;return(o=t==null?void 0:t.get)==null?void 0:o.call(this.element)},set:o=>{var i;(i=t==null?void 0:t.set)==null||i.call(this.element,o),this.triggerChange()}});let n=this.element.disabled,r=new MutationObserver(()=>{this.element.disabled!==n&&(n=this.element.disabled,this.emit(n?"disabled":"enabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>r.disconnect())}};function CT(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function KM(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}var uy=class{constructor(t){this.name=t;this.broadcastChannel=new BroadcastChannel(t)}broadcastChannel;disposeHandlers=[];onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},cy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=CT(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},dy=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),K.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new cy(t,this.deepdeskUrl,{debug:!0}):new uy(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=KM(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(K.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;K.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage({...o,channel:this.sessionId})}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},bT=dy;var ls=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var fy=e=>new Promise(t=>{setTimeout(t,e)});var us=class extends ls{name="ClientError"},my=class extends ls{name="ServerError"},py=new Map,pn=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",{useCache:u=!1,abortLatest:c=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:m=!0,retryOnError:y=C=>C instanceof TypeError,retryOnResponse:v=C=>C.status>=500,version:p="v1",...g}=n;if(u)if(l){if(py.has(s)){r(py.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h={credentials:"include",...g,headers:{"Content-Type":"application/json",...g.headers}};!l&&this.csrfToken&&(h.headers={...h.headers,"X-CSRFToken":this.csrfToken}),typeof p=="string"&&(h.headers={...h.headers,"X-Deepdesk-API-Version":p});let S=f,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&c&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let T=async()=>(S--,a(s,h).then(async C=>v(C)&&!i.isAborted&&S>0?(await fy(d),T()):C.status===401&&m===!0&&x===!1?(x=!0,await this.refreshToken(),T()):C).catch(async C=>{if(y(C)&&!i.isAborted&&S>0)return await fy(d),T();throw C}));T().then(C=>C.json().catch(()=>null).then(k=>{C.status>=500?o(new my("Server Error",k)):C.status===401?o(new us("Unauthorized",k)):C.status===403?o(new us("Forbidden",k)):C.status===404?o(new us("Not Found",k)):C.status>=400&&o(new us("Bad Request",k)),delete this.latestRequestByUrl[s],u&&py.set(s,k),r(k)})).catch(C=>{o(C)})})}async validateToken(){let{has_valid_access_token:t}=await this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return e.refreshingToken||(e.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{e.refreshingToken=null},1e3*60)})),e.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,{method:"POST",body:JSON.stringify(n),...r})}patch(t,n,r){return this.request(t,{method:"PATCH",body:JSON.stringify(n),...r})}put(t,n,r){return this.request(t,{method:"PUT",body:JSON.stringify(n),...r})}delete(t,n){return this.request(t,{method:"DELETE",...n})}};var $M;(t=>{let e;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||={})})($M||={});function uf(e){return{...ee(e),tags:e.tags}}var or=class e{constructor(t,n={}){this.options=n;this.client=new pn(t,{fetch:n.fetch}),this.client.patchFetch(r=>async(o,i)=>{let s=await r(o,i);return this.handleDeepdeskVersionHeaders(s),s})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=await this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(e.exchangeTokenPromise||(e.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),e.exchangeTokenPromise):Promise.resolve()}async createConversation(t){await this.preflight(),K.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...Ae(t),tags:t.tags},{version:"v2"});return uf(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null,useCache:!0});return ee(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null,useCache:!0});return ee(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return ee(t)}async getAccount(){let t=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return ee(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null,useCache:!0});return ee(t)}async checkUserExists(t){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n}async getConversationBySessionId(t,n={}){await this.preflight(),K.info(`Getting conversation for session ${t}`);let{attempts:r=1,retryDelay:o=1e3}=n,i=await this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"});return K.info(`Successfully retrieved conversation ${i.id} for session ${t}`),uf(i)}async isConversationSupported(t,n={}){K.info(`Check if conversation for session ${t} is supported`);let{attempts:r=1,retryDelay:o=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"})).has_active_profile}async updateConversation(t,n){let r=Ae(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return uf(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...Ae(o),tags:o.tags})),{version:"v2"})).map(o=>uf(o))}async sendEvent(t,n){let{data:r,...o}=n,i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[a,l])=>({...s,[a]:l}),{});return this.client.post("/api/events",Ae({...i,...o,data:r,name:t}),{version:"v2"})}async sendEventV1(t,n){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>({...o,[i]:s}),{});return this.client.post("/api/events",{event:t,data:Ae({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){return(await this.client.post("/api/summary",{conversation:{messages:t.filter(o=>o.text&&o.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(t){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw K.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.preflight(),await this.client.post("/apis/admin/session/api-key/",Ae(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})}async getTextSuggestions(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(await this.client.post(`/api/conversations/${t}/recommend/${r}`,Ae(n),{abortLatest:!0})).map(i=>({...ee(i),text:i.text||i.url||i.message,source:r,type:r})).filter((i,s,a)=>s===a.findIndex(l=>l.text===i.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(t,n){return(await this.client.post(`/api/conversations/${t}/autocomplete`,Ae(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))}async getPinnedMessages(t){let n=await this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return ee(n).map(r=>({...r,text:r.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(t){let n=await this.client.post("/api/style-suggestions",Ae(t),{abortLatest:!0});return ee(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,Ae(t),{version:"v2"});return ee(n)}async knowledgeAssist(t,n,r,o={}){let i=await this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Ae({question:t.question,promptInstruction:t.promptInstruction,chatHistory:n.map(s=>({question:s.question,answer:s.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return ee(i)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return ee(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return ee(t.token)}async getCsrfToken(){let{token:t}=await this.client.get("/apis/admin/session/csrf/",{version:null});return t}async verifyLoginToken(t){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return ee(n)}async evaluateRule(t,n,r,o={}){let i=new URLSearchParams;o.raiseForFailingConditions&&i.set("raise_for_failing_conditions","true");let s=await this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${i.toString()}`,r,{version:"v2"});return ee(s.cues)}async getRules(){let t=new URLSearchParams,n=await this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{version:null,useCache:!0});return ee(n)}async translateMessages(t){let n=await this.client.post("/api/translate",Ae(t),{version:"v2"});return ee(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Ov);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&K.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var ml=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(Dg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,ee(o))}catch{K.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var WM;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(WM||={});var gl=class{constructor(t,n={}){this.apiUrl=t;this.client=new pn(t,n)}client;streams={};logger=K;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return ee(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,Ae(n));return ee(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,Ae(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return ee(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",Ae(t));return ee(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new ml(`${this.apiUrl}/sessions/${t}/events`),this.streams[t].connect()),this.streams[t]}closeStream(t){this.streams[t]||(this.streams[t].disconnect(),delete this.streams[t])}};var TT={startTime:null,stopTime:null},kT=W({name:"handlingTime",initialState:TT,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(le,()=>TT)}}),{handlingTimeStart:PT,handlingTimeStop:cf,handlingTimeReset:RT}=kT.actions,AT=kT.reducer;var LT=(e={})=>{let t={onAuthError:ji(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var df={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var Ko=B("styleSuggestions/getAll",async({text:e},t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),{showStyleSuggestions:o}=r.settings,i=(s=r.conversation.current)==null?void 0:s.profileCode;if(!o)return df.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),qM=W({name:"styleSuggestions",initialState:df,reducers:{},extraReducers:e=>{e.addCase(Ko.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(Ko.rejected,t=>{t.fetchState="error"}).addCase(Ko.fulfilled,(t,n)=>{t.fetchState="done",Nr(t.list,n.payload)||(t.list=n.payload)}).addCase(Eo,t=>{t.list=df.list}).addCase(le,()=>df)}}),IT=qM.reducer;var OT=(e={})=>{let t,n=!0,r={getStyleSuggestions:Ko,debounce:500,...e};return o=>i=>s=>{var m;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((m=u.conversation.current)==null?void 0:m.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function GM(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var NT=(e={})=>{let t={getTextSuggestions:un,getAutocompleteSuggestions:Xa,debounce:200,check:Ji,...e},n;return r=>o=>i=>{var v;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,f=(v=l.conversation.current)==null?void 0:v.id,d=i.type===Pd.toString();if(!f||!u&&!c)return a;let{input:{userCommitted:m}}=l;return GM(m,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let p=Vi(l);p===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(p))},d?0:t.debounce)),a}};var MT=Ko.fulfilled.toString();function YM(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var _T=e=>t=>n=>r=>{var u;if(r.type!==MT){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=YM(o,s);r.type===MT&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var XM=oc({answer:$E,auth:Zx,autoflows:ab,conversation:a1,contentTypes:oE,customMessages:hb,passwordlessToken:wb,entities:IE,knowledgeAssistant:zE,handlingTime:AT,info:k1,input:E1,settings:$x,profile:GE,search:N1,summary:FE,styleSuggestions:IT,ui:wC,rules:bb,textSuggestions:rC});function DT(e){return Qw({reducer:XM,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),LT(),NT({debounce:200}),OT({debounce:500}),_T(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var QM=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},ZM=e=>t=>n=>r=>{var a;let o=t.getState(),i=Ag("inlineSuggestions")(o);switch(r.type){case ji.toString():{!r.payload&&e.emit("logout",void 0);break}case an.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:o.conversation.current.id,data:{entities:r.payload}});break;case Gn.fulfilled.toString():e.sendEvent("conversation summarized",{conversationId:o.conversation.current.id,data:{summary:r.payload.summary}});break;case Ye.toString():e.sendEvent(r.payload.name,{conversationId:((a=r.payload.options)==null?void 0:a.includeConversationData)&&o.conversation.current.id,data:r.payload.data});break;case Vc.toString():e.handleKeyDown(r.payload);break;case Eo.toString():e.logSendMessage(r.payload);break;case Kc.toString():e.handleInputChanged(r.payload);break;case Bo.fulfilled.toString():r.isBroadcasted||e.broadcast(Ug,r,!1),e.emit("cues",r.payload);break;default:break}let s=n(r);switch(r.type){case Eo.toString():e.handleAfterSendMessage(r.payload);break;case Za.toString():e.onUpdateShowTabHint(r.payload);break;case cf.toString():e.logHandlingTime();break;case Cn.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",{type:QM(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0}),i&&(t.dispatch(En([])),t.dispatch(Kn()));break}case zc.toString():{let{start:l,end:u}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case ka.toString():{let l=t.getState(),{text:u,selection:c}=l.input.userCommitted;e.emit("reset",{text:u,selectionAfter:c},{mayApplyChanges:!0});break}case $c.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:o.conversation.current.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case En.toString():{i&&r.payload.length>0&&t.dispatch(_r(0));break}default:break}return s},FT=ZM;function gy(e){return e.toISOString().replace("T"," ").replace("Z","")}function HT(e,t){var o,i,s;let{startTime:n,stopTime:r}=e.handlingTime;if(!n||!r)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:e.conversation.current.id,clientVersion:t.version,agentId:(o=e.info.agentInfo)==null?void 0:o.agentId,agentName:(i=e.info.agentInfo)==null?void 0:i.agentName,agentEmail:(s=e.info.agentInfo)==null?void 0:s.agentEmail,timeStart:gy(n),timeStop:gy(r)}}function UT(e,t,n){var k,L,I;let{text:r,metrics:{numCharsTyped:o,numCharsPasted:i,numCharsCut:s,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:u,externalTimeTotalSeconds:c,pastes:f,cuts:d,deletions:m,textSuggestions:y,offeredTextSuggestions:v}}=t[e],p=r.length,h=y.reduce((N,{text:z,searchTerm:_})=>N+z.length-(_?_.length:0),0),S=u??Date.now(),x=(Date.now()-S)/1e3+(c||0),T=o/x,C=y.reduce((N,{searchTerm:z})=>N+(z?z.length:0),0);return{conversationId:t.conversation.current.id,source:"agent",text:r,clientVersion:n.version,pastes:f,cuts:d,deletions:m,lenTextTyped:o+C,lenTextTotal:p,lenTextAssisted:h,lenTextPasted:i,lenTextCut:s,lenTextDeleted:a,timeTotalSeconds:x,charsPerSecond:T,numPastes:l,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:v.filter(N=>N.source==="gpt").length}],agentId:(k=t.info.agentInfo)==null?void 0:k.agentId,agentName:(L=t.info.agentInfo)==null?void 0:L.agentName,agentEmail:(I=t.info.agentInfo)==null?void 0:I.agentEmail}}function hy(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return hy(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?hy(o,t):null}function BT(e,t){return hy(e,t)}function jT(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function JM(e){return typeof e=="object"&&e!==null&&"tagName"in e}function ff(e){return JM(e)&&(Kr(e)||_d(e))}var zT,kn=new Map,e2=["bottom","height","left","right","top","width"],t2=(e={},t={})=>e2.some(n=>e[n]!==t[n]);function VT(e){var n,r;if(e.ownerDocument===document)return[];let t=((r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)??null;return t?[t,...VT(t)]:[]}function KT(e,t){return!e||!t?null:{...e,top:e.top+t.top,left:e.left+t.left}}var pf=!1,$T=()=>{pf=!0;let e=[];if(kn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),kn.delete(n);return}let r=n.getBoundingClientRect();t2(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(KT,t.rect):t.rect;t.callbacks.forEach(r=>r(n))}),kn.size===0){pf=!1;return}zT=window.requestAnimationFrame($T)};function yy(e,t){let n=VT(e),r=[],o=n.map((i,s)=>yy(i,a=>{r[s]=a;let l=kn.get(e);if(!l)return;let u=r.reduce(KT,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),kn.has(e)){let s=kn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else kn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!pf&&$T()},unobserve(){o.forEach(s=>s.unobserve());let i=kn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||kn.delete(e),kn.size||(cancelAnimationFrame(zT),pf=!1)}}}}var WT,Pn=new Map,qT=()=>{Pn.forEach((e,t)=>{if(!t.isConnected){Pn.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),Pn.size!==0&&(WT=window.requestAnimationFrame(qT))};function GT(e,t){return{observe(){let n=Pn.size===0;Pn.has(e)?Pn.get(e).callbacks.push(t):Pn.set(e,{visible:void 0,callbacks:[t]}),n&&qT()},unobserve(){let n=Pn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Pn.delete(e),Pn.size||cancelAnimationFrame(WT)}}}}var vy=["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 Sy(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function cs(e){return parseFloat(e)}function mf(e){return Math.round(e*1e6)}function YT(e){return e/1e6}function wy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=cs(e.width),i=cs(e.borderLeftWidth),s=cs(e.borderRightWidth),a=cs(e.paddingRight),l=YT(mf(o)-mf(i)-mf(s)),u=YT(mf(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function hl(e,t={}){var c;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=t.position??"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Fo(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};Sy(r,n,vy),wy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=GT(e,()=>{Sy(r,n,vy),wy(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=yy(e,f=>{if(f===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),f.height===0&&f.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(Sy(r,n,vy),wy(r,e,n),i(),n.style.top=`${f.top}px`,n.style.left=`${f.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let d=t.closestScrollElement.getBoundingClientRect(),m=window.getComputedStyle(t.closestScrollElement),y=cs(m.borderTopWidth),v=cs(m.borderBottomWidth),p=d.top+y-f.top,g=f.top+f.height+-(d.top+d.height-v);n.style.clipPath=`inset(${p}px 0px ${g}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(c=e.parentElement)==null||c.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var XT=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch{return t}}catch{return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch{K.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function n2(e){return e.offsetParent!==null}function QT(e){if(!n2(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function gf(e,t,n=100){let r=QT(e);t({isVisible:r});let o=setInterval(()=>{let i=QT(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Ie=w(b());var ZT=XT("showTabHint",!0),yl=class e{static version="11.1.1-beta.4";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new or(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[FT({broadcast:(f,d,m)=>{this.broadcastEvents.send(f,d,m)},emit:(f,d,m)=>this.emit(f,d,m),handleAfterSendMessage:f=>this.handleAfterSendMessage(f),handleInputChanged:f=>this.handleInputChanged(f),handleKeyDown:f=>this.handleKeyDown(f),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:f=>this.logSendMessage(f),onUpdateShowTabHint:f=>ZT.update(f),sendEvent:(f,d)=>this.deepdeskApi.sendEvent(f,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new gl(n)}),this.store=DT(c),this.broadcastEvents=new bT({debug:!0,deepdeskUrl:u,eventMap:M1(this.store),createCustomChannel:l}),this.store.dispatch(Za(ZT.value())),this.store.dispatch(Nc({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(K.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(K.warn("Profile has not been loaded (yet)"),!0):(K.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(ji(null)),this.store.dispatch(zn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();tt(r)&&Wx(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(zn())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){K.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Ng({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Fc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(Hc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Mg(t))).payload}async postMessages(t){return(await this.store.dispatch(Bc(t))).payload}async updateConversation(t){return(await this.store.dispatch(Uc(t))).payload}resetConversation(){this.store.dispatch(le()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(Gn());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(Nc(t))}setVisitorInfo(t){this.store.dispatch(T1(t))}async setAgentInfo(t){await this.store.dispatch(Pa(t))}async setAgentSettings(t){await this.store.dispatch(Fg(t))}async getAgentSettings(){return(await this.store.dispatch(Hg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(Pd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(Kc(t))}notifyKeyDown(t){this.store.dispatch(Vc(t))}notifyPaste(t,n){this.store.dispatch(v1({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(h1(t))}notifyExternalSuggestion(t){this.store.dispatch(Cn(t)),this.store.dispatch(Kn())}async evaluateRule(t,n={}){let{payload:r,error:o}=await this.store.dispatch(Bo({label:t,params:n}));if(o)throw new Error(o.message);return r}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(zr({collapse:!1})),this.inputMediator&&this.store.dispatch(d1({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(En([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(y1(l1(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(p1()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(g1()),t.preventDefault(),!s&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(ka()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(_r(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(_r(-1)),this.store.dispatch(ka()),t.preventDefault()):n||(this.store.dispatch(zr({collapse:!0})),this.store.dispatch(vC(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:f}=this.state.input,d=f.text.substring(0,f.selection.end),{tabCompletionSuggestion:m}=this.state.input;this.store.dispatch(Za(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&m&&m.text.startsWith(d)&&(this.store.dispatch(Cn({text:m.text,suggestion:m,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(Kn())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(S1()),this.store.dispatch(En([]))}handlingTimeStart(){this.state.handlingTime.startTime||(K.info("Start handling time"),this.store.dispatch(PT()))}handlingTimeStop(){this.state.handlingTime.startTime&&(K.info("Stop handling time"),this.store.dispatch(cf()))}logSendMessage(t){let n=UT("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logHandlingTime(){let t=HT(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(RT())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(Kn()),this.store.dispatch(Eo(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Cn({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){K.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),K.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=hl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,qt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=hl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,qt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Fo(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,qt.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),K.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(K.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(x1(r.metrics))):K.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!ff(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:f,detectSubmit:d,insertLink:m,inputMediator:y,closestScrollSelector:v,appendOverlayTo:p,inlineSuggestions:g,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:m,isEmbedded:f,inlineSuggestions:g,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Fo(t),this.inputMediator=y||(Kr(t)?new Vo(t):new zo(t)),this.inputMediator.on("change",({plainText:T})=>{this.notifyInputChanged(T)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(w1({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",T=>{this.notifyKeyDown(T)}),this.inputMediator.on("paste",({pastedText:T,selectionText:C})=>{this.notifyPaste(T,C)}),this.inputMediator.on("cut",({selectionText:T})=>{this.notifyCut(T)});let S=v&&BT(t,v)||void 0;if(g){let{customStyles:T,appendOverlayTo:C}=n;if(Kr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let k=this.createInlineContainer(t,"deepdesk-caret");(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:T,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(kC,{})})}),k),this.inputMediator.on("caret",I=>{this.store.dispatch(En([])),I?(k.style.display="block",k.style.top=`${I.top}px`,k.style.left=`${I.left}px`):k.style.display="none"});let L=this.overlayContainerFactory("floating-menu",S||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:C},T==null?void 0:T.floatingMenuRootNode);(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:T,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(gC,{onLogIn:()=>this.loginViaPopup().catch(I=>K.warn(I.message))})})}),L)}else{let T=this.overlayContainerFactory("deepdesk-tab-completion",S||t,{appendTo:p,closestScrollElement:S,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",S||t,{appendTo:p},r==null?void 0:r.suggestionsRootNode);(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:r,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(tb,{inputElement:t})})}),T),(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:r,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(_C,{onLogIn:()=>this.loginViaPopup().catch(k=>K.warn(k.message))})})}),C)}(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:r,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(cC,{})})}),this.createContainer("deepdesk-overlays"));let x;this.inputMediator.on("selection",T=>{clearTimeout(x),T===null?x=setTimeout(()=>{T!==null&&this.store.dispatch(_g(T))},500):this.store.dispatch(_g(T))}),this.inputMediator.on("disabled",()=>{var T;(T=this.inputMediator)==null||T.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Eh(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Eh(!0))),this.store.dispatch(f1({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(Kn()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var T;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((T=this.state.conversation.current)==null?void 0:T.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&K.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:r,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(ST,{onLogIn:()=>this.loginViaPopup().catch(s=>K.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,qt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=gf(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){jT(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Ya());let t=jr(this.state);t&&(await this.store.dispatch(qa()),this.store.dispatch(Nc({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(t){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=async m=>{var y,v;if((y=m.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=m.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Aa),l=!0,o.port1.close(),n()}catch(p){console.error(p),r(p)}finally{l=!0,u()}};let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let f=async m=>{var y;if(m.origin===a.origin)switch((y=m.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){K.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),m.data.message==="Timeout"&&K.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(m.data.message));break}}};window.addEventListener("message",f);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(K.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;K.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Td(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(an()):this.store.dispatch(un(r))})}catch(r){this.handleError(r)}}};async function JT(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function ek(e,t,n={}){let r=n.replace?Gr(e,n.replace.start,n.replace.end):as(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
|
|
26
|
+
`);break}default:break}f&&s++}return l(e),a}var xT=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(xT||{}),rr=class{constructor(t){this.element=t;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(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}triggerChange(){let t=this.getText(),n=this.getHTML(),r=t!==this.currentText;this.isActive&&(t===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&r&&!this.isSubmitting&&this.emit("change",{plainText:t}),r&&(this.currentSelection=this.getSelection()),this.currentText=t,this.isSubmitting=!1,(this.currentHTML!==n||n===null&&r)&&(this.emit("updated",{plainText:t}),this.triggerCaretPosition(),this.currentHTML=n))}triggerSelection(){let t=this.getSelection();(t.start!==this.currentSelection.start||t.end!==this.currentSelection.end)&&(this.currentSelection=t,this.emit("selection",t),this.triggerCaretPosition())}triggerCaretPosition(){let t=this.getCaretPosition();Nr(t,this.currentCaret)||(this.currentCaret=t,this.emit("caret",t))}handleKeyUp(t){let{key:n,shiftKey:r}=t;(n==="Enter"&&r===!0||n==="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(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(xT).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(t={shouldObserve:!0}){this.addEventListener("keydown",r=>this.handleKeyDown(r)),this.addEventListener("keyup",r=>this.handleKeyUp(r)),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",r=>this.handlePaste(r)),this.addEventListener("click",()=>this.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let n=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t!=null&&t.shouldObserve&&n.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{n.disconnect()}),this.currentSelection=this.getSelection()}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function ET(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var zo=class extends rr{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),pl(this.element,t)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let t=this.getRootNode();if(t.activeElement!==this.element)return null;let n="getSelection"in t?t.getSelection():window.getSelection();if(!n)return null;let r="getComposedRanges"in n&&t instanceof ShadowRoot?(i=n.getComposedRanges(t))==null?void 0:i[0]:n.rangeCount>0?n.getRangeAt(0):null;if(!r)return null;let o=this.element.ownerDocument.createRange();return o.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),o.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!o||!this.element.contains(o.startContainer)||!this.element.contains(o.endContainer)?null:o}getCaretPosition(){let t=this.getRange();if(!t||!t.collapsed||!("getBoundingClientRect"in t))return null;let n=t.getBoundingClientRect();return!ET(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!ET(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return fl(this.element,t);let n=this.lastKnownSelection;if(n&&wT(this.element,n.start,n.end))return n;let r=as(this.element);return r.collapse(!1),fl(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return pl(this.element,Gr(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(t={shouldObserve:!0}){super.listen(t),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),t!=null&&t.shouldObserve&&this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let n=this.element.isContentEditable,r=new MutationObserver(()=>{this.element.isContentEditable!==n&&(n=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>r.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var Vo=class extends rr{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:t,selectionEnd:n}=this.element;return{start:t,end:n}}getSelectedText(){let t=this.getSelection();return t?this.getText().slice(t.start,t.end):""}getCaretPosition(){return null}applyChanges(t){if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let t=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var o;return(o=t==null?void 0:t.get)==null?void 0:o.call(this.element)},set:o=>{var i;(i=t==null?void 0:t.set)==null||i.call(this.element,o),this.triggerChange()}});let n=this.element.disabled,r=new MutationObserver(()=>{this.element.disabled!==n&&(n=this.element.disabled,this.emit(n?"disabled":"enabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>r.disconnect())}};function CT(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function KM(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}var uy=class{constructor(t){this.name=t;this.broadcastChannel=new BroadcastChannel(t)}broadcastChannel;disposeHandlers=[];onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},cy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=CT(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},dy=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),K.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new cy(t,this.deepdeskUrl,{debug:!0}):new uy(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=KM(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(K.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;K.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage({...o,channel:this.sessionId})}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},bT=dy;var ls=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var fy=e=>new Promise(t=>{setTimeout(t,e)});var us=class extends ls{name="ClientError"},my=class extends ls{name="ServerError"},py=new Map,pn=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",{useCache:u=!1,abortLatest:c=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:m=!0,retryOnError:y=C=>C instanceof TypeError,retryOnResponse:v=C=>C.status>=500,version:p="v1",...g}=n;if(u)if(l){if(py.has(s)){r(py.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h={credentials:"include",...g,headers:{"Content-Type":"application/json",...g.headers}};!l&&this.csrfToken&&(h.headers={...h.headers,"X-CSRFToken":this.csrfToken}),typeof p=="string"&&(h.headers={...h.headers,"X-Deepdesk-API-Version":p});let S=f,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&c&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let T=async()=>(S--,a(s,h).then(async C=>v(C)&&!i.isAborted&&S>0?(await fy(d),T()):C.status===401&&m===!0&&x===!1?(x=!0,await this.refreshToken(),T()):C).catch(async C=>{if(y(C)&&!i.isAborted&&S>0)return await fy(d),T();throw C}));T().then(C=>C.json().catch(()=>null).then(k=>{C.status>=500?o(new my("Server Error",k)):C.status===401?o(new us("Unauthorized",k)):C.status===403?o(new us("Forbidden",k)):C.status===404?o(new us("Not Found",k)):C.status>=400&&o(new us("Bad Request",k)),delete this.latestRequestByUrl[s],u&&py.set(s,k),r(k)})).catch(C=>{o(C)})})}async validateToken(){let{has_valid_access_token:t}=await this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return e.refreshingToken||(e.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{e.refreshingToken=null},1e3*60)})),e.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,{method:"POST",body:JSON.stringify(n),...r})}patch(t,n,r){return this.request(t,{method:"PATCH",body:JSON.stringify(n),...r})}put(t,n,r){return this.request(t,{method:"PUT",body:JSON.stringify(n),...r})}delete(t,n){return this.request(t,{method:"DELETE",...n})}};var $M;(t=>{let e;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||={})})($M||={});function uf(e){return{...ee(e),tags:e.tags}}var or=class e{constructor(t,n={}){this.options=n;this.client=new pn(t,{fetch:n.fetch}),this.client.patchFetch(r=>async(o,i)=>{let s=await r(o,i);return this.handleDeepdeskVersionHeaders(s),s})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=await this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(e.exchangeTokenPromise||(e.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),e.exchangeTokenPromise):Promise.resolve()}async createConversation(t){await this.preflight(),K.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...Ae(t),tags:t.tags},{version:"v2"});return uf(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null,useCache:!0});return ee(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null,useCache:!0});return ee(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return ee(t)}async getAccount(){let t=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return ee(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null,useCache:!0});return ee(t)}async checkUserExists(t){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n}async getConversationBySessionId(t,n={}){await this.preflight(),K.info(`Getting conversation for session ${t}`);let{attempts:r=1,retryDelay:o=1e3}=n,i=await this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"});return K.info(`Successfully retrieved conversation ${i.id} for session ${t}`),uf(i)}async isConversationSupported(t,n={}){K.info(`Check if conversation for session ${t} is supported`);let{attempts:r=1,retryDelay:o=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"})).has_active_profile}async updateConversation(t,n){let r=Ae(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return uf(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...Ae(o),tags:o.tags})),{version:"v2"})).map(o=>uf(o))}async sendEvent(t,n){let{data:r,...o}=n,i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[a,l])=>({...s,[a]:l}),{});return this.client.post("/api/events",Ae({...i,...o,data:r,name:t}),{version:"v2"})}async sendEventV1(t,n){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>({...o,[i]:s}),{});return this.client.post("/api/events",{event:t,data:Ae({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){return(await this.client.post("/api/summary",{conversation:{messages:t.filter(o=>o.text&&o.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(t){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw K.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.preflight(),await this.client.post("/apis/admin/session/api-key/",Ae(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})}async getTextSuggestions(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(await this.client.post(`/api/conversations/${t}/recommend/${r}`,Ae(n),{abortLatest:!0})).map(i=>({...ee(i),text:i.text||i.url||i.message,source:r,type:r})).filter((i,s,a)=>s===a.findIndex(l=>l.text===i.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(t,n){return(await this.client.post(`/api/conversations/${t}/autocomplete`,Ae(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))}async getPinnedMessages(t){let n=await this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return ee(n).map(r=>({...r,text:r.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(t){let n=await this.client.post("/api/style-suggestions",Ae(t),{abortLatest:!0});return ee(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,Ae(t),{version:"v2"});return ee(n)}async knowledgeAssist(t,n,r,o={}){let i=await this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Ae({question:t.question,promptInstruction:t.promptInstruction,chatHistory:n.map(s=>({question:s.question,answer:s.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return ee(i)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return ee(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return ee(t.token)}async getCsrfToken(){let{token:t}=await this.client.get("/apis/admin/session/csrf/",{version:null});return t}async verifyLoginToken(t){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return ee(n)}async evaluateRule(t,n,r,o={}){let i=new URLSearchParams;o.raiseForFailingConditions&&i.set("raise_for_failing_conditions","true");let s=await this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${i.toString()}`,r,{version:"v2"});return ee(s.cues)}async getRules(){let t=new URLSearchParams,n=await this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{version:null,useCache:!0});return ee(n)}async translateMessages(t){let n=await this.client.post("/api/translate",Ae(t),{version:"v2"});return ee(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Ov);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&K.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var ml=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(Dg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,ee(o))}catch{K.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var WM;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(WM||={});var gl=class{constructor(t,n={}){this.apiUrl=t;this.client=new pn(t,n)}client;streams={};logger=K;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return ee(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,Ae(n));return ee(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,Ae(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return ee(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",Ae(t));return ee(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new ml(`${this.apiUrl}/sessions/${t}/events`),this.streams[t].connect()),this.streams[t]}closeStream(t){this.streams[t]||(this.streams[t].disconnect(),delete this.streams[t])}};var TT={startTime:null,stopTime:null},kT=W({name:"handlingTime",initialState:TT,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(le,()=>TT)}}),{handlingTimeStart:PT,handlingTimeStop:cf,handlingTimeReset:RT}=kT.actions,AT=kT.reducer;var LT=(e={})=>{let t={onAuthError:ji(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var df={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var Ko=B("styleSuggestions/getAll",async({text:e},t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),{showStyleSuggestions:o}=r.settings,i=(s=r.conversation.current)==null?void 0:s.profileCode;if(!o)return df.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),qM=W({name:"styleSuggestions",initialState:df,reducers:{},extraReducers:e=>{e.addCase(Ko.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(Ko.rejected,t=>{t.fetchState="error"}).addCase(Ko.fulfilled,(t,n)=>{t.fetchState="done",Nr(t.list,n.payload)||(t.list=n.payload)}).addCase(Eo,t=>{t.list=df.list}).addCase(le,()=>df)}}),IT=qM.reducer;var OT=(e={})=>{let t,n=!0,r={getStyleSuggestions:Ko,debounce:500,...e};return o=>i=>s=>{var m;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((m=u.conversation.current)==null?void 0:m.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function GM(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var NT=(e={})=>{let t={getTextSuggestions:un,getAutocompleteSuggestions:Xa,debounce:200,check:Ji,...e},n;return r=>o=>i=>{var v;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,f=(v=l.conversation.current)==null?void 0:v.id,d=i.type===Pd.toString();if(!f||!u&&!c)return a;let{input:{userCommitted:m}}=l;return GM(m,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let p=Vi(l);p===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(p))},d?0:t.debounce)),a}};var MT=Ko.fulfilled.toString();function YM(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var _T=e=>t=>n=>r=>{var u;if(r.type!==MT){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=YM(o,s);r.type===MT&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var XM=oc({answer:$E,auth:Zx,autoflows:ab,conversation:a1,contentTypes:oE,customMessages:hb,passwordlessToken:wb,entities:IE,knowledgeAssistant:zE,handlingTime:AT,info:k1,input:E1,settings:$x,profile:GE,search:N1,summary:FE,styleSuggestions:IT,ui:wC,rules:bb,textSuggestions:rC});function DT(e){return Qw({reducer:XM,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),LT(),NT({debounce:200}),OT({debounce:500}),_T(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var QM=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},ZM=e=>t=>n=>r=>{var a;let o=t.getState(),i=Ag("inlineSuggestions")(o);switch(r.type){case ji.toString():{!r.payload&&e.emit("logout",void 0);break}case an.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:o.conversation.current.id,data:{entities:r.payload}});break;case Gn.fulfilled.toString():e.sendEvent("conversation summarized",{conversationId:o.conversation.current.id,data:{summary:r.payload.summary}});break;case Ye.toString():e.sendEvent(r.payload.name,{conversationId:((a=r.payload.options)==null?void 0:a.includeConversationData)&&o.conversation.current.id,data:r.payload.data});break;case Vc.toString():e.handleKeyDown(r.payload);break;case Eo.toString():e.logSendMessage(r.payload);break;case Kc.toString():e.handleInputChanged(r.payload);break;case Bo.fulfilled.toString():r.isBroadcasted||e.broadcast(Ug,r,!1),e.emit("cues",r.payload);break;default:break}let s=n(r);switch(r.type){case Eo.toString():e.handleAfterSendMessage(r.payload);break;case Za.toString():e.onUpdateShowTabHint(r.payload);break;case cf.toString():e.logHandlingTime();break;case Cn.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",{type:QM(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0}),i&&(t.dispatch(En([])),t.dispatch(Kn()));break}case zc.toString():{let{start:l,end:u}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case ka.toString():{let l=t.getState(),{text:u,selection:c}=l.input.userCommitted;e.emit("reset",{text:u,selectionAfter:c},{mayApplyChanges:!0});break}case $c.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:o.conversation.current.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case En.toString():{i&&r.payload.length>0&&t.dispatch(_r(0));break}default:break}return s},FT=ZM;function gy(e){return e.toISOString().replace("T"," ").replace("Z","")}function HT(e,t){var o,i,s;let{startTime:n,stopTime:r}=e.handlingTime;if(!n||!r)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:e.conversation.current.id,clientVersion:t.version,agentId:(o=e.info.agentInfo)==null?void 0:o.agentId,agentName:(i=e.info.agentInfo)==null?void 0:i.agentName,agentEmail:(s=e.info.agentInfo)==null?void 0:s.agentEmail,timeStart:gy(n),timeStop:gy(r)}}function UT(e,t,n){var k,L,I;let{text:r,metrics:{numCharsTyped:o,numCharsPasted:i,numCharsCut:s,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:u,externalTimeTotalSeconds:c,pastes:f,cuts:d,deletions:m,textSuggestions:y,offeredTextSuggestions:v}}=t[e],p=r.length,h=y.reduce((N,{text:z,searchTerm:_})=>N+z.length-(_?_.length:0),0),S=u??Date.now(),x=(Date.now()-S)/1e3+(c||0),T=o/x,C=y.reduce((N,{searchTerm:z})=>N+(z?z.length:0),0);return{conversationId:t.conversation.current.id,source:"agent",text:r,clientVersion:n.version,pastes:f,cuts:d,deletions:m,lenTextTyped:o+C,lenTextTotal:p,lenTextAssisted:h,lenTextPasted:i,lenTextCut:s,lenTextDeleted:a,timeTotalSeconds:x,charsPerSecond:T,numPastes:l,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:v.filter(N=>N.source==="gpt").length}],agentId:(k=t.info.agentInfo)==null?void 0:k.agentId,agentName:(L=t.info.agentInfo)==null?void 0:L.agentName,agentEmail:(I=t.info.agentInfo)==null?void 0:I.agentEmail}}function hy(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return hy(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?hy(o,t):null}function BT(e,t){return hy(e,t)}function jT(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function JM(e){return typeof e=="object"&&e!==null&&"tagName"in e}function ff(e){return JM(e)&&(Kr(e)||_d(e))}var zT,kn=new Map,e2=["bottom","height","left","right","top","width"],t2=(e={},t={})=>e2.some(n=>e[n]!==t[n]);function VT(e){var n,r;if(e.ownerDocument===document)return[];let t=((r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)??null;return t?[t,...VT(t)]:[]}function KT(e,t){return!e||!t?null:{...e,top:e.top+t.top,left:e.left+t.left}}var pf=!1,$T=()=>{pf=!0;let e=[];if(kn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),kn.delete(n);return}let r=n.getBoundingClientRect();t2(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(KT,t.rect):t.rect;t.callbacks.forEach(r=>r(n))}),kn.size===0){pf=!1;return}zT=window.requestAnimationFrame($T)};function yy(e,t){let n=VT(e),r=[],o=n.map((i,s)=>yy(i,a=>{r[s]=a;let l=kn.get(e);if(!l)return;let u=r.reduce(KT,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),kn.has(e)){let s=kn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else kn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!pf&&$T()},unobserve(){o.forEach(s=>s.unobserve());let i=kn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||kn.delete(e),kn.size||(cancelAnimationFrame(zT),pf=!1)}}}}var WT,Pn=new Map,qT=()=>{Pn.forEach((e,t)=>{if(!t.isConnected){Pn.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),Pn.size!==0&&(WT=window.requestAnimationFrame(qT))};function GT(e,t){return{observe(){let n=Pn.size===0;Pn.has(e)?Pn.get(e).callbacks.push(t):Pn.set(e,{visible:void 0,callbacks:[t]}),n&&qT()},unobserve(){let n=Pn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Pn.delete(e),Pn.size||cancelAnimationFrame(WT)}}}}var vy=["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 Sy(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function cs(e){return parseFloat(e)}function mf(e){return Math.round(e*1e6)}function YT(e){return e/1e6}function wy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=cs(e.width),i=cs(e.borderLeftWidth),s=cs(e.borderRightWidth),a=cs(e.paddingRight),l=YT(mf(o)-mf(i)-mf(s)),u=YT(mf(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function hl(e,t={}){var c;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=t.position??"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Fo(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};Sy(r,n,vy),wy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=GT(e,()=>{Sy(r,n,vy),wy(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=yy(e,f=>{if(f===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),f.height===0&&f.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(Sy(r,n,vy),wy(r,e,n),i(),n.style.top=`${f.top}px`,n.style.left=`${f.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let d=t.closestScrollElement.getBoundingClientRect(),m=window.getComputedStyle(t.closestScrollElement),y=cs(m.borderTopWidth),v=cs(m.borderBottomWidth),p=d.top+y-f.top,g=f.top+f.height+-(d.top+d.height-v);n.style.clipPath=`inset(${p}px 0px ${g}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(c=e.parentElement)==null||c.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var XT=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch{return t}}catch{return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch{K.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function n2(e){return e.offsetParent!==null}function QT(e){if(!n2(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function gf(e,t,n=100){let r=QT(e);t({isVisible:r});let o=setInterval(()=>{let i=QT(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Ie=w(b());var ZT=XT("showTabHint",!0),yl=class e{static version="11.1.1-beta.5";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new or(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[FT({broadcast:(f,d,m)=>{this.broadcastEvents.send(f,d,m)},emit:(f,d,m)=>this.emit(f,d,m),handleAfterSendMessage:f=>this.handleAfterSendMessage(f),handleInputChanged:f=>this.handleInputChanged(f),handleKeyDown:f=>this.handleKeyDown(f),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:f=>this.logSendMessage(f),onUpdateShowTabHint:f=>ZT.update(f),sendEvent:(f,d)=>this.deepdeskApi.sendEvent(f,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new gl(n)}),this.store=DT(c),this.broadcastEvents=new bT({debug:!0,deepdeskUrl:u,eventMap:M1(this.store),createCustomChannel:l}),this.store.dispatch(Za(ZT.value())),this.store.dispatch(Nc({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(K.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(K.warn("Profile has not been loaded (yet)"),!0):(K.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(ji(null)),this.store.dispatch(zn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();tt(r)&&Wx(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(zn())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){K.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Ng({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Fc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(Hc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Mg(t))).payload}async postMessages(t){return(await this.store.dispatch(Bc(t))).payload}async updateConversation(t){return(await this.store.dispatch(Uc(t))).payload}resetConversation(){this.store.dispatch(le()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(Gn());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(Nc(t))}setVisitorInfo(t){this.store.dispatch(T1(t))}async setAgentInfo(t){await this.store.dispatch(Pa(t))}async setAgentSettings(t){await this.store.dispatch(Fg(t))}async getAgentSettings(){return(await this.store.dispatch(Hg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(Pd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(Kc(t))}notifyKeyDown(t){this.store.dispatch(Vc(t))}notifyPaste(t,n){this.store.dispatch(v1({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(h1(t))}notifyExternalSuggestion(t){this.store.dispatch(Cn(t)),this.store.dispatch(Kn())}async evaluateRule(t,n={}){let{payload:r,error:o}=await this.store.dispatch(Bo({label:t,params:n}));if(o)throw new Error(o.message);return r}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(zr({collapse:!1})),this.inputMediator&&this.store.dispatch(d1({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(En([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(y1(l1(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(p1()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(g1()),t.preventDefault(),!s&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(ka()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(_r(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(_r(-1)),this.store.dispatch(ka()),t.preventDefault()):n||(this.store.dispatch(zr({collapse:!0})),this.store.dispatch(vC(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:f}=this.state.input,d=f.text.substring(0,f.selection.end),{tabCompletionSuggestion:m}=this.state.input;this.store.dispatch(Za(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&m&&m.text.startsWith(d)&&(this.store.dispatch(Cn({text:m.text,suggestion:m,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(Kn())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(S1()),this.store.dispatch(En([]))}handlingTimeStart(){this.state.handlingTime.startTime||(K.info("Start handling time"),this.store.dispatch(PT()))}handlingTimeStop(){this.state.handlingTime.startTime&&(K.info("Stop handling time"),this.store.dispatch(cf()))}logSendMessage(t){let n=UT("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logHandlingTime(){let t=HT(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(RT())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(Kn()),this.store.dispatch(Eo(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Cn({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){K.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),K.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=hl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,qt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=hl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,qt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Fo(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,qt.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),K.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(K.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(x1(r.metrics))):K.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!ff(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:f,detectSubmit:d,insertLink:m,inputMediator:y,closestScrollSelector:v,appendOverlayTo:p,inlineSuggestions:g,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:m,isEmbedded:f,inlineSuggestions:g,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Fo(t),this.inputMediator=y||(Kr(t)?new Vo(t):new zo(t)),this.inputMediator.on("change",({plainText:T})=>{this.notifyInputChanged(T)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(w1({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",T=>{this.notifyKeyDown(T)}),this.inputMediator.on("paste",({pastedText:T,selectionText:C})=>{this.notifyPaste(T,C)}),this.inputMediator.on("cut",({selectionText:T})=>{this.notifyCut(T)});let S=v&&BT(t,v)||void 0;if(g){let{customStyles:T,appendOverlayTo:C}=n;if(Kr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let k=this.createInlineContainer(t,"deepdesk-caret");(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:T,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(kC,{})})}),k),this.inputMediator.on("caret",I=>{this.store.dispatch(En([])),I?(k.style.display="block",k.style.top=`${I.top}px`,k.style.left=`${I.left}px`):k.style.display="none"});let L=this.overlayContainerFactory("floating-menu",S||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:C},T==null?void 0:T.floatingMenuRootNode);(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:T,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(gC,{onLogIn:()=>this.loginViaPopup().catch(I=>K.warn(I.message))})})}),L)}else{let T=this.overlayContainerFactory("deepdesk-tab-completion",S||t,{appendTo:p,closestScrollElement:S,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",S||t,{appendTo:p},r==null?void 0:r.suggestionsRootNode);(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:r,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(tb,{inputElement:t})})}),T),(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:r,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(_C,{onLogIn:()=>this.loginViaPopup().catch(k=>K.warn(k.message))})})}),C)}(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:r,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(cC,{})})}),this.createContainer("deepdesk-overlays"));let x;this.inputMediator.on("selection",T=>{clearTimeout(x),T===null?x=setTimeout(()=>{T!==null&&this.store.dispatch(_g(T))},500):this.store.dispatch(_g(T))}),this.inputMediator.on("disabled",()=>{var T;(T=this.inputMediator)==null||T.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Eh(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Eh(!0))),this.store.dispatch(f1({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(Kn()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var T;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((T=this.state.conversation.current)==null?void 0:T.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&K.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:r,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(ST,{onLogIn:()=>this.loginViaPopup().catch(s=>K.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,qt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=gf(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){jT(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Ya());let t=jr(this.state);t&&(await this.store.dispatch(qa()),this.store.dispatch(Nc({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(t){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=async m=>{var y,v;if((y=m.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=m.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Aa),l=!0,o.port1.close(),n()}catch(p){console.error(p),r(p)}finally{l=!0,u()}};let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let f=async m=>{var y;if(m.origin===a.origin)switch((y=m.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){K.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),m.data.message==="Timeout"&&K.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(m.data.message));break}}};window.addEventListener("message",f);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(K.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;K.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Td(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(an()):this.store.dispatch(un(r))})}catch(r){this.handleError(r)}}};async function JT(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function ek(e,t,n={}){let r=n.replace?Gr(e,n.replace.start,n.replace.end):as(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
|
|
27
27
|
`).reverse().forEach((s,a)=>{a>0&&r.insertNode(document.createElement("br")),r.insertNode(document.createTextNode(s))}):r.insertNode(document.createTextNode(t))};return Promise.resolve(i()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let s=n.selectionAfter?Gr(e,n.selectionAfter.start,n.selectionAfter.end):(r.collapse(!1),r),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(s)}if(!o)return;o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function r2(e){let t=document.createElement("template");return t.innerHTML=e.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),t.content}function o2(e){let t=document.createDocumentFragment();return e.split(`
|
|
28
28
|
`).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},i=0;for(;o=n.slice(i).match(/(\[([^\]]+)])\(([^)]+)\)/);){let s=document.createElement("a");s.href=o[3],s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer"),s.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(i,i+o.index))),t.appendChild(s),i=i+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(i)))}),t}function tk(e,t){return!e.contains(t)||t===e?null:t.parentNode===e?t:tk(e,t.parentNode)}async function nk(e,t,{isBlock:n,isHTML:r}={}){let o;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let i=()=>{let s=e.ownerDocument.defaultView??window,a=s.getSelection();if((!a||a.rangeCount===0)&&(e.focus(),a=s.getSelection()),!a||a.rangeCount===0)return;let l=a.getRangeAt(0);if(!l)return;o=document.createElement("span"),l.insertNode(o);let u=r?r2(t):o2(t);if(n){let c=l.startContainer===e?e.childNodes[l.startOffset]:l.startContainer,f=tk(e,c)??e.firstChild;e.insertBefore(u,(f==null?void 0:f.nextSibling)??null)}else l.insertNode(u),l.collapse(!1)};return Promise.resolve(i()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!o)try{o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function rk(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function ok(e,t,n){await new or(e).authenticateWithKey(t,n)}async function ik(e){let n=await new pn(e).get("/platform/config/",{version:null,useCache:!0});return ee(n)}async function i2(e){let n=await(e.fetch??window.fetch)(e.url),r=await n.blob();return new File([r],e.name,{type:e.mimeType??n.headers.get("Content-Type")??"image/jpeg"})}async function sk(e,t){let n=await i2(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}}return xk(s2);})();
|
|
29
29
|
/*! Bundled license information:
|