@deepdesk/deepdesk-sdk 19.1.2-beta.2 → 19.2.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
|
@@ -78,7 +78,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error
|
|
|
78
78
|
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
|
|
79
79
|
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 k0=b(R()),f5={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},lP=({className:e,color:t})=>(0,k0.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,k0.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:f5[t||"pink"]})});var cP={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedIn:"dd-XvHAn",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var R0={};dt(R0,{enUS:()=>p5,nlNL:()=>m5});var p5={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},m5={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var ds=b(R()),dP=({onLogIn:e})=>{let t=ie(R0),n=ee("floatingMenu"),r=ee("productName"),o=ye(),i=$(St),s=D("FloatingMenu",cP);if(i===null||n===!1)return null;let a=()=>{i===!0?o(Qn(!0)):e()};return(0,ds.jsxs)("button",{type:"button",className:(0,uP.default)(s.root,{[s.isLoggedIn]:i,[s.isLoggedOut]:!i}),onClick:a,children:[(0,ds.jsx)("div",{className:s.text,children:t(i?"search":"signin",{productName:r})}),(0,ds.jsxs)("div",{className:s.icon,children:[(0,ds.jsx)(lP,{className:s.logo,color:"pink"}),i===!1&&(0,ds.jsx)(aP,{className:s.lock})]})]})};var Gp=b(X());function Dr(e){let{showMidSentenceSuggestions:t,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:r}=e.settings,{text:o,selection:i}=e.input;return i.start!==i.end?!1:i.end>=o.length?!0:t?n&&new RegExp(n).test(o.substring(i.end))||r&&new RegExp(r).test(o.substring(0,i.end))?!0:n===!1&&r===!1:!1}var g5={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1},Wp=({ui:e})=>e.overlayCollapsed,fP=Ee({name:"ui",initialState:g5,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:Yc,setInputFocus:$p,setOverlayCollapsed:di,setOpenOverlayWhenTyping:pP,setOverlayCollapsedUserOverwrite:mP}=fP.actions,gP=fP.reducer;var wP=b(X());var fi=b(X());var hP=b(X());function yP(e,t,n){(0,hP.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var vP={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 Xc=b(R()),xP=({title:e})=>(0,Xc.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18px",height:"18px",viewBox:"0 0 24 24","aria-labelledby":"closeTitle",children:[(0,Xc.jsx)("title",{id:"closeTitle",children:e}),(0,Xc.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 P0={};dt(P0,{enUS:()=>h5,nlNL:()=>y5});var h5={assistant:[{type:0,value:"Assistant"}],close:[{type:0,value:"Close"}]},y5={assistant:[{type:0,value:"Assistent"}],close:[{type:0,value:"Sluiten"}]};var Pn=b(R()),x5=["search","personal-collection-search","search-autocomplete"];function S5(e,t,n,r={}){var i;let o="";return x5.includes(t)?o=_R(v0(e,n,{stripAgentPart:!0}),(i=r.searchKeywords)!=null?i:[n]):o=v0(e,n,r),r.placeholders===!0&&(o=MR(o)),o}var w5=()=>{},b5=({selected:e,suggestion:t})=>{let n=ie(P0),r=ee("inlineSuggestions"),o=$(As),[i,s]=(0,fi.useState)(!1),a=ee("enableSuggestionFeedback"),l=$(x=>x.input.text),c=ye(),u=D("TextSuggestion",vP),f=(0,fi.useRef)(null),d=t.source==="assistant",p=a&&!d;(0,fi.useEffect)(()=>{let x=setTimeout(()=>{c(Aw({text:t.text,suggestion:t}))},500);return()=>{clearTimeout(x)}},[t]),yP(f,"click",()=>{c(vn({suggestion:t,text:t.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let h=()=>{c(Ri({source:t.source,text:t.text,assistantCode:t.assistantCode}))},g=(0,fi.useMemo)(()=>S5(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,Pn.jsxs)("div",{className:u.root,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),children:[(0,Pn.jsx)(de,{ref:f,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:w5,children:t.source==="assistant"?(0,Pn.jsxs)("div",{className:u.assistantContainer,children:[(0,Pn.jsx)(ci,{containerTagName:"div",tagName:"span",className:u.formattedTextTruncated,content:g}),(0,Pn.jsx)("span",{className:u.assistantBadge,children:n("assistant")})]}):(0,Pn.jsx)(ci,{containerTagName:"div",tagName:"span",className:u.formattedText,content:g})}),p&&i&&(0,Pn.jsx)("div",{className:u.actions,children:(0,Pn.jsx)(Bp,{source:"overlay",context:l,suggestion:t})}),d&&i&&(0,Pn.jsx)("div",{className:u.closeIconContainer,children:(0,Pn.jsx)("button",{type:"button",className:u.closeIcon,onClick:h,title:n("close"),children:(0,Pn.jsx)(xP,{title:n("close")})})})]})},SP=b5;var bP=b(R()),E5=({suggestions:e,selectedIndex:t,reverse:n})=>(0,wP.useMemo)(()=>{let o=e.map((i,s)=>(0,bP.jsx)(SP,{index:s,selected:s===t,suggestion:i},`${i.text}-${i.source}`));return n?o.reverse():o},[e,t,n]),Kp=E5;var EP={root:"dd-PfvRI",paper:"dd-HYlyY"};var Qc=b(R()),C5=()=>{let e=(0,Gp.useRef)(null),t=D("InlineSuggestionsOverlay",EP),n=$(Dr),r=ye(),o=$(St),i=$(Ps),s=$(Wp),a=ee("showTextSuggestions"),l=$(ki),c=$(ol);return ri(()=>{setTimeout(()=>{r(di({collapse:!0,skipWhenInputFocus:!0}))})}),(0,Gp.useEffect)(()=>{let u=e.current;if(!u||!u.parentElement)return;u.parentElement.style.left="0px";let f=u.getBoundingClientRect();u.parentElement.style.left=`${Math.min(window.innerWidth-4-f.right,0)}px`}),s||!n||!a||l.length===0||o!==!0||i===!1?null:(0,Qc.jsx)("div",{className:t.root,"data-variant":"inline",children:(0,Qc.jsx)("div",{ref:e,className:t.paper,children:(0,Qc.jsx)(zt,{children:(0,Qc.jsx)(Kp,{suggestions:l,selectedIndex:c})})})})},CP=C5;var pi=b(X());var TP={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 A0={};dt(A0,{enUS:()=>T5,nlNL:()=>k5});var T5={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."}]},k5={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 ct=b(R()),kP=({onClose:e,onSave:t,id:n,error:r})=>{let[o,i]=(0,pi.useState)(""),[s,a]=(0,pi.useState)(!1),[l,c]=(0,pi.useState)(!1),u=D("Nickname",TP),f=pi.default.useRef(null),d=$(y=>y.info.showNicknameDialog),p=ie(A0),h=ee("adminUrl");(0,pi.useEffect)(()=>{r&&a(!0)},[r]);let g=()=>{if(!f.current)return;o.trim()?f.current.setCustomValidity(""):f.current.setCustomValidity(p("nicknameDialogError")),f.current.reportValidity()},x=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,ct.jsxs)(Aa,{isOpen:d,"datatest-id":n,onClose:e||(()=>{}),onBack:e||(()=>{}),children:[(0,ct.jsx)("div",{className:u.titleWrapper,children:(0,ct.jsx)("h1",{className:u.title,children:p("title")})}),(0,ct.jsxs)("form",{className:u.dialogContent,onSubmit:x,children:[(0,ct.jsx)("p",{children:p("nicknameDialogTitle")}),s&&r&&(0,ct.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 S=y.substring(0,v),E=y.substring(v+m.length);return(0,ct.jsxs)(ct.Fragment,{children:[S,(0,ct.jsx)("a",{href:m,target:"_blank",rel:"noopener noreferrer",className:u.errorLink,children:m}),E]})}return y})():p("nicknameDialogSaveErrorWithoutLink")}),(0,ct.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)),i(y.target.value)},onBlur:g,ref:f}),l&&(0,ct.jsx)("div",{className:u.errorMessage,role:"alert",children:p("nicknameDialogEmojiError")}),(0,ct.jsxs)("div",{className:u.buttonsWrapper,children:[r?(0,ct.jsx)("div",{className:u.closeButtonWrapper,children:(0,ct.jsx)("button",{type:"button",className:u.closeButton,onClick:()=>e==null?void 0:e(),children:p("close")})}):null,(0,ct.jsx)("div",{className:u.buttonContinueWrapper,children:(0,ct.jsx)("button",{type:"submit",className:u.continueButton,disabled:!o.trim()||new RegExp("\\p{Extended_Pictographic}","u").test(o),children:p("nicknameDialogContinueButton")})})]})]})]})};var Zc=b(R()),R5=({children:e})=>{let n=ee("locale").replace("-","");return(0,Zc.jsx)(_g.Provider,{value:n,children:e})},P5=({store:e,customStyles:t={},children:n})=>(0,Zc.jsx)(PS,{store:e,children:(0,Zc.jsx)(R5,{children:(0,Zc.jsx)(Ga.Provider,{value:t,children:n})})}),vo=P5;var Yp=b(Me()),Na=b(X());var RP=b(X());function PP(e,t){let[n,r]=(0,RP.useState)(()=>{if(typeof window=="undefined")return t;try{let i=window.localStorage.getItem(e);return i?JSON.parse(i):t}catch(i){return J.error(i),t}});return[n,i=>{try{let s=i instanceof Function?i(n):i;r(s),typeof window!="undefined"&&window.localStorage.setItem(e,JSON.stringify(s))}catch(s){J.error(s)}}]}var AP=()=>/Mac/i.test(navigator.platform);var _P=b(Me()),xo=b(X());var I0={};dt(I0,{enUS:()=>A5,nlNL:()=>I5});var A5={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"}]}]},I5={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 IP={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};var mi=b(R()),_0=(e,t,n)=>r=>(0,mi.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),_5=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r,onLogIn:o})=>{let i=ie(I0),s=on(),a=D("Login",IP),l=ee("productName"),c=(0,xo.useCallback)(x=>{x.preventDefault(),r&&r(Number.parseInt(x.target.value,10))},[]),u=(0,xo.useCallback)(x=>{x.preventDefault(),s.send(Ns,!0)},[t]),f=(0,xo.useMemo)(()=>x=>(0,mi.jsx)("a",{onClick:m=>{m.preventDefault(),o()},href:t,className:a.anchor,target:"_blank",rel:"noreferrer",children:x},"login"),[t]),d=(0,xo.useCallback)(x=>(0,mi.jsx)("button",{type:"button",className:a.anchorButton,onClick:u,children:x},"prompt"),[u]),{min:p,hour:h,day:g}=(0,xo.useMemo)(()=>({min:_0(a,600,c),hour:_0(a,3600,c),day:_0(a,3600*12,c)}),[]);return(0,mi.jsxs)("div",{className:(0,_P.default)(e,a.root),children:[i("loginPlease",{login:n?d:f,productName:l}),r&&(0,mi.jsxs)(xo.Fragment,{children:[(0,mi.jsx)("br",{}),i("snooze",{min:p,hour:h,day:g})]})]})},qp=_5;var MP={root:"dd-DoQhb",text:"dd-Jwnev"};var Jc=b(R()),M5=({title:e})=>{let t=D("SearchTrigger",MP),n=ye(),r=Xe();return(0,Jc.jsxs)("button",{type:"button",className:t.root,onClick:()=>{n(Qn(!0)),r("open search",{via:"autocomplete-overlay"})},children:[(0,Jc.jsx)(Ma,{}),(0,Jc.jsx)("span",{className:t.text,children:e})]})},LP=M5;var M0={};dt(M0,{enUS:()=>L5,nlNL:()=>N5});var L5={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"}]},N5={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 NP={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 _e=b(R()),O5=({onLogIn:e})=>{let t=D("SuggestionsOverlay",NP),n=ie(M0),r=$(Dr),o=$(Pw),i=ye(),s=(0,Na.useRef)(null),a=ee("searchTriggerKey"),l=ee("productName"),c=$(Wp),u=$(St),f=$(gw),d=$(Ps),[p,h]=(0,Na.useState)(null),g=ee("showSearch"),x=ee("showTextSuggestions"),y=ee("adminUrl"),m=ee("isEmbedded"),v=ee("suggestionsPlacement"),[S,E]=PP("dd-snooze-until-ms",0),T=c||S>Date.now(),k=$(ki),A=$(ol),H=k.filter(Q=>Q.source!=="gpt").length,O=()=>{T&&E(0),i(mP(!T))},L=Q=>{let q=Date.now()+Q*1e3;E(q),J.info(`Snooze until: ${new Date(q)}`),i(di({collapse:!0}))};return(0,Na.useEffect)(()=>{H===0&&h(null)},[k,H]),ri(()=>{i(di({collapse:!0,skipWhenInputFocus:!0}))}),u===null||d===!1?null:u===!1?(0,_e.jsxs)("div",{ref:s,className:(0,Yp.default)(t.root,{[t.isCollapsed]:T}),children:[!T&&(0,_e.jsxs)("div",{className:t.triggers,children:[(0,_e.jsx)("div",{style:{flex:1}}),(0,_e.jsx)("div",{className:t.triggersRight,children:(0,_e.jsx)(wi,{className:t.toggleButton,title:n("collapse"),onClick:O,isCollapsed:!1})})]}),(0,_e.jsx)("div",{className:t.toggleButtonWrapper,children:(0,_e.jsx)(wi,{className:t.toggleButton,title:n("open",{productName:l}),onClick:O,isCollapsed:!0})}),(0,_e.jsxs)("div",{className:t.collapsible,children:[f&&(0,_e.jsxs)("div",{className:t.loginError,children:[(0,_e.jsx)("span",{className:t.loginErrorMessage,children:f}),(0,_e.jsx)("button",{type:"button",className:t.loginErrorDismiss,onClick:()=>i(ju()),"aria-label":n("dismissError"),children:n("dismiss")})]}),(0,_e.jsx)(qp,{loginUrl:y,isEmbedded:m,onLogIn:e,onSnooze:L})]})]}):!o||!r?null:(0,_e.jsxs)("div",{ref:s,className:(0,Yp.default)(t.root,{[t.isCollapsed]:T}),children:[!T&&(0,_e.jsxs)("div",{className:t.triggers,children:[(0,_e.jsx)("div",{style:{flex:1},children:g&&(0,_e.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>h(n(AP()?"searchHintMac":"searchHintWindows",{searchTriggerKey:a.toUpperCase()})),onMouseLeave:()=>h(null),children:(0,_e.jsx)(LP,{title:n("search")})})}),(0,_e.jsxs)("div",{className:t.triggersRight,onFocus:()=>{},children:[(0,_e.jsx)("div",{className:(0,Yp.default)(!p&&t.hintsHidden,t.hints),children:p}),(0,_e.jsx)(wi,{className:t.toggleButton,title:n("collapse"),onClick:O,isCollapsed:!1})]})]}),(0,_e.jsx)("div",{className:t.toggleButtonWrapper,children:(0,_e.jsx)(wi,{className:t.toggleButton,title:n("open",{productName:l}),onClick:O,isCollapsed:!0})}),H>0&&x&&(0,_e.jsx)("div",{className:t.collapsible,onFocus:()=>{},children:(0,_e.jsx)(zt,{children:(0,_e.jsx)(Kp,{suggestions:k,selectedIndex:A,reverse:v==="above"})})})]})},OP=O5;var am=b(Me());var bo=b(X());var Oa=b(X());function Xp(e){return e.contentEditable==="true"}function D5(e){let t=0,n=0,r=window.getSelection();if(r.rangeCount!==0){let o=r.getRangeAt(0),i=o.cloneRange();i.selectNodeContents(e),i.setEnd(o.endContainer,o.endOffset),n=i.toString().length,i.selectNodeContents(e),i.setEnd(o.startContainer,o.startOffset),t=i.toString().length}return{selectionStart:t,selectionEnd:n}}function DP(e){let{selectionStart:t,selectionEnd:n}=Xp(e)?D5(e):e;return[t,n]}function FP(e){let[,t]=(0,Oa.useState)(),n=(0,Oa.useRef)(null);return n.current=DP(e),(0,Oa.useEffect)(()=>{let r=()=>{var a;let[o,i]=(a=n.current)!=null?a:[],s=DP(e);(!s||o!==s[0]||i!==s[1])&&(n.current=s,t({}))};return e.addEventListener("keyup",r),e.addEventListener("click",r),e.addEventListener("focus",r),document.addEventListener("selectionchange",r),()=>{e.removeEventListener("keyup",r),e.removeEventListener("click",r),e.removeEventListener("focus",r),document.removeEventListener("selectionchange",r)}},[e]),n.current}function zP(e,t){if(!t)return;let n=e,{value:r}=n,[o,i]=t,s=r.match(Ru);if(!s||s.length===0)return;let a=0;s.find(l=>{let c=r.indexOf(l,a);return o>c&&i<c+l.length?(n.selectionStart=c,n.selectionEnd=c+l.length,!0):(a=c+l.length,!1)})}var HP=b(X()),F5=["div","span","mark","strong","b","i","u","em"];function L0(e,t,n=0){var i;let r=e[e.length-1],o=typeof r=="object"&&r!==null?(i=r.props)==null?void 0:i.tagName:void 0;if(o==="br")return e.pop(),[...e,...t,r];if(F5.includes(o)){let s=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,HP.cloneElement)(r,{children:L0(s,t,n+1)})]}return[...e,...t]}function fs(e){return e.tagName.toLowerCase()==="textarea"}var BP={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 $P=b(Me());var nm=b(X());var Da=b(X());function UP(e,t){let n;return[(...r)=>{window.cancelAnimationFrame(n);let o=t?t(...r):r;n=window.requestAnimationFrame(()=>{e(...o)})},()=>window.cancelAnimationFrame(n)]}function Qp(e){let t=(0,Da.useRef)(null),[n,r]=(0,Da.useState)(!1);return(0,Da.useEffect)(()=>{var u;let o=!1,i=Number.parseFloat((u=window.getComputedStyle(document.body).zoom)!=null?u:"1"),[s,a]=UP((f,d)=>{let p=t.current;if(!p)return;let h=f/i,g=d/i,x=p.getBoundingClientRect(),y=h>x.x&&h<x.x+x.width&&g>x.y&&g<x.y+x.height;y&&!o?(o=!0,r(!0)):!y&&o&&(o=!1,r(!1))},({clientX:f,clientY:d})=>[f,d]),[l,c]=UP(()=>{o=!1,r(!1)});return e.addEventListener("mousemove",s),e.addEventListener("mouseleave",l),()=>{a(),c(),e.removeEventListener("mousemove",s),e.removeEventListener("mouseleave",l)}},[t]),[t,n]}function VP(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Zp(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function jP(e){return e!=null}var WP=b(Me()),Jp=b(X());var So={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 N0=b(R()),em=(0,Jp.forwardRef)((o,r)=>{var i=o,{className:e,children:t}=i,n=oe(i,["className","children"]);let s=(0,Jp.useRef)(null),a=D("TabCompletion",So);return(0,N0.jsx)("div",P(w({ref:Zp([s,r]),className:(0,WP.default)(e,a.popoverContentContainer)},n),{children:(0,N0.jsx)("div",{className:a.popoverContent,children:t})}))});var gi=b(R()),z5=e=>t=>{let n=xv(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},H5=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let i=D("TabCompletion",So),s=qf(),a=(0,nm.useMemo)(()=>z5(e.getBoundingClientRect()),[e]),[l,c]=Qp(e);return(0,nm.useEffect)(()=>{c?s.open():s.close()},[c]),(0,gi.jsxs)("span",{children:[(0,gi.jsx)("mark",{ref:Zp([l,s.triggerRef]),className:(0,$P.default)(i.matchKeyword,{[i.hover]:c}),"aria-haspopup":"dialog","aria-expanded":s.opened?"true":"false",children:r}),s.opened&&(0,gi.jsx)(pa,{className:i.popover,triggerRef:s.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,gi.jsx)(em,{style:n,children:(0,gi.jsx)("div",{className:i.hintText,children:o})})})]})},tm=class extends go{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=>P(w({},o),{keywordRegex:new RegExp(`\\b${VP(o.keyword)}\\b`,"i")})),this.keywordMatches=r.keywordMatches),this.usedKeywordMatches.clear(),n}match(n){let r=this.preparedKeywordMatches.map(i=>{if(this.usedKeywordMatches.has(i))return null;let s=n.match(i.keywordRegex);if(!s)return null;let a=n.charAt(s.index-1),l=n.charAt(s.index+i.keyword.length);return a==="{"&&l==="}"?null:{index:s.index,length:s[0].length,match:s[0],matchString:s[0],suggestion:i.suggestion,preparedKeywordMatch:i,valid:!0}}).filter(jP);if(r.length===0)return null;let o=r.reduce((i,s)=>s.index<i.index?s:i);return this.usedKeywordMatches.add(o.preparedKeywordMatch),o}replaceWith(n,r){return(0,gi.jsx)(H5,{inputElement:r.inputElement,suggestion:r.suggestion,inputStyle:r.inputStyle,boundaryRef:r.boundaryRef,children:n},`keyword_${r.matchString}_${r.key}`)}asTag(){return"mark"}};var KP=b(Me());var O0=b(R()),B5=({inputElement:e,children:t})=>{let n=D("TabCompletion",So),[r,o]=Qp(e);return(0,O0.jsx)("mark",{ref:r,className:(0,KP.default)(n.matchPlaceholder,{[n.hover]:o}),children:t})},rm=class extends go{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,O0.jsx)(B5,{inputElement:n.inputElement,children:t},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var im=b(Me());var Jt=b(X());var D0=b(R()),GP=()=>(0,D0.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,D0.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 Fr=b(X());var YP=b(l0());var qP={root:"dd-ky-Bv",content:"dd-kV5e1"};function om(e,t,n){var o;let r=((o=e.imageSizes)==null?void 0:o[t])||e.image||n;if(!r)return null;try{return new URL(r).toString()}catch(i){return null}}function F0(e){return e.replace("https://www.","").replace("https://","")}var jn=b(R()),U5=3,V5=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),j5=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=U5})=>{let i=D("LinkSearch",qP),[s,a]=(0,Fr.useState)(""),l=ye(),c=$(QR("url")),u=$(Zw("URL")),f=(0,Fr.useMemo)(()=>u.map(V5),[u]),[d,p]=(0,Fr.useState)(f.length-1),h=ee("fallbackImage"),g=v=>{let S=v.target;a(S.value)},x=(v,S)=>{v.stopPropagation(),v.preventDefault(),window.open(S,"_blank")},y=v=>{var T;let S=d-1<0?f.length-1:d-1,E=d+1===f.length?0:d+1;v.code==="Escape"&&(a(""),t()),v.code==="ArrowUp"&&p(S),v.code==="ArrowDown"&&p(E),v.code==="Enter"&&e(((T=f[d])==null?void 0:T.text)||s)},m=(0,Fr.useCallback)((0,YP.default)(v=>{l(Ai({query:v,type:"URL",tags:["link-search"]}))},300),[]);return(0,Fr.useEffect)(()=>{s&&m(s)},[s]),(0,Fr.useEffect)(()=>()=>{l(Zu())},[]),(0,jn.jsxs)("div",{className:i.root,children:[(0,jn.jsx)(zt,{withDivider:!0,children:(s?f:c).slice(0,o).map((v,S)=>(0,jn.jsx)(de,{selected:d===S,onClick:()=>e(v.text),"data-testid":"linksearch-suggestion",children:(0,jn.jsxs)(he,{children:[(0,jn.jsx)(he.Image,{src:om(v,"small",h||void 0),title:v.title||v.text}),(0,jn.jsxs)(he.Content,{className:i.content,cropText:!0,children:[(0,jn.jsx)(he.Title,{children:v.title||F0(v.text)}),v.title&&F0(v.text)]}),(0,jn.jsx)(de.Actions,{children:(0,jn.jsx)(de.ActionButton,{label:r,onClick:E=>x(E,v.text)})})]})},v.text))}),(0,jn.jsx)(_c,{value:s,onChange:g,autoFocus:!0,placeholder:n,onKeyUp:y})]})},XP=j5;var z0={};dt(z0,{enUS:()=>W5,nlNL:()=>$5});var W5={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"}]},$5={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 Ct=b(R()),K5=(0,Jt.forwardRef)((e,t)=>{let n=D("TabCompletion",So);return(0,Ct.jsx)("mark",{ref:t,className:(0,im.default)(n.matchSelection)},"selection-start")}),G5=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let i=ie(z0),s=D("TabCompletion",So),a=ee("addToPersonalCollection"),l=$(Oo("/admin/personal-collection/new")),c=(0,Jt.useRef)(null),u=(0,Jt.useRef)(null),[f,d]=(0,Jt.useState)(null),p=ye(),h=qf(document.activeElement===r),[g]=(0,Jt.useState)(()=>document.createRange());h.triggerRef.current=g,(0,Jt.useEffect)(()=>()=>g.detach(),[]),(0,Jt.useEffect)(()=>{let y=e.current,m=c.current;!y||!m||(g.setStart(y,0),g.setEnd(m,0))},[e.current,c.current]),ri(()=>{h.close()});let x=(0,Jt.useCallback)(y=>{let m=g.toString(),v=/^http(s?):\/\//.test(y)?y:`https://${y}`,S=`[${m}](${v})`;p(vn({text:S,suggestion:{text:S,source:"search-url",type:"url"},eventMetrics:{inputType:"mouse"},replace:"selection"}))},[]);return(0,Ct.jsxs)("span",{children:[(0,Ct.jsx)("mark",{ref:c,className:(0,im.default)(s.matchSelection),"aria-haspopup":"dialog","aria-expanded":h.opened?"true":"false",children:o}),h.opened&&(0,Ct.jsx)(pa,{className:s.popoverRoot,triggerRef:h.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,Ct.jsxs)(em,{style:n,ref:u,children:[(0,Ct.jsxs)("div",{className:(0,im.default)(s.selectionOptions,{[s.selectionOptionsIsHidden]:f!==null}),children:[(0,Ct.jsxs)("button",{type:"button",tabIndex:f===null?-1:void 0,className:s.selectionOptionsButton,onClick:()=>d("insertLink"),children:[(0,Ct.jsx)(GP,{}),(0,Ct.jsx)("span",{children:"\xA0"}),(0,Ct.jsx)("span",{children:i("insertLink")})]}),a&&l&&(0,Ct.jsx)("button",{type:"button",tabIndex:f===null?-1:void 0,className:s.selectionOptionsButton,onClick:()=>{let y=g.toString(),m=`${l}?text=${encodeURIComponent(y)}`;window.open(m,"_blank")},children:(0,Ct.jsx)("span",{children:i("addToPersonalCollection")})})]}),f==="insertLink"&&(0,Ct.jsx)(XP,{placeholder:i("linkInputPlaceholder"),visitUrlText:i("visitUrl"),onSelectLink:x,onDismiss:()=>{d(null),h.close()}})]})})]},"selection-end")},sm=class extends go{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,Jt.createRef)(),this.foundIndex=0,n}match(n){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[r,o]=this.props.selection;if(r===o)return null;let i=this.foundIndex===0?r:o,s=i>=this.charCount&&i<=this.charCount+n.length?{index:i-this.charCount,length:0,match:"",valid:!0}:null;s&&this.foundIndex++;let a=this.foundIndex===1;return s&&a?this.charCount+=i-this.charCount:this.charCount+=n.length,s?w({isStart:a},s):null}replaceWith(n,r){return r.isStart?(0,Ct.jsx)(K5,{ref:this.startRef}):(0,Ct.jsx)(G5,{inputElement:r.inputElement,startRef:this.startRef,boundaryRef:r.boundaryRef,inputStyle:r.inputStyle})}asTag(){return"mark"}};var wo=b(R()),q5=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:i,keywordMatches:s,inputElement:a,source:l})=>{let c=D("TabCompletion",BP),u=ee("insertLink"),f=ee("addToPersonalCollection"),d=ee("showMidSentenceSuggestions"),p=ee("inlineSuggestions"),h=FP(a),g=(0,bo.useRef)(null),x=$(St);(0,bo.useEffect)(()=>{fs(a)&&h&&zP(a,h)},[h]);let y=(0,bo.useCallback)(S=>{if(!o||!n)return S;let E=[(0,wo.jsx)("span",{className:c.resetIndent,children:"\u200B"},"u200B"),(0,wo.jsx)("span",{"data-testid":"tab-completion",className:(0,am.default)(c.tabText,c.resetIndent),"data-source":l,children:n},"tabText")];return r&&E.push((0,wo.jsx)("span",{className:(0,am.default)(c.hint,c.resetIndent),children:(0,wo.jsx)(Cu,{keyCode:"tab"},"tabHint")},"tabHint")),L0(S,E)},[o,n,r]),m=(0,bo.useMemo)(()=>{let S=[];return(u||f)&&S.push(new sm("selection")),S.push(new rm("placeholders")),i&&S.push(new tm("keywords")),S},[p,u,f,i]),v=(0,bo.useMemo)(()=>{let S=window.getComputedStyle(a);return{"--dd-color":S.color,"--dd-font-size":S.fontSize,"--dd-font-family":S.fontFamily,"--dd-font-variant":S.fontVariant}},[]);return!e||!x?null:(0,wo.jsxs)("div",{ref:S=>{S!=null&&S.parentElement&&(g.current=S==null?void 0:S.parentElement)},className:c.root,style:v,children:[(0,wo.jsx)(ci,{tagName:"span",containerTagName:"div",className:(0,am.default)(c.container,c.agentText),disableLineBreaks:fs(a),content:t||"\u200B",onAfterParse:y,matchers:m,selection:h,keywordMatches:s,inputElement:a,inputStyle:v,boundaryRef:g,inlineSuggestionsOnlyAtEnd:!d}),(0,wo.jsx)("br",{})]},"tab-completion")},Y5=e=>{var x,y,m;let{input:t,ui:n,settings:r,styleSuggestions:o,conversation:i}=e,s=Is({input:t}),a=(s==null?void 0:s.text)||"",l=(s==null?void 0:s.source)||"",c=(x=t.html)!=null?x:Ia(t.text),u=a.indexOf(t.text)===0?a.slice(t.text.length):"",{showTabHint:f}=n,{isSupported:d}=i,{showTabCompletion:p,visible:h,showStyleSuggestions:g}=r;return{showTabHint:f,showStyleSuggestions:g,showTabCompletion:p&&Dr(e),content:c,tabText:u,source:l,keywordMatches:(m=(y=o.list)==null?void 0:y.keywordMatches)!=null?m:[],enabled:h&&d!==!1}},QP=RS(Y5)(q5);var hi=b(X());var X5={token:null,interval:null},H0=fe("passwordlessToken/getTemporaryPasswordlessToken",(e,t)=>_(null,null,function*(){let{deepdeskAPI:n}=t.extra;return{token:yield n.requestPasswordlessToken()}})),B0=fe("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(H0()),setInterval(()=>r(H0()),n)}),ZP=Ee({name:"passwordlessToken",initialState:X5,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(H0.fulfilled,(t,n)=>{t.token=n.payload.token}),e.addCase(B0.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:JP}=ZP.actions,eA=ZP.reducer;function Q5(e){return"buttonText"in e&&"eventName"in e}function tA(e){if(e)return Q5(e)?{label:e.buttonText,event:e.eventName,value:e.payload}:e}function Z5(e){return e==null?void 0:e.map(t=>tA(t))}function J5(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t}var nA=Ht([Pb],e=>e.map(n=>{let r=tA(n.callToAction),o=Z5(n.callToActions);return P(w(w(w({text:n.response,title:n.name},r?{callToAction:r}:{}),o!=null&&o.length?{callToActions:o}:{}),n.message!==void 0?{message:n.message}:{}),{editable:n.editable,isLoading:n.isLoading,evaluationId:n.evaluationId,rule:{id:J5(n.code),label:n.code,name:n.name,description:n.name}})}));var lm=b(X()),V0=b(Me());var U0=b(R()),Fa=()=>(0,U0.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,U0.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 rA={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};var zr=b(R()),eF=({entities:e})=>{let t=D("EntitiesWidgetList",rA),[n,r]=(0,lm.useState)(void 0),o=Xe(),i=()=>{r(void 0)},s=a=>{e&&(r(e.indexOf(a)),Tr(a.text),o("entity copied",{entity:a,type:"copy"}))};return(0,lm.useEffect)(()=>{let a=setTimeout(i,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,zr.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,zr.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>s(a),children:[(0,zr.jsx)("span",{className:t.entityText,children:a.text}),(0,zr.jsxs)("span",{className:t.iconWrapper,children:[(0,zr.jsx)("span",{className:(0,V0.default)(t.icon),children:(0,zr.jsx)(Fa,{})}),(0,zr.jsx)("span",{className:(0,V0.default)(t.icon,n===l&&t.iconClicked),children:(0,zr.jsx)(Fa,{})})]})]},a.text))})},oA=eF;var j0=b(R()),iA=()=>(0,j0.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,j0.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 fA=b(X());var sA={root:"dd-ohnXe",trigger:"dd-7i-S3",button:"dd-t53Cg",nav:"dd-qZFnm",item:"dd-FZC0F"};var aA={root:"dd-nazq3",rotation:"dd-3EHTv"};var cA=b(R()),tF=({size:e=12})=>{let t=D("LoadingSpinner",aA);return(0,cA.jsx)("span",{"data-testid":"loading-spinner",style:{width:`${e}px`,height:`${e}px`},className:t.root})},lA=tF;var W0=b(R()),uA=()=>(0,W0.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 512 512",fill:"currentColor",children:(0,W0.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 eu=b(R()),dA=e=>(0,eu.jsxs)("svg",P(w({xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 448 512","aria-labelledby":"checkTitle"},e),{children:[(0,eu.jsx)("title",{id:"checkTitle",children:"Check"}),(0,eu.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 $0={};dt($0,{enUS:()=>nF,nlNL:()=>rF});var nF={error:[{type:0,value:"Something went wrong"}]},rF={error:[{type:0,value:"Er ging iets fout"}]};var An=b(R()),oF=3e3,iF=({assistantOptions:e})=>{let t=D("OnDemandAssistants",sA),n=ie($0),r=(0,fA.useRef)(),o=nd(Cr),i=$(yR),s=Xe(),a=i.filter(u=>u.isPinned),l=i.filter(u=>!u.isPinned),c=u=>_(null,null,function*(){clearTimeout(r.current),s("trigger on demand assistant",{assistantCode:u}),yield o.call(P(w({},e),{assistantCode:u})),r.current=setTimeout(()=>o.reset(),oF)});return i.length===0?null:(0,An.jsxs)("div",{className:t.root,children:[a.map(({assistant:u,assistantName:f,displayName:d})=>(0,An.jsx)("button",{type:"button",className:t.button,disabled:o.state==="loading",onClick:()=>c(u),children:d||f},u)),l.length>0&&(0,An.jsxs)(mt,{placement:"top-end",children:[(0,An.jsx)(mt.Trigger,{className:t.trigger,disabled:o.state==="loading",children:(0,An.jsx)(zp,{"data-testid":"trigger"})}),(0,An.jsx)(mt.Content,{className:t.nav,"data-testid":"popover",children:l.map(({assistant:u,assistantName:f,displayName:d})=>(0,An.jsx)(mt.Button,{className:t.item,disabled:o.state==="loading",onClick:()=>c(u),children:d||f},u))})]}),o.state==="loading"&&(0,An.jsx)(lA,{}),o.state==="done"&&(0,An.jsx)(dA,{"data-testid":"trigger-done"}),o.state==="error"&&(0,An.jsx)(Qk,{trigger:(0,An.jsx)(uA,{}),children:n("error")})]})},pA=iF;var tu={};dt(tu,{enUS:()=>sF,nlNL:()=>aF});var sF={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"}]},aF={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 ps=b(X());var K0={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 Tt=b(R()),lF=500,cF=100,uF=({content:e,onChange:t,onCopy:n})=>{let r=(0,ps.useRef)(null),o=D("WidgetCue",K0);return(0,ps.useEffect)(()=>{let i=r.current;if(!i)return;i.style.setProperty("height","0px");let s=Math.min(Math.max(i.scrollHeight,cF),lF);i.style.setProperty("height",`${s}px`)},[e]),(0,Tt.jsx)("textarea",{ref:r,className:o.editableCue,onCopy:n,onChange:t,value:e})},dF=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o})=>{var g;let i=D("WidgetCue",K0),s=ie(tu),a=Xe(),l=ee("hasKeyboardInput"),[c,u]=(0,ps.useState)(e.text),f=x=>{let y=x?P(w({},e),{callToAction:x}):e;t&&t(c,y),n(e)},d=(x,y)=>{r&&r(x,e),y&&No(y,i.fadeup)},p=x=>{o&&o(x,e)},h=x=>{x.preventDefault(),x.stopPropagation(),n(e)};return(0,ps.useEffect)(()=>{a("Assistant response displayed",{evaluationId:e.evaluationId,assistantCode:e.rule.label,assistantOutput:e.text})},[]),(0,Tt.jsxs)(de,{"data-testid":"cue",children:[(0,Tt.jsx)(he,{children:(0,Tt.jsxs)(he.Content,{children:[e.title&&(0,Tt.jsx)(he.Title,{className:i.title,"data-testid":"widget-cue-title",children:e.rule.label.startsWith("__")?s(e.rule.label):e.title}),e.message&&(0,Tt.jsx)("p",{className:i.ctaMessage,children:e.message}),e.editable?(0,Tt.jsx)(uF,{content:c,onCopy:()=>{let x=document.getSelection();x&&d(x.toString())},onChange:x=>{var y;return u((y=x.target.value)!=null?y:"")}}):(0,Tt.jsx)(Xi,{content:e.text,useLabel:s("useCue"),copyLabel:s("copyCue"),onCopy:d,onUse:l?p:void 0})]})}),(0,Tt.jsxs)(de.ButtonsContainer,{children:[(0,Tt.jsxs)("div",{className:i.actions,children:[(0,Tt.jsx)(de.Button,{onClick:x=>{var y;return d((y=vd(c,"reply")[0])!=null?y:c,x.target)},variant:"primary",children:s("copyCue")}),e.callToAction&&(0,Tt.jsx)(de.Button,{onClick:()=>f(),variant:"primary",children:e.callToAction.label}),(g=e.callToActions)==null?void 0:g.map((x,y)=>(0,Tt.jsx)(de.Button,{onClick:()=>f(x),variant:"primary",children:x.label},`${x.event}-${x.label}-${y}`)),(0,Tt.jsx)(de.Button,{onClick:h,variant:"secondary",children:s("removeCue")})]}),(0,Tt.jsx)(Ed,{evaluationId:e.evaluationId,assistantCode:e.rule.label,assistantOutput:e.text,feedbackText:e.text,feedbackType:"assistant"})]})]})},mA=dF;var za=b(R()),fF=({cues:e})=>{let t=ye(),n=on(),r=ie(tu),o=Xe(),i=c=>{t(Sd({code:c.rule.label})),o("Assistant response closed",{evaluationId:c.evaluationId,assistantCode:c.rule.label,assistantOutput:c.text})},s=(c,u)=>{Tr(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(xd(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(Kr,{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,za.jsx)(za.Fragment,{children:e.map(c=>c.isLoading?(0,za.jsx)(Xf,{title:c.rule.label.startsWith("__")?r(c.rule.label):c.title},c.rule.id):(0,za.jsx)(mA,{cue:c,onCallToAction:a,onRemove:i,onCopy:s,onUse:l},c.evaluationId))})},gA=fF;var cm=b(X());var hA={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var gn=b(R());function pF(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var yA=({data:e,schema:t})=>{let n=D("WidgetCustomData",hA),r=o=>{Tr(o)};return(0,cm.useEffect)(()=>{J.info("Custom data",e,t)},[e]),(0,gn.jsx)("dl",{className:n.root,children:t.map(o=>{let i=pF(e,o.path);return(0,gn.jsxs)(cm.Fragment,{children:[(0,gn.jsx)("dt",{className:n.label,children:o.label}),(0,gn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&i?(0,gn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!i?(0,gn.jsx)("span",{className:n.isFalse,children:o.falseValue}):o.type==="array"&&Array.isArray(i)&&i.length>0?(0,gn.jsxs)("button",{type:"button",onClick:()=>r(i.join(", ")),className:n.copyButton,children:[(0,gn.jsx)("span",{className:n.copyButtonText,children:i.join(", ")}),(0,gn.jsx)(Fa,{})]}):typeof i=="string"||typeof i=="number"?(0,gn.jsxs)("button",{type:"button",onClick:()=>r(`${i}`),className:n.copyButton,children:[(0,gn.jsx)("span",{className:n.copyButtonText,children:i}),(0,gn.jsx)(Fa,{})]}):"-"})]},o.label)})})};var xA=b(X());var mF=/(https?:\/\/[^\s]+)/,vA=e=>e.split(" ").find(t=>mF.test(t));var Wn=b(R()),gF=({suggestion:e,lines:t,onUse:n})=>{var f;let r=e.text||e.url||e.message,o=vA(r),i=ie($c),s=ee("showImages"),a=ee("fallbackImage"),l=ee("hasKeyboardInput"),c=d=>{d.preventDefault(),d.stopPropagation(),l&&n(r)},u=(0,xA.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,Wn.jsxs)(de,{onClick:l?c:void 0,"data-testid":"edit-suggestion",children:[(0,Wn.jsxs)(he,{children:[s&&e.image&&(0,Wn.jsx)(he.Image,{src:om(e,"small",a||void 0),title:e.title}),(0,Wn.jsxs)(he.Content,{children:[e.title&&(0,Wn.jsx)(he.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((f=e.searchKeywords)==null?void 0:f.length)>0&&(0,Wn.jsx)(de.Labels,{labels:e.searchKeywords}),(0,Wn.jsx)(he.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,Wn.jsxs)(de.Actions,{children:[o&&(0,Wn.jsx)(de.ActionButton,{onClick:u,label:i("visitUrl")}),l&&(0,Wn.jsx)(de.ActionButton,{primary:!0,onClick:c,label:i("useSuggestion")})]})]})},SA=gF;var nu=b(R()),hF=({lines:e,suggestions:t})=>{let n=on(),r=(o,i)=>{n.send(Kr,{text:o,suggestion:P(w({},i),{source:i.source,sourceText:i.text})})};return(0,nu.jsx)(nu.Fragment,{children:t.map(o=>(0,nu.jsx)(SA,{suggestion:o,lines:e,onUse:i=>r(i,o)},o.text||o.url||o.message))})},wA=hF;var ru={};dt(ru,{enUS:()=>yF,nlNL:()=>vF});var yF={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"}]},vF={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 Ha={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 ae=b(R()),bA=(e,t)=>{let n=$(St);(0,hi.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},xF=({onLogIn:e})=>{let t=D("Widget",Ha),n=ee("isEmbedded"),r=ee("adminUrl");return(0,ae.jsx)("div",{className:t.loginText,children:(0,ae.jsx)("div",{children:(0,ae.jsx)(qp,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},G0=({text:e})=>{let t=D("Widget",Ha);return(0,ae.jsx)("div",{className:t.stateText,children:(0,ae.jsx)("div",{children:(0,ae.jsx)("p",{children:e})})},"notification")},SF=()=>{let e=ie(ru),t=ye(),n=D("Widget",Ha),r=ee("showSearch"),o=ee("isEmbedded"),i=$(Oo("/admin/")),s=on(),a=ee("productName"),l=Xe();return bA(()=>{if(o)return t(B0()),()=>{t(JP())}},[t,o]),!r&&!i?null:(0,ae.jsxs)("div",{className:n.shortcutList,children:[r&&(0,ae.jsx)(de.Button,{"data-testid":"shortcut-search","aria-label":e("linkSearch"),className:n.shortcut,icon:(0,ae.jsx)(Ma,{}),onClick:()=>{s.send("ShowCommandPalette",{isOpen:!0}),l("open search",{via:"widget-shortcut"})},children:e("linkSearch")}),i&&(0,ae.jsx)(de.Button,{as:"a",target:"_blank",icon:(0,ae.jsx)(iA,{}),href:i,"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})})]})},wF=({title:e,content:t})=>{let n=ie(ru),[r,o]=(0,hi.useState)(!0);return r?(0,ae.jsx)(Sr,{"data-testid":"custom-data-banner",type:"custom-data-banner",title:e,children:(0,ae.jsx)(zt,{withDivider:!0,children:(0,ae.jsxs)(de,{children:[(0,ae.jsx)(he,{children:(0,ae.jsx)(he.Content,{children:(0,ae.jsx)(Xi,{content:t})})}),(0,ae.jsx)(de.ButtonsContainer,{children:(0,ae.jsx)(de.Button,{onClick:()=>o(!1),children:n("close")})})]})})}):null},bF=()=>{let e=ye(),t=$(Nc),n=$(xR),r=$(nA),o=$(Uw),i=$(Fp),s=$(Up),a=$(ns),l=$(br);return(0,hi.useEffect)(()=>{o&&!n&&J.warn("Custom data provided, but no schema.")},[o,n]),bA(()=>{t.forEach(({type:c})=>{c==="entities"?e(gr()):Pu.includes(c)||e(hr(c))})},[e,l,a]),(0,hi.useEffect)(()=>{r.length>0&&!t.some(c=>c.type==="cues")&&J.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,ae.jsx)(hi.Fragment,{children:t.map(({type:c,title:u,amount:f,lines:d,schema:p,property:h})=>{var g,x;switch(c){case"entities":return i&&i.length>0&&(0,ae.jsx)(Sr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,ae.jsx)(oA,{entities:i})},c);case"cues":return r&&r.length>0&&(0,ae.jsx)(Sr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,ae.jsx)(zt,{withDivider:!0,children:(0,ae.jsx)(gA,{cues:r})})},c);case"custom-data-banner":return o&&h&&o[h]&&(0,ae.jsx)(wF,{title:u,content:String(o[h])},c);case"custom-data":return o&&p&&(0,ae.jsx)(Sr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,ae.jsx)(zt,{withDivider:!0,children:(0,ae.jsx)(yA,{data:o,schema:p})})},c);default:return((x=(g=s[c])==null?void 0:g.suggestions)==null?void 0:x.length)>0&&(0,ae.jsx)(Sr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,ae.jsx)(zt,{withDivider:!0,children:(0,ae.jsx)(wA,{lines:d,contentType:c,suggestions:s[c].suggestions.slice(0,f)||[]})})},c)}})})},q0=({children:e})=>{let t=D("Widget",Ha);return(0,ae.jsx)("div",{className:t.footer,children:e})},Y0=({children:e})=>{let t=D("Widget",Ha);return(0,ae.jsx)("div",{className:t.root,"data-testid":"widget",children:e})},EF=({onLogIn:e,knowledgeAssistOptions:t={},assistantOptions:n={transcript:"in-memory-transcript"}})=>{let r=ie(ru),o=$(Ps),i=$(St),s=$(Tw),a=$(ns),l=$(vR("knowledge-assist")),c=$(SR);return o===!1?(0,ae.jsx)(G0,{text:r("notSupported")}):i===!1?(0,ae.jsx)(xF,{onLogIn:e}):i===null?(0,ae.jsx)(G0,{text:r("waiting")}):!s||!a?(0,ae.jsx)(G0,{text:r("waitingForConversation")}):(0,ae.jsx)(Y0,{children:(0,ae.jsxs)(bp,{initialQuestion:t.initialQuestion,assistantCode:c!=null?c:void 0,evaluateKnowledgeAssistFn:El,children:[(0,ae.jsxs)(Ts,{children:[(0,ae.jsx)(SF,{}),(0,ae.jsx)(bF,{}),l&&(0,ae.jsx)(Cp,{title:l.title,emptyState:t.emptyState})]}),(0,ae.jsxs)(q0,{children:[l&&(0,ae.jsx)(Ep,{}),(0,ae.jsx)(pA,{assistantOptions:n})]})]})})},EA=EF;function Ba(e){let t=new Range;return t.selectNodeContents(e),t}function CA(e,t,n){try{return yi(e,t,n),!0}catch(r){return!1}}function um(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function dm(e){return"tagName"in e&&e.tagName==="BR"}var ou=/[\u200B-\u200D\uFEFF]/g;function yi(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,i=!1;function s(l,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(ou,""),f=o+u.length,d=t>=o&&t<=f,p=n>=o&&n<=f;if(d){let h=s(c,t-o);h===0&&!p?r.setStartBefore(l):r.setStart(l,h)}p&&(r.setEnd(l,s(c,n-o)),i=!0),o=f;break}case Node.ELEMENT_NODE:{if(dm(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),i=!0;return}for(let u=0;u<l.childNodes.length&&(a(l.childNodes[u]),!i);u++);let c=l.lastChild;um(l)&&c&&!um(c)&&!dm(c)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function iu(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a,l,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(ou,"").length),h&&(l=c+g.substring(0,i).replace(ou,"").length),c+=g.replace(ou,"").length;break}case Node.ELEMENT_NODE:{if(dm(f)&&f.nextSibling){c++;break}!d&&um(f)&&f.previousSibling&&c++;for(let g=0;g<f.childNodes.length;g++){let x=p&&g===r,y=h&&g===i;if(x&&(a=c),y&&(l=c),l!==void 0||((!x||!s)&&u(f.childNodes[g]),h&&g===i-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 su(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a=0,l="";function 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?i:void 0;l+=u.textContent.replace(ou,"").substring(h,g);break}case Node.ELEMENT_NODE:{if(!s&&a===1&&dm(u)&&u.nextSibling){l+=`
|
|
80
80
|
`;break}!f&&!s&&a===1&&um(u)&&u.previousSibling&&(l+=`
|
|
81
|
-
`);let h=d?r:0,g=p?Math.min(i,u.childNodes.length):u.childNodes.length;for(let x=h;x<g&&(c(u.childNodes[x]),a!==2);x++);break}default:break}p&&(a=2)}return c(e),l}var TA=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(TA||{}),Eo=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let i=this.getCaretPosition();Mo(i,this.cachedCaretPosition)||(this.cachedCaretPosition=i,this.emit("caretposition",i))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(TA).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}off(t,n){if(!this.eventListeners[t])return;let r=this.eventListeners[t].indexOf(n);r!==-1&&this.eventListeners[t].splice(r,1)}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function kA(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var ms=class extends Eo{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),su(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 i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!kA(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!kA(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return iu(this.element,n);let r=this.lastKnownSelection;if(r&&CA(this.element,r.start,r.end))return r;let o=Ba(this.element);return o.collapse(!1),iu(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return su(this.element,yi(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(i=>{var s,a;i.length===2&&i[0].addedNodes.length===1&&((s=i[0].addedNodes[0])==null?void 0:s.textContent)==="\u2060"&&((a=i[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var CF=["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 RA(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,i=window.getComputedStyle(e),s=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",CF.forEach(u=>{o[u]=i[u]}),n?e.scrollHeight>Number.parseInt(i.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),s.appendChild(r);let l=e.getBoundingClientRect(),c={top:l.top-e.scrollTop+a.offsetTop+Number.parseInt(i.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+Number.parseInt(i.borderLeftWidth)};return s.removeChild(r),c}var gs=class extends Eo{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 RA(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var i;return(i=n==null?void 0:n.get)==null?void 0:i.call(this.element)},set:i=>{var s;(s=n==null?void 0:n.set)==null||s.call(this.element,i),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function PA(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function TF(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var X0=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()}},Q0=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=PA(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()}},Z0=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.externalId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setExternalId(t){this.externalId!==t&&(this.cleanup(),J.info("Set externalId",t),this.externalId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Q0(t,this.deepdeskUrl,{debug:!0}):new X0(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=TF(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(J.info("Received broadcast event",this.externalId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;J.info("Broadcast event",{externalId:this.externalId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage(P(w({},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)}},AA=Z0;function kF(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function Ue(e){return Array.isArray(e)?e.map(Ue):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(w({},t),{[kF(n)]:Ue(e[n])}),{}):e}function RF(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function en(e){return Array.isArray(e)?e.map(en):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(w({},t),{[RF(n)]:en(e[n])}),{}):e}var Ua=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var J0=e=>new Promise(t=>{setTimeout(t,e)});var hs=class extends Ua{constructor(){super(...arguments);this.name="ClientError"}},tx=class extends Ua{constructor(){super(...arguments);this.name="ServerError"}},ex=new Map;function PF(e){return _(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t!=null&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(J.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var ys=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 i={isAborted:!1,reject:o},s=`${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:x=null}=T,y=oe(T,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(c){if(!l)throw new Error(`Can't use 'useCache' for ${n.method}`);if(ex.has(s)){r(ex.get(s));return}}let m=P(w({credentials:"include"},y),{headers:w({Accept:"application/json","Content-Type":"application/json"},y.headers)});!l&&this.csrfToken&&(m.headers=P(w({},m.headers),{"X-CSRFToken":this.csrfToken})),typeof x=="string"&&(m.headers=P(w({},m.headers),{"X-Deepdesk-API-Version":x}));let v=f,S=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&u&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let E=()=>_(this,null,function*(){return v--,a(s,m).then(k=>_(this,null,function*(){return g(k)&&!i.isAborted&&v>0?(yield J0(d),E()):k.status===401&&p===!0&&S===!1?(S=!0,yield this.refreshToken(),E()):k})).catch(k=>_(this,null,function*(){if(h(k)&&!i.isAborted&&v>0)return yield J0(d),E();throw k}))});E().then(k=>_(this,null,function*(){let A=yield PF(k);if(delete this.latestRequestByUrl[s],k.status>=500){o(new tx("Server Error",A));return}if(k.status===401){o(new hs("Unauthorized",A));return}if(k.status===403){o(new hs("Forbidden",A));return}if(k.status===404){o(new hs("Not Found",A));return}if(k.status>=400){o(new hs("Bad Request",A));return}c&&ex.set(s,A),r(A)})).catch(k=>{o(k)})})}validateToken(){return _(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 hs("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,w({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,w({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,w({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,w({method:"DELETE"},n))}};var IA;(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={}))})(IA||(IA={}));function nx(e){return P(w({},Ue(e)),{metadata:e.metadata})}var vs=class vs{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new ys(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>_(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return _(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(vs.exchangeTokenPromise||(vs.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),vs.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return _(this,null,function*(){var r;yield this.preflight(),J.info(`Creating conversation for session ${t.externalId} and agent ${t.agentId}`);let n=yield this.client.post("/api/v2/conversations",P(w({chat_start_time:new Date().toISOString()},en(t)),{metadata:(r=t.metadata)!=null?r:{}}));return nx(n)})}getMe(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return Ue(t)})}postIdentity(t){return _(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",en(t))})}patchMe(t){return _(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",en(t));return Ue(n)})}getProfile(t){return _(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return Ue(n)})}getKnowledgeAssistant(t){return _(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return Ue(n)})}getContentTypes(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return Ue(t)})}getAccount(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return Ue(t)})}getPlatformConfig(t){return _(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return Ue(r)})}checkUserExists(t){return _(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationByExternalId(r){return _(this,arguments,function*(t,n={}){yield this.preflight(),J.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/v2/conversations/by_external_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return J.info(`Successfully retrieved conversation ${s.id} for session ${t}`),nx(s)})}isConversationSupported(r){return _(this,arguments,function*(t,n={}){J.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${t}/has_active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(t,n){return _(this,null,function*(){var i;yield this.preflight();let r=en(n);n.metadata&&(r.metadata=(i=n.metadata)!=null?i:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return nx(o)})}postMessages(t,n){return _(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>P(w({},en(r)),{metadata:r.metadata})))})}sendEvent(t,n){return _(this,null,function*(){yield this.preflight();let a=n,{data:r}=a,o=oe(a,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((l,[c,u])=>P(w({},l),{[c]:u}),{}),s=["platform","agentId","agentName","agentEmail","conversationId"].reduce((l,c)=>(o[c]&&(l[c]=o[c]),l),{});return this.client.post("/api/v2/events",en(P(w(w({},i),s),{data:r,name:t})),{version:"v2"})})}getEntities(t){return _(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:t.filter(r=>r.text)})})}getTemporaryExchangeToken(){return _(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(t){return _(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw J.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return _(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",en(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return _(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}`,en(n),{abortLatest:!0})).map(s=>P(w({},Ue(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,l)=>a===l.findIndex(c=>c.text===s.text))})}isLoggedIn(){return _(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return _(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${t}/autocomplete`,en(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return _(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return Ue(n).map(r=>P(w({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return _(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",en(t),{abortLatest:!0,version:"v2"});return Ue(n)})}search(t){return _(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,en(t));return Ue(n)})}requestLoginByEmail(t){return _(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return Ue(n)})}requestPasswordlessToken(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return Ue(t.token)})}getCsrfToken(){return _(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return _(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return Ue(n)})}evaluateAssistant(t,n){return _(this,null,function*(){var s;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()}`,i=yield this.client.post(o,{input:(s=n==null?void 0:n.input)!=null?s:{},conversation:n==null?void 0:n.transcript});return Ue(i)})}createAssistantThread(t){return _(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return Ue(r)})}postMessageToAssistantThread(t){return _(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:r,message:o}=t,i=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return Ue(i)})}translateMessages(t){return _(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",en(t));return Ue(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(dS);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&J.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};vs.exchangeTokenPromise=null;var Co=vs;var fm=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=Ue(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 _A={startTime:null,stopTime:null},MA=e=>e.handlingTime,LA=Ee({name:"handlingTime",initialState:_A,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(it,()=>_A)}}),{handlingTimeStart:NA,handlingTimeStop:pm,handlingTimeReset:OA}=LA.actions,DA=LA.reducer;var FA=(e={})=>{let t=w({onAuthError:Rs(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var mm={list:{keywordMatches:[]},fetchState:"idle"};var xs=fe("styleSuggestions/getAll",(n,r)=>_(null,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(l=i.conversation.current)==null?void 0:l.profileCode;if(!s)return mm.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),AF=Ee({name:"styleSuggestions",initialState:mm,reducers:{},extraReducers:e=>{e.addCase(xs.pending,t=>{t.fetchState="loading"}).addCase(xs.rejected,t=>{t.fetchState="error"}).addCase(xs.fulfilled,(t,n)=>{t.fetchState="done",Mo(t.list,n.payload)||(t.list=n.payload)}).addCase(Pi,t=>{t.list=mm.list}).addCase(it,()=>mm)}}),zA=AF.reducer;var HA=(e={})=>{let t,n=!0,r=w({getStyleSuggestions:xs,debounce:500},e);return o=>i=>s=>{var p;let a=o.getState().input.text,l=i(s),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 IF(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var BA=(e={})=>{let t=w({getTextSuggestions:hr,getAutocompleteSuggestions:Gc,debounce:200,check:Dr},e),n;return r=>o=>i=>{var g;let{input:s}=r.getState(),a=o(i),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=i.type===Vp.toString();if(!f||!c&&!u)return a;let{input:p}=l;return IF(p,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let x=As(l);x===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(x))},d?0:t.debounce)),a}};var UA=xs.fulfilled.toString();function _F(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var VA=e=>t=>n=>r=>{var c;if(r.type!==UA){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(c=i.conversation)==null?void 0:c.current;if(o===s)return;let l=_F(o,s);r.type===UA&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var MF=Mu({assistants:Nb,auth:xw,conversation:kw,contentTypes:hR,passwordlessToken:eA,entities:WR,handlingTime:DA,info:qw,input:zw,settings:Db,profile:wR,search:eb,styleSuggestions:zA,ui:gP,textSuggestions:eP});function jA(e){return sw({reducer:MF,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(FA()).concat(BA({debounce:200})).concat(HA({debounce:500})).concat(VA(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,i)=>o.concat(i),n)},preloadedState:e.preloadedState})}var LF=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},NF=e=>t=>n=>r=>{var l,c;let o=t.getState(),i=Li("inlineSuggestions")(o),s=Li("autoSelectSuggestion")(o)||i;switch(r.type){case Rs.toString():{!r.payload&&e.emit("logout",void 0);break}case gr.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 Pi.toString():e.logSendMessage(r.payload);break;case xd.toString():e.emit("call-to-action",{cue:r.payload});break;case Cr.fulfilled.toString():r.isBroadcasted||e.broadcast(wg,r,!1);break;default:break}let a=n(r);switch(r.type){case Pi.toString():e.handleAfterSendMessage(r.payload);break;case Yc.toString():e.onUpdateShowTabHint(r.payload);break;case pm.toString():e.logHandlingTime();break;case _s.toString():e.broadcast(ed,r);break;case Ri.toString():e.broadcast(ed,r);break;case Sd.toString():t.dispatch(Ri({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{let u=o.assistants.cues.find(f=>f.code===r.meta.arg.data.assistantCode);e.emit("event",P(w({},r.meta.arg),{cue:u}));break}case vn.toString():{let{start:u,end:f}=o.input.selection;e.emit("select-suggestion",P(w({type:LF(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:u,end:f}:{start:0,end:f}})),i&&t.dispatch(Lo([]));break}case Gu.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(c=o.conversation.current)==null?void 0:c.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Lo.toString():{s&&r.payload.length>0&&t.dispatch(qu(0));break}default:break}return a},WA=NF;function rx(e){return e.toISOString().replace("T"," ").replace("Z","")}var OF=(e,t)=>t.version,$A=Ht([Ms,br,MA,OF],(e,t,n,r)=>{if(!t)return J.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:i}=n;return!o||!i?(J.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:t,clientVersion:r,agentId:e==null?void 0:e.agentId,agentName:e==null?void 0:e.agentName,agentEmail:e==null?void 0:e.agentEmail,timeStart:rx(o),timeStop:rx(i)}});function KA(e,t){let{text:n,metrics:{numPaste:r,pastes:o,textSuggestions:i}}=e.input,s=n.length;return{source:"agent",clientVersion:t.version,pastes:o,lenTextTotal:s,numPastes:r,suggestions:i}}var au=class extends Error{};function DF(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var gm=class{constructor(){this.queues={}}push(t,n){let r=()=>{let i=this.queues[t][1];i?(this.queues[t]=[i.promise,null],i.resolve()):delete this.queues[t]};if(!this.queues[t]){let i=n().finally(r);return this.queues[t]=[i,null],i}this.queues[t][1]&&this.queues[t][1].reject(new au("Queued async function is outdated"));let o=DF();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};function ox(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return ox(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?ox(o,t):null}function ix(e,t){return ox(e,t)}var FF={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},GA=(e,t)=>{var o,i,s;if(!((s=(i=(o=e.uiConfig)==null?void 0:o.widget)==null?void 0:i.types.find(a=>a.type==="cues"))==null?void 0:s.isActive))return J.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let r=e[FF[t]];return r&&r.length>0?r.map(a=>a.code):(J.warn(`No assistant set in profile for conversation event "${t}"`),[])};function qA(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function zF(e){return typeof e=="object"&&e!==null&&"tagName"in e}function hm(e){return zF(e)&&(fs(e)||Xp(e))}var XA,Hr=new Map,HF=["bottom","height","left","right","top","width"],YA=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:HF.some(n=>e[n]!==t[n]);function QA(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,...QA(t)]:[]}function ZA(e,t){return!e||!t?null:P(w({},e),{top:e.top+t.top,left:e.left+t.left})}var ym=!1,JA=()=>{ym=!0;let e=[];if(Hr.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Hr.delete(n);return}let r=n.getBoundingClientRect();YA(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(ZA,t.rect):t.rect;YA(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Hr.size===0){ym=!1;return}XA=window.requestAnimationFrame(JA)};function sx(e,t){let n=QA(e),r=[],o=n.map((i,s)=>sx(i,a=>{r[s]=a;let l=Hr.get(e);if(!l)return;let c=r.reduce(ZA,l.rect);l.callbacks.forEach(u=>u(c))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Hr.has(e)){let s=Hr.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Hr.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!ym&&JA()},unobserve(){o.forEach(s=>s.unobserve());let i=Hr.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Hr.delete(e),Hr.size||(cancelAnimationFrame(XA),ym=!1)}}}}var eI,Br=new Map,tI=()=>{Br.forEach((e,t)=>{if(!t.isConnected){Br.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),Br.size!==0&&(eI=window.requestAnimationFrame(tI))};function nI(e,t){return{observe(){let n=Br.size===0;Br.has(e)?Br.get(e).callbacks.push(t):Br.set(e,{visible:void 0,callbacks:[t]}),n&&tI()},unobserve(){let n=Br.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Br.delete(e),Br.size||cancelAnimationFrame(eI)}}}}var ax=["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 lx(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Va(e){return Number.parseFloat(e)}function vm(e){return Math.round(e*1e6)}function rI(e){return e/1e6}function cx(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Va(e.width),i=Va(e.borderLeftWidth),s=Va(e.borderRightWidth),a=Va(e.paddingRight),l=rI(vm(o)-vm(i)-vm(s)),c=rI(vm(r));if(l-c>2){let u=l-c;n.style.paddingRight=`${a+u}px`}}function lu(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",Yi(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};lx(r,n,ax),cx(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=nI(e,()=>{lx(r,n,ax),cx(r,e,n),i(),setTimeout(i,0)}),a,l=!0,c=sx(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(lx(r,n,ax),cx(r,e,n),i(),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=Va(h.borderTopWidth),x=Va(h.borderBottomWidth),y=p.top+g-d.top,m=d.top+d.height+-(p.top+p.height-x);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(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),c.unobserve(),s.unobserve(),n.remove()}]}function BF(e){return e.offsetParent!==null}function oI(e){if(!BF(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 xm(e,t,n=100){let r=oI(e);t({isVisible:r});let o=setInterval(()=>{let i=oI(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var iI=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){J.warn("[Deepdesk] SessionStorage is blocked by browser")}}});var be=b(R());var sI=iI("showTabHint",!0),ja=class ja{constructor({deepdeskUrl:t,version:n=ja.version||"unknown",locale:r="en-US",token:o,fetch:i,productName:s,createCustomChannel:a,websocketClient:l=fm}){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 gm;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let c=t.replace(/\/api$/,"");this.deepdeskApi=new Co(c,{token:o,fetch:i}),this.version=n,this.instanceId=ja.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[WA({broadcast:(h,g,x)=>{this.broadcastEvents.send(h,g,x)},emit:(h,g)=>this.emit(h,g),handleAfterSendMessage:h=>this.handleAfterSendMessage(h),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:h=>this.logSendMessage(h),onUpdateShowTabHint:h=>sI.update(h),sendEvent:(h,g)=>this.deepdeskApi.sendEvent(h,g)})]};this.store=jA(u),this.broadcastEvents=new AA({debug:!0,deepdeskUrl:c,eventMap:tb(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:()=>_(this,null,function*(){var h;return(h=St(this.state))!=null?h:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(Yc(sI.value())),this.store.dispatch(wd({locale:r,adminUrl:c,productName:s}));let f=[],d=h=>{if(!h.conversationId)return;let g=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(Lb(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(Mb(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(_s([{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=ki(this.state)[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}externalId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.externalId}shouldAbort(){return this.state.conversation.isSupported===!1?(J.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(J.warn("Profile has not been loaded (yet)"),!0):(J.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(t){if(St(this.state))t();else{let n=this.subscribe(St,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Rs(null)),this.store.dispatch($r()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return _(this,null,function*(){return(yield this.store.dispatch($r())).payload})}isConversationSupported(t,n){return _(this,null,function*(){return(yield this.store.dispatch(mg({externalId:t,options:n}))).payload})}createConversation(t){return _(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(Wu(P(w({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}getConversationByExternalId(t,n){return _(this,null,function*(){return this.hasConversation()&&this.externalId()!==t&&this.resetConversation(),(yield this.store.dispatch($u({externalId:t,options:n}))).payload})}upsertConversation(t){return _(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(gg(P(w({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return _(this,null,function*(){yield this.store.dispatch(hg(t))})}updateConversation(t){return _(this,null,function*(){return(yield this.store.dispatch(Ku(t))).payload})}resetConversation(){this.store.dispatch(it()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(wd(t))}setVisitorInfo(t){this.store.dispatch(Ww(t))}setCustomData(t){this.store.dispatch($w(t))}setAgentInfo(t,n){return _(this,null,function*(){var o;yield this.store.dispatch(il(w(w({},t),n))),(o=this.state.info.agentInfo)!=null&&o.agentNickname||this.broadcastEvents.send(Ju,{showNicknameDialog:!0})})}setAgentSettings(t){return _(this,null,function*(){yield this.store.dispatch(vg(t))})}getAgentSettings(){return _(this,null,function*(){return(yield this.store.dispatch(xg())).payload})}refresh(){return _(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(Yu({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}))}notifyExternalSuggestion(t){this.store.dispatch(vn(t))}evaluateAssistant(t,n){return _(this,null,function*(){var l;let{input:r={},transcript:o,showCuesInWidget:i=!0,includeMetadata:s}=n||{},a=yield this.store.dispatch(Cr({assistantCode:t,transcript:o,includeMetadata:s,input:r,skipState:!i}));if(a.error)throw new Error(`Assistant evaluation failed: ${(l=a.payload)!=null?l:a.error.message}`);return a.payload.output})}evaluateConversationAssistant(t,n){return _(this,null,function*(){yield this.loadProfileConfig();let r=this.state.profile.data;if(!r){J.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=GA(r,t);yield Promise.all(o.map(i=>this.queues.push(i,()=>_(this,null,function*(){yield this.evaluateAssistant(i,w({includeMetadata:!0},n))})).catch(s=>{if(s instanceof au){J.warn(`Queued assistant "${i}" was outdated and dropped`);return}throw s})))})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=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(_w(yg(t))),!Dr(this.state)||t.key!=="Tab"&&!c)return;let h=()=>{n||!p||s&&(t.shiftKey||(this.store.dispatch(Nw()),t.preventDefault()))},g=()=>{n||!p||f&&i<=0||s&&(t.shiftKey||(this.store.dispatch(Ow()),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(qu(-1)),this.store.dispatch(di({collapse:!0})),this.store.dispatch(pP(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let x=Is(this.state);if(!x)return;this.store.dispatch(Yc(!1)),this.store.dispatch(vn({text:x.text,suggestion:x,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(f||this.state.input.selectedSuggestionIndex===-1)return;let x=Is(this.state);if(!x)return;this.store.dispatch(vn({text:x.text,suggestion:x,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(f||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let x=Is(this.state);if(!x)return;this.store.dispatch(vn({text:x.text,suggestion:x,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(di({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Lo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(J.info("Start handling time"),this.store.dispatch(NA()))}handlingTimeStop(){this.state.handlingTime.startTime&&(J.info("Stop handling time"),this.store.dispatch(pm()))}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=$A(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(OA()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Pi((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(Fw()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){J.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),J.error(i)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}setPlatformVariables(t){this.store.dispatch(Kw(t))}whenConversationLoaded(t){let n=i=>{var s;return(s=i.conversation.current)==null?void 0:s.id},r=()=>this.loadProfileConfig().then(()=>t());return n(this.state)&&r(),this.subscribe(n,i=>{i&&r()})}overlayContainerFactory(t,n,r,o){let[i,s]=lu(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),[i,s]}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,s=i?i.ownerDocument.defaultView:null;if(i&&(s===window||(s==null?void 0:s.parent)===window)){let[l,c]=lu(i,{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 Yi(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),J.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(J.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Dw(r.metrics))):J.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!hm(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s,inputMediator:a}=d,l=oe(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),c={customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),Yi(t),this.inputMediator=a||(fs(t)?new gs(t):new ms(t)),this.inputMediator.on("change",({plainText:p,rawHTML:h})=>{this.store.dispatch(Yu({text:p,html:h}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(Mw(yg(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:h})=>{this.store.dispatch(Lw({text:p,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(Iw(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(Xu(p))},500):this.store.dispatch(Xu(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($p(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch($p(!0))}),this.renderSuggestions(t,c),this.subscribe(Li("inlineSuggestions"),()=>{this.renderSuggestions(t,c)}),this.subscribe(Li("suggestionsPlacement"),()=>{this.renderSuggestions(t,c)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(Yu({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(Xu(this.inputMediator.getSelection())),this.store.dispatch($p(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,To.createRoot)(n),o=null,i=a=>{o=a,s()},s=()=>{r==null||r.render((0,be.jsx)(vo,{store:this.store,children:(0,be.jsx)(Gr,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(kP,{id:"deepdesk-nickname-dialog",error:o,onSave:a=>_(this,null,function*(){try{yield this.store.dispatch(Vw({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(Ju,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(l){J.error("Error setting agent nickname",l),i("error"),this.nicknameDialogFailed=!0}})})})}))};s(),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,i;(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(s=>s()),this.unmountHandlers=[],(i=this.inputMediator)==null||i.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,i,s;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(i=this.aboveSuggestions)==null||i.unmount(),(s=this.belowSuggestions)==null||s.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"),i=(0,To.createRoot)(o);i.render((0,be.jsx)(vo,{store:this.store,customStyles:r,children:(0,be.jsx)(Gr,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(CP,{})})}));let s=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",s),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",s),i.unmount(),o.remove()}}}renderAboveOrBelowSuggestions(t,n,r){let{customStyles:o,closestScrollSelector:i,appendOverlayTo:s}=n,a=i&&ix(t,i)||void 0,[l,c]=this.overlayContainerFactory("deepdesk-tab-completion",a||t,{appendTo:s,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},o==null?void 0:o.rootNode),[u,f]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||t,{appendTo:s,placement:r},o==null?void 0:o.suggestionsRootNode),d=(0,To.createRoot)(l);d.render((0,be.jsx)(vo,{store:this.store,customStyles:o,children:(0,be.jsx)(Gr,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(QP,{inputElement:t})})}));let p=(0,To.createRoot)(u);return p.render((0,be.jsx)(vo,{store:this.store,customStyles:o,children:(0,be.jsx)(Gr,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(OP,{onLogIn:()=>this.loginViaPopup().catch(h=>J.warn(h.message))})})})),{unmount(){d.unmount(),p.unmount(),c(),f()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i,floatingMenuParent:s}=n,a=o&&ix(t,o)||void 0,[l,c]=this.overlayContainerFactory("floating-menu",a||t,{appendTo:s!=null?s:i},r==null?void 0:r.floatingMenuParent),u=(0,To.createRoot)(l);return u.render((0,be.jsx)(vo,{store:this.store,customStyles:r,children:(0,be.jsx)(Gr,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(dP,{onLogIn:()=>this.loginViaPopup().catch(f=>J.warn(f.message))})})})),{unmount(){u.unmount(),c()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays"),o=(0,To.createRoot)(r);return o.render((0,be.jsx)(vo,{store:this.store,customStyles:n,children:(0,be.jsx)(Gr,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(sP,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&J.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:i}),this.widgetRoot=(0,To.createRoot)(t),this.widgetRoot.render((0,be.jsx)(vo,{store:this.store,customStyles:r,children:(0,be.jsx)(Gr,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(EA,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(s=>J.warn(s.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:i}=r,s=(0,To.createRoot)(n);return s.render((0,be.jsx)(vo,{store:this.store,customStyles:o,children:(0,be.jsx)(Gr,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(Y0,{children:(0,be.jsxs)(bp,{assistantCode:t,initialQuestion:i,evaluateKnowledgeAssistFn:El,children:[(0,be.jsx)(Ts,{children:(0,be.jsx)(Cp,{title:r.title,emptyState:r.emptyState})}),(0,be.jsx)(q0,{children:(0,be.jsx)(Ep,{})})]})})})})),{unmount(){s.unmount()}}}setupHandlingTime(t){let n=xm(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){qA(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>_(this,null,function*(){yield this.store.dispatch(Lc());let t=ns(this.state);t&&this.store.dispatch(wd({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 _(this,null,function*(){return new Promise((n,r)=>{this.store.dispatch(ju());let o=new MessageChannel,i=o.port1,s=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,c=()=>{u&&!u.closed&&u.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=p=>_(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(al),l=!0,o.port1.close(),n()}catch(x){console.error(x),r(x)}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=>_(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){J.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){J.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}).`;J.warn(g),this.store.dispatch(dg(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.";J.warn(g),this.store.dispatch(dg(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 _(this,null,function*(){this.isMounted&&(yield this.store.dispatch(Vp()))})}refreshWidgetSuggestions(){return _(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Nc(this.state);try{n.forEach(({type:r})=>{switch(r){case"entities":this.store.dispatch(gr());break;case"pinned-messages":case"sticky-messages":break;default:Pu.includes(r)||this.store.dispatch(hr(r))}})}catch(r){this.handleError(r)}})}};ja.version="19.1.2-beta.2",ja.count=0;var cu=ja;function UF(e){return _(this,null,function*(){var o,i,s;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(s=(i=e.mimeType)!=null?i:n.headers.get("Content-Type"))!=null?s:"image/jpeg"})})}function aI(e,t){return _(this,null,function*(){let n=yield UF(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 lI(e,t,n){return _(this,null,function*(){yield new Co(e).authenticateWithKey(t,n)})}function cI(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function uI(r,o){return _(this,arguments,function*(e,t,n={}){var f,d;let{value:i}=e,{start:s,end:a}=(f=n.replace)!=null?f:{start:0,end:i.length},l=`${i.slice(0,s)}${t}${i.slice(a)}`,c=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+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 dI(r,o){return _(this,arguments,function*(e,t,n={}){let i=n.replace?yi(e,n.replace.start,n.replace.end):Ba(e),s,a=()=>{if(n.setRange)return n.setRange(i.cloneRange());i.deleteContents(),s=document.createElement("span"),i.insertNode(s),n.insertBRs!==!1?t.split(`
|
|
81
|
+
`);let h=d?r:0,g=p?Math.min(i,u.childNodes.length):u.childNodes.length;for(let x=h;x<g&&(c(u.childNodes[x]),a!==2);x++);break}default:break}p&&(a=2)}return c(e),l}var TA=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(TA||{}),Eo=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let i=this.getCaretPosition();Mo(i,this.cachedCaretPosition)||(this.cachedCaretPosition=i,this.emit("caretposition",i))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(TA).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}off(t,n){if(!this.eventListeners[t])return;let r=this.eventListeners[t].indexOf(n);r!==-1&&this.eventListeners[t].splice(r,1)}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function kA(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var ms=class extends Eo{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),su(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 i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!kA(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!kA(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return iu(this.element,n);let r=this.lastKnownSelection;if(r&&CA(this.element,r.start,r.end))return r;let o=Ba(this.element);return o.collapse(!1),iu(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return su(this.element,yi(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(i=>{var s,a;i.length===2&&i[0].addedNodes.length===1&&((s=i[0].addedNodes[0])==null?void 0:s.textContent)==="\u2060"&&((a=i[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var CF=["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 RA(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,i=window.getComputedStyle(e),s=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",CF.forEach(u=>{o[u]=i[u]}),n?e.scrollHeight>Number.parseInt(i.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),s.appendChild(r);let l=e.getBoundingClientRect(),c={top:l.top-e.scrollTop+a.offsetTop+Number.parseInt(i.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+Number.parseInt(i.borderLeftWidth)};return s.removeChild(r),c}var gs=class extends Eo{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 RA(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var i;return(i=n==null?void 0:n.get)==null?void 0:i.call(this.element)},set:i=>{var s;(s=n==null?void 0:n.set)==null||s.call(this.element,i),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function PA(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function TF(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var X0=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()}},Q0=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=PA(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()}},Z0=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.externalId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setExternalId(t){this.externalId!==t&&(this.cleanup(),J.info("Set externalId",t),this.externalId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Q0(t,this.deepdeskUrl,{debug:!0}):new X0(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=TF(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(J.info("Received broadcast event",this.externalId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;J.info("Broadcast event",{externalId:this.externalId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage(P(w({},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)}},AA=Z0;function kF(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function Ue(e){return Array.isArray(e)?e.map(Ue):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(w({},t),{[kF(n)]:Ue(e[n])}),{}):e}function RF(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function en(e){return Array.isArray(e)?e.map(en):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(w({},t),{[RF(n)]:en(e[n])}),{}):e}var Ua=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var J0=e=>new Promise(t=>{setTimeout(t,e)});var hs=class extends Ua{constructor(){super(...arguments);this.name="ClientError"}},tx=class extends Ua{constructor(){super(...arguments);this.name="ServerError"}},ex=new Map;function PF(e){return _(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t!=null&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(J.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var ys=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 i={isAborted:!1,reject:o},s=`${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:x=null}=T,y=oe(T,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(c){if(!l)throw new Error(`Can't use 'useCache' for ${n.method}`);if(ex.has(s)){r(ex.get(s));return}}let m=P(w({credentials:"include"},y),{headers:w({Accept:"application/json","Content-Type":"application/json"},y.headers)});!l&&this.csrfToken&&(m.headers=P(w({},m.headers),{"X-CSRFToken":this.csrfToken})),typeof x=="string"&&(m.headers=P(w({},m.headers),{"X-Deepdesk-API-Version":x}));let v=f,S=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&u&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let E=()=>_(this,null,function*(){return v--,a(s,m).then(k=>_(this,null,function*(){return g(k)&&!i.isAborted&&v>0?(yield J0(d),E()):k.status===401&&p===!0&&S===!1?(S=!0,yield this.refreshToken(),E()):k})).catch(k=>_(this,null,function*(){if(h(k)&&!i.isAborted&&v>0)return yield J0(d),E();throw k}))});E().then(k=>_(this,null,function*(){let A=yield PF(k);if(delete this.latestRequestByUrl[s],k.status>=500){o(new tx("Server Error",A));return}if(k.status===401){o(new hs("Unauthorized",A));return}if(k.status===403){o(new hs("Forbidden",A));return}if(k.status===404){o(new hs("Not Found",A));return}if(k.status>=400){o(new hs("Bad Request",A));return}c&&ex.set(s,A),r(A)})).catch(k=>{o(k)})})}validateToken(){return _(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 hs("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,w({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,w({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,w({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,w({method:"DELETE"},n))}};var IA;(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={}))})(IA||(IA={}));function nx(e){return P(w({},Ue(e)),{metadata:e.metadata})}var vs=class vs{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new ys(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>_(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return _(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(vs.exchangeTokenPromise||(vs.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),vs.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return _(this,null,function*(){var r;yield this.preflight(),J.info(`Creating conversation for session ${t.externalId} and agent ${t.agentId}`);let n=yield this.client.post("/api/v2/conversations",P(w({chat_start_time:new Date().toISOString()},en(t)),{metadata:(r=t.metadata)!=null?r:{}}));return nx(n)})}getMe(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return Ue(t)})}postIdentity(t){return _(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",en(t))})}patchMe(t){return _(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",en(t));return Ue(n)})}getProfile(t){return _(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return Ue(n)})}getKnowledgeAssistant(t){return _(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return Ue(n)})}getContentTypes(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return Ue(t)})}getAccount(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return Ue(t)})}getPlatformConfig(t){return _(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return Ue(r)})}checkUserExists(t){return _(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationByExternalId(r){return _(this,arguments,function*(t,n={}){yield this.preflight(),J.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/v2/conversations/by_external_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return J.info(`Successfully retrieved conversation ${s.id} for session ${t}`),nx(s)})}isConversationSupported(r){return _(this,arguments,function*(t,n={}){J.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${t}/has_active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(t,n){return _(this,null,function*(){var i;yield this.preflight();let r=en(n);n.metadata&&(r.metadata=(i=n.metadata)!=null?i:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return nx(o)})}postMessages(t,n){return _(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>P(w({},en(r)),{metadata:r.metadata})))})}sendEvent(t,n){return _(this,null,function*(){yield this.preflight();let a=n,{data:r}=a,o=oe(a,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((l,[c,u])=>P(w({},l),{[c]:u}),{}),s=["platform","agentId","agentName","agentEmail","conversationId"].reduce((l,c)=>(o[c]&&(l[c]=o[c]),l),{});return this.client.post("/api/v2/events",en(P(w(w({},i),s),{data:r,name:t})),{version:"v2"})})}getEntities(t){return _(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:t.filter(r=>r.text)})})}getTemporaryExchangeToken(){return _(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(t){return _(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw J.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return _(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",en(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return _(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}`,en(n),{abortLatest:!0})).map(s=>P(w({},Ue(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,l)=>a===l.findIndex(c=>c.text===s.text))})}isLoggedIn(){return _(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return _(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${t}/autocomplete`,en(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return _(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return Ue(n).map(r=>P(w({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return _(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",en(t),{abortLatest:!0,version:"v2"});return Ue(n)})}search(t){return _(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,en(t));return Ue(n)})}requestLoginByEmail(t){return _(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return Ue(n)})}requestPasswordlessToken(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return Ue(t.token)})}getCsrfToken(){return _(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return _(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return Ue(n)})}evaluateAssistant(t,n){return _(this,null,function*(){var s;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()}`,i=yield this.client.post(o,{input:(s=n==null?void 0:n.input)!=null?s:{},conversation:n==null?void 0:n.transcript});return Ue(i)})}createAssistantThread(t){return _(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return Ue(r)})}postMessageToAssistantThread(t){return _(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:r,message:o}=t,i=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return Ue(i)})}translateMessages(t){return _(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",en(t));return Ue(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(dS);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&J.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};vs.exchangeTokenPromise=null;var Co=vs;var fm=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=Ue(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 _A={startTime:null,stopTime:null},MA=e=>e.handlingTime,LA=Ee({name:"handlingTime",initialState:_A,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(it,()=>_A)}}),{handlingTimeStart:NA,handlingTimeStop:pm,handlingTimeReset:OA}=LA.actions,DA=LA.reducer;var FA=(e={})=>{let t=w({onAuthError:Rs(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var mm={list:{keywordMatches:[]},fetchState:"idle"};var xs=fe("styleSuggestions/getAll",(n,r)=>_(null,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(l=i.conversation.current)==null?void 0:l.profileCode;if(!s)return mm.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),AF=Ee({name:"styleSuggestions",initialState:mm,reducers:{},extraReducers:e=>{e.addCase(xs.pending,t=>{t.fetchState="loading"}).addCase(xs.rejected,t=>{t.fetchState="error"}).addCase(xs.fulfilled,(t,n)=>{t.fetchState="done",Mo(t.list,n.payload)||(t.list=n.payload)}).addCase(Pi,t=>{t.list=mm.list}).addCase(it,()=>mm)}}),zA=AF.reducer;var HA=(e={})=>{let t,n=!0,r=w({getStyleSuggestions:xs,debounce:500},e);return o=>i=>s=>{var p;let a=o.getState().input.text,l=i(s),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 IF(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var BA=(e={})=>{let t=w({getTextSuggestions:hr,getAutocompleteSuggestions:Gc,debounce:200,check:Dr},e),n;return r=>o=>i=>{var g;let{input:s}=r.getState(),a=o(i),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=i.type===Vp.toString();if(!f||!c&&!u)return a;let{input:p}=l;return IF(p,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let x=As(l);x===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(x))},d?0:t.debounce)),a}};var UA=xs.fulfilled.toString();function _F(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var VA=e=>t=>n=>r=>{var c;if(r.type!==UA){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(c=i.conversation)==null?void 0:c.current;if(o===s)return;let l=_F(o,s);r.type===UA&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var MF=Mu({assistants:Nb,auth:xw,conversation:kw,contentTypes:hR,passwordlessToken:eA,entities:WR,handlingTime:DA,info:qw,input:zw,settings:Db,profile:wR,search:eb,styleSuggestions:zA,ui:gP,textSuggestions:eP});function jA(e){return sw({reducer:MF,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(FA()).concat(BA({debounce:200})).concat(HA({debounce:500})).concat(VA(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,i)=>o.concat(i),n)},preloadedState:e.preloadedState})}var LF=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},NF=e=>t=>n=>r=>{var l,c;let o=t.getState(),i=Li("inlineSuggestions")(o),s=Li("autoSelectSuggestion")(o)||i;switch(r.type){case Rs.toString():{!r.payload&&e.emit("logout",void 0);break}case gr.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 Pi.toString():e.logSendMessage(r.payload);break;case xd.toString():e.emit("call-to-action",{cue:r.payload});break;case Cr.fulfilled.toString():r.isBroadcasted||e.broadcast(wg,r,!1);break;default:break}let a=n(r);switch(r.type){case Pi.toString():e.handleAfterSendMessage(r.payload);break;case Yc.toString():e.onUpdateShowTabHint(r.payload);break;case pm.toString():e.logHandlingTime();break;case _s.toString():e.broadcast(ed,r);break;case Ri.toString():e.broadcast(ed,r);break;case Sd.toString():t.dispatch(Ri({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{let u=o.assistants.cues.find(f=>f.code===r.meta.arg.data.assistantCode);e.emit("event",P(w({},r.meta.arg),{cue:u}));break}case vn.toString():{let{start:u,end:f}=o.input.selection;e.emit("select-suggestion",P(w({type:LF(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:u,end:f}:{start:0,end:f}})),i&&t.dispatch(Lo([]));break}case Gu.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(c=o.conversation.current)==null?void 0:c.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Lo.toString():{s&&r.payload.length>0&&t.dispatch(qu(0));break}default:break}return a},WA=NF;function rx(e){return e.toISOString().replace("T"," ").replace("Z","")}var OF=(e,t)=>t.version,$A=Ht([Ms,br,MA,OF],(e,t,n,r)=>{if(!t)return J.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:i}=n;return!o||!i?(J.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:t,clientVersion:r,agentId:e==null?void 0:e.agentId,agentName:e==null?void 0:e.agentName,agentEmail:e==null?void 0:e.agentEmail,timeStart:rx(o),timeStop:rx(i)}});function KA(e,t){let{text:n,metrics:{numPaste:r,pastes:o,textSuggestions:i}}=e.input,s=n.length;return{source:"agent",clientVersion:t.version,pastes:o,lenTextTotal:s,numPastes:r,suggestions:i}}var au=class extends Error{};function DF(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var gm=class{constructor(){this.queues={}}push(t,n){let r=()=>{let i=this.queues[t][1];i?(this.queues[t]=[i.promise,null],i.resolve()):delete this.queues[t]};if(!this.queues[t]){let i=n().finally(r);return this.queues[t]=[i,null],i}this.queues[t][1]&&this.queues[t][1].reject(new au("Queued async function is outdated"));let o=DF();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};function ox(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return ox(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?ox(o,t):null}function ix(e,t){return ox(e,t)}var FF={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},GA=(e,t)=>{var o,i,s;if(!((s=(i=(o=e.uiConfig)==null?void 0:o.widget)==null?void 0:i.types.find(a=>a.type==="cues"))==null?void 0:s.isActive))return J.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let r=e[FF[t]];return r&&r.length>0?r.map(a=>a.code):(J.warn(`No assistant set in profile for conversation event "${t}"`),[])};function qA(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function zF(e){return typeof e=="object"&&e!==null&&"tagName"in e}function hm(e){return zF(e)&&(fs(e)||Xp(e))}var XA,Hr=new Map,HF=["bottom","height","left","right","top","width"],YA=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:HF.some(n=>e[n]!==t[n]);function QA(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,...QA(t)]:[]}function ZA(e,t){return!e||!t?null:P(w({},e),{top:e.top+t.top,left:e.left+t.left})}var ym=!1,JA=()=>{ym=!0;let e=[];if(Hr.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Hr.delete(n);return}let r=n.getBoundingClientRect();YA(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(ZA,t.rect):t.rect;YA(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Hr.size===0){ym=!1;return}XA=window.requestAnimationFrame(JA)};function sx(e,t){let n=QA(e),r=[],o=n.map((i,s)=>sx(i,a=>{r[s]=a;let l=Hr.get(e);if(!l)return;let c=r.reduce(ZA,l.rect);l.callbacks.forEach(u=>u(c))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Hr.has(e)){let s=Hr.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Hr.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!ym&&JA()},unobserve(){o.forEach(s=>s.unobserve());let i=Hr.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Hr.delete(e),Hr.size||(cancelAnimationFrame(XA),ym=!1)}}}}var eI,Br=new Map,tI=()=>{Br.forEach((e,t)=>{if(!t.isConnected){Br.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),Br.size!==0&&(eI=window.requestAnimationFrame(tI))};function nI(e,t){return{observe(){let n=Br.size===0;Br.has(e)?Br.get(e).callbacks.push(t):Br.set(e,{visible:void 0,callbacks:[t]}),n&&tI()},unobserve(){let n=Br.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Br.delete(e),Br.size||cancelAnimationFrame(eI)}}}}var ax=["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 lx(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Va(e){return Number.parseFloat(e)}function vm(e){return Math.round(e*1e6)}function rI(e){return e/1e6}function cx(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Va(e.width),i=Va(e.borderLeftWidth),s=Va(e.borderRightWidth),a=Va(e.paddingRight),l=rI(vm(o)-vm(i)-vm(s)),c=rI(vm(r));if(l-c>2){let u=l-c;n.style.paddingRight=`${a+u}px`}}function lu(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",Yi(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};lx(r,n,ax),cx(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=nI(e,()=>{lx(r,n,ax),cx(r,e,n),i(),setTimeout(i,0)}),a,l=!0,c=sx(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(lx(r,n,ax),cx(r,e,n),i(),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=Va(h.borderTopWidth),x=Va(h.borderBottomWidth),y=p.top+g-d.top,m=d.top+d.height+-(p.top+p.height-x);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(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),c.unobserve(),s.unobserve(),n.remove()}]}function BF(e){return e.offsetParent!==null}function oI(e){if(!BF(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 xm(e,t,n=100){let r=oI(e);t({isVisible:r});let o=setInterval(()=>{let i=oI(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var iI=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){J.warn("[Deepdesk] SessionStorage is blocked by browser")}}});var be=b(R());var sI=iI("showTabHint",!0),ja=class ja{constructor({deepdeskUrl:t,version:n=ja.version||"unknown",locale:r="en-US",token:o,fetch:i,productName:s,createCustomChannel:a,websocketClient:l=fm}){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 gm;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let c=t.replace(/\/api$/,"");this.deepdeskApi=new Co(c,{token:o,fetch:i}),this.version=n,this.instanceId=ja.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[WA({broadcast:(h,g,x)=>{this.broadcastEvents.send(h,g,x)},emit:(h,g)=>this.emit(h,g),handleAfterSendMessage:h=>this.handleAfterSendMessage(h),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:h=>this.logSendMessage(h),onUpdateShowTabHint:h=>sI.update(h),sendEvent:(h,g)=>this.deepdeskApi.sendEvent(h,g)})]};this.store=jA(u),this.broadcastEvents=new AA({debug:!0,deepdeskUrl:c,eventMap:tb(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:()=>_(this,null,function*(){var h;return(h=St(this.state))!=null?h:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(Yc(sI.value())),this.store.dispatch(wd({locale:r,adminUrl:c,productName:s}));let f=[],d=h=>{if(!h.conversationId)return;let g=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(Lb(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(Mb(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(_s([{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=ki(this.state)[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}externalId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.externalId}shouldAbort(){return this.state.conversation.isSupported===!1?(J.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(J.warn("Profile has not been loaded (yet)"),!0):(J.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(t){if(St(this.state))t();else{let n=this.subscribe(St,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Rs(null)),this.store.dispatch($r()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return _(this,null,function*(){return(yield this.store.dispatch($r())).payload})}isConversationSupported(t,n){return _(this,null,function*(){return(yield this.store.dispatch(mg({externalId:t,options:n}))).payload})}createConversation(t){return _(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(Wu(P(w({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}getConversationByExternalId(t,n){return _(this,null,function*(){return this.hasConversation()&&this.externalId()!==t&&this.resetConversation(),(yield this.store.dispatch($u({externalId:t,options:n}))).payload})}upsertConversation(t){return _(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(gg(P(w({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return _(this,null,function*(){yield this.store.dispatch(hg(t))})}updateConversation(t){return _(this,null,function*(){return(yield this.store.dispatch(Ku(t))).payload})}resetConversation(){this.store.dispatch(it()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(wd(t))}setVisitorInfo(t){this.store.dispatch(Ww(t))}setCustomData(t){this.store.dispatch($w(t))}setAgentInfo(t,n){return _(this,null,function*(){var o;yield this.store.dispatch(il(w(w({},t),n))),(o=this.state.info.agentInfo)!=null&&o.agentNickname||this.broadcastEvents.send(Ju,{showNicknameDialog:!0})})}setAgentSettings(t){return _(this,null,function*(){yield this.store.dispatch(vg(t))})}getAgentSettings(){return _(this,null,function*(){return(yield this.store.dispatch(xg())).payload})}refresh(){return _(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(Yu({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}))}notifyExternalSuggestion(t){this.store.dispatch(vn(t))}evaluateAssistant(t,n){return _(this,null,function*(){var l;let{input:r={},transcript:o,showCuesInWidget:i=!0,includeMetadata:s}=n||{},a=yield this.store.dispatch(Cr({assistantCode:t,transcript:o,includeMetadata:s,input:r,skipState:!i}));if(a.error)throw new Error(`Assistant evaluation failed: ${(l=a.payload)!=null?l:a.error.message}`);return a.payload.output})}evaluateConversationAssistant(t,n){return _(this,null,function*(){yield this.loadProfileConfig();let r=this.state.profile.data;if(!r){J.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=GA(r,t);yield Promise.all(o.map(i=>this.queues.push(i,()=>_(this,null,function*(){yield this.evaluateAssistant(i,w({includeMetadata:!0},n))})).catch(s=>{if(s instanceof au){J.warn(`Queued assistant "${i}" was outdated and dropped`);return}throw s})))})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=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(_w(yg(t))),!Dr(this.state)||t.key!=="Tab"&&!c)return;let h=()=>{n||!p||s&&(t.shiftKey||(this.store.dispatch(Nw()),t.preventDefault()))},g=()=>{n||!p||f&&i<=0||s&&(t.shiftKey||(this.store.dispatch(Ow()),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(qu(-1)),this.store.dispatch(di({collapse:!0})),this.store.dispatch(pP(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let x=Is(this.state);if(!x)return;this.store.dispatch(Yc(!1)),this.store.dispatch(vn({text:x.text,suggestion:x,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(f||this.state.input.selectedSuggestionIndex===-1)return;let x=Is(this.state);if(!x)return;this.store.dispatch(vn({text:x.text,suggestion:x,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(f||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let x=Is(this.state);if(!x)return;this.store.dispatch(vn({text:x.text,suggestion:x,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(di({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Lo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(J.info("Start handling time"),this.store.dispatch(NA()))}handlingTimeStop(){this.state.handlingTime.startTime&&(J.info("Stop handling time"),this.store.dispatch(pm()))}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=$A(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(OA()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Pi((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(Fw()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){J.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),J.error(i)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}setPlatformVariables(t){this.store.dispatch(Kw(t))}whenConversationLoaded(t){let n=i=>{var s;return(s=i.conversation.current)==null?void 0:s.id},r=()=>this.loadProfileConfig().then(()=>t());return n(this.state)&&r(),this.subscribe(n,i=>{i&&r()})}overlayContainerFactory(t,n,r,o){let[i,s]=lu(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),[i,s]}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,s=i?i.ownerDocument.defaultView:null;if(i&&(s===window||(s==null?void 0:s.parent)===window)){let[l,c]=lu(i,{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 Yi(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),J.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(J.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Dw(r.metrics))):J.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!hm(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s,inputMediator:a}=d,l=oe(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),c={customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),Yi(t),this.inputMediator=a||(fs(t)?new gs(t):new ms(t)),this.inputMediator.on("change",({plainText:p,rawHTML:h})=>{this.store.dispatch(Yu({text:p,html:h}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(Mw(yg(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:h})=>{this.store.dispatch(Lw({text:p,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(Iw(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(Xu(p))},500):this.store.dispatch(Xu(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($p(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch($p(!0))}),this.renderSuggestions(t,c),this.subscribe(Li("inlineSuggestions"),()=>{this.renderSuggestions(t,c)}),this.subscribe(Li("suggestionsPlacement"),()=>{this.renderSuggestions(t,c)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(Yu({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(Xu(this.inputMediator.getSelection())),this.store.dispatch($p(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,To.createRoot)(n),o=null,i=a=>{o=a,s()},s=()=>{r==null||r.render((0,be.jsx)(vo,{store:this.store,children:(0,be.jsx)(Gr,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(kP,{id:"deepdesk-nickname-dialog",error:o,onSave:a=>_(this,null,function*(){try{yield this.store.dispatch(Vw({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(Ju,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(l){J.error("Error setting agent nickname",l),i("error"),this.nicknameDialogFailed=!0}})})})}))};s(),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,i;(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(s=>s()),this.unmountHandlers=[],(i=this.inputMediator)==null||i.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,i,s;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(i=this.aboveSuggestions)==null||i.unmount(),(s=this.belowSuggestions)==null||s.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"),i=(0,To.createRoot)(o);i.render((0,be.jsx)(vo,{store:this.store,customStyles:r,children:(0,be.jsx)(Gr,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(CP,{})})}));let s=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",s),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",s),i.unmount(),o.remove()}}}renderAboveOrBelowSuggestions(t,n,r){let{customStyles:o,closestScrollSelector:i,appendOverlayTo:s}=n,a=i&&ix(t,i)||void 0,[l,c]=this.overlayContainerFactory("deepdesk-tab-completion",a||t,{appendTo:s,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},o==null?void 0:o.rootNode),[u,f]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||t,{appendTo:s,placement:r},o==null?void 0:o.suggestionsRootNode),d=(0,To.createRoot)(l);d.render((0,be.jsx)(vo,{store:this.store,customStyles:o,children:(0,be.jsx)(Gr,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(QP,{inputElement:t})})}));let p=(0,To.createRoot)(u);return p.render((0,be.jsx)(vo,{store:this.store,customStyles:o,children:(0,be.jsx)(Gr,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(OP,{onLogIn:()=>this.loginViaPopup().catch(h=>J.warn(h.message))})})})),{unmount(){d.unmount(),p.unmount(),c(),f()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i,floatingMenuParent:s}=n,a=o&&ix(t,o)||void 0,[l,c]=this.overlayContainerFactory("floating-menu",a||t,{appendTo:s!=null?s:i},r==null?void 0:r.floatingMenuParent),u=(0,To.createRoot)(l);return u.render((0,be.jsx)(vo,{store:this.store,customStyles:r,children:(0,be.jsx)(Gr,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(dP,{onLogIn:()=>this.loginViaPopup().catch(f=>J.warn(f.message))})})})),{unmount(){u.unmount(),c()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays"),o=(0,To.createRoot)(r);return o.render((0,be.jsx)(vo,{store:this.store,customStyles:n,children:(0,be.jsx)(Gr,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(sP,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&J.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:i}),this.widgetRoot=(0,To.createRoot)(t),this.widgetRoot.render((0,be.jsx)(vo,{store:this.store,customStyles:r,children:(0,be.jsx)(Gr,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(EA,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(s=>J.warn(s.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:i}=r,s=(0,To.createRoot)(n);return s.render((0,be.jsx)(vo,{store:this.store,customStyles:o,children:(0,be.jsx)(Gr,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(Y0,{children:(0,be.jsxs)(bp,{assistantCode:t,initialQuestion:i,evaluateKnowledgeAssistFn:El,children:[(0,be.jsx)(Ts,{children:(0,be.jsx)(Cp,{title:r.title,emptyState:r.emptyState})}),(0,be.jsx)(q0,{children:(0,be.jsx)(Ep,{})})]})})})})),{unmount(){s.unmount()}}}setupHandlingTime(t){let n=xm(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){qA(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>_(this,null,function*(){yield this.store.dispatch(Lc());let t=ns(this.state);t&&this.store.dispatch(wd({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 _(this,null,function*(){return new Promise((n,r)=>{this.store.dispatch(ju());let o=new MessageChannel,i=o.port1,s=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,c=()=>{u&&!u.closed&&u.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=p=>_(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(al),l=!0,o.port1.close(),n()}catch(x){console.error(x),r(x)}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=>_(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){J.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){J.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}).`;J.warn(g),this.store.dispatch(dg(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.";J.warn(g),this.store.dispatch(dg(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 _(this,null,function*(){this.isMounted&&(yield this.store.dispatch(Vp()))})}refreshWidgetSuggestions(){return _(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Nc(this.state);try{n.forEach(({type:r})=>{switch(r){case"entities":this.store.dispatch(gr());break;case"pinned-messages":case"sticky-messages":break;default:Pu.includes(r)||this.store.dispatch(hr(r))}})}catch(r){this.handleError(r)}})}};ja.version="19.2.0",ja.count=0;var cu=ja;function UF(e){return _(this,null,function*(){var o,i,s;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(s=(i=e.mimeType)!=null?i:n.headers.get("Content-Type"))!=null?s:"image/jpeg"})})}function aI(e,t){return _(this,null,function*(){let n=yield UF(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 lI(e,t,n){return _(this,null,function*(){yield new Co(e).authenticateWithKey(t,n)})}function cI(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function uI(r,o){return _(this,arguments,function*(e,t,n={}){var f,d;let{value:i}=e,{start:s,end:a}=(f=n.replace)!=null?f:{start:0,end:i.length},l=`${i.slice(0,s)}${t}${i.slice(a)}`,c=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+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 dI(r,o){return _(this,arguments,function*(e,t,n={}){let i=n.replace?yi(e,n.replace.start,n.replace.end):Ba(e),s,a=()=>{if(n.setRange)return n.setRange(i.cloneRange());i.deleteContents(),s=document.createElement("span"),i.insertNode(s),n.insertBRs!==!1?t.split(`
|
|
82
82
|
`).reverse().forEach((l,c)=>{c>0&&i.insertNode(document.createElement("br")),i.insertNode(document.createTextNode(l))}):i.insertNode(document.createTextNode(t))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let l=n.selectionAfter?yi(e,n.selectionAfter.start,n.selectionAfter.end):(i.collapse(!1),i),c=window.getSelection();c==null||c.removeAllRanges(),c==null||c.addRange(l)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}function VF(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 jF(e){let t=document.createDocumentFragment();return e.split(`
|
|
83
83
|
`).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},i=0;for(;o=n.slice(i).match(/(\[([^\]]+)])\(([^)]+)\)/);){let s=document.createElement("a");s.href=o[3],s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer"),s.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(i,i+o.index))),t.appendChild(s),i=i+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(i)))}),t}function fI(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):fI(n,t)}function pI(o,i){return _(this,arguments,function*(e,t,{isBlock:n,isHTML:r}={}){let s;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let a=()=>{var d;let l=(d=e.ownerDocument.defaultView)!=null?d:window,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;s=document.createElement("span"),u.insertNode(s);let f=r?VF(t):jF(t);n?fI(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(),!!s)try{s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}return kI(WF);})();
|
|
84
84
|
/*! Bundled license information:
|