@deepdesk/deepdesk-sdk 15.1.1-beta.0 → 15.1.1-beta.1
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.esm.js +1 -1
- package/dist/index.iife.js +1 -1
- package/package.json +1 -1
package/dist/index.iife.js
CHANGED
|
@@ -24,7 +24,7 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
|
24
24
|
c6.8-6.8,15.4-10.2,24.7-10.2h11.9v-70c0-44.4,16.2-82.8,47.8-115.2S212.1,0,256.4,0s82.8,16.2,115.2,47.8
|
|
25
25
|
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 sy=x(E()),TN={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},mT=({className:e,color:t})=>(0,sy.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,sy.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:TN[t||"pink"]})});var gT={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedIn:"dd-XvHAn",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var ay={};lt(ay,{enUS:()=>CN,nlNL:()=>kN});var CN={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},kN={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Go=x(E()),yT=({onLogIn:e})=>{let t=q(ay),n=U("floatingMenu"),r=U("productName"),o=Z(),i=_(ft),s=A("FloatingMenu",gT);if(i===null||n===!1)return null;let a=()=>{i===!0?o(Qt(!0)):e()};return(0,Go.jsxs)("button",{className:(0,hT.default)(s.root,{[s.isLoggedIn]:i,[s.isLoggedOut]:!i}),onClick:a,children:[(0,Go.jsx)("div",{className:s.text,children:t(i?"search":"signin",{productName:r})}),(0,Go.jsxs)("div",{className:s.icon,children:[(0,Go.jsx)(mT,{className:s.logo,color:"pink"}),i===!1&&(0,Go.jsx)(pT,{className:s.lock})]})]})};var mf=x(F());function Mn(e){let{showMidSentenceSuggestions:t,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:r}=e.settings,{text:o,selection:i}=e.input;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 PN={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1},cf=({ui:e})=>e.overlayCollapsed,vT=re({name:"ui",initialState:PN,reducers:{setShowTabHint(e,t){e.showTabHint=t.payload},setInputFocus(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:Ol,setInputFocus:df,setOverlayCollapsed:Jr,setOpenOverlayWhenTyping:ST,setOverlayCollapsedUserOverwrite:xT}=vT.actions,wT=vT.reducer;var ff=x(F());var bs=x(F());var bT=x(F());function ET(e,t,n){(0,bT.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var TT={root:"dd-1MBCO",actions:"dd--x4cy",badge:"dd-4Fpkz",formattedText:"dd-EzvTB"};var Yo=x(E()),LN=["search","personal-collection-search","search-autocomplete"];function AN(e,t,n,r={}){var i;let o="";return LN.includes(t)?o=tE(Mh(e,n,{stripAgentPart:!0}),(i=r.searchKeywords)!=null?i:[n]):o=Mh(e,n,r),r.placeholders===!0&&(o=nE(o)),o}var IN=()=>{},ON=({selected:e,suggestion:t})=>{let n=U("inlineSuggestions"),r=_(as),o=U("enableSuggestionFeedback"),i=_(c=>c.input.text),s=Z(),a=A("TextSuggestion",TT),l=(0,bs.useRef)(null);(0,bs.useEffect)(()=>{let c=setTimeout(()=>{s(B1({text:t.text,suggestion:t}))},500);return()=>{clearTimeout(c)}},[t]),ET(l,"click",()=>{s(un({suggestion:t,text:t.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let u=(0,bs.useMemo)(()=>AN(t.text,t.source,r,{stripAgentPart:n,placeholders:!0,searchKeywords:t.searchKeywords}),[n,t.text,t.source,r,t.searchKeywords]);return t.source==="gpt"&&!n?null:(0,Yo.jsxs)("div",{className:a.root,children:[(0,Yo.jsx)(se,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:IN,children:(0,Yo.jsx)(fs,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:u})}),o&&(0,Yo.jsx)("div",{className:a.actions,children:(0,Yo.jsx)(sf,{source:"overlay",context:i,suggestion:t})})]})},CT=ON;var ly=x(E()),NN=({suggestions:e,selectedIndex:t,reverse:n})=>{let r=(0,ff.useMemo)(()=>{let o=e.map((i,s)=>(0,ly.jsx)(CT,{index:s,selected:s===t,suggestion:i},`${i.text}-${i.source}`));return n?o.reverse():o},[e,t,n]);return(0,ly.jsx)(ff.Fragment,{children:r})},pf=NN;var kT={root:"dd-PfvRI",paper:"dd-HYlyY"};var Nl=x(E()),_N=({textSuggestions:e,selectedIndex:t})=>{let n=(0,mf.useRef)(null),r=A("InlineSuggestionsOverlay",kT),o=_(Mn),i=Z(),s=_(ft),a=_(ss),l=_(cf),u=U("showTextSuggestions");return Zr(()=>{setTimeout(()=>{i(Jr({collapse:!0,skipWhenInputFocus:!0}))})}),(0,mf.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,Nl.jsx)("div",{className:r.root,"data-variant":"inline",children:(0,Nl.jsx)("div",{ref:n,className:r.paper,children:(0,Nl.jsx)(bt,{children:(0,Nl.jsx)(pf,{suggestions:e,selectedIndex:t})})})})},MN=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),PT=Po(MN)(_N);var _l=x(E()),DN=({children:e})=>{let n=U("locale").replace("-","");return(0,_l.jsx)(xh.Provider,{value:n,children:e})},FN=({store:e,customStyles:t={},children:n})=>(0,_l.jsx)(th,{store:e,children:(0,_l.jsx)(DN,{children:(0,_l.jsx)(Us.Provider,{value:t,children:n})})}),Xo=FN;var hf=x(ue()),Es=x(F());var RT=x(F());function LT(e,t){let[n,r]=(0,RT.useState)(()=>{if(typeof window=="undefined")return t;try{let i=window.localStorage.getItem(e);return i?JSON.parse(i):t}catch(i){return z.error(i),t}});return[n,i=>{try{let s=i instanceof Function?i(n):i;r(s),typeof window!="undefined"&&window.localStorage.setItem(e,JSON.stringify(s))}catch(s){z.error(s)}}]}var AT=()=>/Mac/i.test(navigator.platform);var OT=x(ue()),dr=x(F());var uy={};lt(uy,{enUS:()=>HN,nlNL:()=>UN});var HN={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"}]}]},UN={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 IT={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};var eo=x(E()),cy=(e,t,n)=>r=>(0,eo.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),zN=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r,onLogIn:o})=>{let i=q(uy),s=Rt(),a=A("Login",IT),l=U("productName"),u=(0,dr.useCallback)(m=>{m.preventDefault(),r&&r(parseInt(m.target.value,10))},[]),c=(0,dr.useCallback)(m=>{m.preventDefault(),s.send(cs,!0)},[t]),f=(0,dr.useMemo)(()=>m=>(0,eo.jsx)("a",{onClick:h=>{h.preventDefault(),o()},href:t,className:a.anchor,target:"_blank",rel:"noreferrer",children:m},"login"),[t]),d=(0,dr.useCallback)(m=>(0,eo.jsx)("button",{type:"button",className:a.anchorButton,onClick:c,children:m},"prompt"),[c]),{min:p,hour:y,day:v}=(0,dr.useMemo)(()=>({min:cy(a,60*10,u),hour:cy(a,60*60,u),day:cy(a,60*60*12,u)}),[]);return(0,eo.jsxs)("div",{className:(0,OT.default)(e,a.root),children:[i("loginPlease",{login:n?d:f,productName:l}),r&&(0,eo.jsxs)(dr.Fragment,{children:[(0,eo.jsx)("br",{}),i("snooze",{min:p,hour:y,day:v})]})]})},gf=zN;var NT={root:"dd-DoQhb",text:"dd-Jwnev"};var Ml=x(E()),jN=({title:e})=>{let t=A("SearchTrigger",NT),n=Z();return(0,Ml.jsxs)("button",{type:"button",className:t.root,onClick:()=>n(Qt(!0)),children:[(0,Ml.jsx)(ms,{}),(0,Ml.jsx)("span",{className:t.text,children:e})]})},_T=jN;var dy={};lt(dy,{enUS:()=>BN,nlNL:()=>VN});var BN={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"}]},VN={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 MT={root:"dd-oa7Vc",isInline:"dd-bwk31",toggleButton:"dd-MSB8Z",toggleButtonWrapper:"dd-ZkCzT",toggleButtonWrapperHidden:"dd-Sq66c",isCollapsed:"dd-vkrPk",collapsible:"dd-CWQJe",hints:"dd-IOoo3",hintsHidden:"dd-psVuT",triggers:"dd-toIoo",triggersRight:"dd-mc4l2"};var we=x(E()),WN=({textSuggestions:e,selectedIndex:t,onLogIn:n})=>{let r=A("SuggestionsOverlay",MT),o=q(dy),i=_(Mn),s=j1(),a=Z(),l=(0,Es.useRef)(null),u=U("searchTriggerKey"),c=U("productName"),f=_(cf),d=_(ft),p=_(ss),[y,v]=(0,Es.useState)(null),m=U("showSearch"),g=U("showTextSuggestions"),h=U("adminUrl"),S=U("isEmbedded"),[w,P]=LT("dd-snooze-until-ms",0),T=f||w>Date.now(),R=e.filter(G=>G.source!=="gpt").length,N=()=>{T&&P(0),a(xT(!T))},M=G=>{let B=Date.now()+G*1e3;P(B),z.info(`Snooze until: ${new Date(B)}`),a(Jr({collapse:!0}))};return(0,Es.useEffect)(()=>{R===0&&v(null)},[e,R]),Zr(()=>{a(Jr({collapse:!0,skipWhenInputFocus:!0}))}),d===null||p===!1?null:d===!1?(0,we.jsxs)("div",{ref:l,className:(0,hf.default)(r.root,{[r.isCollapsed]:T}),children:[!T&&(0,we.jsxs)("div",{className:r.triggers,children:[(0,we.jsx)("div",{style:{flex:1}}),(0,we.jsx)("div",{className:r.triggersRight,children:(0,we.jsx)(uo,{className:r.toggleButton,title:o("collapse"),onClick:N,isCollapsed:!1})})]}),(0,we.jsx)("div",{className:r.toggleButtonWrapper,children:(0,we.jsx)(uo,{className:r.toggleButton,title:o("open",{productName:c}),onClick:N,isCollapsed:!0})}),(0,we.jsx)("div",{className:r.collapsible,children:(0,we.jsx)(gf,{loginUrl:h,isEmbedded:S,onLogIn:n,onSnooze:M})})]}):!s||!i?null:(0,we.jsxs)("div",{ref:l,className:(0,hf.default)(r.root,{[r.isCollapsed]:T}),children:[!T&&(0,we.jsxs)("div",{className:r.triggers,children:[(0,we.jsx)("div",{style:{flex:1},children:m&&(0,we.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>v(o(AT()?"searchHintMac":"searchHintWindows",{searchTriggerKey:u.toUpperCase()})),onMouseLeave:()=>v(null),children:(0,we.jsx)(_T,{title:o("search")})})}),(0,we.jsxs)("div",{className:r.triggersRight,onFocus:()=>{},children:[(0,we.jsx)("div",{className:(0,hf.default)(!y&&r.hintsHidden,r.hints),children:y}),(0,we.jsx)(uo,{className:r.toggleButton,title:o("collapse"),onClick:N,isCollapsed:!1})]})]}),(0,we.jsx)("div",{className:r.toggleButtonWrapper,children:(0,we.jsx)(uo,{className:r.toggleButton,title:o("open",{productName:c}),onClick:N,isCollapsed:!0})}),R>0&&g&&(0,we.jsx)("div",{className:r.collapsible,onFocus:()=>{},children:(0,we.jsx)(bt,{children:(0,we.jsx)(pf,{suggestions:e,selectedIndex:t,reverse:!0})})})]})},KN=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),DT=Po(KN)(WN);var Rf=x(ue());var mr=x(F());var Ts=x(F());function yf(e){return e.contentEditable==="true"}function $N(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 FT(e){let{selectionStart:t,selectionEnd:n}=yf(e)?$N(e):e;return[t,n]}function HT(e){let[,t]=(0,Ts.useState)(),n=(0,Ts.useRef)(null);return n.current=FT(e),(0,Ts.useEffect)(()=>{let r=()=>{var a;let[o,i]=(a=n.current)!=null?a:[],s=FT(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 UT(e,t){if(!t)return;let n=e,{value:r}=n,[o,i]=t,s=r.match(cu);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 zT=x(F()),qN=["div","span","mark","strong","b","i","u","em"];function fy(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(qN.includes(o)){let s=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,zT.cloneElement)(r,{children:fy(s,t,n+1)})]}return[...e,...t]}function Qo(e){return e.tagName.toLowerCase()==="textarea"}var jT={root:"dd-7-cgW",container:"dd-PsRQ8",agentText:"dd-qnW-V",tabText:"dd-cUHUr",hint:"dd-v7fSg",matchSelection:"dd-8cr8y",focus:"dd-3tr9l",resetIndent:"dd-TvQfZ",matchKeyword:"dd-oJkRD",matchPlaceholder:"dd-QvNoo",hover:"dd--wi0R",hintText:"dd-7gQQh",popover:"dd-xbRu-",popoverRoot:"dd-rA2x8",popoverContentContainer:"dd-JHICl",popoverContent:"dd--mfkC",selectionOptions:"dd-p52wn",selectionOptionsIsHidden:"dd-sSTDp",selectionOptionsButton:"dd-Q6kRY",caret:"dd-jIhc8",popoverSuggestionsRoot:"dd-iFDbL",suggestionsOverlayInputStyles:"dd-zzENA"};var $T=x(ue());var Ef=x(F());var Cs=x(F());function BT(e,t){let n;return[(...r)=>{window.cancelAnimationFrame(n);let o=t?t(...r):r;n=window.requestAnimationFrame(()=>{e(...o)})},()=>window.cancelAnimationFrame(n)]}function vf(e){let t=(0,Cs.useRef)(null),[n,r]=(0,Cs.useState)(!1);return(0,Cs.useEffect)(()=>{var c;let o=!1,i=parseFloat((c=window.getComputedStyle(document.body).zoom)!=null?c:"1"),[s,a]=BT((f,d)=>{let p=t.current;if(!p)return;let y=f/i,v=d/i,m=p.getBoundingClientRect(),g=y>m.x&&y<m.x+m.width&&v>m.y&&v<m.y+m.height;g&&!o?(o=!0,r(!0)):!g&&o&&(o=!1,r(!1))},({clientX:f,clientY:d})=>[f,d]),[l,u]=BT(()=>{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 VT(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Sf(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function WT(e){return e!=null}var KT=x(ue()),xf=x(F());var fr={root:"dd-7-cgW",container:"dd-PsRQ8",agentText:"dd-qnW-V",tabText:"dd-cUHUr",hint:"dd-v7fSg",matchSelection:"dd-8cr8y",focus:"dd-3tr9l",resetIndent:"dd-TvQfZ",matchKeyword:"dd-oJkRD",matchPlaceholder:"dd-QvNoo",hover:"dd--wi0R",hintText:"dd-7gQQh",popover:"dd-xbRu-",popoverRoot:"dd-rA2x8",popoverContentContainer:"dd-JHICl",popoverContent:"dd--mfkC",selectionOptions:"dd-p52wn",selectionOptionsIsHidden:"dd-sSTDp",selectionOptionsButton:"dd-Q6kRY",caret:"dd-jIhc8",popoverSuggestionsRoot:"dd-iFDbL",suggestionsOverlayInputStyles:"dd-zzENA"};var py=x(E()),wf=(0,xf.forwardRef)((o,r)=>{var i=o,{className:e,children:t}=i,n=ee(i,["className","children"]);let s=(0,xf.useRef)(null),a=A("TabCompletion",fr);return(0,py.jsx)("div",I(C({ref:Sf([s,r]),className:(0,KT.default)(e,a.popoverContentContainer)},n),{children:(0,py.jsx)("div",{className:a.popoverContent,children:t})}))});var to=x(E()),GN=e=>t=>{let n=ey(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},YN=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let i=A("TabCompletion",fr),s=rf(),a=(0,Ef.useMemo)(()=>GN(e.getBoundingClientRect()),[e]),[l,u]=vf(e);return(0,Ef.useEffect)(()=>{u?s.open():s.close()},[u]),(0,to.jsxs)("span",{children:[(0,to.jsx)("mark",{ref:Sf([l,s.triggerRef]),className:(0,$T.default)(i.matchKeyword,{[i.hover]:u}),"aria-haspopup":"dialog","aria-expanded":s.opened?"true":"false",children:r}),s.opened&&(0,to.jsx)(xs,{className:i.popover,triggerRef:s.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,to.jsx)(wf,{style:n,children:(0,to.jsx)("div",{className:i.hintText,children:o})})})]})},bf=class extends ir{constructor(){super(...arguments);this.keywordMatches=[];this.preparedKeywordMatches=[];this.usedKeywordMatches=new Set}onBeforeParse(n,r){return r.keywordMatches&&r.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=r.keywordMatches.map(o=>I(C({},o),{keywordRegex:new RegExp(`\\b${VT(o.keyword)}\\b`,"i")})),this.keywordMatches=r.keywordMatches),this.usedKeywordMatches.clear(),n}match(n){let r=this.preparedKeywordMatches.map(i=>{if(this.usedKeywordMatches.has(i))return null;let s=n.match(i.keywordRegex);if(!s)return null;let a=n.charAt(s.index-1),l=n.charAt(s.index+i.keyword.length);return a==="{"&&l==="}"?null:{index:s.index,length:s[0].length,match:s[0],matchString:s[0],suggestion:i.suggestion,preparedKeywordMatch:i,valid:!0}}).filter(WT);if(r.length===0)return null;let o=r.reduce((i,s)=>s.index<i.index?s:i);return this.usedKeywordMatches.add(o.preparedKeywordMatch),o}replaceWith(n,r){return(0,to.jsx)(YN,{inputElement:r.inputElement,suggestion:r.suggestion,inputStyle:r.inputStyle,boundaryRef:r.boundaryRef,children:n},`keyword_${r.matchString}_${r.key}`)}asTag(){return"mark"}};var qT=x(ue());var my=x(E()),XN=({inputElement:e,children:t})=>{let n=A("TabCompletion",fr),[r,o]=vf(e);return(0,my.jsx)("mark",{ref:r,className:(0,qT.default)(n.matchPlaceholder,{[n.hover]:o}),children:t})},Tf=class extends ir{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,my.jsx)(XN,{inputElement:n.inputElement,children:t},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var kf=x(ue());var yt=x(F());var gy=x(E()),GT=()=>(0,gy.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,gy.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 Dn=x(F());var XT=x(Ch());var YT={root:"dd-ky-Bv",content:"dd-kV5e1"};function Cf(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(i){return null}}function hy(e){return e.replace("https://www.","").replace("https://","")}var tn=x(E()),QN=3,ZN=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),JN=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=QN})=>{let i=A("LinkSearch",YT),[s,a]=(0,Dn.useState)(""),l=Z(),u=_(rT("url")),c=_(ub("URL")),f=(0,Dn.useMemo)(()=>c.map(ZN),[c]),[d,p]=(0,Dn.useState)(f.length-1),y=U("fallbackImage"),v=S=>{let w=S.target;a(w.value)},m=(S,w)=>{S.stopPropagation(),S.preventDefault(),window.open(w,"_blank")},g=S=>{var T;let w=d-1<0?f.length-1:d-1,P=d+1===f.length?0:d+1;S.code==="Escape"&&(a(""),t()),S.code==="ArrowUp"&&p(w),S.code==="ArrowDown"&&p(P),S.code==="Enter"&&e(((T=f[d])==null?void 0:T.text)||s)},h=(0,Dn.useCallback)((0,XT.default)(S=>{l(Ao({query:S,type:"URL",tags:["link-search"]}))},300),[]);return(0,Dn.useEffect)(()=>{s&&h(s)},[s]),(0,Dn.useEffect)(()=>()=>{l(Sd())},[]),(0,tn.jsxs)("div",{className:i.root,children:[(0,tn.jsx)(bt,{withDivider:!0,children:(s?f:u).slice(0,o).map((S,w)=>(0,tn.jsx)(se,{selected:d===w,onClick:()=>e(S.text),"data-testid":"linksearch-suggestion",children:(0,tn.jsxs)(he,{children:[(0,tn.jsx)(he.Image,{src:Cf(S,"small",y||void 0),title:S.title||S.text}),(0,tn.jsxs)(he.Content,{className:i.content,cropText:!0,children:[(0,tn.jsx)(he.Title,{children:S.title||hy(S.text)}),S.title&&hy(S.text)]}),(0,tn.jsx)(se.Actions,{children:(0,tn.jsx)(se.ActionButton,{label:r,onClick:P=>m(P,S.text)})})]})},S.text))}),(0,tn.jsx)(ol,{value:s,onChange:v,autoFocus:!0,placeholder:n,onKeyUp:g})]})},QT=JN;var yy={};lt(yy,{enUS:()=>e_,nlNL:()=>t_});var e_={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},t_={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var ht=x(E()),n_=(0,yt.forwardRef)((e,t)=>{let n=A("TabCompletion",fr);return(0,ht.jsx)("mark",{ref:t,className:(0,kf.default)(n.matchSelection)},"selection-start")}),r_=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let i=q(yy),s=A("TabCompletion",fr),a=(0,yt.useRef)(null),l=(0,yt.useRef)(null),[u,c]=(0,yt.useState)(null),f=Z(),d=rf(document.activeElement===r),[p]=(0,yt.useState)(()=>document.createRange());d.triggerRef.current=p,(0,yt.useEffect)(()=>()=>p.detach(),[]),(0,yt.useEffect)(()=>{let v=e.current,m=a.current;!v||!m||(p.setStart(v,0),p.setEnd(m,0))},[e.current,a.current]),Zr(()=>{d.close()});let y=(0,yt.useCallback)(v=>{let m=p.toString(),g=/^http(s?):\/\//.test(v)?v:`https://${v}`;f(pd({text:`[${m}](${g})`,replace:"selection"}))},[]);return(0,ht.jsxs)("span",{children:[(0,ht.jsx)("mark",{ref:a,className:(0,kf.default)(s.matchSelection),"aria-haspopup":"dialog","aria-expanded":d.opened?"true":"false",children:o}),d.opened&&(0,ht.jsx)(xs,{className:s.popoverRoot,triggerRef:d.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,ht.jsxs)(wf,{style:n,ref:l,children:[(0,ht.jsx)("div",{className:(0,kf.default)(s.selectionOptions,{[s.selectionOptionsIsHidden]:u!==null}),children:(0,ht.jsxs)("button",{type:"button",tabIndex:u===null?-1:void 0,className:s.selectionOptionsButton,onClick:()=>c("insertLink"),children:[(0,ht.jsx)(GT,{}),(0,ht.jsx)("span",{children:"\xA0"}),(0,ht.jsx)("span",{children:i("insertLink")})]})}),u==="insertLink"&&(0,ht.jsx)(QT,{placeholder:i("linkInputPlaceholder"),visitUrlText:i("visitUrl"),onSelectLink:y,onDismiss:()=>{c(null),d.close()}})]})})]},"selection-end")},Pf=class extends ir{constructor(){super(...arguments);this.charCount=0;this.foundIndex=0;this.startRef=null}onBeforeParse(n,r){return this.props=r,this.charCount=0,this.startRef=(0,yt.createRef)(),this.foundIndex=0,n}match(n){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[r,o]=this.props.selection;if(r===o)return null;let i=this.foundIndex===0?r:o,s=i>=this.charCount&&i<=this.charCount+n.length?{index:i-this.charCount,length:0,match:"",valid:!0}:null;s&&this.foundIndex++;let a=this.foundIndex===1;return s&&a?this.charCount+=i-this.charCount:this.charCount+=n.length,s?C({isStart:a},s):null}replaceWith(n,r){return r.isStart?(0,ht.jsx)(n_,{ref:this.startRef}):(0,ht.jsx)(r_,{inputElement:r.inputElement,startRef:this.startRef,boundaryRef:r.boundaryRef,inputStyle:r.inputStyle})}asTag(){return"mark"}};var pr=x(E()),o_=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:i,keywordMatches:s,inputElement:a,source:l})=>{let u=A("TabCompletion",jT),c=U("insertLink"),f=U("showMidSentenceSuggestions"),d=U("inlineSuggestions"),p=HT(a),y=(0,mr.useRef)(null),v=_(ft);(0,mr.useEffect)(()=>{Qo(a)&&p&&UT(a,p)},[p]);let m=(0,mr.useCallback)(S=>{if(!o||!n)return S;let w=[(0,pr.jsx)("span",{className:u.resetIndent,children:"\u200B"},"u200B"),(0,pr.jsx)("span",{"data-testid":"tab-completion",className:(0,Rf.default)(u.tabText,u.resetIndent),"data-source":l,children:n},"tabText")];return r&&w.push((0,pr.jsx)("span",{className:(0,Rf.default)(u.hint,u.resetIndent),children:(0,pr.jsx)(au,{keyCode:"tab"},"tabHint")})),fy(S,w)},[o,n,r]),g=(0,mr.useMemo)(()=>{let S=[];return c&&S.push(new Pf("selection")),S.push(new Tf("placeholders")),i&&S.push(new bf("keywords")),S},[d,c,i]),h=(0,mr.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,pr.jsxs)("div",{ref:S=>{S!=null&&S.parentElement&&(y.current=S==null?void 0:S.parentElement)},className:u.root,style:h,children:[(0,pr.jsx)(fs,{tagName:"span",containerTagName:"div",className:(0,Rf.default)(u.container,u.agentText),disableLineBreaks:Qo(a),content:t||"\u200B",onAfterParse:m,matchers:g,selection:p,keywordMatches:s,inputElement:a,inputStyle:h,boundaryRef:y,inlineSuggestionsOnlyAtEnd:!f}),(0,pr.jsx)("br",{})]})},i_=e=>{var m,g,h;let{input:t,ui:n,settings:r,styleSuggestions:o,conversation:i}=e,s=ls({input:t}),a=(s==null?void 0:s.text)||"",l=(s==null?void 0:s.source)||"",u=(m=t.html)!=null?m:ps(t.text),c=a.indexOf(t.text)===0?a.slice(t.text.length):"",{showTabHint:f}=n,{isSupported:d}=i,{showTabCompletion:p,visible:y,showStyleSuggestions:v}=r;return{showTabHint:f,showStyleSuggestions:v,showTabCompletion:p&&Mn(e),content:u,tabText:c,source:l,keywordMatches:(h=(g=o.list)==null?void 0:g.keywordMatches)!=null?h:[],enabled:y&&d!==!1}},ZT=Po(i_)(o_);var TC=x(ue()),Rs=x(F());var s_={token:null,interval:null},vy=J("passwordlessToken/getTemporaryPasswordlessToken",(e,t)=>k(void 0,null,function*(){let{deepdeskAPI:n}=t.extra;return{token:yield n.requestPasswordlessToken()}})),Sy=J("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(vy()),setInterval(()=>r(vy()),n)}),JT=re({name:"passwordlessToken",initialState:s_,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(vy.fulfilled,(t,n)=>{t.token=n.payload.token}),e.addCase(Sy.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:eC}=JT.actions,tC=JT.reducer;function a_(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t}var nC=ln([Hb],e=>e.map(n=>({text:n.response,title:n.name,callToAction:n.callToAction,isLoading:n.isLoading,specialType:n.specialType,rule:{id:a_(n.code),label:n.code,name:n.name,description:n.name}})));var Lf=x(F());var wy=x(ue());var xy=x(E()),Dl=()=>(0,xy.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,xy.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 rC={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};var Fn=x(E()),l_=({entities:e})=>{let t=A("EntitiesWidgetList",rC),[n,r]=(0,Lf.useState)(void 0),o=Z(),i=()=>{r(void 0)},s=a=>{e&&(r(e.indexOf(a)),Nn(a.text),o(Xt({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,Lf.useEffect)(()=>{let a=setTimeout(i,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,Fn.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,Fn.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>s(a),children:[(0,Fn.jsx)("span",{className:t.entityText,children:a.text}),(0,Fn.jsxs)("span",{className:t.iconWrapper,children:[(0,Fn.jsx)("span",{className:(0,wy.default)(t.icon),children:(0,Fn.jsx)(Dl,{})}),(0,Fn.jsx)("span",{className:(0,wy.default)(t.icon,n===l&&t.iconClicked),children:(0,Fn.jsx)(Dl,{})})]})]},a.text))})},oC=l_;var by=x(E()),iC=()=>(0,by.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,by.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 Ey=x(E()),sC=()=>(0,Ey.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Ey.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 Ty=x(E()),aC=()=>(0,Ty.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Ty.jsx)("path",{d:"M319-250h322v-60H319v60Zm0-170h322v-60H319v60ZM220-80q-24 0-42-18t-18-42v-680q0-24 18-42t42-18h361l219 219v521q0 24-18 42t-42 18H220Zm331-554v-186H220v680h520v-494H551ZM220-820v186-186 680-680Z"})});var cC=x(F());var lC={loadingBar:"dd-6as-V",placeHolderShimmer:"dd-TFYmA"};var uC=x(E()),u_=({width:e})=>{let t=A("LoadingProgressBar",lC);return(0,uC.jsx)("div",{className:t.loadingBar,style:{width:e}})},Af=u_;var gr=x(E()),If=({title:e})=>{let t=(0,cC.useRef)(null);return Gv(t),(0,gr.jsx)(se,{ref:t,children:(0,gr.jsx)(he,{children:(0,gr.jsxs)(he.Content,{children:[(0,gr.jsx)(he.Title,{children:e}),(0,gr.jsx)(Af,{width:"60%"}),(0,gr.jsx)(Af,{width:"90%"}),(0,gr.jsx)(Af,{width:"50%"})]})})})};var Fl={};lt(Fl,{enUS:()=>c_,nlNL:()=>d_});var c_={useCue:[{type:0,value:"Add to message"}],__summarizerAssistant__:[{type:0,value:"Summary"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},d_={useCue:[{type:0,value:"Voeg toe aan bericht"}],__summarizerAssistant__:[{type:0,value:"Samenvatting"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var Zo=x(F());var Cy={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",actions:"dd-9Iqn9",thumbsUp:"dd-6QwVx",thumbsDown:"dd-d3E8l",form:"dd-sPNU2",formInput:"dd-F3E4I",formSubmit:"dd-vw5S0",actionButton:"dd-cCWyJ",editableCue:"dd-nWSD-",inputSpace:"dd-DGYB1"};var it=x(E()),f_=500,p_=100,m_=({content:e,onChange:t})=>{let n=(0,Zo.useRef)(null),r=A("WidgetCue",Cy);return(0,Zo.useEffect)(()=>{let o=n.current;if(!o)return;o.style.setProperty("height","0px");let i=Math.min(Math.max(o.scrollHeight,p_),f_);o.style.setProperty("height",`${i}px`)},[e]),(0,it.jsx)("textarea",{ref:n,className:r.editableCue,onChange:t,value:e})},g_=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o})=>{var v;let i=A("WidgetCue",Cy),s=q(Fl),a=Qr(),l=U("hasKeyboardInput"),[u,c]=(0,Zo.useState)(e.text),f=()=>{t&&t(e),n(e)},d=m=>{r&&r(m,e)},p=m=>{o&&o(m,e)},y=m=>{m.preventDefault(),m.stopPropagation(),n(e)};return(0,Zo.useEffect)(()=>{a("Assistant response displayed",{name:e.rule.name,description:e.rule.description,group:e.rule.label,cueText:e.text})},[]),(0,it.jsxs)(se,{"data-testid":"cue",children:[(0,it.jsx)(he,{children:(0,it.jsxs)(he.Content,{children:[e.title&&(0,it.jsx)(he.Title,{className:i.title,"data-testid":"widget-cue-title",children:e.rule.label.startsWith("__")?s(e.rule.label):e.title}),e.specialType==="summary"?(0,it.jsx)(m_,{content:u,onChange:m=>{var g;return c((g=m.target.value)!=null?g:"")}}):(0,it.jsx)(ws,{content:e.text,useLabel:s("useCue"),copyLabel:s("copyCue"),onCopy:d,onUse:l?p:void 0})]})}),(0,it.jsxs)(se.ButtonsContainer,{children:[(0,it.jsxs)("div",{className:i.actions,children:[e.specialType==="summary"&&(0,it.jsx)(se.Button,{onClick:()=>d(u),children:s("copyCue")}),e.callToAction&&(0,it.jsx)(se.Button,{onClick:f,children:e.callToAction.label}),(0,it.jsx)(se.Button,{onClick:y,children:s("removeCue")})]}),e.specialType==="summary"?(0,it.jsx)(jo,{eventName:"summary feedback",feedbackText:(v=e.text)!=null?v:"",feedbackType:"summary",eventData:{summary:e.text}}):(0,it.jsx)(jo,{eventName:"Assistant response feedback",eventData:{name:e.rule.name,group:e.rule.label,description:e.rule.description,cueText:e.text},feedbackText:e.text,feedbackType:"assistant"})]})]})},dC=g_;var ks=x(E()),h_=({cues:e})=>{let t=Z(),n=Rt(),r=q(Fl),o=Qr(),i=u=>{t(zb({code:u.rule.label})),o("Assistant response closed",{name:u.rule.name,group:u.rule.label,description:u.rule.description,cueText:u.text})},s=(u,c)=>{switch(Nn(u),c.specialType){case"summary":o("summary copied to clipboard",{originalText:c.text,finalText:u,assistant:c.rule.label});break;default:o("Assistant response copied",{name:c.rule.name,group:c.rule.label,description:c.rule.description,copiedText:u})}},a=u=>{u.callToAction&&(t(Fd(u)),o("Assistant call to action",{name:u.rule.name,group:u.rule.label,description:u.rule.description,eventName:u.callToAction.event,value:u.callToAction.value}))},l=(u,c)=>{n.send(In,{text:u,suggestion:{source:"cue",sourceText:u}}),o("Assistant response used",{name:c.rule.name,group:c.rule.label,description:c.rule.description,usedText:u})};return(0,ks.jsx)(ks.Fragment,{children:e.map(u=>u.isLoading?(0,ks.jsx)(If,{title:u.rule.label.startsWith("__")?r(u.rule.label):u.title},u.rule.id):(0,ks.jsx)(dC,{cue:u,onCallToAction:a,onRemove:i,onCopy:s,onUse:l},u.rule.id))})},fC=h_;var Of=x(F());var pC={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var vn=x(E());function y_(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var mC=({data:e,schema:t})=>{let n=A("WidgetCustomData",pC),r=o=>{Nn(o)};return(0,Of.useEffect)(()=>{z.info("Custom data",e,t)},[e]),(0,vn.jsx)("dl",{className:n.root,children:t.map(o=>{let i=y_(e,o.path);return(0,vn.jsxs)(Of.Fragment,{children:[(0,vn.jsx)("dt",{className:n.label,children:o.label}),(0,vn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&i?(0,vn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!i?(0,vn.jsx)("span",{className:n.isFalse,children:o.falseValue}):i?(0,vn.jsxs)("button",{type:"button",onClick:()=>r(i),className:n.copyButton,children:[(0,vn.jsx)("span",{className:n.copyButtonText,children:i}),(0,vn.jsx)(Dl,{})]}):"-"})]},o.label)})})};var At=x(F());var ky=x(E()),gC=()=>(0,ky.jsx)("svg",{focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"ReplayIcon",children:(0,ky.jsx)("path",{d:"M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8"})});var Ps={};lt(Ps,{enUS:()=>v_,nlNL:()=>S_});var v_={titleKnowledgeAssistant:[{type:0,value:"Knowledge Assistant"}],inputPlaceholder:[{type:0,value:"What is your question?"}],useCue:[{type:0,value:"Add to message"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Submit"}],resetLabel:[{type:0,value:"Reset"}],showMore:[{type:0,value:"Show "},{type:1,value:"amount"},{type:0,value:" more"}]},S_={titleKnowledgeAssistant:[{type:0,value:"Knowledge Assistant"}],inputPlaceholder:[{type:0,value:"Wat is je vraag?"}],useCue:[{type:0,value:"Voeg toe aan bericht"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Verzend"}],resetLabel:[{type:0,value:"Reset"}],showMore:[{type:0,value:"Toon "},{type:1,value:"amount"},{type:0,value:" meer"}]};var Py={form:"dd-pleCH",formInput:"dd-pGJMY",formSubmit:"dd--gkRg",actionButton:"dd-I2NEH",sources:"dd-xf9c6",source:"dd-a-vyX",link:"dd-PyUPS",linkContent:"dd-gARDA",showMoreSources:"dd-uDGi-"};var ge=x(E()),x_=3,w_=({sources:e,onClick:t})=>{let n=q(Ps),r=A("WidgetKnowledgeAssistant",Py),[o,i]=(0,At.useState)(!1),s=o?e:e.slice(0,x_);return s.length===0?null:(0,ge.jsxs)("ul",{className:r.sources,children:[s.map(a=>(0,ge.jsx)("li",{className:r.source,"data-testid":"knowledge-assist-source",children:(0,ge.jsx)("a",{className:r.link,rel:"noreferrer",target:"_blank",href:a.url,onClick:l=>{l.stopPropagation(),t(a)},"data-tooltip":a.url?decodeURIComponent(a.url):void 0,children:(0,ge.jsx)("span",{className:r.linkContent,children:a.name})})},a.name)),s<e&&(0,ge.jsx)("button",{type:"button",className:r.showMoreSources,onClick:()=>i(!0),children:n("showMore",{amount:e.length-s.length})})]})},b_=({innerRef:e,item:t,index:n,hasKeyboardInput:r,onCopy:o,onUse:i,onSourceClick:s})=>{var l;let a=q(Ps);return(0,ge.jsxs)(se,{"data-testid":"knowledge-assist-answer",ref:e,children:[(0,ge.jsx)(he,{children:(0,ge.jsxs)(he.Content,{children:[(0,ge.jsx)(he.Title,{children:t.question}),(0,ge.jsx)(ws,{content:t.answer.answer,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:o,onUse:r?i:void 0}),(0,ge.jsx)(w_,{sources:(l=t.answer.sources)!=null?l:[],onClick:u=>s(u,t.question)})]})}),(0,ge.jsxs)(se.ButtonsContainer,{children:[(0,ge.jsx)("div",{}),(0,ge.jsx)(jo,{eventName:"knowledge assist feedback",eventData:{question:t.question,isFollowUpQuestion:n>0,isAgent:!0,answer:t.answer.answer},feedbackText:t.answer.answer,feedbackType:"assistant"})]})]})},Ry=(0,At.createContext)(null),hC=({children:e})=>{let[t,n]=(0,At.useState)(null),r=_(fl("knowledge-assist")),[o,i]=(0,At.useState)(!1),[s,a]=(0,At.useState)(null),l=Z(),u=zo(d=>ll({input:d,threadId:t,onNewThreadId(p){n(p)}})),c={isEnabled:r,isSubmitting:o,threadId:t,pendingInput:s,onSubmit(d){return k(this,null,function*(){i(!0),a(d),yield u.call(d),i(!1),a(null)})},onReset(){t&&l(ds(t))}};return(0,ge.jsx)(Ry.Provider,{value:c,children:e})},yC=()=>{let e=q(Ps),t=A("WidgetKnowledgeAssistant",Py),n=(0,At.useContext)(Ry),r=(0,At.useRef)(null),[o,i]=(0,At.useState)(""),s=u=>{i(u.target.value)},a=u=>{u.preventDefault(),n.onSubmit(o).then(()=>{var c;r.current&&((c=r.current)==null||c.focus(),i(""))})},l=u=>{u.preventDefault(),n.onReset()};return n.isEnabled?(0,ge.jsxs)("form",{className:t.form,onSubmit:a,children:[(0,ge.jsx)("input",{ref:r,className:t.formInput,placeholder:e("inputPlaceholder"),type:"text",disabled:n.isSubmitting,value:o,onChange:s}),(0,ge.jsx)("button",{type:"submit",disabled:n.isSubmitting||o==="",className:t.formSubmit,children:e("submitLabel")}),(0,ge.jsx)("button",{type:"button",title:e("resetLabel"),disabled:n.threadId===null||n.isSubmitting,onClick:l,className:t.actionButton,children:(0,ge.jsx)(gC,{})})]}):null},vC=()=>{var c,f;let e=q(Ps),t=Qr(),n=(0,At.useRef)(null),r=(0,At.useContext)(Ry),o=(f=_(al((c=r.threadId)!=null?c:-1)))!=null?f:[],i=U("hasKeyboardInput"),s=Rt(),a=d=>{Nn(d),t("Assistant response copied",{name:"Knowledge Assistant",group:"knowlegde-assist",description:"",copiedText:d})},l=(d,p)=>{t("knowledge assist source viewed",{question:p,sourceViewed:d.url||d.name})},u=d=>{s.send(In,{text:d,suggestion:{source:"cue",sourceText:d}}),t("Assistant response used",{name:"Knowledge Assistant",group:"knowlegde-assist",description:"",usedText:d})};return!r.isEnabled||(o==null?void 0:o.length)===0&&!r.isSubmitting?null:(0,ge.jsx)(wn,{type:"knowledge",title:e("titleKnowledgeAssistant"),"data-testid":"knowledge",children:(0,ge.jsxs)(bt,{withDivider:!0,children:[o.map((d,p)=>(0,ge.jsx)(b_,{innerRef:p===o.length-1?n:void 0,item:d,index:p,hasKeyboardInput:i,onCopy:a,onUse:u,onSourceClick:l},`${d.question}_${d.answer}_${p}`)),r.pendingInput&&(0,ge.jsx)(If,{title:r.pendingInput})]})})};var xC=x(F());var T_=/(https?:\/\/[^\s]+)/,SC=e=>e.split(" ").find(t=>T_.test(t));var nn=x(E()),C_=({suggestion:e,lines:t,onUse:n})=>{var f;let r=e.text||e.url||e.message,o=SC(r),i=q(Rl),s=U("showImages"),a=U("fallbackImage"),l=U("hasKeyboardInput"),u=d=>{d.preventDefault(),d.stopPropagation(),l&&n(r)},c=(0,xC.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,nn.jsxs)(se,{onClick:l?u:void 0,"data-testid":"edit-suggestion",children:[(0,nn.jsxs)(he,{children:[s&&e.image&&(0,nn.jsx)(he.Image,{src:Cf(e,"small",a||void 0),title:e.title}),(0,nn.jsxs)(he.Content,{children:[e.title&&(0,nn.jsx)(he.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((f=e.searchKeywords)==null?void 0:f.length)>0&&(0,nn.jsx)(se.Labels,{labels:e.searchKeywords}),(0,nn.jsx)(he.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,nn.jsxs)(se.Actions,{children:[o&&(0,nn.jsx)(se.ActionButton,{onClick:c,label:i("visitUrl")}),l&&(0,nn.jsx)(se.ActionButton,{primary:!0,onClick:u,label:i("useSuggestion")})]})]})},wC=C_;var Hl=x(E()),k_=({lines:e,suggestions:t})=>{let n=Rt(),r=(o,i)=>{n.send(In,{text:o,suggestion:I(C({},i),{source:i.source,sourceText:i.text})})};return(0,Hl.jsx)(Hl.Fragment,{children:t.map(o=>(0,Hl.jsx)(wC,{suggestion:o,lines:e,onUse:i=>r(i,o)},o.text||o.url||o.message))})},bC=k_;var Ul={};lt(Ul,{enUS:()=>P_,nlNL:()=>R_});var P_={waiting:[{type:0,value:"Loading\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],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"}]},R_={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],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 Jo={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",sectionList:"dd-bF9pF",footer:"dd-tvofr",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",footerShortcut:"dd-dH7XJ",link:"dd-DRo0x"};var K=x(E()),CC=(e,t)=>{let n=_(ft);(0,Rs.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},L_=({onLogIn:e})=>{let t=A("Widget",Jo),n=U("isEmbedded"),r=U("adminUrl");return(0,K.jsx)("div",{className:t.loginText,children:(0,K.jsx)("div",{children:(0,K.jsx)(gf,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},EC=({text:e})=>{let t=A("Widget",Jo);return(0,K.jsx)("div",{className:t.stateText,children:(0,K.jsx)("div",{children:(0,K.jsx)("p",{children:e})})},"notification")},A_=()=>{let e=q(Ul),t=A("Widget",Jo),n=zo(()=>On({})),r=U("showSummaryCommand"),o=_(fl("knowledge-assist"));return(0,K.jsx)(K.Fragment,{children:r&&o&&(0,K.jsx)("button",{type:"button",disabled:n.state==="loading",className:t.footerShortcut,onClick:()=>n.call(),children:e("linkSummary")})})},I_=()=>{let e=q(Ul),t=Z(),n=A("Widget",Jo),r=U("showSearch"),o=U("showSummaryCommand"),i=U("showKnowledgeSearch"),s=_(fl("knowledge-assist")),a=U("isEmbedded"),l=_(vs("/admin/")),u=Rt(),c=U("productName"),f=U("hasKeyboardInput"),d=zo(()=>On({})),p=r||o||i||l;return CC(()=>{if(a)return t(Sy()),()=>{t(eC())}},[t,a]),!p||!f?null:(0,K.jsx)(wn,{title:e("actions"),type:"shortcuts",children:(0,K.jsxs)("div",{className:n.shortcutList,children:[r&&(0,K.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-search","aria-label":e("linkSearch"),onClick:()=>u.send("ShowCommandPalette",{isOpen:!0}),children:[(0,K.jsx)(ms,{}),e("linkSearch")]}),o&&!s&&(0,K.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-summary","aria-label":e("linkSummary"),disabled:d.state==="loading",onClick:()=>d.call(),children:[(0,K.jsx)(aC,{}),e("linkSummary")]}),i&&!s&&(0,K.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-knowledge-assist","aria-label":e("linkKnowledgeSearch"),onClick:()=>u.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,K.jsx)(sC,{}),e("linkKnowledgeSearch")]}),l&&(0,K.jsxs)("a",{className:n.shortcut,target:"_blank",href:l,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:c}),rel:"noreferrer",children:[(0,K.jsx)(iC,{}),e("linkStudioLogin",{productName:c})]})]})})},O_=()=>{let e=Z(),t=_(dl),n=_(Wb),r=_(nC),o=_(eb),i=_(Yd),s=_(af),a=_(No),l=_(An);return(0,Rs.useEffect)(()=>{!!o&&!n&&z.warn("Custom data provided, but no schema.")},[o,n]),CC(()=>{t.forEach(({type:u})=>{u==="entities"?e(mn()):du.includes(u)||e(yn(u))})},[e,l,a]),(0,Rs.useEffect)(()=>{r.length>0&&!t.some(u=>u.type==="cues")&&z.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,K.jsx)(Rs.Fragment,{children:t.map(({type:u,title:c,amount:f,lines:d,schema:p})=>{var y,v;switch(u){case"entities":return i&&i.length>0&&(0,K.jsx)(wn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,K.jsx)(oC,{entities:i})},u);case"cues":return r&&r.length>0&&(0,K.jsx)(wn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,K.jsx)(bt,{withDivider:!0,children:(0,K.jsx)(fC,{cues:r})})},u);case"custom-data":return o&&p&&(0,K.jsx)(wn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,K.jsx)(bt,{withDivider:!0,children:(0,K.jsx)(mC,{data:o,schema:p})})},u);default:return((v=(y=s[u])==null?void 0:y.suggestions)==null?void 0:v.length)>0&&(0,K.jsx)(wn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,K.jsx)(bt,{withDivider:!0,children:(0,K.jsx)(bC,{lines:d,contentType:u,suggestions:s[u].suggestions.slice(0,f)||[]})})},u)}})})},N_=({children:e})=>{let t=A("Widget",Jo);return(0,K.jsx)("div",{className:t.footer,children:e})},__=({onLogIn:e})=>{let t=q(Ul),n=A("Widget",Jo),r=_(ss),o=_(ft),i=_(H1),s=_(No);return r===!1?(0,K.jsx)(EC,{text:t("notSupported")}):o===!1?(0,K.jsx)(L_,{onLogIn:e}):!s||!i||o===null?(0,K.jsx)(EC,{text:t("waiting")}):(0,K.jsx)("div",{className:(0,TC.default)(n.root),"data-testid":"widget",children:(0,K.jsxs)(hC,{children:[(0,K.jsxs)(lu,{className:n.sectionList,children:[(0,K.jsx)(I_,{}),(0,K.jsx)(O_,{}),(0,K.jsx)(vC,{})]}),(0,K.jsxs)(N_,{children:[(0,K.jsx)(yC,{}),(0,K.jsx)(A_,{})]})]})})},kC=__;function Ls(e){let t=new Range;return t.selectNodeContents(e),t}function PC(e,t,n){try{return no(e,t,n),!0}catch(r){return!1}}function Nf(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function _f(e){return"tagName"in e&&e.tagName==="BR"}var zl=/[\u200B-\u200D\uFEFF]/g;function no(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(zl,""),f=o+c.length,d=t>=o&&t<=f,p=n>=o&&n<=f;if(d){let y=s(u,t-o);y===0&&!p?r.setStartBefore(l):r.setStart(l,y)}p&&(r.setEnd(l,s(u,n-o)),i=!0),o=f;break}case Node.ELEMENT_NODE:{if(_f(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;Nf(l)&&u&&!Nf(u)&&!_f(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function jl(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===e,p=f===n,y=f===o;switch(f.nodeType){case Node.TEXT_NODE:{let v=f.textContent;p&&(a=u+v.substring(0,r).replace(zl,"").length),y&&(l=u+v.substring(0,i).replace(zl,"").length),u+=v.replace(zl,"").length;break}case Node.ELEMENT_NODE:{if(_f(f)&&f.nextSibling){u++;break}!d&&Nf(f)&&f.previousSibling&&u++;for(let v=0;v<f.childNodes.length;v++){let m=p&&v===r,g=y&&v===i;if(m&&(a=u),g&&(l=u),l!==void 0||((!m||!s)&&c(f.childNodes[v]),y&&v===i-1&&(l=u),l!==void 0))break}y&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:l,end:l}}function Bl(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=0,l="";function u(c){let f=c===e,d=c===n,p=c===o;switch(d&&(a=1),c.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let y=d?r:0,v=p?i:void 0;l+=c.textContent.replace(zl,"").substring(y,v);break}case Node.ELEMENT_NODE:{if(!s&&a===1&&_f(c)&&c.nextSibling){l+=`
|
|
26
26
|
`;break}!f&&!s&&a===1&&Nf(c)&&c.previousSibling&&(l+=`
|
|
27
|
-
`);let y=d?r:0,v=p?Math.min(i,c.childNodes.length):c.childNodes.length;for(let m=y;m<v&&(u(c.childNodes[m]),a!==2);m++);break}default:break}p&&(a=2)}return u(e),l}var RC=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(RC||{}),hr=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}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)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let i=this.getCaretPosition();$r(i,this.cachedCaretPosition)||(this.cachedCaretPosition=i,this.emit("caretposition",i))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(RC).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",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.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),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.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!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()})}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))}off(t,n){if(!this.eventListeners[t])return;let r=this.eventListeners[t].indexOf(n);r!==-1&&this.eventListeners[t].splice(r,1)}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function LC(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var ei=class extends hr{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Bl(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var s;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(s=r.getComposedRanges(n))==null?void 0:s[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!LC(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!LC(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return jl(this.element,n);let r=this.lastKnownSelection;if(r&&PC(this.element,r.start,r.end))return r;let o=Ls(this.element);return o.collapse(!1),jl(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Bl(this.element,no(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(i=>{var s,a;i.length===2&&i[0].addedNodes.length===1&&((s=i[0].addedNodes[0])==null?void 0:s.textContent)==="\u2060"&&((a=i[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var M_=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function AC(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,i=window.getComputedStyle(e),s=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",M_.forEach(function(c){o[c]=i[c]}),n?e.scrollHeight>parseInt(i.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),s.appendChild(r);let l=e.getBoundingClientRect(),u={top:l.top-e.scrollTop+a.offsetTop+parseInt(i.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+parseInt(i.borderLeftWidth)};return s.removeChild(r),u}var ti=class extends hr{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return AC(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var i;return(i=n==null?void 0:n.get)==null?void 0:i.call(this.element)},set:i=>{var s;(s=n==null?void 0:n.set)==null||s.call(this.element,i),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function IC(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 D_(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var Ly=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}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()}},Ay=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=IC(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}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()}},Iy=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),z.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 Ay(t,this.deepdeskUrl,{debug:!0}):new Ly(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=D_(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(z.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;z.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(I(C({},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)}},OC=Iy;function F_(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function be(e){return Array.isArray(e)?e.map(be):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(C({},t),{[F_(n)]:be(e[n])}),{}):e}function H_(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function $e(e){return Array.isArray(e)?e.map($e):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(C({},t),{[H_(n)]:$e(e[n])}),{}):e}var As=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var Oy=e=>new Promise(t=>{setTimeout(t,e)});var Is=class extends As{constructor(){super(...arguments);this.name="ClientError"}},_y=class extends As{constructor(){super(...arguments);this.name="ServerError"}},Ny=new Map;function U_(e){return k(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(z.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var ro=class ro{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}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",T=n,{useCache:u=!1,abortLatest:c=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:y=R=>R instanceof TypeError,retryOnResponse:v=R=>R.status>=500,version:m=null}=T,g=ee(T,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(Ny.has(s)){r(Ny.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h=I(C({credentials:"include"},g),{headers:C({Accept:"application/json","Content-Type":"application/json"},g.headers)});!l&&this.csrfToken&&(h.headers=I(C({},h.headers),{"X-CSRFToken":this.csrfToken})),typeof m=="string"&&(h.headers=I(C({},h.headers),{"X-Deepdesk-API-Version":m}));let S=f,w=!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 P=()=>k(this,null,function*(){return S--,a(s,h).then(R=>k(this,null,function*(){return v(R)&&!i.isAborted&&S>0?(yield Oy(d),P()):R.status===401&&p===!0&&w===!1?(w=!0,yield this.refreshToken(),P()):R})).catch(R=>k(this,null,function*(){if(y(R)&&!i.isAborted&&S>0)return yield Oy(d),P();throw R}))});P().then(R=>k(this,null,function*(){let N=yield U_(R);if(delete this.latestRequestByUrl[s],R.status>=500){o(new _y("Server Error",N));return}else if(R.status===401){o(new Is("Unauthorized",N));return}else if(R.status===403){o(new Is("Forbidden",N));return}else if(R.status===404){o(new Is("Not Found",N));return}else if(R.status>=400){o(new Is("Bad Request",N));return}u&&Ny.set(s,N),r(N)})).catch(R=>{o(R)})})}validateToken(){return k(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)try{yield this.refreshToken()}catch(r){return!1}let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/");return!!n})}refreshToken(){return ro.refreshingToken||(ro.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{ro.refreshingToken=null},1e3*60)})),ro.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,C({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,C({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,C({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,C({method:"DELETE"},n))}};ro.refreshingToken=null;var ni=ro;var NC;(t=>{let e;(s=>(s.SEND_MESSAGE="Send Message",s.HANDLING_TIME="Handling Time",s.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",s.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||(t.EventType={}))})(NC||(NC={}));function Mf(e){return I(C({},be(e)),{tags:e.tags})}var ri=class ri{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new ni(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>k(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return k(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(ri.exchangeTokenPromise||(ri.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),ri.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return k(this,null,function*(){yield this.preflight(),z.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",I(C({},$e(t)),{tags:t.tags}),{version:"v2"});return Mf(n)})}getMe(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return be(t)})}postIdentity(t){return k(this,null,function*(){yield this.client.post("/apis/admin/session/me/identities/",$e(t))})}patchMe(t){return k(this,null,function*(){let n=yield this.client.patch("/apis/admin/session/me/",$e(t));return be(n)})}getProfile(t){return k(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return be(n)})}getKnowledgeAssistant(t){return k(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return be(n)})}getContentTypes(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return be(t)})}getAccount(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return be(t)})}getPlatformConfig(t){return k(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return be(r)})}checkUserExists(t){return k(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationBySessionId(r){return k(this,arguments,function*(t,n={}){yield this.preflight(),z.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return z.info(`Successfully retrieved conversation ${s.id} for session ${t}`),Mf(s)})}isConversationSupported(r){return k(this,arguments,function*(t,n={}){z.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return k(this,null,function*(){let r=$e(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Mf(o)})}postMessages(t,n){return k(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>I(C({},$e(o)),{tags:o.tags})),{version:"v2"})).map(o=>Mf(o))})}sendEvent(t,n){return k(this,null,function*(){let s=n,{data:r}=s,o=ee(s,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>I(C({},a),{[l]:u}),{});return this.client.post("/api/events",$e(I(C(C({},i),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return k(this,null,function*(){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>I(C({},o),{[i]:s}),{});return this.client.post("/api/events",{event:t,data:$e(C(C({},n),r))},{version:"v1"})})}getEntities(t){return k(this,null,function*(){return(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)},{version:"v1"})).entities})}getTemporaryExchangeToken(){return k(this,null,function*(){return(yield this.client.get("/auth/exchange-token")).jwt})}exchangeTokenForAccessCookie(t){return k(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw z.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return k(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",$e(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return k(this,arguments,function*(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(yield this.client.post(`/api/conversations/${t}/recommend/${r}`,$e(n),{abortLatest:!0,version:"v1"})).map(s=>I(C({},be(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,l)=>a===l.findIndex(u=>u.text===s.text))})}isLoggedIn(){return k(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return k(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/autocomplete`,$e(n),{abortLatest:!0,version:"v1"})).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))})}getPinnedMessages(t){return k(this,null,function*(){let n=yield this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0,version:"v1"});return be(n).map(r=>I(C({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return k(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",$e(t),{abortLatest:!0,version:"v1"});return be(n)})}search(t){return k(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,$e(t),{version:"v2"});return be(n)})}knowledgeAssist(i,s,a){return k(this,arguments,function*(t,n,r,o={}){let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,$e({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(u=>({question:u.question,answer:u.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return be(l)})}requestLoginByEmail(t){return k(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return be(n)})}requestPasswordlessToken(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return be(t.token)})}getCsrfToken(){return k(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return k(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return be(n)})}getSummary(r){return k(this,arguments,function*(t,n={}){let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(i=>i.text&&i.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return be(o)})}evaluateAssistant(t,n){return k(this,null,function*(){var a;let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let l=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",l)}else r.append("expect_response_format",o);n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let i=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,s=yield this.client.post(i,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return be(s.output)})}createAssistantThread(t){return k(this,null,function*(){let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return be(r)})}postMessageToAssistantThread(t){return k(this,null,function*(){let{assistantCode:n,threadId:r,message:o}=t,i=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return be(i)})}translateMessages(t){return k(this,null,function*(){let n=yield this.client.post("/api/translate",$e(t),{version:"v2"});return be(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(i0);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&z.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};ri.exchangeTokenPromise=null;var yr=ri;var _C={startTime:null,stopTime:null},MC=e=>e.handlingTime,DC=re({name:"handlingTime",initialState:_C,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(Ne,()=>_C)}}),{handlingTimeStart:FC,handlingTimeStop:Df,handlingTimeReset:HC}=DC.actions,UC=DC.reducer;var zC=(e={})=>{let t=C({onAuthError:is(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Ff={list:{keywordMatches:[]},fetchState:"idle"};var oi=J("styleSuggestions/getAll",(n,r)=>k(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(l=i.conversation.current)==null?void 0:l.profileCode;if(!s)return Ff.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),z_=re({name:"styleSuggestions",initialState:Ff,reducers:{},extraReducers:e=>{e.addCase(oi.pending,t=>{t.fetchState="loading"}).addCase(oi.rejected,t=>{t.fetchState="error"}).addCase(oi.fulfilled,(t,n)=>{t.fetchState="done",$r(t.list,n.payload)||(t.list=n.payload)}).addCase(Lo,t=>{t.list=Ff.list}).addCase(Ne,()=>Ff)}}),jC=z_.reducer;var BC=(e={})=>{let t,n=!0,r=C({getStyleSuggestions:oi,debounce:500},e);return o=>i=>s=>{var p;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(!((p=u.conversation.current)==null?void 0:p.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 j_(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var VC=(e={})=>{let t=C({getTextSuggestions:yn,getAutocompleteSuggestions:Al,debounce:200,check:Mn},e),n;return r=>o=>i=>{var v;let{input: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===lf.toString();if(!f||!u&&!c)return a;let{input:p}=l;return j_(p,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let m=as(l);m===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(m))},d?0:t.debounce)),a}};var WC=oi.fulfilled.toString();function B_(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 KC=e=>t=>n=>r=>{var u;if(r.type!==WC){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=B_(o,s);r.type===WC&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var V_=Ic({assistants:jb,auth:R1,conversation:U1,contentTypes:Vb,passwordlessToken:tC,entities:hE,knowledgeAssistant:Db,handlingTime:UC,info:ib,input:Q1,settings:w1,profile:Kb,search:db,styleSuggestions:jC,ui:wT,textSuggestions:sT});function $C(e){return Pw({reducer:V_,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}),zC(),VC({debounce:200}),BC({debounce:500}),KC(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var W_=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},K_=e=>t=>n=>r=>{var a,l,u,c,f,d;let o=t.getState(),i=qa("inlineSuggestions")(o);switch(r.type){case is.toString():{!r.payload&&e.emit("logout",void 0);break}case mn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case Xt.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Lo.toString():e.logSendMessage(r.payload);break;case Fd.toString():e.emit("call-to-action",{cue:r.payload});break;case rr.fulfilled.toString():r.isBroadcasted||e.broadcast(dh,r,!1);break;default:break}let s=n(r);switch(r.type){case Lo.toString():e.handleAfterSendMessage(r.payload);break;case Ol.toString():e.onUpdateShowTabHint(r.payload);break;case Df.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case pd.toString():{let{start:p,end:y}=o.input.selection;e.emit("replace",I(C({},r.payload),{replace:r.payload.replace==="selection"?{start:p,end:y}:{start:0,end:y}}));break}case un.toString():{let{start:p,end:y}=o.input.selection;e.emit("select-suggestion",I(C({type:W_(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:p,end:y}:{start:0,end:y}})),i&&t.dispatch(qr([]));break}case md.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(c=o.conversation.current)==null?void 0:c.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case qr.toString():{i&&r.payload.length>0&&t.dispatch(gd(0));break}case On.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{summary:r.payload,assistant:(d=t.getState().profile.data)==null?void 0:d.summarizerAssistantNew}});break}default:break}return s},qC=K_;function My(e){return e.toISOString().replace("T"," ").replace("Z","")}var $_=(e,t)=>t.version,GC=ln([us,An,MC,$_],(e,t,n,r)=>{if(!t)return z.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:i}=n;return!o||!i?(z.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:t,clientVersion:r,agentId:e==null?void 0:e.agentId,agentName:e==null?void 0:e.agentName,agentEmail:e==null?void 0:e.agentEmail,timeStart:My(o),timeStop:My(i)}});function YC(e,t,n){var N,M,G,B;let r=(N=t.conversation.current)==null?void 0:N.id;if(!r)return z.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:i,numCharsPasted:s,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:f,pastes:d,cuts:p,deletions:y,textSuggestions:v,offeredTextSuggestions:m}}=t[e],g=o.length,S=v.reduce((V,{text:fe,searchTerm:Ge})=>V+fe.length-(Ge?Ge.length:0),0),w=c!=null?c:Date.now(),P=(Date.now()-w)/1e3+(f||0),T=i/P,R=v.reduce((V,{searchTerm:fe})=>V+(fe?fe.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:p,deletions:y,lenTextTyped:i+R,lenTextTotal:g,lenTextAssisted:S,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:P,charsPerSecond:T,numPastes:u,textSuggestionsV2:v,suggestionsCounters:[{source:"gpt",countOffered:m.filter(V=>V.source==="gpt").length}],agentId:(M=t.info.agentInfo)==null?void 0:M.agentId,agentName:(G=t.info.agentInfo)==null?void 0:G.agentName,agentEmail:(B=t.info.agentInfo)==null?void 0:B.agentEmail}}function Dy(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Dy(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Dy(o,t):null}function Fy(e,t){return Dy(e,t)}function XC(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function q_(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Hf(e){return q_(e)&&(Qo(e)||yf(e))}var ZC,Hn=new Map,G_=["bottom","height","left","right","top","width"],QC=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:G_.some(n=>e[n]!==t[n]);function JC(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...JC(t)]:[]}function ek(e,t){return!e||!t?null:I(C({},e),{top:e.top+t.top,left:e.left+t.left})}var Uf=!1,tk=()=>{Uf=!0;let e=[];if(Hn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Hn.delete(n);return}let r=n.getBoundingClientRect();QC(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(ek,t.rect):t.rect;QC(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Hn.size===0){Uf=!1;return}ZC=window.requestAnimationFrame(tk)};function Hy(e,t){let n=JC(e),r=[],o=n.map((i,s)=>Hy(i,a=>{r[s]=a;let l=Hn.get(e);if(!l)return;let u=r.reduce(ek,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Hn.has(e)){let s=Hn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Hn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!Uf&&tk()},unobserve(){o.forEach(s=>s.unobserve());let i=Hn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Hn.delete(e),Hn.size||(cancelAnimationFrame(ZC),Uf=!1)}}}}var nk,Un=new Map,rk=()=>{Un.forEach((e,t)=>{if(!t.isConnected){Un.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)))}),Un.size!==0&&(nk=window.requestAnimationFrame(rk))};function ok(e,t){return{observe(){let n=Un.size===0;Un.has(e)?Un.get(e).callbacks.push(t):Un.set(e,{visible:void 0,callbacks:[t]}),n&&rk()},unobserve(){let n=Un.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Un.delete(e),Un.size||cancelAnimationFrame(nk)}}}}var Uy=["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 zy(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Os(e){return parseFloat(e)}function zf(e){return Math.round(e*1e6)}function ik(e){return e/1e6}function jy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Os(e.width),i=Os(e.borderLeftWidth),s=Os(e.borderRightWidth),a=Os(e.paddingRight),l=ik(zf(o)-zf(i)-zf(s)),u=ik(zf(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function Vl(e,t={}){var c,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Wo(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};zy(r,n,Uy),jy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=ok(e,()=>{zy(r,n,Uy),jy(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=Hy(e,d=>{if(d===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),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(zy(r,n,Uy),jy(r,e,n),i(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let p=t.closestScrollElement.getBoundingClientRect(),y=window.getComputedStyle(t.closestScrollElement),v=Os(y.borderTopWidth),m=Os(y.borderBottomWidth),g=p.top+v-d.top,h=d.top+d.height+-(p.top+p.height-m);n.style.clipPath=`inset(${g}px 0px ${h}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var sk=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){z.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function Y_(e){return e.offsetParent!==null}function ak(e){if(!Y_(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 jf(e,t,n=100){let r=ak(e);t({isVisible:r});let o=setInterval(()=>{let i=ak(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Me=x(E());var lk=sk("showTabHint",!0),Ns=class Ns{constructor({deepdeskUrl:t,version:n=Ns.version||"unknown",locale:r="en-US",token:o,fetch:i,productName:s,createCustomChannel:a}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.floatingMenu=null;this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=t.replace(/\/api$/,"");this.deepdeskApi=new yr(l,{token:o,fetch:i}),this.version=n,this.instanceId=Ns.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[qC({broadcast:(c,f,d)=>{this.broadcastEvents.send(c,f,d)},emit:(c,f)=>this.emit(c,f),handleAfterSendMessage:c=>this.handleAfterSendMessage(c),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:c=>this.logSendMessage(c),onUpdateShowTabHint:c=>lk.update(c),sendEvent:(c,f)=>this.deepdeskApi.sendEvent(c,f)})]};this.store=$C(u),this.broadcastEvents=new OC({debug:!0,deepdeskUrl:l,eventMap:fb(this.store),createCustomChannel:a}),this.store.dispatch(Ol(lk.value())),this.store.dispatch(ad({locale:r,adminUrl:l,productName:s}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t: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?(z.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(z.warn("Profile has not been loaded (yet)"),!0):(z.warn("No conversation loaded (yet)"),!0)}login(){this.store.dispatch(is(null)),this.store.dispatch(er());let t=n=>ft(n)&&b1(n)!=="loading";return new Promise(n=>{let r=this.subscribe(t,o=>{o&&(r(),n())});this.unmountHandlers.push(()=>{r()})})}isLoggedIn(){return k(this,null,function*(){return(yield this.store.dispatch(er())).payload})}isConversationSupported(t,n){return k(this,null,function*(){return(yield this.store.dispatch(ih({sessionId:t,options:n}))).payload})}createConversation(t){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(ud(t))).payload})}getConversationBySessionId(t,n){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(cd({sessionId:t,options:n}))).payload})}upsertConversation(t){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(sh(t))).payload})}postMessages(t){return k(this,null,function*(){return(yield this.store.dispatch(fd(t))).payload})}updateConversation(t){return k(this,null,function*(){return(yield this.store.dispatch(dd(t))).payload})}resetConversation(){this.store.dispatch(Ne()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(ad(t))}setVisitorInfo(t){this.store.dispatch(nb(t))}setCustomData(t){this.store.dispatch(rb(t))}setAgentInfo(t,n){return k(this,null,function*(){yield this.store.dispatch(Xa(C(C({},t),n)))})}setAgentSettings(t){return k(this,null,function*(){yield this.store.dispatch(lh(t))})}getAgentSettings(){return k(this,null,function*(){return(yield this.store.dispatch(uh())).payload})}refresh(){return k(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(hd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(lf()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(un(t))}evaluateAssistant(t,n){return k(this,null,function*(){let c=n||{},{input:r={},transcript:o,showCuesInWidget:i=!0,includeTags:s,expectFormat:a}=c,l=ee(c,["input","transcript","showCuesInWidget","includeTags","expectFormat"]);Object.assign(r,l);let u=yield this.store.dispatch(rr({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeTags:s,input:r,skipState:!i}));if(u.error)throw new Error(u.error.message);return u.payload})}evaluateConversationAssistant(t,n){return k(this,null,function*(){yield this.loadProfileConfig();let r={accepted:"conversationAcceptedAssistant","new-message":"conversationNewMessageAssistant",ended:"conversationEndedAssistant"},o=this.state.profile.data[r[t]];if(!o){z.warn(`No assistant set in profile for conversation event "${t}"`);return}yield this.evaluateAssistant(o,C({transcript:"stored-transcript",includeTags:!0},n))})}getSummary(){return k(this,null,function*(){var n;if(!this.hasConversation())return z.warn("No conversation to create summary for."),null;(n=this.state.profile.data)!=null&&n.summarizerAssistantNew||z.warn("No profile loaded yet, or no summarizer assistant set in profile");let t=yield this.store.dispatch(On({}));if(t.error)throw new Error(t.error.message);return t.payload})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.settings,u=a?"below":"above",c=o.length>0;if(this.store.dispatch(W1(ah(t))),!Mn(this.state)||t.key!=="Tab"&&!l)return;let f=()=>{n||!c||s&&(t.shiftKey||(this.store.dispatch(q1()),t.preventDefault()))},d=()=>{n||!c||a&&i<=0||s&&(t.shiftKey||(this.store.dispatch(G1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():f();break;case"ArrowDown":{u==="below"?f():d();break}case"Escape":{n||(this.store.dispatch(gd(-1)),this.store.dispatch(Jr({collapse:!0})),this.store.dispatch(ST(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let p=ls(this.state);if(!p)return;this.store.dispatch(Ol(!1)),this.store.dispatch(un({text:p.text,suggestion:p,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let p=ls(this.state);if(!p)return;this.store.dispatch(un({text:p.text,suggestion:p,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let p=ls(this.state);if(!p)return;this.store.dispatch(un({text:p.text,suggestion:p,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(Jr({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(qr([]))}handlingTimeStart(){this.state.handlingTime.startTime||(z.info("Start handling time"),this.store.dispatch(FC()))}handlingTimeStop(){this.state.handlingTime.startTime&&(z.info("Stop handling time"),this.store.dispatch(Df()))}logSendMessage(t){let n=YC("input",this.state,{version:this.version});n&&(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=GC(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(HC()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Lo((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(X1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){z.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),z.error(i)}})}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}setPlatformVariables(t){this.store.dispatch(ob(t))}whenConversationLoaded(t){let n=o=>{var i;return(i=o.conversation.current)==null?void 0:i.id},r=()=>this.loadProfileConfig().then(()=>t());n(this.state)&&r(),this.subscribe(n,o=>{o&&r()})}overlayContainerFactory(t,n,r,o){let[i,s]=Vl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,qe.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var a;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=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,s=i?i.ownerDocument.defaultView:null;if(i&&(s===window||(s==null?void 0:s.parent)===window)){let[l,u]=Vl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{(0,qe.unmountComponentAtNode)(o),u()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Wo(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,qe.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),z.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}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()?(z.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Y1(r.metrics))):z.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Hf(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s,inputMediator:a}=d,l=ee(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),u={customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),Wo(t),this.inputMediator=a||(Qo(t)?new ti(t):new ei(t)),this.inputMediator.on("change",({plainText:p,rawHTML:y})=>{this.store.dispatch(hd({text:p,html:y}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(K1(ah(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:y})=>{this.store.dispatch($1({text:p,selectionText:y}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(V1(p))});let c;this.inputMediator.on("selection",p=>{clearTimeout(c),p===null?c=setTimeout(()=>{p!==null&&this.store.dispatch(yd(p))},500):this.store.dispatch(yd(p))}),this.inputMediator.on("disabled",()=>{var p;(p=this.inputMediator)==null||p.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{this.settings.detectSubmit&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(df(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(df(!0))}),this.renderSuggestions(t,u),this.subscribe(qa("inlineSuggestions"),()=>{this.renderSuggestions(t,u)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(hd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(yd(this.inputMediator.getSelection())),this.store.dispatch(df(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var p;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((p=this.state.conversation.current)==null?void 0:p.sessionId)}),this.isMounted=!0}subscribe(t,n){let r=t(this.store.getState());return this.store.subscribe(()=>{let o=t(this.store.getState());o!==r&&(r=o,n(r))})}unmount(){var t,n,r,o;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.floatingMenu)==null||r.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(o=this.inputMediator)==null||o.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderSuggestions(t,n){var r,o,i;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(i=this.aboveSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.aboveSuggestions=this.renderAboveSuggestions(t,n)}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret");(0,qe.render)((0,Me.jsx)(Xo,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(PT,{})})}),o);let i=s=>{s?(o.style.display="block",o.style.top=`${s.top}px`,o.style.left=`${s.left}px`):o.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var s;(0,qe.unmountComponentAtNode)(o),(s=this.inputMediator)==null||s.off("caretposition",i),o.remove()}}}renderAboveSuggestions(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i}=n,s=o&&Fy(t,o)||void 0,a=this.overlayContainerFactory("deepdesk-tab-completion",s||t,{appendTo:i,closestScrollElement:s,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),l=this.overlayContainerFactory("deepdesk-suggestions-overlay",s||t,{appendTo:i},r==null?void 0:r.suggestionsRootNode);return(0,qe.render)((0,Me.jsx)(Xo,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(ZT,{inputElement:t})})}),a),(0,qe.render)((0,Me.jsx)(Xo,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(DT,{onLogIn:()=>this.loginViaPopup().catch(u=>z.warn(u.message))})})}),l),{unmount(){(0,qe.unmountComponentAtNode)(a),(0,qe.unmountComponentAtNode)(l),a.remove(),l.remove()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i,floatingMenuParent:s}=n,a=o&&Fy(t,o)||void 0,l=this.overlayContainerFactory("floating-menu",a||t,{appendTo:s!=null?s:i},r==null?void 0:r.floatingMenuParent);return(0,qe.render)((0,Me.jsx)(Xo,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(yT,{onLogIn:()=>this.loginViaPopup().catch(u=>z.warn(u.message))})})}),l),{unmount(){(0,qe.unmountComponentAtNode)(l),l.remove()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays");return(0,qe.render)((0,Me.jsx)(Xo,{store:this.store,customStyles:n,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(fT,{})})}),r),{unmount(){(0,qe.unmountComponentAtNode)(r),r.remove()}}}renderWidget(t,n={}){if(this.widgetRoot&&z.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,qe.render)((0,Me.jsx)(Xo,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(kC,{onLogIn:()=>this.loginViaPopup().catch(s=>z.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,qe.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=jf(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){XC(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>k(this,null,function*(){yield this.store.dispatch(cl());let t=No(this.state);t&&(yield this.store.dispatch(il()),this.store.dispatch(ad({showSearch:t.search,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew||t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))})),this.loadProfileConfigPromise)}loginViaPopup(t){return k(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.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=p=>k(this,null,function*(){var y,v;if((y=p.data)!=null&&y.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((v=p.data)==null?void 0:v.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Za),l=!0,o.port1.close(),n()}catch(m){console.error(m),r(m)}finally{l=!0,u()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let f=p=>k(this,null,function*(){var y;if(p.origin===a.origin)switch((y=p.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){z.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),p.data.message==="Timeout"&&z.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(p.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)}checkForTrialMode(t){return k(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(z.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;z.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return k(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=dl(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(mn()):du.includes(r)||this.store.dispatch(yn(r))})}catch(r){this.handleError(r)}})}};Ns.version="15.1.1-beta.0",Ns.count=0;var Wl=Ns;function X_(e){return k(this,null,function*(){var o,i,s;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(s=(i=e.mimeType)!=null?i:n.headers.get("Content-Type"))!=null?s:"image/jpeg"})})}function uk(e,t){return k(this,null,function*(){let n=yield X_(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}})}function ck(e,t,n){return k(this,null,function*(){yield new yr(e).authenticateWithKey(t,n)})}function dk(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function fk(r,o){return k(this,arguments,function*(e,t,n={}){var f,d;let{value:i}=e,{start:s,end:a}=(f=n.replace)!=null?f:{start:0,end:i.length},l=`${i.slice(0,s)}${t}${i.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+t.length},c=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(c()).then(()=>{e.selectionStart=u.start,e.selectionEnd=u.end,e.blur(),e.focus()})})}function pk(r,o){return k(this,arguments,function*(e,t,n={}){let i=n.replace?no(e,n.replace.start,n.replace.end):Ls(e),s,a=()=>{if(n.setRange)return n.setRange(i.cloneRange());i.deleteContents(),s=document.createElement("span"),i.insertNode(s),n.insertBRs!==!1?t.split(`
|
|
27
|
+
`);let y=d?r:0,v=p?Math.min(i,c.childNodes.length):c.childNodes.length;for(let m=y;m<v&&(u(c.childNodes[m]),a!==2);m++);break}default:break}p&&(a=2)}return u(e),l}var RC=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(RC||{}),hr=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}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)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let i=this.getCaretPosition();$r(i,this.cachedCaretPosition)||(this.cachedCaretPosition=i,this.emit("caretposition",i))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(RC).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",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.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),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.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!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()})}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))}off(t,n){if(!this.eventListeners[t])return;let r=this.eventListeners[t].indexOf(n);r!==-1&&this.eventListeners[t].splice(r,1)}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function LC(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var ei=class extends hr{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Bl(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var s;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(s=r.getComposedRanges(n))==null?void 0:s[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!LC(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!LC(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return jl(this.element,n);let r=this.lastKnownSelection;if(r&&PC(this.element,r.start,r.end))return r;let o=Ls(this.element);return o.collapse(!1),jl(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Bl(this.element,no(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(i=>{var s,a;i.length===2&&i[0].addedNodes.length===1&&((s=i[0].addedNodes[0])==null?void 0:s.textContent)==="\u2060"&&((a=i[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var M_=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function AC(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,i=window.getComputedStyle(e),s=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",M_.forEach(function(c){o[c]=i[c]}),n?e.scrollHeight>parseInt(i.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),s.appendChild(r);let l=e.getBoundingClientRect(),u={top:l.top-e.scrollTop+a.offsetTop+parseInt(i.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+parseInt(i.borderLeftWidth)};return s.removeChild(r),u}var ti=class extends hr{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return AC(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var i;return(i=n==null?void 0:n.get)==null?void 0:i.call(this.element)},set:i=>{var s;(s=n==null?void 0:n.set)==null||s.call(this.element,i),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function IC(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 D_(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var Ly=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}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()}},Ay=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=IC(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}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()}},Iy=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),z.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 Ay(t,this.deepdeskUrl,{debug:!0}):new Ly(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=D_(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(z.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;z.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(I(C({},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)}},OC=Iy;function F_(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function be(e){return Array.isArray(e)?e.map(be):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(C({},t),{[F_(n)]:be(e[n])}),{}):e}function H_(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function $e(e){return Array.isArray(e)?e.map($e):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(C({},t),{[H_(n)]:$e(e[n])}),{}):e}var As=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var Oy=e=>new Promise(t=>{setTimeout(t,e)});var Is=class extends As{constructor(){super(...arguments);this.name="ClientError"}},_y=class extends As{constructor(){super(...arguments);this.name="ServerError"}},Ny=new Map;function U_(e){return k(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(z.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var ro=class ro{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}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",T=n,{useCache:u=!1,abortLatest:c=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:y=R=>R instanceof TypeError,retryOnResponse:v=R=>R.status>=500,version:m=null}=T,g=ee(T,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(Ny.has(s)){r(Ny.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h=I(C({credentials:"include"},g),{headers:C({Accept:"application/json","Content-Type":"application/json"},g.headers)});!l&&this.csrfToken&&(h.headers=I(C({},h.headers),{"X-CSRFToken":this.csrfToken})),typeof m=="string"&&(h.headers=I(C({},h.headers),{"X-Deepdesk-API-Version":m}));let S=f,w=!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 P=()=>k(this,null,function*(){return S--,a(s,h).then(R=>k(this,null,function*(){return v(R)&&!i.isAborted&&S>0?(yield Oy(d),P()):R.status===401&&p===!0&&w===!1?(w=!0,yield this.refreshToken(),P()):R})).catch(R=>k(this,null,function*(){if(y(R)&&!i.isAborted&&S>0)return yield Oy(d),P();throw R}))});P().then(R=>k(this,null,function*(){let N=yield U_(R);if(delete this.latestRequestByUrl[s],R.status>=500){o(new _y("Server Error",N));return}else if(R.status===401){o(new Is("Unauthorized",N));return}else if(R.status===403){o(new Is("Forbidden",N));return}else if(R.status===404){o(new Is("Not Found",N));return}else if(R.status>=400){o(new Is("Bad Request",N));return}u&&Ny.set(s,N),r(N)})).catch(R=>{o(R)})})}validateToken(){return k(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)try{yield this.refreshToken()}catch(r){return!1}let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/");return!!n})}refreshToken(){return ro.refreshingToken||(ro.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{ro.refreshingToken=null},1e3*60)})),ro.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,C({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,C({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,C({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,C({method:"DELETE"},n))}};ro.refreshingToken=null;var ni=ro;var NC;(t=>{let e;(s=>(s.SEND_MESSAGE="Send Message",s.HANDLING_TIME="Handling Time",s.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",s.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||(t.EventType={}))})(NC||(NC={}));function Mf(e){return I(C({},be(e)),{tags:e.tags})}var ri=class ri{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new ni(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>k(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return k(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(ri.exchangeTokenPromise||(ri.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),ri.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return k(this,null,function*(){yield this.preflight(),z.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",I(C({},$e(t)),{tags:t.tags}),{version:"v2"});return Mf(n)})}getMe(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return be(t)})}postIdentity(t){return k(this,null,function*(){yield this.client.post("/apis/admin/session/me/identities/",$e(t))})}patchMe(t){return k(this,null,function*(){let n=yield this.client.patch("/apis/admin/session/me/",$e(t));return be(n)})}getProfile(t){return k(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return be(n)})}getKnowledgeAssistant(t){return k(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return be(n)})}getContentTypes(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return be(t)})}getAccount(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return be(t)})}getPlatformConfig(t){return k(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return be(r)})}checkUserExists(t){return k(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationBySessionId(r){return k(this,arguments,function*(t,n={}){yield this.preflight(),z.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return z.info(`Successfully retrieved conversation ${s.id} for session ${t}`),Mf(s)})}isConversationSupported(r){return k(this,arguments,function*(t,n={}){z.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return k(this,null,function*(){let r=$e(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Mf(o)})}postMessages(t,n){return k(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>I(C({},$e(o)),{tags:o.tags})),{version:"v2"})).map(o=>Mf(o))})}sendEvent(t,n){return k(this,null,function*(){let s=n,{data:r}=s,o=ee(s,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>I(C({},a),{[l]:u}),{});return this.client.post("/api/events",$e(I(C(C({},i),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return k(this,null,function*(){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>I(C({},o),{[i]:s}),{});return this.client.post("/api/events",{event:t,data:$e(C(C({},n),r))},{version:"v1"})})}getEntities(t){return k(this,null,function*(){return(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)},{version:"v1"})).entities})}getTemporaryExchangeToken(){return k(this,null,function*(){return(yield this.client.get("/auth/exchange-token")).jwt})}exchangeTokenForAccessCookie(t){return k(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw z.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return k(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",$e(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return k(this,arguments,function*(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(yield this.client.post(`/api/conversations/${t}/recommend/${r}`,$e(n),{abortLatest:!0,version:"v1"})).map(s=>I(C({},be(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,l)=>a===l.findIndex(u=>u.text===s.text))})}isLoggedIn(){return k(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return k(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/autocomplete`,$e(n),{abortLatest:!0,version:"v1"})).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))})}getPinnedMessages(t){return k(this,null,function*(){let n=yield this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0,version:"v1"});return be(n).map(r=>I(C({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return k(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",$e(t),{abortLatest:!0,version:"v1"});return be(n)})}search(t){return k(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,$e(t),{version:"v2"});return be(n)})}knowledgeAssist(i,s,a){return k(this,arguments,function*(t,n,r,o={}){let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,$e({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(u=>({question:u.question,answer:u.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return be(l)})}requestLoginByEmail(t){return k(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return be(n)})}requestPasswordlessToken(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return be(t.token)})}getCsrfToken(){return k(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return k(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return be(n)})}getSummary(r){return k(this,arguments,function*(t,n={}){let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(i=>i.text&&i.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return be(o)})}evaluateAssistant(t,n){return k(this,null,function*(){var a;let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let l=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",l)}else r.append("expect_response_format",o);n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let i=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,s=yield this.client.post(i,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return be(s.output)})}createAssistantThread(t){return k(this,null,function*(){let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return be(r)})}postMessageToAssistantThread(t){return k(this,null,function*(){let{assistantCode:n,threadId:r,message:o}=t,i=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return be(i)})}translateMessages(t){return k(this,null,function*(){let n=yield this.client.post("/api/translate",$e(t),{version:"v2"});return be(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(i0);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&z.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};ri.exchangeTokenPromise=null;var yr=ri;var _C={startTime:null,stopTime:null},MC=e=>e.handlingTime,DC=re({name:"handlingTime",initialState:_C,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(Ne,()=>_C)}}),{handlingTimeStart:FC,handlingTimeStop:Df,handlingTimeReset:HC}=DC.actions,UC=DC.reducer;var zC=(e={})=>{let t=C({onAuthError:is(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Ff={list:{keywordMatches:[]},fetchState:"idle"};var oi=J("styleSuggestions/getAll",(n,r)=>k(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(l=i.conversation.current)==null?void 0:l.profileCode;if(!s)return Ff.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),z_=re({name:"styleSuggestions",initialState:Ff,reducers:{},extraReducers:e=>{e.addCase(oi.pending,t=>{t.fetchState="loading"}).addCase(oi.rejected,t=>{t.fetchState="error"}).addCase(oi.fulfilled,(t,n)=>{t.fetchState="done",$r(t.list,n.payload)||(t.list=n.payload)}).addCase(Lo,t=>{t.list=Ff.list}).addCase(Ne,()=>Ff)}}),jC=z_.reducer;var BC=(e={})=>{let t,n=!0,r=C({getStyleSuggestions:oi,debounce:500},e);return o=>i=>s=>{var p;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(!((p=u.conversation.current)==null?void 0:p.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 j_(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var VC=(e={})=>{let t=C({getTextSuggestions:yn,getAutocompleteSuggestions:Al,debounce:200,check:Mn},e),n;return r=>o=>i=>{var v;let{input: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===lf.toString();if(!f||!u&&!c)return a;let{input:p}=l;return j_(p,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let m=as(l);m===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(m))},d?0:t.debounce)),a}};var WC=oi.fulfilled.toString();function B_(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 KC=e=>t=>n=>r=>{var u;if(r.type!==WC){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=B_(o,s);r.type===WC&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var V_=Ic({assistants:jb,auth:R1,conversation:U1,contentTypes:Vb,passwordlessToken:tC,entities:hE,knowledgeAssistant:Db,handlingTime:UC,info:ib,input:Q1,settings:w1,profile:Kb,search:db,styleSuggestions:jC,ui:wT,textSuggestions:sT});function $C(e){return Pw({reducer:V_,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}),zC(),VC({debounce:200}),BC({debounce:500}),KC(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var W_=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},K_=e=>t=>n=>r=>{var a,l,u,c,f,d;let o=t.getState(),i=qa("inlineSuggestions")(o);switch(r.type){case is.toString():{!r.payload&&e.emit("logout",void 0);break}case mn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case Xt.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Lo.toString():e.logSendMessage(r.payload);break;case Fd.toString():e.emit("call-to-action",{cue:r.payload});break;case rr.fulfilled.toString():r.isBroadcasted||e.broadcast(dh,r,!1);break;default:break}let s=n(r);switch(r.type){case Lo.toString():e.handleAfterSendMessage(r.payload);break;case Ol.toString():e.onUpdateShowTabHint(r.payload);break;case Df.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case pd.toString():{let{start:p,end:y}=o.input.selection;e.emit("replace",I(C({},r.payload),{replace:r.payload.replace==="selection"?{start:p,end:y}:{start:0,end:y}}));break}case un.toString():{let{start:p,end:y}=o.input.selection;e.emit("select-suggestion",I(C({type:W_(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:p,end:y}:{start:0,end:y}})),i&&t.dispatch(qr([]));break}case md.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(c=o.conversation.current)==null?void 0:c.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case qr.toString():{i&&r.payload.length>0&&t.dispatch(gd(0));break}case On.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{summary:r.payload,assistant:(d=t.getState().profile.data)==null?void 0:d.summarizerAssistantNew}});break}default:break}return s},qC=K_;function My(e){return e.toISOString().replace("T"," ").replace("Z","")}var $_=(e,t)=>t.version,GC=ln([us,An,MC,$_],(e,t,n,r)=>{if(!t)return z.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:i}=n;return!o||!i?(z.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:t,clientVersion:r,agentId:e==null?void 0:e.agentId,agentName:e==null?void 0:e.agentName,agentEmail:e==null?void 0:e.agentEmail,timeStart:My(o),timeStop:My(i)}});function YC(e,t,n){var N,M,G,B;let r=(N=t.conversation.current)==null?void 0:N.id;if(!r)return z.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:i,numCharsPasted:s,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:f,pastes:d,cuts:p,deletions:y,textSuggestions:v,offeredTextSuggestions:m}}=t[e],g=o.length,S=v.reduce((V,{text:fe,searchTerm:Ge})=>V+fe.length-(Ge?Ge.length:0),0),w=c!=null?c:Date.now(),P=(Date.now()-w)/1e3+(f||0),T=i/P,R=v.reduce((V,{searchTerm:fe})=>V+(fe?fe.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:p,deletions:y,lenTextTyped:i+R,lenTextTotal:g,lenTextAssisted:S,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:P,charsPerSecond:T,numPastes:u,textSuggestionsV2:v,suggestionsCounters:[{source:"gpt",countOffered:m.filter(V=>V.source==="gpt").length}],agentId:(M=t.info.agentInfo)==null?void 0:M.agentId,agentName:(G=t.info.agentInfo)==null?void 0:G.agentName,agentEmail:(B=t.info.agentInfo)==null?void 0:B.agentEmail}}function Dy(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Dy(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Dy(o,t):null}function Fy(e,t){return Dy(e,t)}function XC(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function q_(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Hf(e){return q_(e)&&(Qo(e)||yf(e))}var ZC,Hn=new Map,G_=["bottom","height","left","right","top","width"],QC=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:G_.some(n=>e[n]!==t[n]);function JC(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...JC(t)]:[]}function ek(e,t){return!e||!t?null:I(C({},e),{top:e.top+t.top,left:e.left+t.left})}var Uf=!1,tk=()=>{Uf=!0;let e=[];if(Hn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Hn.delete(n);return}let r=n.getBoundingClientRect();QC(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(ek,t.rect):t.rect;QC(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Hn.size===0){Uf=!1;return}ZC=window.requestAnimationFrame(tk)};function Hy(e,t){let n=JC(e),r=[],o=n.map((i,s)=>Hy(i,a=>{r[s]=a;let l=Hn.get(e);if(!l)return;let u=r.reduce(ek,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Hn.has(e)){let s=Hn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Hn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!Uf&&tk()},unobserve(){o.forEach(s=>s.unobserve());let i=Hn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Hn.delete(e),Hn.size||(cancelAnimationFrame(ZC),Uf=!1)}}}}var nk,Un=new Map,rk=()=>{Un.forEach((e,t)=>{if(!t.isConnected){Un.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)))}),Un.size!==0&&(nk=window.requestAnimationFrame(rk))};function ok(e,t){return{observe(){let n=Un.size===0;Un.has(e)?Un.get(e).callbacks.push(t):Un.set(e,{visible:void 0,callbacks:[t]}),n&&rk()},unobserve(){let n=Un.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Un.delete(e),Un.size||cancelAnimationFrame(nk)}}}}var Uy=["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 zy(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Os(e){return parseFloat(e)}function zf(e){return Math.round(e*1e6)}function ik(e){return e/1e6}function jy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Os(e.width),i=Os(e.borderLeftWidth),s=Os(e.borderRightWidth),a=Os(e.paddingRight),l=ik(zf(o)-zf(i)-zf(s)),u=ik(zf(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function Vl(e,t={}){var c,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Wo(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};zy(r,n,Uy),jy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=ok(e,()=>{zy(r,n,Uy),jy(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=Hy(e,d=>{if(d===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),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(zy(r,n,Uy),jy(r,e,n),i(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let p=t.closestScrollElement.getBoundingClientRect(),y=window.getComputedStyle(t.closestScrollElement),v=Os(y.borderTopWidth),m=Os(y.borderBottomWidth),g=p.top+v-d.top,h=d.top+d.height+-(p.top+p.height-m);n.style.clipPath=`inset(${g}px 0px ${h}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var sk=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){z.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function Y_(e){return e.offsetParent!==null}function ak(e){if(!Y_(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 jf(e,t,n=100){let r=ak(e);t({isVisible:r});let o=setInterval(()=>{let i=ak(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Me=x(E());var lk=sk("showTabHint",!0),Ns=class Ns{constructor({deepdeskUrl:t,version:n=Ns.version||"unknown",locale:r="en-US",token:o,fetch:i,productName:s,createCustomChannel:a}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.floatingMenu=null;this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=t.replace(/\/api$/,"");this.deepdeskApi=new yr(l,{token:o,fetch:i}),this.version=n,this.instanceId=Ns.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[qC({broadcast:(c,f,d)=>{this.broadcastEvents.send(c,f,d)},emit:(c,f)=>this.emit(c,f),handleAfterSendMessage:c=>this.handleAfterSendMessage(c),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:c=>this.logSendMessage(c),onUpdateShowTabHint:c=>lk.update(c),sendEvent:(c,f)=>this.deepdeskApi.sendEvent(c,f)})]};this.store=$C(u),this.broadcastEvents=new OC({debug:!0,deepdeskUrl:l,eventMap:fb(this.store),createCustomChannel:a}),this.store.dispatch(Ol(lk.value())),this.store.dispatch(ad({locale:r,adminUrl:l,productName:s}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t: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?(z.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(z.warn("Profile has not been loaded (yet)"),!0):(z.warn("No conversation loaded (yet)"),!0)}login(){this.store.dispatch(is(null)),this.store.dispatch(er());let t=n=>ft(n)&&b1(n)!=="loading";return new Promise(n=>{let r=this.subscribe(t,o=>{o&&(r(),n())});this.unmountHandlers.push(()=>{r()})})}isLoggedIn(){return k(this,null,function*(){return(yield this.store.dispatch(er())).payload})}isConversationSupported(t,n){return k(this,null,function*(){return(yield this.store.dispatch(ih({sessionId:t,options:n}))).payload})}createConversation(t){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(ud(t))).payload})}getConversationBySessionId(t,n){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(cd({sessionId:t,options:n}))).payload})}upsertConversation(t){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(sh(t))).payload})}postMessages(t){return k(this,null,function*(){return(yield this.store.dispatch(fd(t))).payload})}updateConversation(t){return k(this,null,function*(){return(yield this.store.dispatch(dd(t))).payload})}resetConversation(){this.store.dispatch(Ne()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(ad(t))}setVisitorInfo(t){this.store.dispatch(nb(t))}setCustomData(t){this.store.dispatch(rb(t))}setAgentInfo(t,n){return k(this,null,function*(){yield this.store.dispatch(Xa(C(C({},t),n)))})}setAgentSettings(t){return k(this,null,function*(){yield this.store.dispatch(lh(t))})}getAgentSettings(){return k(this,null,function*(){return(yield this.store.dispatch(uh())).payload})}refresh(){return k(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(hd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(lf()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(un(t))}evaluateAssistant(t,n){return k(this,null,function*(){let c=n||{},{input:r={},transcript:o,showCuesInWidget:i=!0,includeTags:s,expectFormat:a}=c,l=ee(c,["input","transcript","showCuesInWidget","includeTags","expectFormat"]);Object.assign(r,l);let u=yield this.store.dispatch(rr({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeTags:s,input:r,skipState:!i}));if(u.error)throw new Error(u.error.message);return u.payload})}evaluateConversationAssistant(t,n){return k(this,null,function*(){yield this.loadProfileConfig();let r={accepted:"conversationAcceptedAssistant","new-message":"conversationNewMessageAssistant",ended:"conversationEndedAssistant"},o=this.state.profile.data[r[t]];if(!o){z.warn(`No assistant set in profile for conversation event "${t}"`);return}yield this.evaluateAssistant(o,C({transcript:"stored-transcript",includeTags:!0},n))})}getSummary(){return k(this,null,function*(){var n;if(!this.hasConversation())return z.warn("No conversation to create summary for."),null;(n=this.state.profile.data)!=null&&n.summarizerAssistantNew||z.warn("No profile loaded yet, or no summarizer assistant set in profile");let t=yield this.store.dispatch(On({}));if(t.error)throw new Error(t.error.message);return t.payload})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.settings,u=a?"below":"above",c=o.length>0;if(this.store.dispatch(W1(ah(t))),!Mn(this.state)||t.key!=="Tab"&&!l)return;let f=()=>{n||!c||s&&(t.shiftKey||(this.store.dispatch(q1()),t.preventDefault()))},d=()=>{n||!c||a&&i<=0||s&&(t.shiftKey||(this.store.dispatch(G1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():f();break;case"ArrowDown":{u==="below"?f():d();break}case"Escape":{n||(this.store.dispatch(gd(-1)),this.store.dispatch(Jr({collapse:!0})),this.store.dispatch(ST(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let p=ls(this.state);if(!p)return;this.store.dispatch(Ol(!1)),this.store.dispatch(un({text:p.text,suggestion:p,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let p=ls(this.state);if(!p)return;this.store.dispatch(un({text:p.text,suggestion:p,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let p=ls(this.state);if(!p)return;this.store.dispatch(un({text:p.text,suggestion:p,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(Jr({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(qr([]))}handlingTimeStart(){this.state.handlingTime.startTime||(z.info("Start handling time"),this.store.dispatch(FC()))}handlingTimeStop(){this.state.handlingTime.startTime&&(z.info("Stop handling time"),this.store.dispatch(Df()))}logSendMessage(t){let n=YC("input",this.state,{version:this.version});n&&(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=GC(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(HC()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Lo((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(X1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){z.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),z.error(i)}})}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}setPlatformVariables(t){this.store.dispatch(ob(t))}whenConversationLoaded(t){let n=o=>{var i;return(i=o.conversation.current)==null?void 0:i.id},r=()=>this.loadProfileConfig().then(()=>t());n(this.state)&&r(),this.subscribe(n,o=>{o&&r()})}overlayContainerFactory(t,n,r,o){let[i,s]=Vl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,qe.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var a;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=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,s=i?i.ownerDocument.defaultView:null;if(i&&(s===window||(s==null?void 0:s.parent)===window)){let[l,u]=Vl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{(0,qe.unmountComponentAtNode)(o),u()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Wo(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,qe.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),z.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}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()?(z.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Y1(r.metrics))):z.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Hf(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s,inputMediator:a}=d,l=ee(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),u={customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),Wo(t),this.inputMediator=a||(Qo(t)?new ti(t):new ei(t)),this.inputMediator.on("change",({plainText:p,rawHTML:y})=>{this.store.dispatch(hd({text:p,html:y}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(K1(ah(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:y})=>{this.store.dispatch($1({text:p,selectionText:y}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(V1(p))});let c;this.inputMediator.on("selection",p=>{clearTimeout(c),p===null?c=setTimeout(()=>{p!==null&&this.store.dispatch(yd(p))},500):this.store.dispatch(yd(p))}),this.inputMediator.on("disabled",()=>{var p;(p=this.inputMediator)==null||p.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{this.settings.detectSubmit&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(df(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(df(!0))}),this.renderSuggestions(t,u),this.subscribe(qa("inlineSuggestions"),()=>{this.renderSuggestions(t,u)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(hd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(yd(this.inputMediator.getSelection())),this.store.dispatch(df(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var p;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((p=this.state.conversation.current)==null?void 0:p.sessionId)}),this.isMounted=!0}subscribe(t,n){let r=t(this.store.getState());return this.store.subscribe(()=>{let o=t(this.store.getState());o!==r&&(r=o,n(r))})}unmount(){var t,n,r,o;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.floatingMenu)==null||r.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(o=this.inputMediator)==null||o.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderSuggestions(t,n){var r,o,i;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(i=this.aboveSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.aboveSuggestions=this.renderAboveSuggestions(t,n)}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret");(0,qe.render)((0,Me.jsx)(Xo,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(PT,{})})}),o);let i=s=>{s?(o.style.display="block",o.style.top=`${s.top}px`,o.style.left=`${s.left}px`):o.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var s;(0,qe.unmountComponentAtNode)(o),(s=this.inputMediator)==null||s.off("caretposition",i),o.remove()}}}renderAboveSuggestions(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i}=n,s=o&&Fy(t,o)||void 0,a=this.overlayContainerFactory("deepdesk-tab-completion",s||t,{appendTo:i,closestScrollElement:s,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),l=this.overlayContainerFactory("deepdesk-suggestions-overlay",s||t,{appendTo:i},r==null?void 0:r.suggestionsRootNode);return(0,qe.render)((0,Me.jsx)(Xo,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(ZT,{inputElement:t})})}),a),(0,qe.render)((0,Me.jsx)(Xo,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(DT,{onLogIn:()=>this.loginViaPopup().catch(u=>z.warn(u.message))})})}),l),{unmount(){(0,qe.unmountComponentAtNode)(a),(0,qe.unmountComponentAtNode)(l),a.remove(),l.remove()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i,floatingMenuParent:s}=n,a=o&&Fy(t,o)||void 0,l=this.overlayContainerFactory("floating-menu",a||t,{appendTo:s!=null?s:i},r==null?void 0:r.floatingMenuParent);return(0,qe.render)((0,Me.jsx)(Xo,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(yT,{onLogIn:()=>this.loginViaPopup().catch(u=>z.warn(u.message))})})}),l),{unmount(){(0,qe.unmountComponentAtNode)(l),l.remove()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays");return(0,qe.render)((0,Me.jsx)(Xo,{store:this.store,customStyles:n,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(fT,{})})}),r),{unmount(){(0,qe.unmountComponentAtNode)(r),r.remove()}}}renderWidget(t,n={}){if(this.widgetRoot&&z.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,qe.render)((0,Me.jsx)(Xo,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(kC,{onLogIn:()=>this.loginViaPopup().catch(s=>z.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,qe.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=jf(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){XC(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>k(this,null,function*(){yield this.store.dispatch(cl());let t=No(this.state);t&&(yield this.store.dispatch(il()),this.store.dispatch(ad({showSearch:t.search,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew||t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))})),this.loadProfileConfigPromise)}loginViaPopup(t){return k(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.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=p=>k(this,null,function*(){var y,v;if((y=p.data)!=null&&y.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((v=p.data)==null?void 0:v.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Za),l=!0,o.port1.close(),n()}catch(m){console.error(m),r(m)}finally{l=!0,u()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let f=p=>k(this,null,function*(){var y;if(p.origin===a.origin)switch((y=p.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){z.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),p.data.message==="Timeout"&&z.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(p.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)}checkForTrialMode(t){return k(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(z.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;z.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return k(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=dl(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(mn()):du.includes(r)||this.store.dispatch(yn(r))})}catch(r){this.handleError(r)}})}};Ns.version="15.1.1-beta.1",Ns.count=0;var Wl=Ns;function X_(e){return k(this,null,function*(){var o,i,s;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(s=(i=e.mimeType)!=null?i:n.headers.get("Content-Type"))!=null?s:"image/jpeg"})})}function uk(e,t){return k(this,null,function*(){let n=yield X_(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}})}function ck(e,t,n){return k(this,null,function*(){yield new yr(e).authenticateWithKey(t,n)})}function dk(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function fk(r,o){return k(this,arguments,function*(e,t,n={}){var f,d;let{value:i}=e,{start:s,end:a}=(f=n.replace)!=null?f:{start:0,end:i.length},l=`${i.slice(0,s)}${t}${i.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+t.length},c=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(c()).then(()=>{e.selectionStart=u.start,e.selectionEnd=u.end,e.blur(),e.focus()})})}function pk(r,o){return k(this,arguments,function*(e,t,n={}){let i=n.replace?no(e,n.replace.start,n.replace.end):Ls(e),s,a=()=>{if(n.setRange)return n.setRange(i.cloneRange());i.deleteContents(),s=document.createElement("span"),i.insertNode(s),n.insertBRs!==!1?t.split(`
|
|
28
28
|
`).reverse().forEach((l,u)=>{u>0&&i.insertNode(document.createElement("br")),i.insertNode(document.createTextNode(l))}):i.insertNode(document.createTextNode(t))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let l=n.selectionAfter?no(e,n.selectionAfter.start,n.selectionAfter.end):(i.collapse(!1),i),u=window.getSelection();u==null||u.removeAllRanges(),u==null||u.addRange(l)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}function Q_(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 Z_(e){let t=document.createDocumentFragment();return e.split(`
|
|
29
29
|
`).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 mk(e,t){let n=e.parentElement;if(!n){console.warn("No insert point found");return}let{display:r}=window.getComputedStyle(n);r.includes("block")||r==="table-cell"?n==null||n.insertBefore(t,e.nextSibling):mk(n,t)}function gk(o,i){return k(this,arguments,function*(e,t,{isBlock:n,isHTML:r}={}){let s;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let a=()=>{var d;let l=(d=e.ownerDocument.defaultView)!=null?d:window,u=l.getSelection();if((!u||u.rangeCount===0)&&(e.focus(),u=l.getSelection()),!u||u.rangeCount===0)return;let c=u.getRangeAt(0);if(!c)return;s=document.createElement("span"),c.insertNode(s);let f=r?Q_(t):Z_(t);n?mk(c.startContainer,f):(c.insertNode(f),c.collapse(!1))};return Promise.resolve(a()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!s)try{s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}return Ak(J_);})();
|
|
30
30
|
/*! Bundled license information:
|