@deepdesk/deepdesk-sdk 19.6.2-beta.7 → 19.6.2-beta.8

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.
@@ -80,7 +80,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
80
80
  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
81
81
  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 FS=E(A()),j6={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},oI=({className:e,color:t})=>(0,FS.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,FS.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:j6[t||"pink"]})});var sI={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedIn:"dd-XvHAn",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var zS={};ut(zS,{enUS:()=>K6,nlNL:()=>G6});var K6={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},G6={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Ci=E(A()),aI=({onLogIn:e})=>{let t=ae(zS),n=Z("floatingMenu"),r=Z("productName"),o=ve(),s=j(kt),i=F("FloatingMenu",sI);if(s===null||n===!1)return null;let a=()=>{s===!0?o(cr(!0)):e()};return(0,Ci.jsxs)("button",{type:"button",className:(0,iI.default)(i.root,{[i.isLoggedIn]:s,[i.isLoggedOut]:!s}),onClick:a,children:[(0,Ci.jsx)("div",{className:i.text,children:t(s?"search":"signin",{productName:r})}),(0,Ci.jsxs)("div",{className:i.icon,children:[(0,Ci.jsx)(oI,{className:i.logo,color:"pink"}),s===!1&&(0,Ci.jsx)(rI,{className:i.lock})]})]})};var Bm=E(Q());function Gr(e){let{showMidSentenceSuggestions:t,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:r}=e.settings,{text:o,selection:s}=e.input;return s.end<e.input.suggestionTextStart||s.start!==s.end?!1:s.end>=o.length?!0:t?n&&new RegExp(n).test(o.substring(s.end))||r&&new RegExp(r).test(o.substring(0,s.end))?!0:n===!1&&r===!1:!1}var q6={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1},Lm=({ui:e})=>e.overlayCollapsed,lI=Re({name:"ui",initialState:q6,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:yu,setInputFocus:Om,setOverlayCollapsed:Ss,setOpenOverlayWhenTyping:cI,setOverlayCollapsedUserOverwrite:uI}=lI.actions,dI=lI.reducer;var fI={styleRow:"dd-prYfH",styleSuggestion:"dd-JTmXy"};var vu=E(A()),Y6=({match:e,selected:t,styles:n})=>(0,vu.jsx)(pe,{as:"button",selected:t,className:n.styleRow,"data-testid":"style-suggestion-item",title:e.suggestion,children:(0,vu.jsx)("span",{className:n.styleSuggestion,children:e.suggestion})}),X6=({matches:e,selectedIndex:t})=>{let n=F("StyleSuggestionList",fI);return(0,vu.jsx)(Ct,{children:e.map((r,o)=>(0,vu.jsx)(Y6,{match:r,selected:t===o,styles:n},`${r.keyword}-${o}`))})},Nm=X6;var vI=E(Q());var xs=E(Q());var pI=E(Q());function mI(e,t,n){(0,pI.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var gI={root:"dd-1MBCO",actions:"dd--x4cy",closeIconContainer:"dd-1z5NR",closeIcon:"dd-8qMF-",badge:"dd-4Fpkz",formattedText:"dd-EzvTB",assistantContainer:"dd-j6o8F",formattedTextTruncated:"dd-fv169",assistantBadge:"dd-VD57E"};var Su=E(A()),hI=({title:e})=>(0,Su.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18px",height:"18px",viewBox:"0 0 24 24","aria-labelledby":"closeTitle",children:[(0,Su.jsx)("title",{id:"closeTitle",children:e}),(0,Su.jsx)("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"})]});var HS={};ut(HS,{enUS:()=>Q6,nlNL:()=>Z6});var Q6={assistant:[{type:0,value:"Assistant"}],close:[{type:0,value:"Close"}]},Z6={assistant:[{type:0,value:"Assistent"}],close:[{type:0,value:"Sluiten"}]};var Hn=E(A()),ez=["search","personal-collection-search","search-autocomplete"];function tz(e,t,n,r={}){var s;let o="";return ez.includes(t)?o=RA(AS(e,n,{stripAgentPart:!0}),(s=r.searchKeywords)!=null?s:[n]):o=AS(e,n,r),r.placeholders===!0&&(o=PA(o)),o}var nz=()=>{},rz=({selected:e,suggestion:t})=>{let n=ae(HS),r=Z("inlineSuggestions"),o=j(Os),[s,i]=(0,xs.useState)(!1),a=Z("enableSuggestionFeedback"),l=j(S=>S.input.text),c=ve(),u=F("TextSuggestion",gI),f=(0,xs.useRef)(null),d=t.source==="assistant",p=a&&!d;(0,xs.useEffect)(()=>{let S=setTimeout(()=>{c(Qb({text:t.text,suggestion:t}))},500);return()=>{clearTimeout(S)}},[t]),mI(f,"click",()=>{c(Tn({suggestion:t,text:t.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let h=()=>{c(Ds({source:t.source,text:t.text,assistantCode:t.assistantCode}))},y=(0,xs.useMemo)(()=>tz(t.text,t.source,o,{stripAgentPart:r,placeholders:!0,searchKeywords:t.searchKeywords}),[r,t.text,t.source,o,t.searchKeywords]);return t.source==="gpt"&&!r?null:(0,Hn.jsxs)("div",{className:u.root,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:[(0,Hn.jsx)(pe,{ref:f,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:nz,children:t.source==="assistant"?(0,Hn.jsxs)("div",{className:u.assistantContainer,children:[(0,Hn.jsx)(hs,{containerTagName:"div",tagName:"span",className:u.formattedTextTruncated,content:y}),(0,Hn.jsx)("span",{className:u.assistantBadge,children:n("assistant")})]}):(0,Hn.jsx)(hs,{containerTagName:"div",tagName:"span",className:u.formattedText,content:y})}),p&&s&&(0,Hn.jsx)("div",{className:u.actions,children:(0,Hn.jsx)(Am,{source:"overlay",context:l,suggestion:t})}),d&&s&&(0,Hn.jsx)("div",{className:u.closeIconContainer,children:(0,Hn.jsx)("button",{type:"button",className:u.closeIcon,onClick:h,title:n("close"),children:(0,Hn.jsx)(hI,{title:n("close")})})})]})},yI=rz;var SI=E(A()),oz=({suggestions:e,selectedIndex:t,reverse:n})=>(0,vI.useMemo)(()=>{let o=e.map((s,i)=>(0,SI.jsx)(yI,{index:i,selected:i===t,suggestion:s},`${s.text}-${s.source}`));return n?o.reverse():o},[e,t,n]),Dm=oz;var xI={root:"dd-PfvRI",paper:"dd-HYlyY"};var Fm={list:{keywordMatches:[]},fetchState:"idle"},zm=e=>e.styleSuggestions.list,Ti=ge("styleSuggestions/getAll",(n,r)=>M(null,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,s=t.getState(),{showStyleSuggestions:i}=s.settings,a=(l=s.conversation.current)==null?void 0:l.profileCode;if(!i)return Fm.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),wI=Re({name:"styleSuggestions",initialState:Fm,reducers:{commitStyleSuggestion(e,t){let{keyword:n,suggestion:r}=t.payload;e.list.keywordMatches=e.list.keywordMatches.filter(o=>o.keyword.toLowerCase()!==n.toLowerCase()||o.suggestion!==r)}},extraReducers:e=>{e.addCase(Ti.pending,t=>{t.fetchState="loading"}).addCase(Ti.rejected,t=>{t.fetchState="error"}).addCase(Ti.fulfilled,(t,n)=>{t.fetchState="done",Bo(t.list,n.payload)||(t.list=n.payload)}).addCase(Fs,t=>{t.list=Fm.list}).addCase(Ge,()=>Fm)}}),{commitStyleSuggestion:bI}=wI.actions,EI=wI.reducer;var Hm=e=>{let t=new Set;return e.filter(({keyword:n,suggestion:r})=>{let o=JSON.stringify([n.toLowerCase(),r]);return t.has(o)?!1:(t.add(o),!0)})};var ki=E(A()),sz=()=>{var S;let e=(0,Bm.useRef)(null),t=F("InlineSuggestionsOverlay",xI),n=j(Gr),r=ve(),o=j(kt),s=j(Gi),i=j(Lm),a=Z("showTextSuggestions"),l=j(Ns),c=j(Cl),u=Z("showStyleSuggestions"),f=Z("showStyleSuggestionList"),d=j(zm),p=u&&f?Hm((S=d.keywordMatches)!=null?S:[]):[],h=p.length>0,y=a&&l.length>0;return ps(()=>{setTimeout(()=>{r(Ss({collapse:!0,skipWhenInputFocus:!0}))})}),(0,Bm.useEffect)(()=>{let m=e.current;if(!m||!m.parentElement)return;m.parentElement.style.left="0px";let g=m.getBoundingClientRect();m.parentElement.style.left=`${Math.min(window.innerWidth-4-g.right,0)}px`}),i||o!==!0||s===!1||!n&&!h||!y&&!h?null:(0,ki.jsx)("div",{className:t.root,"data-variant":"inline",children:(0,ki.jsxs)("div",{ref:e,className:t.paper,children:[h&&(0,ki.jsx)(Nm,{matches:p,selectedIndex:-1}),y&&(0,ki.jsx)(Ct,{children:(0,ki.jsx)(Dm,{suggestions:l,selectedIndex:c})})]})})},CI=sz;var ws=E(Q());var TI={root:"dd-7zvcP",dialogContent:"dd-4C0lK",continueButton:"dd-YUPQW",buttonContinueWrapper:"dd-IKpYs",nicknameInput:"dd-rxhGp",titleWrapper:"dd-nw3nD",title:"dd-5iof5",closeButtonWrapper:"dd-UUAzA",closeButton:"dd-7rjP5",buttonsWrapper:"dd-5e9Xb",errorMessage:"dd--5VgX",errorLink:"dd-u461n"};var BS={};ut(BS,{enUS:()=>iz,nlNL:()=>az});var iz={title:[{type:0,value:"Enter your nickname"}],close:[{type:0,value:"Close"}],nicknameDialogTitle:[{type:0,value:"Please enter the name you'd like customers to see during chat conversations. This nickname will be used across your Deepdesk environment."}],nicknameDialogInputPlaceholder:[{type:0,value:"Enter your nickname"}],nicknameDialogContinueButton:[{type:0,value:"Continue"}],nicknameDialogError:[{type:0,value:"Nickname cannot be empty or spaces only"}],nicknameDialogEmojiError:[{type:0,value:"You cannot use emojis in this field."}],nicknameDialogSaveError:[{type:0,value:"We couldn't save your details just now. Please try again, or update it at "},{type:1,value:"account"},{type:0,value:".deepdesk.com/admin/user-settings"}],nicknameDialogSaveErrorWithoutLink:[{type:0,value:"We couldn\u2019t save your details just now. Please try again later, or update them in My Deepdesk \u2192 Settings."}]},az={title:[{type:0,value:"Voer je bijnaam in"}],close:[{type:0,value:"Sluiten"}],nicknameDialogTitle:[{type:0,value:"Voer de naam in die je wilt dat klanten zien tijdens chatgesprekken. Deze bijnaam wordt gebruikt in je Deepdesk-omgeving."}],nicknameDialogInputPlaceholder:[{type:0,value:"Voer je bijnaam in"}],nicknameDialogContinueButton:[{type:0,value:"Doorgaan"}],nicknameDialogError:[{type:0,value:"Bijnaam mag niet leeg of alleen spaties zijn"}],nicknameDialogEmojiError:[{type:0,value:"Je kunt geen emoji's gebruiken in dit veld."}],nicknameDialogSaveError:[{type:0,value:"We konden je gegevens nu niet opslaan. Probeer het opnieuw of werk het bij op "},{type:1,value:"account"},{type:0,value:".deepdesk.com/admin/user-settings"}],nicknameDialogSaveErrorWithoutLink:[{type:0,value:"We konden je gegevens nu niet opslaan. Probeer het opnieuw later, of werk ze bij in My Deepdesk \u2192 Instellingen."}]};var ht=E(A()),kI=({onClose:e,onSave:t,id:n,error:r})=>{let[o,s]=(0,ws.useState)(""),[i,a]=(0,ws.useState)(!1),[l,c]=(0,ws.useState)(!1),u=F("Nickname",TI),f=ws.default.useRef(null),d=j(m=>m.info.showNicknameDialog),p=ae(BS),h=Z("adminUrl");(0,ws.useEffect)(()=>{r&&a(!0)},[r]);let y=()=>{if(!f.current)return;o.trim()?f.current.setCustomValidity(""):f.current.setCustomValidity(p("nicknameDialogError")),f.current.reportValidity()},S=m=>{m.preventDefault();let g=o.trim(),v=m.currentTarget.querySelector("#nickname-input");if(!g){v.setCustomValidity(p("nicknameDialogError")),v.reportValidity();return}v.setCustomValidity(""),t(g)};return(0,ht.jsxs)(Ka,{isOpen:d,"datatest-id":n,onClose:e||(()=>{}),onBack:e||(()=>{}),children:[(0,ht.jsx)("div",{className:u.titleWrapper,children:(0,ht.jsx)("h1",{className:u.title,children:p("title")})}),(0,ht.jsxs)("form",{className:u.dialogContent,onSubmit:S,children:[(0,ht.jsx)("p",{children:p("nicknameDialogTitle")}),i&&r&&(0,ht.jsx)("div",{className:u.errorMessage,children:h?(()=>{let m=p("nicknameDialogSaveError",{account:h}),g=`${h}.deepdesk.com/admin/user-settings`,v=m.indexOf(g);if(v!==-1){let x=m.substring(0,v),T=m.substring(v+g.length);return(0,ht.jsxs)(ht.Fragment,{children:[x,(0,ht.jsx)("a",{href:g,target:"_blank",rel:"noopener noreferrer",className:u.errorLink,children:g}),T]})}return m})():p("nicknameDialogSaveErrorWithoutLink")}),(0,ht.jsx)("input",{required:!0,minLength:1,maxLength:20,"data-testid":"nickname-input",id:"nickname-input",className:u.nicknameInput,type:"text",placeholder:p("nicknameDialogInputPlaceholder"),value:o,onChange:m=>{c(new RegExp("\\p{Extended_Pictographic}","u").test(m.target.value)),s(m.target.value)},onBlur:y,ref:f}),l&&(0,ht.jsx)("div",{className:u.errorMessage,role:"alert",children:p("nicknameDialogEmojiError")}),(0,ht.jsxs)("div",{className:u.buttonsWrapper,children:[r?(0,ht.jsx)("div",{className:u.closeButtonWrapper,children:(0,ht.jsx)("button",{type:"button",className:u.closeButton,onClick:()=>e==null?void 0:e(),children:p("close")})}):null,(0,ht.jsx)("div",{className:u.buttonContinueWrapper,children:(0,ht.jsx)("button",{type:"submit",className:u.continueButton,disabled:!o.trim()||new RegExp("\\p{Extended_Pictographic}","u").test(o),children:p("nicknameDialogContinueButton")})})]})]})]})};var xu=E(A()),lz=({children:e})=>{let n=Z("locale").replace("-","");return(0,xu.jsx)(Nh.Provider,{value:n,children:e})},cz=({store:e,customStyles:t={},children:n})=>(0,xu.jsx)($w,{store:e,children:(0,xu.jsx)(lz,{children:(0,xu.jsx)(fl.Provider,{value:t,children:n})})}),Ro=cz;var Vm=E(De()),Za=E(Q());var RI=E(Q());function PI(e,t){let[n,r]=(0,RI.useState)(()=>{if(typeof window=="undefined")return t;try{let s=window.localStorage.getItem(e);return s?JSON.parse(s):t}catch(s){return J.error(s),t}});return[n,s=>{try{let i=s instanceof Function?s(n):s;r(i),typeof window!="undefined"&&window.localStorage.setItem(e,JSON.stringify(i))}catch(i){J.error(i)}}]}var AI=()=>/Mac/i.test(navigator.platform);var _I=E(De()),Po=E(Q());var US={};ut(US,{enUS:()=>uz,nlNL:()=>dz});var uz={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"}]}]},dz={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 II={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};var bs=E(A()),VS=(e,t,n)=>r=>(0,bs.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),fz=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r,onLogIn:o})=>{let s=ae(US),i=dn(),a=F("Login",II),l=Z("productName"),c=Z("signInViaPopup"),u=n&&!c,f=(0,Po.useCallback)(g=>{g.preventDefault(),r&&r(Number.parseInt(g.target.value,10))},[]),d=(0,Po.useCallback)(g=>{g.preventDefault(),i.send(Zi,!0)},[t]),p=(0,Po.useMemo)(()=>g=>(0,bs.jsx)("a",{onClick:x=>{x.preventDefault(),o()},href:t,className:a.anchor,target:"_blank",rel:"noreferrer",children:g},"login"),[t]),h=(0,Po.useCallback)(g=>(0,bs.jsx)("button",{type:"button",className:a.anchorButton,onClick:d,children:g},"prompt"),[d]),{min:y,hour:S,day:m}=(0,Po.useMemo)(()=>({min:VS(a,600,f),hour:VS(a,3600,f),day:VS(a,3600*12,f)}),[]);return(0,bs.jsxs)("div",{className:(0,_I.default)(e,a.root),children:[s("loginPlease",{login:u?h:p,productName:l}),r&&(0,bs.jsxs)(Po.Fragment,{children:[(0,bs.jsx)("br",{}),s("snooze",{min:y,hour:S,day:m})]})]})},Um=fz;var MI={root:"dd-DoQhb",text:"dd-Jwnev"};var wu=E(A()),pz=({title:e})=>{let t=F("SearchTrigger",MI),n=ve(),r=tt();return(0,wu.jsxs)("button",{type:"button",className:t.root,onClick:()=>{n(cr(!0)),r("open search",{via:"autocomplete-overlay"})},children:[(0,wu.jsx)(Xa,{}),(0,wu.jsx)("span",{className:t.text,children:e})]})},LI=pz;var WS={};ut(WS,{enUS:()=>mz,nlNL:()=>gz});var mz={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"}],dismiss:[{type:0,value:"Dismiss"}],dismissError:[{type:0,value:"Dismiss error"}]},gz={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"}],dismiss:[{type:0,value:"Sluiten"}],dismissError:[{type:0,value:"Foutmelding sluiten"}]};var OI={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",loginError:"dd-KCXeb",loginErrorMessage:"dd-Bv-BG",loginErrorDismiss:"dd-iSCjU"};var Me=E(A()),hz=({onLogIn:e})=>{var $;let t=F("SuggestionsOverlay",OI),n=ae(WS),r=j(Gr),o=j(Xb),s=ve(),i=(0,Za.useRef)(null),a=Z("searchTriggerKey"),l=Z("productName"),c=j(Lm),u=j(kt),f=j(Db),d=j(Gi),[p,h]=(0,Za.useState)(null),y=Z("showSearch"),S=Z("showTextSuggestions"),m=Z("adminUrl"),g=Z("isEmbedded"),v=Z("suggestionsPlacement"),[x,T]=PI("dd-snooze-until-ms",0),C=c||x>Date.now(),k=j(Ns),P=j(Cl),L=Z("showStyleSuggestions"),N=Z("showStyleSuggestionList"),B=j(zm),q=L&&N?Hm(($=B.keywordMatches)!=null?$:[]):[],X=q.length>0,I=k.filter(O=>O.source!=="gpt").length,z=()=>{C&&T(0),s(uI(!C))},W=O=>{let G=Date.now()+O*1e3;T(G),J.info(`Snooze until: ${new Date(G)}`),s(Ss({collapse:!0}))};return(0,Za.useEffect)(()=>{I===0&&h(null)},[k,I]),ps(()=>{s(Ss({collapse:!0,skipWhenInputFocus:!0}))}),u===null||d===!1?null:u===!1?(0,Me.jsxs)("div",{ref:i,className:(0,Vm.default)(t.root,{[t.isCollapsed]:C}),children:[!C&&(0,Me.jsxs)("div",{className:t.triggers,children:[(0,Me.jsx)("div",{style:{flex:1}}),(0,Me.jsx)("div",{className:t.triggersRight,children:(0,Me.jsx)(Is,{className:t.toggleButton,title:n("collapse"),onClick:z,isCollapsed:!1})})]}),(0,Me.jsx)("div",{className:t.toggleButtonWrapper,children:(0,Me.jsx)(Is,{className:t.toggleButton,title:n("open",{productName:l}),onClick:z,isCollapsed:!0})}),(0,Me.jsxs)("div",{className:t.collapsible,children:[f&&(0,Me.jsxs)("div",{className:t.loginError,children:[(0,Me.jsx)("span",{className:t.loginErrorMessage,children:f}),(0,Me.jsx)("button",{type:"button",className:t.loginErrorDismiss,onClick:()=>s(Id()),"aria-label":n("dismissError"),children:n("dismiss")})]}),(0,Me.jsx)(Um,{loginUrl:m,isEmbedded:g,onLogIn:e,onSnooze:W})]})]}):!o||!r&&!X?null:(0,Me.jsxs)("div",{ref:i,className:(0,Vm.default)(t.root,{[t.isCollapsed]:C}),children:[!C&&(0,Me.jsxs)("div",{className:t.triggers,children:[(0,Me.jsx)("div",{style:{flex:1},children:y&&(0,Me.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>h(n(AI()?"searchHintMac":"searchHintWindows",{searchTriggerKey:a.toUpperCase()})),onMouseLeave:()=>h(null),children:(0,Me.jsx)(LI,{title:n("search")})})}),(0,Me.jsxs)("div",{className:t.triggersRight,onFocus:()=>{},children:[(0,Me.jsx)("div",{className:(0,Vm.default)(!p&&t.hintsHidden,t.hints),children:p}),(0,Me.jsx)(Is,{className:t.toggleButton,title:n("collapse"),onClick:z,isCollapsed:!1})]})]}),(0,Me.jsx)("div",{className:t.toggleButtonWrapper,children:(0,Me.jsx)(Is,{className:t.toggleButton,title:n("open",{productName:l}),onClick:z,isCollapsed:!0})}),(X||I>0&&S)&&(0,Me.jsxs)("div",{className:t.collapsible,onFocus:()=>{},children:[X&&(0,Me.jsx)(Nm,{matches:q,selectedIndex:-1}),I>0&&S&&(0,Me.jsx)(Ct,{children:(0,Me.jsx)(Dm,{suggestions:k,selectedIndex:P,reverse:v==="above"})})]})]})},NI=hz;var tg=E(De());var _o=E(Q());var Ja=E(Q());function Wm(e){return e.contentEditable==="true"}function yz(e){let t=0,n=0,r=window.getSelection();if(r.rangeCount!==0){let o=r.getRangeAt(0),s=o.cloneRange();s.selectNodeContents(e),s.setEnd(o.endContainer,o.endOffset),n=s.toString().length,s.selectNodeContents(e),s.setEnd(o.startContainer,o.startOffset),t=s.toString().length}return{selectionStart:t,selectionEnd:n}}function DI(e){let{selectionStart:t,selectionEnd:n}=Wm(e)?yz(e):e;return[t,n]}function FI(e){let[,t]=(0,Ja.useState)(),n=(0,Ja.useRef)(null);return n.current=DI(e),(0,Ja.useEffect)(()=>{let r=()=>{var a;let[o,s]=(a=n.current)!=null?a:[],i=DI(e);(!i||o!==i[0]||s!==i[1])&&(n.current=i,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 zI(e,t){if(!t)return;let n=e,{value:r}=n,[o,s]=t,i=r.match(od);if(!i||i.length===0)return;let a=0;i.find(l=>{let c=r.indexOf(l,a);return o>c&&s<c+l.length?(n.selectionStart=c,n.selectionEnd=c+l.length,!0):(a=c+l.length,!1)})}var HI=E(Q()),vz=["div","span","mark","strong","b","i","u","em"];function $S(e,t,n=0){var s;let r=e[e.length-1],o=typeof r=="object"&&r!==null?(s=r.props)==null?void 0:s.tagName:void 0;if(o==="br")return e.pop(),[...e,...t,r];if(vz.includes(o)){let i=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,HI.cloneElement)(r,{children:$S(i,t,n+1)})]}return[...e,...t]}function Ri(e){return e.tagName.toLowerCase()==="textarea"}var BI={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 $I=E(De());var Xm=E(Q());var el=E(Q());function UI(e,t){let n;return[(...r)=>{window.cancelAnimationFrame(n);let o=t?t(...r):r;n=window.requestAnimationFrame(()=>{e(...o)})},()=>window.cancelAnimationFrame(n)]}function $m(e){let t=(0,el.useRef)(null),[n,r]=(0,el.useState)(!1);return(0,el.useEffect)(()=>{var u;let o=!1,s=Number.parseFloat((u=window.getComputedStyle(document.body).zoom)!=null?u:"1"),[i,a]=UI((f,d)=>{let p=t.current;if(!p)return;let h=f/s,y=d/s,S=p.getBoundingClientRect(),m=h>S.x&&h<S.x+S.width&&y>S.y&&y<S.y+S.height;m&&!o?(o=!0,r(!0)):!m&&o&&(o=!1,r(!1))},({clientX:f,clientY:d})=>[f,d]),[l,c]=UI(()=>{o=!1,r(!1)});return e.addEventListener("mousemove",i),e.addEventListener("mouseleave",l),()=>{a(),c(),e.removeEventListener("mousemove",i),e.removeEventListener("mouseleave",l)}},[t]),[t,n]}function jm(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Km(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function VI(e){return e!=null}var WI=E(De()),Gm=E(Q());var Ao={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 jS=E(A()),qm=(0,Gm.forwardRef)((o,r)=>{var s=o,{className:e,children:t}=s,n=ie(s,["className","children"]);let i=(0,Gm.useRef)(null),a=F("TabCompletion",Ao);return(0,jS.jsx)("div",_(b({ref:Km([i,r]),className:(0,WI.default)(e,a.popoverContentContainer)},n),{children:(0,jS.jsx)("div",{className:a.popoverContent,children:t})}))});var Es=E(A()),Sz=e=>t=>{let n=uS(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},xz=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let s=F("TabCompletion",Ao),i=sm(),a=(0,Xm.useMemo)(()=>Sz(e.getBoundingClientRect()),[e]),[l,c]=$m(e);return(0,Xm.useEffect)(()=>{c?i.open():i.close()},[c]),(0,Es.jsxs)("span",{children:[(0,Es.jsx)("mark",{ref:Km([l,i.triggerRef]),className:(0,$I.default)(s.matchKeyword,{[s.hover]:c}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:r}),i.opened&&(0,Es.jsx)(ja,{className:s.popover,triggerRef:i.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,Es.jsx)(qm,{style:n,children:(0,Es.jsx)("div",{className:s.hintText,children:o})})})]})},Ym=class extends Co{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=>_(b({},o),{keywordRegex:new RegExp(`\\b${jm(o.keyword)}\\b`,"i")})),this.keywordMatches=r.keywordMatches),this.usedKeywordMatches.clear(),n}match(n){let r=this.preparedKeywordMatches.map(s=>{if(this.usedKeywordMatches.has(s))return null;let i=n.match(s.keywordRegex);if(!i)return null;let a=n.charAt(i.index-1),l=n.charAt(i.index+s.keyword.length);return a==="{"&&l==="}"?null:{index:i.index,length:i[0].length,match:i[0],matchString:i[0],suggestion:s.suggestion,preparedKeywordMatch:s,valid:!0}}).filter(VI);if(r.length===0)return null;let o=r.reduce((s,i)=>i.index<s.index?i:s);return this.usedKeywordMatches.add(o.preparedKeywordMatch),o}replaceWith(n,r){return(0,Es.jsx)(xz,{inputElement:r.inputElement,suggestion:r.suggestion,inputStyle:r.inputStyle,boundaryRef:r.boundaryRef,children:n},`keyword_${r.matchString}_${r.key}`)}asTag(){return"mark"}};var jI=E(De());var KS=E(A()),wz=({inputElement:e,children:t})=>{let n=F("TabCompletion",Ao),[r,o]=$m(e);return(0,KS.jsx)("mark",{ref:r,className:(0,jI.default)(n.matchPlaceholder,{[n.hover]:o}),children:t})},Qm=class extends Co{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,KS.jsx)(wz,{inputElement:n.inputElement,children:t},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var Jm=E(De());var sn=E(Q());function KI(e,t){let n=new URL(e),r=n.searchParams.get("redirect");if(r){let o=new URL(r,n.origin);return t.forEach((s,i)=>{o.searchParams.set(i,s)}),n.searchParams.set("redirect",`${o.pathname}${o.search}${o.hash}`),n.toString()}return t.forEach((o,s)=>{n.searchParams.set(s,o)}),n.toString()}var GS=E(A()),GI=()=>(0,GS.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,GS.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 qr=E(Q());var YI=E(vS());var qI={root:"dd-ky-Bv",content:"dd-kV5e1"};function Zm(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(s){return null}}function qS(e){return e.replace("https://www.","").replace("https://","")}var tr=E(A()),bz=3,Ez=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),Cz=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=bz})=>{let s=F("LinkSearch",qI),[i,a]=(0,qr.useState)(""),l=ve(),c=j(GA("url")),u=j(xE("URL")),f=(0,qr.useMemo)(()=>u.map(Ez),[u]),[d,p]=(0,qr.useState)(f.length-1),h=Z("fallbackImage"),y=v=>{let x=v.target;a(x.value)},S=(v,x)=>{v.stopPropagation(),v.preventDefault(),window.open(x,"_blank")},m=v=>{var C;let x=d-1<0?f.length-1:d-1,T=d+1===f.length?0:d+1;v.code==="Escape"&&(a(""),t()),v.code==="ArrowUp"&&p(x),v.code==="ArrowDown"&&p(T),v.code==="Enter"&&e(((C=f[d])==null?void 0:C.text)||i)},g=(0,qr.useCallback)((0,YI.default)(v=>{l(zs({query:v,type:"URL",tags:["link-search"]}))},300),[]);return(0,qr.useEffect)(()=>{i&&g(i)},[i]),(0,qr.useEffect)(()=>()=>{l(Bd())},[]),(0,tr.jsxs)("div",{className:s.root,children:[(0,tr.jsx)(Ct,{withDivider:!0,children:(i?f:c).slice(0,o).map((v,x)=>(0,tr.jsx)(pe,{selected:d===x,onClick:()=>e(v.text),"data-testid":"linksearch-suggestion",children:(0,tr.jsxs)(be,{children:[(0,tr.jsx)(be.Image,{src:Zm(v,"small",h||void 0),title:v.title||v.text}),(0,tr.jsxs)(be.Content,{className:s.content,cropText:!0,children:[(0,tr.jsx)(be.Title,{children:v.title||qS(v.text)}),v.title&&qS(v.text)]}),(0,tr.jsx)(pe.Actions,{children:(0,tr.jsx)(pe.ActionButton,{label:r,onClick:T=>S(T,v.text)})})]})},v.text))}),(0,tr.jsx)(Zc,{value:i,onChange:y,autoFocus:!0,placeholder:n,onKeyUp:m})]})},XI=Cz;var YS={};ut(YS,{enUS:()=>Tz,nlNL:()=>kz});var Tz={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}],addToPersonalCollection:[{type:0,value:"Add to Personal Collection"}]},kz={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}],addToPersonalCollection:[{type:0,value:"Toevoegen aan Personal Collection"}]};var It=E(A()),Rz=(0,sn.forwardRef)((e,t)=>{let n=F("TabCompletion",Ao);return(0,It.jsx)("mark",{ref:t,className:(0,Jm.default)(n.matchSelection)},"selection-start")}),Pz=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let s=ae(YS),i=F("TabCompletion",Ao),a=Z("addToPersonalCollection"),l=j(ea("/admin/personal-collection/new")),c=j(v=>{var x;return(x=v.conversation.current)==null?void 0:x.profileCode}),u=j(Vn)!==null,f=(0,sn.useRef)(null),d=(0,sn.useRef)(null),[p,h]=(0,sn.useState)(null),y=ve(),S=sm(document.activeElement===r),[m]=(0,sn.useState)(()=>document.createRange());S.triggerRef.current=m,(0,sn.useEffect)(()=>()=>m.detach(),[]),(0,sn.useEffect)(()=>{let v=e.current,x=f.current;!v||!x||(m.setStart(v,0),m.setEnd(x,0))},[e.current,f.current]),ps(()=>{S.close()});let g=(0,sn.useCallback)(v=>{let x=m.toString(),T=/^http(s?):\/\//.test(v)?v:`https://${v}`,C=`[${x}](${T})`;y(Tn({text:C,suggestion:{text:C,source:"search-url",type:"url"},eventMetrics:{inputType:"mouse"},replace:"selection"}))},[]);return(0,It.jsxs)("span",{children:[(0,It.jsx)("mark",{ref:f,className:(0,Jm.default)(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":S.opened?"true":"false",children:o}),S.opened&&(0,It.jsx)(ja,{className:i.popoverRoot,triggerRef:S.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,It.jsxs)(qm,{style:n,ref:d,children:[(0,It.jsxs)("div",{className:(0,Jm.default)(i.selectionOptions,{[i.selectionOptionsIsHidden]:p!==null}),children:[(0,It.jsxs)("button",{type:"button",tabIndex:p===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>h("insertLink"),children:[(0,It.jsx)(GI,{}),(0,It.jsx)("span",{children:"\xA0"}),(0,It.jsx)("span",{children:s("insertLink")})]}),a&&l&&(0,It.jsx)("button",{type:"button",tabIndex:p===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>{let v=m.toString(),x=new URLSearchParams({text:v});u&&c&&x.set("profile",c);let T=KI(l,x);window.open(T,"_blank")},children:(0,It.jsx)("span",{children:s("addToPersonalCollection")})})]}),p==="insertLink"&&(0,It.jsx)(XI,{placeholder:s("linkInputPlaceholder"),visitUrlText:s("visitUrl"),onSelectLink:g,onDismiss:()=>{h(null),S.close()}})]})})]},"selection-end")},eg=class extends Co{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,sn.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 s=this.foundIndex===0?r:o,i=s>=this.charCount&&s<=this.charCount+n.length?{index:s-this.charCount,length:0,match:"",valid:!0}:null;i&&this.foundIndex++;let a=this.foundIndex===1;return i&&a?this.charCount+=s-this.charCount:this.charCount+=n.length,i?b({isStart:a},i):null}replaceWith(n,r){return r.isStart?(0,It.jsx)(Rz,{ref:this.startRef}):(0,It.jsx)(Pz,{inputElement:r.inputElement,startRef:this.startRef,boundaryRef:r.boundaryRef,inputStyle:r.inputStyle})}asTag(){return"mark"}};var Io=E(A()),Az=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:s,keywordMatches:i,inputElement:a,source:l})=>{let c=F("TabCompletion",BI),u=Z("insertLink"),f=Z("addToPersonalCollection"),d=Z("showMidSentenceSuggestions"),p=Z("inlineSuggestions"),h=FI(a),y=(0,_o.useRef)(null),S=j(kt);(0,_o.useEffect)(()=>{Ri(a)&&h&&zI(a,h)},[h]);let m=(0,_o.useCallback)(x=>{if(!o||!n)return x;let T=[(0,Io.jsx)("span",{className:c.resetIndent,children:"\u200B"},"u200B"),(0,Io.jsx)("span",{"data-testid":"tab-completion",className:(0,tg.default)(c.tabText,c.resetIndent),"data-source":l,children:n},"tabText")];return r&&T.push((0,Io.jsx)("span",{className:(0,tg.default)(c.hint,c.resetIndent),children:(0,Io.jsx)(td,{keyCode:"tab"},"tabHint")},"tabHint")),$S(x,T)},[o,n,r]),g=(0,_o.useMemo)(()=>{let x=[];return(u||f)&&x.push(new eg("selection")),x.push(new Qm("placeholders")),s&&x.push(new Ym("keywords")),x},[p,u,f,s]),v=(0,_o.useMemo)(()=>{let x=window.getComputedStyle(a);return{"--dd-color":x.color,"--dd-font-size":x.fontSize,"--dd-font-family":x.fontFamily,"--dd-font-variant":x.fontVariant}},[]);return!e||!S?null:(0,Io.jsxs)("div",{ref:x=>{x!=null&&x.parentElement&&(y.current=x==null?void 0:x.parentElement)},className:c.root,style:v,children:[(0,Io.jsx)(hs,{tagName:"span",containerTagName:"div",className:(0,tg.default)(c.container,c.agentText),disableLineBreaks:Ri(a),content:t||"\u200B",onAfterParse:m,matchers:g,selection:h,keywordMatches:i,inputElement:a,inputStyle:v,boundaryRef:y,inlineSuggestionsOnlyAtEnd:!d}),(0,Io.jsx)("br",{})]},"tab-completion")},Iz=e=>{var m,g,v;let{input:t,ui:n,settings:r,styleSuggestions:o,conversation:s}=e,i=qi({input:t}),a=(i==null?void 0:i.text)||"",l=(i==null?void 0:i.source)||"",c=(m=t.html)!=null?m:qa(t.text),u=t.text.slice(t.suggestionTextStart,t.selection.end),f=a.indexOf(u)===0?a.slice(u.length):"",{showTabHint:d}=n,{isSupported:p}=s,{showTabCompletion:h,visible:y,showStyleSuggestions:S}=r;return{showTabHint:d,showStyleSuggestions:S,showTabCompletion:h&&Gr(e),content:c,tabText:f,source:l,keywordMatches:(v=(g=o.list)==null?void 0:g.keywordMatches)!=null?v:[],enabled:y&&p!==!1}},QI=Ww(Iz)(Az);var rr=E(Q());var _z={token:null,interval:null},XS=ge("passwordlessToken/getTemporaryPasswordlessToken",(e,t)=>M(null,null,function*(){let{deepdeskAPI:n}=t.extra;return{token:yield n.requestPasswordlessToken()}})),QS=ge("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(XS()),setInterval(()=>r(XS()),n)}),ZI=Re({name:"passwordlessToken",initialState:_z,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(XS.fulfilled,(t,n)=>{t.token=n.payload.token}),e.addCase(QS.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:JI}=ZI.actions,e_=ZI.reducer;function Mz(e){return"buttonText"in e&&"eventName"in e}function t_(e){if(e)return Mz(e)?{label:e.buttonText,event:e.eventName,value:e.payload}:e}function Lz(e){return e==null?void 0:e.map(t=>t_(t))}function Oz(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t}var n_=Yt([ZE,_d],(e,t)=>(t?e.filter(o=>!o.externalConversationId||o.externalConversationId===t):e).map(o=>{var a;let s=t_(o.callToAction),i=Lz(o.callToActions);return _(b(b(b(b({text:o.response,title:o.name},s?{callToAction:s}:{}),i!=null&&i.length?{callToActions:i}:{}),o.message!==void 0?{message:o.message}:{}),(a=o.sources)!=null&&a.length?{sources:o.sources}:{}),{editable:o.editable,isLoading:o.isLoading,evaluationId:o.evaluationId,rule:{id:Oz(o.code),label:o.code,name:o.name,description:o.name}})}));var ng=E(Q()),JS=E(De());var ZS=E(A()),tl=()=>(0,ZS.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,ZS.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 r_={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};var Yr=E(A()),Nz=({entities:e})=>{let t=F("EntitiesWidgetList",r_),[n,r]=(0,ng.useState)(void 0),o=tt(),s=()=>{r(void 0)},i=a=>{e&&(r(e.indexOf(a)),Mr(a.text),o("entity copied",{entity:a,type:"copy"}))};return(0,ng.useEffect)(()=>{let a=setTimeout(s,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,Yr.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,Yr.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>i(a),children:[(0,Yr.jsx)("span",{className:t.entityText,children:a.text}),(0,Yr.jsxs)("span",{className:t.iconWrapper,children:[(0,Yr.jsx)("span",{className:(0,JS.default)(t.icon),children:(0,Yr.jsx)(tl,{})}),(0,Yr.jsx)("span",{className:(0,JS.default)(t.icon,n===l&&t.iconClicked),children:(0,Yr.jsx)(tl,{})})]})]},a.text))})},o_=Nz;var ex=E(A()),s_=()=>(0,ex.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,ex.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 f_=E(Q());var i_={root:"dd-ohnXe",trigger:"dd-7i-S3",button:"dd-t53Cg",nav:"dd-qZFnm",item:"dd-FZC0F"};var a_={root:"dd-nazq3",rotation:"dd-3EHTv"};var c_=E(A()),Dz=({size:e=12})=>{let t=F("LoadingSpinner",a_);return(0,c_.jsx)("span",{"data-testid":"loading-spinner",style:{width:`${e}px`,height:`${e}px`},className:t.root})},l_=Dz;var tx=E(A()),u_=()=>(0,tx.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 512 512",fill:"currentColor",children:(0,tx.jsx)("path",{d:"M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224c0-17.7-14.3-32-32-32s-32 14.3-32 32s14.3 32 32 32s32-14.3 32-32z"})});var bu=E(A()),d_=e=>(0,bu.jsxs)("svg",_(b({xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 448 512","aria-labelledby":"checkTitle"},e),{children:[(0,bu.jsx)("title",{id:"checkTitle",children:"Check"}),(0,bu.jsx)("path",{fill:"#666",d:"M438.6 105.4c12.5 12.5 12.5 32.8 0 45.3l-256 256c-12.5 12.5-32.8 12.5-45.3 0l-128-128c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0L160 338.7 393.4 105.4c12.5-12.5 32.8-12.5 45.3 0z"})]}));var nx={};ut(nx,{enUS:()=>Fz,nlNL:()=>zz});var Fz={error:[{type:0,value:"Something went wrong"}]},zz={error:[{type:0,value:"Er ging iets fout"}]};var Bn=E(A()),Hz=3e3,Bz=({assistantOptions:e})=>{let t=F("OnDemandAssistants",i_),n=ae(nx),r=(0,f_.useRef)(),o=ve(),s=Pl(Rn),i=j(pA),a=tt(),l=i.filter(d=>d.isPinned),c=i.filter(d=>!d.isPinned),u=()=>M(null,null,function*(){return e.attachments&&e.attachments.length>0?e.attachments:o(((d,p,h)=>M(null,null,function*(){let y;if(e.transcript==="in-memory-transcript"){let S=h.dynamicThunkObject.conversationQuery;if(S){let m=yield S();y=Array.isArray(m)?m:void 0}}else Array.isArray(e.transcript)&&(y=e.transcript);return Qh({transcript:y})})))}),f=d=>M(null,null,function*(){clearTimeout(r.current);let p=yield u();a("trigger on demand assistant",{assistantCode:d}),yield s.call(b(_(b({},e),{assistantCode:d}),p.length>0?{attachments:p}:{})),r.current=setTimeout(()=>s.reset(),Hz)});return i.length===0?null:(0,Bn.jsxs)("div",{className:t.root,children:[l.map(({assistant:d,assistantName:p,displayName:h})=>(0,Bn.jsx)("button",{type:"button",className:t.button,disabled:s.state==="loading",onClick:()=>f(d),children:h||p},d)),c.length>0&&(0,Bn.jsxs)(Qe,{placement:"top-end",children:[(0,Bn.jsx)(Qe.Trigger,{className:t.trigger,disabled:s.state==="loading",children:(0,Bn.jsx)(Pm,{"data-testid":"trigger"})}),(0,Bn.jsx)(Qe.Content,{className:t.nav,"data-testid":"popover",children:c.map(({assistant:d,assistantName:p,displayName:h})=>(0,Bn.jsx)(Qe.Button,{className:t.item,disabled:s.state==="loading",onClick:()=>f(d),children:h||p},d))})]}),s.state==="loading"&&(0,Bn.jsx)(l_,{}),s.state==="done"&&(0,Bn.jsx)(d_,{"data-testid":"trigger-done"}),s.state==="error"&&(0,Bn.jsx)(AP,{trigger:(0,Bn.jsx)(u_,{}),children:n("error")})]})},p_=Bz;var Pi=E(Q());var Eu={};ut(Eu,{enUS:()=>Uz,nlNL:()=>Vz});var Uz={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"}]},Vz={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 rx={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",actions:"dd-9Iqn9",ctaMessage:"dd-ge8nB",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 _t=E(A()),Wz=500,$z=100,jz=({content:e,onChange:t,onCopy:n})=>{let r=(0,Pi.useRef)(null),o=F("WidgetCue",rx);return(0,Pi.useEffect)(()=>{let s=r.current;if(!s)return;s.style.setProperty("height","0px");let i=Math.min(Math.max(s.scrollHeight,$z),Wz);s.style.setProperty("height",`${i}px`)},[e]),(0,_t.jsx)("textarea",{ref:r,className:o.editableCue,onCopy:n,onChange:t,value:e})},Kz=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o,onSourceClick:s})=>{var S;let i=F("WidgetCue",rx),a=ae(Eu),l=tt(),c=Z("hasKeyboardInput"),[u,f]=(0,Pi.useState)(e.text),d=m=>{let g=m?_(b({},e),{callToAction:m}):e;t&&t(u,g),n(e)},p=(m,g)=>{r&&r(m,e),g&&Vo(g,i.fadeup)},h=m=>{o&&o(m,e)},y=m=>{m.preventDefault(),m.stopPropagation(),n(e)};return(0,Pi.useEffect)(()=>{l("Assistant response displayed",{evaluationId:e.evaluationId,assistantCode:e.rule.label,assistantOutput:e.text})},[]),(0,_t.jsxs)(pe,{"data-testid":"cue",children:[(0,_t.jsx)(be,{children:(0,_t.jsxs)(be.Content,{children:[e.title&&(0,_t.jsx)(be.Title,{className:i.title,"data-testid":"widget-cue-title",children:e.rule.label.startsWith("__")?a(e.rule.label):e.title}),e.message&&(0,_t.jsx)("p",{className:i.ctaMessage,children:e.message}),e.editable?(0,_t.jsx)(jz,{content:u,onCopy:()=>{let m=document.getSelection();m&&p(m.toString())},onChange:m=>{var g;return f((g=m.target.value)!=null?g:"")}}):(0,_t.jsx)(gi,{content:e.text,sources:e.sources,onSourceClick:m=>s==null?void 0:s(m,e),useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:p,onUse:c?h:void 0})]})}),(0,_t.jsxs)(pe.ButtonsContainer,{children:[(0,_t.jsxs)("div",{className:i.actions,children:[(0,_t.jsx)(pe.Button,{onClick:m=>{var g;return p((g=sf(u,"reply")[0])!=null?g:u,m.target)},variant:"primary",children:a("copyCue")}),e.callToAction&&(0,_t.jsx)(pe.Button,{onClick:()=>d(),variant:"primary",children:e.callToAction.label}),(S=e.callToActions)==null?void 0:S.map((m,g)=>(0,_t.jsx)(pe.Button,{onClick:()=>d(m),variant:"primary",children:m.label},`${m.event}-${m.label}-${g}`)),(0,_t.jsx)(pe.Button,{onClick:y,variant:"secondary",children:a("removeCue")})]}),(0,_t.jsx)(pf,{evaluationId:e.evaluationId,assistantCode:e.rule.label,assistantOutput:e.text,feedbackType:"assistant"})]})]})},m_=Kz;var nl=E(A()),Gz=({cues:e})=>{let t=ve(),n=dn(),r=ae(Eu),o=tt(),s=u=>{t(lf({code:u.rule.label})),o("Assistant response closed",{evaluationId:u.evaluationId,assistantCode:u.rule.label,assistantOutput:u.text})},i=(u,f)=>{Mr(u),o("Assistant response copied",{evaluationId:f.evaluationId,assistantCode:f.rule.label,assistantOutput:f.text,copiedText:u})},a=(u,f)=>{var d;f.callToAction&&(t(af(f)),o("Assistant call to action",{evaluationId:f.evaluationId,assistantCode:f.rule.label,assistantOutput:f.text,eventName:f.callToAction.event,value:(d=f.callToAction.value)!=null?d:u}))},l=(u,f)=>{var d;n.send(no,{text:u,suggestion:{source:"assistant",assistantCode:(d=f.rule)==null?void 0:d.label,sourceText:u}}),o("Assistant response used",{evaluationId:f.evaluationId,assistantCode:f.rule.label,assistantOutput:f.text,usedText:u})},c=(u,f)=>{o("Assistant source clicked",{evaluationId:f.evaluationId,assistantCode:f.rule.label,source:u})};return(0,nl.jsx)(nl.Fragment,{children:e.map(u=>u.isLoading?(0,nl.jsx)(am,{title:u.rule.label.startsWith("__")?r(u.rule.label):u.title},u.rule.id):(0,nl.jsx)(m_,{cue:u,onCallToAction:a,onRemove:s,onCopy:i,onUse:l,onSourceClick:c},u.evaluationId))})},g_=Gz;var rg=E(Q());var h_={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var wn=E(A());function qz(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var y_=({data:e,schema:t})=>{let n=F("WidgetCustomData",h_),r=o=>{Mr(o)};return(0,rg.useEffect)(()=>{J.info("Custom data",e,t)},[e]),(0,wn.jsx)("dl",{className:n.root,children:t.map(o=>{let s=qz(e,o.path);return(0,wn.jsxs)(rg.Fragment,{children:[(0,wn.jsx)("dt",{className:n.label,children:o.label}),(0,wn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&s?(0,wn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!s?(0,wn.jsx)("span",{className:n.isFalse,children:o.falseValue}):o.type==="array"&&Array.isArray(s)&&s.length>0?(0,wn.jsxs)("button",{type:"button",onClick:()=>r(s.join(", ")),className:n.copyButton,children:[(0,wn.jsx)("span",{className:n.copyButtonText,children:s.join(", ")}),(0,wn.jsx)(tl,{})]}):typeof s=="string"||typeof s=="number"?(0,wn.jsxs)("button",{type:"button",onClick:()=>r(`${s}`),className:n.copyButton,children:[(0,wn.jsx)("span",{className:n.copyButtonText,children:s}),(0,wn.jsx)(tl,{})]}):"-"})]},o.label)})})};var S_=E(Q());var Yz=/(https?:\/\/[^\s]+)/,v_=e=>e.split(" ").find(t=>Yz.test(t));var nr=E(A()),Xz=({suggestion:e,lines:t,onUse:n})=>{var f;let r=e.text||e.url||e.message,o=v_(r),s=ae(fu),i=Z("showImages"),a=Z("fallbackImage"),l=Z("hasKeyboardInput"),c=d=>{d.preventDefault(),d.stopPropagation(),l&&n(r)},u=(0,S_.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,nr.jsxs)(pe,{onClick:l?c:void 0,"data-testid":"edit-suggestion",children:[(0,nr.jsxs)(be,{children:[i&&e.image&&(0,nr.jsx)(be.Image,{src:Zm(e,"small",a||void 0),title:e.title}),(0,nr.jsxs)(be.Content,{children:[e.title&&(0,nr.jsx)(be.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((f=e.searchKeywords)==null?void 0:f.length)>0&&(0,nr.jsx)(pe.Labels,{labels:e.searchKeywords}),(0,nr.jsx)(be.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,nr.jsxs)(pe.Actions,{children:[o&&(0,nr.jsx)(pe.ActionButton,{onClick:u,label:s("visitUrl")}),l&&(0,nr.jsx)(pe.ActionButton,{primary:!0,onClick:c,label:s("useSuggestion")})]})]})},x_=Xz;var Cu=E(A()),Qz=({lines:e,suggestions:t})=>{let n=dn(),r=(o,s)=>{n.send(no,{text:o,suggestion:_(b({},s),{source:s.source,sourceText:s.text})})};return(0,Cu.jsx)(Cu.Fragment,{children:t.map(o=>(0,Cu.jsx)(x_,{suggestion:o,lines:e,onUse:s=>r(s,o)},o.text||o.url||o.message))})},w_=Qz;var Tu={};ut(Tu,{enUS:()=>Zz,nlNL:()=>Jz});var Zz={waiting:[{type:0,value:"Loading\u2026"}],waitingForConversation:[{type:0,value:"Waiting for conversation\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"}],close:[{type:0,value:"Close"}]},Jz={waiting:[{type:0,value:"Laden\u2026"}],waitingForConversation:[{type:0,value:"Wachten op gesprek\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"}],close:[{type:0,value:"Sluiten"}]};var Ai={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",footer:"dd-tvofr",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",footerShortcut:"dd-dH7XJ",link:"dd-DRo0x",interactiveAssistantTabs:"dd-eSP1-",interactiveAssistantTab:"dd-CwcHD",interactiveAssistantTabActive:"dd-GzRs-"};var le=E(A()),b_=(e,t)=>{let n=j(kt);(0,rr.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},e9=({onLogIn:e})=>{let t=F("Widget",Ai),n=Z("isEmbedded"),r=Z("adminUrl");return(0,le.jsx)("div",{className:t.loginText,children:(0,le.jsx)("div",{children:(0,le.jsx)(Um,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},ox=({text:e})=>{let t=F("Widget",Ai);return(0,le.jsx)("div",{className:t.stateText,children:(0,le.jsx)("div",{children:(0,le.jsx)("p",{children:e})})},"notification")},t9=()=>{let e=ae(Tu),t=ve(),n=F("Widget",Ai),r=Z("showSearch"),o=Z("isEmbedded"),s=j(ea("/admin/")),i=dn(),a=Z("productName"),l=tt();return b_(()=>{if(o)return t(QS()),()=>{t(JI())}},[t,o]),!r&&!s?null:(0,le.jsxs)("div",{className:n.shortcutList,children:[r&&(0,le.jsx)(pe.Button,{"data-testid":"shortcut-search","aria-label":e("linkSearch"),className:n.shortcut,icon:(0,le.jsx)(Xa,{}),onClick:()=>{i.send("ShowCommandPalette",{isOpen:!0}),l("open search",{via:"widget-shortcut"})},children:e("linkSearch")}),s&&(0,le.jsx)(pe.Button,{as:"a",target:"_blank",icon:(0,le.jsx)(s_,{}),href:s,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:a}),className:n.shortcut,rel:"noreferrer",onClick:()=>{l("open my deepdesk",{via:"widget-shortcut"})},children:e("linkStudioLogin",{productName:a})})]})},n9=({title:e,content:t})=>{let n=ae(Tu),[r,o]=(0,rr.useState)(!0);return r?(0,le.jsx)(Pr,{"data-testid":"custom-data-banner",type:"custom-data-banner",title:e,children:(0,le.jsx)(Ct,{withDivider:!0,children:(0,le.jsxs)(pe,{children:[(0,le.jsx)(be,{children:(0,le.jsx)(be.Content,{children:(0,le.jsx)(gi,{content:t})})}),(0,le.jsx)(pe.ButtonsContainer,{children:(0,le.jsx)(pe.Button,{onClick:()=>o(!1),children:n("close")})})]})})}):null},r9=()=>{let e=ve(),t=j(tu),n=j(gA),r=j(n_),o=j(cE),s=j(Rm),i=j(Im),a=j(er),l=j(Vn);return(0,rr.useEffect)(()=>{o&&!n&&J.warn("Custom data provided, but no schema.")},[o,n]),b_(()=>{t.forEach(({type:c})=>{c==="entities"?e(Er()):sd.includes(c)||e(Cr(c))})},[e,l,a]),(0,rr.useEffect)(()=>{r.length>0&&!t.some(c=>c.type==="cues")&&J.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,le.jsx)(rr.Fragment,{children:t.map(({type:c,title:u,amount:f,lines:d,schema:p,property:h})=>{var y,S;switch(c){case"entities":return s&&s.length>0&&(0,le.jsx)(Pr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(o_,{entities:s})},c);case"cues":return r&&r.length>0&&(0,le.jsx)(Pr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(Ct,{withDivider:!0,children:(0,le.jsx)(g_,{cues:r})})},c);case"custom-data-banner":return o&&h&&o[h]&&(0,le.jsx)(n9,{title:u,content:String(o[h])},c);case"custom-data":return o&&p&&(0,le.jsx)(Pr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(Ct,{withDivider:!0,children:(0,le.jsx)(y_,{data:o,schema:p})})},c);default:return((S=(y=i[c])==null?void 0:y.suggestions)==null?void 0:S.length)>0&&(0,le.jsx)(Pr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(Ct,{withDivider:!0,children:(0,le.jsx)(w_,{lines:d,contentType:c,suggestions:i[c].suggestions.slice(0,f)||[]})})},c)}})})},sx=({children:e})=>{let t=F("Widget",Ai);return(0,le.jsx)("div",{className:t.footer,children:e})},ix=({children:e})=>{let t=F("Widget",Ai);return(0,le.jsx)("div",{className:t.root,"data-testid":"widget",children:e})},o9=({onLogIn:e,knowledgeAssistOptions:t={},assistantOptions:n={transcript:"in-memory-transcript"},openAdminFeedback:r})=>{var x;let o=ae(Tu),s=F("Widget",Ai),i=ve(),a=j(Gi),l=j(kt),c=j(_d),u=j(er),f=j(mA("knowledge-assist")),d=j(hA),p=j(tC),h=j(eC),y=(x=d.find(T=>T.code===p))!=null?x:d[0],[S,m]=(0,rr.useState)(t.initialQuestion);(0,rr.useEffect)(()=>{m(t.initialQuestion)},[c,t.initialQuestion]),(0,rr.useEffect)(()=>{if(!c)return;let T=El(c);T&&i(Jh(T))},[i,c]),(0,rr.useEffect)(()=>{if(d.length===0)return;let T=d.some(C=>C.code===p);(!p||!T)&&i(Zh(d[0].code))},[d,p,i]);let g=!!f&&d.length>0&&!!y,v=(y==null?void 0:y.displayName)||(y==null?void 0:y.name)||(f==null?void 0:f.title)||"Knowledge Assistant";return a===!1?(0,le.jsx)(ox,{text:o("notSupported")}):l===!1?(0,le.jsx)(e9,{onLogIn:e}):l===null?(0,le.jsx)(ox,{text:o("waiting")}):!c||!u?(0,le.jsx)(ox,{text:o("waitingForConversation")}):(0,le.jsx)(yC,{handler:r,children:(0,le.jsx)(ix,{children:(0,le.jsxs)(um,{initialQuestion:S,onInitialQuestionConsumed:()=>m(void 0),assistantCode:y==null?void 0:y.code,threadId:h,onThreadIdChange:T=>{y!=null&&y.code&&T!=null&&i(ey({assistantCode:y.code,threadId:T}))},evaluateKnowledgeAssistFn:$l,children:[(0,le.jsxs)(Vi,{children:[(0,le.jsx)(t9,{}),(0,le.jsx)(r9,{}),g&&(0,le.jsx)(fm,{title:v,emptyState:t.emptyState})]}),(0,le.jsxs)(sx,{children:[g&&d.length>1&&(0,le.jsx)("div",{className:s.interactiveAssistantTabs,"data-testid":"widget-interactive-assistant-tabs",children:d.map(T=>{let C=T.code===(y==null?void 0:y.code);return(0,le.jsx)("button",{type:"button","aria-pressed":C,className:C?s.interactiveAssistantTabActive:s.interactiveAssistantTab,onClick:()=>i(Zh(T.code)),children:T.displayName||T.name},T.code)})}),g&&(0,le.jsx)(dm,{}),(0,le.jsx)(p_,{assistantOptions:n})]})]},y==null?void 0:y.code)})})},E_=o9;function rl(e){let t=new Range;return t.selectNodeContents(e),t}function C_(e,t,n){try{return Cs(e,t,n),!0}catch(r){return!1}}function og(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function sg(e){return"tagName"in e&&e.tagName==="BR"}var ku=/[\u200B-\u200D\uFEFF]/g;function Cs(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,s=!1;function i(l,c){let u=-1,f=/[\u200B-\u200D\uFEFF]/;if(!f.test(l))return c;for(let d=0;d<=l.length;d++)if(f.test(l[d])||u++,u===c)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let c=l.textContent,u=c.replace(ku,""),f=o+u.length,d=t>=o&&t<=f,p=n>=o&&n<=f;if(d){let h=i(c,t-o);h===0&&!p?r.setStartBefore(l):r.setStart(l,h)}p&&(r.setEnd(l,i(c,n-o)),s=!0),o=f;break}case Node.ELEMENT_NODE:{if(sg(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),s=!0;return}for(let u=0;u<l.childNodes.length&&(a(l.childNodes[u]),!s);u++);let c=l.lastChild;og(l)&&c&&!og(c)&&!sg(c)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function Ru(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:s,collapsed:i}=t,a,l,c=0;function u(f){let d=f===e,p=f===n,h=f===o;switch(f.nodeType){case Node.TEXT_NODE:{let y=f.textContent;p&&(a=c+y.substring(0,r).replace(ku,"").length),h&&(l=c+y.substring(0,s).replace(ku,"").length),c+=y.replace(ku,"").length;break}case Node.ELEMENT_NODE:{if(sg(f)&&f.nextSibling){c++;break}!d&&og(f)&&f.previousSibling&&c++;for(let y=0;y<f.childNodes.length;y++){let S=p&&y===r,m=h&&y===s;if(S&&(a=c),m&&(l=c),l!==void 0||((!S||!i)&&u(f.childNodes[y]),h&&y===s-1&&(l=c),l!==void 0))break}h&&(l=c);break}default:break}}if(u(e),l===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:l,end:l}}function Pu(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:s,collapsed:i}=t,a=0,l="";function c(u){let f=u===e,d=u===n,p=u===o;switch(d&&(a=1),u.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let h=d?r:0,y=p?s:void 0;l+=u.textContent.replace(ku,"").substring(h,y);break}case Node.ELEMENT_NODE:{if(!i&&a===1&&sg(u)&&u.nextSibling){l+=`
82
82
  `;break}!f&&!i&&a===1&&og(u)&&u.previousSibling&&(l+=`
83
- `);let h=d?r:0,y=p?Math.min(s,u.childNodes.length):u.childNodes.length;for(let S=h;S<y&&(c(u.childNodes[S]),a!==2);S++);break}default:break}p&&(a=2)}return c(e),l}var T_=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(T_||{}),Mo=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedSuggestionTextStart=0;this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedSuggestionTextStart=this.getSuggestionTextStart(),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.getSuggestionTextStart(),s=this.cachedCaretPosition===null;if(!this.isActive)return;t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit");let i=t!==this.cachedText,a=n!==null&&n!==this.cachedHTML,l=o!==this.cachedSuggestionTextStart;if((i||a||l)&&(i?(this.cachedText=t,this.cachedHTML=n):a&&(this.cachedHTML=n),this.cachedSuggestionTextStart=o,s=!0,this.emit("change",{plainText:t,rawHTML:n,suggestionTextStart:o})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,s=!0,this.emit("selection",r)),!s)return;let c=this.getCaretPosition();Bo(c,this.cachedCaretPosition)||(this.cachedCaretPosition=c,this.emit("caretposition",c))}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(T_).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()})}getSuggestionTextStart(){return 0}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 k_(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Ii=class extends Mo{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Pu(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){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=r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let s=this.element.ownerDocument.createRange();return s.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),s.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!k_(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!k_(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return Ru(this.element,n);let r=this.lastKnownSelection;if(r&&C_(this.element,r.start,r.end))return r;let o=rl(this.element);return o.collapse(!1),Ru(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Pu(this.element,Cs(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[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 s9=["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 R_(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,s=window.getComputedStyle(e),i=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",s9.forEach(u=>{o[u]=s[u]}),n?e.scrollHeight>Number.parseInt(s.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),i.appendChild(r);let l=e.getBoundingClientRect(),c={top:l.top-e.scrollTop+a.offsetTop+Number.parseInt(s.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+Number.parseInt(s.borderLeftWidth)};return i.removeChild(r),c}var _i=class extends Mo{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 R_(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 s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),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 P_(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let s=document.createElement("iframe"),i=new URL(t);return Object.entries(n).forEach(([a,l])=>{i.searchParams.append(a,l)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=r,s.title=`iframe-${e}`,s.src=i.toString(),window.document.body.appendChild(s),s}function i9(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var ax=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()}},lx=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=P_(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()}},cx=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.externalId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setExternalId(t){this.externalId!==t&&(this.cleanup(),J.info("Set externalId",t),this.externalId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new lx(t,this.deepdeskUrl,{debug:!0}):new ax(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=i9(o.data);typeof s!="object"||s.type!=="event"||s.channel!==t||(J.info("Received broadcast event",this.externalId,o),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(r),n}send(t,n,r){var i,a;J.info("Broadcast event",{externalId:this.externalId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(i=this.eventMap)[t])==null||a.call(i,n));let s=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(_(b({},o),{channel:this.externalId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),this.channel=void 0,t&&((r=this.defaultChannel)==null||r.close(),this.defaultChannel=void 0)}},A_=cx;function a9(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function He(e){return Array.isArray(e)?e.map(He):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>_(b({},t),{[a9(n)]:He(e[n])}),{}):e}function l9(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Mt(e){return Array.isArray(e)?e.map(Mt):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>_(b({},t),{[l9(n)]:Mt(e[n])}),{}):e}var ol=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var Au=e=>new Promise(t=>{setTimeout(t,e)});var Tr=class extends ol{constructor(){super(...arguments);this.name="ClientError"}},ig=class extends ol{constructor(){super(...arguments);this.name="ServerError"}},ux=new Map;function I_(e){return M(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t!=null&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(J.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var Mi=class{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.refreshingToken=null;this.lastFailedRefreshAt=null;this.failedRefreshCooldown=1e4;var r;this.fetch=(r=n.fetch)!=null?r:window.fetch.bind(window)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let s={isAborted:!1,reject:o},i=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",C=n,{useCache:c=!1,abortLatest:u=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:h=k=>k instanceof TypeError,retryOnResponse:y=k=>k.status>=500,version:S=null}=C,m=ie(C,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(c){if(!l)throw new Error(`Can't use 'useCache' for ${n.method}`);if(ux.has(i)){r(ux.get(i));return}}let g=_(b({credentials:"include"},m),{headers:b({Accept:"application/json","Content-Type":"application/json"},m.headers)});!l&&this.csrfToken&&(g.headers=_(b({},g.headers),{"X-CSRFToken":this.csrfToken})),typeof S=="string"&&(g.headers=_(b({},g.headers),{"X-Deepdesk-API-Version":S}));let v=f,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&u&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let T=()=>M(this,null,function*(){return v--,a(i,g).then(k=>M(this,null,function*(){return y(k)&&!s.isAborted&&v>0?(yield Au(d),T()):k.status===401&&p===!0&&x===!1?(x=!0,yield this.refreshToken(),T()):k})).catch(k=>M(this,null,function*(){if(h(k)&&!s.isAborted&&v>0)return yield Au(d),T();throw k}))});T().then(k=>M(this,null,function*(){let P=yield I_(k);if(delete this.latestRequestByUrl[i],k.status>=500){o(new ig("Server Error",P));return}if(k.status===401){o(new Tr("Unauthorized",P));return}if(k.status===403){o(new Tr("Forbidden",P));return}if(k.status===404){o(new Tr("Not Found",P));return}if(k.status>=400){o(new Tr("Bad Request",P));return}c&&ux.set(i,P),r(P)})).catch(k=>{o(k)})})}validateToken(){return M(this,null,function*(){let t,n,r;try{({has_valid_access_token:t,is_logged_in:n,has_valid_refresh_token:r}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1}))}catch(o){return!1}if(!t){if(!r)return!1;try{yield this.refreshToken();let{is_logged_in:o}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1});return o}catch(o){return!1}}return n})}refreshToken(){let t=Date.now();return this.lastFailedRefreshAt&&t-this.lastFailedRefreshAt<this.failedRefreshCooldown?Promise.reject(new Tr("Unauthorized","Failed to refresh token")):this.refreshingToken?this.refreshingToken:(this.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).catch(n=>{throw(n==null?void 0:n.message)==="Unauthorized"&&(this.lastFailedRefreshAt=Date.now()),n}).finally(()=>{this.refreshingToken=null}),this.refreshingToken)}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,b({method:"POST",body:JSON.stringify(n)},r))}postWithStatus(t,n,r){return this.requestWithStatus(t,b({method:"POST",body:JSON.stringify(n)},r))}requestWithStatus(t,n={}){return new Promise((r,o)=>{let s={isAborted:!1,reject:o},i=`${this.baseUrl}${t}`,a=this.fetch,T=n,{useCache:l=!1,abortLatest:c=!1,attempts:u=1,retryDelay:f=500,refreshTokenOn401:d=!0,retryOnError:p=C=>C instanceof TypeError,retryOnResponse:h=C=>C.status>=500,version:y=null}=T,S=ie(T,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]),m=_(b({credentials:"include"},S),{headers:b({Accept:"application/json","Content-Type":"application/json"},S.headers)});this.csrfToken&&(m.headers=_(b({},m.headers),{"X-CSRFToken":this.csrfToken})),typeof y=="string"&&(m.headers=_(b({},m.headers),{"X-Deepdesk-API-Version":y}));let g=u,v=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let x=()=>M(this,null,function*(){return g--,a(i,m).then(C=>M(this,null,function*(){return h(C)&&!s.isAborted&&g>0?(yield Au(f),x()):C.status===401&&d===!0&&v===!1?(v=!0,yield this.refreshToken(),x()):C})).catch(C=>M(this,null,function*(){if(p(C)&&!s.isAborted&&g>0)return yield Au(f),x();throw C}))});x().then(C=>M(this,null,function*(){let k=yield I_(C);if(delete this.latestRequestByUrl[i],C.status>=500){o(new ig("Server Error",k));return}if(C.status===401){o(new Tr("Unauthorized",k));return}if(C.status===403){o(new Tr("Forbidden",k));return}if(C.status===404){o(new Tr("Not Found",k));return}if(C.status>=400){o(new Tr("Bad Request",k));return}r({status:C.status,data:k})})).catch(C=>{delete this.latestRequestByUrl[i],o(C)})})}patch(t,n,r){return this.request(t,b({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,b({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,b({method:"DELETE"},n))}};var __;(t=>{let e;(a=>(a.SUCCESS="success",a.FAILURE="failure",a.CONDITIONS_NOT_MET="conditions_not_met",a.MAX_RECURSION_LEVEL="max_recursion_level",a.NO_ACCESS_TO_ASSISTANT="no_access_to_assistant"))(e=t.EvaluationStatus||(t.EvaluationStatus={}))})(__||(__={}));function ag(e){return _(b({},He(e)),{metadata:e.metadata})}var Li=class Li{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new Mi(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,s)=>M(this,null,function*(){let i=yield r(o,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return M(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(Li.exchangeTokenPromise||(Li.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),Li.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return M(this,null,function*(){var r;yield this.preflight(),J.info(`Creating conversation for session ${t.externalId} and agent ${t.agentId}`);let n=yield this.client.post("/api/v2/conversations",_(b({chat_start_time:new Date().toISOString()},Mt(t)),{metadata:(r=t.metadata)!=null?r:{}}));return ag(n)})}upsertConversation(t){return M(this,null,function*(){var u;yield this.preflight(),J.info(`Upserting conversation for session ${t.externalId} and agent ${t.agentId}`);let{status:n,data:r}=yield this.client.postWithStatus("/api/v2/conversations",_(b({chat_start_time:new Date().toISOString()},Mt(t)),{metadata:(u=t.metadata)!=null?u:{}}),{version:"v2"}),o=ag(r);if(n===201)return o;let{agentId:s,agentName:i,agentEmail:a,agentNickname:l,metadata:c}=t;return this.updateConversation(o.id,{agentId:s,agentEmail:a,agentName:i,agentNickname:l,metadata:c})})}getMe(){return M(this,null,function*(){yield this.preflight();let t=yield this.client.get("/apis/admin/session/me/");return He(t)})}postIdentity(t){return M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",Mt(t))})}patchMe(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",Mt(t));return He(n)})}getProfile(t){return M(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return He(n)})}getKnowledgeAssistant(t){return M(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return He(n)})}getContentTypes(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return He(t)})}getAccount(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return He(t)})}getPlatformConfig(t){return M(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return He(r)})}checkUserExists(t){return M(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationByExternalId(r){return M(this,arguments,function*(t,n={}){yield this.preflight(),J.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/v2/conversations/by_external_id/${t}`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return J.info(`Successfully retrieved conversation ${i.id} for session ${t}`),ag(i)})}isConversationSupported(r){return M(this,arguments,function*(t,n={}){J.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${t}/has_active_profile`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(t,n){return M(this,null,function*(){var s;yield this.preflight();let r=Mt(n);n.metadata&&(r.metadata=(s=n.metadata)!=null?s:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return ag(o)})}postMessages(t,n){return M(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>_(b({},Mt(r)),{metadata:r.metadata})))})}sendEvent(t,n){return M(this,null,function*(){yield this.preflight();let a=n,{data:r}=a,o=ie(a,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((l,[c,u])=>_(b({},l),{[c]:u}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((l,c)=>(o[c]&&(l[c]=o[c]),l),{});return this.client.post("/api/v2/events",Mt(_(b(b({},s),i),{data:r,name:t})),{version:"v2"})})}getEntities(t){return M(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:t.filter(r=>r.text)})})}getTemporaryExchangeToken(){return M(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(t){return M(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw J.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Mt(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return M(this,arguments,function*(t,n={},r){if(yield this.preflight(),r==="sticky-messages")throw new Error("Use getPinnedMessages instead");return(yield this.client.post(`/api/v2/conversations/${t}/recommend/${r}`,Mt(n),{abortLatest:!0})).map(i=>_(b({},He(i)),{text:i.text||i.url||i.message,source:r,type:r})).filter((i,a,l)=>a===l.findIndex(c=>c.text===i.text))})}isLoggedIn(){return M(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return M(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${t}/autocomplete`,Mt(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,s,i)=>s===i.findIndex(a=>a.text===o.text))})}syncPersonalCollection(t){return M(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/personal-collection/sync`,{},{version:"v2"})})}getPinnedMessages(t){return M(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return He(n).map(r=>_(b({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return M(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",Mt(t),{abortLatest:!0,version:"v2"});return He(n)})}search(t){return M(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,Mt(t));return He(n)})}loginWithPassword(t,n){return M(this,null,function*(){yield this.preflight();let r=yield this.client.post("/apis/admin/session/login/",{username:t,password:n},{refreshTokenOn401:!1});return He(r)})}logout(){return M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/logout/",{},{refreshTokenOn401:!1})})}requestLoginByEmail(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return He(n)})}requestPasswordlessToken(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return He(t.token)})}getCsrfToken(){return M(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return M(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return He(n)})}evaluateAssistant(t,n){return M(this,null,function*(){var l,c,u;yield this.preflight();let r=new URLSearchParams;n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let o=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=f=>Mt(f),i=(l=n==null?void 0:n.transcript)==null?void 0:l.map(f=>{var d;return b({source:f.source,text:f.text},(d=f.attachments)!=null&&d.length?{attachments:f.attachments.map(s)}:{})}),a=yield this.client.post(o,b({input:(c=n==null?void 0:n.input)!=null?c:{},conversation:i},(u=n==null?void 0:n.attachments)!=null&&u.length?{attachments:n.attachments.map(s)}:{}));return He(a)})}interactWithAssistant(t){return M(this,null,function*(){yield this.preflight();let n=new URLSearchParams;t.sessionId&&n.append("session_id",t.sessionId),t.externalConversationId&&n.append("external_conversation_id",t.externalConversationId);let r=`/api/v2/assistants/${t.assistantCode}/interact?${n.toString()}`,o=yield this.client.post(r,{message:t.message});return He(o)})}resetAssistantThread(t){return M(this,null,function*(){yield this.preflight();let n=encodeURIComponent(t.assistantCode),r=encodeURIComponent(t.sessionId);yield this.client.delete(`/api/v2/assistants/${n}/sessions/${r}/thread`)})}createAssistantThread(t){return M(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return He(r)})}postMessageToAssistantThread(t){return M(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:r,message:o}=t,s=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return He(s)})}translateMessages(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",Mt(t));return He(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(Rw);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&J.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};Li.exchangeTokenPromise=null;var Lo=Li;var lg=class{constructor(t){this.options=t;this.socket=null;this.maxReconnectAttempts=5;this.reconnectInterval=25e3;this.cleanupCallbacks=[];var n,r;this.socket,this.eventListeners=new Map,this.url=t.url,this.maxReconnectAttempts=(n=t.maxReconnectAttempts)!=null?n:this.maxReconnectAttempts,this.reconnectInterval=(r=t.reconnectInterval)!=null?r:this.reconnectInterval,this.shouldReconnect=t.shouldReconnect}connect(){let t=()=>this.cleanup();window.addEventListener("beforeunload",t),this.cleanupCallbacks.push(()=>window.removeEventListener("beforeunload",t)),this.reconnect()}setupListeners(){this.socket&&(this.socket.onmessage=t=>{var n;try{let r=He(JSON.parse(t.data));r.event&&this.eventListeners.has(r.event)&&((n=this.eventListeners.get(r.event))==null||n.forEach(o=>o(r.data)))}catch(r){console.error("Error parsing WebSocket message:",r)}},this.socket.onclose=t=>{console.log("WebSocket connection closed:",t),setTimeout(()=>{this.reconnect()},this.reconnectInterval)},this.socket.onerror=t=>{console.error("WebSocket error:",t)})}reconnect(){var t,n;if(this.maxReconnectAttempts<=0){console.error("Max reconnect attempts reached, closing WebSocket connection."),(t=this.socket)==null||t.close();return}if(!this.shouldReconnect()){console.error("Should not reconnect, closing WebSocket connection."),(n=this.socket)==null||n.close();return}this.socket&&(this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close()),this.socket=new WebSocket(this.url),this.setupListeners(),this.maxReconnectAttempts--}send(t,n){if(!this.socket){console.error("WebSocket connection is not open.");return}this.socket.send(JSON.stringify({event:t,data:n}))}on(t,n){this.eventListeners.has(t)||this.eventListeners.set(t,[]);let r=this.eventListeners.get(t);r&&!r.includes(n)&&r.push(n)}close(){var t;(t=this.socket)==null||t.close()}cleanup(){this.close(),this.cleanupCallbacks.forEach(t=>t()),this.cleanupCallbacks=[]}};var M_={startTime:null,stopTime:null},L_=e=>e.handlingTime,O_=Re({name:"handlingTime",initialState:M_,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(Ge,()=>M_)}}),{handlingTimeStart:N_,handlingTimeStop:cg,handlingTimeReset:D_}=O_.actions,F_=O_.reducer;var z_=(e={})=>{let t=b({onAuthError:Ki(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var H_=(e={})=>{let t,n=!0,r=b({getStyleSuggestions:Ti,debounce:500},e);return o=>s=>i=>{var p;let a=o.getState().input.text,l=s(i),c=o.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:u}=c.settings;if(!((p=c.conversation.current)==null?void 0:p.id)||!u)return l;let{text:d}=c.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function c9(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end&&e.suggestionTextStart===t.suggestionTextStart}var B_=(e={})=>{let t=b({getTextSuggestions:Cr,getAutocompleteSuggestions:gu,debounce:200,check:Gr},e),n;return r=>o=>s=>{var y;let{input:i}=r.getState(),a=o(s),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:u}=l.settings,f=(y=l.conversation.current)==null?void 0:y.id,d=s.type===_m.toString();if(!f||!c&&!u)return a;let{input:p}=l;return c9(p,i)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let S=Os(l);S===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(S))},d?0:t.debounce)),a}};var U_=Ti.fulfilled.toString();function u9(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let s=e.keywordMatches.filter(l=>l.keyword===o),i=t.keywordMatches.filter(l=>l.keyword===o),a=i.length-s.length;a<=0||r.push(...i.slice(0,a))}),r}var V_=e=>t=>n=>r=>{var c;if(r.type!==U_){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let s=t.getState(),i=s.styleSuggestions.list,a=(c=s.conversation)==null?void 0:c.current;if(o===i)return;let l=u9(o,i);r.type===U_&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var d9=cd({assistants:uC,auth:Bb,conversation:qb,contentTypes:dA,passwordlessToken:e_,entities:BA,handlingTime:F_,info:hE,input:iE,settings:fC,profile:yA,search:bE,styleSuggestions:EI,ui:dI,textSuggestions:XA});function W_(e){return Rb({reducer:d9,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(z_()).concat(B_({debounce:200})).concat(H_({debounce:500})).concat(V_(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,s)=>o.concat(s),n)},preloadedState:e.preloadedState})}function $_(e,t,n){if(t==="")return null;let r=new RegExp(`\\b${jm(t)}\\b`,"gi"),o,s=null;for(;(o=r.exec(e))!==null&&!(o.index>n);)s={start:o.index,end:o.index+o[0].length};return s}var f9=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},p9=e=>t=>n=>r=>{var l,c,u,f,d,p;let o=t.getState(),s=Vs("inlineSuggestions")(o),i=Vs("autoSelectSuggestion")(o)||s;switch(r.type){case Ki.toString():{!r.payload&&e.emit("logout",void 0);break}case Ad.fulfilled.toString():{e.emit("logout",void 0);break}case Er.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(l=o.conversation.current)==null?void 0:l.id,data:{entities:r.payload}});break;case Fs.toString():e.logSendMessage(r.payload);break;case af.toString():e.emit("call-to-action",{cue:r.payload});break;case Rn.fulfilled.toString():if(!r.isBroadcasted){let{externalConversationId:h,currentExternalIdAtRequest:y}=(c=r.payload)!=null?c:{};(!h||!y||h===y)&&e.broadcast(Th,r,!1)}break;case Rn.rejected.toString():break;default:break}let a=n(r);switch(r.type){case Fs.toString():e.handleAfterSendMessage(r.payload);break;case yu.toString():e.onUpdateShowTabHint(r.payload);break;case cg.toString():e.logHandlingTime();break;case Yi.toString():e.broadcast(Vd,r);break;case Ds.toString():e.broadcast(Vd,r);break;case lf.toString():t.dispatch(Ds({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{let h=o.assistants.cues.find(y=>y.code===r.meta.arg.data.assistantCode);e.emit("event",_(b({},r.meta.arg),{cue:h}));break}case Tn.toString():{let{start:h,end:y}=o.input.selection;e.emit("select-suggestion",_(b({type:f9(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:h,end:y}:{start:0,end:y}})),s&&t.dispatch(Uo([]));break}case bI.toString():{let{keyword:h,suggestion:y,eventMetrics:S}=r.payload,{text:m,selection:g}=o.input,v=$_(m,h,(u=g==null?void 0:g.end)!=null?u:m.length);if(!v)break;e.emit("select-suggestion",{text:y,type:"style",replace:v,suggestion:{text:y,source:"style"},eventMetrics:S});break}case Nd.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Uo.toString():{i&&r.payload.length>0&&t.dispatch(Dd(0));break}case Rn.fulfilled.toString():{let{evaluationId:h,output:y,externalConversationId:S}=r.payload,m=r.meta.arg.assistantCode;if(e.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:h,assistantCode:m,assistantOutput:oC(y),externalConversationId:S,evaluationStatus:"success"}}),!r.meta.arg.skipState){let g=t.getState().assistants.cues;e.emit("cues",g)}break}case Rn.rejected.toString():{let h=r.meta.arg.assistantCode,y=(p=r.meta.arg.externalConversationId)!=null?p:(d=t.getState().conversation.current)==null?void 0:d.externalId;e.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:"",assistantCode:h,assistantOutput:"",externalConversationId:y,evaluationStatus:"failed"}});break}default:break}return a},j_=p9;function dx(e){return e.toISOString().replace("T"," ").replace("Z","")}var m9=(e,t)=>t.version,K_=Yt([Xi,Vn,L_,m9],(e,t,n,r)=>{if(!t)return J.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:s}=n;return!o||!s?(J.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:dx(o),timeStop:dx(s)}});function G_(e,t){let{text:n,metrics:{numPaste:r,pastes:o,textSuggestions:s}}=e.input,i=n.length;return{source:"agent",clientVersion:t.version,pastes:o,lenTextTotal:i,numPastes:r,suggestions:s}}var Iu=class extends Error{};function g9(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var ug=class{constructor(){this.queues={}}push(t,n){let r=()=>{let s=this.queues[t][1];s?(this.queues[t]=[s.promise,null],s.resolve()):delete this.queues[t]};if(!this.queues[t]){let s=n().finally(r);return this.queues[t]=[s,null],s}this.queues[t][1]&&this.queues[t][1].reject(new Iu("Queued async function is outdated"));let o=g9();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};function fx(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return fx(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?fx(o,t):null}function px(e,t){return fx(e,t)}var h9={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},q_=(e,t)=>{var o,s,i;if(!((i=(s=(o=e.uiConfig)==null?void 0:o.widget)==null?void 0:s.types.find(a=>a.type==="cues"))==null?void 0:i.isActive))return J.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let r=e[h9[t]];return r&&r.length>0?r.map(a=>a.code):(J.warn(`No assistant set in profile for conversation event "${t}"`),[])};function y9(e){var t,n,r,o;return(o=(r=(n=(t=e.uiConfig)==null?void 0:t.widget)==null?void 0:n.types)==null?void 0:r.some(s=>s.type==="knowledge-assist"&&s.isActive))!=null?o:!1}function Y_(e){var n,r;return((r=(n=e.widgetInteractiveAssistants)==null?void 0:n.length)!=null?r:0)>0&&y9(e)?!0:!!e.knowledgeAssistantNew||!!e.knowledgeAssistant}function v9(e){return typeof e=="object"&&e!==null&&"tagName"in e}function dg(e){return v9(e)&&(Ri(e)||Wm(e))}var Q_,Xr=new Map,S9=["bottom","height","left","right","top","width"],X_=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:S9.some(n=>e[n]!==t[n]);function Z_(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,...Z_(t)]:[]}function J_(e,t){return!e||!t?null:_(b({},e),{top:e.top+t.top,left:e.left+t.left})}var fg=!1,eM=()=>{fg=!0;let e=[];if(Xr.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Xr.delete(n);return}let r=n.getBoundingClientRect();X_(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(J_,t.rect):t.rect;X_(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Xr.size===0){fg=!1;return}Q_=window.requestAnimationFrame(eM)};function mx(e,t){let n=Z_(e),r=[],o=n.map((s,i)=>mx(s,a=>{r[i]=a;let l=Xr.get(e);if(!l)return;let c=r.reduce(J_,l.rect);l.callbacks.forEach(u=>u(c))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),Xr.has(e)){let i=Xr.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else Xr.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!fg&&eM()},unobserve(){o.forEach(i=>i.unobserve());let s=Xr.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||Xr.delete(e),Xr.size||(cancelAnimationFrame(Q_),fg=!1)}}}}var tM,Qr=new Map,nM=()=>{Qr.forEach((e,t)=>{if(!t.isConnected){Qr.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(s=>s(e.visible)))}),Qr.size!==0&&(tM=window.requestAnimationFrame(nM))};function rM(e,t){return{observe(){let n=Qr.size===0;Qr.has(e)?Qr.get(e).callbacks.push(t):Qr.set(e,{visible:void 0,callbacks:[t]}),n&&nM()},unobserve(){let n=Qr.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Qr.delete(e),Qr.size||cancelAnimationFrame(tM)}}}}var gx=["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 hx(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function sl(e){return Number.parseFloat(e)}function pg(e){return Math.round(e*1e6)}function oM(e){return e/1e6}function yx(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=sl(e.width),s=sl(e.borderLeftWidth),i=sl(e.borderRightWidth),a=sl(e.paddingRight),l=oM(pg(o)-pg(s)-pg(i)),c=oM(pg(r));if(l-c>2){let u=l-c;n.style.paddingRight=`${a+u}px`}}function _u(e,t={}){var u,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(u=t.position)!=null?u:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",mi(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};hx(r,n,gx),yx(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=rM(e,()=>{hx(r,n,gx),yx(r,e,n),s(),setTimeout(s,0)}),a,l=!0,c=mx(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(hx(r,n,gx),yx(r,e,n),s(),t.placement==="below"&&n.classList.add("below"),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let p=t.closestScrollElement.getBoundingClientRect(),h=window.getComputedStyle(t.closestScrollElement),y=sl(h.borderTopWidth),S=sl(h.borderBottomWidth),m=p.top+y-d.top,g=d.top+d.height+-(p.top+p.height-S);n.style.clipPath=`inset(${m}px 0px ${g}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),c.observe(),i.observe(),[n,()=>{e.removeEventListener("scroll",s),c.unobserve(),i.unobserve(),n.remove()}]}function x9(e){return e.offsetParent!==null}function sM(e){if(!x9(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 mg(e,t,n=100){let r=sM(e);t({isVisible:r});let o=setInterval(()=>{let s=sM(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var iM=(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){J.warn("[Deepdesk] SessionStorage is blocked by browser")}}});var ke=E(A());var aM=iM("showTabHint",!0),il=class il{constructor({deepdeskUrl:t,version:n=il.version||"unknown",locale:r="en-US",token:o,fetch:s,productName:i,createCustomChannel:a,websocketClient:l=lg}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.disposeHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.belowSuggestions=null;this.floatingMenu=null;this.widgetElement=null;this.widgetRoot=null;this.nicknameDialogUnsubscribe=null;this.nicknameDialogFailed=!1;this.dynamicThunkObject={};this.queues=new ug;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;this.loadProfileConfigPromiseKey=null;this.personalCollectionSyncPendingKey=null;this.personalCollectionSyncDrainPromise=null;let c=t.replace(/\/api$/,"");this.deepdeskApi=new Lo(c,{token:o,fetch:s}),this.version=n,this.instanceId=il.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[j_({broadcast:(h,y,S)=>{this.broadcastEvents.send(h,y,S)},emit:(h,y)=>this.emit(h,y),handleAfterSendMessage:h=>this.handleAfterSendMessage(h),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:h=>this.logSendMessage(h),onUpdateShowTabHint:h=>aM.update(h),sendEvent:(h,y)=>this.deepdeskApi.sendEvent(h,y)})]};this.store=W_(u),this.broadcastEvents=new A_({debug:!0,deepdeskUrl:c,eventMap:EE(this.store),createCustomChannel:a}),this.disposeHandlers.push(()=>{this.broadcastEvents.cleanup()}),this.ws=new l({url:`${c}/api/v2/me/realtime`.replace("https","wss"),reconnectInterval:25e3,shouldReconnect:()=>M(this,null,function*(){var h;return(h=kt(this.state))!=null?h:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(yu(aM.value())),this.store.dispatch(jl({locale:r,adminUrl:c,productName:i}));let f=[],d=h=>{if(!h.conversationId)return;let y=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(lC(h))};this.hasConversation()?y():f.push(y)};this.ws.on("assistants::direct_response",d),this.ws.on("assistants::user_notification",d),this.ws.on("assistants::response_chunk",h=>{if(!h.conversationId)return;let y=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(aC(h))};this.hasConversation()?y():f.push(y)}),this.ws.on("assistants::suggest_as_reply",h=>{if(!h.conversationId)return;let y=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(Yi([{text:h.payload.message,type:"text",source:"assistant",assistantCode:h.code,sourceLabel:h.name}]))};this.hasConversation()?y():f.push(y)});let p=this.whenConversationLoaded(()=>{var h;this.broadcastEvents.setExternalId((h=this.state.conversation.current)==null?void 0:h.externalId),f.forEach(y=>y()),f.length=0});this.disposeHandlers.push(()=>{this.ws.cleanup(),f.length=0,p()})}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=Ns(this.state)[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}externalId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.externalId}shouldAbort(){return this.state.conversation.isSupported===!1?(J.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(J.warn("Profile has not been loaded (yet)"),!0):(J.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(t){if(kt(this.state))t();else{let n=this.subscribe(kt,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Ki(null)),this.store.dispatch(to()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return M(this,null,function*(){return(yield this.store.dispatch(to())).payload})}isConversationSupported(t,n){return M(this,null,function*(){return(yield this.store.dispatch(vh({externalId:t,options:n}))).payload})}createConversation(t){return M(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(Md(_(b({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}getConversationByExternalId(t,n){return M(this,null,function*(){return this.hasConversation()&&this.externalId()!==t&&this.resetConversation(),(yield this.store.dispatch(Ld({externalId:t,options:n}))).payload})}upsertConversation(t){return M(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(Sh(_(b({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return M(this,null,function*(){yield this.store.dispatch(xh(t))})}updateConversation(t){return M(this,null,function*(){return(yield this.store.dispatch(Od(t))).payload})}resetConversation(){this.store.dispatch(Ge()),this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(jl(t))}setVisitorInfo(t){this.store.dispatch(fE(t))}setCustomData(t){this.store.dispatch(pE(t))}setAgentInfo(t,n){return M(this,null,function*(){var o;yield this.store.dispatch(Tl(b(b({},t),n))),(o=this.state.info.agentInfo)!=null&&o.agentNickname||this.broadcastEvents.send(Ud,{showNicknameDialog:!0})})}setAgentSettings(t){return M(this,null,function*(){yield this.store.dispatch(bh(t))})}getAgentSettings(){return M(this,null,function*(){return(yield this.store.dispatch(Eh())).payload})}getMe(){return M(this,null,function*(){return this.deepdeskApi.getMe()})}refresh(){return M(this,null,function*(){if(this.shouldAbort())return Promise.resolve();let t=[];return t.push(this.refreshTextSuggestions()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}syncInputMediator(){this.inputMediator&&this.store.dispatch(Fd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()}))}notifyExternalSuggestion(t){this.store.dispatch(Tn(t))}evaluateAssistant(t,n){return M(this,null,function*(){var u;let{input:r={},attachments:o=[],transcript:s,showCuesInWidget:i=!0,includeMetadata:a,externalConversationId:l}=n||{},c=yield this.store.dispatch(Rn({assistantCode:t,attachments:o,transcript:s,includeMetadata:a,input:r,externalConversationId:l,skipState:!i}));if(c.error)throw new Error(`Assistant evaluation failed: ${(u=c.payload)!=null?u:c.error.message}`);return c.payload.output})}evaluateConversationAssistant(t,n){return M(this,null,function*(){var u,f,p;yield this.loadProfileConfig();let r=this.state.profile.data;if(!r&&((u=this.state.conversation.current)!=null&&u.profileCode)&&(yield this.loadProfileConfig(),r=this.state.profile.data),!r){J.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=q_(r,t),s=(f=n==null?void 0:n.showCuesInWidget)!=null?f:!0,d=n!=null?n:{},{showCuesInWidget:i}=d,a=ie(d,["showCuesInWidget"]),l=(p=n==null?void 0:n.externalConversationId)!=null?p:this.hasConversation()?this.externalId():"",c=yield Promise.all(o.map(h=>this.queues.push(h,()=>M(this,null,function*(){var S,m;let y=yield this.store.dispatch(Rn(b(_(b({assistantCode:h,includeMetadata:!0},a),{skipState:!s}),n!=null&&n.attachments&&(n==null?void 0:n.attachments.length)>0?{attachments:n==null?void 0:n.attachments}:{})));if(y.error)throw new Error(`Assistant evaluation failed: ${(S=y.payload)!=null?S:y.error.message}`);return{assistantCode:h,evaluationId:y.payload.evaluationId,output:y.payload.output,externalConversationId:(m=y.payload.externalConversationId)!=null?m:l}})).catch(y=>{if(y instanceof Iu)return J.warn(`Queued assistant "${h}" was outdated and dropped`),null;throw y})));if(!s)return c.filter(h=>h!==null)})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,autoSelectSuggestion:l,showTextSuggestions:c,suggestionsPlacement:u}=this.settings,f=a||l,d=u==="inline"||u==="below"?"below":"above",p=o.length>0;if(this.store.dispatch(Jb(wh(t))),!Gr(this.state)||t.key!=="Tab"&&!c)return;let h=()=>{n||!p||i&&(t.shiftKey||(this.store.dispatch(nE()),t.preventDefault()))},y=()=>{n||!p||f&&s<=0||i&&(t.shiftKey||(this.store.dispatch(rE()),t.preventDefault()))};switch(t.key){case"ArrowUp":d==="below"?y():h();break;case"ArrowDown":{d==="below"?h():y();break}case"Escape":{n||(this.store.dispatch(Dd(-1)),this.store.dispatch(Ss({collapse:!0})),this.store.dispatch(cI(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let S=qi(this.state);if(!S)return;this.store.dispatch(yu(!1)),this.store.dispatch(Tn({text:S.text,suggestion:S,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(f||this.state.input.selectedSuggestionIndex===-1)return;let S=qi(this.state);if(!S)return;this.store.dispatch(Tn({text:S.text,suggestion:S,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(f||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let S=qi(this.state);if(!S)return;this.store.dispatch(Tn({text:S.text,suggestion:S,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(Ss({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Uo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(J.info("Start handling time"),this.store.dispatch(N_()))}handlingTimeStop(){this.state.handlingTime.startTime&&(J.info("Stop handling time"),this.store.dispatch(cg()))}logSendMessage(t){let n=G_(this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEvent("Send Message",{conversationId:this.conversationId(),data:n}),this.emit("send-message-event",n))}logHandlingTime(){let t=K_(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(D_()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Fs((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(sE()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(s){J.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),J.error(s)}})}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(mE(t))}whenConversationLoaded(t){let n=()=>this.getConversationLoadedKey(),r=()=>{let s=n();s&&this.loadProfileConfig().then(()=>{if(n()!==s)return;let i=this.state.conversation.current,a=er(this.state);!(i!=null&&i.id)||i.profileCode&&(a==null?void 0:a.code)!==i.profileCode||t()})};return n()&&r(),this.subscribe(s=>this.getConversationProfileKey(s.conversation.current),s=>{s&&r()})}overlayContainerFactory(t,n,r,o){let[s,i]=_u(n,r);return s.setAttribute("translate","no"),s.dataset.testid=t,o&&s.classList.add(o),[s,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 s=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[l,c]=_u(s,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{c()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return mi(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),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),J.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()?(J.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(oE(r.metrics))):J.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(!dg(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i,inputMediator:a}=d,l=ie(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),c={customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),mi(t),this.inputMediator=a||(Ri(t)?new _i(t):new Ii(t)),this.inputMediator.on("change",({plainText:p,rawHTML:h,suggestionTextStart:y})=>{this.store.dispatch(Fd({text:p,html:h,suggestionTextStart:y}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(eE(wh(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:h})=>{this.store.dispatch(tE({text:p,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(Zb(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(zd(p))},500):this.store.dispatch(zd(p))}),this.unmountHandlers.push(()=>{clearTimeout(u)}),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(Om(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Om(!0))}),this.renderSuggestions(t,c),this.subscribe(Vs("inlineSuggestions"),()=>{this.renderSuggestions(t,c)}),this.subscribe(Vs("suggestionsPlacement"),()=>{this.renderSuggestions(t,c)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(Fd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()})),this.store.dispatch(zd(this.inputMediator.getSelection())),this.store.dispatch(Om(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{this.restoreMetrics(),this.syncInputMediator(),this.refreshTextSuggestions(),this.promptForNickname()}),this.isMounted=!0}promptForNickname(t){if(this.nicknameDialogUnsubscribe||this.nicknameDialogFailed)return;let n=this.createContainer("nickname-dialog",document.body);document.body.appendChild(n);let r=(0,Oo.createRoot)(n),o=null,s=a=>{o=a,i()},i=()=>{r==null||r.render((0,ke.jsx)(Ro,{store:this.store,children:(0,ke.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(kI,{id:"deepdesk-nickname-dialog",error:o,onSave:a=>M(this,null,function*(){try{yield this.store.dispatch(uE({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(Ud,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(l){J.error("Error setting agent nickname",l),s("error"),this.nicknameDialogFailed=!0}})})})}))};i(),this.nicknameDialogUnsubscribe=()=>{r.unmount(),n.remove(),this.nicknameDialogUnsubscribe=null}}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,s;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.belowSuggestions)==null||r.unmount(),(o=this.floatingMenu)==null||o.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(s=this.inputMediator)==null||s.dispose(),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(t=>t()),this.disposeHandlers=[],this.off()}renderSuggestions(t,n){var r,o,s,i;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(s=this.aboveSuggestions)==null||s.unmount(),(i=this.belowSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions||this.settings.suggestionsPlacement==="inline"?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.settings.suggestionsPlacement==="below"?this.belowSuggestions=this.renderAboveOrBelowSuggestions(t,n,"below"):this.aboveSuggestions=this.renderAboveOrBelowSuggestions(t,n,"above")}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret"),s=(0,Oo.createRoot)(o);s.render((0,ke.jsx)(Ro,{store:this.store,customStyles:r,children:(0,ke.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(CI,{})})}));let i=a=>{a?(o.style.display="block",o.style.top=`${a.top}px`,o.style.left=`${a.left}px`):o.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",i),s.unmount(),o.remove()}}}renderAboveOrBelowSuggestions(t,n,r){let{customStyles:o,closestScrollSelector:s,appendOverlayTo:i}=n,a=s&&px(t,s)||void 0,[l,c]=this.overlayContainerFactory("deepdesk-tab-completion",a||t,{appendTo:i,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},o==null?void 0:o.rootNode),[u,f]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||t,{appendTo:i,placement:r},o==null?void 0:o.suggestionsRootNode),d=(0,Oo.createRoot)(l);d.render((0,ke.jsx)(Ro,{store:this.store,customStyles:o,children:(0,ke.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(QI,{inputElement:t})})}));let p=(0,Oo.createRoot)(u);return p.render((0,ke.jsx)(Ro,{store:this.store,customStyles:o,children:(0,ke.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(NI,{onLogIn:()=>this.loginViaPopup().catch(h=>J.warn(h.message))})})})),{unmount(){d.unmount(),p.unmount(),c(),f()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:s,floatingMenuParent:i}=n,a=o&&px(t,o)||void 0,[l,c]=this.overlayContainerFactory("floating-menu",a||t,{appendTo:i!=null?i:s},r==null?void 0:r.floatingMenuParent),u=(0,Oo.createRoot)(l);return u.render((0,ke.jsx)(Ro,{store:this.store,customStyles:r,children:(0,ke.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(aI,{onLogIn:()=>this.loginViaPopup().catch(f=>J.warn(f.message))})})})),{unmount(){u.unmount(),c()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays"),o=(0,Oo.createRoot)(r);return o.render((0,ke.jsx)(Ro,{store:this.store,customStyles:n,children:(0,ke.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(nI,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&J.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:s,signInViaPopup:i,ssoUrl:a,openAdminFeedback:l}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:s,signInViaPopup:i});let c;if(a)try{c={url:new URL(a,this.settings.adminUrl).toString()}}catch(u){J.warn(`Invalid ssoUrl '${a}' passed to renderWidget`)}this.widgetRoot=(0,Oo.createRoot)(t),this.widgetRoot.render((0,ke.jsx)(Ro,{store:this.store,customStyles:r,children:(0,ke.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(mm,{report:u=>this.deepdeskApi.sendEvent(XP,{data:u}),children:(0,ke.jsx)(E_,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,openAdminFeedback:l,onLogIn:()=>this.loginViaPopup(c).catch(u=>J.warn(u.message))})})})}))}unmountWidget(){var t,n;(n=(t=this.widgetRoot)==null?void 0:t.unmount)==null||n.call(t),this.widgetRoot=null,this.widgetElement=null}renderKnowledgeAssistantWidget(t,n,r={}){let{customStyles:o,initialQuestion:s}=r,i=(0,Oo.createRoot)(n);return i.render((0,ke.jsx)(Ro,{store:this.store,customStyles:o,children:(0,ke.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(ix,{children:(0,ke.jsxs)(um,{assistantCode:t,initialQuestion:s,evaluateKnowledgeAssistFn:$l,children:[(0,ke.jsx)(Vi,{children:(0,ke.jsx)(fm,{title:r.title,emptyState:r.emptyState})}),(0,ke.jsx)(sx,{children:(0,ke.jsx)(dm,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(t){let n=mg(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){pm(t)&&t.message==="Unauthorized"&&this.login()}getConversationProfileKey(t){var n;if(t!=null&&t.id)return`${t.id}:${(n=t.profileCode)!=null?n:""}`}getProfileLoadKey(){var n;let t=this.state.conversation.current;return t!=null&&t.profileCode&&(n=this.getConversationProfileKey(t))!=null?n:null}isCurrentProfileLoadKey(t){return this.getProfileLoadKey()===t}getConversationLoadedKey(){return this.getConversationProfileKey(this.state.conversation.current)}resetProfileDerivedSettings(){this.store.dispatch(SS()),this.store.dispatch(jl(ty))}syncPersonalCollectionForConversation(t){this.personalCollectionSyncPendingKey=t,this.ensurePersonalCollectionSyncDrain()}ensurePersonalCollectionSyncDrain(){return this.personalCollectionSyncDrainPromise?this.personalCollectionSyncDrainPromise:(this.personalCollectionSyncDrainPromise=this.drainPersonalCollectionSync().finally(()=>{this.personalCollectionSyncDrainPromise=null,this.personalCollectionSyncPendingKey&&this.ensurePersonalCollectionSyncDrain()}),this.personalCollectionSyncDrainPromise)}drainPersonalCollectionSync(){return M(this,null,function*(){for(;this.personalCollectionSyncPendingKey;){let t=this.personalCollectionSyncPendingKey;if(this.personalCollectionSyncPendingKey=null,!this.isCurrentProfileLoadKey(t))continue;let n=this.state.conversation.current,r=n==null?void 0:n.id;if(!(!r||!n.profileCode))try{yield this.deepdeskApi.syncPersonalCollection(r)}catch(o){this.isCurrentProfileLoadKey(t)&&J.warn("Failed to sync personal collection for profile",o)}}})}loadProfileConfig(t=!0){let n=this.getProfileLoadKey();if(!n)return this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null,this.resetProfileDerivedSettings(),Promise.resolve();let r=this.state.conversation.current,o=er(this.state);if(o&&o.code!==(r==null?void 0:r.profileCode)&&(this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null,this.resetProfileDerivedSettings()),this.loadProfileConfigPromise&&this.loadProfileConfigPromiseKey===n)return this.loadProfileConfigPromise;this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=n;let s=Promise.resolve().then(()=>M(this,null,function*(){try{yield this.store.dispatch(eu()).unwrap()}catch(l){if(l===Ga)return this.loadProfileConfigPromise===s&&(this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null),t&&this.isCurrentProfileLoadKey(n)&&!er(this.state)?this.loadProfileConfig(!1):void 0;throw l}if(!this.isCurrentProfileLoadKey(n))return;let i=er(this.state),a=this.state.conversation.current;!i||i.code!==(a==null?void 0:a.profileCode)||(this.store.dispatch(jl({showSearch:i.search,showImageSearch:i.imageSearch,showEntitiesCommand:i.entitiesCommand,showSummaryCommand:!!i.summarizerAssistantNew,showKnowledgeSearch:Y_(i),recommendTextSuggestions:i.recommendTextSuggestions})),this.syncPersonalCollectionForConversation(n))})).finally(()=>{this.loadProfileConfigPromise===s&&(er(this.state)||(this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null))});return this.loadProfileConfigPromise=s,s}loginViaPopup(t){return M(this,null,function*(){return new Promise((n,r)=>{this.store.dispatch(Id());let o=new MessageChannel,s=o.port1,i=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,c=()=>{u&&!u.closed&&u.close(),window.removeEventListener("message",f),clearInterval(d)};s.onmessage=p=>M(this,null,function*(){var h,y;if((h=p.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((y=p.data)==null?void 0:y.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Rl),l=!0,o.port1.close(),n()}catch(S){console.error(S),r(S)}finally{l=!0,c()}});let u=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");if(u===null){r(new Error("Popup blocked by browser"));return}let f=p=>M(this,null,function*(){var h;if(!(p.origin!==a.origin||p.source!==u))switch((h=p.data)==null?void 0:h.type){case"deepdesk-popup-request-origin":{try{let y=JSON.stringify({type:"deepdesk-popup-parent-origin"});u.postMessage(y,a.origin)}catch(y){J.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-loaded":{try{let y=JSON.stringify({type:"deepdesk-popup-create-channel"});u.postMessage(y,a.origin,[o.port2])}catch(y){J.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-error":{if(c(),p.data.message==="Platform account url mismatch"){let y="Please contact your administrator: The page that opened the popup is not a trusted origin.";J.warn(y),this.store.dispatch(mh(y)),r(new Error(y));return}if(p.data.message==="Timeout"){let y="Please contact your administrator: Popup timed out. Check if the account's platform.url or account.url is configured correctly.";J.warn(y),this.store.dispatch(mh(y)),r(new Error(y));return}r(new Error(p.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{u&&!u.closed||(c(),l||r(new Error("Popup closed by user")))},200);this.disposeHandlers.push(c)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}refreshTextSuggestions(){return M(this,null,function*(){this.isMounted&&(yield this.store.dispatch(_m()))})}refreshWidgetSuggestions(){return M(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=tu(this.state);try{n.forEach(({type:r})=>{switch(r){case"entities":this.store.dispatch(Er());break;case"pinned-messages":case"sticky-messages":break;default:sd.includes(r)||this.store.dispatch(Cr(r))}})}catch(r){this.handleError(r)}})}};il.version="19.6.2-beta.7",il.count=0;var Mu=il;function w9(e){return M(this,null,function*(){var o,s,i;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(i=(s=e.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function lM(e,t){return M(this,null,function*(){let n=yield w9(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 cM(e,t,n){return M(this,null,function*(){yield new Lo(e).authenticateWithKey(t,n)})}function uM(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function dM(r,o){return M(this,arguments,function*(e,t,n={}){var f,d;let{value:s}=e,{start:i,end:a}=(f=n.replace)!=null?f:{start:0,end:s.length},l=`${s.slice(0,i)}${t}${s.slice(a)}`,c=(d=n.selectionAfter)!=null?d:{start:i+t.length,end:i+t.length},u=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(u()).then(()=>{e.selectionStart=c.start,e.selectionEnd=c.end,e.blur(),e.focus()})})}function fM(r,o){return M(this,arguments,function*(e,t,n={}){let s=n.replace?Cs(e,n.replace.start,n.replace.end):rl(e),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?t.split(`
83
+ `);let h=d?r:0,y=p?Math.min(s,u.childNodes.length):u.childNodes.length;for(let S=h;S<y&&(c(u.childNodes[S]),a!==2);S++);break}default:break}p&&(a=2)}return c(e),l}var T_=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(T_||{}),Mo=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedSuggestionTextStart=0;this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedSuggestionTextStart=this.getSuggestionTextStart(),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.getSuggestionTextStart(),s=this.cachedCaretPosition===null;if(!this.isActive)return;t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit");let i=t!==this.cachedText,a=n!==null&&n!==this.cachedHTML,l=o!==this.cachedSuggestionTextStart;if((i||a||l)&&(i?(this.cachedText=t,this.cachedHTML=n):a&&(this.cachedHTML=n),this.cachedSuggestionTextStart=o,s=!0,this.emit("change",{plainText:t,rawHTML:n,suggestionTextStart:o})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,s=!0,this.emit("selection",r)),!s)return;let c=this.getCaretPosition();Bo(c,this.cachedCaretPosition)||(this.cachedCaretPosition=c,this.emit("caretposition",c))}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(T_).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()})}getSuggestionTextStart(){return 0}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 k_(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Ii=class extends Mo{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Pu(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){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=r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let s=this.element.ownerDocument.createRange();return s.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),s.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!k_(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!k_(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return Ru(this.element,n);let r=this.lastKnownSelection;if(r&&C_(this.element,r.start,r.end))return r;let o=rl(this.element);return o.collapse(!1),Ru(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Pu(this.element,Cs(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[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 s9=["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 R_(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,s=window.getComputedStyle(e),i=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",s9.forEach(u=>{o[u]=s[u]}),n?e.scrollHeight>Number.parseInt(s.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),i.appendChild(r);let l=e.getBoundingClientRect(),c={top:l.top-e.scrollTop+a.offsetTop+Number.parseInt(s.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+Number.parseInt(s.borderLeftWidth)};return i.removeChild(r),c}var _i=class extends Mo{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 R_(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 s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),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 P_(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let s=document.createElement("iframe"),i=new URL(t);return Object.entries(n).forEach(([a,l])=>{i.searchParams.append(a,l)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=r,s.title=`iframe-${e}`,s.src=i.toString(),window.document.body.appendChild(s),s}function i9(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var ax=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()}},lx=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=P_(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()}},cx=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.externalId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setExternalId(t){this.externalId!==t&&(this.cleanup(),J.info("Set externalId",t),this.externalId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new lx(t,this.deepdeskUrl,{debug:!0}):new ax(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=i9(o.data);typeof s!="object"||s.type!=="event"||s.channel!==t||(J.info("Received broadcast event",this.externalId,o),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(r),n}send(t,n,r){var i,a;J.info("Broadcast event",{externalId:this.externalId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(i=this.eventMap)[t])==null||a.call(i,n));let s=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(_(b({},o),{channel:this.externalId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),this.channel=void 0,t&&((r=this.defaultChannel)==null||r.close(),this.defaultChannel=void 0)}},A_=cx;function a9(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function He(e){return Array.isArray(e)?e.map(He):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>_(b({},t),{[a9(n)]:He(e[n])}),{}):e}function l9(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Mt(e){return Array.isArray(e)?e.map(Mt):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>_(b({},t),{[l9(n)]:Mt(e[n])}),{}):e}var ol=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var Au=e=>new Promise(t=>{setTimeout(t,e)});var Tr=class extends ol{constructor(){super(...arguments);this.name="ClientError"}},ig=class extends ol{constructor(){super(...arguments);this.name="ServerError"}},ux=new Map;function I_(e){return M(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t!=null&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(J.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var Mi=class{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.refreshingToken=null;this.lastFailedRefreshAt=null;this.failedRefreshCooldown=1e4;var r;this.fetch=(r=n.fetch)!=null?r:window.fetch.bind(window)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let s={isAborted:!1,reject:o},i=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",C=n,{useCache:c=!1,abortLatest:u=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:h=k=>k instanceof TypeError,retryOnResponse:y=k=>k.status>=500,version:S=null}=C,m=ie(C,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(c){if(!l)throw new Error(`Can't use 'useCache' for ${n.method}`);if(ux.has(i)){r(ux.get(i));return}}let g=_(b({credentials:"include"},m),{headers:b({Accept:"application/json","Content-Type":"application/json"},m.headers)});!l&&this.csrfToken&&(g.headers=_(b({},g.headers),{"X-CSRFToken":this.csrfToken})),typeof S=="string"&&(g.headers=_(b({},g.headers),{"X-Deepdesk-API-Version":S}));let v=f,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&u&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let T=()=>M(this,null,function*(){return v--,a(i,g).then(k=>M(this,null,function*(){return y(k)&&!s.isAborted&&v>0?(yield Au(d),T()):k.status===401&&p===!0&&x===!1?(x=!0,yield this.refreshToken(),T()):k})).catch(k=>M(this,null,function*(){if(h(k)&&!s.isAborted&&v>0)return yield Au(d),T();throw k}))});T().then(k=>M(this,null,function*(){let P=yield I_(k);if(delete this.latestRequestByUrl[i],k.status>=500){o(new ig("Server Error",P));return}if(k.status===401){o(new Tr("Unauthorized",P));return}if(k.status===403){o(new Tr("Forbidden",P));return}if(k.status===404){o(new Tr("Not Found",P));return}if(k.status>=400){o(new Tr("Bad Request",P));return}c&&ux.set(i,P),r(P)})).catch(k=>{o(k)})})}validateToken(){return M(this,null,function*(){let t,n,r;try{({has_valid_access_token:t,is_logged_in:n,has_valid_refresh_token:r}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1}))}catch(o){return!1}if(!t){if(!r)return!1;try{yield this.refreshToken();let{is_logged_in:o}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1});return o}catch(o){return!1}}return n})}refreshToken(){let t=Date.now();return this.lastFailedRefreshAt&&t-this.lastFailedRefreshAt<this.failedRefreshCooldown?Promise.reject(new Tr("Unauthorized","Failed to refresh token")):this.refreshingToken?this.refreshingToken:(this.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).catch(n=>{throw(n==null?void 0:n.message)==="Unauthorized"&&(this.lastFailedRefreshAt=Date.now()),n}).finally(()=>{this.refreshingToken=null}),this.refreshingToken)}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,b({method:"POST",body:JSON.stringify(n)},r))}postWithStatus(t,n,r){return this.requestWithStatus(t,b({method:"POST",body:JSON.stringify(n)},r))}requestWithStatus(t,n={}){return new Promise((r,o)=>{let s={isAborted:!1,reject:o},i=`${this.baseUrl}${t}`,a=this.fetch,T=n,{useCache:l=!1,abortLatest:c=!1,attempts:u=1,retryDelay:f=500,refreshTokenOn401:d=!0,retryOnError:p=C=>C instanceof TypeError,retryOnResponse:h=C=>C.status>=500,version:y=null}=T,S=ie(T,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]),m=_(b({credentials:"include"},S),{headers:b({Accept:"application/json","Content-Type":"application/json"},S.headers)});this.csrfToken&&(m.headers=_(b({},m.headers),{"X-CSRFToken":this.csrfToken})),typeof y=="string"&&(m.headers=_(b({},m.headers),{"X-Deepdesk-API-Version":y}));let g=u,v=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let x=()=>M(this,null,function*(){return g--,a(i,m).then(C=>M(this,null,function*(){return h(C)&&!s.isAborted&&g>0?(yield Au(f),x()):C.status===401&&d===!0&&v===!1?(v=!0,yield this.refreshToken(),x()):C})).catch(C=>M(this,null,function*(){if(p(C)&&!s.isAborted&&g>0)return yield Au(f),x();throw C}))});x().then(C=>M(this,null,function*(){let k=yield I_(C);if(delete this.latestRequestByUrl[i],C.status>=500){o(new ig("Server Error",k));return}if(C.status===401){o(new Tr("Unauthorized",k));return}if(C.status===403){o(new Tr("Forbidden",k));return}if(C.status===404){o(new Tr("Not Found",k));return}if(C.status>=400){o(new Tr("Bad Request",k));return}r({status:C.status,data:k})})).catch(C=>{delete this.latestRequestByUrl[i],o(C)})})}patch(t,n,r){return this.request(t,b({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,b({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,b({method:"DELETE"},n))}};var __;(t=>{let e;(a=>(a.SUCCESS="success",a.FAILURE="failure",a.CONDITIONS_NOT_MET="conditions_not_met",a.MAX_RECURSION_LEVEL="max_recursion_level",a.NO_ACCESS_TO_ASSISTANT="no_access_to_assistant"))(e=t.EvaluationStatus||(t.EvaluationStatus={}))})(__||(__={}));function ag(e){return _(b({},He(e)),{metadata:e.metadata})}var Li=class Li{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new Mi(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,s)=>M(this,null,function*(){let i=yield r(o,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return M(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(Li.exchangeTokenPromise||(Li.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),Li.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return M(this,null,function*(){var r;yield this.preflight(),J.info(`Creating conversation for session ${t.externalId} and agent ${t.agentId}`);let n=yield this.client.post("/api/v2/conversations",_(b({chat_start_time:new Date().toISOString()},Mt(t)),{metadata:(r=t.metadata)!=null?r:{}}));return ag(n)})}upsertConversation(t){return M(this,null,function*(){var u;yield this.preflight(),J.info(`Upserting conversation for session ${t.externalId} and agent ${t.agentId}`);let{status:n,data:r}=yield this.client.postWithStatus("/api/v2/conversations",_(b({chat_start_time:new Date().toISOString()},Mt(t)),{metadata:(u=t.metadata)!=null?u:{}}),{version:"v2"}),o=ag(r);if(n===201)return o;let{agentId:s,agentName:i,agentEmail:a,agentNickname:l,metadata:c}=t;return this.updateConversation(o.id,{agentId:s,agentEmail:a,agentName:i,agentNickname:l,metadata:c})})}getMe(){return M(this,null,function*(){yield this.preflight();let t=yield this.client.get("/apis/admin/session/me/");return He(t)})}postIdentity(t){return M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",Mt(t))})}patchMe(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",Mt(t));return He(n)})}getProfile(t){return M(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return He(n)})}getKnowledgeAssistant(t){return M(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return He(n)})}getContentTypes(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return He(t)})}getAccount(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return He(t)})}getPlatformConfig(t){return M(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return He(r)})}checkUserExists(t){return M(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationByExternalId(r){return M(this,arguments,function*(t,n={}){yield this.preflight(),J.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/v2/conversations/by_external_id/${t}`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return J.info(`Successfully retrieved conversation ${i.id} for session ${t}`),ag(i)})}isConversationSupported(r){return M(this,arguments,function*(t,n={}){J.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${t}/has_active_profile`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(t,n){return M(this,null,function*(){var s;yield this.preflight();let r=Mt(n);n.metadata&&(r.metadata=(s=n.metadata)!=null?s:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return ag(o)})}postMessages(t,n){return M(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>_(b({},Mt(r)),{metadata:r.metadata})))})}sendEvent(t,n){return M(this,null,function*(){yield this.preflight();let a=n,{data:r}=a,o=ie(a,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((l,[c,u])=>_(b({},l),{[c]:u}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((l,c)=>(o[c]&&(l[c]=o[c]),l),{});return this.client.post("/api/v2/events",Mt(_(b(b({},s),i),{data:r,name:t})),{version:"v2"})})}getEntities(t){return M(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:t.filter(r=>r.text)})})}getTemporaryExchangeToken(){return M(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(t){return M(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw J.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Mt(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return M(this,arguments,function*(t,n={},r){if(yield this.preflight(),r==="sticky-messages")throw new Error("Use getPinnedMessages instead");return(yield this.client.post(`/api/v2/conversations/${t}/recommend/${r}`,Mt(n),{abortLatest:!0})).map(i=>_(b({},He(i)),{text:i.text||i.url||i.message,source:r,type:r})).filter((i,a,l)=>a===l.findIndex(c=>c.text===i.text))})}isLoggedIn(){return M(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return M(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${t}/autocomplete`,Mt(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,s,i)=>s===i.findIndex(a=>a.text===o.text))})}syncPersonalCollection(t){return M(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/personal-collection/sync`,{},{version:"v2"})})}getPinnedMessages(t){return M(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return He(n).map(r=>_(b({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return M(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",Mt(t),{abortLatest:!0,version:"v2"});return He(n)})}search(t){return M(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,Mt(t));return He(n)})}loginWithPassword(t,n){return M(this,null,function*(){yield this.preflight();let r=yield this.client.post("/apis/admin/session/login/",{username:t,password:n},{refreshTokenOn401:!1});return He(r)})}logout(){return M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/logout/",{},{refreshTokenOn401:!1})})}requestLoginByEmail(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return He(n)})}requestPasswordlessToken(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return He(t.token)})}getCsrfToken(){return M(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return M(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return He(n)})}evaluateAssistant(t,n){return M(this,null,function*(){var l,c,u;yield this.preflight();let r=new URLSearchParams;n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let o=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=f=>Mt(f),i=(l=n==null?void 0:n.transcript)==null?void 0:l.map(f=>{var d;return b({source:f.source,text:f.text},(d=f.attachments)!=null&&d.length?{attachments:f.attachments.map(s)}:{})}),a=yield this.client.post(o,b({input:(c=n==null?void 0:n.input)!=null?c:{},conversation:i},(u=n==null?void 0:n.attachments)!=null&&u.length?{attachments:n.attachments.map(s)}:{}));return He(a)})}interactWithAssistant(t){return M(this,null,function*(){yield this.preflight();let n=new URLSearchParams;t.sessionId&&n.append("session_id",t.sessionId),t.externalConversationId&&n.append("external_conversation_id",t.externalConversationId);let r=`/api/v2/assistants/${t.assistantCode}/interact?${n.toString()}`,o=yield this.client.post(r,{message:t.message});return He(o)})}resetAssistantThread(t){return M(this,null,function*(){yield this.preflight();let n=encodeURIComponent(t.assistantCode),r=encodeURIComponent(t.sessionId);yield this.client.delete(`/api/v2/assistants/${n}/sessions/${r}/thread`)})}createAssistantThread(t){return M(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return He(r)})}postMessageToAssistantThread(t){return M(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:r,message:o}=t,s=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return He(s)})}translateMessages(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",Mt(t));return He(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(Rw);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&J.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};Li.exchangeTokenPromise=null;var Lo=Li;var lg=class{constructor(t){this.options=t;this.socket=null;this.maxReconnectAttempts=5;this.reconnectInterval=25e3;this.cleanupCallbacks=[];var n,r;this.socket,this.eventListeners=new Map,this.url=t.url,this.maxReconnectAttempts=(n=t.maxReconnectAttempts)!=null?n:this.maxReconnectAttempts,this.reconnectInterval=(r=t.reconnectInterval)!=null?r:this.reconnectInterval,this.shouldReconnect=t.shouldReconnect}connect(){let t=()=>this.cleanup();window.addEventListener("beforeunload",t),this.cleanupCallbacks.push(()=>window.removeEventListener("beforeunload",t)),this.reconnect()}setupListeners(){this.socket&&(this.socket.onmessage=t=>{var n;try{let r=He(JSON.parse(t.data));r.event&&this.eventListeners.has(r.event)&&((n=this.eventListeners.get(r.event))==null||n.forEach(o=>o(r.data)))}catch(r){console.error("Error parsing WebSocket message:",r)}},this.socket.onclose=t=>{console.log("WebSocket connection closed:",t),setTimeout(()=>{this.reconnect()},this.reconnectInterval)},this.socket.onerror=t=>{console.error("WebSocket error:",t)})}reconnect(){var t,n;if(this.maxReconnectAttempts<=0){console.error("Max reconnect attempts reached, closing WebSocket connection."),(t=this.socket)==null||t.close();return}if(!this.shouldReconnect()){console.error("Should not reconnect, closing WebSocket connection."),(n=this.socket)==null||n.close();return}this.socket&&(this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close()),this.socket=new WebSocket(this.url),this.setupListeners(),this.maxReconnectAttempts--}send(t,n){if(!this.socket){console.error("WebSocket connection is not open.");return}this.socket.send(JSON.stringify({event:t,data:n}))}on(t,n){this.eventListeners.has(t)||this.eventListeners.set(t,[]);let r=this.eventListeners.get(t);r&&!r.includes(n)&&r.push(n)}close(){var t;(t=this.socket)==null||t.close()}cleanup(){this.close(),this.cleanupCallbacks.forEach(t=>t()),this.cleanupCallbacks=[]}};var M_={startTime:null,stopTime:null},L_=e=>e.handlingTime,O_=Re({name:"handlingTime",initialState:M_,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(Ge,()=>M_)}}),{handlingTimeStart:N_,handlingTimeStop:cg,handlingTimeReset:D_}=O_.actions,F_=O_.reducer;var z_=(e={})=>{let t=b({onAuthError:Ki(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var H_=(e={})=>{let t,n=!0,r=b({getStyleSuggestions:Ti,debounce:500},e);return o=>s=>i=>{var p;let a=o.getState().input.text,l=s(i),c=o.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:u}=c.settings;if(!((p=c.conversation.current)==null?void 0:p.id)||!u)return l;let{text:d}=c.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function c9(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end&&e.suggestionTextStart===t.suggestionTextStart}var B_=(e={})=>{let t=b({getTextSuggestions:Cr,getAutocompleteSuggestions:gu,debounce:200,check:Gr},e),n;return r=>o=>s=>{var y;let{input:i}=r.getState(),a=o(s),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:u}=l.settings,f=(y=l.conversation.current)==null?void 0:y.id,d=s.type===_m.toString();if(!f||!c&&!u)return a;let{input:p}=l;return c9(p,i)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let S=Os(l);S===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(S))},d?0:t.debounce)),a}};var U_=Ti.fulfilled.toString();function u9(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let s=e.keywordMatches.filter(l=>l.keyword===o),i=t.keywordMatches.filter(l=>l.keyword===o),a=i.length-s.length;a<=0||r.push(...i.slice(0,a))}),r}var V_=e=>t=>n=>r=>{var c;if(r.type!==U_){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let s=t.getState(),i=s.styleSuggestions.list,a=(c=s.conversation)==null?void 0:c.current;if(o===i)return;let l=u9(o,i);r.type===U_&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var d9=cd({assistants:uC,auth:Bb,conversation:qb,contentTypes:dA,passwordlessToken:e_,entities:BA,handlingTime:F_,info:hE,input:iE,settings:fC,profile:yA,search:bE,styleSuggestions:EI,ui:dI,textSuggestions:XA});function W_(e){return Rb({reducer:d9,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(z_()).concat(B_({debounce:200})).concat(H_({debounce:500})).concat(V_(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,s)=>o.concat(s),n)},preloadedState:e.preloadedState})}function $_(e,t,n){if(t==="")return null;let r=new RegExp(`\\b${jm(t)}\\b`,"gi"),o,s=null;for(;(o=r.exec(e))!==null&&!(o.index>n);)s={start:o.index,end:o.index+o[0].length};return s}var f9=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},p9=e=>t=>n=>r=>{var l,c,u,f,d,p;let o=t.getState(),s=Vs("inlineSuggestions")(o),i=Vs("autoSelectSuggestion")(o)||s;switch(r.type){case Ki.toString():{!r.payload&&e.emit("logout",void 0);break}case Ad.fulfilled.toString():{e.emit("logout",void 0);break}case Er.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(l=o.conversation.current)==null?void 0:l.id,data:{entities:r.payload}});break;case Fs.toString():e.logSendMessage(r.payload);break;case af.toString():e.emit("call-to-action",{cue:r.payload});break;case Rn.fulfilled.toString():if(!r.isBroadcasted){let{externalConversationId:h,currentExternalIdAtRequest:y}=(c=r.payload)!=null?c:{};(!h||!y||h===y)&&e.broadcast(Th,r,!1)}break;case Rn.rejected.toString():break;default:break}let a=n(r);switch(r.type){case Fs.toString():e.handleAfterSendMessage(r.payload);break;case yu.toString():e.onUpdateShowTabHint(r.payload);break;case cg.toString():e.logHandlingTime();break;case Yi.toString():e.broadcast(Vd,r);break;case Ds.toString():e.broadcast(Vd,r);break;case lf.toString():t.dispatch(Ds({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{let h=o.assistants.cues.find(y=>y.code===r.meta.arg.data.assistantCode);e.emit("event",_(b({},r.meta.arg),{cue:h}));break}case Tn.toString():{let{start:h,end:y}=o.input.selection;e.emit("select-suggestion",_(b({type:f9(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:h,end:y}:{start:0,end:y}})),s&&t.dispatch(Uo([]));break}case bI.toString():{let{keyword:h,suggestion:y,eventMetrics:S}=r.payload,{text:m,selection:g}=o.input,v=$_(m,h,(u=g==null?void 0:g.end)!=null?u:m.length);if(!v)break;e.emit("select-suggestion",{text:y,type:"style",replace:v,suggestion:{text:y,source:"style"},eventMetrics:S});break}case Nd.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Uo.toString():{i&&r.payload.length>0&&t.dispatch(Dd(0));break}case Rn.fulfilled.toString():{let{evaluationId:h,output:y,externalConversationId:S}=r.payload,m=r.meta.arg.assistantCode;if(e.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:h,assistantCode:m,assistantOutput:oC(y),externalConversationId:S,evaluationStatus:"success"}}),!r.meta.arg.skipState){let g=t.getState().assistants.cues;e.emit("cues",g)}break}case Rn.rejected.toString():{let h=r.meta.arg.assistantCode,y=(p=r.meta.arg.externalConversationId)!=null?p:(d=t.getState().conversation.current)==null?void 0:d.externalId;e.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:"",assistantCode:h,assistantOutput:"",externalConversationId:y,evaluationStatus:"failed"}});break}default:break}return a},j_=p9;function dx(e){return e.toISOString().replace("T"," ").replace("Z","")}var m9=(e,t)=>t.version,K_=Yt([Xi,Vn,L_,m9],(e,t,n,r)=>{if(!t)return J.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:s}=n;return!o||!s?(J.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:dx(o),timeStop:dx(s)}});function G_(e,t){let{text:n,metrics:{numPaste:r,pastes:o,textSuggestions:s}}=e.input,i=n.length;return{source:"agent",clientVersion:t.version,pastes:o,lenTextTotal:i,numPastes:r,suggestions:s}}var Iu=class extends Error{};function g9(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var ug=class{constructor(){this.queues={}}push(t,n){let r=()=>{let s=this.queues[t][1];s?(this.queues[t]=[s.promise,null],s.resolve()):delete this.queues[t]};if(!this.queues[t]){let s=n().finally(r);return this.queues[t]=[s,null],s}this.queues[t][1]&&this.queues[t][1].reject(new Iu("Queued async function is outdated"));let o=g9();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};function fx(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return fx(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?fx(o,t):null}function px(e,t){return fx(e,t)}var h9={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},q_=(e,t)=>{var o,s,i;if(!((i=(s=(o=e.uiConfig)==null?void 0:o.widget)==null?void 0:s.types.find(a=>a.type==="cues"))==null?void 0:i.isActive))return J.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let r=e[h9[t]];if(r&&r.length>0){let a=r.map(l=>l.code);return e.summarizerAssistantNew&&t!=="ended"&&(a=a.filter(l=>l!==e.summarizerAssistantNew)),a}return J.warn(`No assistant set in profile for conversation event "${t}"`),[]};function y9(e){var t,n,r,o;return(o=(r=(n=(t=e.uiConfig)==null?void 0:t.widget)==null?void 0:n.types)==null?void 0:r.some(s=>s.type==="knowledge-assist"&&s.isActive))!=null?o:!1}function Y_(e){var n,r;return((r=(n=e.widgetInteractiveAssistants)==null?void 0:n.length)!=null?r:0)>0&&y9(e)?!0:!!e.knowledgeAssistantNew||!!e.knowledgeAssistant}function v9(e){return typeof e=="object"&&e!==null&&"tagName"in e}function dg(e){return v9(e)&&(Ri(e)||Wm(e))}var Q_,Xr=new Map,S9=["bottom","height","left","right","top","width"],X_=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:S9.some(n=>e[n]!==t[n]);function Z_(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,...Z_(t)]:[]}function J_(e,t){return!e||!t?null:_(b({},e),{top:e.top+t.top,left:e.left+t.left})}var fg=!1,eM=()=>{fg=!0;let e=[];if(Xr.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Xr.delete(n);return}let r=n.getBoundingClientRect();X_(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(J_,t.rect):t.rect;X_(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Xr.size===0){fg=!1;return}Q_=window.requestAnimationFrame(eM)};function mx(e,t){let n=Z_(e),r=[],o=n.map((s,i)=>mx(s,a=>{r[i]=a;let l=Xr.get(e);if(!l)return;let c=r.reduce(J_,l.rect);l.callbacks.forEach(u=>u(c))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),Xr.has(e)){let i=Xr.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else Xr.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!fg&&eM()},unobserve(){o.forEach(i=>i.unobserve());let s=Xr.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||Xr.delete(e),Xr.size||(cancelAnimationFrame(Q_),fg=!1)}}}}var tM,Qr=new Map,nM=()=>{Qr.forEach((e,t)=>{if(!t.isConnected){Qr.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(s=>s(e.visible)))}),Qr.size!==0&&(tM=window.requestAnimationFrame(nM))};function rM(e,t){return{observe(){let n=Qr.size===0;Qr.has(e)?Qr.get(e).callbacks.push(t):Qr.set(e,{visible:void 0,callbacks:[t]}),n&&nM()},unobserve(){let n=Qr.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Qr.delete(e),Qr.size||cancelAnimationFrame(tM)}}}}var gx=["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 hx(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function sl(e){return Number.parseFloat(e)}function pg(e){return Math.round(e*1e6)}function oM(e){return e/1e6}function yx(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=sl(e.width),s=sl(e.borderLeftWidth),i=sl(e.borderRightWidth),a=sl(e.paddingRight),l=oM(pg(o)-pg(s)-pg(i)),c=oM(pg(r));if(l-c>2){let u=l-c;n.style.paddingRight=`${a+u}px`}}function _u(e,t={}){var u,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(u=t.position)!=null?u:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",mi(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};hx(r,n,gx),yx(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=rM(e,()=>{hx(r,n,gx),yx(r,e,n),s(),setTimeout(s,0)}),a,l=!0,c=mx(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(hx(r,n,gx),yx(r,e,n),s(),t.placement==="below"&&n.classList.add("below"),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let p=t.closestScrollElement.getBoundingClientRect(),h=window.getComputedStyle(t.closestScrollElement),y=sl(h.borderTopWidth),S=sl(h.borderBottomWidth),m=p.top+y-d.top,g=d.top+d.height+-(p.top+p.height-S);n.style.clipPath=`inset(${m}px 0px ${g}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),c.observe(),i.observe(),[n,()=>{e.removeEventListener("scroll",s),c.unobserve(),i.unobserve(),n.remove()}]}function x9(e){return e.offsetParent!==null}function sM(e){if(!x9(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 mg(e,t,n=100){let r=sM(e);t({isVisible:r});let o=setInterval(()=>{let s=sM(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var iM=(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){J.warn("[Deepdesk] SessionStorage is blocked by browser")}}});var ke=E(A());var aM=iM("showTabHint",!0),il=class il{constructor({deepdeskUrl:t,version:n=il.version||"unknown",locale:r="en-US",token:o,fetch:s,productName:i,createCustomChannel:a,websocketClient:l=lg}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.disposeHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.belowSuggestions=null;this.floatingMenu=null;this.widgetElement=null;this.widgetRoot=null;this.nicknameDialogUnsubscribe=null;this.nicknameDialogFailed=!1;this.dynamicThunkObject={};this.queues=new ug;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;this.loadProfileConfigPromiseKey=null;this.personalCollectionSyncPendingKey=null;this.personalCollectionSyncDrainPromise=null;let c=t.replace(/\/api$/,"");this.deepdeskApi=new Lo(c,{token:o,fetch:s}),this.version=n,this.instanceId=il.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[j_({broadcast:(h,y,S)=>{this.broadcastEvents.send(h,y,S)},emit:(h,y)=>this.emit(h,y),handleAfterSendMessage:h=>this.handleAfterSendMessage(h),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:h=>this.logSendMessage(h),onUpdateShowTabHint:h=>aM.update(h),sendEvent:(h,y)=>this.deepdeskApi.sendEvent(h,y)})]};this.store=W_(u),this.broadcastEvents=new A_({debug:!0,deepdeskUrl:c,eventMap:EE(this.store),createCustomChannel:a}),this.disposeHandlers.push(()=>{this.broadcastEvents.cleanup()}),this.ws=new l({url:`${c}/api/v2/me/realtime`.replace("https","wss"),reconnectInterval:25e3,shouldReconnect:()=>M(this,null,function*(){var h;return(h=kt(this.state))!=null?h:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(yu(aM.value())),this.store.dispatch(jl({locale:r,adminUrl:c,productName:i}));let f=[],d=h=>{if(!h.conversationId)return;let y=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(lC(h))};this.hasConversation()?y():f.push(y)};this.ws.on("assistants::direct_response",d),this.ws.on("assistants::user_notification",d),this.ws.on("assistants::response_chunk",h=>{if(!h.conversationId)return;let y=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(aC(h))};this.hasConversation()?y():f.push(y)}),this.ws.on("assistants::suggest_as_reply",h=>{if(!h.conversationId)return;let y=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(Yi([{text:h.payload.message,type:"text",source:"assistant",assistantCode:h.code,sourceLabel:h.name}]))};this.hasConversation()?y():f.push(y)});let p=this.whenConversationLoaded(()=>{var h;this.broadcastEvents.setExternalId((h=this.state.conversation.current)==null?void 0:h.externalId),f.forEach(y=>y()),f.length=0});this.disposeHandlers.push(()=>{this.ws.cleanup(),f.length=0,p()})}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=Ns(this.state)[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}externalId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.externalId}shouldAbort(){return this.state.conversation.isSupported===!1?(J.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(J.warn("Profile has not been loaded (yet)"),!0):(J.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(t){if(kt(this.state))t();else{let n=this.subscribe(kt,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Ki(null)),this.store.dispatch(to()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return M(this,null,function*(){return(yield this.store.dispatch(to())).payload})}isConversationSupported(t,n){return M(this,null,function*(){return(yield this.store.dispatch(vh({externalId:t,options:n}))).payload})}createConversation(t){return M(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(Md(_(b({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}getConversationByExternalId(t,n){return M(this,null,function*(){return this.hasConversation()&&this.externalId()!==t&&this.resetConversation(),(yield this.store.dispatch(Ld({externalId:t,options:n}))).payload})}upsertConversation(t){return M(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(Sh(_(b({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return M(this,null,function*(){yield this.store.dispatch(xh(t))})}updateConversation(t){return M(this,null,function*(){return(yield this.store.dispatch(Od(t))).payload})}resetConversation(){this.store.dispatch(Ge()),this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(jl(t))}setVisitorInfo(t){this.store.dispatch(fE(t))}setCustomData(t){this.store.dispatch(pE(t))}setAgentInfo(t,n){return M(this,null,function*(){var o;yield this.store.dispatch(Tl(b(b({},t),n))),(o=this.state.info.agentInfo)!=null&&o.agentNickname||this.broadcastEvents.send(Ud,{showNicknameDialog:!0})})}setAgentSettings(t){return M(this,null,function*(){yield this.store.dispatch(bh(t))})}getAgentSettings(){return M(this,null,function*(){return(yield this.store.dispatch(Eh())).payload})}getMe(){return M(this,null,function*(){return this.deepdeskApi.getMe()})}refresh(){return M(this,null,function*(){if(this.shouldAbort())return Promise.resolve();let t=[];return t.push(this.refreshTextSuggestions()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}syncInputMediator(){this.inputMediator&&this.store.dispatch(Fd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()}))}notifyExternalSuggestion(t){this.store.dispatch(Tn(t))}evaluateAssistant(t,n){return M(this,null,function*(){var u;let{input:r={},attachments:o=[],transcript:s,showCuesInWidget:i=!0,includeMetadata:a,externalConversationId:l}=n||{},c=yield this.store.dispatch(Rn({assistantCode:t,attachments:o,transcript:s,includeMetadata:a,input:r,externalConversationId:l,skipState:!i}));if(c.error)throw new Error(`Assistant evaluation failed: ${(u=c.payload)!=null?u:c.error.message}`);return c.payload.output})}evaluateConversationAssistant(t,n){return M(this,null,function*(){var u,f,p;yield this.loadProfileConfig();let r=this.state.profile.data;if(!r&&((u=this.state.conversation.current)!=null&&u.profileCode)&&(yield this.loadProfileConfig(),r=this.state.profile.data),!r){J.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=q_(r,t),s=(f=n==null?void 0:n.showCuesInWidget)!=null?f:!0,d=n!=null?n:{},{showCuesInWidget:i}=d,a=ie(d,["showCuesInWidget"]),l=(p=n==null?void 0:n.externalConversationId)!=null?p:this.hasConversation()?this.externalId():"",c=yield Promise.all(o.map(h=>this.queues.push(h,()=>M(this,null,function*(){var S,m;let y=yield this.store.dispatch(Rn(b(_(b({assistantCode:h,includeMetadata:!0},a),{skipState:!s}),n!=null&&n.attachments&&(n==null?void 0:n.attachments.length)>0?{attachments:n==null?void 0:n.attachments}:{})));if(y.error)throw new Error(`Assistant evaluation failed: ${(S=y.payload)!=null?S:y.error.message}`);return{assistantCode:h,evaluationId:y.payload.evaluationId,output:y.payload.output,externalConversationId:(m=y.payload.externalConversationId)!=null?m:l}})).catch(y=>{if(y instanceof Iu)return J.warn(`Queued assistant "${h}" was outdated and dropped`),null;throw y})));if(!s)return c.filter(h=>h!==null)})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,autoSelectSuggestion:l,showTextSuggestions:c,suggestionsPlacement:u}=this.settings,f=a||l,d=u==="inline"||u==="below"?"below":"above",p=o.length>0;if(this.store.dispatch(Jb(wh(t))),!Gr(this.state)||t.key!=="Tab"&&!c)return;let h=()=>{n||!p||i&&(t.shiftKey||(this.store.dispatch(nE()),t.preventDefault()))},y=()=>{n||!p||f&&s<=0||i&&(t.shiftKey||(this.store.dispatch(rE()),t.preventDefault()))};switch(t.key){case"ArrowUp":d==="below"?y():h();break;case"ArrowDown":{d==="below"?h():y();break}case"Escape":{n||(this.store.dispatch(Dd(-1)),this.store.dispatch(Ss({collapse:!0})),this.store.dispatch(cI(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let S=qi(this.state);if(!S)return;this.store.dispatch(yu(!1)),this.store.dispatch(Tn({text:S.text,suggestion:S,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(f||this.state.input.selectedSuggestionIndex===-1)return;let S=qi(this.state);if(!S)return;this.store.dispatch(Tn({text:S.text,suggestion:S,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(f||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let S=qi(this.state);if(!S)return;this.store.dispatch(Tn({text:S.text,suggestion:S,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(Ss({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Uo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(J.info("Start handling time"),this.store.dispatch(N_()))}handlingTimeStop(){this.state.handlingTime.startTime&&(J.info("Stop handling time"),this.store.dispatch(cg()))}logSendMessage(t){let n=G_(this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEvent("Send Message",{conversationId:this.conversationId(),data:n}),this.emit("send-message-event",n))}logHandlingTime(){let t=K_(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(D_()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Fs((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(sE()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(s){J.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),J.error(s)}})}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(mE(t))}whenConversationLoaded(t){let n=()=>this.getConversationLoadedKey(),r=()=>{let s=n();s&&this.loadProfileConfig().then(()=>{if(n()!==s)return;let i=this.state.conversation.current,a=er(this.state);!(i!=null&&i.id)||i.profileCode&&(a==null?void 0:a.code)!==i.profileCode||t()})};return n()&&r(),this.subscribe(s=>this.getConversationProfileKey(s.conversation.current),s=>{s&&r()})}overlayContainerFactory(t,n,r,o){let[s,i]=_u(n,r);return s.setAttribute("translate","no"),s.dataset.testid=t,o&&s.classList.add(o),[s,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 s=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[l,c]=_u(s,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{c()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return mi(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),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),J.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()?(J.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(oE(r.metrics))):J.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(!dg(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i,inputMediator:a}=d,l=ie(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),c={customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),mi(t),this.inputMediator=a||(Ri(t)?new _i(t):new Ii(t)),this.inputMediator.on("change",({plainText:p,rawHTML:h,suggestionTextStart:y})=>{this.store.dispatch(Fd({text:p,html:h,suggestionTextStart:y}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(eE(wh(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:h})=>{this.store.dispatch(tE({text:p,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(Zb(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(zd(p))},500):this.store.dispatch(zd(p))}),this.unmountHandlers.push(()=>{clearTimeout(u)}),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(Om(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Om(!0))}),this.renderSuggestions(t,c),this.subscribe(Vs("inlineSuggestions"),()=>{this.renderSuggestions(t,c)}),this.subscribe(Vs("suggestionsPlacement"),()=>{this.renderSuggestions(t,c)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(Fd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()})),this.store.dispatch(zd(this.inputMediator.getSelection())),this.store.dispatch(Om(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{this.restoreMetrics(),this.syncInputMediator(),this.refreshTextSuggestions(),this.promptForNickname()}),this.isMounted=!0}promptForNickname(t){if(this.nicknameDialogUnsubscribe||this.nicknameDialogFailed)return;let n=this.createContainer("nickname-dialog",document.body);document.body.appendChild(n);let r=(0,Oo.createRoot)(n),o=null,s=a=>{o=a,i()},i=()=>{r==null||r.render((0,ke.jsx)(Ro,{store:this.store,children:(0,ke.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(kI,{id:"deepdesk-nickname-dialog",error:o,onSave:a=>M(this,null,function*(){try{yield this.store.dispatch(uE({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(Ud,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(l){J.error("Error setting agent nickname",l),s("error"),this.nicknameDialogFailed=!0}})})})}))};i(),this.nicknameDialogUnsubscribe=()=>{r.unmount(),n.remove(),this.nicknameDialogUnsubscribe=null}}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,s;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.belowSuggestions)==null||r.unmount(),(o=this.floatingMenu)==null||o.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(s=this.inputMediator)==null||s.dispose(),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(t=>t()),this.disposeHandlers=[],this.off()}renderSuggestions(t,n){var r,o,s,i;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(s=this.aboveSuggestions)==null||s.unmount(),(i=this.belowSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions||this.settings.suggestionsPlacement==="inline"?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.settings.suggestionsPlacement==="below"?this.belowSuggestions=this.renderAboveOrBelowSuggestions(t,n,"below"):this.aboveSuggestions=this.renderAboveOrBelowSuggestions(t,n,"above")}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret"),s=(0,Oo.createRoot)(o);s.render((0,ke.jsx)(Ro,{store:this.store,customStyles:r,children:(0,ke.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(CI,{})})}));let i=a=>{a?(o.style.display="block",o.style.top=`${a.top}px`,o.style.left=`${a.left}px`):o.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",i),s.unmount(),o.remove()}}}renderAboveOrBelowSuggestions(t,n,r){let{customStyles:o,closestScrollSelector:s,appendOverlayTo:i}=n,a=s&&px(t,s)||void 0,[l,c]=this.overlayContainerFactory("deepdesk-tab-completion",a||t,{appendTo:i,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},o==null?void 0:o.rootNode),[u,f]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||t,{appendTo:i,placement:r},o==null?void 0:o.suggestionsRootNode),d=(0,Oo.createRoot)(l);d.render((0,ke.jsx)(Ro,{store:this.store,customStyles:o,children:(0,ke.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(QI,{inputElement:t})})}));let p=(0,Oo.createRoot)(u);return p.render((0,ke.jsx)(Ro,{store:this.store,customStyles:o,children:(0,ke.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(NI,{onLogIn:()=>this.loginViaPopup().catch(h=>J.warn(h.message))})})})),{unmount(){d.unmount(),p.unmount(),c(),f()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:s,floatingMenuParent:i}=n,a=o&&px(t,o)||void 0,[l,c]=this.overlayContainerFactory("floating-menu",a||t,{appendTo:i!=null?i:s},r==null?void 0:r.floatingMenuParent),u=(0,Oo.createRoot)(l);return u.render((0,ke.jsx)(Ro,{store:this.store,customStyles:r,children:(0,ke.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(aI,{onLogIn:()=>this.loginViaPopup().catch(f=>J.warn(f.message))})})})),{unmount(){u.unmount(),c()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays"),o=(0,Oo.createRoot)(r);return o.render((0,ke.jsx)(Ro,{store:this.store,customStyles:n,children:(0,ke.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(nI,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&J.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:s,signInViaPopup:i,ssoUrl:a,openAdminFeedback:l}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:s,signInViaPopup:i});let c;if(a)try{c={url:new URL(a,this.settings.adminUrl).toString()}}catch(u){J.warn(`Invalid ssoUrl '${a}' passed to renderWidget`)}this.widgetRoot=(0,Oo.createRoot)(t),this.widgetRoot.render((0,ke.jsx)(Ro,{store:this.store,customStyles:r,children:(0,ke.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(mm,{report:u=>this.deepdeskApi.sendEvent(XP,{data:u}),children:(0,ke.jsx)(E_,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,openAdminFeedback:l,onLogIn:()=>this.loginViaPopup(c).catch(u=>J.warn(u.message))})})})}))}unmountWidget(){var t,n;(n=(t=this.widgetRoot)==null?void 0:t.unmount)==null||n.call(t),this.widgetRoot=null,this.widgetElement=null}renderKnowledgeAssistantWidget(t,n,r={}){let{customStyles:o,initialQuestion:s}=r,i=(0,Oo.createRoot)(n);return i.render((0,ke.jsx)(Ro,{store:this.store,customStyles:o,children:(0,ke.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(ix,{children:(0,ke.jsxs)(um,{assistantCode:t,initialQuestion:s,evaluateKnowledgeAssistFn:$l,children:[(0,ke.jsx)(Vi,{children:(0,ke.jsx)(fm,{title:r.title,emptyState:r.emptyState})}),(0,ke.jsx)(sx,{children:(0,ke.jsx)(dm,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(t){let n=mg(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){pm(t)&&t.message==="Unauthorized"&&this.login()}getConversationProfileKey(t){var n;if(t!=null&&t.id)return`${t.id}:${(n=t.profileCode)!=null?n:""}`}getProfileLoadKey(){var n;let t=this.state.conversation.current;return t!=null&&t.profileCode&&(n=this.getConversationProfileKey(t))!=null?n:null}isCurrentProfileLoadKey(t){return this.getProfileLoadKey()===t}getConversationLoadedKey(){return this.getConversationProfileKey(this.state.conversation.current)}resetProfileDerivedSettings(){this.store.dispatch(SS()),this.store.dispatch(jl(ty))}syncPersonalCollectionForConversation(t){this.personalCollectionSyncPendingKey=t,this.ensurePersonalCollectionSyncDrain()}ensurePersonalCollectionSyncDrain(){return this.personalCollectionSyncDrainPromise?this.personalCollectionSyncDrainPromise:(this.personalCollectionSyncDrainPromise=this.drainPersonalCollectionSync().finally(()=>{this.personalCollectionSyncDrainPromise=null,this.personalCollectionSyncPendingKey&&this.ensurePersonalCollectionSyncDrain()}),this.personalCollectionSyncDrainPromise)}drainPersonalCollectionSync(){return M(this,null,function*(){for(;this.personalCollectionSyncPendingKey;){let t=this.personalCollectionSyncPendingKey;if(this.personalCollectionSyncPendingKey=null,!this.isCurrentProfileLoadKey(t))continue;let n=this.state.conversation.current,r=n==null?void 0:n.id;if(!(!r||!n.profileCode))try{yield this.deepdeskApi.syncPersonalCollection(r)}catch(o){this.isCurrentProfileLoadKey(t)&&J.warn("Failed to sync personal collection for profile",o)}}})}loadProfileConfig(t=!0){let n=this.getProfileLoadKey();if(!n)return this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null,this.resetProfileDerivedSettings(),Promise.resolve();let r=this.state.conversation.current,o=er(this.state);if(o&&o.code!==(r==null?void 0:r.profileCode)&&(this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null,this.resetProfileDerivedSettings()),this.loadProfileConfigPromise&&this.loadProfileConfigPromiseKey===n)return this.loadProfileConfigPromise;this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=n;let s=Promise.resolve().then(()=>M(this,null,function*(){try{yield this.store.dispatch(eu()).unwrap()}catch(l){if(l===Ga)return this.loadProfileConfigPromise===s&&(this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null),t&&this.isCurrentProfileLoadKey(n)&&!er(this.state)?this.loadProfileConfig(!1):void 0;throw l}if(!this.isCurrentProfileLoadKey(n))return;let i=er(this.state),a=this.state.conversation.current;!i||i.code!==(a==null?void 0:a.profileCode)||(this.store.dispatch(jl({showSearch:i.search,showImageSearch:i.imageSearch,showEntitiesCommand:i.entitiesCommand,showSummaryCommand:!!i.summarizerAssistantNew,showKnowledgeSearch:Y_(i),recommendTextSuggestions:i.recommendTextSuggestions})),this.syncPersonalCollectionForConversation(n))})).finally(()=>{this.loadProfileConfigPromise===s&&(er(this.state)||(this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null))});return this.loadProfileConfigPromise=s,s}loginViaPopup(t){return M(this,null,function*(){return new Promise((n,r)=>{this.store.dispatch(Id());let o=new MessageChannel,s=o.port1,i=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,c=()=>{u&&!u.closed&&u.close(),window.removeEventListener("message",f),clearInterval(d)};s.onmessage=p=>M(this,null,function*(){var h,y;if((h=p.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((y=p.data)==null?void 0:y.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Rl),l=!0,o.port1.close(),n()}catch(S){console.error(S),r(S)}finally{l=!0,c()}});let u=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");if(u===null){r(new Error("Popup blocked by browser"));return}let f=p=>M(this,null,function*(){var h;if(!(p.origin!==a.origin||p.source!==u))switch((h=p.data)==null?void 0:h.type){case"deepdesk-popup-request-origin":{try{let y=JSON.stringify({type:"deepdesk-popup-parent-origin"});u.postMessage(y,a.origin)}catch(y){J.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-loaded":{try{let y=JSON.stringify({type:"deepdesk-popup-create-channel"});u.postMessage(y,a.origin,[o.port2])}catch(y){J.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-error":{if(c(),p.data.message==="Platform account url mismatch"){let y="Please contact your administrator: The page that opened the popup is not a trusted origin.";J.warn(y),this.store.dispatch(mh(y)),r(new Error(y));return}if(p.data.message==="Timeout"){let y="Please contact your administrator: Popup timed out. Check if the account's platform.url or account.url is configured correctly.";J.warn(y),this.store.dispatch(mh(y)),r(new Error(y));return}r(new Error(p.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{u&&!u.closed||(c(),l||r(new Error("Popup closed by user")))},200);this.disposeHandlers.push(c)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}refreshTextSuggestions(){return M(this,null,function*(){this.isMounted&&(yield this.store.dispatch(_m()))})}refreshWidgetSuggestions(){return M(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=tu(this.state);try{n.forEach(({type:r})=>{switch(r){case"entities":this.store.dispatch(Er());break;case"pinned-messages":case"sticky-messages":break;default:sd.includes(r)||this.store.dispatch(Cr(r))}})}catch(r){this.handleError(r)}})}};il.version="19.6.2-beta.8",il.count=0;var Mu=il;function w9(e){return M(this,null,function*(){var o,s,i;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(i=(s=e.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function lM(e,t){return M(this,null,function*(){let n=yield w9(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 cM(e,t,n){return M(this,null,function*(){yield new Lo(e).authenticateWithKey(t,n)})}function uM(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function dM(r,o){return M(this,arguments,function*(e,t,n={}){var f,d;let{value:s}=e,{start:i,end:a}=(f=n.replace)!=null?f:{start:0,end:s.length},l=`${s.slice(0,i)}${t}${s.slice(a)}`,c=(d=n.selectionAfter)!=null?d:{start:i+t.length,end:i+t.length},u=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(u()).then(()=>{e.selectionStart=c.start,e.selectionEnd=c.end,e.blur(),e.focus()})})}function fM(r,o){return M(this,arguments,function*(e,t,n={}){let s=n.replace?Cs(e,n.replace.start,n.replace.end):rl(e),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?t.split(`
84
84
  `).reverse().forEach((l,c)=>{c>0&&s.insertNode(document.createElement("br")),s.insertNode(document.createTextNode(l))}):s.insertNode(document.createTextNode(t))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let l=n.selectionAfter?Cs(e,n.selectionAfter.start,n.selectionAfter.end):(s.collapse(!1),s),c=window.getSelection();c==null||c.removeAllRanges(),c==null||c.addRange(l)}if(!i)return;i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}function b9(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 E9(e){let t=document.createDocumentFragment();return e.split(`
85
85
  `).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},s=0;for(;o=n.slice(s).match(/(\[([^\]]+)])\(([^)]+)\)/);){let i=document.createElement("a");i.href=o[3],i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),i.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(s,s+o.index))),t.appendChild(i),s=s+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(s)))}),t}function pM(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):pM(n,t)}function mM(o,s){return M(this,arguments,function*(e,t,{isBlock:n,isHTML:r}={}){let i;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,c=l.getSelection();if((!c||c.rangeCount===0)&&(e.focus(),c=l.getSelection()),!c||c.rangeCount===0)return;let u=c.getRangeAt(0);if(!u)return;i=document.createElement("span"),u.insertNode(i);let f=r?b9(t):E9(t);n?pM(u.startContainer,f):(u.insertNode(f),u.collapse(!1))};return Promise.resolve(a()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!i)try{i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}return FM(C9);})();
86
86
  /*! Bundled license information:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepdesk/deepdesk-sdk",
3
- "version": "19.6.2-beta.7",
3
+ "version": "19.6.2-beta.8",
4
4
  "description": "Deepdesk SDK",
5
5
  "author": "Lukas Batteau",
6
6
  "license": "ISC",