@deepdesk/deepdesk-sdk 10.10.2-beta.0 → 10.10.2

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 la=require("react/jsx-runtime"),fh={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},wu=({className:t,color:e})=>(0,la.jsx)("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,la.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:fh[e||"pink"]})});var Tu={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 ca={};W(ca,{enUS:()=>hh,nlNL:()=>yh});var hh={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},yh={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Ru=require("react-redux"),Xt=require("react/jsx-runtime"),Iu=({onLogIn:t})=>{let e=T(ca),o=C("productName"),n=(0,Ru.useDispatch)(),s=(0,ku.useSelector)(ue),r=v("FloatingMenu",Tu);if(s===null)return null;let i=()=>{s===!0?n(Y(!0)):t()};return(0,Xt.jsxs)("button",{className:(0,Eu.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)(wu,{className:r.logo,color:"pink"}),s===!1&&(0,Xt.jsx)(Cu,{className:r.lock})]})]})};async function Er(t){let o=await new Ne(t).get("/platform/config/",{version:null});return M(o)}var j=require("react/jsx-runtime");var Pu=xu("showTabHint",!0),kn=class t{static version="10.10.2-beta.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:[yu({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=>Pu.update(d),sendEvent:(d,u)=>this.deepdeskApi.sendEvent(d,u)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new En(o)}),this.store=hu(p),this.broadcastEvents=new nu({debug:!0,deepdeskUrl:c,eventMap:Dc(this.store),createCustomChannel:l}),this.store.dispatch(Bo),this.store.dispatch(en(Pu.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(Mr({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(jn(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Vn({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Nr(e))).payload}async postMessages(e){return(await this.store.dispatch(Wn(e))).payload}async updateConversation(e){return(await this.store.dispatch(qn(e))).payload}resetConversation(){this.store.dispatch(N()),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($l(e))}async setAgentInfo(e){await this.store.dispatch(Xo(e))}async setAgentSettings(e){await this.store.dispatch(ui(e))}async getAgentSettings(){return(await this.store.dispatch(gi())).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(Jn(e))}notifyKeyDown(e){this.store.dispatch(Qn(e))}notifyPaste(e,o){this.store.dispatch(Ja({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Qa(e))}notifyExternalSuggestion(e){this.store.dispatch(ke(e)),this.store.dispatch(je())}notifyEditSuggestion(e){this.store.dispatch(gc(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(Va({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(Za($n(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Ga()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{if(o||!a||!r||e.shiftKey)return;this.store.dispatch(Xa());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(wc(!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(Ya()),this.store.dispatch(He([]))}handlingTimeStart(){this.state.handlingTime.startTime||(E.info("Start handling time"),this.store.dispatch(au()))}handlingTimeStop(){this.state.handlingTime.startTime&&(E.info("Stop handling time"),this.store.dispatch(Sr()))}logSendMessage(e){let o=ia("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=ia("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Wa(this.state.overlayInput.metrics))}logHandlingTime(){let e=vu(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(lu())}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,onMoveStart:()=>{s.style.display="none"}});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 Lt(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(tl(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(!Cr(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:m,closestScrollSelector:f,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),Lt(e),this.inputMediator=m||(xt(e)?new We(e):new Gt(e)),this.inputMediator.on("change",({plainText:_})=>{this.notifyInputChanged(_)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(el({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",_=>{this.notifyKeyDown(_)}),this.inputMediator.on("paste",({pastedText:_,selectionText:A})=>{this.notifyPaste(_,A)}),this.inputMediator.on("cut",({selectionText:_})=>{this.notifyCut(_)});let x=f&&Su(e,f)||void 0;if(w){let{customStyles:_,appendOverlayTo:A}=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)(qt,{store:this.store,customStyles:_,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(Ip,{})})}),O),this.inputMediator.on("caret",L=>{this.store.dispatch(He([])),L?(O.style.display="block",O.style.top=`${L.top}px`,O.style.left=`${L.left}px`):O.style.display="none"});let se=this.overlayContainerFactory("floating-menu",x||e,{appendTo:typeof y=="object"&&"appendOverlayTo"in y?y.appendOverlayTo:A},_==null?void 0:_.floatingMenuRootNode);(0,we.render)((0,j.jsx)(qt,{store:this.store,customStyles:_,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(Iu,{onLogIn:()=>this.loginViaPopup().catch(L=>E.warn(L.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),A=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:h},n==null?void 0:n.suggestionsRootNode);(0,we.render)((0,j.jsx)(qt,{store:this.store,customStyles:n,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(id,{inputElement:e})})}),_),(0,we.render)((0,j.jsx)(qt,{store:this.store,customStyles:n,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(Bp,{onLogIn:()=>this.loginViaPopup().catch(O=>E.warn(O.message))})})}),A)}(0,we.render)((0,j.jsx)(qt,{store:this.store,customStyles:n,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(bp,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",_=>{clearTimeout(b),_===null?b=setTimeout(()=>{_!==null&&this.store.dispatch(Dr(_))},500):this.store.dispatch(Dr(_))}),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)(qt,{store:this.store,customStyles:n,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(Yd,{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=wr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){_u(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(mn());let e=St(this.state);e&&(await this.store.dispatch(dn()),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 Er(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 m=>{var f,h;if((f=m.data)!=null&&f.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((h=m.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 m=>{var f;if(m.origin===l.origin)switch((f=m.data)==null?void 0:f.type){case"deepdesk-popup-loaded":{d==null||d.postMessage({type:"deepdesk-popup-create-channel"},l.origin,[i.port2]);break}case"deepdesk-popup-error":{p(),m.data.message==="Timeout"&&E.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(m.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=Ws(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(Le()):this.store.dispatch(Pe(n))})}catch(n){this.handleError(n)}}};async function Au(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 Lu(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 la=require("react/jsx-runtime"),fh={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},wu=({className:t,color:e})=>(0,la.jsx)("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,la.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:fh[e||"pink"]})});var Tu={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 ca={};W(ca,{enUS:()=>hh,nlNL:()=>yh});var hh={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},yh={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Ru=require("react-redux"),Xt=require("react/jsx-runtime"),Iu=({onLogIn:t})=>{let e=T(ca),o=C("productName"),n=(0,Ru.useDispatch)(),s=(0,ku.useSelector)(ue),r=v("FloatingMenu",Tu);if(s===null)return null;let i=()=>{s===!0?n(Y(!0)):t()};return(0,Xt.jsxs)("button",{className:(0,Eu.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)(wu,{className:r.logo,color:"pink"}),s===!1&&(0,Xt.jsx)(Cu,{className:r.lock})]})]})};async function Er(t){let o=await new Ne(t).get("/platform/config/",{version:null});return M(o)}var j=require("react/jsx-runtime");var Pu=xu("showTabHint",!0),kn=class t{static version="10.10.2";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:[yu({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=>Pu.update(d),sendEvent:(d,u)=>this.deepdeskApi.sendEvent(d,u)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new En(o)}),this.store=hu(p),this.broadcastEvents=new nu({debug:!0,deepdeskUrl:c,eventMap:Dc(this.store),createCustomChannel:l}),this.store.dispatch(Bo),this.store.dispatch(en(Pu.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(Mr({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(jn(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Vn({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Nr(e))).payload}async postMessages(e){return(await this.store.dispatch(Wn(e))).payload}async updateConversation(e){return(await this.store.dispatch(qn(e))).payload}resetConversation(){this.store.dispatch(N()),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($l(e))}async setAgentInfo(e){await this.store.dispatch(Xo(e))}async setAgentSettings(e){await this.store.dispatch(ui(e))}async getAgentSettings(){return(await this.store.dispatch(gi())).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(Jn(e))}notifyKeyDown(e){this.store.dispatch(Qn(e))}notifyPaste(e,o){this.store.dispatch(Ja({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Qa(e))}notifyExternalSuggestion(e){this.store.dispatch(ke(e)),this.store.dispatch(je())}notifyEditSuggestion(e){this.store.dispatch(gc(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(Va({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(Za($n(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Ga()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{if(o||!a||!r||e.shiftKey)return;this.store.dispatch(Xa());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(wc(!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(Ya()),this.store.dispatch(He([]))}handlingTimeStart(){this.state.handlingTime.startTime||(E.info("Start handling time"),this.store.dispatch(au()))}handlingTimeStop(){this.state.handlingTime.startTime&&(E.info("Stop handling time"),this.store.dispatch(Sr()))}logSendMessage(e){let o=ia("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=ia("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Wa(this.state.overlayInput.metrics))}logHandlingTime(){let e=vu(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(lu())}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,onMoveStart:()=>{s.style.display="none"}});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 Lt(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(tl(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(!Cr(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:m,closestScrollSelector:f,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),Lt(e),this.inputMediator=m||(xt(e)?new We(e):new Gt(e)),this.inputMediator.on("change",({plainText:_})=>{this.notifyInputChanged(_)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(el({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",_=>{this.notifyKeyDown(_)}),this.inputMediator.on("paste",({pastedText:_,selectionText:A})=>{this.notifyPaste(_,A)}),this.inputMediator.on("cut",({selectionText:_})=>{this.notifyCut(_)});let x=f&&Su(e,f)||void 0;if(w){let{customStyles:_,appendOverlayTo:A}=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)(qt,{store:this.store,customStyles:_,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(Ip,{})})}),O),this.inputMediator.on("caret",L=>{this.store.dispatch(He([])),L?(O.style.display="block",O.style.top=`${L.top}px`,O.style.left=`${L.left}px`):O.style.display="none"});let se=this.overlayContainerFactory("floating-menu",x||e,{appendTo:typeof y=="object"&&"appendOverlayTo"in y?y.appendOverlayTo:A},_==null?void 0:_.floatingMenuRootNode);(0,we.render)((0,j.jsx)(qt,{store:this.store,customStyles:_,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(Iu,{onLogIn:()=>this.loginViaPopup().catch(L=>E.warn(L.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),A=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:h},n==null?void 0:n.suggestionsRootNode);(0,we.render)((0,j.jsx)(qt,{store:this.store,customStyles:n,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(id,{inputElement:e})})}),_),(0,we.render)((0,j.jsx)(qt,{store:this.store,customStyles:n,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(Bp,{onLogIn:()=>this.loginViaPopup().catch(O=>E.warn(O.message))})})}),A)}(0,we.render)((0,j.jsx)(qt,{store:this.store,customStyles:n,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(bp,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",_=>{clearTimeout(b),_===null?b=setTimeout(()=>{_!==null&&this.store.dispatch(Dr(_))},500):this.store.dispatch(Dr(_))}),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)(qt,{store:this.store,customStyles:n,children:(0,j.jsx)(Ut,{broadcastEvents:this.broadcastEvents,children:(0,j.jsx)(Yd,{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=wr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){_u(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(mn());let e=St(this.state);e&&(await this.store.dispatch(dn()),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 Er(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 m=>{var f,h;if((f=m.data)!=null&&f.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((h=m.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 m=>{var f;if(m.origin===l.origin)switch((f=m.data)==null?void 0:f.type){case"deepdesk-popup-loaded":{d==null||d.postMessage({type:"deepdesk-popup-create-channel"},l.origin,[i.port2]);break}case"deepdesk-popup-error":{p(),m.data.message==="Timeout"&&E.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(m.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=Ws(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(Le()):this.store.dispatch(Pe(n))})}catch(n){this.handleError(n)}}};async function Au(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 Lu(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 vh(t){let e=document.createElement("template");return e.innerHTML=t,e.content}function Sh(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 Mu(t,e){return!t.contains(e)||e===t?null:e.parentNode===t?e:Mu(t,e.parentNode)}async function Nu(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?vh(e):Sh(e);if(o){let p=Mu(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 Ou(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function Du(t,e,o){await new at(t).authenticateWithKey(e,o)}async function _h(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 Hu(t,e){let o=await _h(e),n=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[o]}),t.dispatchEvent(n)}finally{Object.hasOwn(t,"files")&&delete t.files}}0&&(module.exports={Card,ContentEditableInput,DeepdeskAPI,DeepdeskSDK,HTTPClient,InputMediator,InputType,KeyboardHint,Label,Locale,Section,SectionList,Sources,Suggestion,SuggestionList,TextAreaInput,ToggleButton,attachFile,authenticateWithKey,createFullRange,createOverlayContainer,createRangeFromOffsets,escapeHTML,fetchPlatformConfig,formatTextMarkup,getRangeOffsets,getRangeText,insertCKEditor,isSupportedInputElement,updateContentEditable,updateTextArea,useStyles,waitForElementVisibilityChange});
package/dist/index.esm.js CHANGED
@@ -6,6 +6,6 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
6
6
  c-17.9,17.9-27.3,40.1-27.3,65.7C163.4,163,163.4,233,163.4,233z M465.5,267.9V477c0,9.4-3.4,17.9-10.2,24.7
7
7
  c-6.8,6.8-15.4,10.2-24.7,10.2h-349c-9.4,0-17.9-3.4-24.7-10.2c-6.8-6.8-10.2-15.4-10.2-24.7V267.9c0-9.4,3.4-17.9,10.2-24.7
8
8
  c6.8-6.8,15.4-10.2,24.7-10.2h11.9v-70c0-44.4,16.2-82.8,47.8-115.2S212.1,0,256.4,0s82.8,16.2,115.2,47.8
9
- c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});import{jsx as ld}from"react/jsx-runtime";var Nv={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},cd=({className:t,color:e})=>ld("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:ld("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:Nv[e||"pink"]})});var pd={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:()=>Ov,nlNL:()=>Dv});var Ov={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},Dv={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};import{useDispatch as Fv}from"react-redux";import{jsx as ii,jsxs as dd}from"react/jsx-runtime";var ud=({onLogIn:t})=>{let e=T(ri),o=C("productName"),n=Fv(),s=Bv(oe),r=v("FloatingMenu",pd);if(s===null)return null;let i=()=>{s===!0?n(W(!0)):t()};return dd("button",{className:Hv(r.root,{[r.isLoggedIn]:s,[r.isLoggedOut]:!s}),onClick:i,children:[ii("div",{className:r.text,children:e(s?"search":"signin",{productName:o})}),dd("div",{className:r.icon,children:[ii(cd,{className:r.logo,color:"pink"}),s===!1&&ii(ad,{className:r.lock})]})]})};async function ai(t){let o=await new ve(t).get("/platform/config/",{version:null});return A(o)}import{jsx as U}from"react/jsx-runtime";var gd=rd("showTabHint",!0),ls=class t{static version="10.10.2-beta.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:[td({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=>gd.update(d),sendEvent:(d,u)=>this.deepdeskApi.sendEvent(d,u)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new Co(o)}),this.store=ed(p),this.broadcastEvents=new zp({debug:!0,deepdeskUrl:c,eventMap:El(this.store),createCustomChannel:l}),this.store.dispatch(Vt),this.store.dispatch(no(gd.value())),this.store.dispatch(Vt({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(Oo(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Do({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(Bo(e))).payload}async updateConversation(e){return(await this.store.dispatch(Ho(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(Vt(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(Vo(e))}notifyKeyDown(e){this.store.dispatch(zo(e))}notifyPaste(e,o){this.store.dispatch(Ni({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Li(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(Ko(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Ii()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{if(o||!a||!r||e.shiftKey)return;this.store.dispatch(Ai());let{selectedSuggestionIndex:d}=this.state.input;e.preventDefault(),!i&&(d===-1?this.store.dispatch(qt()):this.stageSelectedSuggestion({inputType:"arrow"}))};switch(e.key){case"Up":case"ArrowUp":i?p():c();return;case"Down":case"ArrowDown":{i?c():p();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(Me(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Me(-1)),this.store.dispatch(qt()),e.preventDefault()):o||(this.store.dispatch(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(qp()))}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(Ri(this.state.overlayInput.metrics))}logHandlingTime(){let e=od(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Wp())}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,onMoveStart:()=>{s.style.display="none"}});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:m,closestScrollSelector:f,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=m||(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:I})=>{this.notifyPaste(_,I)}),this.inputMediator.on("cut",({selectionText:_})=>{this.notifyCut(_)});let x=f&&nd(e,f)||void 0;if(w){let{customStyles:_,appendOverlayTo:I}=o;if(Ue(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let N=this.createInlineContainer(e,"deepdesk-caret");Ft(U(tt,{store:this.store,customStyles:_,children:U(et,{broadcastEvents:this.broadcastEvents,children:U(yc,{})})}),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:I},_==null?void 0:_.floatingMenuRootNode);Ft(U(tt,{store:this.store,customStyles:_,children:U(et,{broadcastEvents:this.broadcastEvents,children:U(ud,{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),I=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:h},n==null?void 0:n.suggestionsRootNode);Ft(U(tt,{store:this.store,customStyles:n,children:U(et,{broadcastEvents:this.broadcastEvents,children:U(Gc,{inputElement:e})})}),_),Ft(U(tt,{store:this.store,customStyles:n,children:U(et,{broadcastEvents:this.broadcastEvents,children:U(Ec,{onLogIn:()=>this.loginViaPopup().catch(N=>E.warn(N.message))})})}),I)}Ft(U(tt,{store:this.store,customStyles:n,children:U(et,{broadcastEvents:this.broadcastEvents,children:U(dc,{})})}),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(U(tt,{store:this.store,customStyles:n,children:U(et,{broadcastEvents:this.broadcastEvents,children:U(Bp,{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){sd(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(uo());let e=Ke(this.state);e&&(await this.store.dispatch(po()),this.store.dispatch(Vt({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 m=>{var f,h;if((f=m.data)!=null&&f.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((h=m.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 m=>{var f;if(m.origin===l.origin)switch((f=m.data)==null?void 0:f.type){case"deepdesk-popup-loaded":{d==null||d.postMessage({type:"deepdesk-popup-create-channel"},l.origin,[i.port2]);break}case"deepdesk-popup-error":{p(),m.data.message==="Timeout"&&E.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(m.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 Kv(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 Uv(t,e,o={}){let n=o.replace?rt(t,o.replace.start,o.replace.end):xo(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 ld}from"react/jsx-runtime";var Nv={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},cd=({className:t,color:e})=>ld("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:ld("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:Nv[e||"pink"]})});var pd={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:()=>Ov,nlNL:()=>Dv});var Ov={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},Dv={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};import{useDispatch as Fv}from"react-redux";import{jsx as ii,jsxs as dd}from"react/jsx-runtime";var ud=({onLogIn:t})=>{let e=T(ri),o=C("productName"),n=Fv(),s=Bv(oe),r=v("FloatingMenu",pd);if(s===null)return null;let i=()=>{s===!0?n(W(!0)):t()};return dd("button",{className:Hv(r.root,{[r.isLoggedIn]:s,[r.isLoggedOut]:!s}),onClick:i,children:[ii("div",{className:r.text,children:e(s?"search":"signin",{productName:o})}),dd("div",{className:r.icon,children:[ii(cd,{className:r.logo,color:"pink"}),s===!1&&ii(ad,{className:r.lock})]})]})};async function ai(t){let o=await new ve(t).get("/platform/config/",{version:null});return A(o)}import{jsx as U}from"react/jsx-runtime";var gd=rd("showTabHint",!0),ls=class t{static version="10.10.2";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:[td({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=>gd.update(d),sendEvent:(d,u)=>this.deepdeskApi.sendEvent(d,u)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new Co(o)}),this.store=ed(p),this.broadcastEvents=new zp({debug:!0,deepdeskUrl:c,eventMap:El(this.store),createCustomChannel:l}),this.store.dispatch(Vt),this.store.dispatch(no(gd.value())),this.store.dispatch(Vt({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(Oo(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Do({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(Bo(e))).payload}async updateConversation(e){return(await this.store.dispatch(Ho(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(Vt(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(Vo(e))}notifyKeyDown(e){this.store.dispatch(zo(e))}notifyPaste(e,o){this.store.dispatch(Ni({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Li(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(Ko(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Ii()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{if(o||!a||!r||e.shiftKey)return;this.store.dispatch(Ai());let{selectedSuggestionIndex:d}=this.state.input;e.preventDefault(),!i&&(d===-1?this.store.dispatch(qt()):this.stageSelectedSuggestion({inputType:"arrow"}))};switch(e.key){case"Up":case"ArrowUp":i?p():c();return;case"Down":case"ArrowDown":{i?c():p();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(Me(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Me(-1)),this.store.dispatch(qt()),e.preventDefault()):o||(this.store.dispatch(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(qp()))}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(Ri(this.state.overlayInput.metrics))}logHandlingTime(){let e=od(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Wp())}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,onMoveStart:()=>{s.style.display="none"}});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:m,closestScrollSelector:f,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=m||(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:I})=>{this.notifyPaste(_,I)}),this.inputMediator.on("cut",({selectionText:_})=>{this.notifyCut(_)});let x=f&&nd(e,f)||void 0;if(w){let{customStyles:_,appendOverlayTo:I}=o;if(Ue(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let N=this.createInlineContainer(e,"deepdesk-caret");Ft(U(tt,{store:this.store,customStyles:_,children:U(et,{broadcastEvents:this.broadcastEvents,children:U(yc,{})})}),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:I},_==null?void 0:_.floatingMenuRootNode);Ft(U(tt,{store:this.store,customStyles:_,children:U(et,{broadcastEvents:this.broadcastEvents,children:U(ud,{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),I=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:h},n==null?void 0:n.suggestionsRootNode);Ft(U(tt,{store:this.store,customStyles:n,children:U(et,{broadcastEvents:this.broadcastEvents,children:U(Gc,{inputElement:e})})}),_),Ft(U(tt,{store:this.store,customStyles:n,children:U(et,{broadcastEvents:this.broadcastEvents,children:U(Ec,{onLogIn:()=>this.loginViaPopup().catch(N=>E.warn(N.message))})})}),I)}Ft(U(tt,{store:this.store,customStyles:n,children:U(et,{broadcastEvents:this.broadcastEvents,children:U(dc,{})})}),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(U(tt,{store:this.store,customStyles:n,children:U(et,{broadcastEvents:this.broadcastEvents,children:U(Bp,{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){sd(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(uo());let e=Ke(this.state);e&&(await this.store.dispatch(po()),this.store.dispatch(Vt({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 m=>{var f,h;if((f=m.data)!=null&&f.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((h=m.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 m=>{var f;if(m.origin===l.origin)switch((f=m.data)==null?void 0:f.type){case"deepdesk-popup-loaded":{d==null||d.postMessage({type:"deepdesk-popup-create-channel"},l.origin,[i.port2]);break}case"deepdesk-popup-error":{p(),m.data.message==="Timeout"&&E.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(m.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 Kv(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 Uv(t,e,o={}){let n=o.replace?rt(t,o.replace.start,o.replace.end):xo(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 zv(t){let e=document.createElement("template");return e.innerHTML=t,e.content}function jv(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 md(t,e){return!t.contains(e)||e===t?null:e.parentNode===t?e:md(t,e.parentNode)}async function Vv(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?zv(e):jv(e);if(o){let p=md(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 qv(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function Wv(t,e,o){await new je(t).authenticateWithKey(e,o)}async function Gv(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 $v(t,e){let o=await Gv(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,qe as InputType,gs as KeyboardHint,ms as Label,Lo as Locale,Ve as Section,hs as SectionList,ue as Sources,D as Suggestion,re as SuggestionList,Oe as TextAreaInput,ut as ToggleButton,$v as attachFile,Wv as authenticateWithKey,xo as createFullRange,xt as createOverlayContainer,rt as createRangeFromOffsets,Qt as escapeHTML,ai as fetchPlatformConfig,qv as formatTextMarkup,os as getRangeOffsets,ns as getRangeText,Vv as insertCKEditor,oi as isSupportedInputElement,Uv as updateContentEditable,Kv 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()),xA={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},wC=({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:xA[t||"pink"]})});var bC={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={};Pe(Dh,{enUS:()=>_A,nlNL:()=>wA});var _A={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},wA={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var bo=S(w()),EC=({onLogIn:e})=>{let t=j(Dh),n=N("productName"),r=z(),o=R(pt),i=k("FloatingMenu",bC);if(o===null)return null;let s=()=>{o===!0?r($e(!0)):e()};return(0,bo.jsxs)("button",{className:(0,CC.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)(wC,{className:i.logo,color:"pink"}),o===!1&&(0,bo.jsx)(_C,{className:i.lock})]})]})};async function jd(e){let n=await new Gt(e).get("/platform/config/",{version:null});return Z(n)}var we=S(w());var TC=SC("showTabHint",!0),$a=class e{static version="10.10.2-beta.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:[gC({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=>TC.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Wa(n)}),this.store=mC(c),this.broadcastEvents=new nC({debug:!0,deepdeskUrl:u,eventMap:Vw(this.store),createCustomChannel:l}),this.store.dispatch(ra),this.store.dispatch(Ca(TC.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?(B.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(B.warn("Profile has not been loaded (yet)"),!0):(B.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(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){B.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(sc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(ac({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(uc(t))).payload}async updateConversation(t){return(await this.store.dispatch(lc(t))).payload}resetConversation(){this.store.dispatch(te()),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(Bg())).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(gc(t))}notifyKeyDown(t){this.store.dispatch(fc(t))}notifyPaste(t,n){this.store.dispatch(s_({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(o_(t))}notifyExternalSuggestion(t){this.store.dispatch(Ht(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_(dc(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(Ht({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||(B.info("Start handling time"),this.store.dispatch(iC()))}handlingTimeStop(){this.state.handlingTime.startTime&&(B.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=hC(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(sC())}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(Ht({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){B.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),B.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=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,onMoveStart:()=>{o.style.display="none"}});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),B.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(B.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(u_(r.metrics))):B.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!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:y,closestScrollSelector:v,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=y||(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=v&&yC(t,v)||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)(j1,{})})}),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)(EC,{onLogIn:()=>this.loginViaPopup().catch(P=>B.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)(lb,{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)($1,{onLogIn:()=>this.loginViaPopup().catch(E=>B.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)(A1,{})})}),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&&B.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)(Zb,{onLogIn:()=>this.loginViaPopup().catch(s=>B.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){vC(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Ma());let t=Tr(this.state);t&&(await this.store.dispatch(Oa()),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 y=>{var v,f;if((v=y.data)!=null&&v.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((f=y.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 y=>{var v;if(y.origin===l.origin)switch((v=y.data)==null?void 0:v.type){case"deepdesk-popup-loaded":{p==null||p.postMessage({type:"deepdesk-popup-create-channel"},l.origin,[s.port2]);break}case"deepdesk-popup-error":{c(),y.data.message==="Timeout"&&B.warn("Popup timed out. Check if the account's platform url is configured correctly."),i(new Error(y.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(B.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;B.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=ad(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch($t()):this.store.dispatch(Vt(r))})}catch(r){this.handleError(r)}}};async function kC(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 PC(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()),xA={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},wC=({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:xA[t||"pink"]})});var bC={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={};Pe(Dh,{enUS:()=>_A,nlNL:()=>wA});var _A={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},wA={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var bo=S(w()),EC=({onLogIn:e})=>{let t=j(Dh),n=N("productName"),r=z(),o=R(pt),i=k("FloatingMenu",bC);if(o===null)return null;let s=()=>{o===!0?r($e(!0)):e()};return(0,bo.jsxs)("button",{className:(0,CC.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)(wC,{className:i.logo,color:"pink"}),o===!1&&(0,bo.jsx)(_C,{className:i.lock})]})]})};async function jd(e){let n=await new Gt(e).get("/platform/config/",{version:null});return Z(n)}var we=S(w());var TC=SC("showTabHint",!0),$a=class e{static version="10.10.2";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:[gC({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=>TC.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Wa(n)}),this.store=mC(c),this.broadcastEvents=new nC({debug:!0,deepdeskUrl:u,eventMap:Vw(this.store),createCustomChannel:l}),this.store.dispatch(ra),this.store.dispatch(Ca(TC.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?(B.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(B.warn("Profile has not been loaded (yet)"),!0):(B.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(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){B.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(sc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(ac({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(uc(t))).payload}async updateConversation(t){return(await this.store.dispatch(lc(t))).payload}resetConversation(){this.store.dispatch(te()),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(Bg())).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(gc(t))}notifyKeyDown(t){this.store.dispatch(fc(t))}notifyPaste(t,n){this.store.dispatch(s_({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(o_(t))}notifyExternalSuggestion(t){this.store.dispatch(Ht(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_(dc(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(Ht({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||(B.info("Start handling time"),this.store.dispatch(iC()))}handlingTimeStop(){this.state.handlingTime.startTime&&(B.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=hC(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(sC())}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(Ht({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){B.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),B.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=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,onMoveStart:()=>{o.style.display="none"}});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),B.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(B.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(u_(r.metrics))):B.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!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:y,closestScrollSelector:v,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=y||(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=v&&yC(t,v)||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)(j1,{})})}),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)(EC,{onLogIn:()=>this.loginViaPopup().catch(P=>B.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)(lb,{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)($1,{onLogIn:()=>this.loginViaPopup().catch(E=>B.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)(A1,{})})}),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&&B.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)(Zb,{onLogIn:()=>this.loginViaPopup().catch(s=>B.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){vC(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Ma());let t=Tr(this.state);t&&(await this.store.dispatch(Oa()),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 y=>{var v,f;if((v=y.data)!=null&&v.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((f=y.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 y=>{var v;if(y.origin===l.origin)switch((v=y.data)==null?void 0:v.type){case"deepdesk-popup-loaded":{p==null||p.postMessage({type:"deepdesk-popup-create-channel"},l.origin,[s.port2]);break}case"deepdesk-popup-error":{c(),y.data.message==="Timeout"&&B.warn("Popup timed out. Check if the account's platform url is configured correctly."),i(new Error(y.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(B.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;B.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=ad(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch($t()):this.store.dispatch(Vt(r))})}catch(r){this.handleError(r)}}};async function kC(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 PC(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 bA(e){let t=document.createElement("template");return t.innerHTML=e,t.content}function CA(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 RC(e,t){return!e.contains(t)||t===e?null:t.parentNode===e?t:RC(e,t.parentNode)}async function IC(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?bA(t):CA(t);if(n){let c=RC(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 LC(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function AC(e,t,n){await new Un(e).authenticateWithKey(t,n)}async function EA(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 OC(e,t){let n=await EA(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 HC(TA);})();
28
28
  /*! Bundled license information:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepdesk/deepdesk-sdk",
3
- "version": "10.10.2-beta.0",
3
+ "version": "10.10.2",
4
4
  "description": "Deepdesk SDK",
5
5
  "author": "Lukas Batteau",
6
6
  "license": "ISC",