@deepdesk/deepdesk-sdk 19.3.1-beta.0 → 19.3.2-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.iife.js +1 -1
- package/package.json +1 -1
package/dist/index.iife.js
CHANGED
|
@@ -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 Y0=E(P()),m5={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},HP=({className:e,color:t})=>(0,Y0.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,Y0.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:m5[t||"pink"]})});var BP={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedIn:"dd-XvHAn",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var X0={};yt(X0,{enUS:()=>g5,nlNL:()=>h5});var g5={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},h5={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var vi=E(P()),VP=({onLogIn:e})=>{let t=ie(X0),n=X("floatingMenu"),r=X("productName"),o=be(),s=G(Rt),i=O("FloatingMenu",BP);if(s===null||n===!1)return null;let a=()=>{s===!0?o(tr(!0)):e()};return(0,vi.jsxs)("button",{type:"button",className:(0,UP.default)(i.root,{[i.isLoggedIn]:s,[i.isLoggedOut]:!s}),onClick:a,children:[(0,vi.jsx)("div",{className:i.text,children:t(s?"search":"signin",{productName:r})}),(0,vi.jsxs)("div",{className:i.icon,children:[(0,vi.jsx)(HP,{className:i.logo,color:"pink"}),s===!1&&(0,vi.jsx)(zP,{className:i.lock})]})]})};var cm=E(Z());function Ur(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 y5={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1},nm=({ui:e})=>e.overlayCollapsed,jP=Re({name:"ui",initialState:y5,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:ou,setInputFocus:rm,setOverlayCollapsed:hs,setOpenOverlayWhenTyping:WP,setOverlayCollapsedUserOverwrite:$P}=jP.actions,KP=jP.reducer;var GP={styleRow:"dd-prYfH",styleSuggestion:"dd-JTmXy"};var su=E(P()),v5=({match:e,selected:t,styles:n})=>(0,su.jsx)(de,{as:"button",selected:t,className:n.styleRow,"data-testid":"style-suggestion-item",title:e.suggestion,children:(0,su.jsx)("span",{className:n.styleSuggestion,children:e.suggestion})}),S5=({matches:e,selectedIndex:t})=>{let n=O("StyleSuggestionList",GP);return(0,su.jsx)(Ct,{children:e.map((r,o)=>(0,su.jsx)(v5,{match:r,selected:t===o,styles:n},`${r.keyword}-${o}`))})},om=S5;var JP=E(Z());var ys=E(Z());var qP=E(Z());function YP(e,t,n){(0,qP.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var XP={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 iu=E(P()),QP=({title:e})=>(0,iu.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18px",height:"18px",viewBox:"0 0 24 24","aria-labelledby":"closeTitle",children:[(0,iu.jsx)("title",{id:"closeTitle",children:e}),(0,iu.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 Q0={};yt(Q0,{enUS:()=>x5,nlNL:()=>w5});var x5={assistant:[{type:0,value:"Assistant"}],close:[{type:0,value:"Close"}]},w5={assistant:[{type:0,value:"Assistent"}],close:[{type:0,value:"Sluiten"}]};var Ln=E(P()),E5=["search","personal-collection-search","search-autocomplete"];function C5(e,t,n,r={}){var s;let o="";return E5.includes(t)?o=lP(U0(e,n,{stripAgentPart:!0}),(s=r.searchKeywords)!=null?s:[n]):o=U0(e,n,r),r.placeholders===!0&&(o=cP(o)),o}var T5=()=>{},k5=({selected:e,suggestion:t})=>{let n=ie(Q0),r=X("inlineSuggestions"),o=G(_s),[s,i]=(0,ys.useState)(!1),a=X("enableSuggestionFeedback"),l=G(S=>S.input.text),c=be(),u=O("TextSuggestion",XP),f=(0,ys.useRef)(null),d=t.source==="assistant",p=a&&!d;(0,ys.useEffect)(()=>{let S=setTimeout(()=>{c(eb({text:t.text,suggestion:t}))},500);return()=>{clearTimeout(S)}},[t]),YP(f,"click",()=>{c(Cn({suggestion:t,text:t.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let h=()=>{c(Ns({source:t.source,text:t.text,assistantCode:t.assistantCode}))},g=(0,ys.useMemo)(()=>C5(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,Ln.jsxs)("div",{className:u.root,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:[(0,Ln.jsx)(de,{ref:f,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:T5,children:t.source==="assistant"?(0,Ln.jsxs)("div",{className:u.assistantContainer,children:[(0,Ln.jsx)(ms,{containerTagName:"div",tagName:"span",className:u.formattedTextTruncated,content:g}),(0,Ln.jsx)("span",{className:u.assistantBadge,children:n("assistant")})]}):(0,Ln.jsx)(ms,{containerTagName:"div",tagName:"span",className:u.formattedText,content:g})}),p&&s&&(0,Ln.jsx)("div",{className:u.actions,children:(0,Ln.jsx)(Zp,{source:"overlay",context:l,suggestion:t})}),d&&s&&(0,Ln.jsx)("div",{className:u.closeIconContainer,children:(0,Ln.jsx)("button",{type:"button",className:u.closeIcon,onClick:h,title:n("close"),children:(0,Ln.jsx)(QP,{title:n("close")})})})]})},ZP=k5;var eI=E(P()),R5=({suggestions:e,selectedIndex:t,reverse:n})=>(0,JP.useMemo)(()=>{let o=e.map((s,i)=>(0,eI.jsx)(ZP,{index:i,selected:i===t,suggestion:s},`${s.text}-${s.source}`));return n?o.reverse():o},[e,t,n]),sm=R5;var tI={root:"dd-PfvRI",paper:"dd-HYlyY"};var im={list:{keywordMatches:[]},fetchState:"idle"},am=e=>e.styleSuggestions.list,Si=me("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 im.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),nI=Re({name:"styleSuggestions",initialState:im,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(Si.pending,t=>{t.fetchState="loading"}).addCase(Si.rejected,t=>{t.fetchState="error"}).addCase(Si.fulfilled,(t,n)=>{t.fetchState="done",Oo(t.list,n.payload)||(t.list=n.payload)}).addCase(Ls,t=>{t.list=im.list}).addCase(lt,()=>im)}}),{commitStyleSuggestion:rI}=nI.actions,oI=nI.reducer;var lm=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 xi=E(P()),P5=()=>{var S;let e=(0,cm.useRef)(null),t=O("InlineSuggestionsOverlay",tI),n=G(Ur),r=be(),o=G(Rt),s=G(zi),i=G(nm),a=X("showTextSuggestions"),l=G(Ms),c=G(gl),u=X("showStyleSuggestions"),f=X("showStyleSuggestionList"),d=G(am),p=u&&f?lm((S=d.keywordMatches)!=null?S:[]):[],h=p.length>0,g=a&&l.length>0;return ls(()=>{setTimeout(()=>{r(hs({collapse:!0,skipWhenInputFocus:!0}))})}),(0,cm.useEffect)(()=>{let y=e.current;if(!y||!y.parentElement)return;y.parentElement.style.left="0px";let m=y.getBoundingClientRect();y.parentElement.style.left=`${Math.min(window.innerWidth-4-m.right,0)}px`}),i||o!==!0||s===!1||!n&&!h||!g&&!h?null:(0,xi.jsx)("div",{className:t.root,"data-variant":"inline",children:(0,xi.jsxs)("div",{ref:e,className:t.paper,children:[h&&(0,xi.jsx)(om,{matches:p,selectedIndex:-1}),g&&(0,xi.jsx)(Ct,{children:(0,xi.jsx)(sm,{suggestions:l,selectedIndex:c})})]})})},sI=P5;var vs=E(Z());var iI={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 Z0={};yt(Z0,{enUS:()=>I5,nlNL:()=>A5});var I5={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."}]},A5={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 ft=E(P()),aI=({onClose:e,onSave:t,id:n,error:r})=>{let[o,s]=(0,vs.useState)(""),[i,a]=(0,vs.useState)(!1),[l,c]=(0,vs.useState)(!1),u=O("Nickname",iI),f=vs.default.useRef(null),d=G(y=>y.info.showNicknameDialog),p=ie(Z0),h=X("adminUrl");(0,vs.useEffect)(()=>{r&&a(!0)},[r]);let g=()=>{if(!f.current)return;o.trim()?f.current.setCustomValidity(""):f.current.setCustomValidity(p("nicknameDialogError")),f.current.reportValidity()},S=y=>{y.preventDefault();let m=o.trim(),v=y.currentTarget.querySelector("#nickname-input");if(!m){v.setCustomValidity(p("nicknameDialogError")),v.reportValidity();return}v.setCustomValidity(""),t(m)};return(0,ft.jsxs)(Ha,{isOpen:d,"datatest-id":n,onClose:e||(()=>{}),onBack:e||(()=>{}),children:[(0,ft.jsx)("div",{className:u.titleWrapper,children:(0,ft.jsx)("h1",{className:u.title,children:p("title")})}),(0,ft.jsxs)("form",{className:u.dialogContent,onSubmit:S,children:[(0,ft.jsx)("p",{children:p("nicknameDialogTitle")}),i&&r&&(0,ft.jsx)("div",{className:u.errorMessage,children:h?(()=>{let y=p("nicknameDialogSaveError",{account:h}),m=`${h}.deepdesk.com/admin/user-settings`,v=y.indexOf(m);if(v!==-1){let x=y.substring(0,v),C=y.substring(v+m.length);return(0,ft.jsxs)(ft.Fragment,{children:[x,(0,ft.jsx)("a",{href:m,target:"_blank",rel:"noopener noreferrer",className:u.errorLink,children:m}),C]})}return y})():p("nicknameDialogSaveErrorWithoutLink")}),(0,ft.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:y=>{c(new RegExp("\\p{Extended_Pictographic}","u").test(y.target.value)),s(y.target.value)},onBlur:g,ref:f}),l&&(0,ft.jsx)("div",{className:u.errorMessage,role:"alert",children:p("nicknameDialogEmojiError")}),(0,ft.jsxs)("div",{className:u.buttonsWrapper,children:[r?(0,ft.jsx)("div",{className:u.closeButtonWrapper,children:(0,ft.jsx)("button",{type:"button",className:u.closeButton,onClick:()=>e==null?void 0:e(),children:p("close")})}):null,(0,ft.jsx)("div",{className:u.buttonContinueWrapper,children:(0,ft.jsx)("button",{type:"submit",className:u.continueButton,disabled:!o.trim()||new RegExp("\\p{Extended_Pictographic}","u").test(o),children:p("nicknameDialogContinueButton")})})]})]})]})};var au=E(P()),_5=({children:e})=>{let n=X("locale").replace("-","");return(0,au.jsx)(th.Provider,{value:n,children:e})},M5=({store:e,customStyles:t={},children:n})=>(0,au.jsx)(ew,{store:e,children:(0,au.jsx)(_5,{children:(0,au.jsx)(ol.Provider,{value:t,children:n})})}),bo=M5;var dm=E(De()),Wa=E(Z());var lI=E(Z());function cI(e,t){let[n,r]=(0,lI.useState)(()=>{if(typeof window=="undefined")return t;try{let s=window.localStorage.getItem(e);return s?JSON.parse(s):t}catch(s){return ee.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){ee.error(i)}}]}var uI=()=>/Mac/i.test(navigator.platform);var fI=E(De()),Eo=E(Z());var J0={};yt(J0,{enUS:()=>N5,nlNL:()=>L5});var N5={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"}]}]},L5={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 dI={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};var Ss=E(P()),eS=(e,t,n)=>r=>(0,Ss.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),O5=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r,onLogIn:o})=>{let s=ie(J0),i=dn(),a=O("Login",dI),l=X("productName"),c=(0,Eo.useCallback)(S=>{S.preventDefault(),r&&r(Number.parseInt(S.target.value,10))},[]),u=(0,Eo.useCallback)(S=>{S.preventDefault(),i.send(ji,!0)},[t]),f=(0,Eo.useMemo)(()=>S=>(0,Ss.jsx)("a",{onClick:m=>{m.preventDefault(),o()},href:t,className:a.anchor,target:"_blank",rel:"noreferrer",children:S},"login"),[t]),d=(0,Eo.useCallback)(S=>(0,Ss.jsx)("button",{type:"button",className:a.anchorButton,onClick:u,children:S},"prompt"),[u]),{min:p,hour:h,day:g}=(0,Eo.useMemo)(()=>({min:eS(a,600,c),hour:eS(a,3600,c),day:eS(a,3600*12,c)}),[]);return(0,Ss.jsxs)("div",{className:(0,fI.default)(e,a.root),children:[s("loginPlease",{login:n?d:f,productName:l}),r&&(0,Ss.jsxs)(Eo.Fragment,{children:[(0,Ss.jsx)("br",{}),s("snooze",{min:p,hour:h,day:g})]})]})},um=O5;var pI={root:"dd-DoQhb",text:"dd-Jwnev"};var lu=E(P()),D5=({title:e})=>{let t=O("SearchTrigger",pI),n=be(),r=Ze();return(0,lu.jsxs)("button",{type:"button",className:t.root,onClick:()=>{n(tr(!0)),r("open search",{via:"autocomplete-overlay"})},children:[(0,lu.jsx)(Va,{}),(0,lu.jsx)("span",{className:t.text,children:e})]})},mI=D5;var tS={};yt(tS,{enUS:()=>F5,nlNL:()=>z5});var F5={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"}]},z5={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 gI={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(P()),H5=({onLogIn:e})=>{var U;let t=O("SuggestionsOverlay",gI),n=ie(tS),r=G(Ur),o=G(Jw),s=be(),i=(0,Wa.useRef)(null),a=X("searchTriggerKey"),l=X("productName"),c=G(nm),u=G(Rt),f=G(Uw),d=G(zi),[p,h]=(0,Wa.useState)(null),g=X("showSearch"),S=X("showTextSuggestions"),y=X("adminUrl"),m=X("isEmbedded"),v=X("suggestionsPlacement"),[x,C]=cI("dd-snooze-until-ms",0),T=c||x>Date.now(),k=G(Ms),A=G(gl),H=X("showStyleSuggestions"),D=X("showStyleSuggestionList"),B=G(am),J=H&&D?lm((U=B.keywordMatches)!=null?U:[]):[],Y=J.length>0,_=k.filter(N=>N.source!=="gpt").length,V=()=>{T&&C(0),s($P(!T))},z=N=>{let q=Date.now()+N*1e3;C(q),ee.info(`Snooze until: ${new Date(q)}`),s(hs({collapse:!0}))};return(0,Wa.useEffect)(()=>{_===0&&h(null)},[k,_]),ls(()=>{s(hs({collapse:!0,skipWhenInputFocus:!0}))}),u===null||d===!1?null:u===!1?(0,Me.jsxs)("div",{ref:i,className:(0,dm.default)(t.root,{[t.isCollapsed]:T}),children:[!T&&(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)(ks,{className:t.toggleButton,title:n("collapse"),onClick:V,isCollapsed:!1})})]}),(0,Me.jsx)("div",{className:t.toggleButtonWrapper,children:(0,Me.jsx)(ks,{className:t.toggleButton,title:n("open",{productName:l}),onClick:V,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(td()),"aria-label":n("dismissError"),children:n("dismiss")})]}),(0,Me.jsx)(um,{loginUrl:y,isEmbedded:m,onLogIn:e,onSnooze:z})]})]}):!o||!r&&!Y?null:(0,Me.jsxs)("div",{ref:i,className:(0,dm.default)(t.root,{[t.isCollapsed]:T}),children:[!T&&(0,Me.jsxs)("div",{className:t.triggers,children:[(0,Me.jsx)("div",{style:{flex:1},children:g&&(0,Me.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>h(n(uI()?"searchHintMac":"searchHintWindows",{searchTriggerKey:a.toUpperCase()})),onMouseLeave:()=>h(null),children:(0,Me.jsx)(mI,{title:n("search")})})}),(0,Me.jsxs)("div",{className:t.triggersRight,onFocus:()=>{},children:[(0,Me.jsx)("div",{className:(0,dm.default)(!p&&t.hintsHidden,t.hints),children:p}),(0,Me.jsx)(ks,{className:t.toggleButton,title:n("collapse"),onClick:V,isCollapsed:!1})]})]}),(0,Me.jsx)("div",{className:t.toggleButtonWrapper,children:(0,Me.jsx)(ks,{className:t.toggleButton,title:n("open",{productName:l}),onClick:V,isCollapsed:!0})}),(Y||_>0&&S)&&(0,Me.jsxs)("div",{className:t.collapsible,onFocus:()=>{},children:[Y&&(0,Me.jsx)(om,{matches:J,selectedIndex:-1}),_>0&&S&&(0,Me.jsx)(Ct,{children:(0,Me.jsx)(sm,{suggestions:k,selectedIndex:A,reverse:v==="above"})})]})]})},hI=H5;var Cm=E(De());var ko=E(Z());var $a=E(Z());function fm(e){return e.contentEditable==="true"}function B5(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 yI(e){let{selectionStart:t,selectionEnd:n}=fm(e)?B5(e):e;return[t,n]}function vI(e){let[,t]=(0,$a.useState)(),n=(0,$a.useRef)(null);return n.current=yI(e),(0,$a.useEffect)(()=>{let r=()=>{var a;let[o,s]=(a=n.current)!=null?a:[],i=yI(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 SI(e,t){if(!t)return;let n=e,{value:r}=n,[o,s]=t,i=r.match(Hu);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 xI=E(Z()),U5=["div","span","mark","strong","b","i","u","em"];function nS(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(U5.includes(o)){let i=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,xI.cloneElement)(r,{children:nS(i,t,n+1)})]}return[...e,...t]}function wi(e){return e.tagName.toLowerCase()==="textarea"}var wI={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 TI=E(De());var Sm=E(Z());var Ka=E(Z());function bI(e,t){let n;return[(...r)=>{window.cancelAnimationFrame(n);let o=t?t(...r):r;n=window.requestAnimationFrame(()=>{e(...o)})},()=>window.cancelAnimationFrame(n)]}function pm(e){let t=(0,Ka.useRef)(null),[n,r]=(0,Ka.useState)(!1);return(0,Ka.useEffect)(()=>{var u;let o=!1,s=Number.parseFloat((u=window.getComputedStyle(document.body).zoom)!=null?u:"1"),[i,a]=bI((f,d)=>{let p=t.current;if(!p)return;let h=f/s,g=d/s,S=p.getBoundingClientRect(),y=h>S.x&&h<S.x+S.width&&g>S.y&&g<S.y+S.height;y&&!o?(o=!0,r(!0)):!y&&o&&(o=!1,r(!1))},({clientX:f,clientY:d})=>[f,d]),[l,c]=bI(()=>{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 mm(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function gm(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function EI(e){return e!=null}var CI=E(De()),hm=E(Z());var Co={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 rS=E(P()),ym=(0,hm.forwardRef)((o,r)=>{var s=o,{className:e,children:t}=s,n=se(s,["className","children"]);let i=(0,hm.useRef)(null),a=O("TabCompletion",Co);return(0,rS.jsx)("div",I(b({ref:gm([i,r]),className:(0,CI.default)(e,a.popoverContentContainer)},n),{children:(0,rS.jsx)("div",{className:a.popoverContent,children:t})}))});var xs=E(P()),V5=e=>t=>{let n=Vv(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},j5=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let s=O("TabCompletion",Co),i=ip(),a=(0,Sm.useMemo)(()=>V5(e.getBoundingClientRect()),[e]),[l,c]=pm(e);return(0,Sm.useEffect)(()=>{c?i.open():i.close()},[c]),(0,xs.jsxs)("span",{children:[(0,xs.jsx)("mark",{ref:gm([l,i.triggerRef]),className:(0,TI.default)(s.matchKeyword,{[s.hover]:c}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:r}),i.opened&&(0,xs.jsx)(Ea,{className:s.popover,triggerRef:i.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,xs.jsx)(ym,{style:n,children:(0,xs.jsx)("div",{className:s.hintText,children:o})})})]})},vm=class extends So{constructor(){super(...arguments);this.keywordMatches=[];this.preparedKeywordMatches=[];this.usedKeywordMatches=new Set}onBeforeParse(n,r){return r.keywordMatches&&r.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=r.keywordMatches.map(o=>I(b({},o),{keywordRegex:new RegExp(`\\b${mm(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(EI);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,xs.jsx)(j5,{inputElement:r.inputElement,suggestion:r.suggestion,inputStyle:r.inputStyle,boundaryRef:r.boundaryRef,children:n},`keyword_${r.matchString}_${r.key}`)}asTag(){return"mark"}};var kI=E(De());var oS=E(P()),W5=({inputElement:e,children:t})=>{let n=O("TabCompletion",Co),[r,o]=pm(e);return(0,oS.jsx)("mark",{ref:r,className:(0,kI.default)(n.matchPlaceholder,{[n.hover]:o}),children:t})},xm=class extends So{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,oS.jsx)(W5,{inputElement:n.inputElement,children:t},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var bm=E(De());var sn=E(Z());var sS=E(P()),RI=()=>(0,sS.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,sS.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 Vr=E(Z());var II=E(_0());var PI={root:"dd-ky-Bv",content:"dd-kV5e1"};function wm(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 iS(e){return e.replace("https://www.","").replace("https://","")}var qn=E(P()),$5=3,K5=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),G5=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=$5})=>{let s=O("LinkSearch",PI),[i,a]=(0,Vr.useState)(""),l=be(),c=G(PP("url")),u=G(Eb("URL")),f=(0,Vr.useMemo)(()=>u.map(K5),[u]),[d,p]=(0,Vr.useState)(f.length-1),h=X("fallbackImage"),g=v=>{let x=v.target;a(x.value)},S=(v,x)=>{v.stopPropagation(),v.preventDefault(),window.open(x,"_blank")},y=v=>{var T;let x=d-1<0?f.length-1:d-1,C=d+1===f.length?0:d+1;v.code==="Escape"&&(a(""),t()),v.code==="ArrowUp"&&p(x),v.code==="ArrowDown"&&p(C),v.code==="Enter"&&e(((T=f[d])==null?void 0:T.text)||i)},m=(0,Vr.useCallback)((0,II.default)(v=>{l(Os({query:v,type:"URL",tags:["link-search"]}))},300),[]);return(0,Vr.useEffect)(()=>{i&&m(i)},[i]),(0,Vr.useEffect)(()=>()=>{l(dd())},[]),(0,qn.jsxs)("div",{className:s.root,children:[(0,qn.jsx)(Ct,{withDivider:!0,children:(i?f:c).slice(0,o).map((v,x)=>(0,qn.jsx)(de,{selected:d===x,onClick:()=>e(v.text),"data-testid":"linksearch-suggestion",children:(0,qn.jsxs)(Se,{children:[(0,qn.jsx)(Se.Image,{src:wm(v,"small",h||void 0),title:v.title||v.text}),(0,qn.jsxs)(Se.Content,{className:s.content,cropText:!0,children:[(0,qn.jsx)(Se.Title,{children:v.title||iS(v.text)}),v.title&&iS(v.text)]}),(0,qn.jsx)(de.Actions,{children:(0,qn.jsx)(de.ActionButton,{label:r,onClick:C=>S(C,v.text)})})]})},v.text))}),(0,qn.jsx)(Bc,{value:i,onChange:g,autoFocus:!0,placeholder:n,onKeyUp:y})]})},AI=G5;var aS={};yt(aS,{enUS:()=>q5,nlNL:()=>Y5});var q5={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"}]},Y5={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 Lt=E(P()),X5=(0,sn.forwardRef)((e,t)=>{let n=O("TabCompletion",Co);return(0,Lt.jsx)("mark",{ref:t,className:(0,bm.default)(n.matchSelection)},"selection-start")}),Q5=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let s=ie(aS),i=O("TabCompletion",Co),a=X("addToPersonalCollection"),l=G(zo("/admin/personal-collection/new")),c=(0,sn.useRef)(null),u=(0,sn.useRef)(null),[f,d]=(0,sn.useState)(null),p=be(),h=ip(document.activeElement===r),[g]=(0,sn.useState)(()=>document.createRange());h.triggerRef.current=g,(0,sn.useEffect)(()=>()=>g.detach(),[]),(0,sn.useEffect)(()=>{let y=e.current,m=c.current;!y||!m||(g.setStart(y,0),g.setEnd(m,0))},[e.current,c.current]),ls(()=>{h.close()});let S=(0,sn.useCallback)(y=>{let m=g.toString(),v=/^http(s?):\/\//.test(y)?y:`https://${y}`,x=`[${m}](${v})`;p(Cn({text:x,suggestion:{text:x,source:"search-url",type:"url"},eventMetrics:{inputType:"mouse"},replace:"selection"}))},[]);return(0,Lt.jsxs)("span",{children:[(0,Lt.jsx)("mark",{ref:c,className:(0,bm.default)(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":h.opened?"true":"false",children:o}),h.opened&&(0,Lt.jsx)(Ea,{className:i.popoverRoot,triggerRef:h.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,Lt.jsxs)(ym,{style:n,ref:u,children:[(0,Lt.jsxs)("div",{className:(0,bm.default)(i.selectionOptions,{[i.selectionOptionsIsHidden]:f!==null}),children:[(0,Lt.jsxs)("button",{type:"button",tabIndex:f===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>d("insertLink"),children:[(0,Lt.jsx)(RI,{}),(0,Lt.jsx)("span",{children:"\xA0"}),(0,Lt.jsx)("span",{children:s("insertLink")})]}),a&&l&&(0,Lt.jsx)("button",{type:"button",tabIndex:f===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>{let y=g.toString(),m=`${l}?text=${encodeURIComponent(y)}`;window.open(m,"_blank")},children:(0,Lt.jsx)("span",{children:s("addToPersonalCollection")})})]}),f==="insertLink"&&(0,Lt.jsx)(AI,{placeholder:s("linkInputPlaceholder"),visitUrlText:s("visitUrl"),onSelectLink:S,onDismiss:()=>{d(null),h.close()}})]})})]},"selection-end")},Em=class extends So{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,Lt.jsx)(X5,{ref:this.startRef}):(0,Lt.jsx)(Q5,{inputElement:r.inputElement,startRef:this.startRef,boundaryRef:r.boundaryRef,inputStyle:r.inputStyle})}asTag(){return"mark"}};var To=E(P()),Z5=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:s,keywordMatches:i,inputElement:a,source:l})=>{let c=O("TabCompletion",wI),u=X("insertLink"),f=X("addToPersonalCollection"),d=X("showMidSentenceSuggestions"),p=X("inlineSuggestions"),h=vI(a),g=(0,ko.useRef)(null),S=G(Rt);(0,ko.useEffect)(()=>{wi(a)&&h&&SI(a,h)},[h]);let y=(0,ko.useCallback)(x=>{if(!o||!n)return x;let C=[(0,To.jsx)("span",{className:c.resetIndent,children:"\u200B"},"u200B"),(0,To.jsx)("span",{"data-testid":"tab-completion",className:(0,Cm.default)(c.tabText,c.resetIndent),"data-source":l,children:n},"tabText")];return r&&C.push((0,To.jsx)("span",{className:(0,Cm.default)(c.hint,c.resetIndent),children:(0,To.jsx)(Du,{keyCode:"tab"},"tabHint")},"tabHint")),nS(x,C)},[o,n,r]),m=(0,ko.useMemo)(()=>{let x=[];return(u||f)&&x.push(new Em("selection")),x.push(new xm("placeholders")),s&&x.push(new vm("keywords")),x},[p,u,f,s]),v=(0,ko.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,To.jsxs)("div",{ref:x=>{x!=null&&x.parentElement&&(g.current=x==null?void 0:x.parentElement)},className:c.root,style:v,children:[(0,To.jsx)(ms,{tagName:"span",containerTagName:"div",className:(0,Cm.default)(c.container,c.agentText),disableLineBreaks:wi(a),content:t||"\u200B",onAfterParse:y,matchers:m,selection:h,keywordMatches:i,inputElement:a,inputStyle:v,boundaryRef:g,inlineSuggestionsOnlyAtEnd:!d}),(0,To.jsx)("br",{})]},"tab-completion")},J5=e=>{var y,m,v;let{input:t,ui:n,settings:r,styleSuggestions:o,conversation:s}=e,i=Hi({input:t}),a=(i==null?void 0:i.text)||"",l=(i==null?void 0:i.source)||"",c=(y=t.html)!=null?y:Ba(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:g,showStyleSuggestions:S}=r;return{showTabHint:d,showStyleSuggestions:S,showTabCompletion:h&&Ur(e),content:c,tabText:f,source:l,keywordMatches:(v=(m=o.list)==null?void 0:m.keywordMatches)!=null?v:[],enabled:g&&p!==!1}},_I=Jx(J5)(Z5);var ws=E(Z());var e6={token:null,interval:null},lS=me("passwordlessToken/getTemporaryPasswordlessToken",(e,t)=>M(null,null,function*(){let{deepdeskAPI:n}=t.extra;return{token:yield n.requestPasswordlessToken()}})),cS=me("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(lS()),setInterval(()=>r(lS()),n)}),MI=Re({name:"passwordlessToken",initialState:e6,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(lS.fulfilled,(t,n)=>{t.token=n.payload.token}),e.addCase(cS.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:NI}=MI.actions,LI=MI.reducer;function t6(e){return"buttonText"in e&&"eventName"in e}function OI(e){if(e)return t6(e)?{label:e.buttonText,event:e.eventName,value:e.payload}:e}function n6(e){return e==null?void 0:e.map(t=>OI(t))}function r6(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t}var DI=Gt([Jb,nd],(e,t)=>(t?e.filter(o=>!o.externalConversationId||o.externalConversationId===t):e).map(o=>{let s=OI(o.callToAction),i=n6(o.callToActions);return I(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}:{}),{editable:o.editable,isLoading:o.isLoading,evaluationId:o.evaluationId,rule:{id:r6(o.code),label:o.code,name:o.name,description:o.name}})}));var Tm=E(Z()),dS=E(De());var uS=E(P()),Ga=()=>(0,uS.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,uS.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 FI={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};var jr=E(P()),o6=({entities:e})=>{let t=O("EntitiesWidgetList",FI),[n,r]=(0,Tm.useState)(void 0),o=Ze(),s=()=>{r(void 0)},i=a=>{e&&(r(e.indexOf(a)),Ir(a.text),o("entity copied",{entity:a,type:"copy"}))};return(0,Tm.useEffect)(()=>{let a=setTimeout(s,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,jr.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,jr.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>i(a),children:[(0,jr.jsx)("span",{className:t.entityText,children:a.text}),(0,jr.jsxs)("span",{className:t.iconWrapper,children:[(0,jr.jsx)("span",{className:(0,dS.default)(t.icon),children:(0,jr.jsx)(Ga,{})}),(0,jr.jsx)("span",{className:(0,dS.default)(t.icon,n===l&&t.iconClicked),children:(0,jr.jsx)(Ga,{})})]})]},a.text))})},zI=o6;var fS=E(P()),HI=()=>(0,fS.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,fS.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 KI=E(Z());var BI={root:"dd-ohnXe",trigger:"dd-7i-S3",button:"dd-t53Cg",nav:"dd-qZFnm",item:"dd-FZC0F"};var UI={root:"dd-nazq3",rotation:"dd-3EHTv"};var jI=E(P()),s6=({size:e=12})=>{let t=O("LoadingSpinner",UI);return(0,jI.jsx)("span",{"data-testid":"loading-spinner",style:{width:`${e}px`,height:`${e}px`},className:t.root})},VI=s6;var pS=E(P()),WI=()=>(0,pS.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 512 512",fill:"currentColor",children:(0,pS.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 cu=E(P()),$I=e=>(0,cu.jsxs)("svg",I(b({xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 448 512","aria-labelledby":"checkTitle"},e),{children:[(0,cu.jsx)("title",{id:"checkTitle",children:"Check"}),(0,cu.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 mS={};yt(mS,{enUS:()=>i6,nlNL:()=>a6});var i6={error:[{type:0,value:"Something went wrong"}]},a6={error:[{type:0,value:"Er ging iets fout"}]};var On=E(P()),l6=3e3,c6=({assistantOptions:e})=>{let t=O("OnDemandAssistants",BI),n=ie(mS),r=(0,KI.useRef)(),o=gd(fn),s=G(qR),i=Ze(),a=s.filter(u=>u.isPinned),l=s.filter(u=>!u.isPinned),c=u=>M(null,null,function*(){clearTimeout(r.current),i("trigger on demand assistant",{assistantCode:u}),yield o.call(I(b({},e),{assistantCode:u})),r.current=setTimeout(()=>o.reset(),l6)});return s.length===0?null:(0,On.jsxs)("div",{className:t.root,children:[a.map(({assistant:u,assistantName:f,displayName:d})=>(0,On.jsx)("button",{type:"button",className:t.button,disabled:o.state==="loading",onClick:()=>c(u),children:d||f},u)),l.length>0&&(0,On.jsxs)(wt,{placement:"top-end",children:[(0,On.jsx)(wt.Trigger,{className:t.trigger,disabled:o.state==="loading",children:(0,On.jsx)(Xp,{"data-testid":"trigger"})}),(0,On.jsx)(wt.Content,{className:t.nav,"data-testid":"popover",children:l.map(({assistant:u,assistantName:f,displayName:d})=>(0,On.jsx)(wt.Button,{className:t.item,disabled:o.state==="loading",onClick:()=>c(u),children:d||f},u))})]}),o.state==="loading"&&(0,On.jsx)(VI,{}),o.state==="done"&&(0,On.jsx)($I,{"data-testid":"trigger-done"}),o.state==="error"&&(0,On.jsx)(PR,{trigger:(0,On.jsx)(WI,{}),children:n("error")})]})},GI=c6;var uu={};yt(uu,{enUS:()=>u6,nlNL:()=>d6});var u6={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"}]},d6={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 bi=E(Z());var gS={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 Ot=E(P()),f6=500,p6=100,m6=({content:e,onChange:t,onCopy:n})=>{let r=(0,bi.useRef)(null),o=O("WidgetCue",gS);return(0,bi.useEffect)(()=>{let s=r.current;if(!s)return;s.style.setProperty("height","0px");let i=Math.min(Math.max(s.scrollHeight,p6),f6);s.style.setProperty("height",`${i}px`)},[e]),(0,Ot.jsx)("textarea",{ref:r,className:o.editableCue,onCopy:n,onChange:t,value:e})},g6=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o})=>{var g;let s=O("WidgetCue",gS),i=ie(uu),a=Ze(),l=X("hasKeyboardInput"),[c,u]=(0,bi.useState)(e.text),f=S=>{let y=S?I(b({},e),{callToAction:S}):e;t&&t(c,y),n(e)},d=(S,y)=>{r&&r(S,e),y&&Fo(y,s.fadeup)},p=S=>{o&&o(S,e)},h=S=>{S.preventDefault(),S.stopPropagation(),n(e)};return(0,bi.useEffect)(()=>{a("Assistant response displayed",{evaluationId:e.evaluationId,assistantCode:e.rule.label,assistantOutput:e.text})},[]),(0,Ot.jsxs)(de,{"data-testid":"cue",children:[(0,Ot.jsx)(Se,{children:(0,Ot.jsxs)(Se.Content,{children:[e.title&&(0,Ot.jsx)(Se.Title,{className:s.title,"data-testid":"widget-cue-title",children:e.rule.label.startsWith("__")?i(e.rule.label):e.title}),e.message&&(0,Ot.jsx)("p",{className:s.ctaMessage,children:e.message}),e.editable?(0,Ot.jsx)(m6,{content:c,onCopy:()=>{let S=document.getSelection();S&&d(S.toString())},onChange:S=>{var y;return u((y=S.target.value)!=null?y:"")}}):(0,Ot.jsx)(ri,{content:e.text,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:d,onUse:l?p:void 0})]})}),(0,Ot.jsxs)(de.ButtonsContainer,{children:[(0,Ot.jsxs)("div",{className:s.actions,children:[(0,Ot.jsx)(de.Button,{onClick:S=>{var y;return d((y=_d(c,"reply")[0])!=null?y:c,S.target)},variant:"primary",children:i("copyCue")}),e.callToAction&&(0,Ot.jsx)(de.Button,{onClick:()=>f(),variant:"primary",children:e.callToAction.label}),(g=e.callToActions)==null?void 0:g.map((S,y)=>(0,Ot.jsx)(de.Button,{onClick:()=>f(S),variant:"primary",children:S.label},`${S.event}-${S.label}-${y}`)),(0,Ot.jsx)(de.Button,{onClick:h,variant:"secondary",children:i("removeCue")})]}),(0,Ot.jsx)(Dd,{evaluationId:e.evaluationId,assistantCode:e.rule.label,assistantOutput:e.text,feedbackText:e.text,feedbackType:"assistant"})]})]})},qI=g6;var qa=E(P()),h6=({cues:e})=>{let t=be(),n=dn(),r=ie(uu),o=Ze(),s=c=>{t(Nd({code:c.rule.label})),o("Assistant response closed",{evaluationId:c.evaluationId,assistantCode:c.rule.label,assistantOutput:c.text})},i=(c,u)=>{Ir(c),o("Assistant response copied",{evaluationId:u.evaluationId,assistantCode:u.rule.label,assistantOutput:u.text,copiedText:c})},a=(c,u)=>{var f;u.callToAction&&(t(Md(u)),o("Assistant call to action",{evaluationId:u.evaluationId,assistantCode:u.rule.label,assistantOutput:u.text,eventName:u.callToAction.event,value:(f=u.callToAction.value)!=null?f:c}))},l=(c,u)=>{var f;n.send(Xr,{text:c,suggestion:{source:"assistant",assistantCode:(f=u.rule)==null?void 0:f.label,sourceText:c}}),o("Assistant response used",{evaluationId:u.evaluationId,assistantCode:u.rule.label,assistantOutput:u.text,usedText:c})};return(0,qa.jsx)(qa.Fragment,{children:e.map(c=>c.isLoading?(0,qa.jsx)(lp,{title:c.rule.label.startsWith("__")?r(c.rule.label):c.title},c.rule.id):(0,qa.jsx)(qI,{cue:c,onCallToAction:a,onRemove:s,onCopy:i,onUse:l},c.evaluationId))})},YI=h6;var km=E(Z());var XI={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var bn=E(P());function y6(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var QI=({data:e,schema:t})=>{let n=O("WidgetCustomData",XI),r=o=>{Ir(o)};return(0,km.useEffect)(()=>{ee.info("Custom data",e,t)},[e]),(0,bn.jsx)("dl",{className:n.root,children:t.map(o=>{let s=y6(e,o.path);return(0,bn.jsxs)(km.Fragment,{children:[(0,bn.jsx)("dt",{className:n.label,children:o.label}),(0,bn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&s?(0,bn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!s?(0,bn.jsx)("span",{className:n.isFalse,children:o.falseValue}):o.type==="array"&&Array.isArray(s)&&s.length>0?(0,bn.jsxs)("button",{type:"button",onClick:()=>r(s.join(", ")),className:n.copyButton,children:[(0,bn.jsx)("span",{className:n.copyButtonText,children:s.join(", ")}),(0,bn.jsx)(Ga,{})]}):typeof s=="string"||typeof s=="number"?(0,bn.jsxs)("button",{type:"button",onClick:()=>r(`${s}`),className:n.copyButton,children:[(0,bn.jsx)("span",{className:n.copyButtonText,children:s}),(0,bn.jsx)(Ga,{})]}):"-"})]},o.label)})})};var JI=E(Z());var v6=/(https?:\/\/[^\s]+)/,ZI=e=>e.split(" ").find(t=>v6.test(t));var Yn=E(P()),S6=({suggestion:e,lines:t,onUse:n})=>{var f;let r=e.text||e.url||e.message,o=ZI(r),s=ie(eu),i=X("showImages"),a=X("fallbackImage"),l=X("hasKeyboardInput"),c=d=>{d.preventDefault(),d.stopPropagation(),l&&n(r)},u=(0,JI.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,Yn.jsxs)(de,{onClick:l?c:void 0,"data-testid":"edit-suggestion",children:[(0,Yn.jsxs)(Se,{children:[i&&e.image&&(0,Yn.jsx)(Se.Image,{src:wm(e,"small",a||void 0),title:e.title}),(0,Yn.jsxs)(Se.Content,{children:[e.title&&(0,Yn.jsx)(Se.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((f=e.searchKeywords)==null?void 0:f.length)>0&&(0,Yn.jsx)(de.Labels,{labels:e.searchKeywords}),(0,Yn.jsx)(Se.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,Yn.jsxs)(de.Actions,{children:[o&&(0,Yn.jsx)(de.ActionButton,{onClick:u,label:s("visitUrl")}),l&&(0,Yn.jsx)(de.ActionButton,{primary:!0,onClick:c,label:s("useSuggestion")})]})]})},eA=S6;var du=E(P()),x6=({lines:e,suggestions:t})=>{let n=dn(),r=(o,s)=>{n.send(Xr,{text:o,suggestion:I(b({},s),{source:s.source,sourceText:s.text})})};return(0,du.jsx)(du.Fragment,{children:t.map(o=>(0,du.jsx)(eA,{suggestion:o,lines:e,onUse:s=>r(s,o)},o.text||o.url||o.message))})},tA=x6;var fu={};yt(fu,{enUS:()=>w6,nlNL:()=>b6});var w6={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"}]},b6={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 Ya={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",footer:"dd-tvofr",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",footerShortcut:"dd-dH7XJ",link:"dd-DRo0x"};var le=E(P()),nA=(e,t)=>{let n=G(Rt);(0,ws.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},E6=({onLogIn:e})=>{let t=O("Widget",Ya),n=X("isEmbedded"),r=X("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")},hS=({text:e})=>{let t=O("Widget",Ya);return(0,le.jsx)("div",{className:t.stateText,children:(0,le.jsx)("div",{children:(0,le.jsx)("p",{children:e})})},"notification")},C6=()=>{let e=ie(fu),t=be(),n=O("Widget",Ya),r=X("showSearch"),o=X("isEmbedded"),s=G(zo("/admin/")),i=dn(),a=X("productName"),l=Ze();return nA(()=>{if(o)return t(cS()),()=>{t(NI())}},[t,o]),!r&&!s?null:(0,le.jsxs)("div",{className:n.shortcutList,children:[r&&(0,le.jsx)(de.Button,{"data-testid":"shortcut-search","aria-label":e("linkSearch"),className:n.shortcut,icon:(0,le.jsx)(Va,{}),onClick:()=>{i.send("ShowCommandPalette",{isOpen:!0}),l("open search",{via:"widget-shortcut"})},children:e("linkSearch")}),s&&(0,le.jsx)(de.Button,{as:"a",target:"_blank",icon:(0,le.jsx)(HI,{}),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})})]})},T6=({title:e,content:t})=>{let n=ie(fu),[r,o]=(0,ws.useState)(!0);return r?(0,le.jsx)(Cr,{"data-testid":"custom-data-banner",type:"custom-data-banner",title:e,children:(0,le.jsx)(Ct,{withDivider:!0,children:(0,le.jsxs)(de,{children:[(0,le.jsx)(Se,{children:(0,le.jsx)(Se.Content,{children:(0,le.jsx)(ri,{content:t})})}),(0,le.jsx)(de.ButtonsContainer,{children:(0,le.jsx)(de.Button,{onClick:()=>o(!1),children:n("close")})})]})})}):null},k6=()=>{let e=be(),t=G(jc),n=G(XR),r=G(DI),o=G(fb),s=G(Yp),i=G(Jp),a=G(ci),l=G(Rr);return(0,ws.useEffect)(()=>{o&&!n&&ee.warn("Custom data provided, but no schema.")},[o,n]),nA(()=>{t.forEach(({type:c})=>{c==="entities"?e(vr()):Bu.includes(c)||e(Sr(c))})},[e,l,a]),(0,ws.useEffect)(()=>{r.length>0&&!t.some(c=>c.type==="cues")&&ee.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,le.jsx)(ws.Fragment,{children:t.map(({type:c,title:u,amount:f,lines:d,schema:p,property:h})=>{var g,S;switch(c){case"entities":return s&&s.length>0&&(0,le.jsx)(Cr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(zI,{entities:s})},c);case"cues":return r&&r.length>0&&(0,le.jsx)(Cr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(Ct,{withDivider:!0,children:(0,le.jsx)(YI,{cues:r})})},c);case"custom-data-banner":return o&&h&&o[h]&&(0,le.jsx)(T6,{title:u,content:String(o[h])},c);case"custom-data":return o&&p&&(0,le.jsx)(Cr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(Ct,{withDivider:!0,children:(0,le.jsx)(QI,{data:o,schema:p})})},c);default:return((S=(g=i[c])==null?void 0:g.suggestions)==null?void 0:S.length)>0&&(0,le.jsx)(Cr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(Ct,{withDivider:!0,children:(0,le.jsx)(tA,{lines:d,contentType:c,suggestions:i[c].suggestions.slice(0,f)||[]})})},c)}})})},yS=({children:e})=>{let t=O("Widget",Ya);return(0,le.jsx)("div",{className:t.footer,children:e})},vS=({children:e})=>{let t=O("Widget",Ya);return(0,le.jsx)("div",{className:t.root,"data-testid":"widget",children:e})},R6=({onLogIn:e,knowledgeAssistOptions:t={},assistantOptions:n={transcript:"in-memory-transcript"}})=>{let r=ie(fu),o=G(zi),s=G(Rt),i=G(nd),a=G(ci),l=G(YR("knowledge-assist")),c=G(QR);return o===!1?(0,le.jsx)(hS,{text:r("notSupported")}):s===!1?(0,le.jsx)(E6,{onLogIn:e}):s===null?(0,le.jsx)(hS,{text:r("waiting")}):!i||!a?(0,le.jsx)(hS,{text:r("waitingForConversation")}):(0,le.jsx)(vS,{children:(0,le.jsxs)(Lp,{initialQuestion:t.initialQuestion,assistantCode:c!=null?c:void 0,evaluateKnowledgeAssistFn:Ll,children:[(0,le.jsxs)(Oi,{children:[(0,le.jsx)(C6,{}),(0,le.jsx)(k6,{}),l&&(0,le.jsx)(Dp,{title:l.title,emptyState:t.emptyState})]}),(0,le.jsxs)(yS,{children:[l&&(0,le.jsx)(Op,{}),(0,le.jsx)(GI,{assistantOptions:n})]})]})})},rA=R6;function Xa(e){let t=new Range;return t.selectNodeContents(e),t}function oA(e,t,n){try{return bs(e,t,n),!0}catch(r){return!1}}function Rm(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function Pm(e){return"tagName"in e&&e.tagName==="BR"}var pu=/[\u200B-\u200D\uFEFF]/g;function bs(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(pu,""),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(Pm(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;Rm(l)&&c&&!Rm(c)&&!Pm(c)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function mu(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 g=f.textContent;p&&(a=c+g.substring(0,r).replace(pu,"").length),h&&(l=c+g.substring(0,s).replace(pu,"").length),c+=g.replace(pu,"").length;break}case Node.ELEMENT_NODE:{if(Pm(f)&&f.nextSibling){c++;break}!d&&Rm(f)&&f.previousSibling&&c++;for(let g=0;g<f.childNodes.length;g++){let S=p&&g===r,y=h&&g===s;if(S&&(a=c),y&&(l=c),l!==void 0||((!S||!i)&&u(f.childNodes[g]),h&&g===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 gu(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,g=p?s:void 0;l+=u.textContent.replace(pu,"").substring(h,g);break}case Node.ELEMENT_NODE:{if(!i&&a===1&&Pm(u)&&u.nextSibling){l+=`
|
|
82
82
|
`;break}!f&&!i&&a===1&&Rm(u)&&u.previousSibling&&(l+=`
|
|
83
|
-
`);let h=d?r:0,g=p?Math.min(s,u.childNodes.length):u.childNodes.length;for(let S=h;S<g&&(c(u.childNodes[S]),a!==2);S++);break}default:break}p&&(a=2)}return c(e),l}var sA=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(sA||{}),Ro=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();Oo(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(sA).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 iA(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Ei=class extends Ro{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),gu(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!iA(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!iA(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return mu(this.element,n);let r=this.lastKnownSelection;if(r&&oA(this.element,r.start,r.end))return r;let o=Xa(this.element);return o.collapse(!1),mu(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return gu(this.element,bs(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 P6=["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 aA(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",P6.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 Ci=class extends Ro{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 aA(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 lA(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 I6(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var SS=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()}},xS=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=lA(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()}},wS=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(),ee.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 xS(t,this.deepdeskUrl,{debug:!0}):new SS(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=I6(o.data);typeof s!="object"||s.type!=="event"||s.channel!==t||(ee.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;ee.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(I(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)}},cA=wS;function A6(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function je(e){return Array.isArray(e)?e.map(je):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(b({},t),{[A6(n)]:je(e[n])}),{}):e}function _6(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function an(e){return Array.isArray(e)?e.map(an):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(b({},t),{[_6(n)]:an(e[n])}),{}):e}var Qa=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var bS=e=>new Promise(t=>{setTimeout(t,e)});var Ti=class extends Qa{constructor(){super(...arguments);this.name="ClientError"}},CS=class extends Qa{constructor(){super(...arguments);this.name="ServerError"}},ES=new Map;function M6(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:(ee.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var ki=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",T=n,{useCache:c=!1,abortLatest:u=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:h=k=>k instanceof TypeError,retryOnResponse:g=k=>k.status>=500,version:S=null}=T,y=se(T,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(c){if(!l)throw new Error(`Can't use 'useCache' for ${n.method}`);if(ES.has(i)){r(ES.get(i));return}}let m=I(b({credentials:"include"},y),{headers:b({Accept:"application/json","Content-Type":"application/json"},y.headers)});!l&&this.csrfToken&&(m.headers=I(b({},m.headers),{"X-CSRFToken":this.csrfToken})),typeof S=="string"&&(m.headers=I(b({},m.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 C=()=>M(this,null,function*(){return v--,a(i,m).then(k=>M(this,null,function*(){return g(k)&&!s.isAborted&&v>0?(yield bS(d),C()):k.status===401&&p===!0&&x===!1?(x=!0,yield this.refreshToken(),C()):k})).catch(k=>M(this,null,function*(){if(h(k)&&!s.isAborted&&v>0)return yield bS(d),C();throw k}))});C().then(k=>M(this,null,function*(){let A=yield M6(k);if(delete this.latestRequestByUrl[i],k.status>=500){o(new CS("Server Error",A));return}if(k.status===401){o(new Ti("Unauthorized",A));return}if(k.status===403){o(new Ti("Forbidden",A));return}if(k.status===404){o(new Ti("Not Found",A));return}if(k.status>=400){o(new Ti("Bad Request",A));return}c&&ES.set(i,A),r(A)})).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 Ti("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))}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 uA;(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={}))})(uA||(uA={}));function TS(e){return I(b({},je(e)),{metadata:e.metadata})}var Ri=class Ri{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new ki(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?(Ri.exchangeTokenPromise||(Ri.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),Ri.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return M(this,null,function*(){var r;yield this.preflight(),ee.info(`Creating conversation for session ${t.externalId} and agent ${t.agentId}`);let n=yield this.client.post("/api/v2/conversations",I(b({chat_start_time:new Date().toISOString()},an(t)),{metadata:(r=t.metadata)!=null?r:{}}));return TS(n)})}getMe(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return je(t)})}postIdentity(t){return M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",an(t))})}patchMe(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",an(t));return je(n)})}getProfile(t){return M(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return je(n)})}getKnowledgeAssistant(t){return M(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return je(n)})}getContentTypes(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return je(t)})}getAccount(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return je(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 je(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(),ee.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 ee.info(`Successfully retrieved conversation ${i.id} for session ${t}`),TS(i)})}isConversationSupported(r){return M(this,arguments,function*(t,n={}){ee.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=an(n);n.metadata&&(r.metadata=(s=n.metadata)!=null?s:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return TS(o)})}postMessages(t,n){return M(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>I(b({},an(r)),{metadata:r.metadata})))})}sendEvent(t,n){return M(this,null,function*(){yield this.preflight();let a=n,{data:r}=a,o=se(a,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((l,[c,u])=>I(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",an(I(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 ee.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/",an(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}`,an(n),{abortLatest:!0})).map(i=>I(b({},je(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`,an(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))})}getPinnedMessages(t){return M(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return je(n).map(r=>I(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",an(t),{abortLatest:!0,version:"v2"});return je(n)})}search(t){return M(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,an(t));return je(n)})}requestLoginByEmail(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return je(n)})}requestPasswordlessToken(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return je(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 je(n)})}evaluateAssistant(t,n){return M(this,null,function*(){var i;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=yield this.client.post(o,{input:(i=n==null?void 0:n.input)!=null?i:{},conversation:n==null?void 0:n.transcript});return je(s)})}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 je(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 je(s)})}translateMessages(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",an(t));return je(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(Fx);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&ee.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};Ri.exchangeTokenPromise=null;var Po=Ri;var Im=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=je(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 dA={startTime:null,stopTime:null},fA=e=>e.handlingTime,pA=Re({name:"handlingTime",initialState:dA,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(lt,()=>dA)}}),{handlingTimeStart:mA,handlingTimeStop:Am,handlingTimeReset:gA}=pA.actions,hA=pA.reducer;var yA=(e={})=>{let t=b({onAuthError:Fi(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var vA=(e={})=>{let t,n=!0,r=b({getStyleSuggestions:Si,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 N6(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end&&e.suggestionTextStart===t.suggestionTextStart}var SA=(e={})=>{let t=b({getTextSuggestions:Sr,getAutocompleteSuggestions:nu,debounce:200,check:Ur},e),n;return r=>o=>s=>{var g;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=(g=l.conversation.current)==null?void 0:g.id,d=s.type===em.toString();if(!f||!c&&!u)return a;let{input:p}=l;return N6(p,i)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let S=_s(l);S===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(S))},d?0:t.debounce)),a}};var xA=Si.fulfilled.toString();function L6(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 wA=e=>t=>n=>r=>{var c;if(r.type!==xA){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=L6(o,i);r.type===xA&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var O6=Wu({assistants:iE,auth:$w,conversation:Qw,contentTypes:GR,passwordlessToken:LI,entities:wP,handlingTime:hA,info:Sb,input:cb,settings:lE,profile:ZR,search:Tb,styleSuggestions:oI,ui:KP,textSuggestions:_P});function bA(e){return Mw({reducer:O6,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(yA()).concat(SA({debounce:200})).concat(vA({debounce:500})).concat(wA(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,s)=>o.concat(s),n)},preloadedState:e.preloadedState})}function EA(e,t,n){if(t==="")return null;let r=new RegExp(`\\b${mm(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 D6=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},F6=e=>t=>n=>r=>{var l,c,u,f,d,p;let o=t.getState(),s=Hs("inlineSuggestions")(o),i=Hs("autoSelectSuggestion")(o)||s;switch(r.type){case Fi.toString():{!r.payload&&e.emit("logout",void 0);break}case vr.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 Ls.toString():e.logSendMessage(r.payload);break;case Md.toString():e.emit("call-to-action",{cue:r.payload});break;case fn.fulfilled.toString():if(!r.isBroadcasted){let{externalConversationId:h,currentExternalIdAtRequest:g}=(c=r.payload)!=null?c:{};(!h||!g||h===g)&&e.broadcast($g,r,!1)}break;case fn.rejected.toString():break;default:break}let a=n(r);switch(r.type){case Ls.toString():e.handleAfterSendMessage(r.payload);break;case ou.toString():e.onUpdateShowTabHint(r.payload);break;case Am.toString():e.logHandlingTime();break;case Bi.toString():e.broadcast(pd,r);break;case Ns.toString():e.broadcast(pd,r);break;case Nd.toString():t.dispatch(Ns({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{let h=o.assistants.cues.find(g=>g.code===r.meta.arg.data.assistantCode);e.emit("event",I(b({},r.meta.arg),{cue:h}));break}case Cn.toString():{let{start:h,end:g}=o.input.selection;e.emit("select-suggestion",I(b({type:D6(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:h,end:g}:{start:0,end:g}})),s&&t.dispatch(Do([]));break}case rI.toString():{let{keyword:h,suggestion:g,eventMetrics:S}=r.payload,{text:y,selection:m}=o.input,v=EA(y,h,(u=m==null?void 0:m.end)!=null?u:y.length);if(!v)break;e.emit("select-suggestion",{text:g,type:"style",replace:v,suggestion:{text:g,source:"style"},eventMetrics:S});break}case id.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 Do.toString():{i&&r.payload.length>0&&t.dispatch(ad(0));break}case fn.fulfilled.toString():{let{evaluationId:h,output:g,externalConversationId:S}=r.payload,y=r.meta.arg.assistantCode;if(e.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:h,assistantCode:y,assistantOutput:tE(g),externalConversationId:S,evaluationStatus:"success"}}),!r.meta.arg.skipState){let m=t.getState().assistants.cues;e.emit("cues",m)}break}case fn.rejected.toString():{let h=r.meta.arg.assistantCode,g=(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:g,evaluationStatus:"failed"}});break}default:break}return a},CA=F6;function kS(e){return e.toISOString().replace("T"," ").replace("Z","")}var z6=(e,t)=>t.version,TA=Gt([Ui,Rr,fA,z6],(e,t,n,r)=>{if(!t)return ee.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:s}=n;return!o||!s?(ee.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:kS(o),timeStop:kS(s)}});function kA(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 hu=class extends Error{};function H6(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var _m=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 hu("Queued async function is outdated"));let o=H6();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};function RS(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return RS(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?RS(o,t):null}function PS(e,t){return RS(e,t)}var B6={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},RA=(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 ee.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let r=e[B6[t]];return r&&r.length>0?r.map(a=>a.code):(ee.warn(`No assistant set in profile for conversation event "${t}"`),[])};function PA(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function U6(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Mm(e){return U6(e)&&(wi(e)||fm(e))}var AA,Wr=new Map,V6=["bottom","height","left","right","top","width"],IA=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:V6.some(n=>e[n]!==t[n]);function _A(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,..._A(t)]:[]}function MA(e,t){return!e||!t?null:I(b({},e),{top:e.top+t.top,left:e.left+t.left})}var Nm=!1,NA=()=>{Nm=!0;let e=[];if(Wr.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Wr.delete(n);return}let r=n.getBoundingClientRect();IA(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(MA,t.rect):t.rect;IA(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Wr.size===0){Nm=!1;return}AA=window.requestAnimationFrame(NA)};function IS(e,t){let n=_A(e),r=[],o=n.map((s,i)=>IS(s,a=>{r[i]=a;let l=Wr.get(e);if(!l)return;let c=r.reduce(MA,l.rect);l.callbacks.forEach(u=>u(c))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),Wr.has(e)){let i=Wr.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else Wr.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!Nm&&NA()},unobserve(){o.forEach(i=>i.unobserve());let s=Wr.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||Wr.delete(e),Wr.size||(cancelAnimationFrame(AA),Nm=!1)}}}}var LA,$r=new Map,OA=()=>{$r.forEach((e,t)=>{if(!t.isConnected){$r.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)))}),$r.size!==0&&(LA=window.requestAnimationFrame(OA))};function DA(e,t){return{observe(){let n=$r.size===0;$r.has(e)?$r.get(e).callbacks.push(t):$r.set(e,{visible:void 0,callbacks:[t]}),n&&OA()},unobserve(){let n=$r.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||$r.delete(e),$r.size||cancelAnimationFrame(LA)}}}}var AS=["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 _S(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Za(e){return Number.parseFloat(e)}function Lm(e){return Math.round(e*1e6)}function FA(e){return e/1e6}function MS(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Za(e.width),s=Za(e.borderLeftWidth),i=Za(e.borderRightWidth),a=Za(e.paddingRight),l=FA(Lm(o)-Lm(s)-Lm(i)),c=FA(Lm(r));if(l-c>2){let u=l-c;n.style.paddingRight=`${a+u}px`}}function yu(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",ni(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};_S(r,n,AS),MS(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=DA(e,()=>{_S(r,n,AS),MS(r,e,n),s(),setTimeout(s,0)}),a,l=!0,c=IS(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(_S(r,n,AS),MS(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),g=Za(h.borderTopWidth),S=Za(h.borderBottomWidth),y=p.top+g-d.top,m=d.top+d.height+-(p.top+p.height-S);n.style.clipPath=`inset(${y}px 0px ${m}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 j6(e){return e.offsetParent!==null}function zA(e){if(!j6(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 Om(e,t,n=100){let r=zA(e);t({isVisible:r});let o=setInterval(()=>{let s=zA(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var HA=(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){ee.warn("[Deepdesk] SessionStorage is blocked by browser")}}});var ke=E(P());var BA=HA("showTabHint",!0),Ja=class Ja{constructor({deepdeskUrl:t,version:n=Ja.version||"unknown",locale:r="en-US",token:o,fetch:s,productName:i,createCustomChannel:a,websocketClient:l=Im}){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 _m;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let c=t.replace(/\/api$/,"");this.deepdeskApi=new Po(c,{token:o,fetch:s}),this.version=n,this.instanceId=Ja.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[CA({broadcast:(h,g,S)=>{this.broadcastEvents.send(h,g,S)},emit:(h,g)=>this.emit(h,g),handleAfterSendMessage:h=>this.handleAfterSendMessage(h),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:h=>this.logSendMessage(h),onUpdateShowTabHint:h=>BA.update(h),sendEvent:(h,g)=>this.deepdeskApi.sendEvent(h,g)})]};this.store=bA(u),this.broadcastEvents=new cA({debug:!0,deepdeskUrl:c,eventMap:kb(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=Rt(this.state))!=null?h:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(ou(BA.value())),this.store.dispatch(Ld({locale:r,adminUrl:c,productName:i}));let f=[],d=h=>{if(!h.conversationId)return;let g=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(sE(h))};this.hasConversation()?g():f.push(g)};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 g=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(oE(h))};this.hasConversation()?g():f.push(g)}),this.ws.on("assistants::suggest_as_reply",h=>{if(!h.conversationId)return;let g=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(Bi([{text:h.payload.message,type:"text",source:"assistant",assistantCode:h.code,sourceLabel:h.name}]))};this.hasConversation()?g():f.push(g)});let p=this.whenConversationLoaded(()=>{var h;this.broadcastEvents.setExternalId((h=this.state.conversation.current)==null?void 0:h.externalId),f.forEach(g=>g()),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=Ms(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?(ee.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(ee.warn("Profile has not been loaded (yet)"),!0):(ee.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(t){if(Rt(this.state))t();else{let n=this.subscribe(Rt,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Fi(null)),this.store.dispatch(Yr()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return M(this,null,function*(){return(yield this.store.dispatch(Yr())).payload})}isConversationSupported(t,n){return M(this,null,function*(){return(yield this.store.dispatch(zg({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(rd(I(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(od({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(Hg(I(b({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return M(this,null,function*(){yield this.store.dispatch(Bg(t))})}updateConversation(t){return M(this,null,function*(){return(yield this.store.dispatch(sd(t))).payload})}resetConversation(){this.store.dispatch(lt()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(Ld(t))}setVisitorInfo(t){this.store.dispatch(gb(t))}setCustomData(t){this.store.dispatch(hb(t))}setAgentInfo(t,n){return M(this,null,function*(){var o;yield this.store.dispatch(hl(b(b({},t),n))),(o=this.state.info.agentInfo)!=null&&o.agentNickname||this.broadcastEvents.send(fd,{showNicknameDialog:!0})})}setAgentSettings(t){return M(this,null,function*(){yield this.store.dispatch(Vg(t))})}getAgentSettings(){return M(this,null,function*(){return(yield this.store.dispatch(jg())).payload})}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(ld({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()}))}notifyExternalSuggestion(t){this.store.dispatch(Cn(t))}evaluateAssistant(t,n){return M(this,null,function*(){var c;let{input:r={},transcript:o,showCuesInWidget:s=!0,includeMetadata:i,externalConversationId:a}=n||{},l=yield this.store.dispatch(fn({assistantCode:t,transcript:o,includeMetadata:i,input:r,externalConversationId:a,skipState:!s}));if(l.error)throw new Error(`Assistant evaluation failed: ${(c=l.payload)!=null?c:l.error.message}`);return l.payload.output})}evaluateConversationAssistant(t,n){return M(this,null,function*(){var u,d;yield this.loadProfileConfig();let r=this.state.profile.data;if(!r){ee.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=RA(r,t),s=(u=n==null?void 0:n.showCuesInWidget)!=null?u:!0,f=n!=null?n:{},{showCuesInWidget:i}=f,a=se(f,["showCuesInWidget"]),l=(d=n==null?void 0:n.externalConversationId)!=null?d:this.hasConversation()?this.externalId():"",c=yield Promise.all(o.map(p=>this.queues.push(p,()=>M(this,null,function*(){var g,S;let h=yield this.store.dispatch(fn(I(b({assistantCode:p,includeMetadata:!0},a),{skipState:!s})));if(h.error)throw new Error(`Assistant evaluation failed: ${(g=h.payload)!=null?g:h.error.message}`);return{assistantCode:p,evaluationId:h.payload.evaluationId,output:h.payload.output,externalConversationId:(S=h.payload.externalConversationId)!=null?S:l}})).catch(h=>{if(h instanceof hu)return ee.warn(`Queued assistant "${p}" was outdated and dropped`),null;throw h})));if(!s)return c.filter(p=>p!==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(nb(Ug(t))),!Ur(this.state)||t.key!=="Tab"&&!c)return;let h=()=>{n||!p||i&&(t.shiftKey||(this.store.dispatch(sb()),t.preventDefault()))},g=()=>{n||!p||f&&s<=0||i&&(t.shiftKey||(this.store.dispatch(ib()),t.preventDefault()))};switch(t.key){case"ArrowUp":d==="below"?g():h();break;case"ArrowDown":{d==="below"?h():g();break}case"Escape":{n||(this.store.dispatch(ad(-1)),this.store.dispatch(hs({collapse:!0})),this.store.dispatch(WP(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let S=Hi(this.state);if(!S)return;this.store.dispatch(ou(!1)),this.store.dispatch(Cn({text:S.text,suggestion:S,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(f||this.state.input.selectedSuggestionIndex===-1)return;let S=Hi(this.state);if(!S)return;this.store.dispatch(Cn({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=Hi(this.state);if(!S)return;this.store.dispatch(Cn({text:S.text,suggestion:S,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(hs({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Do([]))}handlingTimeStart(){this.state.handlingTime.startTime||(ee.info("Start handling time"),this.store.dispatch(mA()))}handlingTimeStop(){this.state.handlingTime.startTime&&(ee.info("Stop handling time"),this.store.dispatch(Am()))}logSendMessage(t){let n=kA(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=TA(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(gA()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Ls((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(lb()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(s){ee.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),ee.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(yb(t))}whenConversationLoaded(t){let n=s=>{var i;return(i=s.conversation.current)==null?void 0:i.id},r=()=>this.loadProfileConfig().then(()=>t());return n(this.state)&&r(),this.subscribe(n,s=>{s&&r()})}overlayContainerFactory(t,n,r,o){let[s,i]=yu(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]=yu(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 ni(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),ee.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()?(ee.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(ab(r.metrics))):ee.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(!Mm(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=se(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),c={customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),ni(t),this.inputMediator=a||(wi(t)?new Ci(t):new Ei(t)),this.inputMediator.on("change",({plainText:p,rawHTML:h,suggestionTextStart:g})=>{this.store.dispatch(ld({text:p,html:h,suggestionTextStart:g}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(rb(Ug(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:h})=>{this.store.dispatch(ob({text:p,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(tb(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(cd(p))},500):this.store.dispatch(cd(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(rm(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(rm(!0))}),this.renderSuggestions(t,c),this.subscribe(Hs("inlineSuggestions"),()=>{this.renderSuggestions(t,c)}),this.subscribe(Hs("suggestionsPlacement"),()=>{this.renderSuggestions(t,c)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(ld({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()})),this.store.dispatch(cd(this.inputMediator.getSelection())),this.store.dispatch(rm(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,Io.createRoot)(n),o=null,s=a=>{o=a,i()},i=()=>{r==null||r.render((0,ke.jsx)(bo,{store:this.store,children:(0,ke.jsx)(Qr,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(aI,{id:"deepdesk-nickname-dialog",error:o,onSave:a=>M(this,null,function*(){try{yield this.store.dispatch(pb({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(fd,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(l){ee.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,Io.createRoot)(o);s.render((0,ke.jsx)(bo,{store:this.store,customStyles:r,children:(0,ke.jsx)(Qr,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(sI,{})})}));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&&PS(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,Io.createRoot)(l);d.render((0,ke.jsx)(bo,{store:this.store,customStyles:o,children:(0,ke.jsx)(Qr,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(_I,{inputElement:t})})}));let p=(0,Io.createRoot)(u);return p.render((0,ke.jsx)(bo,{store:this.store,customStyles:o,children:(0,ke.jsx)(Qr,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(hI,{onLogIn:()=>this.loginViaPopup().catch(h=>ee.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&&PS(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,Io.createRoot)(l);return u.render((0,ke.jsx)(bo,{store:this.store,customStyles:r,children:(0,ke.jsx)(Qr,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(VP,{onLogIn:()=>this.loginViaPopup().catch(f=>ee.warn(f.message))})})})),{unmount(){u.unmount(),c()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays"),o=(0,Io.createRoot)(r);return o.render((0,ke.jsx)(bo,{store:this.store,customStyles:n,children:(0,ke.jsx)(Qr,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(FP,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&ee.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}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:s}),this.widgetRoot=(0,Io.createRoot)(t),this.widgetRoot.render((0,ke.jsx)(bo,{store:this.store,customStyles:r,children:(0,ke.jsx)(Qr,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(rA,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(i=>ee.warn(i.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,Io.createRoot)(n);return i.render((0,ke.jsx)(bo,{store:this.store,customStyles:o,children:(0,ke.jsx)(Qr,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(vS,{children:(0,ke.jsxs)(Lp,{assistantCode:t,initialQuestion:s,evaluateKnowledgeAssistFn:Ll,children:[(0,ke.jsx)(Oi,{children:(0,ke.jsx)(Dp,{title:r.title,emptyState:r.emptyState})}),(0,ke.jsx)(yS,{children:(0,ke.jsx)(Op,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(t){let n=Om(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){PA(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>M(this,null,function*(){yield this.store.dispatch(Vc());let t=ci(this.state);t&&this.store.dispatch(Ld({showSearch:t.search,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions}))})),this.loadProfileConfigPromise)}loginViaPopup(t){return M(this,null,function*(){return new Promise((n,r)=>{this.store.dispatch(td());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,g;if((h=p.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((g=p.data)==null?void 0:g.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(vl),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");u===null&&r(new Error("Popup blocked by browser"));let f=p=>M(this,null,function*(){var h;if(p.origin===a.origin)switch((h=p.data)==null?void 0:h.type){case"deepdesk-popup-request-origin":{try{let g=JSON.stringify({type:"deepdesk-popup-parent-origin"});u==null||u.postMessage(g,a.origin)}catch(g){ee.error("Error posting message to popup",g),r(g)}break}case"deepdesk-popup-loaded":{try{let g=JSON.stringify({type:"deepdesk-popup-create-channel"});u==null||u.postMessage(g,a.origin,[o.port2])}catch(g){ee.error("Error posting message to popup",g),r(g)}break}case"deepdesk-popup-error":{if(c(),p.data.message==="Platform account url mismatch"){let g=`Please contact your administrator: The platform account url (${p.data.targetOrigin}) is misconfigured as it differs from the origin of the page that opened the popup (${p.data.openerOrigin}).`;ee.warn(g),this.store.dispatch(Og(g)),r(new Error(g))}if(p.data.message==="Timeout"){let g="Please contact your administrator: Popup timed out. Check if the account's platform url is configured correctly.";ee.warn(g),this.store.dispatch(Og(g)),r(new Error(g))}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(em()))})}refreshWidgetSuggestions(){return M(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=jc(this.state);try{n.forEach(({type:r})=>{switch(r){case"entities":this.store.dispatch(vr());break;case"pinned-messages":case"sticky-messages":break;default:Bu.includes(r)||this.store.dispatch(Sr(r))}})}catch(r){this.handleError(r)}})}};Ja.version="19.3.1-beta.0",Ja.count=0;var vu=Ja;function W6(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 UA(e,t){return M(this,null,function*(){let n=yield W6(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 VA(e,t,n){return M(this,null,function*(){yield new Po(e).authenticateWithKey(t,n)})}function jA(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function WA(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 $A(r,o){return M(this,arguments,function*(e,t,n={}){let s=n.replace?bs(e,n.replace.start,n.replace.end):Xa(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,g=p?Math.min(s,u.childNodes.length):u.childNodes.length;for(let S=h;S<g&&(c(u.childNodes[S]),a!==2);S++);break}default:break}p&&(a=2)}return c(e),l}var sA=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(sA||{}),Ro=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();Oo(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(sA).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 iA(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Ei=class extends Ro{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),gu(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!iA(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!iA(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return mu(this.element,n);let r=this.lastKnownSelection;if(r&&oA(this.element,r.start,r.end))return r;let o=Xa(this.element);return o.collapse(!1),mu(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return gu(this.element,bs(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 P6=["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 aA(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",P6.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 Ci=class extends Ro{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 aA(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 lA(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 I6(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var SS=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()}},xS=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=lA(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()}},wS=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(),ee.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 xS(t,this.deepdeskUrl,{debug:!0}):new SS(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=I6(o.data);typeof s!="object"||s.type!=="event"||s.channel!==t||(ee.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;ee.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(I(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)}},cA=wS;function A6(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function je(e){return Array.isArray(e)?e.map(je):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(b({},t),{[A6(n)]:je(e[n])}),{}):e}function _6(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function an(e){return Array.isArray(e)?e.map(an):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(b({},t),{[_6(n)]:an(e[n])}),{}):e}var Qa=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var bS=e=>new Promise(t=>{setTimeout(t,e)});var Ti=class extends Qa{constructor(){super(...arguments);this.name="ClientError"}},CS=class extends Qa{constructor(){super(...arguments);this.name="ServerError"}},ES=new Map;function M6(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:(ee.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var ki=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",T=n,{useCache:c=!1,abortLatest:u=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:h=k=>k instanceof TypeError,retryOnResponse:g=k=>k.status>=500,version:S=null}=T,y=se(T,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(c){if(!l)throw new Error(`Can't use 'useCache' for ${n.method}`);if(ES.has(i)){r(ES.get(i));return}}let m=I(b({credentials:"include"},y),{headers:b({Accept:"application/json","Content-Type":"application/json"},y.headers)});!l&&this.csrfToken&&(m.headers=I(b({},m.headers),{"X-CSRFToken":this.csrfToken})),typeof S=="string"&&(m.headers=I(b({},m.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 C=()=>M(this,null,function*(){return v--,a(i,m).then(k=>M(this,null,function*(){return g(k)&&!s.isAborted&&v>0?(yield bS(d),C()):k.status===401&&p===!0&&x===!1?(x=!0,yield this.refreshToken(),C()):k})).catch(k=>M(this,null,function*(){if(h(k)&&!s.isAborted&&v>0)return yield bS(d),C();throw k}))});C().then(k=>M(this,null,function*(){let A=yield M6(k);if(delete this.latestRequestByUrl[i],k.status>=500){o(new CS("Server Error",A));return}if(k.status===401){o(new Ti("Unauthorized",A));return}if(k.status===403){o(new Ti("Forbidden",A));return}if(k.status===404){o(new Ti("Not Found",A));return}if(k.status>=400){o(new Ti("Bad Request",A));return}c&&ES.set(i,A),r(A)})).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 Ti("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))}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 uA;(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={}))})(uA||(uA={}));function TS(e){return I(b({},je(e)),{metadata:e.metadata})}var Ri=class Ri{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new ki(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?(Ri.exchangeTokenPromise||(Ri.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),Ri.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return M(this,null,function*(){var r;yield this.preflight(),ee.info(`Creating conversation for session ${t.externalId} and agent ${t.agentId}`);let n=yield this.client.post("/api/v2/conversations",I(b({chat_start_time:new Date().toISOString()},an(t)),{metadata:(r=t.metadata)!=null?r:{}}));return TS(n)})}getMe(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return je(t)})}postIdentity(t){return M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",an(t))})}patchMe(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",an(t));return je(n)})}getProfile(t){return M(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return je(n)})}getKnowledgeAssistant(t){return M(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return je(n)})}getContentTypes(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return je(t)})}getAccount(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return je(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 je(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(),ee.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 ee.info(`Successfully retrieved conversation ${i.id} for session ${t}`),TS(i)})}isConversationSupported(r){return M(this,arguments,function*(t,n={}){ee.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=an(n);n.metadata&&(r.metadata=(s=n.metadata)!=null?s:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return TS(o)})}postMessages(t,n){return M(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>I(b({},an(r)),{metadata:r.metadata})))})}sendEvent(t,n){return M(this,null,function*(){yield this.preflight();let a=n,{data:r}=a,o=se(a,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((l,[c,u])=>I(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",an(I(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 ee.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/",an(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}`,an(n),{abortLatest:!0})).map(i=>I(b({},je(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`,an(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))})}getPinnedMessages(t){return M(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return je(n).map(r=>I(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",an(t),{abortLatest:!0,version:"v2"});return je(n)})}search(t){return M(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,an(t));return je(n)})}requestLoginByEmail(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return je(n)})}requestPasswordlessToken(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return je(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 je(n)})}evaluateAssistant(t,n){return M(this,null,function*(){var i;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=yield this.client.post(o,{input:(i=n==null?void 0:n.input)!=null?i:{},conversation:n==null?void 0:n.transcript});return je(s)})}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 je(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 je(s)})}translateMessages(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",an(t));return je(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(Fx);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&ee.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};Ri.exchangeTokenPromise=null;var Po=Ri;var Im=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=je(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 dA={startTime:null,stopTime:null},fA=e=>e.handlingTime,pA=Re({name:"handlingTime",initialState:dA,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(lt,()=>dA)}}),{handlingTimeStart:mA,handlingTimeStop:Am,handlingTimeReset:gA}=pA.actions,hA=pA.reducer;var yA=(e={})=>{let t=b({onAuthError:Fi(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var vA=(e={})=>{let t,n=!0,r=b({getStyleSuggestions:Si,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 N6(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end&&e.suggestionTextStart===t.suggestionTextStart}var SA=(e={})=>{let t=b({getTextSuggestions:Sr,getAutocompleteSuggestions:nu,debounce:200,check:Ur},e),n;return r=>o=>s=>{var g;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=(g=l.conversation.current)==null?void 0:g.id,d=s.type===em.toString();if(!f||!c&&!u)return a;let{input:p}=l;return N6(p,i)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let S=_s(l);S===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(S))},d?0:t.debounce)),a}};var xA=Si.fulfilled.toString();function L6(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 wA=e=>t=>n=>r=>{var c;if(r.type!==xA){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=L6(o,i);r.type===xA&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var O6=Wu({assistants:iE,auth:$w,conversation:Qw,contentTypes:GR,passwordlessToken:LI,entities:wP,handlingTime:hA,info:Sb,input:cb,settings:lE,profile:ZR,search:Tb,styleSuggestions:oI,ui:KP,textSuggestions:_P});function bA(e){return Mw({reducer:O6,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(yA()).concat(SA({debounce:200})).concat(vA({debounce:500})).concat(wA(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,s)=>o.concat(s),n)},preloadedState:e.preloadedState})}function EA(e,t,n){if(t==="")return null;let r=new RegExp(`\\b${mm(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 D6=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},F6=e=>t=>n=>r=>{var l,c,u,f,d,p;let o=t.getState(),s=Hs("inlineSuggestions")(o),i=Hs("autoSelectSuggestion")(o)||s;switch(r.type){case Fi.toString():{!r.payload&&e.emit("logout",void 0);break}case vr.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 Ls.toString():e.logSendMessage(r.payload);break;case Md.toString():e.emit("call-to-action",{cue:r.payload});break;case fn.fulfilled.toString():if(!r.isBroadcasted){let{externalConversationId:h,currentExternalIdAtRequest:g}=(c=r.payload)!=null?c:{};(!h||!g||h===g)&&e.broadcast($g,r,!1)}break;case fn.rejected.toString():break;default:break}let a=n(r);switch(r.type){case Ls.toString():e.handleAfterSendMessage(r.payload);break;case ou.toString():e.onUpdateShowTabHint(r.payload);break;case Am.toString():e.logHandlingTime();break;case Bi.toString():e.broadcast(pd,r);break;case Ns.toString():e.broadcast(pd,r);break;case Nd.toString():t.dispatch(Ns({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{let h=o.assistants.cues.find(g=>g.code===r.meta.arg.data.assistantCode);e.emit("event",I(b({},r.meta.arg),{cue:h}));break}case Cn.toString():{let{start:h,end:g}=o.input.selection;e.emit("select-suggestion",I(b({type:D6(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:h,end:g}:{start:0,end:g}})),s&&t.dispatch(Do([]));break}case rI.toString():{let{keyword:h,suggestion:g,eventMetrics:S}=r.payload,{text:y,selection:m}=o.input,v=EA(y,h,(u=m==null?void 0:m.end)!=null?u:y.length);if(!v)break;e.emit("select-suggestion",{text:g,type:"style",replace:v,suggestion:{text:g,source:"style"},eventMetrics:S});break}case id.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 Do.toString():{i&&r.payload.length>0&&t.dispatch(ad(0));break}case fn.fulfilled.toString():{let{evaluationId:h,output:g,externalConversationId:S}=r.payload,y=r.meta.arg.assistantCode;if(e.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:h,assistantCode:y,assistantOutput:tE(g),externalConversationId:S,evaluationStatus:"success"}}),!r.meta.arg.skipState){let m=t.getState().assistants.cues;e.emit("cues",m)}break}case fn.rejected.toString():{let h=r.meta.arg.assistantCode,g=(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:g,evaluationStatus:"failed"}});break}default:break}return a},CA=F6;function kS(e){return e.toISOString().replace("T"," ").replace("Z","")}var z6=(e,t)=>t.version,TA=Gt([Ui,Rr,fA,z6],(e,t,n,r)=>{if(!t)return ee.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:s}=n;return!o||!s?(ee.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:kS(o),timeStop:kS(s)}});function kA(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 hu=class extends Error{};function H6(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var _m=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 hu("Queued async function is outdated"));let o=H6();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};function RS(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return RS(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?RS(o,t):null}function PS(e,t){return RS(e,t)}var B6={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},RA=(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 ee.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let r=e[B6[t]];return r&&r.length>0?r.map(a=>a.code):(ee.warn(`No assistant set in profile for conversation event "${t}"`),[])};function PA(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function U6(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Mm(e){return U6(e)&&(wi(e)||fm(e))}var AA,Wr=new Map,V6=["bottom","height","left","right","top","width"],IA=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:V6.some(n=>e[n]!==t[n]);function _A(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,..._A(t)]:[]}function MA(e,t){return!e||!t?null:I(b({},e),{top:e.top+t.top,left:e.left+t.left})}var Nm=!1,NA=()=>{Nm=!0;let e=[];if(Wr.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Wr.delete(n);return}let r=n.getBoundingClientRect();IA(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(MA,t.rect):t.rect;IA(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Wr.size===0){Nm=!1;return}AA=window.requestAnimationFrame(NA)};function IS(e,t){let n=_A(e),r=[],o=n.map((s,i)=>IS(s,a=>{r[i]=a;let l=Wr.get(e);if(!l)return;let c=r.reduce(MA,l.rect);l.callbacks.forEach(u=>u(c))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),Wr.has(e)){let i=Wr.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else Wr.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!Nm&&NA()},unobserve(){o.forEach(i=>i.unobserve());let s=Wr.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||Wr.delete(e),Wr.size||(cancelAnimationFrame(AA),Nm=!1)}}}}var LA,$r=new Map,OA=()=>{$r.forEach((e,t)=>{if(!t.isConnected){$r.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)))}),$r.size!==0&&(LA=window.requestAnimationFrame(OA))};function DA(e,t){return{observe(){let n=$r.size===0;$r.has(e)?$r.get(e).callbacks.push(t):$r.set(e,{visible:void 0,callbacks:[t]}),n&&OA()},unobserve(){let n=$r.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||$r.delete(e),$r.size||cancelAnimationFrame(LA)}}}}var AS=["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 _S(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Za(e){return Number.parseFloat(e)}function Lm(e){return Math.round(e*1e6)}function FA(e){return e/1e6}function MS(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Za(e.width),s=Za(e.borderLeftWidth),i=Za(e.borderRightWidth),a=Za(e.paddingRight),l=FA(Lm(o)-Lm(s)-Lm(i)),c=FA(Lm(r));if(l-c>2){let u=l-c;n.style.paddingRight=`${a+u}px`}}function yu(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",ni(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};_S(r,n,AS),MS(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=DA(e,()=>{_S(r,n,AS),MS(r,e,n),s(),setTimeout(s,0)}),a,l=!0,c=IS(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(_S(r,n,AS),MS(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),g=Za(h.borderTopWidth),S=Za(h.borderBottomWidth),y=p.top+g-d.top,m=d.top+d.height+-(p.top+p.height-S);n.style.clipPath=`inset(${y}px 0px ${m}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 j6(e){return e.offsetParent!==null}function zA(e){if(!j6(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 Om(e,t,n=100){let r=zA(e);t({isVisible:r});let o=setInterval(()=>{let s=zA(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var HA=(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){ee.warn("[Deepdesk] SessionStorage is blocked by browser")}}});var ke=E(P());var BA=HA("showTabHint",!0),Ja=class Ja{constructor({deepdeskUrl:t,version:n=Ja.version||"unknown",locale:r="en-US",token:o,fetch:s,productName:i,createCustomChannel:a,websocketClient:l=Im}){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 _m;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let c=t.replace(/\/api$/,"");this.deepdeskApi=new Po(c,{token:o,fetch:s}),this.version=n,this.instanceId=Ja.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[CA({broadcast:(h,g,S)=>{this.broadcastEvents.send(h,g,S)},emit:(h,g)=>this.emit(h,g),handleAfterSendMessage:h=>this.handleAfterSendMessage(h),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:h=>this.logSendMessage(h),onUpdateShowTabHint:h=>BA.update(h),sendEvent:(h,g)=>this.deepdeskApi.sendEvent(h,g)})]};this.store=bA(u),this.broadcastEvents=new cA({debug:!0,deepdeskUrl:c,eventMap:kb(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=Rt(this.state))!=null?h:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(ou(BA.value())),this.store.dispatch(Ld({locale:r,adminUrl:c,productName:i}));let f=[],d=h=>{if(!h.conversationId)return;let g=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(sE(h))};this.hasConversation()?g():f.push(g)};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 g=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(oE(h))};this.hasConversation()?g():f.push(g)}),this.ws.on("assistants::suggest_as_reply",h=>{if(!h.conversationId)return;let g=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(Bi([{text:h.payload.message,type:"text",source:"assistant",assistantCode:h.code,sourceLabel:h.name}]))};this.hasConversation()?g():f.push(g)});let p=this.whenConversationLoaded(()=>{var h;this.broadcastEvents.setExternalId((h=this.state.conversation.current)==null?void 0:h.externalId),f.forEach(g=>g()),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=Ms(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?(ee.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(ee.warn("Profile has not been loaded (yet)"),!0):(ee.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(t){if(Rt(this.state))t();else{let n=this.subscribe(Rt,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Fi(null)),this.store.dispatch(Yr()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return M(this,null,function*(){return(yield this.store.dispatch(Yr())).payload})}isConversationSupported(t,n){return M(this,null,function*(){return(yield this.store.dispatch(zg({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(rd(I(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(od({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(Hg(I(b({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return M(this,null,function*(){yield this.store.dispatch(Bg(t))})}updateConversation(t){return M(this,null,function*(){return(yield this.store.dispatch(sd(t))).payload})}resetConversation(){this.store.dispatch(lt()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(Ld(t))}setVisitorInfo(t){this.store.dispatch(gb(t))}setCustomData(t){this.store.dispatch(hb(t))}setAgentInfo(t,n){return M(this,null,function*(){var o;yield this.store.dispatch(hl(b(b({},t),n))),(o=this.state.info.agentInfo)!=null&&o.agentNickname||this.broadcastEvents.send(fd,{showNicknameDialog:!0})})}setAgentSettings(t){return M(this,null,function*(){yield this.store.dispatch(Vg(t))})}getAgentSettings(){return M(this,null,function*(){return(yield this.store.dispatch(jg())).payload})}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(ld({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()}))}notifyExternalSuggestion(t){this.store.dispatch(Cn(t))}evaluateAssistant(t,n){return M(this,null,function*(){var c;let{input:r={},transcript:o,showCuesInWidget:s=!0,includeMetadata:i,externalConversationId:a}=n||{},l=yield this.store.dispatch(fn({assistantCode:t,transcript:o,includeMetadata:i,input:r,externalConversationId:a,skipState:!s}));if(l.error)throw new Error(`Assistant evaluation failed: ${(c=l.payload)!=null?c:l.error.message}`);return l.payload.output})}evaluateConversationAssistant(t,n){return M(this,null,function*(){var u,d;yield this.loadProfileConfig();let r=this.state.profile.data;if(!r){ee.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=RA(r,t),s=(u=n==null?void 0:n.showCuesInWidget)!=null?u:!0,f=n!=null?n:{},{showCuesInWidget:i}=f,a=se(f,["showCuesInWidget"]),l=(d=n==null?void 0:n.externalConversationId)!=null?d:this.hasConversation()?this.externalId():"",c=yield Promise.all(o.map(p=>this.queues.push(p,()=>M(this,null,function*(){var g,S;let h=yield this.store.dispatch(fn(I(b({assistantCode:p,includeMetadata:!0},a),{skipState:!s})));if(h.error)throw new Error(`Assistant evaluation failed: ${(g=h.payload)!=null?g:h.error.message}`);return{assistantCode:p,evaluationId:h.payload.evaluationId,output:h.payload.output,externalConversationId:(S=h.payload.externalConversationId)!=null?S:l}})).catch(h=>{if(h instanceof hu)return ee.warn(`Queued assistant "${p}" was outdated and dropped`),null;throw h})));if(!s)return c.filter(p=>p!==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(nb(Ug(t))),!Ur(this.state)||t.key!=="Tab"&&!c)return;let h=()=>{n||!p||i&&(t.shiftKey||(this.store.dispatch(sb()),t.preventDefault()))},g=()=>{n||!p||f&&s<=0||i&&(t.shiftKey||(this.store.dispatch(ib()),t.preventDefault()))};switch(t.key){case"ArrowUp":d==="below"?g():h();break;case"ArrowDown":{d==="below"?h():g();break}case"Escape":{n||(this.store.dispatch(ad(-1)),this.store.dispatch(hs({collapse:!0})),this.store.dispatch(WP(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let S=Hi(this.state);if(!S)return;this.store.dispatch(ou(!1)),this.store.dispatch(Cn({text:S.text,suggestion:S,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(f||this.state.input.selectedSuggestionIndex===-1)return;let S=Hi(this.state);if(!S)return;this.store.dispatch(Cn({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=Hi(this.state);if(!S)return;this.store.dispatch(Cn({text:S.text,suggestion:S,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(hs({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Do([]))}handlingTimeStart(){this.state.handlingTime.startTime||(ee.info("Start handling time"),this.store.dispatch(mA()))}handlingTimeStop(){this.state.handlingTime.startTime&&(ee.info("Stop handling time"),this.store.dispatch(Am()))}logSendMessage(t){let n=kA(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=TA(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(gA()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Ls((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(lb()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(s){ee.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),ee.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(yb(t))}whenConversationLoaded(t){let n=s=>{var i;return(i=s.conversation.current)==null?void 0:i.id},r=()=>this.loadProfileConfig().then(()=>t());return n(this.state)&&r(),this.subscribe(n,s=>{s&&r()})}overlayContainerFactory(t,n,r,o){let[s,i]=yu(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]=yu(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 ni(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),ee.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()?(ee.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(ab(r.metrics))):ee.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(!Mm(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=se(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),c={customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),ni(t),this.inputMediator=a||(wi(t)?new Ci(t):new Ei(t)),this.inputMediator.on("change",({plainText:p,rawHTML:h,suggestionTextStart:g})=>{this.store.dispatch(ld({text:p,html:h,suggestionTextStart:g}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(rb(Ug(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:h})=>{this.store.dispatch(ob({text:p,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(tb(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(cd(p))},500):this.store.dispatch(cd(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(rm(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(rm(!0))}),this.renderSuggestions(t,c),this.subscribe(Hs("inlineSuggestions"),()=>{this.renderSuggestions(t,c)}),this.subscribe(Hs("suggestionsPlacement"),()=>{this.renderSuggestions(t,c)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(ld({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()})),this.store.dispatch(cd(this.inputMediator.getSelection())),this.store.dispatch(rm(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,Io.createRoot)(n),o=null,s=a=>{o=a,i()},i=()=>{r==null||r.render((0,ke.jsx)(bo,{store:this.store,children:(0,ke.jsx)(Qr,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(aI,{id:"deepdesk-nickname-dialog",error:o,onSave:a=>M(this,null,function*(){try{yield this.store.dispatch(pb({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(fd,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(l){ee.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,Io.createRoot)(o);s.render((0,ke.jsx)(bo,{store:this.store,customStyles:r,children:(0,ke.jsx)(Qr,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(sI,{})})}));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&&PS(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,Io.createRoot)(l);d.render((0,ke.jsx)(bo,{store:this.store,customStyles:o,children:(0,ke.jsx)(Qr,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(_I,{inputElement:t})})}));let p=(0,Io.createRoot)(u);return p.render((0,ke.jsx)(bo,{store:this.store,customStyles:o,children:(0,ke.jsx)(Qr,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(hI,{onLogIn:()=>this.loginViaPopup().catch(h=>ee.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&&PS(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,Io.createRoot)(l);return u.render((0,ke.jsx)(bo,{store:this.store,customStyles:r,children:(0,ke.jsx)(Qr,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(VP,{onLogIn:()=>this.loginViaPopup().catch(f=>ee.warn(f.message))})})})),{unmount(){u.unmount(),c()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays"),o=(0,Io.createRoot)(r);return o.render((0,ke.jsx)(bo,{store:this.store,customStyles:n,children:(0,ke.jsx)(Qr,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(FP,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&ee.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}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:s}),this.widgetRoot=(0,Io.createRoot)(t),this.widgetRoot.render((0,ke.jsx)(bo,{store:this.store,customStyles:r,children:(0,ke.jsx)(Qr,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(rA,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(i=>ee.warn(i.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,Io.createRoot)(n);return i.render((0,ke.jsx)(bo,{store:this.store,customStyles:o,children:(0,ke.jsx)(Qr,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(vS,{children:(0,ke.jsxs)(Lp,{assistantCode:t,initialQuestion:s,evaluateKnowledgeAssistFn:Ll,children:[(0,ke.jsx)(Oi,{children:(0,ke.jsx)(Dp,{title:r.title,emptyState:r.emptyState})}),(0,ke.jsx)(yS,{children:(0,ke.jsx)(Op,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(t){let n=Om(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){PA(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>M(this,null,function*(){yield this.store.dispatch(Vc());let t=ci(this.state);t&&this.store.dispatch(Ld({showSearch:t.search,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions}))})),this.loadProfileConfigPromise)}loginViaPopup(t){return M(this,null,function*(){return new Promise((n,r)=>{this.store.dispatch(td());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,g;if((h=p.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((g=p.data)==null?void 0:g.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(vl),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");u===null&&r(new Error("Popup blocked by browser"));let f=p=>M(this,null,function*(){var h;if(p.origin===a.origin)switch((h=p.data)==null?void 0:h.type){case"deepdesk-popup-request-origin":{try{let g=JSON.stringify({type:"deepdesk-popup-parent-origin"});u==null||u.postMessage(g,a.origin)}catch(g){ee.error("Error posting message to popup",g),r(g)}break}case"deepdesk-popup-loaded":{try{let g=JSON.stringify({type:"deepdesk-popup-create-channel"});u==null||u.postMessage(g,a.origin,[o.port2])}catch(g){ee.error("Error posting message to popup",g),r(g)}break}case"deepdesk-popup-error":{if(c(),p.data.message==="Platform account url mismatch"){let g=`Please contact your administrator: The platform account url (${p.data.targetOrigin}) is misconfigured as it differs from the origin of the page that opened the popup (${p.data.openerOrigin}).`;ee.warn(g),this.store.dispatch(Og(g)),r(new Error(g))}if(p.data.message==="Timeout"){let g="Please contact your administrator: Popup timed out. Check if the account's platform url is configured correctly.";ee.warn(g),this.store.dispatch(Og(g)),r(new Error(g))}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(em()))})}refreshWidgetSuggestions(){return M(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=jc(this.state);try{n.forEach(({type:r})=>{switch(r){case"entities":this.store.dispatch(vr());break;case"pinned-messages":case"sticky-messages":break;default:Bu.includes(r)||this.store.dispatch(Sr(r))}})}catch(r){this.handleError(r)}})}};Ja.version="19.3.2-beta.0",Ja.count=0;var vu=Ja;function W6(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 UA(e,t){return M(this,null,function*(){let n=yield W6(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 VA(e,t,n){return M(this,null,function*(){yield new Po(e).authenticateWithKey(t,n)})}function jA(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function WA(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 $A(r,o){return M(this,arguments,function*(e,t,n={}){let s=n.replace?bs(e,n.replace.start,n.replace.end):Xa(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?bs(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 $6(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 K6(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 KA(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):KA(n,t)}function GA(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?$6(t):K6(t);n?KA(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 h_(G6);})();
|
|
86
86
|
/*! Bundled license information:
|