@deepdesk/deepdesk-sdk 10.9.3-beta.7 → 10.10.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 aa=require("react/jsx-runtime"),dh={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},xu=({className:t,color:e})=>(0,aa.jsx)("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,aa.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:dh[e||"pink"]})});var bu={root:"_root_1tvv4_1",text:"_text_1tvv4_18",isLoggedIn:"_isLoggedIn_1tvv4_25",isLoggedOut:"_isLoggedOut_1tvv4_29",icon:"_icon_1tvv4_39",logo:"_logo_1tvv4_44",lock:"_lock_1tvv4_49"};var la={};V(la,{enUS:()=>uh,nlNL:()=>gh});var uh={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},gh={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Tu=require("react-redux"),Xt=require("react/jsx-runtime"),Eu=({onLogIn:t})=>{let e=T(la),o=C("productName"),n=(0,Tu.useDispatch)(),s=(0,wu.useSelector)(ue),r=v("FloatingMenu",bu);if(s===null)return null;let i=()=>{s===!0?n(Y(!0)):t()};return(0,Xt.jsxs)("button",{className:(0,Cu.default)(r.root,{[r.isLoggedIn]:s,[r.isLoggedOut]:!s}),onClick:i,children:[(0,Xt.jsx)("div",{className:r.text,children:e(s?"search":"signin",{productName:o})}),(0,Xt.jsxs)("div",{className:r.icon,children:[(0,Xt.jsx)(xu,{className:r.logo,color:"pink"}),s===!1&&(0,Xt.jsx)(_u,{className:r.lock})]})]})};async function Tr(t){let o=await new Ne(t).get("/platform/config/",{version:null});return N(o)}var j=require("react/jsx-runtime");var ku=vu("showTabHint",!0),En=class t{static version="10.9.3-beta.7";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 at(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[mu({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=>ku.update(d),sendEvent:(d,u)=>this.deepdeskApi.sendEvent(d,u)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new Tn(o)}),this.store=gu(p),this.broadcastEvents=new eu({debug:!0,deepdeskUrl:c,eventMap:Oc(this.store),createCustomChannel:l}),this.store.dispatch(Bo),this.store.dispatch(en(ku.value())),this.store.dispatch(Bo({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(So(null)),this.store.dispatch(Xe()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();ue(n)&&Ic(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(Xe())).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(Ar({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(zn(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(jn({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Mr(e))).payload}async postMessages(e){return(await this.store.dispatch(Vn(e))).payload}async updateConversation(e){return(await this.store.dispatch(qn(e))).payload}resetConversation(){this.store.dispatch(M()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Ze());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(Bo(e))}setVisitorInfo(e){this.store.dispatch(Gl(e))}async setAgentInfo(e){await this.store.dispatch(Xo(e))}async setAgentSettings(e){await this.store.dispatch(di(e))}async getAgentSettings(){return(await this.store.dispatch(ui())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(Os()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Zn(e))}notifyKeyDown(e){this.store.dispatch(Xn(e))}notifyPaste(e,o){this.store.dispatch(Za({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Xa(e))}notifyExternalSuggestion(e){this.store.dispatch(ke(e)),this.store.dispatch(je())}notifyEditSuggestion(e){this.store.dispatch(uc(e.contentType,e.suggestions)),this.store.dispatch($e({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(yt({collapse:!1})),this.inputMediator&&this.store.dispatch(ja({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(He([])))}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(Qa(Gn(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Wa()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{if(o||!a||!r||e.shiftKey)return;this.store.dispatch($a());let{selectedSuggestionIndex:d}=this.state.input;e.preventDefault(),!i&&(d===-1?this.store.dispatch(Fo()):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(Fo()),e.preventDefault()):o||(this.store.dispatch(yt({collapse:!0})),this.store.dispatch(Cc(!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(en(!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(je())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Ja()),this.store.dispatch(He([]))}handlingTimeStart(){this.state.handlingTime.startTime||(E.info("Start handling time"),this.store.dispatch(su()))}handlingTimeStop(){this.state.handlingTime.startTime&&(E.info("Stop handling time"),this.store.dispatch(vr()))}logSendMessage(e){let o=ra("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=ra("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Va(this.state.overlayInput.metrics))}logHandlingTime(){let e=fu(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(ru())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(je()),this.store.dispatch(Pt(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){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]=Mt(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]=Mt(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),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(el(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(!br(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:h,inlineSuggestions:w,floatingMenu:y}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:g,isEmbedded:d,inlineSuggestions:w,floatingMenu:!!y}),o.automaticHandlingTime&&this.setupHandlingTime(e),At(e),this.inputMediator=f||(xt(e)?new We(e):new Gt(e)),this.inputMediator.on("change",({plainText:_})=>{this.notifyInputChanged(_)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Ya({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",_=>{this.notifyKeyDown(_)}),this.inputMediator.on("paste",({pastedText:_,selectionText:L})=>{this.notifyPaste(_,L)}),this.inputMediator.on("cut",({selectionText:_})=>{this.notifyCut(_)});let x=m&&hu(e,m)||void 0;if(w){let{customStyles:_,appendOverlayTo:L}=o;if(xt(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let O=this.createInlineContainer(e,"deepdesk-caret");(0,we.render)((0,j.jsx)(Vt,{store:this.store,customStyles:_,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(Ep,{})})}),O),this.inputMediator.on("caret",A=>{this.store.dispatch(He([])),A?(O.style.display="block",O.style.top=`${A.top}px`,O.style.left=`${A.left}px`):O.style.display="none"});let se=this.overlayContainerFactory("floating-menu",x||e,{appendTo:typeof y=="object"&&"appendOverlayTo"in y?y.appendOverlayTo:L},_==null?void 0:_.floatingMenuRootNode);(0,we.render)((0,j.jsx)(Vt,{store:this.store,customStyles:_,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(Eu,{onLogIn:()=>this.loginViaPopup().catch(A=>E.warn(A.message))})})}),se)}else{let _=this.overlayContainerFactory("deepdesk-tab-completion",x||e,{appendTo:h,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),L=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:h},n==null?void 0:n.suggestionsRootNode);(0,we.render)((0,j.jsx)(Vt,{store:this.store,customStyles:n,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(nd,{inputElement:e})})}),_),(0,we.render)((0,j.jsx)(Vt,{store:this.store,customStyles:n,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(Op,{onLogIn:()=>this.loginViaPopup().catch(O=>E.warn(O.message))})})}),L)}(0,we.render)((0,j.jsx)(Vt,{store:this.store,customStyles:n,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(Sp,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",_=>{clearTimeout(b),_===null?b=setTimeout(()=>{_!==null&&this.store.dispatch(Or(_))},500):this.store.dispatch(Or(_))}),this.inputMediator.on("disabled",()=>{var _;(_=this.inputMediator)==null||_.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(yo(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(yo(!0))),this.store.dispatch(qa({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(je()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var _;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((_=this.state.conversation.current)==null?void 0:_.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,isEmbedded:r}=o;this.widgetRoot=e,this.configure({showImages:s,isEmbedded:r}),(0,we.render)((0,j.jsx)(Vt,{store:this.store,customStyles:n,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(Qd,{onLogIn:()=>this.loginViaPopup().catch(i=>E.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&(0,we.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=Cr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){yu(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(gn());let e=St(this.state);e&&this.store.dispatch(Bo({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(){let e=this.state.settings.adminUrl,o=new URL(e),n=await Tr(o.origin);return new Promise((s,r)=>{let i=new MessageChannel,a=i.port1,l=new URL(n.config.platform.hasSso?`${e}/platform/sso/`:`${e}/admin/`);l.searchParams.append("redirect","/sdk/popup/close.html");let c=!1,p=()=>{d&&!d.closed&&d.close(),window.removeEventListener("message",u),clearInterval(g)};a.onmessage=async f=>{var m,h;if((m=f.data)!=null&&m.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((h=f.data)==null?void 0:h.jwt),await this.isLoggedIn(),this.broadcastEvents.send(nn),p(),c=!0,i.port1.close(),s()}catch(w){r(w)}};let d=window.open(l.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");d===null&&r(new Error("Popup blocked by browser"));let u=async f=>{var m;if(f.origin===l.origin)switch((m=f.data)==null?void 0:m.type){case"deepdesk-popup-loaded":{d==null||d.postMessage({type:"deepdesk-popup-create-channel"},l.origin,[i.port2]);break}case"deepdesk-popup-error":{p(),f.data.message==="Timeout"&&E.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(f.data.message));break}}};window.addEventListener("message",u);let g=setInterval(()=>{d&&!d.closed||(p(),c||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(p)})}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=Vs(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(Ae()):this.store.dispatch(Pe(n))})}catch(n){this.handleError(n)}}};async function Iu(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 Ru(t,e,o={}){let n=o.replace?Et(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 aa=require("react/jsx-runtime"),dh={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},xu=({className:t,color:e})=>(0,aa.jsx)("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,aa.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:dh[e||"pink"]})});var bu={root:"_root_1tvv4_1",text:"_text_1tvv4_18",isLoggedIn:"_isLoggedIn_1tvv4_25",isLoggedOut:"_isLoggedOut_1tvv4_29",icon:"_icon_1tvv4_39",logo:"_logo_1tvv4_44",lock:"_lock_1tvv4_49"};var la={};V(la,{enUS:()=>uh,nlNL:()=>gh});var uh={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},gh={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Tu=require("react-redux"),Xt=require("react/jsx-runtime"),Eu=({onLogIn:t})=>{let e=T(la),o=C("productName"),n=(0,Tu.useDispatch)(),s=(0,wu.useSelector)(ue),r=v("FloatingMenu",bu);if(s===null)return null;let i=()=>{s===!0?n(Y(!0)):t()};return(0,Xt.jsxs)("button",{className:(0,Cu.default)(r.root,{[r.isLoggedIn]:s,[r.isLoggedOut]:!s}),onClick:i,children:[(0,Xt.jsx)("div",{className:r.text,children:e(s?"search":"signin",{productName:o})}),(0,Xt.jsxs)("div",{className:r.icon,children:[(0,Xt.jsx)(xu,{className:r.logo,color:"pink"}),s===!1&&(0,Xt.jsx)(_u,{className:r.lock})]})]})};async function Tr(t){let o=await new Ne(t).get("/platform/config/",{version:null});return N(o)}var j=require("react/jsx-runtime");var ku=vu("showTabHint",!0),En=class t{static version="10.10.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 at(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[mu({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=>ku.update(d),sendEvent:(d,u)=>this.deepdeskApi.sendEvent(d,u)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new Tn(o)}),this.store=gu(p),this.broadcastEvents=new eu({debug:!0,deepdeskUrl:c,eventMap:Oc(this.store),createCustomChannel:l}),this.store.dispatch(Bo),this.store.dispatch(en(ku.value())),this.store.dispatch(Bo({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(So(null)),this.store.dispatch(Xe()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();ue(n)&&Ic(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(Xe())).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(Ar({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(zn(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(jn({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Mr(e))).payload}async postMessages(e){return(await this.store.dispatch(Vn(e))).payload}async updateConversation(e){return(await this.store.dispatch(qn(e))).payload}resetConversation(){this.store.dispatch(M()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Ze());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(Bo(e))}setVisitorInfo(e){this.store.dispatch(Gl(e))}async setAgentInfo(e){await this.store.dispatch(Xo(e))}async setAgentSettings(e){await this.store.dispatch(di(e))}async getAgentSettings(){return(await this.store.dispatch(ui())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(Os()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Zn(e))}notifyKeyDown(e){this.store.dispatch(Xn(e))}notifyPaste(e,o){this.store.dispatch(Za({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Xa(e))}notifyExternalSuggestion(e){this.store.dispatch(ke(e)),this.store.dispatch(je())}notifyEditSuggestion(e){this.store.dispatch(uc(e.contentType,e.suggestions)),this.store.dispatch($e({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(yt({collapse:!1})),this.inputMediator&&this.store.dispatch(ja({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(He([])))}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(Qa(Gn(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Wa()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{if(o||!a||!r||e.shiftKey)return;this.store.dispatch($a());let{selectedSuggestionIndex:d}=this.state.input;e.preventDefault(),!i&&(d===-1?this.store.dispatch(Fo()):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(Fo()),e.preventDefault()):o||(this.store.dispatch(yt({collapse:!0})),this.store.dispatch(Cc(!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(en(!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(je())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Ja()),this.store.dispatch(He([]))}handlingTimeStart(){this.state.handlingTime.startTime||(E.info("Start handling time"),this.store.dispatch(su()))}handlingTimeStop(){this.state.handlingTime.startTime&&(E.info("Stop handling time"),this.store.dispatch(vr()))}logSendMessage(e){let o=ra("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=ra("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Va(this.state.overlayInput.metrics))}logHandlingTime(){let e=fu(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(ru())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(je()),this.store.dispatch(Pt(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){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]=Mt(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]=Mt(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),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(el(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(!br(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:h,inlineSuggestions:w,floatingMenu:y}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:g,isEmbedded:d,inlineSuggestions:w,floatingMenu:!!y}),o.automaticHandlingTime&&this.setupHandlingTime(e),At(e),this.inputMediator=f||(xt(e)?new We(e):new Gt(e)),this.inputMediator.on("change",({plainText:_})=>{this.notifyInputChanged(_)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Ya({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",_=>{this.notifyKeyDown(_)}),this.inputMediator.on("paste",({pastedText:_,selectionText:L})=>{this.notifyPaste(_,L)}),this.inputMediator.on("cut",({selectionText:_})=>{this.notifyCut(_)});let x=m&&hu(e,m)||void 0;if(w){let{customStyles:_,appendOverlayTo:L}=o;if(xt(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let O=this.createInlineContainer(e,"deepdesk-caret");(0,we.render)((0,j.jsx)(Vt,{store:this.store,customStyles:_,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(Ep,{})})}),O),this.inputMediator.on("caret",A=>{this.store.dispatch(He([])),A?(O.style.display="block",O.style.top=`${A.top}px`,O.style.left=`${A.left}px`):O.style.display="none"});let se=this.overlayContainerFactory("floating-menu",x||e,{appendTo:typeof y=="object"&&"appendOverlayTo"in y?y.appendOverlayTo:L},_==null?void 0:_.floatingMenuRootNode);(0,we.render)((0,j.jsx)(Vt,{store:this.store,customStyles:_,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(Eu,{onLogIn:()=>this.loginViaPopup().catch(A=>E.warn(A.message))})})}),se)}else{let _=this.overlayContainerFactory("deepdesk-tab-completion",x||e,{appendTo:h,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),L=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:h},n==null?void 0:n.suggestionsRootNode);(0,we.render)((0,j.jsx)(Vt,{store:this.store,customStyles:n,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(nd,{inputElement:e})})}),_),(0,we.render)((0,j.jsx)(Vt,{store:this.store,customStyles:n,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(Op,{onLogIn:()=>this.loginViaPopup().catch(O=>E.warn(O.message))})})}),L)}(0,we.render)((0,j.jsx)(Vt,{store:this.store,customStyles:n,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(Sp,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",_=>{clearTimeout(b),_===null?b=setTimeout(()=>{_!==null&&this.store.dispatch(Or(_))},500):this.store.dispatch(Or(_))}),this.inputMediator.on("disabled",()=>{var _;(_=this.inputMediator)==null||_.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(yo(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(yo(!0))),this.store.dispatch(qa({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(je()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var _;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((_=this.state.conversation.current)==null?void 0:_.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,isEmbedded:r}=o;this.widgetRoot=e,this.configure({showImages:s,isEmbedded:r}),(0,we.render)((0,j.jsx)(Vt,{store:this.store,customStyles:n,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(Qd,{onLogIn:()=>this.loginViaPopup().catch(i=>E.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&(0,we.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=Cr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){yu(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(gn());let e=St(this.state);e&&this.store.dispatch(Bo({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:!!e.knowledgeAssistant,recommendTextSuggestions:e.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async loginViaPopup(){let e=this.state.settings.adminUrl,o=new URL(e),n=await Tr(o.origin);return new Promise((s,r)=>{let i=new MessageChannel,a=i.port1,l=new URL(n.config.platform.hasSso?`${e}/platform/sso/`:`${e}/admin/`);l.searchParams.append("redirect","/sdk/popup/close.html");let c=!1,p=()=>{d&&!d.closed&&d.close(),window.removeEventListener("message",u),clearInterval(g)};a.onmessage=async f=>{var m,h;if((m=f.data)!=null&&m.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((h=f.data)==null?void 0:h.jwt),await this.isLoggedIn(),this.broadcastEvents.send(nn),p(),c=!0,i.port1.close(),s()}catch(w){r(w)}};let d=window.open(l.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");d===null&&r(new Error("Popup blocked by browser"));let u=async f=>{var m;if(f.origin===l.origin)switch((m=f.data)==null?void 0:m.type){case"deepdesk-popup-loaded":{d==null||d.postMessage({type:"deepdesk-popup-create-channel"},l.origin,[i.port2]);break}case"deepdesk-popup-error":{p(),f.data.message==="Timeout"&&E.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(f.data.message));break}}};window.addEventListener("message",u);let g=setInterval(()=>{d&&!d.closed||(p(),c||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(p)})}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=Vs(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(Ae()):this.store.dispatch(Pe(n))})}catch(n){this.handleError(n)}}};async function Iu(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 Ru(t,e,o={}){let n=o.replace?Et(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?Et(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()}})}function mh(t){let e=document.createElement("template");return e.innerHTML=t,e.content}function fh(t){let e=document.createDocumentFragment();return t.split(`
11
11
  `).forEach((o,n)=>{n>0&&e.appendChild(document.createElement("br")),e.appendChild(document.createTextNode(o))}),e}function Pu(t,e){return!t.contains(e)||e===t?null:e.parentNode===t?e:Pu(t,e.parentNode)}async function Lu(t,e,{isBlock:o,isHTML:n}={}){let s;t.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0}));let r=()=>{let i=t.ownerDocument.defaultView??window,a=i.getSelection();if((!a||a.rangeCount===0)&&(t.focus(),a=i.getSelection()),!a||a.rangeCount===0)return;let l=a.getRangeAt(0);if(!l)return;s=document.createElement("span"),l.insertNode(s);let c=n?mh(e):fh(e);if(o){let p=Pu(t,l.startContainer)??t.firstChild;t.insertBefore(c,(p==null?void 0:p.nextSibling)??null)}else l.insertNode(c),l.collapse(!1)};return Promise.resolve(r()).then(()=>{if(t.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0})),t.focus(),!!s)try{s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}function Au(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function Mu(t,e,o){await new at(t).authenticateWithKey(e,o)}async function hh(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 Nu(t,e){let o=await hh(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.d.mts CHANGED
@@ -1025,8 +1025,6 @@ declare namespace Server {
1025
1025
  summarizer_prompt_instruction: string;
1026
1026
  summarizer_model: string;
1027
1027
  knowledge_assistant: string;
1028
- knowledge_assist_for_agents: boolean;
1029
- knowledge_assist_prompt_instruction: string;
1030
1028
  ui_config: {
1031
1029
  widget: {
1032
1030
  types: Array<{
package/dist/index.d.ts CHANGED
@@ -1025,8 +1025,6 @@ declare namespace Server {
1025
1025
  summarizer_prompt_instruction: string;
1026
1026
  summarizer_model: string;
1027
1027
  knowledge_assistant: string;
1028
- knowledge_assist_for_agents: boolean;
1029
- knowledge_assist_prompt_instruction: string;
1030
1028
  ui_config: {
1031
1029
  widget: {
1032
1030
  types: Array<{
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 id}from"react/jsx-runtime";var Rv={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},ad=({className:t,color:e})=>id("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:id("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:Rv[e||"pink"]})});var ld={root:"_root_1tvv4_1",text:"_text_1tvv4_18",isLoggedIn:"_isLoggedIn_1tvv4_25",isLoggedOut:"_isLoggedOut_1tvv4_29",icon:"_icon_1tvv4_39",logo:"_logo_1tvv4_44",lock:"_lock_1tvv4_49"};var ri={};j(ri,{enUS:()=>Pv,nlNL:()=>Lv});var Pv={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},Lv={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};import{useDispatch as Nv}from"react-redux";import{jsx as ii,jsxs as cd}from"react/jsx-runtime";var pd=({onLogIn:t})=>{let e=T(ri),o=C("productName"),n=Nv(),s=Mv(oe),r=v("FloatingMenu",ld);if(s===null)return null;let i=()=>{s===!0?n(W(!0)):t()};return cd("button",{className:Av(r.root,{[r.isLoggedIn]:s,[r.isLoggedOut]:!s}),onClick:i,children:[ii("div",{className:r.text,children:e(s?"search":"signin",{productName:o})}),cd("div",{className:r.icon,children:[ii(ad,{className:r.logo,color:"pink"}),s===!1&&ii(rd,{className:r.lock})]})]})};async function ai(t){let o=await new ve(t).get("/platform/config/",{version:null});return A(o)}import{jsx as K}from"react/jsx-runtime";var dd=nd("showTabHint",!0),ls=class t{static version="10.9.3-beta.7";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 je(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Yp({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=>dd.update(d),sendEvent:(d,u)=>this.deepdeskApi.sendEvent(d,u)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new bo(o)}),this.store=Jp(p),this.broadcastEvents=new Kp({debug:!0,deepdeskUrl:c,eventMap:El(this.store),createCustomChannel:l}),this.store.dispatch(qt),this.store.dispatch(no(dd.value())),this.store.dispatch(qt({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(we()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();oe(n)&&Sl(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(we())).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(bs({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(No(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Oo({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Cs(e))).payload}async postMessages(e){return(await this.store.dispatch(Ho(e))).payload}async updateConversation(e){return(await this.store.dispatch(Do(e))).payload}resetConversation(){this.store.dispatch(L()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Ee());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(qt(e))}setVisitorInfo(e){this.store.dispatch(Da(e))}async setAgentInfo(e){await this.store.dispatch(Yt(e))}async setAgentSettings(e){await this.store.dispatch(nr(e))}async getAgentSettings(){return(await this.store.dispatch(sr())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(wn()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(jo(e))}notifyKeyDown(e){this.store.dispatch(Uo(e))}notifyPaste(e,o){this.store.dispatch(Ni({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Ai(e))}notifyExternalSuggestion(e){this.store.dispatch(ie(e)),this.store.dispatch(_e())}notifyEditSuggestion(e){this.store.dispatch(rl(e.contentType,e.suggestions)),this.store.dispatch(Ce({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(Fe({collapse:!1})),this.inputMediator&&this.store.dispatch(Ei({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(ge([])))}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(Mi(Fo(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Ri()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{if(o||!a||!r||e.shiftKey)return;this.store.dispatch(Li());let{selectedSuggestionIndex:d}=this.state.input;e.preventDefault(),!i&&(d===-1?this.store.dispatch(Vt()):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(Vt()),e.preventDefault()):o||(this.store.dispatch(Fe({collapse:!0})),this.store.dispatch(ml(!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(no(!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(_e())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Oi()),this.store.dispatch(ge([]))}handlingTimeStart(){this.state.handlingTime.startTime||(E.info("Start handling time"),this.store.dispatch(jp()))}handlingTimeStop(){this.state.handlingTime.startTime&&(E.info("Stop handling time"),this.store.dispatch(rs()))}logSendMessage(e){let o=ei("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=ei("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Ii(this.state.overlayInput.metrics))}logHandlingTime(){let e=ed(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(qp())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(_e()),this.store.dispatch(Ge(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]=xt(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{as(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]=xt(r,{appendTo:document.body});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{as(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Xe(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(()=>{as(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(Hi(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(!oi(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:h,inlineSuggestions:w,floatingMenu:y}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:g,isEmbedded:d,inlineSuggestions:w,floatingMenu:!!y}),o.automaticHandlingTime&&this.setupHandlingTime(e),Xe(e),this.inputMediator=f||(Ue(e)?new Oe(e):new Dt(e)),this.inputMediator.on("change",({plainText:_})=>{this.notifyInputChanged(_)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Di({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",_=>{this.notifyKeyDown(_)}),this.inputMediator.on("paste",({pastedText:_,selectionText:R})=>{this.notifyPaste(_,R)}),this.inputMediator.on("cut",({selectionText:_})=>{this.notifyCut(_)});let x=m&&td(e,m)||void 0;if(w){let{customStyles:_,appendOverlayTo:R}=o;if(Ue(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let N=this.createInlineContainer(e,"deepdesk-caret");Ft(K(tt,{store:this.store,customStyles:_,children:K(et,{broadcastEvents:this.broadcastEvents,children:K(fc,{})})}),N),this.inputMediator.on("caret",P=>{this.store.dispatch(ge([])),P?(N.style.display="block",N.style.top=`${P.top}px`,N.style.left=`${P.left}px`):N.style.display="none"});let $=this.overlayContainerFactory("floating-menu",x||e,{appendTo:typeof y=="object"&&"appendOverlayTo"in y?y.appendOverlayTo:R},_==null?void 0:_.floatingMenuRootNode);Ft(K(tt,{store:this.store,customStyles:_,children:K(et,{broadcastEvents:this.broadcastEvents,children:K(pd,{onLogIn:()=>this.loginViaPopup().catch(P=>E.warn(P.message))})})}),$)}else{let _=this.overlayContainerFactory("deepdesk-tab-completion",x||e,{appendTo:h,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),R=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:h},n==null?void 0:n.suggestionsRootNode);Ft(K(tt,{store:this.store,customStyles:n,children:K(et,{broadcastEvents:this.broadcastEvents,children:K(Vc,{inputElement:e})})}),_),Ft(K(tt,{store:this.store,customStyles:n,children:K(et,{broadcastEvents:this.broadcastEvents,children:K(wc,{onLogIn:()=>this.loginViaPopup().catch(N=>E.warn(N.message))})})}),R)}Ft(K(tt,{store:this.store,customStyles:n,children:K(et,{broadcastEvents:this.broadcastEvents,children:K(cc,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",_=>{clearTimeout(b),_===null?b=setTimeout(()=>{_!==null&&this.store.dispatch(Ts(_))},500):this.store.dispatch(Ts(_))}),this.inputMediator.on("disabled",()=>{var _;(_=this.inputMediator)==null||_.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(ki({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(_e()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var _;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((_=this.state.conversation.current)==null?void 0:_.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,isEmbedded:r}=o;this.widgetRoot=e,this.configure({showImages:s,isEmbedded:r}),Ft(K(tt,{store:this.store,customStyles:n,children:K(et,{broadcastEvents:this.broadcastEvents,children:K(Dp,{onLogIn:()=>this.loginViaPopup().catch(i=>E.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&as(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=ni(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){od(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(po());let e=Ke(this.state);e&&this.store.dispatch(qt({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(){let e=this.state.settings.adminUrl,o=new URL(e),n=await ai(o.origin);return new Promise((s,r)=>{let i=new MessageChannel,a=i.port1,l=new URL(n.config.platform.hasSso?`${e}/platform/sso/`:`${e}/admin/`);l.searchParams.append("redirect","/sdk/popup/close.html");let c=!1,p=()=>{d&&!d.closed&&d.close(),window.removeEventListener("message",u),clearInterval(g)};a.onmessage=async f=>{var m,h;if((m=f.data)!=null&&m.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((h=f.data)==null?void 0:h.jwt),await this.isLoggedIn(),this.broadcastEvents.send(ro),p(),c=!0,i.port1.close(),s()}catch(w){r(w)}};let d=window.open(l.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");d===null&&r(new Error("Popup blocked by browser"));let u=async f=>{var m;if(f.origin===l.origin)switch((m=f.data)==null?void 0:m.type){case"deepdesk-popup-loaded":{d==null||d.postMessage({type:"deepdesk-popup-create-channel"},l.origin,[i.port2]);break}case"deepdesk-popup-error":{p(),f.data.message==="Timeout"&&E.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(f.data.message));break}}};window.addEventListener("message",u);let g=setInterval(()=>{d&&!d.closed||(p(),c||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(p)})}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=Pn(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(pe()):this.store.dispatch(ce(n))})}catch(n){this.handleError(n)}}};async function Ov(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 Dv(t,e,o={}){let n=o.replace?rt(t,o.replace.start,o.replace.end):_o(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 id}from"react/jsx-runtime";var Rv={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},ad=({className:t,color:e})=>id("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:id("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:Rv[e||"pink"]})});var ld={root:"_root_1tvv4_1",text:"_text_1tvv4_18",isLoggedIn:"_isLoggedIn_1tvv4_25",isLoggedOut:"_isLoggedOut_1tvv4_29",icon:"_icon_1tvv4_39",logo:"_logo_1tvv4_44",lock:"_lock_1tvv4_49"};var ri={};j(ri,{enUS:()=>Pv,nlNL:()=>Lv});var Pv={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},Lv={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};import{useDispatch as Nv}from"react-redux";import{jsx as ii,jsxs as cd}from"react/jsx-runtime";var pd=({onLogIn:t})=>{let e=T(ri),o=C("productName"),n=Nv(),s=Mv(oe),r=v("FloatingMenu",ld);if(s===null)return null;let i=()=>{s===!0?n(W(!0)):t()};return cd("button",{className:Av(r.root,{[r.isLoggedIn]:s,[r.isLoggedOut]:!s}),onClick:i,children:[ii("div",{className:r.text,children:e(s?"search":"signin",{productName:o})}),cd("div",{className:r.icon,children:[ii(ad,{className:r.logo,color:"pink"}),s===!1&&ii(rd,{className:r.lock})]})]})};async function ai(t){let o=await new ve(t).get("/platform/config/",{version:null});return A(o)}import{jsx as K}from"react/jsx-runtime";var dd=nd("showTabHint",!0),ls=class t{static version="10.10.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 je(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Yp({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=>dd.update(d),sendEvent:(d,u)=>this.deepdeskApi.sendEvent(d,u)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new bo(o)}),this.store=Jp(p),this.broadcastEvents=new Kp({debug:!0,deepdeskUrl:c,eventMap:El(this.store),createCustomChannel:l}),this.store.dispatch(qt),this.store.dispatch(no(dd.value())),this.store.dispatch(qt({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(we()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();oe(n)&&Sl(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(we())).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(bs({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(No(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Oo({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Cs(e))).payload}async postMessages(e){return(await this.store.dispatch(Ho(e))).payload}async updateConversation(e){return(await this.store.dispatch(Do(e))).payload}resetConversation(){this.store.dispatch(L()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Ee());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(qt(e))}setVisitorInfo(e){this.store.dispatch(Da(e))}async setAgentInfo(e){await this.store.dispatch(Yt(e))}async setAgentSettings(e){await this.store.dispatch(nr(e))}async getAgentSettings(){return(await this.store.dispatch(sr())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(wn()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(jo(e))}notifyKeyDown(e){this.store.dispatch(Uo(e))}notifyPaste(e,o){this.store.dispatch(Ni({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Ai(e))}notifyExternalSuggestion(e){this.store.dispatch(ie(e)),this.store.dispatch(_e())}notifyEditSuggestion(e){this.store.dispatch(rl(e.contentType,e.suggestions)),this.store.dispatch(Ce({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(Fe({collapse:!1})),this.inputMediator&&this.store.dispatch(Ei({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(ge([])))}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(Mi(Fo(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Ri()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{if(o||!a||!r||e.shiftKey)return;this.store.dispatch(Li());let{selectedSuggestionIndex:d}=this.state.input;e.preventDefault(),!i&&(d===-1?this.store.dispatch(Vt()):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(Vt()),e.preventDefault()):o||(this.store.dispatch(Fe({collapse:!0})),this.store.dispatch(ml(!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(no(!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(_e())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Oi()),this.store.dispatch(ge([]))}handlingTimeStart(){this.state.handlingTime.startTime||(E.info("Start handling time"),this.store.dispatch(jp()))}handlingTimeStop(){this.state.handlingTime.startTime&&(E.info("Stop handling time"),this.store.dispatch(rs()))}logSendMessage(e){let o=ei("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=ei("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Ii(this.state.overlayInput.metrics))}logHandlingTime(){let e=ed(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(qp())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(_e()),this.store.dispatch(Ge(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]=xt(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{as(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]=xt(r,{appendTo:document.body});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{as(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Xe(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(()=>{as(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(Hi(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(!oi(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:h,inlineSuggestions:w,floatingMenu:y}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:g,isEmbedded:d,inlineSuggestions:w,floatingMenu:!!y}),o.automaticHandlingTime&&this.setupHandlingTime(e),Xe(e),this.inputMediator=f||(Ue(e)?new Oe(e):new Dt(e)),this.inputMediator.on("change",({plainText:_})=>{this.notifyInputChanged(_)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Di({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",_=>{this.notifyKeyDown(_)}),this.inputMediator.on("paste",({pastedText:_,selectionText:R})=>{this.notifyPaste(_,R)}),this.inputMediator.on("cut",({selectionText:_})=>{this.notifyCut(_)});let x=m&&td(e,m)||void 0;if(w){let{customStyles:_,appendOverlayTo:R}=o;if(Ue(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let N=this.createInlineContainer(e,"deepdesk-caret");Ft(K(tt,{store:this.store,customStyles:_,children:K(et,{broadcastEvents:this.broadcastEvents,children:K(fc,{})})}),N),this.inputMediator.on("caret",P=>{this.store.dispatch(ge([])),P?(N.style.display="block",N.style.top=`${P.top}px`,N.style.left=`${P.left}px`):N.style.display="none"});let $=this.overlayContainerFactory("floating-menu",x||e,{appendTo:typeof y=="object"&&"appendOverlayTo"in y?y.appendOverlayTo:R},_==null?void 0:_.floatingMenuRootNode);Ft(K(tt,{store:this.store,customStyles:_,children:K(et,{broadcastEvents:this.broadcastEvents,children:K(pd,{onLogIn:()=>this.loginViaPopup().catch(P=>E.warn(P.message))})})}),$)}else{let _=this.overlayContainerFactory("deepdesk-tab-completion",x||e,{appendTo:h,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),R=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:h},n==null?void 0:n.suggestionsRootNode);Ft(K(tt,{store:this.store,customStyles:n,children:K(et,{broadcastEvents:this.broadcastEvents,children:K(Vc,{inputElement:e})})}),_),Ft(K(tt,{store:this.store,customStyles:n,children:K(et,{broadcastEvents:this.broadcastEvents,children:K(wc,{onLogIn:()=>this.loginViaPopup().catch(N=>E.warn(N.message))})})}),R)}Ft(K(tt,{store:this.store,customStyles:n,children:K(et,{broadcastEvents:this.broadcastEvents,children:K(cc,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",_=>{clearTimeout(b),_===null?b=setTimeout(()=>{_!==null&&this.store.dispatch(Ts(_))},500):this.store.dispatch(Ts(_))}),this.inputMediator.on("disabled",()=>{var _;(_=this.inputMediator)==null||_.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(ki({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(_e()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var _;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((_=this.state.conversation.current)==null?void 0:_.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,isEmbedded:r}=o;this.widgetRoot=e,this.configure({showImages:s,isEmbedded:r}),Ft(K(tt,{store:this.store,customStyles:n,children:K(et,{broadcastEvents:this.broadcastEvents,children:K(Dp,{onLogIn:()=>this.loginViaPopup().catch(i=>E.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&as(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=ni(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){od(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(po());let e=Ke(this.state);e&&this.store.dispatch(qt({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:!!e.knowledgeAssistant,recommendTextSuggestions:e.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async loginViaPopup(){let e=this.state.settings.adminUrl,o=new URL(e),n=await ai(o.origin);return new Promise((s,r)=>{let i=new MessageChannel,a=i.port1,l=new URL(n.config.platform.hasSso?`${e}/platform/sso/`:`${e}/admin/`);l.searchParams.append("redirect","/sdk/popup/close.html");let c=!1,p=()=>{d&&!d.closed&&d.close(),window.removeEventListener("message",u),clearInterval(g)};a.onmessage=async f=>{var m,h;if((m=f.data)!=null&&m.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((h=f.data)==null?void 0:h.jwt),await this.isLoggedIn(),this.broadcastEvents.send(ro),p(),c=!0,i.port1.close(),s()}catch(w){r(w)}};let d=window.open(l.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");d===null&&r(new Error("Popup blocked by browser"));let u=async f=>{var m;if(f.origin===l.origin)switch((m=f.data)==null?void 0:m.type){case"deepdesk-popup-loaded":{d==null||d.postMessage({type:"deepdesk-popup-create-channel"},l.origin,[i.port2]);break}case"deepdesk-popup-error":{p(),f.data.message==="Timeout"&&E.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(f.data.message));break}}};window.addEventListener("message",u);let g=setInterval(()=>{d&&!d.closed||(p(),c||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(p)})}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=Pn(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(pe()):this.store.dispatch(ce(n))})}catch(n){this.handleError(n)}}};async function Ov(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 Dv(t,e,o={}){let n=o.replace?rt(t,o.replace.start,o.replace.end):_o(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?rt(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()}})}function Hv(t){let e=document.createElement("template");return e.innerHTML=t,e.content}function Bv(t){let e=document.createDocumentFragment();return t.split(`
11
11
  `).forEach((o,n)=>{n>0&&e.appendChild(document.createElement("br")),e.appendChild(document.createTextNode(o))}),e}function ud(t,e){return!t.contains(e)||e===t?null:e.parentNode===t?e:ud(t,e.parentNode)}async function Fv(t,e,{isBlock:o,isHTML:n}={}){let s;t.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0}));let r=()=>{let i=t.ownerDocument.defaultView??window,a=i.getSelection();if((!a||a.rangeCount===0)&&(t.focus(),a=i.getSelection()),!a||a.rangeCount===0)return;let l=a.getRangeAt(0);if(!l)return;s=document.createElement("span"),l.insertNode(s);let c=n?Hv(e):Bv(e);if(o){let p=ud(t,l.startContainer)??t.firstChild;t.insertBefore(c,(p==null?void 0:p.nextSibling)??null)}else l.insertNode(c),l.collapse(!1)};return Promise.resolve(r()).then(()=>{if(t.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0})),t.focus(),!!s)try{s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}function Kv(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function Uv(t,e,o){await new je(t).authenticateWithKey(e,o)}async function zv(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 jv(t,e){let o=await zv(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{H as Card,Dt as ContentEditableInput,je as DeepdeskAPI,ls as DeepdeskSDK,ve as HTTPClient,Ne as InputMediator,Ve as InputType,gs as KeyboardHint,ms as Label,Lo as Locale,qe as Section,hs as SectionList,ue as Sources,D as Suggestion,re as SuggestionList,Oe as TextAreaInput,ut as ToggleButton,jv as attachFile,Uv as authenticateWithKey,_o as createFullRange,xt as createOverlayContainer,rt as createRangeFromOffsets,Qt as escapeHTML,ai as fetchPlatformConfig,Kv as formatTextMarkup,os as getRangeOffsets,ns as getRangeText,Fv as insertCKEditor,oi as isSupportedInputElement,Dv as updateContentEditable,Ov as updateTextArea,v as useStyles,ni 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 Mh=S(w()),yA={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},xC=({className:e,color:t})=>(0,Mh.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,Mh.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:yA[t||"pink"]})});var _C={root:"_root_1tvv4_1",text:"_text_1tvv4_18",isLoggedIn:"_isLoggedIn_1tvv4_25",isLoggedOut:"_isLoggedOut_1tvv4_29",icon:"_icon_1tvv4_39",logo:"_logo_1tvv4_44",lock:"_lock_1tvv4_49"};var Dh={};ke(Dh,{enUS:()=>vA,nlNL:()=>SA});var vA={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},SA={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var bo=S(w()),bC=({onLogIn:e})=>{let t=j(Dh),n=N("productName"),r=U(),o=R(pt),i=k("FloatingMenu",_C);if(o===null)return null;let s=()=>{o===!0?r($e(!0)):e()};return(0,bo.jsxs)("button",{className:(0,wC.default)(i.root,{[i.isLoggedIn]:o,[i.isLoggedOut]:!o}),onClick:s,children:[(0,bo.jsx)("div",{className:i.text,children:t(o?"search":"signin",{productName:n})}),(0,bo.jsxs)("div",{className:i.icon,children:[(0,bo.jsx)(xC,{className:i.logo,color:"pink"}),o===!1&&(0,bo.jsx)(SC,{className:i.lock})]})]})};async function jd(e){let n=await new Gt(e).get("/platform/config/",{version:null});return ne(n)}var we=S(w());var CC=yC("showTabHint",!0),Wa=class e{static version="10.9.3-beta.7";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 Un(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[fC({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=>CC.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Ka(n)}),this.store=pC(c),this.broadcastEvents=new eC({debug:!0,deepdeskUrl:u,eventMap:Kw(this.store),createCustomChannel:l}),this.store.dispatch(ra),this.store.dispatch(Ca(CC.value())),this.store.dispatch(ra({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?(H.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(H.warn("Profile has not been loaded (yet)"),!0):(H.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Ai(null)),this.store.dispatch(Ln()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();pt(r)&&Fw(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(Ln())).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){H.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Zm({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(ic(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(sc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Jm(t))).payload}async postMessages(t){return(await this.store.dispatch(lc(t))).payload}async updateConversation(t){return(await this.store.dispatch(ac(t))).payload}resetConversation(){this.store.dispatch(ee()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(On());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(ra(t))}setVisitorInfo(t){this.store.dispatch(ow(t))}async setAgentInfo(t){await this.store.dispatch(Sa(t))}async setAgentSettings(t){await this.store.dispatch(jg(t))}async getAgentSettings(){return(await this.store.dispatch(Hg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(rd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(mc(t))}notifyKeyDown(t){this.store.dispatch(pc(t))}notifyPaste(t,n){this.store.dispatch(s_({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(o_(t))}notifyExternalSuggestion(t){this.store.dispatch(Bt(t)),this.store.dispatch(wn())}notifyEditSuggestion(t){this.store.dispatch(bw(t.contentType,t.suggestions)),this.store.dispatch(In({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(Cr({collapse:!1})),this.inputMediator&&this.store.dispatch(Zx({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(i_(cc(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(t_()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{if(n||!a||!i||t.shiftKey)return;this.store.dispatch(r_());let{selectedSuggestionIndex:p}=this.state.input;t.preventDefault(),!s&&(p===-1?this.store.dispatch(ia()):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(vr(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(vr(-1)),this.store.dispatch(ia()),t.preventDefault()):n||(this.store.dispatch(Cr({collapse:!0})),this.store.dispatch(Aw(!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(Ca(!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(a_()),this.store.dispatch(on([]))}handlingTimeStart(){this.state.handlingTime.startTime||(H.info("Start handling time"),this.store.dispatch(rC()))}handlingTimeStop(){this.state.handlingTime.startTime&&(H.info("Stop handling time"),this.store.dispatch(Od()))}logSendMessage(t){let n=Oh("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=Oh("overlayInput",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.store.dispatch(e_(this.state.overlayInput.metrics))}logHandlingTime(){let t=mC(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(oC())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(wn()),this.store.dispatch(no(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){H.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),H.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]=lo(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Nt.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]=lo(i,{appendTo:document.body});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,Nt.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 ao(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,Nt.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),H.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()?(H.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(u_(r.metrics))):H.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(!Md(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:f,inlineSuggestions:h,floatingMenu:m}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:g,isEmbedded:p,inlineSuggestions:h,floatingMenu:!!m}),n.automaticHandlingTime&&this.setupHandlingTime(t),ao(t),this.inputMediator=v||(Pr(t)?new Pn(t):new _o(t)),this.inputMediator.on("change",({plainText:b})=>{this.notifyInputChanged(b)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(l_({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:C})=>{this.notifyPaste(b,C)}),this.inputMediator.on("cut",({selectionText:b})=>{this.notifyCut(b)});let x=y&&gC(t,y)||void 0;if(h){let{customStyles:b,appendOverlayTo:C}=n;if(Pr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let E=this.createInlineContainer(t,"deepdesk-caret");(0,Nt.render)((0,we.jsx)(xo,{store:this.store,customStyles:b,children:(0,we.jsx)(ho,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(D1,{})})}),E),this.inputMediator.on("caret",P=>{this.store.dispatch(on([])),P?(E.style.display="block",E.style.top=`${P.top}px`,E.style.left=`${P.left}px`):E.style.display="none"});let I=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof m=="object"&&"appendOverlayTo"in m?m.appendOverlayTo:C},b==null?void 0:b.floatingMenuRootNode);(0,Nt.render)((0,we.jsx)(xo,{store:this.store,customStyles:b,children:(0,we.jsx)(ho,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(bC,{onLogIn:()=>this.loginViaPopup().catch(P=>H.warn(P.message))})})}),I)}else{let b=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:f,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:f},r==null?void 0:r.suggestionsRootNode);(0,Nt.render)((0,we.jsx)(xo,{store:this.store,customStyles:r,children:(0,we.jsx)(ho,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(sb,{inputElement:t})})}),b),(0,Nt.render)((0,we.jsx)(xo,{store:this.store,customStyles:r,children:(0,we.jsx)(ho,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(K1,{onLogIn:()=>this.loginViaPopup().catch(E=>H.warn(E.message))})})}),C)}(0,Nt.render)((0,we.jsx)(xo,{store:this.store,customStyles:r,children:(0,we.jsx)(ho,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(I1,{})})}),this.createContainer("deepdesk-overlays"));let _;this.inputMediator.on("selection",b=>{clearTimeout(_),b===null?_=setTimeout(()=>{b!==null&&this.store.dispatch(tg(b))},500):this.store.dispatch(tg(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(Li(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Li(!0))),this.store.dispatch(Jx({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&&H.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,Nt.render)((0,we.jsx)(xo,{store:this.store,customStyles:r,children:(0,we.jsx)(ho,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(Qb,{onLogIn:()=>this.loginViaPopup().catch(s=>H.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Nt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Dd(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){hC(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Na());let t=Tr(this.state);t&&this.store.dispatch(ra({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(){let t=this.state.settings.adminUrl,n=new URL(t),r=await jd(n.origin);return new Promise((o,i)=>{let s=new MessageChannel,a=s.port1,l=new URL(r.config.platform.hasSso?`${t}/platform/sso/`:`${t}/admin/`);l.searchParams.append("redirect","/sdk/popup/close.html");let u=!1,c=()=>{p&&!p.closed&&p.close(),window.removeEventListener("message",d),clearInterval(g)};a.onmessage=async v=>{var y,f;if((y=v.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((f=v.data)==null?void 0:f.jwt),await this.isLoggedIn(),this.broadcastEvents.send(ka),c(),u=!0,s.port1.close(),o()}catch(h){i(h)}};let p=window.open(l.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");p===null&&i(new Error("Popup blocked by browser"));let d=async v=>{var y;if(v.origin===l.origin)switch((y=v.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{p==null||p.postMessage({type:"deepdesk-popup-create-channel"},l.origin,[s.port2]);break}case"deepdesk-popup-error":{c(),v.data.message==="Timeout"&&H.warn("Popup timed out. Check if the account's platform url is configured correctly."),i(new Error(v.data.message));break}}};window.addEventListener("message",d);let g=setInterval(()=>{p&&!p.closed||(c(),u||i(new Error("Popup closed by user")))},200);this.unmountHandlers.push(c)})}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(H.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;H.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=ad(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch($t()):this.store.dispatch(Kt(r))})}catch(r){this.handleError(r)}}};async function EC(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 TC(e,t,n={}){let r=n.replace?Lr(e,n.replace.start,n.replace.end):Ui(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 Mh=S(w()),yA={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},xC=({className:e,color:t})=>(0,Mh.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,Mh.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:yA[t||"pink"]})});var _C={root:"_root_1tvv4_1",text:"_text_1tvv4_18",isLoggedIn:"_isLoggedIn_1tvv4_25",isLoggedOut:"_isLoggedOut_1tvv4_29",icon:"_icon_1tvv4_39",logo:"_logo_1tvv4_44",lock:"_lock_1tvv4_49"};var Dh={};ke(Dh,{enUS:()=>vA,nlNL:()=>SA});var vA={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},SA={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var bo=S(w()),bC=({onLogIn:e})=>{let t=j(Dh),n=N("productName"),r=U(),o=R(pt),i=k("FloatingMenu",_C);if(o===null)return null;let s=()=>{o===!0?r($e(!0)):e()};return(0,bo.jsxs)("button",{className:(0,wC.default)(i.root,{[i.isLoggedIn]:o,[i.isLoggedOut]:!o}),onClick:s,children:[(0,bo.jsx)("div",{className:i.text,children:t(o?"search":"signin",{productName:n})}),(0,bo.jsxs)("div",{className:i.icon,children:[(0,bo.jsx)(xC,{className:i.logo,color:"pink"}),o===!1&&(0,bo.jsx)(SC,{className:i.lock})]})]})};async function jd(e){let n=await new Gt(e).get("/platform/config/",{version:null});return ne(n)}var we=S(w());var CC=yC("showTabHint",!0),Wa=class e{static version="10.10.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 Un(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[fC({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=>CC.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Ka(n)}),this.store=pC(c),this.broadcastEvents=new eC({debug:!0,deepdeskUrl:u,eventMap:Kw(this.store),createCustomChannel:l}),this.store.dispatch(ra),this.store.dispatch(Ca(CC.value())),this.store.dispatch(ra({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?(H.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(H.warn("Profile has not been loaded (yet)"),!0):(H.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Ai(null)),this.store.dispatch(Ln()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();pt(r)&&Fw(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(Ln())).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){H.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Zm({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(ic(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(sc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Jm(t))).payload}async postMessages(t){return(await this.store.dispatch(lc(t))).payload}async updateConversation(t){return(await this.store.dispatch(ac(t))).payload}resetConversation(){this.store.dispatch(ee()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(On());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(ra(t))}setVisitorInfo(t){this.store.dispatch(ow(t))}async setAgentInfo(t){await this.store.dispatch(Sa(t))}async setAgentSettings(t){await this.store.dispatch(jg(t))}async getAgentSettings(){return(await this.store.dispatch(Hg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(rd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(mc(t))}notifyKeyDown(t){this.store.dispatch(pc(t))}notifyPaste(t,n){this.store.dispatch(s_({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(o_(t))}notifyExternalSuggestion(t){this.store.dispatch(Bt(t)),this.store.dispatch(wn())}notifyEditSuggestion(t){this.store.dispatch(bw(t.contentType,t.suggestions)),this.store.dispatch(In({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(Cr({collapse:!1})),this.inputMediator&&this.store.dispatch(Zx({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(i_(cc(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(t_()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{if(n||!a||!i||t.shiftKey)return;this.store.dispatch(r_());let{selectedSuggestionIndex:p}=this.state.input;t.preventDefault(),!s&&(p===-1?this.store.dispatch(ia()):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(vr(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(vr(-1)),this.store.dispatch(ia()),t.preventDefault()):n||(this.store.dispatch(Cr({collapse:!0})),this.store.dispatch(Aw(!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(Ca(!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(a_()),this.store.dispatch(on([]))}handlingTimeStart(){this.state.handlingTime.startTime||(H.info("Start handling time"),this.store.dispatch(rC()))}handlingTimeStop(){this.state.handlingTime.startTime&&(H.info("Stop handling time"),this.store.dispatch(Od()))}logSendMessage(t){let n=Oh("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=Oh("overlayInput",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.store.dispatch(e_(this.state.overlayInput.metrics))}logHandlingTime(){let t=mC(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(oC())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(wn()),this.store.dispatch(no(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){H.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),H.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]=lo(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Nt.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]=lo(i,{appendTo:document.body});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,Nt.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 ao(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,Nt.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),H.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()?(H.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(u_(r.metrics))):H.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(!Md(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:f,inlineSuggestions:h,floatingMenu:m}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:g,isEmbedded:p,inlineSuggestions:h,floatingMenu:!!m}),n.automaticHandlingTime&&this.setupHandlingTime(t),ao(t),this.inputMediator=v||(Pr(t)?new Pn(t):new _o(t)),this.inputMediator.on("change",({plainText:b})=>{this.notifyInputChanged(b)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(l_({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:C})=>{this.notifyPaste(b,C)}),this.inputMediator.on("cut",({selectionText:b})=>{this.notifyCut(b)});let x=y&&gC(t,y)||void 0;if(h){let{customStyles:b,appendOverlayTo:C}=n;if(Pr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let E=this.createInlineContainer(t,"deepdesk-caret");(0,Nt.render)((0,we.jsx)(xo,{store:this.store,customStyles:b,children:(0,we.jsx)(ho,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(D1,{})})}),E),this.inputMediator.on("caret",P=>{this.store.dispatch(on([])),P?(E.style.display="block",E.style.top=`${P.top}px`,E.style.left=`${P.left}px`):E.style.display="none"});let I=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof m=="object"&&"appendOverlayTo"in m?m.appendOverlayTo:C},b==null?void 0:b.floatingMenuRootNode);(0,Nt.render)((0,we.jsx)(xo,{store:this.store,customStyles:b,children:(0,we.jsx)(ho,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(bC,{onLogIn:()=>this.loginViaPopup().catch(P=>H.warn(P.message))})})}),I)}else{let b=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:f,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:f},r==null?void 0:r.suggestionsRootNode);(0,Nt.render)((0,we.jsx)(xo,{store:this.store,customStyles:r,children:(0,we.jsx)(ho,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(sb,{inputElement:t})})}),b),(0,Nt.render)((0,we.jsx)(xo,{store:this.store,customStyles:r,children:(0,we.jsx)(ho,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(K1,{onLogIn:()=>this.loginViaPopup().catch(E=>H.warn(E.message))})})}),C)}(0,Nt.render)((0,we.jsx)(xo,{store:this.store,customStyles:r,children:(0,we.jsx)(ho,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(I1,{})})}),this.createContainer("deepdesk-overlays"));let _;this.inputMediator.on("selection",b=>{clearTimeout(_),b===null?_=setTimeout(()=>{b!==null&&this.store.dispatch(tg(b))},500):this.store.dispatch(tg(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(Li(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Li(!0))),this.store.dispatch(Jx({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&&H.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,Nt.render)((0,we.jsx)(xo,{store:this.store,customStyles:r,children:(0,we.jsx)(ho,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(Qb,{onLogIn:()=>this.loginViaPopup().catch(s=>H.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Nt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Dd(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){hC(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Na());let t=Tr(this.state);t&&this.store.dispatch(ra({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async loginViaPopup(){let t=this.state.settings.adminUrl,n=new URL(t),r=await jd(n.origin);return new Promise((o,i)=>{let s=new MessageChannel,a=s.port1,l=new URL(r.config.platform.hasSso?`${t}/platform/sso/`:`${t}/admin/`);l.searchParams.append("redirect","/sdk/popup/close.html");let u=!1,c=()=>{p&&!p.closed&&p.close(),window.removeEventListener("message",d),clearInterval(g)};a.onmessage=async v=>{var y,f;if((y=v.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((f=v.data)==null?void 0:f.jwt),await this.isLoggedIn(),this.broadcastEvents.send(ka),c(),u=!0,s.port1.close(),o()}catch(h){i(h)}};let p=window.open(l.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");p===null&&i(new Error("Popup blocked by browser"));let d=async v=>{var y;if(v.origin===l.origin)switch((y=v.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{p==null||p.postMessage({type:"deepdesk-popup-create-channel"},l.origin,[s.port2]);break}case"deepdesk-popup-error":{c(),v.data.message==="Timeout"&&H.warn("Popup timed out. Check if the account's platform url is configured correctly."),i(new Error(v.data.message));break}}};window.addEventListener("message",d);let g=setInterval(()=>{p&&!p.closed||(c(),u||i(new Error("Popup closed by user")))},200);this.unmountHandlers.push(c)})}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(H.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;H.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=ad(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch($t()):this.store.dispatch(Kt(r))})}catch(r){this.handleError(r)}}};async function EC(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 TC(e,t,n={}){let r=n.replace?Lr(e,n.replace.start,n.replace.end):Ui(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?Lr(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()}})}function xA(e){let t=document.createElement("template");return t.innerHTML=e,t.content}function _A(e){let t=document.createDocumentFragment();return e.split(`
27
27
  `).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br")),t.appendChild(document.createTextNode(n))}),t}function kC(e,t){return!e.contains(t)||t===e?null:t.parentNode===e?t:kC(e,t.parentNode)}async function PC(e,t,{isBlock:n,isHTML:r}={}){let o;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let i=()=>{let s=e.ownerDocument.defaultView??window,a=s.getSelection();if((!a||a.rangeCount===0)&&(e.focus(),a=s.getSelection()),!a||a.rangeCount===0)return;let l=a.getRangeAt(0);if(!l)return;o=document.createElement("span"),l.insertNode(o);let u=r?xA(t):_A(t);if(n){let c=kC(e,l.startContainer)??e.firstChild;e.insertBefore(u,(c==null?void 0:c.nextSibling)??null)}else l.insertNode(u),l.collapse(!1)};return Promise.resolve(i()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!o)try{o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function RC(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function IC(e,t,n){await new Un(e).authenticateWithKey(t,n)}async function wA(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 LC(e,t){let n=await wA(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 jC(bA);})();
28
28
  /*! Bundled license information:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepdesk/deepdesk-sdk",
3
- "version": "10.9.3-beta.7",
3
+ "version": "10.10.0",
4
4
  "description": "Deepdesk SDK",
5
5
  "author": "Lukas Batteau",
6
6
  "license": "ISC",