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

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 ca=require("react/jsx-runtime"),yh={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},Tu=({className:t,color:e})=>(0,ca.jsx)("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,ca.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:yh[e||"pink"]})});var Eu={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 pa={};W(pa,{enUS:()=>vh,nlNL:()=>Sh});var vh={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},Sh={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Iu=require("react-redux"),Xt=require("react/jsx-runtime"),Pu=({onLogIn:t})=>{let e=w(pa),o=C("productName"),n=(0,Iu.useDispatch)(),s=(0,Ru.useSelector)(ue),r=v("FloatingMenu",Eu);if(s===null)return null;let i=()=>{s===!0?n(Y(!0)):t()};return(0,Xt.jsxs)("button",{className:(0,ku.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)(Tu,{className:r.logo,color:"pink"}),s===!1&&(0,Xt.jsx)(wu,{className:r.lock})]})]})};async function kr(t){let o=await new Ne(t).get("/platform/config/",{version:null});return M(o)}var j=require("react/jsx-runtime");var Au=bu("showTabHint",!0),kn=class t{static version="10.10.1-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:[vu({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=>Au.update(d),sendEvent:(d,u)=>this.deepdeskApi.sendEvent(d,u)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new En(o)}),this.store=yu(p),this.broadcastEvents=new su({debug:!0,deepdeskUrl:c,eventMap:Hc(this.store),createCustomChannel:l}),this.store.dispatch(Bo),this.store.dispatch(en(Au.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?(T.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(T.warn("Profile has not been loaded (yet)"),!0):(T.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)&&Pc(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){T.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(Nr({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(Or(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(Xl(e))}async setAgentInfo(e){await this.store.dispatch(Xo(e))}async setAgentSettings(e){await this.store.dispatch(gi(e))}async getAgentSettings(){return(await this.store.dispatch(mi())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(Ds()),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(Ya({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Za(e))}notifyExternalSuggestion(e){this.store.dispatch(ke(e)),this.store.dispatch(je())}notifyEditSuggestion(e){this.store.dispatch(mc(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(qa({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(Ja($n(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch($a()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{if(o||!a||!r||e.shiftKey)return;this.store.dispatch(Qa());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(Tc(!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(el()),this.store.dispatch(He([]))}handlingTimeStart(){this.state.handlingTime.startTime||(T.info("Start handling time"),this.store.dispatch(lu()))}handlingTimeStop(){this.state.handlingTime.startTime&&(T.info("Stop handling time"),this.store.dispatch(_r()))}logSendMessage(e){let o=aa("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=aa("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Ga(this.state.overlayInput.metrics))}logHandlingTime(){let e=Su(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(cu())}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){T.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),T.error(i)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=Mt(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=Mt(r,{appendTo:document.body});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return 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),T.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()?(T.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(ol(n.metrics))):T.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(!wr(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:y,inlineSuggestions:E,floatingMenu:h}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:g,isEmbedded:d,inlineSuggestions:E,floatingMenu:!!h}),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(tl({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&&_u(e,f)||void 0;if(E){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)(Pp,{})})}),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 h=="object"&&"appendOverlayTo"in h?h.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)(Pu,{onLogIn:()=>this.loginViaPopup().catch(L=>T.warn(L.message))})})}),se)}else{let _=this.overlayContainerFactory("deepdesk-tab-completion",x||e,{appendTo:y,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),A=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:y},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)(ad,{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)(Fp,{onLogIn:()=>this.loginViaPopup().catch(O=>T.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)(Cp,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",_=>{clearTimeout(b),_===null?b=setTimeout(()=>{_!==null&&this.store.dispatch(Hr(_))},500):this.store.dispatch(Hr(_))}),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(Wa({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&&T.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)(eu,{onLogIn:()=>this.loginViaPopup().catch(i=>T.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=Tr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){xu(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 kr(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,y;if((f=m.data)!=null&&f.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((y=m.data)==null?void 0:y.jwt),await this.isLoggedIn(),this.broadcastEvents.send(nn),p(),c=!0,i.port1.close(),s()}catch(E){r(E)}};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"&&T.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(T.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;T.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=Gs(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 Lu(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 Mu(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 ca=require("react/jsx-runtime"),yh={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},Tu=({className:t,color:e})=>(0,ca.jsx)("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,ca.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:yh[e||"pink"]})});var Eu={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 pa={};W(pa,{enUS:()=>vh,nlNL:()=>Sh});var vh={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},Sh={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Iu=require("react-redux"),Xt=require("react/jsx-runtime"),Pu=({onLogIn:t})=>{let e=w(pa),o=C("productName"),n=(0,Iu.useDispatch)(),s=(0,Ru.useSelector)(ue),r=v("FloatingMenu",Eu);if(s===null)return null;let i=()=>{s===!0?n(Y(!0)):t()};return(0,Xt.jsxs)("button",{className:(0,ku.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)(Tu,{className:r.logo,color:"pink"}),s===!1&&(0,Xt.jsx)(wu,{className:r.lock})]})]})};async function kr(t){let o=await new Ne(t).get("/platform/config/",{version:null});return M(o)}var j=require("react/jsx-runtime");var Au=bu("showTabHint",!0),kn=class t{static version="10.10.1";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:[vu({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=>Au.update(d),sendEvent:(d,u)=>this.deepdeskApi.sendEvent(d,u)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new En(o)}),this.store=yu(p),this.broadcastEvents=new su({debug:!0,deepdeskUrl:c,eventMap:Hc(this.store),createCustomChannel:l}),this.store.dispatch(Bo),this.store.dispatch(en(Au.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?(T.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(T.warn("Profile has not been loaded (yet)"),!0):(T.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)&&Pc(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){T.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(Nr({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(Or(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(Xl(e))}async setAgentInfo(e){await this.store.dispatch(Xo(e))}async setAgentSettings(e){await this.store.dispatch(gi(e))}async getAgentSettings(){return(await this.store.dispatch(mi())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(Ds()),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(Ya({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Za(e))}notifyExternalSuggestion(e){this.store.dispatch(ke(e)),this.store.dispatch(je())}notifyEditSuggestion(e){this.store.dispatch(mc(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(qa({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(Ja($n(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch($a()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{if(o||!a||!r||e.shiftKey)return;this.store.dispatch(Qa());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(Tc(!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(el()),this.store.dispatch(He([]))}handlingTimeStart(){this.state.handlingTime.startTime||(T.info("Start handling time"),this.store.dispatch(lu()))}handlingTimeStop(){this.state.handlingTime.startTime&&(T.info("Stop handling time"),this.store.dispatch(_r()))}logSendMessage(e){let o=aa("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=aa("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Ga(this.state.overlayInput.metrics))}logHandlingTime(){let e=Su(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(cu())}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){T.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),T.error(i)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=Mt(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=Mt(r,{appendTo:document.body});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return 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),T.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()?(T.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(ol(n.metrics))):T.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(!wr(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:y,inlineSuggestions:E,floatingMenu:h}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:g,isEmbedded:d,inlineSuggestions:E,floatingMenu:!!h}),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(tl({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&&_u(e,f)||void 0;if(E){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)(Pp,{})})}),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 h=="object"&&"appendOverlayTo"in h?h.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)(Pu,{onLogIn:()=>this.loginViaPopup().catch(L=>T.warn(L.message))})})}),se)}else{let _=this.overlayContainerFactory("deepdesk-tab-completion",x||e,{appendTo:y,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),A=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:y},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)(ad,{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)(Fp,{onLogIn:()=>this.loginViaPopup().catch(O=>T.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)(Cp,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",_=>{clearTimeout(b),_===null?b=setTimeout(()=>{_!==null&&this.store.dispatch(Hr(_))},500):this.store.dispatch(Hr(_))}),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(Wa({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&&T.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)(eu,{onLogIn:()=>this.loginViaPopup().catch(i=>T.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=Tr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){xu(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 kr(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,y;if((f=m.data)!=null&&f.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((y=m.data)==null?void 0:y.jwt),await this.isLoggedIn(),this.broadcastEvents.send(nn),p(),c=!0,i.port1.close(),s()}catch(E){r(E)}};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"&&T.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(T.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;T.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=Gs(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 Lu(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 Mu(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 _h(t){let e=document.createElement("template");return e.innerHTML=t,e.content}function xh(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 Nu(t,e){return!t.contains(e)||e===t?null:e.parentNode===t?e:Nu(t,e.parentNode)}async function Ou(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?_h(e):xh(e);if(o){let p=Nu(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 Du(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function Hu(t,e,o){await new at(t).authenticateWithKey(e,o)}async function bh(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 Bu(t,e){let o=await bh(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 cd}from"react/jsx-runtime";var Dv={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},pd=({className:t,color:e})=>cd("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:cd("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:Dv[e||"pink"]})});var dd={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 ii={};j(ii,{enUS:()=>Hv,nlNL:()=>Bv});var Hv={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},Bv={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};import{useDispatch as Uv}from"react-redux";import{jsx as ai,jsxs as ud}from"react/jsx-runtime";var gd=({onLogIn:t})=>{let e=w(ii),o=C("productName"),n=Uv(),s=Kv(oe),r=v("FloatingMenu",dd);if(s===null)return null;let i=()=>{s===!0?n(W(!0)):t()};return ud("button",{className:Fv(r.root,{[r.isLoggedIn]:s,[r.isLoggedOut]:!s}),onClick:i,children:[ai("div",{className:r.text,children:e(s?"search":"signin",{productName:o})}),ud("div",{className:r.icon,children:[ai(pd,{className:r.logo,color:"pink"}),s===!1&&ai(ld,{className:r.lock})]})]})};async function li(t){let o=await new ve(t).get("/platform/config/",{version:null});return A(o)}import{jsx as U}from"react/jsx-runtime";var md=id("showTabHint",!0),cs=class t{static version="10.10.1-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:[od({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=>md.update(d),sendEvent:(d,u)=>this.deepdeskApi.sendEvent(d,u)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new Co(o)}),this.store=td(p),this.broadcastEvents=new jp({debug:!0,deepdeskUrl:c,eventMap:kl(this.store),createCustomChannel:l}),this.store.dispatch(Vt),this.store.dispatch(no(md.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?(T.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(T.warn("Profile has not been loaded (yet)"),!0):(T.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)&&_l(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){T.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(Cs({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(ws(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(Ha(e))}async setAgentInfo(e){await this.store.dispatch(Yt(e))}async setAgentSettings(e){await this.store.dispatch(sr(e))}async getAgentSettings(){return(await this.store.dispatch(rr())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(Tn()),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(Oi({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Mi(e))}notifyExternalSuggestion(e){this.store.dispatch(ie(e)),this.store.dispatch(_e())}notifyEditSuggestion(e){this.store.dispatch(il(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(ki({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(Ni(Ko(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Pi()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{if(o||!a||!r||e.shiftKey)return;this.store.dispatch(Li());let{selectedSuggestionIndex:d}=this.state.input;e.preventDefault(),!i&&(d===-1?this.store.dispatch(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(fl(!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(Di()),this.store.dispatch(ge([]))}handlingTimeStart(){this.state.handlingTime.startTime||(T.info("Start handling time"),this.store.dispatch(Wp()))}handlingTimeStop(){this.state.handlingTime.startTime&&(T.info("Stop handling time"),this.store.dispatch(is()))}logSendMessage(e){let o=ti("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=ti("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Ii(this.state.overlayInput.metrics))}logHandlingTime(){let e=nd(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Gp())}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){T.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),T.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(()=>{ls(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=xt(r,{appendTo:document.body});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{ls(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(()=>{ls(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),T.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()?(T.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Bi(n.metrics))):T.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(!ni(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:y,inlineSuggestions:E,floatingMenu:h}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:g,isEmbedded:d,inlineSuggestions:E,floatingMenu:!!h}),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(Hi({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&&sd(e,f)||void 0;if(E){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(vc,{})})}),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 h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:I},_==null?void 0:_.floatingMenuRootNode);Ft(U(tt,{store:this.store,customStyles:_,children:U(et,{broadcastEvents:this.broadcastEvents,children:U(gd,{onLogIn:()=>this.loginViaPopup().catch(P=>T.warn(P.message))})})}),$)}else{let _=this.overlayContainerFactory("deepdesk-tab-completion",x||e,{appendTo:y,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),I=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:y},n==null?void 0:n.suggestionsRootNode);Ft(U(tt,{store:this.store,customStyles:n,children:U(et,{broadcastEvents:this.broadcastEvents,children:U($c,{inputElement:e})})}),_),Ft(U(tt,{store:this.store,customStyles:n,children:U(et,{broadcastEvents:this.broadcastEvents,children:U(kc,{onLogIn:()=>this.loginViaPopup().catch(N=>T.warn(N.message))})})}),I)}Ft(U(tt,{store:this.store,customStyles:n,children:U(et,{broadcastEvents:this.broadcastEvents,children:U(uc,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",_=>{clearTimeout(b),_===null?b=setTimeout(()=>{_!==null&&this.store.dispatch(Es(_))},500):this.store.dispatch(Es(_))}),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(Ri({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&&T.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(Fp,{onLogIn:()=>this.loginViaPopup().catch(i=>T.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&ls(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=si(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){rd(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 li(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,y;if((f=m.data)!=null&&f.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((y=m.data)==null?void 0:y.jwt),await this.isLoggedIn(),this.broadcastEvents.send(ro),p(),c=!0,i.port1.close(),s()}catch(E){r(E)}};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"&&T.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(T.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;T.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=An(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 zv(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 jv(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 cd}from"react/jsx-runtime";var Dv={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},pd=({className:t,color:e})=>cd("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:cd("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:Dv[e||"pink"]})});var dd={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 ii={};j(ii,{enUS:()=>Hv,nlNL:()=>Bv});var Hv={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},Bv={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};import{useDispatch as Uv}from"react-redux";import{jsx as ai,jsxs as ud}from"react/jsx-runtime";var gd=({onLogIn:t})=>{let e=w(ii),o=C("productName"),n=Uv(),s=Kv(oe),r=v("FloatingMenu",dd);if(s===null)return null;let i=()=>{s===!0?n(W(!0)):t()};return ud("button",{className:Fv(r.root,{[r.isLoggedIn]:s,[r.isLoggedOut]:!s}),onClick:i,children:[ai("div",{className:r.text,children:e(s?"search":"signin",{productName:o})}),ud("div",{className:r.icon,children:[ai(pd,{className:r.logo,color:"pink"}),s===!1&&ai(ld,{className:r.lock})]})]})};async function li(t){let o=await new ve(t).get("/platform/config/",{version:null});return A(o)}import{jsx as U}from"react/jsx-runtime";var md=id("showTabHint",!0),cs=class t{static version="10.10.1";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:[od({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=>md.update(d),sendEvent:(d,u)=>this.deepdeskApi.sendEvent(d,u)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new Co(o)}),this.store=td(p),this.broadcastEvents=new jp({debug:!0,deepdeskUrl:c,eventMap:kl(this.store),createCustomChannel:l}),this.store.dispatch(Vt),this.store.dispatch(no(md.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?(T.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(T.warn("Profile has not been loaded (yet)"),!0):(T.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)&&_l(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){T.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(Cs({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(ws(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(Ha(e))}async setAgentInfo(e){await this.store.dispatch(Yt(e))}async setAgentSettings(e){await this.store.dispatch(sr(e))}async getAgentSettings(){return(await this.store.dispatch(rr())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(Tn()),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(Oi({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Mi(e))}notifyExternalSuggestion(e){this.store.dispatch(ie(e)),this.store.dispatch(_e())}notifyEditSuggestion(e){this.store.dispatch(il(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(ki({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(Ni(Ko(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Pi()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{if(o||!a||!r||e.shiftKey)return;this.store.dispatch(Li());let{selectedSuggestionIndex:d}=this.state.input;e.preventDefault(),!i&&(d===-1?this.store.dispatch(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(fl(!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(Di()),this.store.dispatch(ge([]))}handlingTimeStart(){this.state.handlingTime.startTime||(T.info("Start handling time"),this.store.dispatch(Wp()))}handlingTimeStop(){this.state.handlingTime.startTime&&(T.info("Stop handling time"),this.store.dispatch(is()))}logSendMessage(e){let o=ti("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=ti("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Ii(this.state.overlayInput.metrics))}logHandlingTime(){let e=nd(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Gp())}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){T.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),T.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(()=>{ls(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=xt(r,{appendTo:document.body});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{ls(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(()=>{ls(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),T.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()?(T.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Bi(n.metrics))):T.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(!ni(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:y,inlineSuggestions:E,floatingMenu:h}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:g,isEmbedded:d,inlineSuggestions:E,floatingMenu:!!h}),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(Hi({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&&sd(e,f)||void 0;if(E){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(vc,{})})}),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 h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:I},_==null?void 0:_.floatingMenuRootNode);Ft(U(tt,{store:this.store,customStyles:_,children:U(et,{broadcastEvents:this.broadcastEvents,children:U(gd,{onLogIn:()=>this.loginViaPopup().catch(P=>T.warn(P.message))})})}),$)}else{let _=this.overlayContainerFactory("deepdesk-tab-completion",x||e,{appendTo:y,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),I=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:y},n==null?void 0:n.suggestionsRootNode);Ft(U(tt,{store:this.store,customStyles:n,children:U(et,{broadcastEvents:this.broadcastEvents,children:U($c,{inputElement:e})})}),_),Ft(U(tt,{store:this.store,customStyles:n,children:U(et,{broadcastEvents:this.broadcastEvents,children:U(kc,{onLogIn:()=>this.loginViaPopup().catch(N=>T.warn(N.message))})})}),I)}Ft(U(tt,{store:this.store,customStyles:n,children:U(et,{broadcastEvents:this.broadcastEvents,children:U(uc,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",_=>{clearTimeout(b),_===null?b=setTimeout(()=>{_!==null&&this.store.dispatch(Es(_))},500):this.store.dispatch(Es(_))}),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(Ri({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&&T.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(Fp,{onLogIn:()=>this.loginViaPopup().catch(i=>T.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&ls(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=si(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){rd(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 li(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,y;if((f=m.data)!=null&&f.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((y=m.data)==null?void 0:y.jwt),await this.isLoggedIn(),this.broadcastEvents.send(ro),p(),c=!0,i.port1.close(),s()}catch(E){r(E)}};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"&&T.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(T.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;T.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=An(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 zv(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 jv(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 Vv(t){let e=document.createElement("template");return e.innerHTML=t,e.content}function qv(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 fd(t,e){return!t.contains(e)||e===t?null:e.parentNode===t?e:fd(t,e.parentNode)}async function Wv(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?Vv(e):qv(e);if(o){let p=fd(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 Gv(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function $v(t,e,o){await new je(t).authenticateWithKey(e,o)}async function Xv(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 Qv(t,e){let o=await Xv(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,cs as DeepdeskSDK,ve as HTTPClient,Ne as InputMediator,qe as InputType,ms as KeyboardHint,fs as Label,Lo as Locale,Ve as Section,ys as SectionList,ue as Sources,D as Suggestion,re as SuggestionList,Oe as TextAreaInput,ut as ToggleButton,Qv as attachFile,$v as authenticateWithKey,xo as createFullRange,xt as createOverlayContainer,rt as createRangeFromOffsets,Qt as escapeHTML,li as fetchPlatformConfig,Gv as formatTextMarkup,ns as getRangeOffsets,ss as getRangeText,Wv as insertCKEditor,ni as isSupportedInputElement,jv as updateContentEditable,zv as updateTextArea,v as useStyles,si 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 Dh=S(w()),wA={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},bC=({className:e,color:t})=>(0,Dh.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,Dh.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:wA[t||"pink"]})});var CC={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 Fh={};Pe(Fh,{enUS:()=>bA,nlNL:()=>CA});var bA={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},CA={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var bo=S(w()),TC=({onLogIn:e})=>{let t=j(Fh),n=N("productName"),r=z(),o=R(pt),i=k("FloatingMenu",CC);if(o===null)return null;let s=()=>{o===!0?r($e(!0)):e()};return(0,bo.jsxs)("button",{className:(0,EC.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)(bC,{className:i.logo,color:"pink"}),o===!1&&(0,bo.jsx)(wC,{className:i.lock})]})]})};async function Hd(e){let n=await new Gt(e).get("/platform/config/",{version:null});return Z(n)}var we=S(w());var kC=xC("showTabHint",!0),$a=class e{static version="10.10.1-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:[hC({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=>kC.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Wa(n)}),this.store=gC(c),this.broadcastEvents=new rC({debug:!0,deepdeskUrl:u,eventMap:Ww(this.store),createCustomChannel:l}),this.store.dispatch(ra),this.store.dispatch(Ca(kC.value())),this.store.dispatch(ra({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(H.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(H.warn("Profile has not been loaded (yet)"),!0):(H.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Ai(null)),this.store.dispatch(Ln()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();pt(r)&&jw(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(Ln())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){H.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Jm({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(eg(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(iw(t))}async setAgentInfo(t){await this.store.dispatch(Sa(t))}async setAgentSettings(t){await this.store.dispatch(Hg(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(od()),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(a_({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(i_(t))}notifyExternalSuggestion(t){this.store.dispatch(Bt(t)),this.store.dispatch(wn())}notifyEditSuggestion(t){this.store.dispatch(Cw(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(Jx({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(s_(dc(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(n_()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{if(n||!a||!i||t.shiftKey)return;this.store.dispatch(o_());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(Ow(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:g}=this.state.input;this.store.dispatch(Ca(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&g&&g.text.startsWith(d)&&(this.store.dispatch(Bt({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(wn())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(l_()),this.store.dispatch(on([]))}handlingTimeStart(){this.state.handlingTime.startTime||(H.info("Start handling time"),this.store.dispatch(sC()))}handlingTimeStop(){this.state.handlingTime.startTime&&(H.info("Stop handling time"),this.store.dispatch(Nd()))}logSendMessage(t){let n=Nh("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=Nh("overlayInput",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.store.dispatch(t_(this.state.overlayInput.metrics))}logHandlingTime(){let t=yC(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(aC())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(wn()),this.store.dispatch(no(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Bt({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){H.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),H.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=lo(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Nt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=lo(i,{appendTo:document.body});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,Nt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return ao(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,Nt.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),H.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(H.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(c_(r.metrics))):H.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Dd(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:m,inlineSuggestions:h,floatingMenu:f}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:g,isEmbedded:p,inlineSuggestions:h,floatingMenu:!!f}),n.automaticHandlingTime&&this.setupHandlingTime(t),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(u_({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&&vC(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)(H1,{})})}),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 f=="object"&&"appendOverlayTo"in f?f.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)(TC,{onLogIn:()=>this.loginViaPopup().catch(P=>H.warn(P.message))})})}),I)}else{let b=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:m,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:m},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)(ub,{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)(q1,{onLogIn:()=>this.loginViaPopup().catch(E=>H.warn(E.message))})})}),C)}(0,Nt.render)((0,we.jsx)(xo,{store:this.store,customStyles:r,children:(0,we.jsx)(ho,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(O1,{})})}),this.createContainer("deepdesk-overlays"));let _;this.inputMediator.on("selection",b=>{clearTimeout(_),b===null?_=setTimeout(()=>{b!==null&&this.store.dispatch(ng(b))},500):this.store.dispatch(ng(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(e_({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(wn()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var b;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((b=this.state.conversation.current)==null?void 0:b.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&H.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,Nt.render)((0,we.jsx)(xo,{store:this.store,customStyles:r,children:(0,we.jsx)(ho,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(Jb,{onLogIn:()=>this.loginViaPopup().catch(s=>H.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Nt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Fd(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){SC(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 Hd(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,m;if((v=y.data)!=null&&v.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((m=y.data)==null?void 0:m.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"&&H.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(H.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;H.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=ld(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 PC(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 RC(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 Dh=S(w()),wA={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},bC=({className:e,color:t})=>(0,Dh.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,Dh.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:wA[t||"pink"]})});var CC={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 Fh={};Pe(Fh,{enUS:()=>bA,nlNL:()=>CA});var bA={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},CA={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var bo=S(w()),TC=({onLogIn:e})=>{let t=j(Fh),n=N("productName"),r=z(),o=R(pt),i=k("FloatingMenu",CC);if(o===null)return null;let s=()=>{o===!0?r($e(!0)):e()};return(0,bo.jsxs)("button",{className:(0,EC.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)(bC,{className:i.logo,color:"pink"}),o===!1&&(0,bo.jsx)(wC,{className:i.lock})]})]})};async function Hd(e){let n=await new Gt(e).get("/platform/config/",{version:null});return Z(n)}var we=S(w());var kC=xC("showTabHint",!0),$a=class e{static version="10.10.1";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:[hC({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=>kC.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Wa(n)}),this.store=gC(c),this.broadcastEvents=new rC({debug:!0,deepdeskUrl:u,eventMap:Ww(this.store),createCustomChannel:l}),this.store.dispatch(ra),this.store.dispatch(Ca(kC.value())),this.store.dispatch(ra({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(H.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(H.warn("Profile has not been loaded (yet)"),!0):(H.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Ai(null)),this.store.dispatch(Ln()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();pt(r)&&jw(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(Ln())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){H.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Jm({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(eg(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(iw(t))}async setAgentInfo(t){await this.store.dispatch(Sa(t))}async setAgentSettings(t){await this.store.dispatch(Hg(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(od()),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(a_({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(i_(t))}notifyExternalSuggestion(t){this.store.dispatch(Bt(t)),this.store.dispatch(wn())}notifyEditSuggestion(t){this.store.dispatch(Cw(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(Jx({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(s_(dc(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(n_()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{if(n||!a||!i||t.shiftKey)return;this.store.dispatch(o_());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(Ow(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:g}=this.state.input;this.store.dispatch(Ca(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&g&&g.text.startsWith(d)&&(this.store.dispatch(Bt({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(wn())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(l_()),this.store.dispatch(on([]))}handlingTimeStart(){this.state.handlingTime.startTime||(H.info("Start handling time"),this.store.dispatch(sC()))}handlingTimeStop(){this.state.handlingTime.startTime&&(H.info("Stop handling time"),this.store.dispatch(Nd()))}logSendMessage(t){let n=Nh("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=Nh("overlayInput",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.store.dispatch(t_(this.state.overlayInput.metrics))}logHandlingTime(){let t=yC(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(aC())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(wn()),this.store.dispatch(no(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Bt({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){H.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),H.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=lo(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Nt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=lo(i,{appendTo:document.body});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,Nt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return ao(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,Nt.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),H.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(H.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(c_(r.metrics))):H.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Dd(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:m,inlineSuggestions:h,floatingMenu:f}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:g,isEmbedded:p,inlineSuggestions:h,floatingMenu:!!f}),n.automaticHandlingTime&&this.setupHandlingTime(t),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(u_({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&&vC(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)(H1,{})})}),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 f=="object"&&"appendOverlayTo"in f?f.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)(TC,{onLogIn:()=>this.loginViaPopup().catch(P=>H.warn(P.message))})})}),I)}else{let b=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:m,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:m},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)(ub,{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)(q1,{onLogIn:()=>this.loginViaPopup().catch(E=>H.warn(E.message))})})}),C)}(0,Nt.render)((0,we.jsx)(xo,{store:this.store,customStyles:r,children:(0,we.jsx)(ho,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(O1,{})})}),this.createContainer("deepdesk-overlays"));let _;this.inputMediator.on("selection",b=>{clearTimeout(_),b===null?_=setTimeout(()=>{b!==null&&this.store.dispatch(ng(b))},500):this.store.dispatch(ng(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(e_({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(wn()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var b;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((b=this.state.conversation.current)==null?void 0:b.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&H.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,Nt.render)((0,we.jsx)(xo,{store:this.store,customStyles:r,children:(0,we.jsx)(ho,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(Jb,{onLogIn:()=>this.loginViaPopup().catch(s=>H.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Nt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Fd(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){SC(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 Hd(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,m;if((v=y.data)!=null&&v.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((m=y.data)==null?void 0:m.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"&&H.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(H.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;H.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=ld(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 PC(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 RC(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 EA(e){let t=document.createElement("template");return t.innerHTML=e,t.content}function TA(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 IC(e,t){return!e.contains(t)||t===e?null:t.parentNode===e?t:IC(e,t.parentNode)}async function LC(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?EA(t):TA(t);if(n){let c=IC(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 AC(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function OC(e,t,n){await new Un(e).authenticateWithKey(t,n)}async function kA(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 NC(e,t){let n=await kA(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 UC(PA);})();
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.1-beta.0",
3
+ "version": "10.10.1",
4
4
  "description": "Deepdesk SDK",
5
5
  "author": "Lukas Batteau",
6
6
  "license": "ISC",