@deepdesk/deepdesk-sdk 10.6.2-beta.5 → 10.7.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 CHANGED
@@ -6,6 +6,6 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
6
6
  c-17.9,17.9-27.3,40.1-27.3,65.7C163.4,163,163.4,233,163.4,233z M465.5,267.9V477c0,9.4-3.4,17.9-10.2,24.7
7
7
  c-6.8,6.8-15.4,10.2-24.7,10.2h-349c-9.4,0-17.9-3.4-24.7-10.2c-6.8-6.8-10.2-15.4-10.2-24.7V267.9c0-9.4,3.4-17.9,10.2-24.7
8
8
  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
9
- 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 oa=require("react/jsx-runtime"),sh={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},fu=({className:t,color:e})=>(0,oa.jsx)("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,oa.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:sh[e||"pink"]})});var hu={root:"_root_bgd7a_1",text:"_text_bgd7a_18",icon:"_icon_bgd7a_33",logo:"_logo_bgd7a_38",lock:"_lock_bgd7a_43"};var na={};V(na,{enUS:()=>rh,nlNL:()=>ih});var rh={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:0,value:"Search"}]},ih={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:0,value:"Zoek"}]};var vu=require("react-redux"),Gt=require("react/jsx-runtime"),Su=()=>{let t=T(na),e=C("productName"),o=C("adminUrl"),n=(0,vu.useDispatch)(),s=(0,yu.useSelector)(ue),r=h("FloatingMenu",hu);if(s===null)return null;let i=()=>{s===!0?n(ee(!0)):window.open(o,"_blank")};return(0,Gt.jsxs)("button",{className:r.root,onClick:i,children:[(0,Gt.jsx)("div",{className:r.text,children:s?t("search"):t("signin",{productName:e})}),(0,Gt.jsxs)("div",{className:r.icon,children:[(0,Gt.jsx)(fu,{className:r.logo,color:"pink"}),s===!1&&(0,Gt.jsx)(mu,{className:r.lock})]})]})};var z=require("react/jsx-runtime");var _u=uu("showTabHint",!0),Cn=class t{static version="10.6.2-beta.5";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:l}){let c=e.replace(/\/api$/,"");this.deepdeskApi=new it(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[lu({emit:(d,u,g)=>this.emit(d,u,g),handleAfterSendMessage:d=>this.handleAfterSendMessage(d),handleInputChanged:d=>this.handleInputChanged(d),handleKeyDown:d=>this.handleKeyDown(d),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:d=>this.logSendMessage(d),logSendEditSuggestionMessage:d=>this.logSendEditMessage(d),onUpdateShowTabHint:d=>_u.update(d),sendEvent:(d,u)=>this.deepdeskApi.sendEvent(d,u)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new bn(o)}),this.store=au(p),this.broadcastEvents=new $d({debug:!0,deepdeskUrl:c,eventMap:Lc(this.store),createCustomChannel:l}),this.store.dispatch(Do),this.store.dispatch(Jo(_u.value())),this.store.dispatch(Do({locale:s,adminUrl:c,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(k.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(k.warn("Profile has not been loaded (yet)"),!0):(k.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(vo(null)),this.store.dispatch($e()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();ue(n)&&Tc(n)!=="loading"&&e()});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch($e())).payload}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(o){k.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(kr({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Hn(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Bn({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Rr(e))).payload}async postMessages(e){return(await this.store.dispatch(Kn(e))).payload}async updateConversation(e){return(await this.store.dispatch(Fn(e))).payload}resetConversation(){this.store.dispatch(P()),this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Qe());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(Do(e))}setVisitorInfo(e){this.store.dispatch(zl(e))}async setAgentInfo(e){await this.store.dispatch(Go(e))}async setAgentSettings(e){await this.store.dispatch(ii(e))}async getAgentSettings(){return(await this.store.dispatch(ai())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(Is()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Wn(e))}notifyKeyDown(e){this.store.dispatch(qn(e))}notifyPaste(e,o){this.store.dispatch(Wa({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(qa(e))}notifyExternalSuggestion(e){this.store.dispatch(ke(e)),this.store.dispatch(Ue())}notifyEditSuggestion(e){this.store.dispatch(cc(e.contentType,e.suggestions)),this.store.dispatch(Ge({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(ht({collapse:!1})),this.inputMediator&&this.store.dispatch(Ba({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(Oe([])))}handleKeyDown(e){let{overlayCollapsed:o}=this.state.ui,{textSuggestions:n,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=n.length>0,l=s!==-1;if(this.store.dispatch(Va(zn(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Ua()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{if(o||!a||!r||e.shiftKey)return;this.store.dispatch(ja());let{selectedSuggestionIndex:d}=this.state.input;e.preventDefault(),!i&&(d===-1?this.store.dispatch(Ho()):this.stageSelectedSuggestion({inputType:"arrow"}))};switch(e.key){case"Up":case"ArrowUp":i?p():c();return;case"Down":case"ArrowDown":{i?c():p();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(ut(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(ut(-1)),this.store.dispatch(Ho()),e.preventDefault()):o||(this.store.dispatch(ht({collapse:!0})),this.store.dispatch(_c(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:d}=this.state.input,u=d.text.substring(0,d.selection.end),{tabCompletionSuggestion:g}=this.state.input;this.store.dispatch(Jo(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&g&&g.text.startsWith(u)&&(this.store.dispatch(ke({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(Ue())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Ga()),this.store.dispatch(Oe([]))}handlingTimeStart(){this.state.handlingTime.startTime||(k.info("Start handling time"),this.store.dispatch(Jd()))}handlingTimeStop(){this.state.handlingTime.startTime&&(k.info("Stop handling time"),this.store.dispatch(ur()))}logSendMessage(e){let o=ea("input",this.state,{version:this.version});e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logSendEditMessage(e){let o=ea("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Ka(this.state.overlayInput.metrics))}logHandlingTime(){let e=cu(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Yd())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(Ue()),this.store.dispatch(It(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(ke({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){k.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),k.error(i)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=Lt(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=Lt(r,{appendTo:document.body});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return At(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),k.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(k.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Xa(n.metrics))):k.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch{}}mount(e,o={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!hr(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:n={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,isEmbedded:d,detectSubmit:u,insertLink:g,inputMediator:f,closestScrollSelector:m,appendOverlayTo:v,inlineSuggestions:E,floatingMenu:y}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:g,isEmbedded:d,inlineSuggestions:E,floatingMenu:y}),o.automaticHandlingTime&&this.setupHandlingTime(e),At(e),this.inputMediator=f||(St(e)?new qe(e):new Vt(e)),this.inputMediator.on("change",({plainText:S})=>{this.notifyInputChanged(S)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch($a({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",S=>{this.notifyKeyDown(S)}),this.inputMediator.on("paste",({pastedText:S,selectionText:H})=>{this.notifyPaste(S,H)}),this.inputMediator.on("cut",({selectionText:S})=>{this.notifyCut(S)});let x=m&&pu(e,m)||void 0;if(E){let{customStyles:S,appendOverlayTo:H}=o;if(St(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let N=this.createInlineContainer(e,"deepdesk-caret");(0,we.render)((0,z.jsx)(jt,{store:this.store,customStyles:S,children:(0,z.jsx)(Kt,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(_p,{})})}),N),this.inputMediator.on("caret",B=>{this.store.dispatch(Oe([])),B?(N.style.display="block",N.style.top=`${B.top}px`,N.style.left=`${B.left}px`):N.style.display="none"});let Y=this.overlayContainerFactory("floating-menu",x||e,{appendTo:H});(0,we.render)((0,z.jsx)(jt,{store:this.store,customStyles:S,children:(0,z.jsx)(Kt,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(Su,{})})}),Y)}else{let S=this.overlayContainerFactory("deepdesk-tab-completion",x||e,{appendTo:v,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),H=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:v},n==null?void 0:n.suggestionsRootNode);(0,we.render)((0,z.jsx)(jt,{store:this.store,customStyles:n,children:(0,z.jsx)(Kt,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(Zp,{inputElement:e})})}),S),(0,we.render)((0,z.jsx)(jt,{store:this.store,customStyles:n,children:(0,z.jsx)(Kt,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(Ip,{})})}),H)}(0,we.render)((0,z.jsx)(jt,{store:this.store,customStyles:n,children:(0,z.jsx)(Kt,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(gp,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",S=>{clearTimeout(b),S===null?b=setTimeout(()=>{S!==null&&this.store.dispatch(Pr(S))},500):this.store.dispatch(Pr(S))}),this.inputMediator.on("disabled",()=>{var S;(S=this.inputMediator)==null||S.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{u&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(ho(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(ho(!0))),this.store.dispatch(Fa({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(Ue()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var S;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((S=this.state.conversation.current)==null?void 0:S.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(o=>o()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,o={}){if(this.widgetRoot&&k.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:n,showImages:s,showPersonalCollectionLink:r,isEmbedded:i}=o;this.widgetRoot=e,this.configure({showImages:s,showPersonalCollectionLink:r,isEmbedded:i}),(0,we.render)((0,z.jsx)(jt,{store:this.store,customStyles:n,children:(0,z.jsx)(Kt,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(qd,{})})}),e),this.whenConversationLoaded(()=>{var a;this.broadcastEvents.setSessionId((a=this.state.conversation.current)==null?void 0:a.sessionId)})}unmountWidget(){this.widgetRoot&&(0,we.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=yr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){du(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(pn());let e=wo(this.state);e&&this.store.dispatch(Do({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:e.knowledgeAssistForAgents,recommendTextSuggestions:e.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async loginViaPopup(){return new Promise((e,o)=>{let n=this.state.settings.adminUrl,s=new MessageChannel,r=s.port1,i=new URL(`${n}/platform/sso/`);i.searchParams.append("redirect","/sdk/popup/close.html");let a=!1,l=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};r.onmessage=async u=>{var g,f;if((g=u.data)!=null&&g.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((f=u.data)==null?void 0:f.jwt),this.broadcastEvents.send(tn),l(),a=!0,s.port1.close(),e()}catch(m){o(m)}};let c=window.open(i.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&o(new Error("Popup blocked by browser"));let p=async u=>{var g;if(u.origin===i.origin)switch((g=u.data)==null?void 0:g.type){case"deepdesk-popup-loaded":{c==null||c.postMessage({type:"deepdesk-popup-create-channel"},i.origin,[s.port2]);break}case"deepdesk-popup-error":{l(),u.data.message==="Timeout"&&k.warn("Popup timed out. Check if the account's platform url is configured correctly."),o(new Error(u.data.message));break}}};window.addEventListener("message",p);let d=setInterval(()=>{c&&!c.closed||(l(),a||o(new Error("Popup closed by user")))},200);this.unmountHandlers.push(l)})}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(k.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(o){let{message:n}=o;k.info(n),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let o=Fs(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(Ae()):this.store.dispatch(We(n))})}catch(n){this.handleError(n)}}};async function xu(t,e,o={}){let{value:n}=t,{start:s,end:r}=o.replace??{start:0,end:n.length},i=`${n.slice(0,s)}${e}${n.slice(r)}`,a=o.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function bu(t,e,o={}){let n=o.replace?wt(t,o.replace.start,o.replace.end):Po(t),s,r=()=>{if(o.setRange)return o.setRange(n.cloneRange());n.deleteContents(),s=document.createElement("span"),n.insertNode(s),o.insertBRs!==!1?e.split(`
9
+ 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 oa=require("react/jsx-runtime"),sh={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},fu=({className:t,color:e})=>(0,oa.jsx)("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,oa.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:sh[e||"pink"]})});var hu={root:"_root_bgd7a_1",text:"_text_bgd7a_18",icon:"_icon_bgd7a_33",logo:"_logo_bgd7a_38",lock:"_lock_bgd7a_43"};var na={};V(na,{enUS:()=>rh,nlNL:()=>ih});var rh={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:0,value:"Search"}]},ih={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:0,value:"Zoek"}]};var vu=require("react-redux"),Gt=require("react/jsx-runtime"),Su=()=>{let t=T(na),e=C("productName"),o=C("adminUrl"),n=(0,vu.useDispatch)(),s=(0,yu.useSelector)(ue),r=h("FloatingMenu",hu);if(s===null)return null;let i=()=>{s===!0?n(ee(!0)):window.open(o,"_blank")};return(0,Gt.jsxs)("button",{className:r.root,onClick:i,children:[(0,Gt.jsx)("div",{className:r.text,children:s?t("search"):t("signin",{productName:e})}),(0,Gt.jsxs)("div",{className:r.icon,children:[(0,Gt.jsx)(fu,{className:r.logo,color:"pink"}),s===!1&&(0,Gt.jsx)(mu,{className:r.lock})]})]})};var z=require("react/jsx-runtime");var _u=uu("showTabHint",!0),Cn=class t{static version="10.7.0";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:l}){let c=e.replace(/\/api$/,"");this.deepdeskApi=new it(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[lu({emit:(d,u,g)=>this.emit(d,u,g),handleAfterSendMessage:d=>this.handleAfterSendMessage(d),handleInputChanged:d=>this.handleInputChanged(d),handleKeyDown:d=>this.handleKeyDown(d),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:d=>this.logSendMessage(d),logSendEditSuggestionMessage:d=>this.logSendEditMessage(d),onUpdateShowTabHint:d=>_u.update(d),sendEvent:(d,u)=>this.deepdeskApi.sendEvent(d,u)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new bn(o)}),this.store=au(p),this.broadcastEvents=new $d({debug:!0,deepdeskUrl:c,eventMap:Lc(this.store),createCustomChannel:l}),this.store.dispatch(Do),this.store.dispatch(Jo(_u.value())),this.store.dispatch(Do({locale:s,adminUrl:c,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(k.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(k.warn("Profile has not been loaded (yet)"),!0):(k.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(vo(null)),this.store.dispatch($e()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();ue(n)&&Tc(n)!=="loading"&&e()});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch($e())).payload}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(o){k.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(kr({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Hn(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Bn({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Rr(e))).payload}async postMessages(e){return(await this.store.dispatch(Kn(e))).payload}async updateConversation(e){return(await this.store.dispatch(Fn(e))).payload}resetConversation(){this.store.dispatch(P()),this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Qe());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(Do(e))}setVisitorInfo(e){this.store.dispatch(zl(e))}async setAgentInfo(e){await this.store.dispatch(Go(e))}async setAgentSettings(e){await this.store.dispatch(ii(e))}async getAgentSettings(){return(await this.store.dispatch(ai())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(Is()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Wn(e))}notifyKeyDown(e){this.store.dispatch(qn(e))}notifyPaste(e,o){this.store.dispatch(Wa({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(qa(e))}notifyExternalSuggestion(e){this.store.dispatch(ke(e)),this.store.dispatch(Ue())}notifyEditSuggestion(e){this.store.dispatch(cc(e.contentType,e.suggestions)),this.store.dispatch(Ge({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(ht({collapse:!1})),this.inputMediator&&this.store.dispatch(Ba({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(Oe([])))}handleKeyDown(e){let{overlayCollapsed:o}=this.state.ui,{textSuggestions:n,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=n.length>0,l=s!==-1;if(this.store.dispatch(Va(zn(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Ua()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{if(o||!a||!r||e.shiftKey)return;this.store.dispatch(ja());let{selectedSuggestionIndex:d}=this.state.input;e.preventDefault(),!i&&(d===-1?this.store.dispatch(Ho()):this.stageSelectedSuggestion({inputType:"arrow"}))};switch(e.key){case"Up":case"ArrowUp":i?p():c();return;case"Down":case"ArrowDown":{i?c():p();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(ut(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(ut(-1)),this.store.dispatch(Ho()),e.preventDefault()):o||(this.store.dispatch(ht({collapse:!0})),this.store.dispatch(_c(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:d}=this.state.input,u=d.text.substring(0,d.selection.end),{tabCompletionSuggestion:g}=this.state.input;this.store.dispatch(Jo(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&g&&g.text.startsWith(u)&&(this.store.dispatch(ke({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(Ue())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Ga()),this.store.dispatch(Oe([]))}handlingTimeStart(){this.state.handlingTime.startTime||(k.info("Start handling time"),this.store.dispatch(Jd()))}handlingTimeStop(){this.state.handlingTime.startTime&&(k.info("Stop handling time"),this.store.dispatch(ur()))}logSendMessage(e){let o=ea("input",this.state,{version:this.version});e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logSendEditMessage(e){let o=ea("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Ka(this.state.overlayInput.metrics))}logHandlingTime(){let e=cu(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Yd())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(Ue()),this.store.dispatch(It(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(ke({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){k.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),k.error(i)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=Lt(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=Lt(r,{appendTo:document.body});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return At(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),k.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(k.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Xa(n.metrics))):k.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch{}}mount(e,o={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!hr(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:n={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,isEmbedded:d,detectSubmit:u,insertLink:g,inputMediator:f,closestScrollSelector:m,appendOverlayTo:v,inlineSuggestions:E,floatingMenu:y}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:g,isEmbedded:d,inlineSuggestions:E,floatingMenu:y}),o.automaticHandlingTime&&this.setupHandlingTime(e),At(e),this.inputMediator=f||(St(e)?new qe(e):new Vt(e)),this.inputMediator.on("change",({plainText:S})=>{this.notifyInputChanged(S)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch($a({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",S=>{this.notifyKeyDown(S)}),this.inputMediator.on("paste",({pastedText:S,selectionText:H})=>{this.notifyPaste(S,H)}),this.inputMediator.on("cut",({selectionText:S})=>{this.notifyCut(S)});let x=m&&pu(e,m)||void 0;if(E){let{customStyles:S,appendOverlayTo:H}=o;if(St(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let N=this.createInlineContainer(e,"deepdesk-caret");(0,we.render)((0,z.jsx)(jt,{store:this.store,customStyles:S,children:(0,z.jsx)(Kt,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(_p,{})})}),N),this.inputMediator.on("caret",B=>{this.store.dispatch(Oe([])),B?(N.style.display="block",N.style.top=`${B.top}px`,N.style.left=`${B.left}px`):N.style.display="none"});let Y=this.overlayContainerFactory("floating-menu",x||e,{appendTo:H});(0,we.render)((0,z.jsx)(jt,{store:this.store,customStyles:S,children:(0,z.jsx)(Kt,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(Su,{})})}),Y)}else{let S=this.overlayContainerFactory("deepdesk-tab-completion",x||e,{appendTo:v,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),H=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:v},n==null?void 0:n.suggestionsRootNode);(0,we.render)((0,z.jsx)(jt,{store:this.store,customStyles:n,children:(0,z.jsx)(Kt,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(Zp,{inputElement:e})})}),S),(0,we.render)((0,z.jsx)(jt,{store:this.store,customStyles:n,children:(0,z.jsx)(Kt,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(Ip,{})})}),H)}(0,we.render)((0,z.jsx)(jt,{store:this.store,customStyles:n,children:(0,z.jsx)(Kt,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(gp,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",S=>{clearTimeout(b),S===null?b=setTimeout(()=>{S!==null&&this.store.dispatch(Pr(S))},500):this.store.dispatch(Pr(S))}),this.inputMediator.on("disabled",()=>{var S;(S=this.inputMediator)==null||S.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{u&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(ho(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(ho(!0))),this.store.dispatch(Fa({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(Ue()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var S;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((S=this.state.conversation.current)==null?void 0:S.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(o=>o()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,o={}){if(this.widgetRoot&&k.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:n,showImages:s,showPersonalCollectionLink:r,isEmbedded:i}=o;this.widgetRoot=e,this.configure({showImages:s,showPersonalCollectionLink:r,isEmbedded:i}),(0,we.render)((0,z.jsx)(jt,{store:this.store,customStyles:n,children:(0,z.jsx)(Kt,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(qd,{})})}),e),this.whenConversationLoaded(()=>{var a;this.broadcastEvents.setSessionId((a=this.state.conversation.current)==null?void 0:a.sessionId)})}unmountWidget(){this.widgetRoot&&(0,we.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=yr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){du(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(pn());let e=wo(this.state);e&&this.store.dispatch(Do({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:e.knowledgeAssistForAgents,recommendTextSuggestions:e.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async loginViaPopup(){return new Promise((e,o)=>{let n=this.state.settings.adminUrl,s=new MessageChannel,r=s.port1,i=new URL(`${n}/platform/sso/`);i.searchParams.append("redirect","/sdk/popup/close.html");let a=!1,l=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};r.onmessage=async u=>{var g,f;if((g=u.data)!=null&&g.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((f=u.data)==null?void 0:f.jwt),this.broadcastEvents.send(tn),l(),a=!0,s.port1.close(),e()}catch(m){o(m)}};let c=window.open(i.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&o(new Error("Popup blocked by browser"));let p=async u=>{var g;if(u.origin===i.origin)switch((g=u.data)==null?void 0:g.type){case"deepdesk-popup-loaded":{c==null||c.postMessage({type:"deepdesk-popup-create-channel"},i.origin,[s.port2]);break}case"deepdesk-popup-error":{l(),u.data.message==="Timeout"&&k.warn("Popup timed out. Check if the account's platform url is configured correctly."),o(new Error(u.data.message));break}}};window.addEventListener("message",p);let d=setInterval(()=>{c&&!c.closed||(l(),a||o(new Error("Popup closed by user")))},200);this.unmountHandlers.push(l)})}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(k.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(o){let{message:n}=o;k.info(n),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let o=Fs(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(Ae()):this.store.dispatch(We(n))})}catch(n){this.handleError(n)}}};async function xu(t,e,o={}){let{value:n}=t,{start:s,end:r}=o.replace??{start:0,end:n.length},i=`${n.slice(0,s)}${e}${n.slice(r)}`,a=o.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function bu(t,e,o={}){let n=o.replace?wt(t,o.replace.start,o.replace.end):Po(t),s,r=()=>{if(o.setRange)return o.setRange(n.cloneRange());n.deleteContents(),s=document.createElement("span"),n.insertNode(s),o.insertBRs!==!1?e.split(`
10
10
  `).reverse().forEach((i,a)=>{a>0&&n.insertNode(document.createElement("br")),n.insertNode(document.createTextNode(i))}):n.insertNode(document.createTextNode(e))};return Promise.resolve(r()).then(()=>{try{if(o.selectionAfter!==!1){t.focus();let i=o.selectionAfter?wt(t,o.selectionAfter.start,o.selectionAfter.end):(n.collapse(!1),n),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(i)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}async function Cu(t,e){let o;t.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0}));let n=()=>{let s=t.ownerDocument.defaultView??window,r=s.getSelection();if((!r||r.rangeCount===0)&&(t.focus(),r=s.getSelection()),!r||r.rangeCount===0)return;let i=r.getRangeAt(0);i&&(i.deleteContents(),o=document.createElement("span"),i.insertNode(o),e.split(`
11
11
  `).reverse().forEach((a,l)=>{l>0&&i.insertNode(document.createElement("br")),i.insertNode(document.createTextNode(a))}),i.collapse(!1))};return Promise.resolve(n()).then(()=>{if(t.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0})),t.focus(),!!o)try{o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function wu(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function Tu(t,e,o){await new it(t).authenticateWithKey(e,o)}async function Eu(t){let o=await new Me(t).get("/platform/config/",{version:null});return A(o)}async function ah(t){let o=await(t.fetch??window.fetch)(t.url),n=await o.blob();return new File([n],t.name,{type:t.mimeType??o.headers.get("Content-Type")??"image/jpeg"})}async function ku(t,e){let o=await ah(e),n=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[o]}),t.dispatchEvent(n)}finally{Object.hasOwn(t,"files")&&delete t.files}}0&&(module.exports={Card,ContentEditableInput,DeepdeskAPI,DeepdeskSDK,HTTPClient,InputMediator,InputType,KeyboardHint,Label,Locale,Section,SectionList,Sources,Suggestion,SuggestionList,TextAreaInput,ToggleButton,attachFile,authenticateWithKey,createFullRange,createOverlayContainer,createRangeFromOffsets,escapeHTML,fetchPlatformConfig,formatTextMarkup,getRangeOffsets,getRangeText,insertCKEditor,isSupportedInputElement,updateContentEditable,updateTextArea,useStyles,waitForElementVisibilityChange});
package/dist/index.esm.js CHANGED
@@ -6,6 +6,6 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
6
6
  c-17.9,17.9-27.3,40.1-27.3,65.7C163.4,163,163.4,233,163.4,233z M465.5,267.9V477c0,9.4-3.4,17.9-10.2,24.7
7
7
  c-6.8,6.8-15.4,10.2-24.7,10.2h-349c-9.4,0-17.9-3.4-24.7-10.2c-6.8-6.8-10.2-15.4-10.2-24.7V267.9c0-9.4,3.4-17.9,10.2-24.7
8
8
  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
9
- 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`})})});import{jsx as od}from"react/jsx-runtime";var xv={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},nd=({className:t,color:e})=>od("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:od("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:xv[e||"pink"]})});var sd={root:"_root_bgd7a_1",text:"_text_bgd7a_18",icon:"_icon_bgd7a_33",logo:"_logo_bgd7a_38",lock:"_lock_bgd7a_43"};var ti={};j(ti,{enUS:()=>bv,nlNL:()=>Cv});var bv={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:0,value:"Search"}]},Cv={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:0,value:"Zoek"}]};import{useDispatch as Tv}from"react-redux";import{jsx as oi,jsxs as rd}from"react/jsx-runtime";var id=()=>{let t=w(ti),e=C("productName"),o=C("adminUrl"),n=Tv(),s=wv(oe),r=y("FloatingMenu",sd);if(s===null)return null;let i=()=>{s===!0?n(G(!0)):window.open(o,"_blank")};return rd("button",{className:r.root,onClick:i,children:[oi("div",{className:r.text,children:s?t("search"):t("signin",{productName:e})}),rd("div",{className:r.icon,children:[oi(nd,{className:r.logo,color:"pink"}),s===!1&&oi(td,{className:r.lock})]})]})};import{jsx as K}from"react/jsx-runtime";var ad=Yp("showTabHint",!0),os=class t{static version="10.6.2-beta.5";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:l}){let c=e.replace(/\/api$/,"");this.deepdeskApi=new Ue(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Xp({emit:(d,u,g)=>this.emit(d,u,g),handleAfterSendMessage:d=>this.handleAfterSendMessage(d),handleInputChanged:d=>this.handleInputChanged(d),handleKeyDown:d=>this.handleKeyDown(d),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:d=>this.logSendMessage(d),logSendEditSuggestionMessage:d=>this.logSendEditMessage(d),onUpdateShowTabHint:d=>ad.update(d),sendEvent:(d,u)=>this.deepdeskApi.sendEvent(d,u)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new _o(o)}),this.store=$p(p),this.broadcastEvents=new Dp({debug:!0,deepdeskUrl:c,eventMap:Cl(this.store),createCustomChannel:l}),this.store.dispatch(jt),this.store.dispatch(oo(ad.value())),this.store.dispatch(jt({locale:s,adminUrl:c,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(E.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(E.warn("Profile has not been loaded (yet)"),!0):(E.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Et(null)),this.store.dispatch(Ce()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();oe(n)&&hl(n)!=="loading"&&e()});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(Ce())).payload}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(o){E.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(vs({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Po(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Ao({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Ss(e))).payload}async postMessages(e){return(await this.store.dispatch(Mo(e))).payload}async updateConversation(e){return(await this.store.dispatch(Lo(e))).payload}resetConversation(){this.store.dispatch(R()),this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Te());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(jt(e))}setVisitorInfo(e){this.store.dispatch(Aa(e))}async setAgentInfo(e){await this.store.dispatch(Jt(e))}async setAgentSettings(e){await this.store.dispatch(Ys(e))}async getAgentSettings(){return(await this.store.dispatch(er())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(Sn()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Fo(e))}notifyKeyDown(e){this.store.dispatch(Ho(e))}notifyPaste(e,o){this.store.dispatch(Ii({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(ki(e))}notifyExternalSuggestion(e){this.store.dispatch(ie(e)),this.store.dispatch(ve())}notifyEditSuggestion(e){this.store.dispatch(ol(e.contentType,e.suggestions)),this.store.dispatch(be({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(Be({collapse:!1})),this.inputMediator&&this.store.dispatch(xi({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(de([])))}handleKeyDown(e){let{overlayCollapsed:o}=this.state.ui,{textSuggestions:n,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=n.length>0,l=s!==-1;if(this.store.dispatch(Ri(Oo(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(wi()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{if(o||!a||!r||e.shiftKey)return;this.store.dispatch(Ei());let{selectedSuggestionIndex:d}=this.state.input;e.preventDefault(),!i&&(d===-1?this.store.dispatch(qt()):this.stageSelectedSuggestion({inputType:"arrow"}))};switch(e.key){case"Up":case"ArrowUp":i?p():c();return;case"Down":case"ArrowDown":{i?c():p();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(Me(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Me(-1)),this.store.dispatch(qt()),e.preventDefault()):o||(this.store.dispatch(Be({collapse:!0})),this.store.dispatch(dl(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:d}=this.state.input,u=d.text.substring(0,d.selection.end),{tabCompletionSuggestion:g}=this.state.input;this.store.dispatch(oo(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&g&&g.text.startsWith(u)&&(this.store.dispatch(ie({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(ve())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Pi()),this.store.dispatch(de([]))}handlingTimeStart(){this.state.handlingTime.startTime||(E.info("Start handling time"),this.store.dispatch(Fp()))}handlingTimeStop(){this.state.handlingTime.startTime&&(E.info("Stop handling time"),this.store.dispatch(Yn()))}logSendMessage(e){let o=Qr("input",this.state,{version:this.version});e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logSendEditMessage(e){let o=Qr("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Ci(this.state.overlayInput.metrics))}logHandlingTime(){let e=Qp(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Kp())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(ve()),this.store.dispatch(We(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(ie({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){E.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),E.error(i)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=_t(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{ts(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=_t(r,{appendTo:document.body});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{ts(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return $e(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{ts(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),E.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(E.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Li(n.metrics))):E.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch{}}mount(e,o={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Jr(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:n={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,isEmbedded:d,detectSubmit:u,insertLink:g,inputMediator:f,closestScrollSelector:m,appendOverlayTo:v,inlineSuggestions:T,floatingMenu:h}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:g,isEmbedded:d,inlineSuggestions:T,floatingMenu:h}),o.automaticHandlingTime&&this.setupHandlingTime(e),$e(e),this.inputMediator=f||(Fe(e)?new Oe(e):new Ht(e)),this.inputMediator.on("change",({plainText:S})=>{this.notifyInputChanged(S)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Ai({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",S=>{this.notifyKeyDown(S)}),this.inputMediator.on("paste",({pastedText:S,selectionText:O})=>{this.notifyPaste(S,O)}),this.inputMediator.on("cut",({selectionText:S})=>{this.notifyCut(S)});let x=m&&Zp(e,m)||void 0;if(T){let{customStyles:S,appendOverlayTo:O}=o;if(Fe(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let M=this.createInlineContainer(e,"deepdesk-caret");Kt(K(et,{store:this.store,customStyles:S,children:K(Ye,{broadcastEvents:this.broadcastEvents,children:K(dc,{})})}),M),this.inputMediator.on("caret",D=>{this.store.dispatch(de([])),D?(M.style.display="block",M.style.top=`${D.top}px`,M.style.left=`${D.left}px`):M.style.display="none"});let W=this.overlayContainerFactory("floating-menu",x||e,{appendTo:O});Kt(K(et,{store:this.store,customStyles:S,children:K(Ye,{broadcastEvents:this.broadcastEvents,children:K(id,{})})}),W)}else{let S=this.overlayContainerFactory("deepdesk-tab-completion",x||e,{appendTo:v,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),O=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:v},n==null?void 0:n.suggestionsRootNode);Kt(K(et,{store:this.store,customStyles:n,children:K(Ye,{broadcastEvents:this.broadcastEvents,children:K(Uc,{inputElement:e})})}),S),Kt(K(et,{store:this.store,customStyles:n,children:K(Ye,{broadcastEvents:this.broadcastEvents,children:K(_c,{})})}),O)}Kt(K(et,{store:this.store,customStyles:n,children:K(Ye,{broadcastEvents:this.broadcastEvents,children:K(rc,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",S=>{clearTimeout(b),S===null?b=setTimeout(()=>{S!==null&&this.store.dispatch(xs(S))},500):this.store.dispatch(xs(S))}),this.inputMediator.on("disabled",()=>{var S;(S=this.inputMediator)==null||S.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{u&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Tt(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Tt(!0))),this.store.dispatch(bi({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(ve()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var S;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((S=this.state.conversation.current)==null?void 0:S.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(o=>o()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,o={}){if(this.widgetRoot&&E.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:n,showImages:s,showPersonalCollectionLink:r,isEmbedded:i}=o;this.widgetRoot=e,this.configure({showImages:s,showPersonalCollectionLink:r,isEmbedded:i}),Kt(K(et,{store:this.store,customStyles:n,children:K(Ye,{broadcastEvents:this.broadcastEvents,children:K(Lp,{})})}),e),this.whenConversationLoaded(()=>{var a;this.broadcastEvents.setSessionId((a=this.state.conversation.current)==null?void 0:a.sessionId)})}unmountWidget(){this.widgetRoot&&ts(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=Yr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Jp(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(lo());let e=At(this.state);e&&this.store.dispatch(jt({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:e.knowledgeAssistForAgents,recommendTextSuggestions:e.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async loginViaPopup(){return new Promise((e,o)=>{let n=this.state.settings.adminUrl,s=new MessageChannel,r=s.port1,i=new URL(`${n}/platform/sso/`);i.searchParams.append("redirect","/sdk/popup/close.html");let a=!1,l=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};r.onmessage=async u=>{var g,f;if((g=u.data)!=null&&g.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((f=u.data)==null?void 0:f.jwt),this.broadcastEvents.send(so),l(),a=!0,s.port1.close(),e()}catch(m){o(m)}};let c=window.open(i.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&o(new Error("Popup blocked by browser"));let p=async u=>{var g;if(u.origin===i.origin)switch((g=u.data)==null?void 0:g.type){case"deepdesk-popup-loaded":{c==null||c.postMessage({type:"deepdesk-popup-create-channel"},i.origin,[s.port2]);break}case"deepdesk-popup-error":{l(),u.data.message==="Timeout"&&E.warn("Popup timed out. Check if the account's platform url is configured correctly."),o(new Error(u.data.message));break}}};window.addEventListener("message",p);let d=setInterval(()=>{c&&!c.closed||(l(),a||o(new Error("Popup closed by user")))},200);this.unmountHandlers.push(l)})}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(E.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(o){let{message:n}=o;E.info(n),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let o=Tn(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(ce()):this.store.dispatch(xe(n))})}catch(n){this.handleError(n)}}};async function Ev(t,e,o={}){let{value:n}=t,{start:s,end:r}=o.replace??{start:0,end:n.length},i=`${n.slice(0,s)}${e}${n.slice(r)}`,a=o.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function kv(t,e,o={}){let n=o.replace?st(t,o.replace.start,o.replace.end):vo(t),s,r=()=>{if(o.setRange)return o.setRange(n.cloneRange());n.deleteContents(),s=document.createElement("span"),n.insertNode(s),o.insertBRs!==!1?e.split(`
9
+ 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`})})});import{jsx as od}from"react/jsx-runtime";var xv={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},nd=({className:t,color:e})=>od("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:od("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:xv[e||"pink"]})});var sd={root:"_root_bgd7a_1",text:"_text_bgd7a_18",icon:"_icon_bgd7a_33",logo:"_logo_bgd7a_38",lock:"_lock_bgd7a_43"};var ti={};j(ti,{enUS:()=>bv,nlNL:()=>Cv});var bv={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:0,value:"Search"}]},Cv={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:0,value:"Zoek"}]};import{useDispatch as Tv}from"react-redux";import{jsx as oi,jsxs as rd}from"react/jsx-runtime";var id=()=>{let t=w(ti),e=C("productName"),o=C("adminUrl"),n=Tv(),s=wv(oe),r=y("FloatingMenu",sd);if(s===null)return null;let i=()=>{s===!0?n(G(!0)):window.open(o,"_blank")};return rd("button",{className:r.root,onClick:i,children:[oi("div",{className:r.text,children:s?t("search"):t("signin",{productName:e})}),rd("div",{className:r.icon,children:[oi(nd,{className:r.logo,color:"pink"}),s===!1&&oi(td,{className:r.lock})]})]})};import{jsx as K}from"react/jsx-runtime";var ad=Yp("showTabHint",!0),os=class t{static version="10.7.0";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:l}){let c=e.replace(/\/api$/,"");this.deepdeskApi=new Ue(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Xp({emit:(d,u,g)=>this.emit(d,u,g),handleAfterSendMessage:d=>this.handleAfterSendMessage(d),handleInputChanged:d=>this.handleInputChanged(d),handleKeyDown:d=>this.handleKeyDown(d),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:d=>this.logSendMessage(d),logSendEditSuggestionMessage:d=>this.logSendEditMessage(d),onUpdateShowTabHint:d=>ad.update(d),sendEvent:(d,u)=>this.deepdeskApi.sendEvent(d,u)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new _o(o)}),this.store=$p(p),this.broadcastEvents=new Dp({debug:!0,deepdeskUrl:c,eventMap:Cl(this.store),createCustomChannel:l}),this.store.dispatch(jt),this.store.dispatch(oo(ad.value())),this.store.dispatch(jt({locale:s,adminUrl:c,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(E.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(E.warn("Profile has not been loaded (yet)"),!0):(E.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Et(null)),this.store.dispatch(Ce()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();oe(n)&&hl(n)!=="loading"&&e()});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(Ce())).payload}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(o){E.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(vs({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Po(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Ao({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Ss(e))).payload}async postMessages(e){return(await this.store.dispatch(Mo(e))).payload}async updateConversation(e){return(await this.store.dispatch(Lo(e))).payload}resetConversation(){this.store.dispatch(R()),this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Te());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(jt(e))}setVisitorInfo(e){this.store.dispatch(Aa(e))}async setAgentInfo(e){await this.store.dispatch(Jt(e))}async setAgentSettings(e){await this.store.dispatch(Ys(e))}async getAgentSettings(){return(await this.store.dispatch(er())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(Sn()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Fo(e))}notifyKeyDown(e){this.store.dispatch(Ho(e))}notifyPaste(e,o){this.store.dispatch(Ii({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(ki(e))}notifyExternalSuggestion(e){this.store.dispatch(ie(e)),this.store.dispatch(ve())}notifyEditSuggestion(e){this.store.dispatch(ol(e.contentType,e.suggestions)),this.store.dispatch(be({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(Be({collapse:!1})),this.inputMediator&&this.store.dispatch(xi({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(de([])))}handleKeyDown(e){let{overlayCollapsed:o}=this.state.ui,{textSuggestions:n,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=n.length>0,l=s!==-1;if(this.store.dispatch(Ri(Oo(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(wi()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{if(o||!a||!r||e.shiftKey)return;this.store.dispatch(Ei());let{selectedSuggestionIndex:d}=this.state.input;e.preventDefault(),!i&&(d===-1?this.store.dispatch(qt()):this.stageSelectedSuggestion({inputType:"arrow"}))};switch(e.key){case"Up":case"ArrowUp":i?p():c();return;case"Down":case"ArrowDown":{i?c():p();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(Me(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Me(-1)),this.store.dispatch(qt()),e.preventDefault()):o||(this.store.dispatch(Be({collapse:!0})),this.store.dispatch(dl(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:d}=this.state.input,u=d.text.substring(0,d.selection.end),{tabCompletionSuggestion:g}=this.state.input;this.store.dispatch(oo(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&g&&g.text.startsWith(u)&&(this.store.dispatch(ie({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(ve())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Pi()),this.store.dispatch(de([]))}handlingTimeStart(){this.state.handlingTime.startTime||(E.info("Start handling time"),this.store.dispatch(Fp()))}handlingTimeStop(){this.state.handlingTime.startTime&&(E.info("Stop handling time"),this.store.dispatch(Yn()))}logSendMessage(e){let o=Qr("input",this.state,{version:this.version});e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logSendEditMessage(e){let o=Qr("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Ci(this.state.overlayInput.metrics))}logHandlingTime(){let e=Qp(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Kp())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(ve()),this.store.dispatch(We(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(ie({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){E.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),E.error(i)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=_t(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{ts(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=_t(r,{appendTo:document.body});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{ts(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return $e(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{ts(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),E.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(E.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Li(n.metrics))):E.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch{}}mount(e,o={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Jr(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:n={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,isEmbedded:d,detectSubmit:u,insertLink:g,inputMediator:f,closestScrollSelector:m,appendOverlayTo:v,inlineSuggestions:T,floatingMenu:h}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:g,isEmbedded:d,inlineSuggestions:T,floatingMenu:h}),o.automaticHandlingTime&&this.setupHandlingTime(e),$e(e),this.inputMediator=f||(Fe(e)?new Oe(e):new Ht(e)),this.inputMediator.on("change",({plainText:S})=>{this.notifyInputChanged(S)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Ai({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",S=>{this.notifyKeyDown(S)}),this.inputMediator.on("paste",({pastedText:S,selectionText:O})=>{this.notifyPaste(S,O)}),this.inputMediator.on("cut",({selectionText:S})=>{this.notifyCut(S)});let x=m&&Zp(e,m)||void 0;if(T){let{customStyles:S,appendOverlayTo:O}=o;if(Fe(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let M=this.createInlineContainer(e,"deepdesk-caret");Kt(K(et,{store:this.store,customStyles:S,children:K(Ye,{broadcastEvents:this.broadcastEvents,children:K(dc,{})})}),M),this.inputMediator.on("caret",D=>{this.store.dispatch(de([])),D?(M.style.display="block",M.style.top=`${D.top}px`,M.style.left=`${D.left}px`):M.style.display="none"});let W=this.overlayContainerFactory("floating-menu",x||e,{appendTo:O});Kt(K(et,{store:this.store,customStyles:S,children:K(Ye,{broadcastEvents:this.broadcastEvents,children:K(id,{})})}),W)}else{let S=this.overlayContainerFactory("deepdesk-tab-completion",x||e,{appendTo:v,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),O=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:v},n==null?void 0:n.suggestionsRootNode);Kt(K(et,{store:this.store,customStyles:n,children:K(Ye,{broadcastEvents:this.broadcastEvents,children:K(Uc,{inputElement:e})})}),S),Kt(K(et,{store:this.store,customStyles:n,children:K(Ye,{broadcastEvents:this.broadcastEvents,children:K(_c,{})})}),O)}Kt(K(et,{store:this.store,customStyles:n,children:K(Ye,{broadcastEvents:this.broadcastEvents,children:K(rc,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",S=>{clearTimeout(b),S===null?b=setTimeout(()=>{S!==null&&this.store.dispatch(xs(S))},500):this.store.dispatch(xs(S))}),this.inputMediator.on("disabled",()=>{var S;(S=this.inputMediator)==null||S.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{u&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Tt(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Tt(!0))),this.store.dispatch(bi({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(ve()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var S;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((S=this.state.conversation.current)==null?void 0:S.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(o=>o()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,o={}){if(this.widgetRoot&&E.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:n,showImages:s,showPersonalCollectionLink:r,isEmbedded:i}=o;this.widgetRoot=e,this.configure({showImages:s,showPersonalCollectionLink:r,isEmbedded:i}),Kt(K(et,{store:this.store,customStyles:n,children:K(Ye,{broadcastEvents:this.broadcastEvents,children:K(Lp,{})})}),e),this.whenConversationLoaded(()=>{var a;this.broadcastEvents.setSessionId((a=this.state.conversation.current)==null?void 0:a.sessionId)})}unmountWidget(){this.widgetRoot&&ts(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=Yr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Jp(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(lo());let e=At(this.state);e&&this.store.dispatch(jt({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:e.knowledgeAssistForAgents,recommendTextSuggestions:e.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async loginViaPopup(){return new Promise((e,o)=>{let n=this.state.settings.adminUrl,s=new MessageChannel,r=s.port1,i=new URL(`${n}/platform/sso/`);i.searchParams.append("redirect","/sdk/popup/close.html");let a=!1,l=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};r.onmessage=async u=>{var g,f;if((g=u.data)!=null&&g.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((f=u.data)==null?void 0:f.jwt),this.broadcastEvents.send(so),l(),a=!0,s.port1.close(),e()}catch(m){o(m)}};let c=window.open(i.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&o(new Error("Popup blocked by browser"));let p=async u=>{var g;if(u.origin===i.origin)switch((g=u.data)==null?void 0:g.type){case"deepdesk-popup-loaded":{c==null||c.postMessage({type:"deepdesk-popup-create-channel"},i.origin,[s.port2]);break}case"deepdesk-popup-error":{l(),u.data.message==="Timeout"&&E.warn("Popup timed out. Check if the account's platform url is configured correctly."),o(new Error(u.data.message));break}}};window.addEventListener("message",p);let d=setInterval(()=>{c&&!c.closed||(l(),a||o(new Error("Popup closed by user")))},200);this.unmountHandlers.push(l)})}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(E.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(o){let{message:n}=o;E.info(n),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let o=Tn(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(ce()):this.store.dispatch(xe(n))})}catch(n){this.handleError(n)}}};async function Ev(t,e,o={}){let{value:n}=t,{start:s,end:r}=o.replace??{start:0,end:n.length},i=`${n.slice(0,s)}${e}${n.slice(r)}`,a=o.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function kv(t,e,o={}){let n=o.replace?st(t,o.replace.start,o.replace.end):vo(t),s,r=()=>{if(o.setRange)return o.setRange(n.cloneRange());n.deleteContents(),s=document.createElement("span"),n.insertNode(s),o.insertBRs!==!1?e.split(`
10
10
  `).reverse().forEach((i,a)=>{a>0&&n.insertNode(document.createElement("br")),n.insertNode(document.createTextNode(i))}):n.insertNode(document.createTextNode(e))};return Promise.resolve(r()).then(()=>{try{if(o.selectionAfter!==!1){t.focus();let i=o.selectionAfter?st(t,o.selectionAfter.start,o.selectionAfter.end):(n.collapse(!1),n),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(i)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}async function Rv(t,e){let o;t.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0}));let n=()=>{let s=t.ownerDocument.defaultView??window,r=s.getSelection();if((!r||r.rangeCount===0)&&(t.focus(),r=s.getSelection()),!r||r.rangeCount===0)return;let i=r.getRangeAt(0);i&&(i.deleteContents(),o=document.createElement("span"),i.insertNode(o),e.split(`
11
11
  `).reverse().forEach((a,l)=>{l>0&&i.insertNode(document.createElement("br")),i.insertNode(document.createTextNode(a))}),i.collapse(!1))};return Promise.resolve(n()).then(()=>{if(t.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0})),t.focus(),!!o)try{o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function Iv(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function Pv(t,e,o){await new Ue(t).authenticateWithKey(e,o)}async function Av(t){let o=await new he(t).get("/platform/config/",{version:null});return I(o)}async function Lv(t){let o=await(t.fetch??window.fetch)(t.url),n=await o.blob();return new File([n],t.name,{type:t.mimeType??o.headers.get("Content-Type")??"image/jpeg"})}async function Mv(t,e){let o=await Lv(e),n=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[o]}),t.dispatchEvent(n)}finally{Object.hasOwn(t,"files")&&delete t.files}}export{B as Card,Ht as ContentEditableInput,Ue as DeepdeskAPI,os as DeepdeskSDK,he as HTTPClient,Ne as InputMediator,qe as InputType,cs as KeyboardHint,ps as Label,ko as Locale,je as Section,us as SectionList,pe as Sources,N as Suggestion,re as SuggestionList,Oe as TextAreaInput,dt as ToggleButton,Mv as attachFile,Pv as authenticateWithKey,vo as createFullRange,_t as createOverlayContainer,st as createRangeFromOffsets,Xt as escapeHTML,Av as fetchPlatformConfig,Iv as formatTextMarkup,Qn as getRangeOffsets,Zn as getRangeText,Rv as insertCKEditor,Jr as isSupportedInputElement,kv as updateContentEditable,Ev as updateTextArea,y as useStyles,Yr as waitForElementVisibilityChange};
@@ -22,7 +22,7 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
22
22
  c-17.9,17.9-27.3,40.1-27.3,65.7C163.4,163,163.4,233,163.4,233z M465.5,267.9V477c0,9.4-3.4,17.9-10.2,24.7
23
23
  c-6.8,6.8-15.4,10.2-24.7,10.2h-349c-9.4,0-17.9-3.4-24.7-10.2c-6.8-6.8-10.2-15.4-10.2-24.7V267.9c0-9.4,3.4-17.9,10.2-24.7
24
24
  c6.8-6.8,15.4-10.2,24.7-10.2h11.9v-70c0-44.4,16.2-82.8,47.8-115.2S212.1,0,256.4,0s82.8,16.2,115.2,47.8
25
- 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 Ah=S(w()),pA={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},yE=({className:e,color:t})=>(0,Ah.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,Ah.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:pA[t||"pink"]})});var vE={root:"_root_bgd7a_1",text:"_text_bgd7a_18",icon:"_icon_bgd7a_33",logo:"_logo_bgd7a_38",lock:"_lock_bgd7a_43"};var Oh={};Te(Oh,{enUS:()=>fA,nlNL:()=>mA});var fA={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:0,value:"Search"}]},mA={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:0,value:"Zoek"}]};var So=S(w()),SE=()=>{let e=j(Oh),t=M("productName"),n=M("adminUrl"),r=z(),o=I(dt),i=k("FloatingMenu",vE);if(o===null)return null;let s=()=>{o===!0?r($e(!0)):window.open(n,"_blank")};return(0,So.jsxs)("button",{className:i.root,onClick:s,children:[(0,So.jsx)("div",{className:i.text,children:o?e("search"):e("signin",{productName:t})}),(0,So.jsxs)("div",{className:i.icon,children:[(0,So.jsx)(yE,{className:i.logo,color:"pink"}),o===!1&&(0,So.jsx)(hE,{className:i.lock})]})]})};var _e=S(w());var xE=mE("showTabHint",!0),Va=class e{static version="10.6.2-beta.5";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new zn(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[cE({emit:(p,d,g)=>this.emit(p,d,g),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),logSendEditSuggestionMessage:p=>this.logSendEditMessage(p),onUpdateShowTabHint:p=>xE.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new za(n)}),this.store=uE(c),this.broadcastEvents=new Yb({debug:!0,deepdeskUrl:u,eventMap:Vw(this.store),createCustomChannel:l}),this.store.dispatch(na),this.store.dispatch(ba(xE.value())),this.store.dispatch(na({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(B.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(B.warn("Profile has not been loaded (yet)"),!0):(B.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Ii(null)),this.store.dispatch(An()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();dt(r)&&Dw(r)!=="loading"&&t()});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(An())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){B.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Gm({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(rc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(oc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Xm(t))).payload}async postMessages(t){return(await this.store.dispatch(sc(t))).payload}async updateConversation(t){return(await this.store.dispatch(ic(t))).payload}resetConversation(){this.store.dispatch(J()),this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(Nn());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(na(t))}setVisitorInfo(t){this.store.dispatch(tw(t))}async setAgentInfo(t){await this.store.dispatch(va(t))}async setAgentSettings(t){await this.store.dispatch(Ng(t))}async getAgentSettings(){return(await this.store.dispatch(Mg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(ed()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(pc(t))}notifyKeyDown(t){this.store.dispatch(cc(t))}notifyPaste(t,n){this.store.dispatch(r_({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(t_(t))}notifyExternalSuggestion(t){this.store.dispatch(Bt(t)),this.store.dispatch(wn())}notifyEditSuggestion(t){this.store.dispatch(ww(t.contentType,t.suggestions)),this.store.dispatch(Ln({contentType:t.contentType,suggestion:typeof t.index=="number"?t.suggestions[t.index]:null}))}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(Er({collapse:!1})),this.inputMediator&&this.store.dispatch(Xx({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(on([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(n_(lc(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(Zx()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{if(n||!a||!i||t.shiftKey)return;this.store.dispatch(e_());let{selectedSuggestionIndex:p}=this.state.input;t.preventDefault(),!s&&(p===-1?this.store.dispatch(oa()):this.stageSelectedSuggestion({inputType:"arrow"}))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(Sr(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Sr(-1)),this.store.dispatch(oa()),t.preventDefault()):n||(this.store.dispatch(Er({collapse:!0})),this.store.dispatch(Lw(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:g}=this.state.input;this.store.dispatch(ba(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&g&&g.text.startsWith(d)&&(this.store.dispatch(Bt({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(wn())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(o_()),this.store.dispatch(on([]))}handlingTimeStart(){this.state.handlingTime.startTime||(B.info("Start handling time"),this.store.dispatch(eE()))}handlingTimeStop(){this.state.handlingTime.startTime&&(B.info("Stop handling time"),this.store.dispatch(Id()))}logSendMessage(t){let n=Ih("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logSendEditMessage(t){let n=Ih("overlayInput",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.store.dispatch(Yx(this.state.overlayInput.metrics))}logHandlingTime(){let t=dE(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(tE())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(wn()),this.store.dispatch(Jr(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Bt({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){B.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),B.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=io(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,At.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=io(i,{appendTo:document.body});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,At.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return oo(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,At.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),B.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(B.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(s_(r.metrics))):B.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Ad(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:d,insertLink:g,inputMediator:v,closestScrollSelector:y,appendOverlayTo:m,inlineSuggestions:h,floatingMenu:f}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:g,isEmbedded:p,inlineSuggestions:h,floatingMenu:f}),n.automaticHandlingTime&&this.setupHandlingTime(t),oo(t),this.inputMediator=v||(kr(t)?new Pn(t):new yo(t)),this.inputMediator.on("change",({plainText:b})=>{this.notifyInputChanged(b)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(i_({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",b=>{this.notifyKeyDown(b)}),this.inputMediator.on("paste",({pastedText:b,selectionText:E})=>{this.notifyPaste(b,E)}),this.inputMediator.on("cut",({selectionText:b})=>{this.notifyCut(b)});let x=y&&pE(t,y)||void 0;if(h){let{customStyles:b,appendOverlayTo:E}=n;if(kr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let C=this.createInlineContainer(t,"deepdesk-caret");(0,At.render)((0,_e.jsx)(ho,{store:this.store,customStyles:b,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(O1,{})})}),C),this.inputMediator.on("caret",P=>{this.store.dispatch(on([])),P?(C.style.display="block",C.style.top=`${P.top}px`,C.style.left=`${P.left}px`):C.style.display="none"});let R=this.overlayContainerFactory("floating-menu",x||t,{appendTo:E});(0,At.render)((0,_e.jsx)(ho,{store:this.store,customStyles:b,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(SE,{})})}),R)}else{let b=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:m,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),E=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:m},r==null?void 0:r.suggestionsRootNode);(0,At.render)((0,_e.jsx)(ho,{store:this.store,customStyles:r,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(rb,{inputElement:t})})}),b),(0,At.render)((0,_e.jsx)(ho,{store:this.store,customStyles:r,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(U1,{})})}),E)}(0,At.render)((0,_e.jsx)(ho,{store:this.store,customStyles:r,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(k1,{})})}),this.createContainer("deepdesk-overlays"));let _;this.inputMediator.on("selection",b=>{clearTimeout(_),b===null?_=setTimeout(()=>{b!==null&&this.store.dispatch(Ym(b))},500):this.store.dispatch(Ym(b))}),this.inputMediator.on("disabled",()=>{var b;(b=this.inputMediator)==null||b.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Ri(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Ri(!0))),this.store.dispatch(Qx({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(wn()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var b;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((b=this.state.conversation.current)==null?void 0:b.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&B.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,showPersonalCollectionLink:i,isEmbedded:s}=n;this.widgetRoot=t,this.configure({showImages:o,showPersonalCollectionLink:i,isEmbedded:s}),(0,At.render)((0,_e.jsx)(ho,{store:this.store,customStyles:r,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(qb,{})})}),t),this.whenConversationLoaded(()=>{var a;this.broadcastEvents.setSessionId((a=this.state.conversation.current)==null?void 0:a.sessionId)})}unmountWidget(){this.widgetRoot&&(0,At.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Od(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){fE(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Aa());let t=Ni(this.state);t&&this.store.dispatch(na({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:t.knowledgeAssistForAgents,recommendTextSuggestions:t.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async loginViaPopup(){return new Promise((t,n)=>{let r=this.state.settings.adminUrl,o=new MessageChannel,i=o.port1,s=new URL(`${r}/platform/sso/`);s.searchParams.append("redirect","/sdk/popup/close.html");let a=!1,l=()=>{u&&!u.closed&&u.close(),window.removeEventListener("message",c),clearInterval(p)};i.onmessage=async d=>{var g,v;if((g=d.data)!=null&&g.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=d.data)==null?void 0:v.jwt),this.broadcastEvents.send(Ta),l(),a=!0,o.port1.close(),t()}catch(y){n(y)}};let u=window.open(s.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");u===null&&n(new Error("Popup blocked by browser"));let c=async d=>{var g;if(d.origin===s.origin)switch((g=d.data)==null?void 0:g.type){case"deepdesk-popup-loaded":{u==null||u.postMessage({type:"deepdesk-popup-create-channel"},s.origin,[o.port2]);break}case"deepdesk-popup-error":{l(),d.data.message==="Timeout"&&B.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(d.data.message));break}}};window.addEventListener("message",c);let p=setInterval(()=>{u&&!u.closed||(l(),a||n(new Error("Popup closed by user")))},200);this.unmountHandlers.push(l)})}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(B.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;B.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=od(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(Kt()):this.store.dispatch(In(r))})}catch(r){this.handleError(r)}}};async function _E(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function wE(e,t,n={}){let r=n.replace?Ir(e,n.replace.start,n.replace.end):Hi(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
25
+ c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});var Ah=S(w()),pA={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},yE=({className:e,color:t})=>(0,Ah.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,Ah.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:pA[t||"pink"]})});var vE={root:"_root_bgd7a_1",text:"_text_bgd7a_18",icon:"_icon_bgd7a_33",logo:"_logo_bgd7a_38",lock:"_lock_bgd7a_43"};var Oh={};Te(Oh,{enUS:()=>fA,nlNL:()=>mA});var fA={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:0,value:"Search"}]},mA={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:0,value:"Zoek"}]};var So=S(w()),SE=()=>{let e=j(Oh),t=M("productName"),n=M("adminUrl"),r=z(),o=I(dt),i=k("FloatingMenu",vE);if(o===null)return null;let s=()=>{o===!0?r($e(!0)):window.open(n,"_blank")};return(0,So.jsxs)("button",{className:i.root,onClick:s,children:[(0,So.jsx)("div",{className:i.text,children:o?e("search"):e("signin",{productName:t})}),(0,So.jsxs)("div",{className:i.icon,children:[(0,So.jsx)(yE,{className:i.logo,color:"pink"}),o===!1&&(0,So.jsx)(hE,{className:i.lock})]})]})};var _e=S(w());var xE=mE("showTabHint",!0),Va=class e{static version="10.7.0";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new zn(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[cE({emit:(p,d,g)=>this.emit(p,d,g),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),logSendEditSuggestionMessage:p=>this.logSendEditMessage(p),onUpdateShowTabHint:p=>xE.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new za(n)}),this.store=uE(c),this.broadcastEvents=new Yb({debug:!0,deepdeskUrl:u,eventMap:Vw(this.store),createCustomChannel:l}),this.store.dispatch(na),this.store.dispatch(ba(xE.value())),this.store.dispatch(na({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(B.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(B.warn("Profile has not been loaded (yet)"),!0):(B.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Ii(null)),this.store.dispatch(An()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();dt(r)&&Dw(r)!=="loading"&&t()});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(An())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){B.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Gm({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(rc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(oc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Xm(t))).payload}async postMessages(t){return(await this.store.dispatch(sc(t))).payload}async updateConversation(t){return(await this.store.dispatch(ic(t))).payload}resetConversation(){this.store.dispatch(J()),this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(Nn());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(na(t))}setVisitorInfo(t){this.store.dispatch(tw(t))}async setAgentInfo(t){await this.store.dispatch(va(t))}async setAgentSettings(t){await this.store.dispatch(Ng(t))}async getAgentSettings(){return(await this.store.dispatch(Mg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(ed()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(pc(t))}notifyKeyDown(t){this.store.dispatch(cc(t))}notifyPaste(t,n){this.store.dispatch(r_({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(t_(t))}notifyExternalSuggestion(t){this.store.dispatch(Bt(t)),this.store.dispatch(wn())}notifyEditSuggestion(t){this.store.dispatch(ww(t.contentType,t.suggestions)),this.store.dispatch(Ln({contentType:t.contentType,suggestion:typeof t.index=="number"?t.suggestions[t.index]:null}))}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(Er({collapse:!1})),this.inputMediator&&this.store.dispatch(Xx({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(on([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(n_(lc(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(Zx()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{if(n||!a||!i||t.shiftKey)return;this.store.dispatch(e_());let{selectedSuggestionIndex:p}=this.state.input;t.preventDefault(),!s&&(p===-1?this.store.dispatch(oa()):this.stageSelectedSuggestion({inputType:"arrow"}))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(Sr(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Sr(-1)),this.store.dispatch(oa()),t.preventDefault()):n||(this.store.dispatch(Er({collapse:!0})),this.store.dispatch(Lw(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:g}=this.state.input;this.store.dispatch(ba(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&g&&g.text.startsWith(d)&&(this.store.dispatch(Bt({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(wn())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(o_()),this.store.dispatch(on([]))}handlingTimeStart(){this.state.handlingTime.startTime||(B.info("Start handling time"),this.store.dispatch(eE()))}handlingTimeStop(){this.state.handlingTime.startTime&&(B.info("Stop handling time"),this.store.dispatch(Id()))}logSendMessage(t){let n=Ih("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logSendEditMessage(t){let n=Ih("overlayInput",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.store.dispatch(Yx(this.state.overlayInput.metrics))}logHandlingTime(){let t=dE(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(tE())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(wn()),this.store.dispatch(Jr(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Bt({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){B.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),B.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=io(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,At.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=io(i,{appendTo:document.body});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,At.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return oo(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,At.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),B.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(B.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(s_(r.metrics))):B.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Ad(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:d,insertLink:g,inputMediator:v,closestScrollSelector:y,appendOverlayTo:m,inlineSuggestions:h,floatingMenu:f}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:g,isEmbedded:p,inlineSuggestions:h,floatingMenu:f}),n.automaticHandlingTime&&this.setupHandlingTime(t),oo(t),this.inputMediator=v||(kr(t)?new Pn(t):new yo(t)),this.inputMediator.on("change",({plainText:b})=>{this.notifyInputChanged(b)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(i_({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",b=>{this.notifyKeyDown(b)}),this.inputMediator.on("paste",({pastedText:b,selectionText:E})=>{this.notifyPaste(b,E)}),this.inputMediator.on("cut",({selectionText:b})=>{this.notifyCut(b)});let x=y&&pE(t,y)||void 0;if(h){let{customStyles:b,appendOverlayTo:E}=n;if(kr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let C=this.createInlineContainer(t,"deepdesk-caret");(0,At.render)((0,_e.jsx)(ho,{store:this.store,customStyles:b,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(O1,{})})}),C),this.inputMediator.on("caret",P=>{this.store.dispatch(on([])),P?(C.style.display="block",C.style.top=`${P.top}px`,C.style.left=`${P.left}px`):C.style.display="none"});let R=this.overlayContainerFactory("floating-menu",x||t,{appendTo:E});(0,At.render)((0,_e.jsx)(ho,{store:this.store,customStyles:b,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(SE,{})})}),R)}else{let b=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:m,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),E=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:m},r==null?void 0:r.suggestionsRootNode);(0,At.render)((0,_e.jsx)(ho,{store:this.store,customStyles:r,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(rb,{inputElement:t})})}),b),(0,At.render)((0,_e.jsx)(ho,{store:this.store,customStyles:r,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(U1,{})})}),E)}(0,At.render)((0,_e.jsx)(ho,{store:this.store,customStyles:r,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(k1,{})})}),this.createContainer("deepdesk-overlays"));let _;this.inputMediator.on("selection",b=>{clearTimeout(_),b===null?_=setTimeout(()=>{b!==null&&this.store.dispatch(Ym(b))},500):this.store.dispatch(Ym(b))}),this.inputMediator.on("disabled",()=>{var b;(b=this.inputMediator)==null||b.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Ri(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Ri(!0))),this.store.dispatch(Qx({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(wn()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var b;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((b=this.state.conversation.current)==null?void 0:b.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&B.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,showPersonalCollectionLink:i,isEmbedded:s}=n;this.widgetRoot=t,this.configure({showImages:o,showPersonalCollectionLink:i,isEmbedded:s}),(0,At.render)((0,_e.jsx)(ho,{store:this.store,customStyles:r,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(qb,{})})}),t),this.whenConversationLoaded(()=>{var a;this.broadcastEvents.setSessionId((a=this.state.conversation.current)==null?void 0:a.sessionId)})}unmountWidget(){this.widgetRoot&&(0,At.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Od(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){fE(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Aa());let t=Ni(this.state);t&&this.store.dispatch(na({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:t.knowledgeAssistForAgents,recommendTextSuggestions:t.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async loginViaPopup(){return new Promise((t,n)=>{let r=this.state.settings.adminUrl,o=new MessageChannel,i=o.port1,s=new URL(`${r}/platform/sso/`);s.searchParams.append("redirect","/sdk/popup/close.html");let a=!1,l=()=>{u&&!u.closed&&u.close(),window.removeEventListener("message",c),clearInterval(p)};i.onmessage=async d=>{var g,v;if((g=d.data)!=null&&g.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=d.data)==null?void 0:v.jwt),this.broadcastEvents.send(Ta),l(),a=!0,o.port1.close(),t()}catch(y){n(y)}};let u=window.open(s.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");u===null&&n(new Error("Popup blocked by browser"));let c=async d=>{var g;if(d.origin===s.origin)switch((g=d.data)==null?void 0:g.type){case"deepdesk-popup-loaded":{u==null||u.postMessage({type:"deepdesk-popup-create-channel"},s.origin,[o.port2]);break}case"deepdesk-popup-error":{l(),d.data.message==="Timeout"&&B.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(d.data.message));break}}};window.addEventListener("message",c);let p=setInterval(()=>{u&&!u.closed||(l(),a||n(new Error("Popup closed by user")))},200);this.unmountHandlers.push(l)})}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(B.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;B.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=od(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(Kt()):this.store.dispatch(In(r))})}catch(r){this.handleError(r)}}};async function _E(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function wE(e,t,n={}){let r=n.replace?Ir(e,n.replace.start,n.replace.end):Hi(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
26
26
  `).reverse().forEach((s,a)=>{a>0&&r.insertNode(document.createElement("br")),r.insertNode(document.createTextNode(s))}):r.insertNode(document.createTextNode(t))};return Promise.resolve(i()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let s=n.selectionAfter?Ir(e,n.selectionAfter.start,n.selectionAfter.end):(r.collapse(!1),r),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(s)}if(!o)return;o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}async function bE(e,t){let n;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let r=()=>{let o=e.ownerDocument.defaultView??window,i=o.getSelection();if((!i||i.rangeCount===0)&&(e.focus(),i=o.getSelection()),!i||i.rangeCount===0)return;let s=i.getRangeAt(0);s&&(s.deleteContents(),n=document.createElement("span"),s.insertNode(n),t.split(`
27
27
  `).reverse().forEach((a,l)=>{l>0&&s.insertNode(document.createElement("br")),s.insertNode(document.createTextNode(a))}),s.collapse(!1))};return Promise.resolve(r()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!n)try{n.scrollIntoView&&n.scrollIntoView({block:"nearest",inline:"nearest"})}finally{n&&n.remove()}})}function EE(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function CE(e,t,n){await new zn(e).authenticateWithKey(t,n)}async function TE(e){let n=await new $t(e).get("/platform/config/",{version:null});return te(n)}async function gA(e){let n=await(e.fetch??window.fetch)(e.url),r=await n.blob();return new File([r],e.name,{type:e.mimeType??n.headers.get("Content-Type")??"image/jpeg"})}async function kE(e,t){let n=await gA(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}}return NE(hA);})();
28
28
  /*! Bundled license information:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepdesk/deepdesk-sdk",
3
- "version": "10.6.2-beta.5",
3
+ "version": "10.7.0",
4
4
  "description": "Deepdesk SDK",
5
5
  "author": "Lukas Batteau",
6
6
  "license": "ISC",