@deepdesk/deepdesk-sdk 11.1.1-beta.2 → 11.1.1-beta.4

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.esm.js CHANGED
@@ -1,11 +1,11 @@
1
- var $d=Object.defineProperty;var Q=(t,e)=>{for(var o in e)$d(t,o,{get:e[o],enumerable:!0})};import Nr from"classnames";import Qd,{createContext as Jd,useContext as zn,useEffect as Yd,useState as eu}from"react";import qd,{useContext as Gd}from"react";import jd from"classnames";var _t=qd.createContext({});function h(t,e){let{debug:o,...n}=Gd(_t),s=n[t];return s?Object.entries(e).reduce((r,[i,a])=>{let l=s[i];return{...r,[i]:jd(a,l,o?`${t}__${i}`:!1)}},{}):e}var Mr={root:"uo"};import{jsx as go,jsxs as Xd}from"react/jsx-runtime";var mo=()=>Xd("svg",{className:Mr.root,width:"185",height:"170",viewBox:"0 0 185 170",xmlns:"http://www.w3.org/2000/svg",children:[go("defs",{children:go("style",{children:".cls-1 { fill: #b3b3b3; }"})}),go("title",{children:"Failed loading image"}),go("path",{className:"cls-1",d:"M15 130.896V16.994c0-1.097.898-1.994 2.007-1.994h150.986A2 2 0 0 1 170 16.994v69.147L133.015 51 87.26 120.377l-35.863-17.758L15 130.896zM2 0C.895 0 0 .887 0 2v166c0 1.105.887 2 2 2h181c1.105 0 2-.887 2-2V2c0-1.105-.887-2-2-2H2zm49 72c11.046 0 20-9.178 20-20.5S62.046 31 51 31s-20 9.178-20 20.5S39.954 72 51 72z",fillRule:"evenodd"})]});var Un={root:"yo",imageWrapper:"G",image:"wo",content:"m",title:"vo",contentIsCropped:"ko",lineClamp:"zo"};import{jsx as st}from"react/jsx-runtime";var fo=Jd(Un),tu=({title:t,src:e})=>{let o=zn(fo),[n,s]=eu(!1);return Yd(()=>{s(!1)},[e]),st("div",{className:o.imageWrapper,children:e&&!n?st("img",{className:o.image,alt:t,src:e,onError:()=>s(!0)}):st(mo,{})})},ou=({className:t,lineClamp:e=!1,cropText:o=!1,children:n})=>{let s=zn(fo);return st("div",{className:Nr(s.content,t,{[s.contentIsCropped]:o,[s.lineClamp]:e}),children:n})},nu=({as:t="h1",cropText:e=!1,className:o,children:n,...s})=>{let r=zn(fo);return Qd.createElement(t,{className:Nr(r.title,o,{[r.contentIsCropped]:e}),...s},n)},ho=({children:t})=>{let e=h("Card",Un);return st("div",{className:e.root,children:st(fo.Provider,{value:e,children:t})})};ho.Image=tu;ho.Content=ou;ho.Title=nu;var H=ho;import ru from"classnames";var Or={root:"N"};import{jsx as lu}from"react/jsx-runtime";var iu={"arrow-up":"\u25B2","arrow-down":"\u25BC",tab:"tab",esc:"Esc",enter:"\u21B5"},au=({className:t,keyCode:e,...o})=>{let n=h("KeyboardHint",Or);return lu("span",{"data-key":iu[e],className:ru(t,n.root),...o})},Vn=au;import du from"classnames";var _r={root:"jo"};import{jsx as pu}from"react/jsx-runtime";var uu=({className:t,children:e,...o})=>{let n=h("Label",_r);return pu("span",{...o,className:du(t,n.root),children:e})},$n=uu;var Dr={root:"qo",subTitleContainer:"Co",subtitle:"So",suggestions:"Eo"};import{jsx as qn,jsxs as fu}from"react/jsx-runtime";var mu=({title:t,children:e,type:o,...n})=>{let s=h("Section",Dr);return fu("section",{...n,className:s.root,"data-section-type":o,children:[t&&qn("div",{className:s.subTitleContainer,children:qn("span",{className:s.subtitle,children:t})}),qn("div",{className:s.suggestions,children:e})]})},Re=mu;import yu from"classnames";import vu from"react";var Hr={root:"Go"};import{jsx as xu}from"react/jsx-runtime";var Su=vu.forwardRef(({className:t,children:e},o)=>{let n=h("SectionList",Hr);return xu("div",{ref:o,className:yu(n.root,t),children:e})}),Gn=Su;import Dt from"classnames";import wu,{createContext as Tu,useCallback as Eu,useContext as rt}from"react";import{jsx as Fr,jsxs as bu}from"react/jsx-runtime";var Br=({className:t})=>bu("svg",{viewBox:"0 0 12 12",version:"1.1",xmlns:"http://www.w3.org/2000/svg",className:t,children:[Fr("line",{x1:"1",y1:"11",x2:"11",y2:"1",stroke:"black",strokeWidth:"2"}),Fr("line",{x1:"1",y1:"1",x2:"11",y2:"11",stroke:"black",strokeWidth:"2"})]});var jn={fadein:"Y",root:"e",isClickable:"A",isSelected:"No",actions:"F",actionsIsFixed:"Yo",actionButton:"t",dropdownList:"H",dropdownButton:"L",dropdownItem:"M",dropdownItemButton:"R",actionButtonIsPrimary:"Ao",actionButtonIsDisabled:"Fo",labels:"Ho",label:"Lo",closeIcon:"n"};import{jsx as re,jsxs as Mu}from"react/jsx-runtime";var ze=Tu(jn),ku=({fixed:t,children:e,...o})=>{let n=rt(ze);return re("div",{...o,className:Dt(n.actions,{[n.actionsIsFixed]:t}),children:e})},Ru=({className:t,title:e,...o})=>{let n=rt(ze);return re("div",{className:Dt(n.closeIcon,t),title:e,role:"button","aria-label":e,...o,children:re(Br,{})})},Pu=({className:t,primary:e,disabled:o,label:n,children:s})=>{let r=rt(ze);return Mu("div",{className:Dt(t,r.actionButton,r.dropdownButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:o}),onMouseDown:i=>i.stopPropagation(),onClick:i=>i.stopPropagation(),children:[n,re("ul",{className:r.dropdownList,children:s})]})},Iu=({index:t,label:e,onClick:o})=>{let n=rt(ze);return re("li",{className:n.dropdownItem,children:re("button",{className:n.dropdownItemButton,type:"button","data-index":t,onClick:o,children:e})})},Au=({className:t,primary:e,disabled:o,onClick:n,label:s})=>{let r=rt(ze);return re("button",{type:"button",className:Dt(t,r.actionButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:o}),onClick:n??(i=>i.stopPropagation()),disabled:o,"aria-hidden":o,children:s})},Lu=({labels:t})=>{let e=rt(ze);return re("div",{className:e.labels,children:t.map(o=>re("span",{className:e.label,children:o},o))})},Ve=wu.forwardRef(({className:t,selected:e,onClick:o,children:n,as:s="div",...r},i)=>{let a=h("Suggestion",jn),l=Eu(c=>{c.preventDefault(),o&&o(c)},[o]);return re(s,{...r,ref:i,className:Dt(t,a.root,{[a.isSelected]:e,[a.isClickable]:!!o}),onClick:l,children:re(ze.Provider,{value:a,children:n})})});Ve.Labels=Lu;Ve.Actions=ku;Ve.ActionButton=Au;Ve.DropdownButton=Pu;Ve.DropdownItem=Iu;Ve.CloseIcon=Ru;var O=Ve;import Ou from"classnames";var Kr={root:"Mo",isWithDivider:"Ro"};import{jsx as Du}from"react/jsx-runtime";var _u=({withDivider:t,children:e})=>{let o=h("SuggestionList",Kr);return Du("div",{"data-testid":"suggestions-overlay-list",className:Ou(o.root,{[o.isWithDivider]:t}),children:e})},oe=_u;import Fu from"classnames";var Ur={root:"u",isCollapsed:"T"};import{jsx as Wn}from"react/jsx-runtime";var Bu=({className:t,isCollapsed:e,title:o,onClick:n})=>{let s=h("ToggleButton",Ur);return Wn("button",{type:"button",className:Fu(s.root,t,{[s.isCollapsed]:e}),onClick:n,title:o,children:Wn("svg",{width:"14",height:"8",viewBox:"-2.5 -5 75 60",preserveAspectRatio:"none",children:Wn("path",{d:"M0,0 l35,50 l35,-50",fill:"none",stroke:"grey",strokeLinecap:"round",strokeWidth:"6"})})})},it=Bu;var zr=/(?:[.,;:!?\\n]|:\\)|:\\(|:-\\)|:-\\()/g,yo=/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\})/g;var Vr=/x-deepdesk-(([a-z0-9\-_])+-version)/,Pe=(m=>(m.SEARCH="search",m.TEMPLATE="template",m.ELASTIC_SEARCH="search-autocomplete",m.GPT="gpt",m.TRIE="trie",m.TRIE_WITH_TYPOS="trie-with-typos",m.SEMANTIC="semantic",m.TEXT_RECOMMENDATION="text_recommendation",m.URL_RECOMMENDATION="url_recommendation",m.LINK_RECOMMENDATION="link_recommendation",m.PERSONAL_COLLECTION="personal-collection",m.PERSONAL_COLLECTION_SEARCH="personal-collection-search",m.SEARCH_OVERLAY="search-overlay",m.SEARCH_PREVIEW="search-preview",m.SEARCH_URL="search-url",m))(Pe||{}),at=(r=>(r.ENTER="enter",r.TAB="tab",r.ARROW="arrow",r.HOTKEY="hotkey",r.MOUSE="mouse",r))(at||{});import{render as Mt,unmountComponentAtNode as Bn}from"react-dom";import{Fragment as ef}from"react";import{createSlice as Ku}from"@reduxjs/toolkit";import{useSelector as Uu}from"react-redux";var vo=(o=>(o.NL_NL="nl-NL",o.EN_US="en-US",o))(vo||{});var zu={locale:"en-US",deanonymize:!1,fallbackImage:!1,isEmbedded:!1,showAutoflows:!1,showCustomMessages:!1,showImages:!1,showSearch:!1,showImageSearch:!1,showStyleSuggestions:!1,showMidSentenceSuggestions:!1,showSuggestionsBeforePattern:!1,showSuggestionsAfterPattern:!1,showTabCompletion:!0,showTextSuggestions:!0,showEntitiesCommand:!1,showSummaryCommand:!1,showKnowledgeSearch:!1,textSuggestionsCount:3,recommendTextSuggestions:!0,searchTriggerKey:"k",visible:!0,insertLink:!1,inlineSuggestions:!1,floatingMenu:!1,adminUrl:void 0,productName:"Deepdesk"},$r=Ku({name:"settings",initialState:zu,reducers:{set(t,e){Object.entries(e.payload).forEach(o=>{let[n,s]=o;typeof s>"u"||(t[n]=s)})}}}),{set:So}=$r.actions,Xn=t=>e=>e.settings[t],C=t=>Uu(Xn(t)),qr=$r.reducer;import{useSelector as Qi}from"react-redux";import{createAsyncThunk as Zn,createSlice as Vu}from"@reduxjs/toolkit";var $u={isLoggedIn:!0,loginFetchState:"idle",verifyFetchState:"idle",showLoginOverlay:!1},W=t=>t.auth.isLoggedIn,Gr=t=>t.auth.loginFetchState,jr=t=>t.auth.verifyFetchState,Wr=t=>t.auth.showLoginOverlay,Se=Zn("auth/validate",async(t,e)=>e.extra.deepdeskAPI.isLoggedIn()),Xr=Zn("auth/requestLogin",async({email:t},e)=>{let{deepdeskAPI:o}=e.extra;return o.requestLoginByEmail(t)}),Ht=Zn("auth/verifyLoginToken",async({token:t},e)=>{let{deepdeskAPI:o}=e.extra;return o.verifyLoginToken(t)}),Zr=Vu({name:"auth",initialState:$u,reducers:{setIsLoggedIn(t,e){t.isLoggedIn=e.payload},setShowLoginOverlay(t,e){t.showLoginOverlay=e.payload}},extraReducers:t=>{t.addCase(Se.pending,e=>{e.loginFetchState="loading"}),t.addCase(Se.fulfilled,(e,{payload:o})=>{e.isLoggedIn=o,e.loginFetchState="done"}),t.addCase(Se.rejected,e=>{e.loginFetchState="error",e.isLoggedIn=!1}),t.addCase(Ht.pending,e=>{e.verifyFetchState="loading"}),t.addCase(Ht.rejected,e=>{e.verifyFetchState="error"}),t.addCase(Ht.fulfilled,(e,o)=>{o.payload.isLoggedIn?e.verifyFetchState="done":e.verifyFetchState="error"})}}),{setIsLoggedIn:lt,setShowLoginOverlay:Qr}=Zr.actions,Jr=Zr.reducer;import{createAction as ut,createSlice as Yu}from"@reduxjs/toolkit";import{diffChars as ep}from"diff";import{useSelector as tp}from"react-redux";function Yr(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function Ie(t,e,o=10){let n=typeof t,s=typeof e;if(o===0)throw new Error("Max depth deepEqual, possible circular references?");return n!==s?!1:t==null||n==="string"||n==="number"||n==="boolean"?t===e:Array.isArray(t)&&Array.isArray(e)?t.length!==e.length?!1:t.every((r,i)=>Ie(r,e[i],o-1)):Yr(t)&&Yr(e)?Object.keys(t).length!==Object.keys(e).length?!1:Object.keys(t).every(i=>Ie(t[i],e[i],o-1)):!1}function qu(t){return Math.max(...t.map(e=>e.length))}function Gu(t,e){let o=t.reduce((n,s)=>{if(s){let r=n[s]?n[s]+1:1;return{...n,[s]:r}}return n},{});return Object.keys(o).reduce((n,s)=>(o[s]<e&&n.push(s),n),[])}function ei(t,e){let n=[...t.map(({text:s})=>s.split(/\b(\w+)\b/))];for(let s=0;s<qu(n);s++){let r=Gu(n.map(a=>a[s]),e),i=n.filter(a=>!r.includes(a[s]));if(i.length>=e)n=i;else return{text:n[0].slice(0,s).join("").replace(/ (\?| |!|\.|,|\n)/g,"$1").trimEnd(),source:"mixed"}}}var ju=2;function Qn(t,e=""){if(t.length===0)return;if(t.length===1)return t[0];let o=ei(t,ju);return o&&o.text!==e?o:t[0]}import{createAction as Xu,createAsyncThunk as ct,createSlice as Zu}from"@reduxjs/toolkit";var Wu={info(...t){console.info("[Deepdesk]",...t)},warn(...t){console.warn("[Deepdesk]",...t)},error(...t){console.error("[Deepdesk]",...t)}},E=Wu;var ti={current:null,isSupported:null},N=Xu("resetConversation"),xo=t=>{let{current:e}=t.conversation;return(e==null?void 0:e.sessionId)||null},bo=t=>{let{current:e}=t.conversation;return(e==null?void 0:e.id)||null},dt=t=>t.conversation.isSupported,Jn=ct("conversation/isSupported",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.isConversationSupported(t.sessionId,t.options)}),Co=ct("conversation/create",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.createConversation(t)}),wo=ct("conversation/bySessionId",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.getConversationBySessionId(t.sessionId,t.options)}),To=ct("conversation/update",(t,e)=>{let{deepdeskAPI:o}=e.extra,n=bo(e.getState());if(!n)throw new Error("No current conversation to update");return o.updateConversation(n,t)}),Yn=ct("conversation/upsert",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.getConversationBySessionId(t.sessionId).catch(()=>null).then(n=>{if(!n)return o.createConversation(t);let{agentId:s,agentName:r,agentEmail:i,agentNickname:a,tags:l}=t;return o.updateConversation(n.id,{agentId:s,agentEmail:i,agentName:r,agentNickname:a,tags:l})})}),Eo=ct("conversation/postMessages",(t,e)=>{let{deepdeskAPI:o}=e.extra,n=bo(e.getState());if(!n)throw new Error("No current conversation to update messages");return o.postMessages(n,t.map(s=>({...s})))}),Qu=[Co.rejected,wo.rejected,To.rejected,Eo.rejected].map(t=>t==null?void 0:t.toString()),Ju=Zu({name:"conversation",initialState:ti,reducers:{},extraReducers:t=>{t.addCase(Jn.fulfilled,(e,o)=>{e.isSupported=o.payload}).addCase(Co.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(wo.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(Yn.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(To.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(Eo.fulfilled,(e,o)=>{e.current&&(e.current.messages=o.payload)}).addCase(N,()=>ti).addMatcher(e=>Qu.includes(e.type),(e,o)=>{var n;throw E.info("Conversation action rejected",o.type,((n=o.error)==null?void 0:n.message)||"No message"),new Error(o.error.message)})}}),oi=Ju.reducer;var Ae={text:"",html:null,selection:{start:0,end:0},stagedSuggestion:null,userCommitted:{text:"",selection:{start:0,end:0}},tabCompletionSuggestion:void 0,previousKeyDownEvent:null,textSuggestions:[],selectedSuggestionIndex:-1,metrics:{numCharsTyped:0,numCharsPasted:0,numCharsCut:0,numCharsDeleted:0,numPaste:0,agentStartedTypingTimestamp:null,externalTimeTotalSeconds:null,pastes:[],deletions:[],offeredTextSuggestions:[],textSuggestions:[],cuts:[]}};function ni(t){let{key:e,shiftKey:o,ctrlKey:n,metaKey:s,altKey:r}=t;return{key:e,shiftKey:o,ctrlKey:n,metaKey:s,altKey:r}}var Ro=ut("input/replaceText"),Po=ut("input/keyDown"),$e=ut("input/sendMessage"),Io=ut("input/uiInputChange"),Ao=ut("input/applyImageSuggestion"),G=ut("input/sendEvent");function ko(t){if(!t.stagedSuggestion)return;let{text:e,suggestion:{source:o,abVariant:n,abTestName:s,trainingJobs:r,sourceText:i,searchTerm:a,text:l},eventMetrics:{inputType:c},replace:d}=t.stagedSuggestion,u=o==="search"||o==="personal-collection-search",p=e.slice(t.userCommitted.text.substring(0,t.userCommitted.selection.start).length);(u||d==="selection")&&(p=e),t.stagedSuggestion.suggestion.source==="search-overlay"&&(p=l),t.userCommitted.text=t.text,t.userCommitted.selection=t.selection,t.metrics.textSuggestions.push({text:p,source:o,abVariant:n,abTestName:s,inputType:c,sourceText:i,trainingJobs:r||[],searchTerm:u?t.userCommitted.text:a}),t.stagedSuggestion=null,t.textSuggestions=[],t.selectedSuggestionIndex=-1}var si=Yu({name:"input",initialState:Ae,reducers:{initialInput(t,e){let{text:o,selection:n,html:s}=e.payload;t.text=o,t.selection.start=(n==null?void 0:n.start)??o.length,t.selection.end=(n==null?void 0:n.end)??o.length,t.userCommitted.text=o,t.userCommitted.selection.start=(n==null?void 0:n.start)??o.length,t.userCommitted.selection.end=(n==null?void 0:n.end)??o.length,t.html=s||null},reset(t){Object.assign(t,{...Ae,selection:t.selection})},resetToCommitted(t){t.text=t.userCommitted.text,t.selection=t.userCommitted.selection,t.stagedSuggestion=null,t.tabCompletionSuggestion=Qn(t.textSuggestions,t.userCommitted.text)},changeSelection(t,e){e.payload&&(Ie(t.selection,e.payload)||(t.selection=e.payload,t.userCommitted.selection=t.selection,t.stagedSuggestion&&ko(t)))},platformInput(t,e){let{text:o,html:n,selection:s}=e.payload;s&&(t.selection.start=s.start,t.selection.end=s.end),t.text=o,t.html=n||null},userInput(t,e){var r,i,a,l;if(t.previousKeyDownEvent){let{key:c,shiftKey:d,ctrlKey:u,metaKey:p,altKey:g}=t.previousKeyDownEvent;switch(c){case"Enter":d&&(t.metrics.numCharsTyped+=1);break;case"Backspace":case"Delete":{let{text:f}=t,{text:m}=e.payload,S=ep(f,m);f.length-m.length>1&&t.metrics.deletions.push(...S.filter(w=>w.removed).map(w=>w.value)),t.metrics.numCharsDeleted+=f.length-m.length;break}case"C":case"V":case"X":if(!u&&!p){t.metrics.numCharsTyped+=1;let f=((r=t.selection)==null?void 0:r.start)!==void 0&&((i=t.selection)==null?void 0:i.end)!==void 0?t.text.substring(t.selection.start,t.selection.end):null;f&&f.length>0&&(t.metrics.numCharsDeleted+=f.length,t.metrics.deletions.push(f))}break;case"Shift":break;default:if(!u&&!p&&!g){t.metrics.numCharsTyped+=1;let f=((a=t.selection)==null?void 0:a.start)!==void 0&&((l=t.selection)==null?void 0:l.end)!==void 0?t.text.substring(t.selection.start,t.selection.end):null;f&&f.length>0&&(t.metrics.numCharsDeleted+=f.length,t.metrics.deletions.push(f))}}}!t.metrics.agentStartedTypingTimestamp&&e.payload.text!==t.text&&(t.metrics.agentStartedTypingTimestamp=Date.now()),e.payload.text===""&&(t.metrics=Ae.metrics,t.textSuggestions=[],t.stagedSuggestion=null),t.text!==e.payload.text&&ko(t);let{text:o,html:n,selection:s}=e.payload;s&&(t.selection.start=s.start,t.selection.end=s.end,t.userCommitted.selection.start=s.start,t.userCommitted.selection.end=s.end),t.text=o,t.html=n||null,t.userCommitted.text=o,t.previousKeyDownEvent=null},stageSuggestion(t,e){let{text:o}=e.payload;switch(t.stagedSuggestion=e.payload,t.tabCompletionSuggestion=void 0,e.payload.replace){case"selection":t.text=`${t.text.slice(0,t.selection.start)}${o}${t.text.slice(t.selection.end)}`,t.selection.end=t.selection.start+o.length,t.selection.start+=o.length;break;case"until-selection-end":t.text=`${o}${t.text.slice(t.selection.end)}`,t.selection.start=o.length,t.selection.end=o.length;break;default:throw new Error(`Unknown replace ${e.payload.replace}`)}e.payload.eventMetrics.inputType==="tab"&&ko(t)},commitSuggestion(t){ko(t)},offeredTextSuggestion(t,e){let{text:o,suggestion:{source:n}}=e.payload;t.metrics.offeredTextSuggestions.find(r=>r.text===o)||t.metrics.offeredTextSuggestions.push({text:o,source:n})},registerCut(t,e){let{metrics:o}=t,n=e.payload;t.metrics={...t.metrics,numCharsCut:o.numCharsCut+n.length,cuts:[...o.cuts,n]}},registerPaste(t,e){let{metrics:o}=t,{text:n,selectionText:s}=e.payload,r=o.numCharsDeleted+(s&&s.length?s.length:0),i=s&&s.length?[...o.deletions,s]:o.deletions;t.metrics={...t.metrics,numCharsDeleted:r,deletions:i,numCharsPasted:o.numCharsPasted+n.length,numPaste:o.numPaste+1,pastes:[...o.pastes,n]}},registerKeyDown(t,e){t.previousKeyDownEvent=e.payload},nextTextSuggestionIndex(t){let e=t.textSuggestions.length;t.selectedSuggestionIndex=t.selectedSuggestionIndex<e-1?t.selectedSuggestionIndex+1:t.selectedSuggestionIndex},previousTextSuggestionIndex(t){t.selectedSuggestionIndex=t.selectedSuggestionIndex>=0?t.selectedSuggestionIndex-1:t.selectedSuggestionIndex},setTextSuggestions(t,e){if(t.selectedSuggestionIndex=-1,t.textSuggestions=e.payload,e.payload.length===0)return;let o=t.userCommitted.text.substring(0,t.userCommitted.selection.end),n=Qn(e.payload,o);t.tabCompletionSuggestion=n!=null&&n.text.includes(o)?n:void 0},setSelectedTextSuggestionIndex(t,e){t.selectedSuggestionIndex=e.payload},setMetrics(t,{payload:e}){t.metrics=e}},extraReducers:t=>{t.addCase(N,e=>{e.tabCompletionSuggestion=Ae.tabCompletionSuggestion,e.previousKeyDownEvent=Ae.previousKeyDownEvent,e.textSuggestions=Ae.textSuggestions,e.selectedSuggestionIndex=Ae.selectedSuggestionIndex,e.metrics=Ae.metrics})}}),pt=t=>t.input.userCommitted.text.substring(0,t.input.userCommitted.selection.end),op=t=>t.input.selection,ri=()=>tp(op),{userInput:ii,changeSelection:es,initialInput:ai,nextTextSuggestionIndex:li,offeredTextSuggestion:ci,previousTextSuggestionIndex:di,registerCut:ui,registerKeyDown:pi,registerPaste:gi,reset:mi,resetToCommitted:Ft,platformInput:fi,setSelectedTextSuggestionIndex:Le,setTextSuggestions:pe,stageSuggestion:ge,commitSuggestion:xe,setMetrics:hi}=si.actions,yi=si.reducer;import{createAsyncThunk as ip,createSlice as ap}from"@reduxjs/toolkit";import{createAsyncThunk as os,createSlice as sp}from"@reduxjs/toolkit";function np(t){return t.replace(/(_\w)/g,e=>e[1].toUpperCase())}function I(t){return Array.isArray(t)?t.map(I):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,o)=>({...e,[np(o)]:I(t[o])}),{}):t}function ts(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function U(t){return Array.isArray(t)?t.map(U):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,o)=>({...e,[ts(o)]:U(t[o])}),{}):t}var rp={agentInfo:void 0,agentSettings:{},visitorInfo:void 0,fetchState:"idle"},Kt=t=>{var e,o,n;return{timezone:((e=t.info.visitorInfo)==null?void 0:e.visitorTimeZone)||Intl.DateTimeFormat().resolvedOptions().timeZone,agentName:((o=t.info.agentInfo)==null?void 0:o.agentNickname)||"",visitorName:((n=t.info.visitorInfo)==null?void 0:n.visitorName)||""}},Bt=os("info/setAgentInfo",async(t,e)=>{let{deepdeskAPI:o}=e.extra;if(!t.agentId&&!t.agentNickname)throw new Error("At least provide agentId or agentNickname");let n=await o.client.get("/apis/admin/session/me/",{version:null}),s={};return n.external_id||(s.external_id=t.agentId),n.nickname||(s.nickname=t.agentNickname),!s.external_id&&!s.nickname?I(n):(await o.client.patch("/apis/admin/session/me/",s,{version:null}),I(n))}),ns=os("info/setAgentSettings",async(t,e)=>{let{deepdeskAPI:o}=e.extra,n=await o.client.get("/apis/admin/session/me/",{version:null}),s={...typeof n.ui_config=="object"?n.ui_config:{},...t};return await o.client.patch("/apis/admin/session/me/",{ui_config:s}),s}),ss=os("info/getAgentSettings",async(t,e)=>{let{deepdeskAPI:o}=e.extra;return(await o.client.get("/apis/admin/session/me/",{version:null})).ui_config}),vi=t=>t.info.agentInfo,Si=sp({name:"info",initialState:rp,reducers:{setVisitorInfo(t,e){t.visitorInfo={...t.visitorInfo,...e.payload}}},extraReducers:t=>{t.addCase(Bt.pending,(e,o)=>{e.fetchState="loading",e.agentInfo={...e.agentInfo,...o.meta.arg}}).addCase(Bt.rejected,e=>{e.fetchState="error"}).addCase(Bt.fulfilled,(e,o)=>{e.fetchState="done",e.agentInfo={...e.agentInfo,...o.meta.arg,agentId:o.payload.externalId||o.meta.arg.agentId||"",agentNickname:o.payload.nickname||o.meta.arg.agentNickname||""}}).addCase(ns.fulfilled,(e,o)=>{e.agentSettings=o.payload}).addCase(ss.fulfilled,(e,o)=>{e.agentSettings=o.payload}).addCase(N,e=>{e.visitorInfo=void 0})}}),{setVisitorInfo:xi}=Si.actions,bi=Si.reducer;var Lo={list:[],fetchState:"idle",isOpen:!1,page:"search",aggregates:{}},Ci=t=>t.search.isOpen,wi=t=>t.search.page,Ti=t=>t.search.list,Ei=t=>t.search.aggregates;function ki(t,e=o=>o){return o=>o.search.list.filter(n=>n.type===t).map(e)}var qe=ip("search/getAll",async(t,e)=>{var a;let{deepdeskAPI:o}=e.extra,n=e.getState(),s=(a=n.conversation.current)==null?void 0:a.profileCode;if(!s)throw new Error("Profile should be provided in order to be able to search");let{results:r,aggregates:i}=await o.search({profile:s,query:t.query,tags:t.tags,size:t.size,current:t.current,filters:{type:t.type},params:Kt(n)});return{results:r.map(l=>({...l,source:`search-${l.type.toLowerCase()}`,searchTerm:t.query})),aggregates:i}}),Ri=ap({name:"search",initialState:Lo,reducers:{setIsOpen(t,e){t.isOpen=e.payload},setPage(t,e){t.page=e.payload},resetSearch(t){t.fetchState=Lo.fetchState,t.list=Lo.list}},extraReducers:t=>{t.addCase(qe.pending,e=>{e.fetchState="loading"}).addCase(qe.rejected,(e,o)=>{e.fetchState="error",E.error(o.error)}).addCase(qe.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload.results,e.aggregates=o.payload.aggregates||{}}).addCase(N,()=>Lo)}}),{resetSearch:Mo,setIsOpen:ee,setPage:ie}=Ri.actions,Pi=Ri.reducer;import{createAction as lp,createAsyncThunk as cp,createSlice as dp}from"@reduxjs/toolkit";var rs={cues:[],fetchState:"idle"},Ii=t=>{var e;return(e=t.rules)==null?void 0:e.cues},up=lp("rules/resetCues"),be=cp("rules/evaluate",async(t,e)=>{var a;let{deepdeskAPI:o}=e.extra,n=(a=e.getState().conversation.current)==null?void 0:a.id;if(!n)throw new Error("No current conversation to evaluate rules");if(!(await o.getAccount()).ruleEngine)throw new Error("Rule engine is not enabled for this account");if(!(await o.getRules()).some(l=>l.label===t.label))throw new Error(`No rules found with label: ${t.label}`);return await o.evaluateRule(t.label,n,t.params)}),Ai=dp({name:"answer",initialState:rs,reducers:{removeCue(t,e){t.cues=t.cues.filter(o=>o.id!==e.payload.id)}},extraReducers:t=>{t.addCase(be.pending,e=>{e.fetchState="loading"}).addCase(be.rejected,e=>{e.fetchState="error"}).addCase(be.fulfilled,(e,o)=>{let n=Date.now(),s=o.payload.map(a=>({id:a.id||a.text,timestamp:n,...a})),r=s.map(a=>a.id),i=e.cues.filter(a=>!r.includes(a.id));e.fetchState="done",e.cues=[...s,...i]}).addCase(N,()=>rs).addCase(up.toString(),()=>rs)}}),{removeCue:Li}=Ai.actions,Mi=Ai.reducer;var is="SetCues",gt="ShowLoginOverlay",Ut="UserLoggedIn",pp="UserLoggedOut",Me="ApplySuggestion",as="ApplyImageSuggestion",gp="ShowCommandPalette",mp=t=>({[is]:e=>{t.dispatch({type:be.fulfilled,payload:e})},[gp]:e=>{t.dispatch(ee(e.isOpen)),e.page&&t.dispatch(ie(e.page))},[gt]:e=>{t.dispatch(Qr(e))},[Ut]:()=>{t.dispatch(Se())},[pp]:()=>{t.dispatch(Se())},[as]:e=>{t.dispatch(Ao({suggestion:e.suggestion}))},[Me]:e=>{t.dispatch(ge({...e,eventMetrics:{inputType:"mouse"},replace:"selection"})),t.dispatch(xe())}}),Ni=mp;import Oi,{useContext as fp}from"react";import{jsx as hp}from"react/jsx-runtime";var _i=Oi.createContext(null),Ge=({broadcastEvents:t,children:e})=>{let o=Oi.useMemo(()=>t,[]);return hp(_i.Provider,{value:o,children:e})},ae=()=>{let t=fp(_i);if(!t)throw new Error("You should use the useBroadcastEvents within a BroadcastEventsProvider");return t};import ys from"classnames";import{useCallback as Xi,useEffect as Vp,useMemo as $p,useState as vs}from"react";import{useDispatch as qp,useSelector as Gp}from"react-redux";import{createContext as Pp,useContext as Ip}from"react";var ls=function(t,e){return ls=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,n){o.__proto__=n}||function(o,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(o[s]=n[s])},ls(t,e)};function zt(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");ls(t,e);function o(){this.constructor=t}t.prototype=e===null?Object.create(e):(o.prototype=e.prototype,new o)}var te=function(){return te=Object.assign||function(e){for(var o,n=1,s=arguments.length;n<s;n++){o=arguments[n];for(var r in o)Object.prototype.hasOwnProperty.call(o,r)&&(e[r]=o[r])}return e},te.apply(this,arguments)};function Di(t,e){var o={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(o[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(o[n[s]]=t[n[s]]);return o}function No(t,e,o){if(o||arguments.length===2)for(var n=0,s=e.length,r;n<s;n++)(r||!(n in e))&&(r||(r=Array.prototype.slice.call(e,0,n)),r[n]=e[n]);return t.concat(r||Array.prototype.slice.call(e))}var Oo;(function(t){t[t.EXPECT_ARGUMENT_CLOSING_BRACE=1]="EXPECT_ARGUMENT_CLOSING_BRACE",t[t.EMPTY_ARGUMENT=2]="EMPTY_ARGUMENT",t[t.MALFORMED_ARGUMENT=3]="MALFORMED_ARGUMENT",t[t.EXPECT_ARGUMENT_TYPE=4]="EXPECT_ARGUMENT_TYPE",t[t.INVALID_ARGUMENT_TYPE=5]="INVALID_ARGUMENT_TYPE",t[t.EXPECT_ARGUMENT_STYLE=6]="EXPECT_ARGUMENT_STYLE",t[t.INVALID_NUMBER_SKELETON=7]="INVALID_NUMBER_SKELETON",t[t.INVALID_DATE_TIME_SKELETON=8]="INVALID_DATE_TIME_SKELETON",t[t.EXPECT_NUMBER_SKELETON=9]="EXPECT_NUMBER_SKELETON",t[t.EXPECT_DATE_TIME_SKELETON=10]="EXPECT_DATE_TIME_SKELETON",t[t.UNCLOSED_QUOTE_IN_ARGUMENT_STYLE=11]="UNCLOSED_QUOTE_IN_ARGUMENT_STYLE",t[t.EXPECT_SELECT_ARGUMENT_OPTIONS=12]="EXPECT_SELECT_ARGUMENT_OPTIONS",t[t.EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE=13]="EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE",t[t.INVALID_PLURAL_ARGUMENT_OFFSET_VALUE=14]="INVALID_PLURAL_ARGUMENT_OFFSET_VALUE",t[t.EXPECT_SELECT_ARGUMENT_SELECTOR=15]="EXPECT_SELECT_ARGUMENT_SELECTOR",t[t.EXPECT_PLURAL_ARGUMENT_SELECTOR=16]="EXPECT_PLURAL_ARGUMENT_SELECTOR",t[t.EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT=17]="EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT",t[t.EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT=18]="EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT",t[t.INVALID_PLURAL_ARGUMENT_SELECTOR=19]="INVALID_PLURAL_ARGUMENT_SELECTOR",t[t.DUPLICATE_PLURAL_ARGUMENT_SELECTOR=20]="DUPLICATE_PLURAL_ARGUMENT_SELECTOR",t[t.DUPLICATE_SELECT_ARGUMENT_SELECTOR=21]="DUPLICATE_SELECT_ARGUMENT_SELECTOR",t[t.MISSING_OTHER_CLAUSE=22]="MISSING_OTHER_CLAUSE",t[t.INVALID_TAG=23]="INVALID_TAG",t[t.INVALID_TAG_NAME=25]="INVALID_TAG_NAME",t[t.UNMATCHED_CLOSING_TAG=26]="UNMATCHED_CLOSING_TAG",t[t.UNCLOSED_TAG=27]="UNCLOSED_TAG"})(Oo||(Oo={}));var _o=class{constructor(e){console.warn(`[vite-messages-plugin]: Message "${e}" was not precompiled. Did you use the correct extenstion *.messages.ts?`)}};var le;(function(t){t[t.literal=0]="literal",t[t.argument=1]="argument",t[t.number=2]="number",t[t.date=3]="date",t[t.time=4]="time",t[t.select=5]="select",t[t.plural=6]="plural",t[t.pound=7]="pound",t[t.tag=8]="tag"})(le||(le={}));var Do;(function(t){t[t.number=0]="number",t[t.dateTime=1]="dateTime"})(Do||(Do={}));function cs(t){return t.type===le.literal}function Hi(t){return t.type===le.argument}function Ho(t){return t.type===le.number}function Fo(t){return t.type===le.date}function Bo(t){return t.type===le.time}function Ko(t){return t.type===le.select}function Uo(t){return t.type===le.plural}function Fi(t){return t.type===le.pound}function zo(t){return t.type===le.tag}function Vo(t){return!!(t&&typeof t=="object"&&t.type===Do.number)}function Vt(t){return!!(t&&typeof t=="object"&&t.type===Do.dateTime)}function ds(t){t.forEach(function(e){if(delete e.location,Ko(e)||Uo(e))for(var o in e.options)delete e.options[o].location,ds(e.options[o].value);else Ho(e)&&Vo(e.style)||(Fo(e)||Bo(e))&&Vt(e.style)?delete e.style.location:zo(e)&&ds(e.children)})}function Bi(t,e){e===void 0&&(e={}),e=te({shouldParseSkeletons:!0,requiresOtherClause:!0},e);var o=new _o(t,e).parse();if(o.err){var n=SyntaxError(Oo[o.err.kind]);throw n.location=o.err.location,n.originalMessage=o.err.message,n}return e!=null&&e.captureLocation||ds(o.val),o.val}function $o(t,e){var o=e&&e.cache?e.cache:Cp,n=e&&e.serializer?e.serializer:bp,s=e&&e.strategy?e.strategy:vp;return s(t,{cache:o,serializer:n})}function yp(t){return t==null||typeof t=="number"||typeof t=="boolean"}function Ki(t,e,o,n){var s=yp(n)?n:o(n),r=e.get(s);return typeof r>"u"&&(r=t.call(this,n),e.set(s,r)),r}function Ui(t,e,o){var n=Array.prototype.slice.call(arguments,3),s=o(n),r=e.get(s);return typeof r>"u"&&(r=t.apply(this,n),e.set(s,r)),r}function us(t,e,o,n,s){return o.bind(e,t,n,s)}function vp(t,e){var o=t.length===1?Ki:Ui;return us(t,this,o,e.cache.create(),e.serializer)}function Sp(t,e){return us(t,this,Ui,e.cache.create(),e.serializer)}function xp(t,e){return us(t,this,Ki,e.cache.create(),e.serializer)}var bp=function(){return JSON.stringify(arguments)};function ps(){this.cache=Object.create(null)}ps.prototype.get=function(t){return this.cache[t]};ps.prototype.set=function(t,e){this.cache[t]=e};var Cp={create:function(){return new ps}},qo={variadic:Sp,monadic:xp};var je;(function(t){t.MISSING_VALUE="MISSING_VALUE",t.INVALID_VALUE="INVALID_VALUE",t.MISSING_INTL_API="MISSING_INTL_API"})(je||(je={}));var $t=function(t){zt(e,t);function e(o,n,s){var r=t.call(this,o)||this;return r.code=n,r.originalMessage=s,r}return e.prototype.toString=function(){return"[formatjs Error: ".concat(this.code,"] ").concat(this.message)},e}(Error);var gs=function(t){zt(e,t);function e(o,n,s,r){return t.call(this,'Invalid values for "'.concat(o,'": "').concat(n,'". Options are "').concat(Object.keys(s).join('", "'),'"'),je.INVALID_VALUE,r)||this}return e}($t);var zi=function(t){zt(e,t);function e(o,n,s){return t.call(this,'Value for "'.concat(o,'" must be of type ').concat(n),je.INVALID_VALUE,s)||this}return e}($t);var Vi=function(t){zt(e,t);function e(o,n){return t.call(this,'The intl string context variable "'.concat(o,'" was not provided to the string "').concat(n,'"'),je.MISSING_VALUE,n)||this}return e}($t);var j;(function(t){t[t.literal=0]="literal",t[t.object=1]="object"})(j||(j={}));function wp(t){return t.length<2?t:t.reduce(function(e,o){var n=e[e.length-1];return!n||n.type!==j.literal||o.type!==j.literal?e.push(o):n.value+=o.value,e},[])}function Tp(t){return typeof t=="function"}function qt(t,e,o,n,s,r,i){if(t.length===1&&cs(t[0]))return[{type:j.literal,value:t[0].value}];for(var a=[],l=0,c=t;l<c.length;l++){var d=c[l];if(cs(d)){a.push({type:j.literal,value:d.value});continue}if(Fi(d)){typeof r=="number"&&a.push({type:j.literal,value:o.getNumberFormat(e).format(r)});continue}var u=d.value;if(!(s&&u in s))throw new Vi(u,i);var p=s[u];if(Hi(d)){(!p||typeof p=="string"||typeof p=="number")&&(p=typeof p=="string"||typeof p=="number"?String(p):""),a.push({type:typeof p=="string"?j.literal:j.object,value:p});continue}if(Fo(d)){var g=typeof d.style=="string"?n.date[d.style]:Vt(d.style)?d.style.parsedOptions:void 0;a.push({type:j.literal,value:o.getDateTimeFormat(e,g).format(p)});continue}if(Bo(d)){var g=typeof d.style=="string"?n.time[d.style]:Vt(d.style)?d.style.parsedOptions:n.time.medium;a.push({type:j.literal,value:o.getDateTimeFormat(e,g).format(p)});continue}if(Ho(d)){var g=typeof d.style=="string"?n.number[d.style]:Vo(d.style)?d.style.parsedOptions:void 0;g&&g.scale&&(p=p*(g.scale||1)),a.push({type:j.literal,value:o.getNumberFormat(e,g).format(p)});continue}if(zo(d)){var f=d.children,m=d.value,S=s[m];if(!Tp(S))throw new zi(m,"function",i);var w=qt(f,e,o,n,s,r),v=S(w.map(function(x){return x.value}));Array.isArray(v)||(v=[v]),a.push.apply(a,v.map(function(x){return{type:typeof x=="string"?j.literal:j.object,value:x}}))}if(Ko(d)){var y=d.options[p]||d.options.other;if(!y)throw new gs(d.value,p,Object.keys(d.options),i);a.push.apply(a,qt(y.value,e,o,n,s));continue}if(Uo(d)){var y=d.options["=".concat(p)];if(!y){if(!Intl.PluralRules)throw new $t(`Intl.PluralRules is not available in this environment.
1
+ var nu=Object.defineProperty;var Z=(t,e)=>{for(var o in e)nu(t,o,{get:e[o],enumerable:!0})};import Hr from"classnames";import du,{createContext as uu,useContext as $n,useEffect as pu,useState as gu}from"react";import su,{useContext as ru}from"react";import iu from"classnames";var _t=su.createContext({});function h(t,e){let{debug:o,...n}=ru(_t),s=n[t];return s?Object.entries(e).reduce((r,[i,a])=>{let l=s[i];return{...r,[i]:iu(a,l,o?`${t}__${i}`:!1)}},{}):e}var Dr={root:"jo"};import{jsx as go,jsxs as lu}from"react/jsx-runtime";var mo=()=>lu("svg",{className:Dr.root,width:"185",height:"170",viewBox:"0 0 185 170",xmlns:"http://www.w3.org/2000/svg",children:[go("defs",{children:go("style",{children:".cls-1 { fill: #b3b3b3; }"})}),go("title",{children:"Failed loading image"}),go("path",{className:"cls-1",d:"M15 130.896V16.994c0-1.097.898-1.994 2.007-1.994h150.986A2 2 0 0 1 170 16.994v69.147L133.015 51 87.26 120.377l-35.863-17.758L15 130.896zM2 0C.895 0 0 .887 0 2v166c0 1.105.887 2 2 2h181c1.105 0 2-.887 2-2V2c0-1.105-.887-2-2-2H2zm49 72c11.046 0 20-9.178 20-20.5S62.046 31 51 31s-20 9.178-20 20.5S39.954 72 51 72z",fillRule:"evenodd"})]});var Vn={root:"Yo",imageWrapper:"F",image:"qo",content:"m",title:"Co",contentIsCropped:"So",lineClamp:"Eo"};import{jsx as st}from"react/jsx-runtime";var fo=uu(Vn),mu=({title:t,src:e})=>{let o=$n(fo),[n,s]=gu(!1);return pu(()=>{s(!1)},[e]),st("div",{className:o.imageWrapper,children:e&&!n?st("img",{className:o.image,alt:t,src:e,onError:()=>s(!0)}):st(mo,{})})},fu=({className:t,lineClamp:e=!1,cropText:o=!1,children:n})=>{let s=$n(fo);return st("div",{className:Hr(s.content,t,{[s.contentIsCropped]:o,[s.lineClamp]:e}),children:n})},hu=({as:t="h1",cropText:e=!1,className:o,children:n,...s})=>{let r=$n(fo);return du.createElement(t,{className:Hr(r.title,o,{[r.contentIsCropped]:e}),...s},n)},ho=({children:t})=>{let e=h("Card",Vn);return st("div",{className:e.root,children:st(fo.Provider,{value:e,children:t})})};ho.Image=mu;ho.Content=fu;ho.Title=hu;var H=ho;import vu from"classnames";var Fr={root:"H"};import{jsx as bu}from"react/jsx-runtime";var Su={"arrow-up":"\u25B2","arrow-down":"\u25BC",tab:"tab",esc:"Esc",enter:"\u21B5"},xu=({className:t,keyCode:e,...o})=>{let n=h("KeyboardHint",Fr);return bu("span",{"data-key":Su[e],className:vu(t,n.root),...o})},qn=xu;import wu from"classnames";var Br={root:"Go"};import{jsx as Eu}from"react/jsx-runtime";var Tu=({className:t,children:e,...o})=>{let n=h("Label",Br);return Eu("span",{...o,className:wu(t,n.root),children:e})},Gn=Tu;var Kr={root:"No",subTitleContainer:"Ao",subtitle:"Fo",suggestions:"Ho"};import{jsx as jn,jsxs as Pu}from"react/jsx-runtime";var Ru=({title:t,children:e,type:o,...n})=>{let s=h("Section",Kr);return Pu("section",{...n,className:s.root,"data-section-type":o,children:[t&&jn("div",{className:s.subTitleContainer,children:jn("span",{className:s.subtitle,children:t})}),jn("div",{className:s.suggestions,children:e})]})},ke=Ru;import Lu from"classnames";import Au from"react";var Ur={root:"Lo"};import{jsx as Nu}from"react/jsx-runtime";var Mu=Au.forwardRef(({className:t,children:e},o)=>{let n=h("SectionList",Ur);return Nu("div",{ref:o,className:Lu(n.root,t),children:e})}),Wn=Mu;import Dt from"classnames";import Zn,{createContext as _u,useCallback as Du,useContext as rt}from"react";var Xn={fadein:"L",root:"e",isClickable:"M",isSelected:"Mo",actions:"R",actionsIsFixed:"Ro",actionButton:"t",dropdownList:"T",dropdownButton:"U",dropdownItem:"B",dropdownItemButton:"D",actionButtonIsPrimary:"To",actionButtonIsDisabled:"Uo",labels:"Bo",label:"Do",iconButtons:"I",iconButton:"n"};import{jsx as de,jsxs as $r}from"react/jsx-runtime";var Ke=_u(Xn),Hu=({fixed:t,children:e,...o})=>{let n=rt(Ke);return de("div",{...o,className:Dt(n.actions,{[n.actionsIsFixed]:t}),children:e})};function zr(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type===Vr}var Vr=({className:t,icon:e,title:o,...n})=>{let s=rt(Ke);return de("button",{type:"button",className:Dt(s.iconButton,t),title:o,"aria-label":o,...n,children:e})},Fu=({className:t,primary:e,disabled:o,label:n,children:s})=>{let r=rt(Ke);return $r("div",{className:Dt(t,r.actionButton,r.dropdownButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:o}),onMouseDown:i=>i.stopPropagation(),onClick:i=>i.stopPropagation(),children:[n,de("ul",{className:r.dropdownList,children:s})]})},Bu=({index:t,label:e,onClick:o})=>{let n=rt(Ke);return de("li",{className:n.dropdownItem,children:de("button",{className:n.dropdownItemButton,type:"button","data-index":t,onClick:o,children:e})})},Ku=({className:t,primary:e,disabled:o,onClick:n,label:s})=>{let r=rt(Ke);return de("button",{type:"button",className:Dt(t,r.actionButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:o}),onClick:n??(i=>i.stopPropagation()),disabled:o,"aria-hidden":o,children:s})},Uu=({labels:t})=>{let e=rt(Ke);return de("div",{className:e.labels,children:t.map(o=>de("span",{className:e.label,children:o},o))})},Ue=Zn.forwardRef(({className:t,selected:e,onClick:o,children:n,as:s="div",...r},i)=>{let a=h("Suggestion",Xn),l=Du(u=>{u.preventDefault(),o&&o(u)},[o]),c=Zn.Children.toArray(n).filter(zr),d=Zn.Children.toArray(n).filter(u=>!zr(u));return de(s,{...r,ref:i,className:Dt(t,a.root,{[a.isSelected]:e,[a.isClickable]:!!o}),onClick:l,children:$r(Ke.Provider,{value:a,children:[d,de("div",{className:a.iconButtons,children:c})]})})});Ue.Labels=Uu;Ue.Actions=Hu;Ue.ActionButton=Ku;Ue.DropdownButton=Fu;Ue.DropdownItem=Bu;Ue.IconButton=Vr;var M=Ue;import Vu from"classnames";var qr={root:"Io",isWithDivider:"Oo"};import{jsx as qu}from"react/jsx-runtime";var $u=({withDivider:t,children:e})=>{let o=h("SuggestionList",qr);return qu("div",{"data-testid":"suggestions-overlay-list",className:Vu(o.root,{[o.isWithDivider]:t}),children:e})},te=$u;import ju from"classnames";var Gr={root:"u",isCollapsed:"O"};import{jsx as Qn}from"react/jsx-runtime";var Wu=({className:t,isCollapsed:e,title:o,onClick:n})=>{let s=h("ToggleButton",Gr);return Qn("button",{type:"button",className:ju(s.root,t,{[s.isCollapsed]:e}),onClick:n,title:o,children:Qn("svg",{width:"14",height:"8",viewBox:"-2.5 -5 75 60",preserveAspectRatio:"none",children:Qn("path",{d:"M0,0 l35,50 l35,-50",fill:"none",stroke:"grey",strokeLinecap:"round",strokeWidth:"6"})})})},it=Wu;var jr=/(?:[.,;:!?\\n]|:\\)|:\\(|:-\\)|:-\\()/g,yo=/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\})/g;var Wr=/x-deepdesk-(([a-z0-9\-_])+-version)/,Re=(m=>(m.SEARCH="search",m.TEMPLATE="template",m.ELASTIC_SEARCH="search-autocomplete",m.GPT="gpt",m.TRIE="trie",m.TRIE_WITH_TYPOS="trie-with-typos",m.SEMANTIC="semantic",m.TEXT_RECOMMENDATION="text_recommendation",m.URL_RECOMMENDATION="url_recommendation",m.LINK_RECOMMENDATION="link_recommendation",m.PERSONAL_COLLECTION="personal-collection",m.PERSONAL_COLLECTION_SEARCH="personal-collection-search",m.SEARCH_OVERLAY="search-overlay",m.SEARCH_PREVIEW="search-preview",m.SEARCH_URL="search-url",m))(Re||{}),at=(r=>(r.ENTER="enter",r.TAB="tab",r.ARROW="arrow",r.HOTKEY="hotkey",r.MOUSE="mouse",r))(at||{});import{render as Nt,unmountComponentAtNode as Bn}from"react-dom";import{Fragment as rf}from"react";import{createSlice as Xu}from"@reduxjs/toolkit";import{useSelector as Zu}from"react-redux";var vo=(o=>(o.NL_NL="nl-NL",o.EN_US="en-US",o))(vo||{});var Qu={locale:"en-US",deanonymize:!1,fallbackImage:!1,isEmbedded:!1,showAutoflows:!1,showCustomMessages:!1,showImages:!1,showSearch:!1,showImageSearch:!1,showStyleSuggestions:!1,showMidSentenceSuggestions:!1,showSuggestionsBeforePattern:!1,showSuggestionsAfterPattern:!1,showTabCompletion:!0,showTextSuggestions:!0,showEntitiesCommand:!1,showSummaryCommand:!1,showKnowledgeSearch:!1,textSuggestionsCount:3,recommendTextSuggestions:!0,searchTriggerKey:"k",visible:!0,insertLink:!1,inlineSuggestions:!1,floatingMenu:!1,adminUrl:void 0,productName:"Deepdesk"},Xr=Xu({name:"settings",initialState:Qu,reducers:{set(t,e){Object.entries(e.payload).forEach(o=>{let[n,s]=o;typeof s>"u"||(t[n]=s)})}}}),{set:So}=Xr.actions,Jn=t=>e=>e.settings[t],b=t=>Zu(Jn(t)),Zr=Xr.reducer;import{useSelector as Ji}from"react-redux";import{createAsyncThunk as Yn,createSlice as Ju}from"@reduxjs/toolkit";var Yu={isLoggedIn:!0,loginFetchState:"idle",verifyFetchState:"idle",showLoginOverlay:!1},W=t=>t.auth.isLoggedIn,Qr=t=>t.auth.loginFetchState,Jr=t=>t.auth.verifyFetchState,Yr=t=>t.auth.showLoginOverlay,ve=Yn("auth/validate",async(t,e)=>e.extra.deepdeskAPI.isLoggedIn()),ei=Yn("auth/requestLogin",async({email:t},e)=>{let{deepdeskAPI:o}=e.extra;return o.requestLoginByEmail(t)}),Ht=Yn("auth/verifyLoginToken",async({token:t},e)=>{let{deepdeskAPI:o}=e.extra;return o.verifyLoginToken(t)}),ti=Ju({name:"auth",initialState:Yu,reducers:{setIsLoggedIn(t,e){t.isLoggedIn=e.payload},setShowLoginOverlay(t,e){t.showLoginOverlay=e.payload}},extraReducers:t=>{t.addCase(ve.pending,e=>{e.loginFetchState="loading"}),t.addCase(ve.fulfilled,(e,{payload:o})=>{e.isLoggedIn=o,e.loginFetchState="done"}),t.addCase(ve.rejected,e=>{e.loginFetchState="error",e.isLoggedIn=!1}),t.addCase(Ht.pending,e=>{e.verifyFetchState="loading"}),t.addCase(Ht.rejected,e=>{e.verifyFetchState="error"}),t.addCase(Ht.fulfilled,(e,o)=>{o.payload.isLoggedIn?e.verifyFetchState="done":e.verifyFetchState="error"})}}),{setIsLoggedIn:lt,setShowLoginOverlay:oi}=ti.actions,ni=ti.reducer;import{createAction as ut,createSlice as lp}from"@reduxjs/toolkit";import{diffChars as cp}from"diff";import{useSelector as dp}from"react-redux";function si(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function Pe(t,e,o=10){let n=typeof t,s=typeof e;if(o===0)throw new Error("Max depth deepEqual, possible circular references?");return n!==s?!1:t==null||n==="string"||n==="number"||n==="boolean"?t===e:Array.isArray(t)&&Array.isArray(e)?t.length!==e.length?!1:t.every((r,i)=>Pe(r,e[i],o-1)):si(t)&&si(e)?Object.keys(t).length!==Object.keys(e).length?!1:Object.keys(t).every(i=>Pe(t[i],e[i],o-1)):!1}function ep(t){return Math.max(...t.map(e=>e.length))}function tp(t,e){let o=t.reduce((n,s)=>{if(s){let r=n[s]?n[s]+1:1;return{...n,[s]:r}}return n},{});return Object.keys(o).reduce((n,s)=>(o[s]<e&&n.push(s),n),[])}function ri(t,e){let n=[...t.map(({text:s})=>s.split(/\b(\w+)\b/))];for(let s=0;s<ep(n);s++){let r=tp(n.map(a=>a[s]),e),i=n.filter(a=>!r.includes(a[s]));if(i.length>=e)n=i;else return{text:n[0].slice(0,s).join("").replace(/ (\?| |!|\.|,|\n)/g,"$1").trimEnd(),source:"mixed"}}}var op=2;function es(t,e=""){if(t.length===0)return;if(t.length===1)return t[0];let o=ri(t,op);return o&&o.text!==e?o:t[0]}import{createAction as sp,createAsyncThunk as ct,createSlice as rp}from"@reduxjs/toolkit";var np={info(...t){console.info("[Deepdesk]",...t)},warn(...t){console.warn("[Deepdesk]",...t)},error(...t){console.error("[Deepdesk]",...t)}},T=np;var ii={current:null,isSupported:null},_=sp("resetConversation"),xo=t=>{let{current:e}=t.conversation;return(e==null?void 0:e.sessionId)||null},bo=t=>{let{current:e}=t.conversation;return(e==null?void 0:e.id)||null},dt=t=>t.conversation.isSupported,ts=ct("conversation/isSupported",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.isConversationSupported(t.sessionId,t.options)}),Co=ct("conversation/create",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.createConversation(t)}),wo=ct("conversation/bySessionId",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.getConversationBySessionId(t.sessionId,t.options)}),To=ct("conversation/update",(t,e)=>{let{deepdeskAPI:o}=e.extra,n=bo(e.getState());if(!n)throw new Error("No current conversation to update");return o.updateConversation(n,t)}),os=ct("conversation/upsert",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.getConversationBySessionId(t.sessionId).catch(()=>null).then(n=>{if(!n)return o.createConversation(t);let{agentId:s,agentName:r,agentEmail:i,agentNickname:a,tags:l}=t;return o.updateConversation(n.id,{agentId:s,agentEmail:i,agentName:r,agentNickname:a,tags:l})})}),Eo=ct("conversation/postMessages",(t,e)=>{let{deepdeskAPI:o}=e.extra,n=bo(e.getState());if(!n)throw new Error("No current conversation to update messages");return o.postMessages(n,t.map(s=>({...s})))}),ip=[Co.rejected,wo.rejected,To.rejected,Eo.rejected].map(t=>t==null?void 0:t.toString()),ap=rp({name:"conversation",initialState:ii,reducers:{},extraReducers:t=>{t.addCase(ts.fulfilled,(e,o)=>{e.isSupported=o.payload}).addCase(Co.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(wo.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(os.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(To.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(Eo.fulfilled,(e,o)=>{e.current&&(e.current.messages=o.payload)}).addCase(_,()=>ii).addMatcher(e=>ip.includes(e.type),(e,o)=>{var n;throw T.info("Conversation action rejected",o.type,((n=o.error)==null?void 0:n.message)||"No message"),new Error(o.error.message)})}}),ai=ap.reducer;var Ie={text:"",html:null,selection:{start:0,end:0},stagedSuggestion:null,userCommitted:{text:"",selection:{start:0,end:0}},tabCompletionSuggestion:void 0,previousKeyDownEvent:null,textSuggestions:[],selectedSuggestionIndex:-1,metrics:{numCharsTyped:0,numCharsPasted:0,numCharsCut:0,numCharsDeleted:0,numPaste:0,agentStartedTypingTimestamp:null,externalTimeTotalSeconds:null,pastes:[],deletions:[],offeredTextSuggestions:[],textSuggestions:[],cuts:[]}};function li(t){let{key:e,shiftKey:o,ctrlKey:n,metaKey:s,altKey:r}=t;return{key:e,shiftKey:o,ctrlKey:n,metaKey:s,altKey:r}}var Ro=ut("input/replaceText"),Po=ut("input/keyDown"),ze=ut("input/sendMessage"),Io=ut("input/uiInputChange"),Lo=ut("input/applyImageSuggestion"),G=ut("input/sendEvent");function ko(t){if(!t.stagedSuggestion)return;let{text:e,suggestion:{source:o,abVariant:n,abTestName:s,trainingJobs:r,sourceText:i,searchTerm:a,text:l},eventMetrics:{inputType:c},replace:d}=t.stagedSuggestion,u=o==="search"||o==="personal-collection-search",g=e.slice(t.userCommitted.text.substring(0,t.userCommitted.selection.start).length);(u||d==="selection")&&(g=e),t.stagedSuggestion.suggestion.source==="search-overlay"&&(g=l),t.userCommitted.text=t.text,t.userCommitted.selection=t.selection,t.metrics.textSuggestions.push({text:g,source:o,abVariant:n,abTestName:s,inputType:c,sourceText:i,trainingJobs:r||[],searchTerm:u?t.userCommitted.text:a}),t.stagedSuggestion=null,t.textSuggestions=[],t.selectedSuggestionIndex=-1}var ci=lp({name:"input",initialState:Ie,reducers:{initialInput(t,e){let{text:o,selection:n,html:s}=e.payload;t.text=o,t.selection.start=(n==null?void 0:n.start)??o.length,t.selection.end=(n==null?void 0:n.end)??o.length,t.userCommitted.text=o,t.userCommitted.selection.start=(n==null?void 0:n.start)??o.length,t.userCommitted.selection.end=(n==null?void 0:n.end)??o.length,t.html=s||null},reset(t){Object.assign(t,{...Ie,selection:t.selection})},resetToCommitted(t){t.text=t.userCommitted.text,t.selection=t.userCommitted.selection,t.stagedSuggestion=null,t.tabCompletionSuggestion=es(t.textSuggestions,t.userCommitted.text)},changeSelection(t,e){e.payload&&(Pe(t.selection,e.payload)||(t.selection=e.payload,t.userCommitted.selection=t.selection,t.stagedSuggestion&&ko(t)))},platformInput(t,e){let{text:o,html:n,selection:s}=e.payload;s&&(t.selection.start=s.start,t.selection.end=s.end),t.text=o,t.html=n||null},userInput(t,e){var r,i,a,l;if(t.previousKeyDownEvent){let{key:c,shiftKey:d,ctrlKey:u,metaKey:g,altKey:p}=t.previousKeyDownEvent;switch(c){case"Enter":d&&(t.metrics.numCharsTyped+=1);break;case"Backspace":case"Delete":{let{text:f}=t,{text:m}=e.payload,y=cp(f,m);f.length-m.length>1&&t.metrics.deletions.push(...y.filter(E=>E.removed).map(E=>E.value)),t.metrics.numCharsDeleted+=f.length-m.length;break}case"C":case"V":case"X":if(!u&&!g){t.metrics.numCharsTyped+=1;let f=((r=t.selection)==null?void 0:r.start)!==void 0&&((i=t.selection)==null?void 0:i.end)!==void 0?t.text.substring(t.selection.start,t.selection.end):null;f&&f.length>0&&(t.metrics.numCharsDeleted+=f.length,t.metrics.deletions.push(f))}break;case"Shift":break;default:if(!u&&!g&&!p){t.metrics.numCharsTyped+=1;let f=((a=t.selection)==null?void 0:a.start)!==void 0&&((l=t.selection)==null?void 0:l.end)!==void 0?t.text.substring(t.selection.start,t.selection.end):null;f&&f.length>0&&(t.metrics.numCharsDeleted+=f.length,t.metrics.deletions.push(f))}}}!t.metrics.agentStartedTypingTimestamp&&e.payload.text!==t.text&&(t.metrics.agentStartedTypingTimestamp=Date.now()),e.payload.text===""&&(t.metrics=Ie.metrics,t.textSuggestions=[],t.stagedSuggestion=null),t.text!==e.payload.text&&ko(t);let{text:o,html:n,selection:s}=e.payload;s&&(t.selection.start=s.start,t.selection.end=s.end,t.userCommitted.selection.start=s.start,t.userCommitted.selection.end=s.end),t.text=o,t.html=n||null,t.userCommitted.text=o,t.previousKeyDownEvent=null},stageSuggestion(t,e){let{text:o}=e.payload;switch(t.stagedSuggestion=e.payload,t.tabCompletionSuggestion=void 0,e.payload.replace){case"selection":t.text=`${t.text.slice(0,t.selection.start)}${o}${t.text.slice(t.selection.end)}`,t.selection.end=t.selection.start+o.length,t.selection.start+=o.length;break;case"until-selection-end":t.text=`${o}${t.text.slice(t.selection.end)}`,t.selection.start=o.length,t.selection.end=o.length;break;default:throw new Error(`Unknown replace ${e.payload.replace}`)}e.payload.eventMetrics.inputType==="tab"&&ko(t)},commitSuggestion(t){ko(t)},offeredTextSuggestion(t,e){let{text:o,suggestion:{source:n}}=e.payload;t.metrics.offeredTextSuggestions.find(r=>r.text===o)||t.metrics.offeredTextSuggestions.push({text:o,source:n})},registerCut(t,e){let{metrics:o}=t,n=e.payload;t.metrics={...t.metrics,numCharsCut:o.numCharsCut+n.length,cuts:[...o.cuts,n]}},registerPaste(t,e){let{metrics:o}=t,{text:n,selectionText:s}=e.payload,r=o.numCharsDeleted+(s&&s.length?s.length:0),i=s&&s.length?[...o.deletions,s]:o.deletions;t.metrics={...t.metrics,numCharsDeleted:r,deletions:i,numCharsPasted:o.numCharsPasted+n.length,numPaste:o.numPaste+1,pastes:[...o.pastes,n]}},registerKeyDown(t,e){t.previousKeyDownEvent=e.payload},nextTextSuggestionIndex(t){let e=t.textSuggestions.length;t.selectedSuggestionIndex=t.selectedSuggestionIndex<e-1?t.selectedSuggestionIndex+1:t.selectedSuggestionIndex},previousTextSuggestionIndex(t){t.selectedSuggestionIndex=t.selectedSuggestionIndex>=0?t.selectedSuggestionIndex-1:t.selectedSuggestionIndex},setTextSuggestions(t,e){if(t.selectedSuggestionIndex=-1,t.textSuggestions=e.payload,e.payload.length===0)return;let o=t.userCommitted.text.substring(0,t.userCommitted.selection.end),n=es(e.payload,o);t.tabCompletionSuggestion=n!=null&&n.text.includes(o)?n:void 0},setSelectedTextSuggestionIndex(t,e){t.selectedSuggestionIndex=e.payload},setMetrics(t,{payload:e}){t.metrics=e}},extraReducers:t=>{t.addCase(_,e=>{e.tabCompletionSuggestion=Ie.tabCompletionSuggestion,e.previousKeyDownEvent=Ie.previousKeyDownEvent,e.textSuggestions=Ie.textSuggestions,e.selectedSuggestionIndex=Ie.selectedSuggestionIndex,e.metrics=Ie.metrics})}}),pt=t=>t.input.userCommitted.text.substring(0,t.input.userCommitted.selection.end),up=t=>t.input.selection,di=()=>dp(up),{userInput:ui,changeSelection:ns,initialInput:pi,nextTextSuggestionIndex:gi,offeredTextSuggestion:mi,previousTextSuggestionIndex:fi,registerCut:hi,registerKeyDown:yi,registerPaste:vi,reset:Si,resetToCommitted:Ft,platformInput:xi,setSelectedTextSuggestionIndex:Le,setTextSuggestions:ue,stageSuggestion:pe,commitSuggestion:Se,setMetrics:bi}=ci.actions,Ci=ci.reducer;import{createAsyncThunk as fp,createSlice as hp}from"@reduxjs/toolkit";import{createAsyncThunk as rs,createSlice as gp}from"@reduxjs/toolkit";function pp(t){return t.replace(/(_\w)/g,e=>e[1].toUpperCase())}function L(t){return Array.isArray(t)?t.map(L):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,o)=>({...e,[pp(o)]:L(t[o])}),{}):t}function ss(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function K(t){return Array.isArray(t)?t.map(K):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,o)=>({...e,[ss(o)]:K(t[o])}),{}):t}var mp={agentInfo:void 0,agentSettings:{},visitorInfo:void 0,fetchState:"idle"},Kt=t=>{var e,o,n;return{timezone:((e=t.info.visitorInfo)==null?void 0:e.visitorTimeZone)||Intl.DateTimeFormat().resolvedOptions().timeZone,agentName:((o=t.info.agentInfo)==null?void 0:o.agentNickname)||"",visitorName:((n=t.info.visitorInfo)==null?void 0:n.visitorName)||""}},Bt=rs("info/setAgentInfo",async(t,e)=>{let{deepdeskAPI:o}=e.extra;if(!t.agentId&&!t.agentNickname)throw new Error("At least provide agentId or agentNickname");let n=await o.client.get("/apis/admin/session/me/",{version:null}),s={};return n.external_id||(s.external_id=t.agentId),n.nickname||(s.nickname=t.agentNickname),!s.external_id&&!s.nickname?L(n):(await o.client.patch("/apis/admin/session/me/",s,{version:null}),L(n))}),is=rs("info/setAgentSettings",async(t,e)=>{let{deepdeskAPI:o}=e.extra,n=await o.client.get("/apis/admin/session/me/",{version:null}),s={...typeof n.ui_config=="object"?n.ui_config:{},...t};return await o.client.patch("/apis/admin/session/me/",{ui_config:s}),s}),as=rs("info/getAgentSettings",async(t,e)=>{let{deepdeskAPI:o}=e.extra;return(await o.client.get("/apis/admin/session/me/",{version:null})).ui_config}),wi=t=>t.info.agentInfo,Ti=gp({name:"info",initialState:mp,reducers:{setVisitorInfo(t,e){t.visitorInfo={...t.visitorInfo,...e.payload}}},extraReducers:t=>{t.addCase(Bt.pending,(e,o)=>{e.fetchState="loading",e.agentInfo={...e.agentInfo,...o.meta.arg}}).addCase(Bt.rejected,e=>{e.fetchState="error"}).addCase(Bt.fulfilled,(e,o)=>{e.fetchState="done",e.agentInfo={...e.agentInfo,...o.meta.arg,agentId:o.payload.externalId||o.meta.arg.agentId||"",agentNickname:o.payload.nickname||o.meta.arg.agentNickname||""}}).addCase(is.fulfilled,(e,o)=>{e.agentSettings=o.payload}).addCase(as.fulfilled,(e,o)=>{e.agentSettings=o.payload}).addCase(_,e=>{e.visitorInfo=void 0})}}),{setVisitorInfo:Ei}=Ti.actions,ki=Ti.reducer;var Ao={list:[],fetchState:"idle",isOpen:!1,page:"search",aggregates:{}},Ri=t=>t.search.isOpen,Pi=t=>t.search.page,Ii=t=>t.search.list,Li=t=>t.search.aggregates;function Ai(t,e=o=>o){return o=>o.search.list.filter(n=>n.type===t).map(e)}var Ve=fp("search/getAll",async(t,e)=>{var a;let{deepdeskAPI:o}=e.extra,n=e.getState(),s=(a=n.conversation.current)==null?void 0:a.profileCode;if(!s)throw new Error("Profile should be provided in order to be able to search");let{results:r,aggregates:i}=await o.search({profile:s,query:t.query,tags:t.tags,size:t.size,current:t.current,filters:{type:t.type},params:Kt(n)});return{results:r.map(l=>({...l,source:`search-${l.type.toLowerCase()}`,searchTerm:t.query})),aggregates:i}}),Mi=hp({name:"search",initialState:Ao,reducers:{setIsOpen(t,e){t.isOpen=e.payload},setPage(t,e){t.page=e.payload},resetSearch(t){t.fetchState=Ao.fetchState,t.list=Ao.list}},extraReducers:t=>{t.addCase(Ve.pending,e=>{e.fetchState="loading"}).addCase(Ve.rejected,(e,o)=>{e.fetchState="error",T.error(o.error)}).addCase(Ve.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload.results,e.aggregates=o.payload.aggregates||{}}).addCase(_,()=>Ao)}}),{resetSearch:Mo,setIsOpen:Y,setPage:re}=Mi.actions,Ni=Mi.reducer;var ls="SetCues",gt="ShowLoginOverlay",Ut="UserLoggedIn",yp="UserLoggedOut",Ae="ApplySuggestion",cs="ApplyImageSuggestion",vp="ShowCommandPalette",Sp=t=>({[ls]:e=>{t.dispatch({...e,isBroadcasted:!0})},[vp]:e=>{t.dispatch(Y(e.isOpen)),e.page&&t.dispatch(re(e.page))},[gt]:e=>{t.dispatch(oi(e))},[Ut]:()=>{t.dispatch(ve())},[yp]:()=>{t.dispatch(ve())},[cs]:e=>{t.dispatch(Lo({suggestion:e.suggestion}))},[Ae]:e=>{t.dispatch(pe({...e,eventMetrics:{inputType:"mouse"},replace:"selection"})),t.dispatch(Se())}}),Oi=Sp;import _i,{useContext as xp}from"react";import{jsx as bp}from"react/jsx-runtime";var Di=_i.createContext(null),$e=({broadcastEvents:t,children:e})=>{let o=_i.useMemo(()=>t,[]);return bp(Di.Provider,{value:o,children:e})},oe=()=>{let t=xp(Di);if(!t)throw new Error("You should use the useBroadcastEvents within a BroadcastEventsProvider");return t};import Ss from"classnames";import{useCallback as Zi,useEffect as Wp,useMemo as Xp,useState as xs}from"react";import{useDispatch as Zp,useSelector as Qp}from"react-redux";import{createContext as Np,useContext as Op}from"react";var ds=function(t,e){return ds=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,n){o.__proto__=n}||function(o,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(o[s]=n[s])},ds(t,e)};function zt(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");ds(t,e);function o(){this.constructor=t}t.prototype=e===null?Object.create(e):(o.prototype=e.prototype,new o)}var ee=function(){return ee=Object.assign||function(e){for(var o,n=1,s=arguments.length;n<s;n++){o=arguments[n];for(var r in o)Object.prototype.hasOwnProperty.call(o,r)&&(e[r]=o[r])}return e},ee.apply(this,arguments)};function Hi(t,e){var o={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(o[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(o[n[s]]=t[n[s]]);return o}function No(t,e,o){if(o||arguments.length===2)for(var n=0,s=e.length,r;n<s;n++)(r||!(n in e))&&(r||(r=Array.prototype.slice.call(e,0,n)),r[n]=e[n]);return t.concat(r||Array.prototype.slice.call(e))}var Oo;(function(t){t[t.EXPECT_ARGUMENT_CLOSING_BRACE=1]="EXPECT_ARGUMENT_CLOSING_BRACE",t[t.EMPTY_ARGUMENT=2]="EMPTY_ARGUMENT",t[t.MALFORMED_ARGUMENT=3]="MALFORMED_ARGUMENT",t[t.EXPECT_ARGUMENT_TYPE=4]="EXPECT_ARGUMENT_TYPE",t[t.INVALID_ARGUMENT_TYPE=5]="INVALID_ARGUMENT_TYPE",t[t.EXPECT_ARGUMENT_STYLE=6]="EXPECT_ARGUMENT_STYLE",t[t.INVALID_NUMBER_SKELETON=7]="INVALID_NUMBER_SKELETON",t[t.INVALID_DATE_TIME_SKELETON=8]="INVALID_DATE_TIME_SKELETON",t[t.EXPECT_NUMBER_SKELETON=9]="EXPECT_NUMBER_SKELETON",t[t.EXPECT_DATE_TIME_SKELETON=10]="EXPECT_DATE_TIME_SKELETON",t[t.UNCLOSED_QUOTE_IN_ARGUMENT_STYLE=11]="UNCLOSED_QUOTE_IN_ARGUMENT_STYLE",t[t.EXPECT_SELECT_ARGUMENT_OPTIONS=12]="EXPECT_SELECT_ARGUMENT_OPTIONS",t[t.EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE=13]="EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE",t[t.INVALID_PLURAL_ARGUMENT_OFFSET_VALUE=14]="INVALID_PLURAL_ARGUMENT_OFFSET_VALUE",t[t.EXPECT_SELECT_ARGUMENT_SELECTOR=15]="EXPECT_SELECT_ARGUMENT_SELECTOR",t[t.EXPECT_PLURAL_ARGUMENT_SELECTOR=16]="EXPECT_PLURAL_ARGUMENT_SELECTOR",t[t.EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT=17]="EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT",t[t.EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT=18]="EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT",t[t.INVALID_PLURAL_ARGUMENT_SELECTOR=19]="INVALID_PLURAL_ARGUMENT_SELECTOR",t[t.DUPLICATE_PLURAL_ARGUMENT_SELECTOR=20]="DUPLICATE_PLURAL_ARGUMENT_SELECTOR",t[t.DUPLICATE_SELECT_ARGUMENT_SELECTOR=21]="DUPLICATE_SELECT_ARGUMENT_SELECTOR",t[t.MISSING_OTHER_CLAUSE=22]="MISSING_OTHER_CLAUSE",t[t.INVALID_TAG=23]="INVALID_TAG",t[t.INVALID_TAG_NAME=25]="INVALID_TAG_NAME",t[t.UNMATCHED_CLOSING_TAG=26]="UNMATCHED_CLOSING_TAG",t[t.UNCLOSED_TAG=27]="UNCLOSED_TAG"})(Oo||(Oo={}));var _o=class{constructor(e){console.warn(`[vite-messages-plugin]: Message "${e}" was not precompiled. Did you use the correct extenstion *.messages.ts?`)}};var ie;(function(t){t[t.literal=0]="literal",t[t.argument=1]="argument",t[t.number=2]="number",t[t.date=3]="date",t[t.time=4]="time",t[t.select=5]="select",t[t.plural=6]="plural",t[t.pound=7]="pound",t[t.tag=8]="tag"})(ie||(ie={}));var Do;(function(t){t[t.number=0]="number",t[t.dateTime=1]="dateTime"})(Do||(Do={}));function us(t){return t.type===ie.literal}function Fi(t){return t.type===ie.argument}function Ho(t){return t.type===ie.number}function Fo(t){return t.type===ie.date}function Bo(t){return t.type===ie.time}function Ko(t){return t.type===ie.select}function Uo(t){return t.type===ie.plural}function Bi(t){return t.type===ie.pound}function zo(t){return t.type===ie.tag}function Vo(t){return!!(t&&typeof t=="object"&&t.type===Do.number)}function Vt(t){return!!(t&&typeof t=="object"&&t.type===Do.dateTime)}function ps(t){t.forEach(function(e){if(delete e.location,Ko(e)||Uo(e))for(var o in e.options)delete e.options[o].location,ps(e.options[o].value);else Ho(e)&&Vo(e.style)||(Fo(e)||Bo(e))&&Vt(e.style)?delete e.style.location:zo(e)&&ps(e.children)})}function Ki(t,e){e===void 0&&(e={}),e=ee({shouldParseSkeletons:!0,requiresOtherClause:!0},e);var o=new _o(t,e).parse();if(o.err){var n=SyntaxError(Oo[o.err.kind]);throw n.location=o.err.location,n.originalMessage=o.err.message,n}return e!=null&&e.captureLocation||ps(o.val),o.val}function $o(t,e){var o=e&&e.cache?e.cache:Rp,n=e&&e.serializer?e.serializer:kp,s=e&&e.strategy?e.strategy:wp;return s(t,{cache:o,serializer:n})}function Cp(t){return t==null||typeof t=="number"||typeof t=="boolean"}function Ui(t,e,o,n){var s=Cp(n)?n:o(n),r=e.get(s);return typeof r>"u"&&(r=t.call(this,n),e.set(s,r)),r}function zi(t,e,o){var n=Array.prototype.slice.call(arguments,3),s=o(n),r=e.get(s);return typeof r>"u"&&(r=t.apply(this,n),e.set(s,r)),r}function gs(t,e,o,n,s){return o.bind(e,t,n,s)}function wp(t,e){var o=t.length===1?Ui:zi;return gs(t,this,o,e.cache.create(),e.serializer)}function Tp(t,e){return gs(t,this,zi,e.cache.create(),e.serializer)}function Ep(t,e){return gs(t,this,Ui,e.cache.create(),e.serializer)}var kp=function(){return JSON.stringify(arguments)};function ms(){this.cache=Object.create(null)}ms.prototype.get=function(t){return this.cache[t]};ms.prototype.set=function(t,e){this.cache[t]=e};var Rp={create:function(){return new ms}},qo={variadic:Tp,monadic:Ep};var qe;(function(t){t.MISSING_VALUE="MISSING_VALUE",t.INVALID_VALUE="INVALID_VALUE",t.MISSING_INTL_API="MISSING_INTL_API"})(qe||(qe={}));var $t=function(t){zt(e,t);function e(o,n,s){var r=t.call(this,o)||this;return r.code=n,r.originalMessage=s,r}return e.prototype.toString=function(){return"[formatjs Error: ".concat(this.code,"] ").concat(this.message)},e}(Error);var fs=function(t){zt(e,t);function e(o,n,s,r){return t.call(this,'Invalid values for "'.concat(o,'": "').concat(n,'". Options are "').concat(Object.keys(s).join('", "'),'"'),qe.INVALID_VALUE,r)||this}return e}($t);var Vi=function(t){zt(e,t);function e(o,n,s){return t.call(this,'Value for "'.concat(o,'" must be of type ').concat(n),qe.INVALID_VALUE,s)||this}return e}($t);var $i=function(t){zt(e,t);function e(o,n){return t.call(this,'The intl string context variable "'.concat(o,'" was not provided to the string "').concat(n,'"'),qe.MISSING_VALUE,n)||this}return e}($t);var j;(function(t){t[t.literal=0]="literal",t[t.object=1]="object"})(j||(j={}));function Pp(t){return t.length<2?t:t.reduce(function(e,o){var n=e[e.length-1];return!n||n.type!==j.literal||o.type!==j.literal?e.push(o):n.value+=o.value,e},[])}function Ip(t){return typeof t=="function"}function qt(t,e,o,n,s,r,i){if(t.length===1&&us(t[0]))return[{type:j.literal,value:t[0].value}];for(var a=[],l=0,c=t;l<c.length;l++){var d=c[l];if(us(d)){a.push({type:j.literal,value:d.value});continue}if(Bi(d)){typeof r=="number"&&a.push({type:j.literal,value:o.getNumberFormat(e).format(r)});continue}var u=d.value;if(!(s&&u in s))throw new $i(u,i);var g=s[u];if(Fi(d)){(!g||typeof g=="string"||typeof g=="number")&&(g=typeof g=="string"||typeof g=="number"?String(g):""),a.push({type:typeof g=="string"?j.literal:j.object,value:g});continue}if(Fo(d)){var p=typeof d.style=="string"?n.date[d.style]:Vt(d.style)?d.style.parsedOptions:void 0;a.push({type:j.literal,value:o.getDateTimeFormat(e,p).format(g)});continue}if(Bo(d)){var p=typeof d.style=="string"?n.time[d.style]:Vt(d.style)?d.style.parsedOptions:n.time.medium;a.push({type:j.literal,value:o.getDateTimeFormat(e,p).format(g)});continue}if(Ho(d)){var p=typeof d.style=="string"?n.number[d.style]:Vo(d.style)?d.style.parsedOptions:void 0;p&&p.scale&&(g=g*(p.scale||1)),a.push({type:j.literal,value:o.getNumberFormat(e,p).format(g)});continue}if(zo(d)){var f=d.children,m=d.value,y=s[m];if(!Ip(y))throw new Vi(m,"function",i);var E=qt(f,e,o,n,s,r),S=y(E.map(function(x){return x.value}));Array.isArray(S)||(S=[S]),a.push.apply(a,S.map(function(x){return{type:typeof x=="string"?j.literal:j.object,value:x}}))}if(Ko(d)){var v=d.options[g]||d.options.other;if(!v)throw new fs(d.value,g,Object.keys(d.options),i);a.push.apply(a,qt(v.value,e,o,n,s));continue}if(Uo(d)){var v=d.options["=".concat(g)];if(!v){if(!Intl.PluralRules)throw new $t(`Intl.PluralRules is not available in this environment.
2
2
  Try polyfilling it using "@formatjs/intl-pluralrules"
3
- `,je.MISSING_INTL_API,i);var k=o.getPluralRules(e,{type:d.pluralType}).select(p-(d.offset||0));y=d.options[k]||d.options.other}if(!y)throw new gs(d.value,p,Object.keys(d.options),i);a.push.apply(a,qt(y.value,e,o,n,s,p-(d.offset||0)));continue}}return wp(a)}function Ep(t,e){return e?te(te(te({},t||{}),e||{}),Object.keys(t).reduce(function(o,n){return o[n]=te(te({},t[n]),e[n]||{}),o},{})):t}function kp(t,e){return e?Object.keys(t).reduce(function(o,n){return o[n]=Ep(t[n],e[n]),o},te({},t)):t}function ms(t){return{create:function(){return{get:function(e){return t[e]},set:function(e,o){t[e]=o}}}}}function Rp(t){return t===void 0&&(t={number:{},dateTime:{},pluralRules:{}}),{getNumberFormat:$o(function(){for(var e,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];return new((e=Intl.NumberFormat).bind.apply(e,No([void 0],o,!1)))},{cache:ms(t.number),strategy:qo.variadic}),getDateTimeFormat:$o(function(){for(var e,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];return new((e=Intl.DateTimeFormat).bind.apply(e,No([void 0],o,!1)))},{cache:ms(t.dateTime),strategy:qo.variadic}),getPluralRules:$o(function(){for(var e,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];return new((e=Intl.PluralRules).bind.apply(e,No([void 0],o,!1)))},{cache:ms(t.pluralRules),strategy:qo.variadic})}}var $i=function(){function t(e,o,n,s){o===void 0&&(o=t.defaultLocale);var r=this;if(this.formatterCache={number:{},dateTime:{},pluralRules:{}},this.format=function(c){var d=r.formatToParts(c);if(d.length===1)return d[0].value;var u=d.reduce(function(p,g){return!p.length||g.type!==j.literal||typeof p[p.length-1]!="string"?p.push(g.value):p[p.length-1]+=g.value,p},[]);return u.length<=1?u[0]||"":u},this.formatToParts=function(c){return qt(r.ast,r.locales,r.formatters,r.formats,c,void 0,r.message)},this.resolvedOptions=function(){var c;return{locale:((c=r.resolvedLocale)===null||c===void 0?void 0:c.toString())||Intl.NumberFormat.supportedLocalesOf(r.locales)[0]}},this.getAst=function(){return r.ast},this.locales=o,this.resolvedLocale=t.resolveLocale(o),typeof e=="string"){if(this.message=e,!t.__parse)throw new TypeError("IntlMessageFormat.__parse must be set to process `message` of type `string`");var i=s||{},a=i.formatters,l=Di(i,["formatters"]);this.ast=t.__parse(e,te(te({},l),{locale:this.resolvedLocale}))}else this.ast=e;if(!Array.isArray(this.ast))throw new TypeError("A message must be provided as a String or AST.");this.formats=kp(t.formats,n),this.formatters=s&&s.formatters||Rp(this.formatterCache)}return Object.defineProperty(t,"defaultLocale",{get:function(){return t.memoizedDefaultLocale||(t.memoizedDefaultLocale=new Intl.NumberFormat().resolvedOptions().locale),t.memoizedDefaultLocale},enumerable:!1,configurable:!0}),t.memoizedDefaultLocale=null,t.resolveLocale=function(e){if(!(typeof Intl.Locale>"u")){var o=Intl.NumberFormat.supportedLocalesOf(e);return o.length>0?new Intl.Locale(o[0]):new Intl.Locale(typeof e=="string"?e:e[0])}},t.__parse=Bi,t.formats={number:{integer:{maximumFractionDigits:0},currency:{style:"currency"},percent:{style:"percent"}},date:{short:{month:"numeric",day:"numeric",year:"2-digit"},medium:{month:"short",day:"numeric",year:"numeric"},long:{month:"long",day:"numeric",year:"numeric"},full:{weekday:"long",month:"long",day:"numeric",year:"numeric"}},time:{short:{hour:"numeric",minute:"numeric"},medium:{hour:"numeric",minute:"numeric",second:"numeric"},long:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"},full:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"}}},t}();function Ap(t,e){return e.split(".").reduce((o,n)=>o?o[n]:void 0,t)}var Lp="dummy",fs=Pp(null);function R(t){let e=Ip(fs);if(!e)throw new Error("useTranslator() may be used only in the context of a <LocaleContext> component.");let o=t[e]??{};return(n,s)=>{let r=Ap(o,n);return r?new $i(r).format(s):(e!==Lp&&console.warn(`${n} does not exist in messages of ${e}`),`[${n}]`)}}import{useEffect as Np,useRef as Op}from"react";var qi={root:"U",content:"To"};import{jsx as Gi}from"react/jsx-runtime";var _p=({isOpen:t,autoFocus:e,children:o,onClose:n,onBack:s,onKeyDown:r,overlayAriaLabel:i,contentAriaLabel:a})=>{let l=Op(null),c=h("Dialog",qi),d=p=>{if(p.key==="Escape"){p.preventDefault(),p.stopPropagation(),s();return}r&&r(p)},u=p=>{p.target===l.current&&t&&n()};return Np(()=>{var p,g;!l.current||!t||!e||(g=(p=l.current)==null?void 0:p.querySelector("input, textarea"))==null||g.focus()},[t,e,l]),t?Gi("div",{role:"dialog","data-testid":"dialog",className:c.root,"aria-label":i,ref:l,onKeyDown:d,onMouseDown:u,children:Gi("div",{"data-testid":"dialog-content",className:c.content,"aria-label":a,children:o})}):null},Go=_p;import Hp from"classnames";var ji={root:"y"};import{jsx as Bp}from"react/jsx-runtime";var Fp=({className:t,value:e,...o})=>{let n=h("TextInput",ji);return Bp("input",{className:Hp(t,n.root),type:"text",value:e,...o})},Gt=Fp;var hs={};Q(hs,{enUS:()=>Kp,nlNL:()=>Up});var Kp={back:[{type:0,value:"Back"}],promptTitle:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],verifyCodeTitle:[{type:0,value:"Paste the code from your email"}],verifyCodeBody:[{type:0,value:"Copy the code from the email you just received and paste it here."}],verifyCodeInputPlaceholder:[{type:0,value:"Paste link or code here"}],verifyCodeSubmitLabel:[{type:0,value:"Sign in"}],verifyCodeError:[{type:0,value:"Sign in failed. The code is probably no longer valid. Please "},{type:8,value:"login",children:[{type:0,value:"request new code"}]},{type:0,value:"."}],requestCodeTitle:[{type:0,value:"Have a code sent to your email"}],requestCodeBody:[{type:0,value:"Enter your email and request a code. If you are an existing "},{type:1,value:"productName"},{type:0,value:" user you will receive an email with a code. If you are a new user you will receive an email asking to request access to "},{type:1,value:"productName"},{type:0,value:" first."}],requestCodeInputPlaceholder:[{type:0,value:"Enter your email"}],requestCodeSubmitLabel:[{type:0,value:"Request code"}]},Up={back:[{type:0,value:"Terug"}],promptTitle:[{type:0,value:"Login bij "},{type:1,value:"productName"}],verifyCodeTitle:[{type:0,value:"Plak de code uit je email"}],verifyCodeBody:[{type:0,value:"Kopieer de code uit de email en plak deze hier."}],verifyCodeInputPlaceholder:[{type:0,value:"Plak hier de code"}],verifyCodeSubmitLabel:[{type:0,value:"Inloggen"}],verifyCodeError:[{type:0,value:"Inloggen is niet gelukt. De code is waarschijnlijk niet meer geldig. "},{type:8,value:"login",children:[{type:0,value:"Vraag een nieuwe code aan"}]},{type:0,value:"."}],requestCodeTitle:[{type:0,value:"Verstuur een login code naar je email"}],requestCodeBody:[{type:0,value:"Voer je e-mailadres in en krijg een login code. Als je een bestaande "},{type:1,value:"productName"},{type:0,value:" gebruiker bent krijg je een email met een code. Als je een nieuwe gebruiker bent wordt er een email verstuurd met een toegangsverzoek voor "},{type:1,value:"productName"},{type:0,value:"."}],requestCodeInputPlaceholder:[{type:0,value:"Typ hier je e-mailadres"}],requestCodeSubmitLabel:[{type:0,value:"Code aanvragen"}]};var Wi={root:"Uo",anchorButton:"Bo",errorMessage:"Do",title:"Io",subtitle:"Oo",text:"Xo",input:"Jo",actions:"Ko",button:"w",primaryButton:"Po"};import{jsx as J,jsxs as jo}from"react/jsx-runtime";var jp=t=>{try{let e=new URL(t);return new URLSearchParams(e.search).get("token")||void 0}catch{return t}},Wp=({agentEmail:t,isOpen:e,origin:o="",onSuccess:n,onDismiss:s})=>{let r=R(hs),i=h("LoginTokenDialog",Wi),a=Gp(jr),l=qp(),c=C("productName"),[d,u]=vs(t||""),[p,g]=vs(0),[f,m]=vs(""),S=Xi(async k=>{k.preventDefault(),l(Xr({email:d})),g(1)},[o,d]),w=()=>{m(""),g(0)},v=Xi(async k=>{k.preventDefault();let x=jp(k.target.elements.token.value);if(!x){m(r("verifyCodeError",{login:y}));return}l(Ht({token:x}))},[o]),y=$p(()=>k=>J("button",{type:"button","data-testid":"login-token-dialog-back-button",className:i.anchorButton,onClick:w,children:k},"back-button"),[]);return Vp(()=>{a==="error"&&m(r("verifyCodeError",{login:y})),a==="done"&&n()},[a]),J(Go,{autoFocus:!0,isOpen:e,contentAriaLabel:r("promptTitle",{productName:c}),overlayAriaLabel:r("promptTitle",{productName:c}),onClose:s,onBack:s,children:jo("div",{className:i.root,children:[J("h1",{className:i.title,children:r("promptTitle",{productName:c})}),p===0&&jo("form",{onSubmit:S,children:[J("h2",{className:i.subtitle,children:r("requestCodeTitle")}),J("p",{className:i.text,children:r("requestCodeBody",{productName:c})}),J(Gt,{className:i.input,name:"email",placeholder:r("requestCodeInputPlaceholder"),value:d,onChange:k=>u(k.target.value)}),J("div",{className:i.actions,children:J("button",{type:"submit",className:ys(i.button,i.primaryButton),children:r("requestCodeSubmitLabel")})})]}),p===1&&jo("form",{onSubmit:v,children:[J("h2",{className:i.subtitle,children:r("verifyCodeTitle")}),J("p",{className:i.text,children:r("verifyCodeBody")}),J(Gt,{className:i.input,name:"token",placeholder:r("verifyCodeInputPlaceholder"),disabled:["loading","done"].includes(a)}),f&&J("div",{className:i.errorMessage,children:f}),jo("div",{className:i.actions,children:[J("button",{type:"button",className:ys(i.button),onClick:w,children:r("back")}),J("button",{type:"submit",className:ys(i.button,i.primaryButton),disabled:["loading","done"].includes(a),children:r("verifyCodeSubmitLabel")})]})]})]})})},Zi=Wp;import{jsx as Zp}from"react/jsx-runtime";var Xp=()=>{let t=Qi(Wr),e=Qi(vi),o=C("adminUrl"),n=ae(),s=()=>n.send(gt,!1),r=()=>{n.send(gt,!1),n.send(Ut)};return Zp(Zi,{isOpen:t,agentEmail:e==null?void 0:e.agentEmail,origin:o,onDismiss:s,onSuccess:r})},Ji=Xp;import jm from"lodash.debounce";import{Fragment as Wm,useCallback as Bs,useEffect as Ks,useState as Us}from"react";import{useDispatch as Xm,useSelector as Qe}from"react-redux";import{createAsyncThunk as Qp,createSlice as Jp}from"@reduxjs/toolkit";var Yp={data:null,fetchState:"idle"},Yi=t=>t.contentTypes.data,jt=Qp("contentTypes/getContentTypes",async(t,e)=>e.extra.deepdeskAPI.getContentTypes()),eg=Jp({name:"contentTypes",initialState:Yp,reducers:{},extraReducers:t=>{t.addCase(jt.pending,e=>{e.fetchState="loading"}).addCase(jt.rejected,e=>{e.fetchState="error"}).addCase(jt.fulfilled,(e,o)=>{e.fetchState="done",e.data=o.payload})}}),ea=eg.reducer;function We(t){let e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.left="-999999px",e.style.top="-999999px",document.body.appendChild(e),e.focus(),e.select(),document.execCommand("copy"),e.remove()}import{useEffect as Ca,useState as Kg,useRef as Ug,useCallback as zg}from"react";import{useState as sg}from"react";import Ss from"classnames";var ne={root:"Qo",list:"Vo",listWrapper:"Wo",listHorizontal:"B",page:"v",search:"D",pageNav:"Zo",pageTitle:"_o",pageBackButton:"I",listHeader:"oe",listHeading:"ee",listMoreButton:"ie",listItem:"O",listItemContent:"a",listItemText:"re",listItemDescription:"te",listItemActions:"X",truncate:"ne",lineClamp:"ae",listItemTitle:"de",listItemAction:"pe",listItemPrimaryAction:"le",listItemSelected:"se",sources:"xe",sourcesTitle:"ce",source:"fe",icon:"J",searchIcon:"ge",searchInputWrapper:"be",searchInput:"k",select:"he",selectType:"me",selectWrapper:"z",image:"ue",imageSrc:"ye",imageSrcHidden:"we",imageSrcStatus:"ve",imageTitle:"ke",actions:"ze",actionsWrapper:"je",actionsBar:"qe",actionButton:"K",hasShortKeys:"Ce",actionShortcut:"Se",actionShortcutFixKerning:"Ee"};var Xe={};Q(Xe,{enUS:()=>og,nlNL:()=>ng});var og={visitUrl:[{type:0,value:"Visit"}],back:[{type:0,value:"Back"}],loading:[{type:0,value:"Loading..."}],imageError:[{type:0,value:"Could not load image"}],showAll:[{type:0,value:"Show more"}]},ng={visitUrl:[{type:0,value:"Bekijk"}],back:[{type:0,value:"Terug"}],loading:[{type:0,value:"Laden..."}],imageError:[{type:0,value:"Kan afbeelding niet laden"}],showAll:[{type:0,value:"Toon meer"}]};import{jsx as Wt,jsxs as ig}from"react/jsx-runtime";var rg=({src:t,title:e})=>{let o=h("CommandPalette",ne),[n,s]=sg("loading"),r=R(Xe);return ig("div",{className:o.image,children:[Wt("img",{src:t,alt:e,onLoad:()=>s("done"),onError:()=>s("error"),className:Ss(o.imageSrc,{[o.imageSrcHidden]:["loading","error"].includes(n)})}),n==="loading"&&Wt("span",{className:Ss(o.imageSrc,o.imageSrcStatus),children:r("loading")}),n==="error"&&Wt("span",{className:Ss(o.imageSrc,o.imageSrcStatus),children:Wt(mo,{})}),e&&Wt("span",{className:o.imageTitle,children:e})]})},ta=rg;import ag from"react";import lg from"classnames";import{jsx as xs,jsxs as oa}from"react/jsx-runtime";function bs({children:t,heading:e,orientation:o,hasMore:n,onShowAll:s}){let r=R(Xe),i=h("CommandPalette",ne);return ag.Children.count(t)===0?null:oa("div",{"data-testid":"commandpalette-list",className:i.list,children:[(e||n)&&oa("div",{className:i.listHeader,children:[e&&xs("h4",{className:i.listHeading,children:e}),n&&s&&xs("button",{onClick:s,className:i.listMoreButton,type:"button",children:r("showAll")})]}),xs("div",{className:lg(i.listWrapper,o==="horizontal"&&i.listHorizontal),children:t})]})}import Zo from"classnames";import{Interweave as Mg}from"interweave";var cg=/[.*+?^${}()|[\]\\]/g,dg=/[^0-9A-Za-zÀ-ÖØ-öø-ÿ](?=[0-9A-Za-zÀ-ÖØ-öø-ÿ]*$)/;function ug(t){return t.replace(cg,"\\$&")}function pg(t,e){let o=t.split("").findIndex((n,s)=>n!==e[s]);return o>-1?o:Math.min(t.length,e.length)}function gg(t){return t.search(dg)}function na(t,e=[]){let o=t;return e.forEach(n=>{if(!n)return;let s=new RegExp(`\\b(${ug(n)})\\b`,"gi");o=o.replace(s,"<strong>$1</strong>")}),o}function sa(t){return t.replace(yo,'<mark data-type="placeholder">$1</mark>')}function Xt(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function mg(t,e){return t.split("").map((i,a)=>({char:i,index:a})).filter(({char:i,index:a})=>/\s/.test(i)&&a<=e).map(({index:i})=>i).reverse()[0]}function Cs(t,e,o={}){if(e){let n=pg(e.toLowerCase(),t.toLowerCase()),s=Xt(t.substring(n,t.length));if(o.stripAgentPart){let l=t.substring(0,n),c=gg(l);return`<span style="opacity: 0.5">${l.substring(c+1)}</span>${s}`}let i=e.split(zr).length>3||e.length>30?mg(e.trim(),n):0;return`${`${i>0?"\u2026":""}${Xt(t.substring(i,n))}`}<strong>${s}</strong>`}return t}var fg=/(<\/[a-zA-Z]+[0-9]?>|<[a-zA-Z]+\s?\/>|<br>)/i;function ws(t){return fg.test(t)}function ra(t){let e=document.createElement("template");return e.innerHTML=t,e.content.textContent??""}import yg,{useState as ia,useEffect as aa,useMemo as vg,useRef as la,useCallback as Sg,useContext as xg}from"react";import bg from"classnames";var Ts={root:"Ge",trigger:"P",content:"Ne",contentOpen:"Ye",contentTop:"Ae",contentBottom:"Fe",item:"Q"};import{jsx as Wo,jsxs as Eg}from"react/jsx-runtime";var Cg=0,ca=yg.createContext(null),wg=()=>{let t=xg(ca);if(!t)throw new Error("Invalid DropdownContext");return t},da=({trigger:t,children:e,position:o="bottom"})=>{let n=vg(()=>++Cg,[]),s=la(null),r=la(null),i=h("Dropdown",Ts),[a,l]=ia(!1),[c,d]=ia(o),u=g=>{g.preventDefault(),g.stopPropagation(),l(!a)},p=Sg(([g])=>{!g.isIntersecting&&a&&d(c==="top"?"bottom":"top")},[a]);return aa(()=>{let g=f=>{s.current&&!s.current.contains(f.target)&&l(!1)};return document.addEventListener("click",g),()=>{document.removeEventListener("click",g)}},[]),aa(()=>{if(!r.current&&!a)return()=>{};let g=new IntersectionObserver(p,{root:null,rootMargin:"0px",threshold:1});return r.current&&g.observe(r.current),()=>{r.current&&g.unobserve(r.current)}},[r,a]),Wo(ca.Provider,{value:{setIsOpen:l},children:Eg("div",{ref:s,className:i.root,children:[Wo("button",{id:`dropdown-${n}`,"data-testid":"dropdown-trigger","aria-haspopup":"true","aria-expanded":a,"aria-label":"Dropdown trigger",type:"button",className:i.trigger,onClick:u,children:t}),Wo("div",{"data-testid":"dropdown-content",ref:r,"aria-hidden":!a,"aria-labelledby":`dropdown-${n}`,className:bg(i.content,{[i.contentOpen]:a,[i.contentTop]:c==="top",[i.contentBottom]:c==="bottom"}),children:e})]})})};function Tg({as:t,children:e,onClick:o,...n}){let s=t||"button",r=h("Dropdown",Ts),{setIsOpen:i}=wg(),a=l=>{i(!1),o(l),l.stopPropagation()};return Wo(s,{type:"button",className:r.item,onClick:a,...n,children:e})}da.Item=Tg;var Es=da;import{jsx as ua}from"react/jsx-runtime";var pa=t=>ua("svg",{xmlns:"http://www.w3.org/2000/svg",height:"16",width:"14",viewBox:"0 0 448 512",...t,children:ua("path",{fill:"currentColor",d:"M8 256a56 56 0 1 1 112 0A56 56 0 1 1 8 256zm160 0a56 56 0 1 1 112 0 56 56 0 1 1 -112 0zm216-56a56 56 0 1 1 0 112 56 56 0 1 1 0-112z"})});var Ze={};Q(Ze,{enUS:()=>kg,nlNL:()=>Rg});var kg={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Add"}],sendSuggestion:[{type:0,value:"Send"}],suggestionSent:[{type:0,value:"Sent"}],sendingError:[{type:0,value:"Sending failed"}],tryAgain:[{type:0,value:"Try again"}],editSuggestion:[{type:0,value:"Edit"}],visitUrl:[{type:0,value:"Visit"}],giveFeedback:[{type:0,value:"Give feedback"}],answer:[{type:0,value:"Answer"}]},Rg={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Gebruik"}],sendSuggestion:[{type:0,value:"Verzenden"}],suggestionSent:[{type:0,value:"Verzonden"}],sendingError:[{type:0,value:"Verzenden mislukt"}],tryAgain:[{type:0,value:"Probeer opnieuw"}],editSuggestion:[{type:0,value:"Bewerken"}],visitUrl:[{type:0,value:"Bekijk"}],giveFeedback:[{type:0,value:"Geef feedback"}],answer:[{type:0,value:"Antwoord"}]};import{jsx as ks}from"react/jsx-runtime";var Pg="%0d%0a%0d%0a%0d%0a",Ig=(t,e)=>{let o=[`Suggestie: ${encodeURIComponent(e)}`,"Beschrijf je feedback:"];return`mailto:${t.join(",")}?subject=Suggestie feedback&body=${o.join(Pg)}`},Ag=({suggestion:t,onFeedback:e})=>{let o=R(Ze),n=C("suggestionFeedbackEmailAddresses");return!n||n.length===0?null:ks(Es,{trigger:ks(pa,{"data-testid":"feedback-dropdown-trigger"}),children:ks(Es.Item,{as:"a",href:Ig(n,t),onClick:e,children:o("giveFeedback")})})},Xo=Ag;import Rs from"react";import{jsx as Lg}from"react/jsx-runtime";var ga=Rs.createContext(void 0);function Ne(){let t=Rs.useContext(ga);if(t===void 0)throw new Error("useCommandPalette must be used within the CommandPalette component");return t}var ma=({children:t,page:e,isOpen:o,onChangeOpen:n,selected:s,setSelected:r})=>{let i=Rs.useMemo(()=>({page:e,isOpen:o,onChangeOpen:n,selected:s,setSelected:r}),[o,e,s]);return Lg(ga.Provider,{value:i,children:t})};import{jsx as Oe,jsxs as Ps}from"react/jsx-runtime";function Is({closeOnSelect:t=!0,lineClamp:e,children:o,onClick:n,onFeedback:s,onSourceClick:r,description:i,sources:a,id:l,styles:c,...d}){let{selected:u,onChangeOpen:p}=Ne(),g=h("CommandPalette",ne);function f(m){n(m),t&&p(!1)}return Ps("div",{className:Zo(g.listItem,l===u&&g.listItemSelected),children:[Oe("button",{type:"button",className:Zo(g.listItemAction,g.listItemPrimaryAction),"aria-disabled":d.disabled??!1,onClick:f,"data-command-palette-item":!0,"data-item-id":l,...d,children:Ps("div",{className:g.listItemContent,children:[typeof o=="string"?Oe("p",{className:Zo(g.listItemText,g.truncate,c==null?void 0:c.title),children:o}):o,i&&Oe(Mg,{tagName:"p",allowList:[],content:ws(i)?ra(i):i,className:Zo(g.listItemDescription,c==null?void 0:c.description,e?g.lineClamp:g.truncate)})]})}),s&&Oe("div",{className:g.listItemActions,children:Oe(Xo,{suggestion:String(o),onFeedback:s})}),a&&Ps("div",{className:g.sources,children:[Oe("span",{className:g.sourcesTitle,children:"Sources"}),a.map(m=>m.url?Oe("a",{className:g.source,href:m.url,target:"_blank",title:m.url,rel:"noopener noreferrer",onClick:()=>r&&r(m),children:m.name},m.url):Oe("span",{className:g.source,children:m.name},m.name))]})]})}import{jsx as fa,jsxs as Ng}from"react/jsx-runtime";var ha=()=>Ng("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 256 512","aria-labelledby":"angleLeftTitle",children:[fa("title",{id:"angleLeftTitle",children:"AngleLeft"}),fa("path",{d:"M192 448c-8.188 0-16.38-3.125-22.62-9.375l-160-160c-12.5-12.5-12.5-32.75 0-45.25l160-160c12.5-12.5 32.75-12.5 45.25 0s12.5 32.75 0 45.25L77.25 256l137.4 137.4c12.5 12.5 12.5 32.75 0 45.25C208.4 444.9 200.2 448 192 448z"})]});import{jsx as ya,jsxs as As}from"react/jsx-runtime";function Ls({children:t,title:e,id:o,onDismiss:n}){let s=R(Xe),r=h("CommandPalette",ne),{page:i}=Ne();return i!==o?null:As("div",{className:r.page,id:`page_${o}`,tabIndex:-1,children:[n&&As("div",{className:r.pageNav,children:[As("button",{className:r.pageBackButton,type:"button",onClick:n,children:[ya(ha,{}),s("back")]}),e&&ya("h3",{className:r.pageTitle,children:e})]}),t]})}import{forwardRef as _g}from"react";import{jsx as va,jsxs as Og}from"react/jsx-runtime";var mt=()=>Og("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 24 24",width:"1em",fill:"currentColor",children:[va("path",{d:"M0 0h24v24H0z",fill:"none"}),va("path",{d:"M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"})]});import{jsx as ft,jsxs as Ms}from"react/jsx-runtime";function Dg({onChange:t,onChangeType:e,placeholder:o,typePlaceholder:n,types:s,value:r,selectedType:i},a){let l=h("CommandPalette",ne);return Ms("div",{className:l.search,children:[ft("div",{className:l.searchIcon,children:ft(mt,{})}),Ms("div",{className:l.searchInputWrapper,children:[ft("input",{ref:a,spellCheck:!1,autoComplete:"off",onChange:c=>{t(c.currentTarget.value)},onFocus:c=>{c.currentTarget.select()},className:l.searchInput,placeholder:o,value:r,type:"text",id:"command-palette-search-input",autoFocus:!0}),s&&s.length>0&&ft("div",{className:l.selectWrapper,children:Ms("select",{"data-testid":"command-palette-type-select",className:l.select,onChange:c=>e(c.target.value===n?void 0:c.target.value),value:i||n,children:[n&&ft("option",{children:n}),s.map(c=>ft("option",{value:c.value,children:c.label},c.value))]})})]})]})}var Sa=_g(Dg);import xa from"classnames";import{jsx as Fg,jsxs as Bg}from"react/jsx-runtime";var Hg=({onClick:t,shortKeys:e,children:o,...n})=>{let s=h("CommandPalette",ne);return Bg("button",{type:"button",...n,onClick:t,className:xa(s.actionButton,n.className,{[s.hasShortKeys]:e&&e.length>0}),children:[o,e&&e.map(r=>Fg("span",{className:xa(s.actionShortcut,r===8629&&s.actionShortcutFixKerning),children:typeof r=="number"?String.fromCharCode(r):r},r))]})},ba=Hg;import{jsx as wa,jsxs as $g}from"react/jsx-runtime";var Vg="[data-command-palette-item]";function ht({placeholder:t="Start typing to search...",typePlaceholder:e="All types",defaultPage:o="search",page:n,onChangePage:s,onChangeSearch:r,onChangeType:i,onChangeOpen:a,selectedType:l,types:c,children:d,isOpen:u,search:p}){let[g,f]=Kg(),m=Ug(null),S=()=>{s&&s(o),i(void 0),r(""),a(!1)},w=()=>{var P;if(n!==o&&s){s(o);return}if(l&&i){i(void 0),(P=m.current)==null||P.focus();return}if(p.length>0){r("");return}a(!1)},v=()=>{let P=y();P.length!==0&&f(P[0].dataset.itemId)},y=()=>Array.from(document.querySelectorAll(Vg)||[]),k=P=>document.querySelector(`[data-item-id=${P}]`),x=P=>{let M=k(P);M&&f(M.dataset.itemId)},T=P=>{let M=k(P);M&&M.scrollIntoView({behavior:"smooth"})},L=()=>{if(!g)return;let P=y(),M=k(g);if(!M)return;let V=P.indexOf(M),Z=P[V+1];Z&&Z.dataset.itemId?x(Z.dataset.itemId):v()},z=()=>{if(!g)return;let P=y(),M=k(g);if(!M)return;let V=P.indexOf(M),Z=P[V-1];Z&&Z.dataset.itemId?x(Z.dataset.itemId):x(P[P.length-1].dataset.itemId)},F=zg(P=>{switch(P.key){case"ArrowDown":{P.preventDefault(),L();break}case"ArrowUp":{P.preventDefault(),z();break}case"Enter":{if(g){let M=k(g);M==null||M.click()}break}}},[g]);return Ca(()=>{v()},[p,n,l,u]),Ca(()=>{g&&T(g)},[g]),wa(Go,{autoFocus:!0,contentAriaLabel:"Search Results",overlayAriaLabel:"Command Palette",isOpen:u,onBack:w,onClose:S,onKeyDown:F,children:$g(ma,{selected:g,setSelected:f,isOpen:u,onChangeOpen:a,page:n,children:[n===o&&wa(Sa,{ref:m,onChange:r,onChangeType:i,placeholder:t,value:p,selectedType:l,types:c,typePlaceholder:e}),d]})})}ht.Page=Ls;ht.List=bs;ht.Image=ta;ht.ListItem=Is;ht.Button=ba;var D=ht;import{useEffect as qg}from"react";function Ta(t,e){qg(()=>{let o=n=>{var s;((s=navigator==null?void 0:navigator.platform)!=null&&s.toLowerCase().includes("mac")?n.metaKey:n.ctrlKey)&&n.key===t&&(n.preventDefault(),n.stopPropagation(),e())};return document.addEventListener("keydown",o),()=>{document.removeEventListener("keydown",o)}},[])}import{useEffect as Pa,useRef as Yg}from"react";import{useSelector as em,useDispatch as tm}from"react-redux";import{createAsyncThunk as Gg,createSlice as jg}from"@reduxjs/toolkit";var Ea={data:null,fetchState:"idle"},Qo=t=>{var r;let e=[],{visitorName:o}=t.info.visitorInfo??{},{agentName:n,agentNickname:s}=t.info.agentInfo??{};return n&&n!==o&&e.push(n),s&&s!==o&&e.push(s),((r=t.entities.data)==null?void 0:r.filter(i=>!e.includes(i.text)))??null},ce=Gg("entities/getEntities",async(t,e)=>{let{deepdeskAPI:o,dynamicThunkObject:n}=e.extra;if(!n.conversationQuery)return Promise.resolve([]);let s=n.conversationQuery,r=await s();return r.length===0?Promise.resolve([]):o.getEntities(r)}),Wg=t=>t.filter((e,o)=>o===t.findIndex(n=>n.text===e.text)),Xg=jg({name:"entities",initialState:Ea,reducers:{},extraReducers:t=>{t.addCase(ce.pending,e=>{e.fetchState="loading"}).addCase(ce.rejected,e=>{e.fetchState="error"}).addCase(ce.fulfilled,(e,o)=>{e.fetchState="done",e.data=Wg(e.data?[...e.data,...o.payload]:o.payload)}).addCase(N,()=>Ea)}}),ka=Xg.reducer;var Ns={};Q(Ns,{enUS:()=>Zg,nlNL:()=>Qg});var Zg={noResults:[{type:0,value:"No entities have been found"}],copy:[{type:0,value:"Copy"}],use:[{type:0,value:"Use"}]},Qg={noResults:[{type:0,value:"Er zijn geen entiteiten gevonden"}],copy:[{type:0,value:"Kopieer"}],use:[{type:0,value:"Gebruik"}]};var Ra={root:"He",empty:"Le"};import{jsx as Os,jsxs as nm}from"react/jsx-runtime";var om=({onCopy:t})=>{let e=Yg(null),o=h("EntitiesList",Ra),n=em(Qo),{setSelected:s}=Ne(),r=R(Ns),i=tm();return Pa(()=>{i(ce())},[]),Pa(()=>{e.current&&(e.current.focus(),s("entity-0"))},[e]),nm("div",{className:o.root,ref:e,tabIndex:-1,children:[n&&n.length>0&&Os(D.List,{children:n.map((a,l)=>Os(D.ListItem,{id:`entity-${l}`,closeOnSelect:!0,onClick:()=>t(a),children:a.text},a.text))},"entities"),n&&n.length===0&&Os("p",{className:o.empty,children:r("noResults")})]})},Ia=om;import{Fragment as dm,useEffect as Jo,useRef as um,useState as pm}from"react";import{useSelector as _a,useDispatch as gm}from"react-redux";import{createAsyncThunk as sm,createSlice as rm}from"@reduxjs/toolkit";var Aa={data:null,fetchState:"idle"},La=t=>t.summary.data,Ma=t=>t.summary.fetchState==="error",Ce=sm("summary/getSummary",async(t,e)=>{var d,u,p;let o=e.getState().profile.data,n=(d=e.getState().conversation.current)==null?void 0:d.sessionId,s=(p=(u=e.getState().info)==null?void 0:u.agentInfo)==null?void 0:p.agentId;if(!o)throw new Error("Profile is not defined");let{deepdeskAPI:r,dynamicThunkObject:i}=e.extra;if(!i.conversationQuery)return Promise.reject(new Error("setConversationQuery method is not defined"));let a=i.conversationQuery,l=await a();if(l.length===0)return Promise.reject(new Error("No messages are included"));let c=await r.getSummary(l,{externalConversationId:n,agentId:s,promptInstruction:o.summarizerPromptInstruction,model:o.summarizerModel});return c?{summary:c}:Promise.reject(new Error("Summary is not provided"))}),im=rm({name:"summary",initialState:Aa,reducers:{},extraReducers:t=>{t.addCase(Ce.pending,e=>{e.data=null,e.fetchState="loading"}).addCase(Ce.rejected,e=>{e.data=null,e.fetchState="error"}).addCase(Ce.fulfilled,(e,o)=>{e.fetchState="done",o.payload&&(e.data=o.payload.summary)}).addCase(N,()=>Aa)}}),Na=im.reducer;var _s={};Q(_s,{enUS:()=>am,nlNL:()=>lm});var am={copy:[{type:0,value:"Copy"}],error:[{type:0,value:"Could not generate a summary"}],loading:[{type:0,value:"Generating summary, this may take a few moments."}]},lm={copy:[{type:0,value:"Kopieer"}],error:[{type:0,value:"Kon helaas geen samenvatting genereren."}],loading:[{type:0,value:"Samenvatting wordt gemaakt, dit kan even duren."}]};var Oa={root:"Me",actions:"Re",main:"Te",textInput:"V",loading:"Ue",error:"Be"};import{jsx as yt,jsxs as fm}from"react/jsx-runtime";var mm=({onCopy:t})=>{let e=um(null),o=h("SummaryForm",Oa),[n,s]=pm(""),r=R(_s),i=_a(La),a=_a(Ma),l=gm(),c=()=>{l(G({name:"summary copied to clipboard",data:{originalText:i,finalText:n},options:{includeConversationData:!0}})),t(n)},d=()=>{let u=document.getSelection();u&&l(G({name:"summary copied to clipboard",data:{originalText:i,finalText:u==null?void 0:u.toString()},options:{includeConversationData:!0}}))};return Jo(()=>{l(Ce())},[]),Jo(()=>{s(i||"")},[i]),Jo(()=>{e.current&&i&&e.current.focus()},[e,i]),Jo(()=>{let u=p=>{p.key==="Enter"&&p.shiftKey&&c()};return document.addEventListener("keydown",u),()=>{document.removeEventListener("keydown",u)}},[n]),yt("div",{className:o.root,tabIndex:-1,children:a?yt("p",{className:o.error,children:r("error")}):fm(dm,{children:[yt("div",{className:o.main,children:yt("textarea",{placeholder:i?void 0:r("loading"),disabled:!i,className:o.textInput,ref:e,value:n,onCopy:d,onChange:u=>s(u.target.value)})}),yt("div",{className:o.actions,children:yt(D.Button,{shortKeys:[8679,8629],onClick:c,children:r("copy")})})]})})},Da=mm;var Zt={};Q(Zt,{enUS:()=>hm,nlNL:()=>ym});var hm={personalCollectionLink:[{type:0,value:"Go to Personal Collection"}],searchPlaceholder:[{type:0,value:"Start typing to search..."}],urlSuggestions:[{type:0,value:"Link suggestions"}],personalSuggestions:[{type:0,value:"Personal suggestions"}],pinnedMessages:[{type:0,value:"Pinned messages"}],imageSuggestions:[{type:0,value:"Images"}],typePlaceholder:[{type:0,value:"All types"}],navigation:[{type:0,value:"Navigation"}],entitiesClipboard:[{type:0,value:"Conversation clipper"}],entitiesTitle:[{type:0,value:"Copy to your clipboard"}],summaryClipboard:[{type:0,value:"Summarize conversation"}],summaryTitle:[{type:0,value:"Conversation summary"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Commands"}],use:[{type:0,value:"Use"}],preview:[{type:0,value:"Preview"}],warning:[{type:0,value:"Are you sure you want to discard the message?"}]},ym={personalCollectionLink:[{type:0,value:"Ga naar persoonlijke collectie"}],searchPlaceholder:[{type:0,value:"Begin met typen om te zoeken..."}],personalSuggestions:[{type:0,value:"Persoonlijke suggesties"}],urlSuggestions:[{type:0,value:"Link suggesties"}],imageSuggestions:[{type:0,value:"Afbeeldingen"}],navigation:[{type:0,value:"Navigatie"}],typePlaceholder:[{type:0,value:"Alle types"}],pinnedMessages:[{type:0,value:"Actueel"}],entitiesClipboard:[{type:0,value:"Klembord"}],entitiesTitle:[{type:0,value:"Kopieer naar klembord"}],summaryClipboard:[{type:0,value:"Gesprek samenvatten"}],summaryTitle:[{type:0,value:"Gesprek samenvatting"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Acties"}],use:[{type:0,value:"Gebruik"}],preview:[{type:0,value:"Bewerk"}],warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}]};import Am,{useEffect as Fs,useRef as Lm}from"react";import{useDispatch as Mm,useSelector as qa}from"react-redux";var Ds={};Q(Ds,{enUS:()=>vm,nlNL:()=>Sm});var vm={use:[{type:0,value:"Use"}],loading:[{type:0,value:"Loading..."}],error:[{type:0,value:"Something went wrong, please try again later."}],anotherQuestion:[{type:0,value:"Send a message..."}],reset:[{type:0,value:"Reset conversation"}]},Sm={use:[{type:0,value:"Gebruik"}],loading:[{type:0,value:"Laden..."}],error:[{type:0,value:"Er ging iets mis, probeer het later opnieuw."}],anotherQuestion:[{type:0,value:"Stuur een bericht..."}],reset:[{type:0,value:"Reset gesprek"}]};var Ha={root:"W",title:"De",empty:"Ie",status:"Oe",form:"Z",input:"_",submit:"Xe",question:"Je",answer:"Ke",alignRight:"Pe"};import{createAction as Em,createAsyncThunk as km,createSlice as Rm}from"@reduxjs/toolkit";import{createAsyncThunk as bm,createSlice as Cm}from"@reduxjs/toolkit";var wm={data:null,fetchState:"idle"},Fa=t=>{var e;return(e=t.knowledgeAssistant)==null?void 0:e.data},Qt=bm("knowledgeAssistant/getKnowledgeAssistant",async(t,e)=>{var i;let{deepdeskAPI:o}=e.extra,n=e.getState(),s=n.conversation.current;if(!s||!s.profileCode)throw new Error("No conversation of conversation profileCode found");let r=(i=n.profile.data)==null?void 0:i.knowledgeAssistant;return r?o.getKnowledgeAssistant(r):null}),Tm=Cm({name:"knowledgeAssistant",initialState:wm,reducers:{},extraReducers:t=>{t.addCase(Qt.pending,e=>{e.fetchState="loading"}).addCase(Qt.rejected,e=>{e.fetchState="error"}).addCase(Qt.fulfilled,(e,o)=>{e.fetchState="done",e.data=o.payload})}}),Ba=Tm.reducer;var Hs={data:[],fetchState:"idle"},Ka=t=>{var e;return(e=t.answer)==null?void 0:e.data},Ua=t=>t.answer.fetchState,St=Em("answer/resetKnowledgeSearch"),vt=km("answer/getAnswer",async(t,e)=>{var l,c,d;let{deepdeskAPI:o}=e.extra,n=e.getState().answer.data,s=Fa(e.getState()),r=(l=e.getState().conversation.current)==null?void 0:l.sessionId,i=(d=(c=e.getState().info)==null?void 0:c.agentInfo)==null?void 0:d.agentId;if(!s)throw new Error("KnowledgeAssistant is not defined");let a=await o.knowledgeAssist({promptInstruction:s.prompt,question:t},n,s.code,{agentId:i,conversationId:r});return{question:t,answer:a}}),Pm=Rm({name:"answer",initialState:Hs,reducers:{},extraReducers:t=>{t.addCase(vt.pending,e=>{e.fetchState="loading"}).addCase(vt.rejected,e=>{e.fetchState="error"}).addCase(vt.fulfilled,(e,o)=>{e.fetchState="done",e.data=[...e.data,o.payload]}).addCase(N,()=>Hs).addCase(St,()=>Hs)}}),za=Pm.reducer;import{jsx as Va,jsxs as Im}from"react/jsx-runtime";var $a=()=>Im("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 512 512","aria-labelledby":"paperPlaneTitle",children:[Va("title",{id:"paperPlaneTitle",children:"PaperPlane"}),Va("path",{d:"M498.1 5.6c10.1 7 15.4 19.1 13.5 31.2l-64 416c-1.5 9.7-7.4 18.2-16 23s-18.9 5.4-28 1.6L284 427.7l-68.5 74.1c-8.9 9.7-22.9 12.9-35.2 8.1S160 493.2 160 480V396.4c0-4 1.5-7.8 4.2-10.7L331.8 202.8c5.8-6.3 5.6-16-.4-22s-15.7-6.4-22-.7L106 360.8 17.7 316.6C7.1 311.3 .3 300.7 0 288.9s5.9-22.8 16.1-28.7l448-256c10.7-6.1 23.9-5.5 34 1.4z"})]});import{jsx as we,jsxs as Ga}from"react/jsx-runtime";var Nm=({onUse:t,onResetQuestion:e,question:o})=>{let[n,s]=Am.useState(""),{setSelected:r}=Ne(),i=Lm(null),a=h("EntitiesList",Ha),l=R(Ds),c=Mm(),d=qa(Ka),u=qa(Ua),p=async f=>{f.preventDefault(),f.stopPropagation(),n!==""&&c(vt(n))},g=(f,m)=>{c(G({name:"knowledge assist source viewed",data:{question:m,sourceViewed:f.url||f.name},options:{includeConversationData:!0}}))};return Fs(()=>{var f;o&&u==="idle"?c(vt(o)):(f=i.current)==null||f.focus()},[i,u]),Fs(()=>{u==="done"&&(c(G({name:"knowledge assist question answered",data:{question:n||o,sources:d[d.length-1].answer.sources,answer:d[d.length-1].answer.answer,isFollowUpQuestion:d.length>1},options:{includeConversationData:!0}})),r(`knowledge-assist-${d.length-1}`),s(""))},[u,d]),Fs(()=>{i.current&&i.current.scrollIntoView({behavior:"smooth"})},[i,d]),Ga("div",{className:a.root,children:[d.length>0&&we("div",{className:a.alignRight,children:we(D.Button,{onClick:e,children:l("reset")})}),d.map(({question:f,answer:m},S)=>we(D.List,{children:we(D.ListItem,{id:`knowledge-assist-${S}`,"data-testid":"knowledge-search-answer",description:m.answer,closeOnSelect:!0,onClick:()=>t(m.answer),onSourceClick:w=>g(w,f),sources:m.sources,styles:{title:a.question,description:a.answer},children:f})},`${m.answer}_${S}`)),u==="loading"&&we("p",{className:a.status,children:l("loading")}),u==="error"&&we("p",{className:a.status,children:l("error")}),Ga("form",{className:a.form,onSubmit:p,children:[we("input",{ref:i,placeholder:l("anotherQuestion"),className:a.input,type:"text",value:n,onFocus:()=>{r(void 0)},onChange:f=>{r(void 0),s(f.target.value)}}),we("button",{type:"submit",className:a.submit,children:we($a,{})})]})]})},ja=Nm;import{createAsyncThunk as Om,createSlice as _m}from"@reduxjs/toolkit";var Dm={data:null,fetchState:"idle"},_e=t=>t.profile.data,Yo=t=>t.profile.data?t.profile.data.uiConfig.widget.types.filter(e=>e.isActive):[],Jt=Om("profile/getProfile",async(t,e)=>{var r;let{deepdeskAPI:o}=e.extra,n=e.getState(),s=n.conversation.current;if(!s||!s.profileCode)throw new Error("No conversation of conversation profileCode found");return((r=n.profile.data)==null?void 0:r.code)===s.profileCode?n.profile.data:o.getProfile(s.profileCode)}),Hm=_m({name:"profile",initialState:Dm,reducers:{},extraReducers:t=>{t.addCase(Jt.pending,e=>{e.fetchState="loading"}).addCase(Jt.rejected,e=>{e.fetchState="error"}).addCase(Jt.fulfilled,(e,o)=>{e.fetchState="done",e.data=o.payload})}}),Wa=Hm.reducer;import{useEffect as zm}from"react";import{useDispatch as Vm}from"react-redux";import{createAction as Km,createAsyncThunk as Ja,createSlice as Um}from"@reduxjs/toolkit";var Fm=["{amount}"," {amount}","{date}","{email}","{iban}","{name}","{postal_code}","{street}","{tarif}","{usage}","{3_digits}","{4_digits}","{5_digits}","{6_digits}","{7_digits}","{8_digits}","{9_digits}","{10_digits}"],Bm=new RegExp(Fm.map(t=>`(?:${t.replace("{","\\{").replace("}","\\}")})`).join("|"));function Xa(t,e){let o=t.split(Bm),n=0,s=[];for(let r=0;r<o.length;r++){let i=o[r];if(s.push(i),r===o.length-1)break;if(e.indexOf(i)===-1)return t;let a=o[r+1],l=r===o.length-2;n+=i.length;let c=n;if(l){let u=a.charAt(0),p=0;do c=u?e.indexOf(u,c+1):-1,p+=1;while(c!==-1&&a.indexOf(e.slice(c))!==0);if(c===-1&&p>2)return t}else c=a&&a!==""?e.indexOf(a,n):-1;let d=c===-1?e.slice(n):e.slice(n,c);s.push(d),n=c}return s.join("")}function Za(t,e){return typeof e=="boolean"?t:t.slice(0,e)}var Ya={suggestions:[],fetchState:"idle",isInitialRequest:null},Qa={default:Ya},el=t=>e=>{var o;return((o=e.textSuggestions[t])==null?void 0:o.suggestions)??[]},tl=t=>{let e=Object.keys(t.textSuggestions).map(o=>{var n;return(n=t.textSuggestions[o])==null?void 0:n.fetchState});return e.length===0?!0:e.every(o=>o!=="done")},en=t=>t.textSuggestions,ol=t=>{let e=t.toLowerCase();return o=>{let n=o.text.toLowerCase();return n.startsWith(e)&&n.length>e.length}},tn=Km("textSuggestions/refresh"),de=Ja("textSuggestions/recommendations",async(t,e)=>{var c;let{deepdeskAPI:o}=e.extra,n=e.getState(),s=(c=n.conversation.current)==null?void 0:c.id,{textSuggestionsCount:r,inlineSuggestions:i}=n.settings,a=pt(n);if(!s)throw new Error("No current conversation to fetch text suggestions");let l=await o.getTextSuggestions(s,Kt(n),t);if(t==="default"){let d=i?l.filter(ol(a)):l;e.dispatch(pe(d.slice(0,r)))}return l}),Yt=Ja("textSuggestions/autocompletions",async(t,e)=>{var c;let{deepdeskAPI:o}=e.extra,n=e.getState(),s=(c=n.conversation.current)==null?void 0:c.id,{textSuggestionsCount:r,deanonymize:i,inlineSuggestions:a}=n.settings;if(!s)throw new Error("No current conversation to fetch text suggestions");let l=await o.getAutocompleteSuggestions(s,{...Kt(n),input:t});if(!e.getState().input.text)throw new Error("Abort");return a&&(l=l.filter(ol(t))),i&&(l=l.map(d=>({...d,text:d.source!=="trie-with-typos"?Xa(d.text,t):d.text}))),l=Za(l,r),e.dispatch(pe(l)),l}),nl=Um({name:"textSuggestions",initialState:Qa,reducers:{setTextSuggestions:{reducer(t,e){let{contentType:o}=e.payload;t[o].fetchState="done",t[o].suggestions=e.payload.suggestions},prepare(t,e){return{payload:{contentType:t,suggestions:e}}}},setSuggestionState(t,e){return e.payload}},extraReducers:t=>{t.addCase(de.pending,(e,o)=>{let n=o.meta.arg,s=e[n]||Ya;return{...e,[n]:{...s,fetchState:"loading",isInitialRequest:s.isInitialRequest===null}}}).addCase(de.rejected,(e,o)=>{let n=o.meta.arg;e[n]&&(e[n].fetchState="error")}).addCase(de.fulfilled,(e,o)=>{let n=o.meta.arg;e[n]&&(e[n].fetchState="done",e[n].suggestions=o.payload)}).addCase(Yt.pending,e=>{e.default.fetchState="loading"}).addCase(Yt.rejected,e=>{e.default.fetchState="error"}).addCase(Yt.fulfilled,(e,o)=>{e.default.fetchState="done",e.default.suggestions=o.payload}).addCase(N,()=>Qa)}}),{setTextSuggestions:RT,setSuggestionState:PT}=nl.actions,sl=nl.reducer;import{useSelector as rl}from"react-redux";import{jsx as on,jsxs as qm}from"react/jsx-runtime";var $m=({commands:t,onClick:e})=>{var a,l,c;let o=Vm(),n=R(Zt),s=rl(_e),r=rl(en),i=((c=(l=(a=s==null?void 0:s.uiConfig)==null?void 0:a.search)==null?void 0:l.initialTypes)==null?void 0:c.filter(({isActive:d})=>d))||[];return zm(()=>{i.forEach(({type:d})=>{(!r[d]||r[d].suggestions.length===0)&&o(de(d))})},[]),qm("div",{children:[t.length>0&&on(D.List,{heading:n("commands"),children:t.map((d,u)=>on(D.ListItem,{id:`command-${u}`,closeOnSelect:!1,onClick:d.onClick,children:d.label},d.label))}),i.map(({type:d,title:u})=>{var p;return on(D.List,{heading:u,orientation:"vertical",children:(p=r[d])==null?void 0:p.suggestions.map((g,f)=>on(D.ListItem,{id:`${d}-${f}`,closeOnSelect:!1,description:g.text,onClick:()=>e(g.text,g),"data-testid":"search-overlay-suggestion",children:g.title},`${g.id}-${g.text}`))},d)})]})},il=$m;import{jsx as se,jsxs as zs}from"react/jsx-runtime";var Zm=200,Qm=5,Jm=4,al=(t,e)=>!e||t.toLowerCase().includes(e.toLowerCase()),Ym=()=>{let t=Xm(),e=ae(),o=R(Zt),[n,s]=Us(!1),[r,i]=Us(""),a=Qe(wi),l=Qe(_e),[c,d]=Us(),u=Qe(W),p=C("showSearch"),g=C("showEntitiesCommand"),f=C("showSummaryCommand"),m=C("showKnowledgeSearch"),S=C("showImageSearch"),w=C("searchTriggerKey"),v=Qe(Yi),y=Qe(Ti),k=Qe(Ei),x=Qe(Ci),T=b=>Ot(y.filter(B=>B.type===b.toUpperCase()),b),L=[{value:"PERSONAL",label:o("personalSuggestions"),list:T("PERSONAL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"URL",label:o("urlSuggestions"),list:T("URL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"STICKYMESSAGE",label:o("pinnedMessages"),list:T("STICKYMESSAGE"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"IMAGE",label:o("imageSuggestions"),lineClamp:!1,list:T("IMAGE"),listOrientation:"horizontal",shouldShow:S}].filter(b=>b.shouldShow),z=[{label:o("entitiesClipboard"),onClick:()=>t(ie("entities")),shouldShow:g&&al(o("entitiesClipboard"),r)},{label:o("summaryClipboard"),onClick:()=>t(ie("summary")),shouldShow:f&&al(o("summaryClipboard"),r)},{label:r?`${o("knowledgeAssist")}: ${r}`:o("knowledgeAssist"),onClick:()=>t(ie("knowledgeAssist")),shouldShow:m}].filter(b=>b.shouldShow),F=(v==null?void 0:v.map(b=>({value:b.code.toUpperCase(),label:`${b.name}s`,list:T(b.code.toUpperCase()),listOrientation:"vertical",lineClamp:!0})))||[],P=Bs(jm((b,B)=>{t(qe({query:b,type:B,tags:["search-overlay"],size:c?50:20}))},Zm),[c]),M=Bs((b,B)=>{switch(B.type){case"IMAGE":e.send(as,{suggestion:B});break;default:e.send(Me,{text:b,suggestion:B})}t(ee(!1))},[t]),V=b=>{We(b.text),t(G({name:"entity copied",data:{entity:b,type:"copy"}})),t(ee(!1))},Z=Bs(b=>{t(G({name:"suggestion feedback",data:{text:b.text,source:"search",context:r},options:{includeConversationData:!0}}))},[r]),_=b=>{e.send(Me,{text:b,suggestion:{source:"knowledge-assist",text:b}}),t(G({name:"answer used",data:{originalText:b},options:{includeConversationData:!0}})),i(""),t(ie("search")),t(St()),t(ee(!1))},Nt=b=>{We(b),t(ee(!1))};function Ot(b,B){return b.slice(0,c?10:B.toLowerCase()==="image"?Jm:Qm)}function Ue(b){return B=>{n?window.confirm(o("warning"))&&(b(B),s(!1)):b(B)}}return Ks(()=>{r?P(r,c):t(Mo())},[r,c]),Ks(()=>{a==="search"&&t(St())},[a]),Ks(()=>{u&&t(jt())},[u]),Ta(w,()=>t(ee(!0))),!p||!l?null:zs(D,{placeholder:o("searchPlaceholder"),typePlaceholder:o("typePlaceholder"),onChangeSearch:i,onChangeOpen:Ue(b=>t(ee(b))),onChangeType:b=>d(b),onChangePage:Ue(b=>t(ie(b))),selectedType:c,search:r,page:a,isOpen:x,types:[...F,...L],children:[zs(D.Page,{id:"search",children:[r.length===0&&se(il,{commands:z,onClick:M}),r.length>0&&zs(Wm,{children:[z.length>0&&se(D.List,{heading:o("commands"),children:z.map((b,B)=>se(D.ListItem,{closeOnSelect:!1,onClick:b.onClick,id:`commands-${B}`,children:b.label},b.label))}),[...F,...L].map(({value:b,label:B,list:Lr,lineClamp:zd,listOrientation:Vd})=>se(D.List,{heading:B,orientation:Vd==="horizontal"?"horizontal":"vertical",onShowAll:()=>d(b),hasMore:!c&&k[b.toLowerCase()]>Ot(Lr,b).length,children:Ot(Lr,b).map(Y=>se(D.ListItem,{id:`${b}-${Y.id}`,closeOnSelect:!1,lineClamp:zd,onClick:()=>M(Y.text,Y),description:b!=="IMAGE"?Y.title&&Y.text:void 0,onFeedback:b!=="IMAGE"?()=>Z(Y):void 0,children:b==="IMAGE"?se(D.Image,{title:Y.title||Y.text,src:Y.image}):Y.title||Y.text},`${Y.id}-${Y.text}`))},b))]})]}),se(D.Page,{id:"entities",title:o("entitiesTitle"),onDismiss:Ue(()=>{t(ie("search"))}),children:se(Ia,{onCopy:V})}),se(D.Page,{id:"summary",title:o("summaryTitle"),onDismiss:Ue(()=>{t(ie("search"))}),children:se(Da,{onCopy:Nt})}),se(D.Page,{id:"knowledgeAssist",title:o("knowledgeAssist"),onDismiss:Ue(()=>{t(St()),t(ie("search"))}),children:se(ja,{question:r,onUse:_,onResetQuestion:()=>{t(St()),i("")}})})]})},ll=Ym;import{jsx as cl,jsxs as of}from"react/jsx-runtime";var tf=()=>{let t=C("showSearch"),e=C("isEmbedded");return of(ef,{children:[t&&cl(ll,{}),e&&cl(Ji,{})]})},dl=tf;import lf from"classnames";import{useSelector as cf}from"react-redux";import{jsx as Vs}from"react/jsx-runtime";var ul=({className:t})=>Vs("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",x:"0px",y:"0px",viewBox:"0 0 512 512",xmlSpace:"preserve",className:t,children:Vs("g",{children:Vs("path",{d:`M163.4,233h186v-70c0-25.6-9.4-47.8-27.3-65.7C304.2,79.4,282,70,256.4,70s-47.8,9.4-65.7,27.3
3
+ `,qe.MISSING_INTL_API,i);var k=o.getPluralRules(e,{type:d.pluralType}).select(g-(d.offset||0));v=d.options[k]||d.options.other}if(!v)throw new fs(d.value,g,Object.keys(d.options),i);a.push.apply(a,qt(v.value,e,o,n,s,g-(d.offset||0)));continue}}return Pp(a)}function Lp(t,e){return e?ee(ee(ee({},t||{}),e||{}),Object.keys(t).reduce(function(o,n){return o[n]=ee(ee({},t[n]),e[n]||{}),o},{})):t}function Ap(t,e){return e?Object.keys(t).reduce(function(o,n){return o[n]=Lp(t[n],e[n]),o},ee({},t)):t}function hs(t){return{create:function(){return{get:function(e){return t[e]},set:function(e,o){t[e]=o}}}}}function Mp(t){return t===void 0&&(t={number:{},dateTime:{},pluralRules:{}}),{getNumberFormat:$o(function(){for(var e,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];return new((e=Intl.NumberFormat).bind.apply(e,No([void 0],o,!1)))},{cache:hs(t.number),strategy:qo.variadic}),getDateTimeFormat:$o(function(){for(var e,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];return new((e=Intl.DateTimeFormat).bind.apply(e,No([void 0],o,!1)))},{cache:hs(t.dateTime),strategy:qo.variadic}),getPluralRules:$o(function(){for(var e,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];return new((e=Intl.PluralRules).bind.apply(e,No([void 0],o,!1)))},{cache:hs(t.pluralRules),strategy:qo.variadic})}}var qi=function(){function t(e,o,n,s){o===void 0&&(o=t.defaultLocale);var r=this;if(this.formatterCache={number:{},dateTime:{},pluralRules:{}},this.format=function(c){var d=r.formatToParts(c);if(d.length===1)return d[0].value;var u=d.reduce(function(g,p){return!g.length||p.type!==j.literal||typeof g[g.length-1]!="string"?g.push(p.value):g[g.length-1]+=p.value,g},[]);return u.length<=1?u[0]||"":u},this.formatToParts=function(c){return qt(r.ast,r.locales,r.formatters,r.formats,c,void 0,r.message)},this.resolvedOptions=function(){var c;return{locale:((c=r.resolvedLocale)===null||c===void 0?void 0:c.toString())||Intl.NumberFormat.supportedLocalesOf(r.locales)[0]}},this.getAst=function(){return r.ast},this.locales=o,this.resolvedLocale=t.resolveLocale(o),typeof e=="string"){if(this.message=e,!t.__parse)throw new TypeError("IntlMessageFormat.__parse must be set to process `message` of type `string`");var i=s||{},a=i.formatters,l=Hi(i,["formatters"]);this.ast=t.__parse(e,ee(ee({},l),{locale:this.resolvedLocale}))}else this.ast=e;if(!Array.isArray(this.ast))throw new TypeError("A message must be provided as a String or AST.");this.formats=Ap(t.formats,n),this.formatters=s&&s.formatters||Mp(this.formatterCache)}return Object.defineProperty(t,"defaultLocale",{get:function(){return t.memoizedDefaultLocale||(t.memoizedDefaultLocale=new Intl.NumberFormat().resolvedOptions().locale),t.memoizedDefaultLocale},enumerable:!1,configurable:!0}),t.memoizedDefaultLocale=null,t.resolveLocale=function(e){if(!(typeof Intl.Locale>"u")){var o=Intl.NumberFormat.supportedLocalesOf(e);return o.length>0?new Intl.Locale(o[0]):new Intl.Locale(typeof e=="string"?e:e[0])}},t.__parse=Ki,t.formats={number:{integer:{maximumFractionDigits:0},currency:{style:"currency"},percent:{style:"percent"}},date:{short:{month:"numeric",day:"numeric",year:"2-digit"},medium:{month:"short",day:"numeric",year:"numeric"},long:{month:"long",day:"numeric",year:"numeric"},full:{weekday:"long",month:"long",day:"numeric",year:"numeric"}},time:{short:{hour:"numeric",minute:"numeric"},medium:{hour:"numeric",minute:"numeric",second:"numeric"},long:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"},full:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"}}},t}();function _p(t,e){return e.split(".").reduce((o,n)=>o?o[n]:void 0,t)}var Dp="dummy",ys=Np(null);function R(t){let e=Op(ys);if(!e)throw new Error("useTranslator() may be used only in the context of a <LocaleContext> component.");let o=t[e]??{};return(n,s)=>{let r=_p(o,n);return r?new qi(r).format(s):(e!==Dp&&console.warn(`${n} does not exist in messages of ${e}`),`[${n}]`)}}import{useEffect as Fp,useRef as Bp}from"react";var Gi={root:"X",content:"Xo"};import{jsx as ji}from"react/jsx-runtime";var Kp=({isOpen:t,autoFocus:e,children:o,onClose:n,onBack:s,onKeyDown:r,overlayAriaLabel:i,contentAriaLabel:a})=>{let l=Bp(null),c=h("Dialog",Gi),d=g=>{if(g.key==="Escape"){g.preventDefault(),g.stopPropagation(),s();return}r&&r(g)},u=g=>{g.target===l.current&&t&&n()};return Fp(()=>{var g,p;!l.current||!t||!e||(p=(g=l.current)==null?void 0:g.querySelector("input, textarea"))==null||p.focus()},[t,e,l]),t?ji("div",{role:"dialog","data-testid":"dialog",className:c.root,"aria-label":i,ref:l,onKeyDown:d,onMouseDown:u,children:ji("div",{"data-testid":"dialog-content",className:c.content,"aria-label":a,children:o})}):null},Go=Kp;import zp from"classnames";var Wi={root:"y"};import{jsx as $p}from"react/jsx-runtime";var Vp=({className:t,value:e,...o})=>{let n=h("TextInput",Wi);return $p("input",{className:zp(t,n.root),type:"text",value:e,...o})},Gt=Vp;var vs={};Z(vs,{enUS:()=>qp,nlNL:()=>Gp});var qp={back:[{type:0,value:"Back"}],promptTitle:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],verifyCodeTitle:[{type:0,value:"Paste the code from your email"}],verifyCodeBody:[{type:0,value:"Copy the code from the email you just received and paste it here."}],verifyCodeInputPlaceholder:[{type:0,value:"Paste link or code here"}],verifyCodeSubmitLabel:[{type:0,value:"Sign in"}],verifyCodeError:[{type:0,value:"Sign in failed. The code is probably no longer valid. Please "},{type:8,value:"login",children:[{type:0,value:"request new code"}]},{type:0,value:"."}],requestCodeTitle:[{type:0,value:"Have a code sent to your email"}],requestCodeBody:[{type:0,value:"Enter your email and request a code. If you are an existing "},{type:1,value:"productName"},{type:0,value:" user you will receive an email with a code. If you are a new user you will receive an email asking to request access to "},{type:1,value:"productName"},{type:0,value:" first."}],requestCodeInputPlaceholder:[{type:0,value:"Enter your email"}],requestCodeSubmitLabel:[{type:0,value:"Request code"}]},Gp={back:[{type:0,value:"Terug"}],promptTitle:[{type:0,value:"Login bij "},{type:1,value:"productName"}],verifyCodeTitle:[{type:0,value:"Plak de code uit je email"}],verifyCodeBody:[{type:0,value:"Kopieer de code uit de email en plak deze hier."}],verifyCodeInputPlaceholder:[{type:0,value:"Plak hier de code"}],verifyCodeSubmitLabel:[{type:0,value:"Inloggen"}],verifyCodeError:[{type:0,value:"Inloggen is niet gelukt. De code is waarschijnlijk niet meer geldig. "},{type:8,value:"login",children:[{type:0,value:"Vraag een nieuwe code aan"}]},{type:0,value:"."}],requestCodeTitle:[{type:0,value:"Verstuur een login code naar je email"}],requestCodeBody:[{type:0,value:"Voer je e-mailadres in en krijg een login code. Als je een bestaande "},{type:1,value:"productName"},{type:0,value:" gebruiker bent krijg je een email met een code. Als je een nieuwe gebruiker bent wordt er een email verstuurd met een toegangsverzoek voor "},{type:1,value:"productName"},{type:0,value:"."}],requestCodeInputPlaceholder:[{type:0,value:"Typ hier je e-mailadres"}],requestCodeSubmitLabel:[{type:0,value:"Code aanvragen"}]};var Xi={root:"Jo",anchorButton:"Ko",errorMessage:"Po",title:"Qo",subtitle:"Vo",text:"Wo",input:"Zo",actions:"_o",button:"w",primaryButton:"oe"};import{jsx as Q,jsxs as jo}from"react/jsx-runtime";var Jp=t=>{try{let e=new URL(t);return new URLSearchParams(e.search).get("token")||void 0}catch{return t}},Yp=({agentEmail:t,isOpen:e,origin:o="",onSuccess:n,onDismiss:s})=>{let r=R(vs),i=h("LoginTokenDialog",Xi),a=Qp(Jr),l=Zp(),c=b("productName"),[d,u]=xs(t||""),[g,p]=xs(0),[f,m]=xs(""),y=Zi(async k=>{k.preventDefault(),l(ei({email:d})),p(1)},[o,d]),E=()=>{m(""),p(0)},S=Zi(async k=>{k.preventDefault();let x=Jp(k.target.elements.token.value);if(!x){m(r("verifyCodeError",{login:v}));return}l(Ht({token:x}))},[o]),v=Xp(()=>k=>Q("button",{type:"button","data-testid":"login-token-dialog-back-button",className:i.anchorButton,onClick:E,children:k},"back-button"),[]);return Wp(()=>{a==="error"&&m(r("verifyCodeError",{login:v})),a==="done"&&n()},[a]),Q(Go,{autoFocus:!0,isOpen:e,contentAriaLabel:r("promptTitle",{productName:c}),overlayAriaLabel:r("promptTitle",{productName:c}),onClose:s,onBack:s,children:jo("div",{className:i.root,children:[Q("h1",{className:i.title,children:r("promptTitle",{productName:c})}),g===0&&jo("form",{onSubmit:y,children:[Q("h2",{className:i.subtitle,children:r("requestCodeTitle")}),Q("p",{className:i.text,children:r("requestCodeBody",{productName:c})}),Q(Gt,{className:i.input,name:"email",placeholder:r("requestCodeInputPlaceholder"),value:d,onChange:k=>u(k.target.value)}),Q("div",{className:i.actions,children:Q("button",{type:"submit",className:Ss(i.button,i.primaryButton),children:r("requestCodeSubmitLabel")})})]}),g===1&&jo("form",{onSubmit:S,children:[Q("h2",{className:i.subtitle,children:r("verifyCodeTitle")}),Q("p",{className:i.text,children:r("verifyCodeBody")}),Q(Gt,{className:i.input,name:"token",placeholder:r("verifyCodeInputPlaceholder"),disabled:["loading","done"].includes(a)}),f&&Q("div",{className:i.errorMessage,children:f}),jo("div",{className:i.actions,children:[Q("button",{type:"button",className:Ss(i.button),onClick:E,children:r("back")}),Q("button",{type:"submit",className:Ss(i.button,i.primaryButton),disabled:["loading","done"].includes(a),children:r("verifyCodeSubmitLabel")})]})]})]})})},Qi=Yp;import{jsx as tg}from"react/jsx-runtime";var eg=()=>{let t=Ji(Yr),e=Ji(wi),o=b("adminUrl"),n=oe(),s=()=>n.send(gt,!1),r=()=>{n.send(gt,!1),n.send(Ut)};return tg(Qi,{isOpen:t,agentEmail:e==null?void 0:e.agentEmail,origin:o,onDismiss:s,onSuccess:r})},Yi=eg;import Jm from"lodash.debounce";import{Fragment as Ym,useCallback as Us,useEffect as zs,useState as Vs}from"react";import{useDispatch as ef,useSelector as Xe}from"react-redux";import{createAsyncThunk as og,createSlice as ng}from"@reduxjs/toolkit";var sg={data:null,fetchState:"idle"},ea=t=>t.contentTypes.data,jt=og("contentTypes/getContentTypes",async(t,e)=>e.extra.deepdeskAPI.getContentTypes()),rg=ng({name:"contentTypes",initialState:sg,reducers:{},extraReducers:t=>{t.addCase(jt.pending,e=>{e.fetchState="loading"}).addCase(jt.rejected,e=>{e.fetchState="error"}).addCase(jt.fulfilled,(e,o)=>{e.fetchState="done",e.data=o.payload})}}),ta=rg.reducer;function Ge(t){let e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.left="-999999px",e.style.top="-999999px",document.body.appendChild(e),e.focus(),e.select(),document.execCommand("copy"),e.remove()}import{useEffect as wa,useState as qg,useRef as Gg,useCallback as jg}from"react";import{useState as cg}from"react";import bs from"classnames";var ne={root:"ee",list:"ie",listWrapper:"re",listHorizontal:"J",page:"v",search:"K",pageNav:"te",pageTitle:"ne",pageBackButton:"P",listHeader:"ae",listHeading:"pe",listMoreButton:"de",listItem:"Q",listItemContent:"a",listItemText:"le",listItemDescription:"se",listItemActions:"V",truncate:"ce",lineClamp:"xe",listItemTitle:"fe",listItemAction:"ge",listItemPrimaryAction:"be",listItemSelected:"he",sources:"me",sourcesTitle:"ue",source:"ye",icon:"W",searchIcon:"we",searchInputWrapper:"ve",searchInput:"k",select:"ke",selectType:"ze",selectWrapper:"z",image:"je",imageSrc:"Ye",imageSrcHidden:"qe",imageSrcStatus:"Ce",imageTitle:"Se",actions:"Ee",actionsWrapper:"Ge",actionsBar:"Ne",actionButton:"Z",hasShortKeys:"Ae",actionShortcut:"Fe",actionShortcutFixKerning:"He"};var je={};Z(je,{enUS:()=>ag,nlNL:()=>lg});var ag={visitUrl:[{type:0,value:"Visit"}],back:[{type:0,value:"Back"}],loading:[{type:0,value:"Loading..."}],imageError:[{type:0,value:"Could not load image"}],showAll:[{type:0,value:"Show more"}]},lg={visitUrl:[{type:0,value:"Bekijk"}],back:[{type:0,value:"Terug"}],loading:[{type:0,value:"Laden..."}],imageError:[{type:0,value:"Kan afbeelding niet laden"}],showAll:[{type:0,value:"Toon meer"}]};import{jsx as Wt,jsxs as ug}from"react/jsx-runtime";var dg=({src:t,title:e})=>{let o=h("CommandPalette",ne),[n,s]=cg("loading"),r=R(je);return ug("div",{className:o.image,children:[Wt("img",{src:t,alt:e,onLoad:()=>s("done"),onError:()=>s("error"),className:bs(o.imageSrc,{[o.imageSrcHidden]:["loading","error"].includes(n)})}),n==="loading"&&Wt("span",{className:bs(o.imageSrc,o.imageSrcStatus),children:r("loading")}),n==="error"&&Wt("span",{className:bs(o.imageSrc,o.imageSrcStatus),children:Wt(mo,{})}),e&&Wt("span",{className:o.imageTitle,children:e})]})},oa=dg;import pg from"react";import gg from"classnames";import{jsx as Cs,jsxs as na}from"react/jsx-runtime";function ws({children:t,heading:e,orientation:o,hasMore:n,onShowAll:s}){let r=R(je),i=h("CommandPalette",ne);return pg.Children.count(t)===0?null:na("div",{"data-testid":"commandpalette-list",className:i.list,children:[(e||n)&&na("div",{className:i.listHeader,children:[e&&Cs("h4",{className:i.listHeading,children:e}),n&&s&&Cs("button",{onClick:s,className:i.listMoreButton,type:"button",children:r("showAll")})]}),Cs("div",{className:gg(i.listWrapper,o==="horizontal"&&i.listHorizontal),children:t})]})}import Zo from"classnames";import{Interweave as Hg}from"interweave";var mg=/[.*+?^${}()|[\]\\]/g,fg=/[^0-9A-Za-zÀ-ÖØ-öø-ÿ](?=[0-9A-Za-zÀ-ÖØ-öø-ÿ]*$)/;function hg(t){return t.replace(mg,"\\$&")}function yg(t,e){let o=t.split("").findIndex((n,s)=>n!==e[s]);return o>-1?o:Math.min(t.length,e.length)}function vg(t){return t.search(fg)}function sa(t,e=[]){let o=t;return e.forEach(n=>{if(!n)return;let s=new RegExp(`\\b(${hg(n)})\\b`,"gi");o=o.replace(s,"<strong>$1</strong>")}),o}function ra(t){return t.replace(yo,'<mark data-type="placeholder">$1</mark>')}function Xt(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function Sg(t,e){return t.split("").map((i,a)=>({char:i,index:a})).filter(({char:i,index:a})=>/\s/.test(i)&&a<=e).map(({index:i})=>i).reverse()[0]}function Ts(t,e,o={}){if(e){let n=yg(e.toLowerCase(),t.toLowerCase()),s=Xt(t.substring(n,t.length));if(o.stripAgentPart){let l=t.substring(0,n),c=vg(l);return`<span style="opacity: 0.5">${l.substring(c+1)}</span>${s}`}let i=e.split(jr).length>3||e.length>30?Sg(e.trim(),n):0;return`${`${i>0?"\u2026":""}${Xt(t.substring(i,n))}`}<strong>${s}</strong>`}return t}var xg=/(<\/[a-zA-Z]+[0-9]?>|<[a-zA-Z]+\s?\/>|<br>)/i;function Es(t){return xg.test(t)}function ia(t){let e=document.createElement("template");return e.innerHTML=t,e.content.textContent??""}import Cg,{useState as aa,useEffect as la,useMemo as wg,useRef as ca,useCallback as Tg,useContext as Eg}from"react";import kg from"classnames";var ks={root:"Le",trigger:"_",content:"Me",contentOpen:"Re",contentTop:"Te",contentBottom:"Ue",item:"oo"};import{jsx as Wo,jsxs as Lg}from"react/jsx-runtime";var Rg=0,da=Cg.createContext(null),Pg=()=>{let t=Eg(da);if(!t)throw new Error("Invalid DropdownContext");return t},ua=({trigger:t,children:e,position:o="bottom"})=>{let n=wg(()=>++Rg,[]),s=ca(null),r=ca(null),i=h("Dropdown",ks),[a,l]=aa(!1),[c,d]=aa(o),u=p=>{p.preventDefault(),p.stopPropagation(),l(!a)},g=Tg(([p])=>{!p.isIntersecting&&a&&d(c==="top"?"bottom":"top")},[a]);return la(()=>{let p=f=>{s.current&&!s.current.contains(f.target)&&l(!1)};return document.addEventListener("click",p),()=>{document.removeEventListener("click",p)}},[]),la(()=>{if(!r.current&&!a)return()=>{};let p=new IntersectionObserver(g,{root:null,rootMargin:"0px",threshold:1});return r.current&&p.observe(r.current),()=>{r.current&&p.unobserve(r.current)}},[r,a]),Wo(da.Provider,{value:{setIsOpen:l},children:Lg("div",{ref:s,className:i.root,children:[Wo("button",{id:`dropdown-${n}`,"data-testid":"dropdown-trigger","aria-haspopup":"true","aria-expanded":a,"aria-label":"Dropdown trigger",type:"button",className:i.trigger,onClick:u,children:t}),Wo("div",{"data-testid":"dropdown-content",ref:r,"aria-hidden":!a,"aria-labelledby":`dropdown-${n}`,className:kg(i.content,{[i.contentOpen]:a,[i.contentTop]:c==="top",[i.contentBottom]:c==="bottom"}),children:e})]})})};function Ig({as:t,children:e,onClick:o,...n}){let s=t||"button",r=h("Dropdown",ks),{setIsOpen:i}=Pg(),a=l=>{i(!1),o(l),l.stopPropagation()};return Wo(s,{type:"button",className:r.item,onClick:a,...n,children:e})}ua.Item=Ig;var Rs=ua;import{jsx as pa}from"react/jsx-runtime";var ga=t=>pa("svg",{xmlns:"http://www.w3.org/2000/svg",height:"16",width:"14",viewBox:"0 0 448 512",...t,children:pa("path",{fill:"currentColor",d:"M8 256a56 56 0 1 1 112 0A56 56 0 1 1 8 256zm160 0a56 56 0 1 1 112 0 56 56 0 1 1 -112 0zm216-56a56 56 0 1 1 0 112 56 56 0 1 1 0-112z"})});var We={};Z(We,{enUS:()=>Ag,nlNL:()=>Mg});var Ag={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Add"}],sendSuggestion:[{type:0,value:"Send"}],suggestionSent:[{type:0,value:"Sent"}],sendingError:[{type:0,value:"Sending failed"}],tryAgain:[{type:0,value:"Try again"}],editSuggestion:[{type:0,value:"Edit"}],visitUrl:[{type:0,value:"Visit"}],giveFeedback:[{type:0,value:"Give feedback"}],answer:[{type:0,value:"Answer"}]},Mg={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Gebruik"}],sendSuggestion:[{type:0,value:"Verzenden"}],suggestionSent:[{type:0,value:"Verzonden"}],sendingError:[{type:0,value:"Verzenden mislukt"}],tryAgain:[{type:0,value:"Probeer opnieuw"}],editSuggestion:[{type:0,value:"Bewerken"}],visitUrl:[{type:0,value:"Bekijk"}],giveFeedback:[{type:0,value:"Geef feedback"}],answer:[{type:0,value:"Antwoord"}]};import{jsx as Ps}from"react/jsx-runtime";var Ng="%0d%0a%0d%0a%0d%0a",Og=(t,e)=>{let o=[`Suggestie: ${encodeURIComponent(e)}`,"Beschrijf je feedback:"];return`mailto:${t.join(",")}?subject=Suggestie feedback&body=${o.join(Ng)}`},_g=({suggestion:t,onFeedback:e})=>{let o=R(We),n=b("suggestionFeedbackEmailAddresses");return!n||n.length===0?null:Ps(Rs,{trigger:Ps(ga,{"data-testid":"feedback-dropdown-trigger"}),children:Ps(Rs.Item,{as:"a",href:Og(n,t),onClick:e,children:o("giveFeedback")})})},Xo=_g;import Is from"react";import{jsx as Dg}from"react/jsx-runtime";var ma=Is.createContext(void 0);function Me(){let t=Is.useContext(ma);if(t===void 0)throw new Error("useCommandPalette must be used within the CommandPalette component");return t}var fa=({children:t,page:e,isOpen:o,onChangeOpen:n,selected:s,setSelected:r})=>{let i=Is.useMemo(()=>({page:e,isOpen:o,onChangeOpen:n,selected:s,setSelected:r}),[o,e,s]);return Dg(ma.Provider,{value:i,children:t})};import{jsx as Ne,jsxs as Ls}from"react/jsx-runtime";function As({closeOnSelect:t=!0,lineClamp:e,children:o,onClick:n,onFeedback:s,onSourceClick:r,description:i,sources:a,id:l,styles:c,...d}){let{selected:u,onChangeOpen:g}=Me(),p=h("CommandPalette",ne);function f(m){n(m),t&&g(!1)}return Ls("div",{className:Zo(p.listItem,l===u&&p.listItemSelected),children:[Ne("button",{type:"button",className:Zo(p.listItemAction,p.listItemPrimaryAction),"aria-disabled":d.disabled??!1,onClick:f,"data-command-palette-item":!0,"data-item-id":l,...d,children:Ls("div",{className:p.listItemContent,children:[typeof o=="string"?Ne("p",{className:Zo(p.listItemText,p.truncate,c==null?void 0:c.title),children:o}):o,i&&Ne(Hg,{tagName:"p",allowList:[],content:Es(i)?ia(i):i,className:Zo(p.listItemDescription,c==null?void 0:c.description,e?p.lineClamp:p.truncate)})]})}),s&&Ne("div",{className:p.listItemActions,children:Ne(Xo,{suggestion:String(o),onFeedback:s})}),a&&Ls("div",{className:p.sources,children:[Ne("span",{className:p.sourcesTitle,children:"Sources"}),a.map(m=>m.url?Ne("a",{className:p.source,href:m.url,target:"_blank",title:m.url,rel:"noopener noreferrer",onClick:()=>r&&r(m),children:m.name},m.url):Ne("span",{className:p.source,children:m.name},m.name))]})]})}import{jsx as ha,jsxs as Fg}from"react/jsx-runtime";var ya=()=>Fg("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 256 512","aria-labelledby":"angleLeftTitle",children:[ha("title",{id:"angleLeftTitle",children:"AngleLeft"}),ha("path",{d:"M192 448c-8.188 0-16.38-3.125-22.62-9.375l-160-160c-12.5-12.5-12.5-32.75 0-45.25l160-160c12.5-12.5 32.75-12.5 45.25 0s12.5 32.75 0 45.25L77.25 256l137.4 137.4c12.5 12.5 12.5 32.75 0 45.25C208.4 444.9 200.2 448 192 448z"})]});import{jsx as va,jsxs as Ms}from"react/jsx-runtime";function Ns({children:t,title:e,id:o,onDismiss:n}){let s=R(je),r=h("CommandPalette",ne),{page:i}=Me();return i!==o?null:Ms("div",{className:r.page,id:`page_${o}`,tabIndex:-1,children:[n&&Ms("div",{className:r.pageNav,children:[Ms("button",{className:r.pageBackButton,type:"button",onClick:n,children:[va(ya,{}),s("back")]}),e&&va("h3",{className:r.pageTitle,children:e})]}),t]})}import{forwardRef as Kg}from"react";import{jsx as Sa,jsxs as Bg}from"react/jsx-runtime";var mt=()=>Bg("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 24 24",width:"1em",fill:"currentColor",children:[Sa("path",{d:"M0 0h24v24H0z",fill:"none"}),Sa("path",{d:"M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"})]});import{jsx as ft,jsxs as Os}from"react/jsx-runtime";function Ug({onChange:t,onChangeType:e,placeholder:o,typePlaceholder:n,types:s,value:r,selectedType:i},a){let l=h("CommandPalette",ne);return Os("div",{className:l.search,children:[ft("div",{className:l.searchIcon,children:ft(mt,{})}),Os("div",{className:l.searchInputWrapper,children:[ft("input",{ref:a,spellCheck:!1,autoComplete:"off",onChange:c=>{t(c.currentTarget.value)},onFocus:c=>{c.currentTarget.select()},className:l.searchInput,placeholder:o,value:r,type:"text",id:"command-palette-search-input",autoFocus:!0}),s&&s.length>0&&ft("div",{className:l.selectWrapper,children:Os("select",{"data-testid":"command-palette-type-select",className:l.select,onChange:c=>e(c.target.value===n?void 0:c.target.value),value:i||n,children:[n&&ft("option",{children:n}),s.map(c=>ft("option",{value:c.value,children:c.label},c.value))]})})]})]})}var xa=Kg(Ug);import ba from"classnames";import{jsx as Vg,jsxs as $g}from"react/jsx-runtime";var zg=({onClick:t,shortKeys:e,children:o,...n})=>{let s=h("CommandPalette",ne);return $g("button",{type:"button",...n,onClick:t,className:ba(s.actionButton,n.className,{[s.hasShortKeys]:e&&e.length>0}),children:[o,e&&e.map(r=>Vg("span",{className:ba(s.actionShortcut,r===8629&&s.actionShortcutFixKerning),children:typeof r=="number"?String.fromCharCode(r):r},r))]})},Ca=zg;import{jsx as Ta,jsxs as Xg}from"react/jsx-runtime";var Wg="[data-command-palette-item]";function ht({placeholder:t="Start typing to search...",typePlaceholder:e="All types",defaultPage:o="search",page:n,onChangePage:s,onChangeSearch:r,onChangeType:i,onChangeOpen:a,selectedType:l,types:c,children:d,isOpen:u,search:g}){let[p,f]=qg(),m=Gg(null),y=()=>{s&&s(o),i(void 0),r(""),a(!1)},E=()=>{var I;if(n!==o&&s){s(o);return}if(l&&i){i(void 0),(I=m.current)==null||I.focus();return}if(g.length>0){r("");return}a(!1)},S=()=>{let I=v();I.length!==0&&f(I[0].dataset.itemId)},v=()=>Array.from(document.querySelectorAll(Wg)||[]),k=I=>document.querySelector(`[data-item-id=${I}]`),x=I=>{let O=k(I);O&&f(O.dataset.itemId)},w=I=>{let O=k(I);O&&O.scrollIntoView({behavior:"smooth"})},N=()=>{if(!p)return;let I=v(),O=k(p);if(!O)return;let P=I.indexOf(O),$=I[P+1];$&&$.dataset.itemId?x($.dataset.itemId):S()},U=()=>{if(!p)return;let I=v(),O=k(p);if(!O)return;let P=I.indexOf(O),$=I[P-1];$&&$.dataset.itemId?x($.dataset.itemId):x(I[I.length-1].dataset.itemId)},F=jg(I=>{switch(I.key){case"ArrowDown":{I.preventDefault(),N();break}case"ArrowUp":{I.preventDefault(),U();break}case"Enter":{if(p){let O=k(p);O==null||O.click()}break}}},[p]);return wa(()=>{S()},[g,n,l,u]),wa(()=>{p&&w(p)},[p]),Ta(Go,{autoFocus:!0,contentAriaLabel:"Search Results",overlayAriaLabel:"Command Palette",isOpen:u,onBack:E,onClose:y,onKeyDown:F,children:Xg(fa,{selected:p,setSelected:f,isOpen:u,onChangeOpen:a,page:n,children:[n===o&&Ta(xa,{ref:m,onChange:r,onChangeType:i,placeholder:t,value:g,selectedType:l,types:c,typePlaceholder:e}),d]})})}ht.Page=Ns;ht.List=ws;ht.Image=oa;ht.ListItem=As;ht.Button=Ca;var D=ht;import{useEffect as Zg}from"react";function Ea(t,e){Zg(()=>{let o=n=>{var s;((s=navigator==null?void 0:navigator.platform)!=null&&s.toLowerCase().includes("mac")?n.metaKey:n.ctrlKey)&&n.key===t&&(n.preventDefault(),n.stopPropagation(),e())};return document.addEventListener("keydown",o),()=>{document.removeEventListener("keydown",o)}},[])}import{useEffect as Ia,useRef as sm}from"react";import{useSelector as rm,useDispatch as im}from"react-redux";import{createAsyncThunk as Qg,createSlice as Jg}from"@reduxjs/toolkit";var ka={data:null,fetchState:"idle"},Qo=t=>{var r;let e=[],{visitorName:o}=t.info.visitorInfo??{},{agentName:n,agentNickname:s}=t.info.agentInfo??{};return n&&n!==o&&e.push(n),s&&s!==o&&e.push(s),((r=t.entities.data)==null?void 0:r.filter(i=>!e.includes(i.text)))??null},ae=Qg("entities/getEntities",async(t,e)=>{let{deepdeskAPI:o,dynamicThunkObject:n}=e.extra;if(!n.conversationQuery)return Promise.resolve([]);let s=n.conversationQuery,r=await s();return r.length===0?Promise.resolve([]):o.getEntities(r)}),Yg=t=>t.filter((e,o)=>o===t.findIndex(n=>n.text===e.text)),em=Jg({name:"entities",initialState:ka,reducers:{},extraReducers:t=>{t.addCase(ae.pending,e=>{e.fetchState="loading"}).addCase(ae.rejected,e=>{e.fetchState="error"}).addCase(ae.fulfilled,(e,o)=>{e.fetchState="done",e.data=Yg(e.data?[...e.data,...o.payload]:o.payload)}).addCase(_,()=>ka)}}),Ra=em.reducer;var _s={};Z(_s,{enUS:()=>tm,nlNL:()=>om});var tm={noResults:[{type:0,value:"No entities have been found"}],copy:[{type:0,value:"Copy"}],use:[{type:0,value:"Use"}]},om={noResults:[{type:0,value:"Er zijn geen entiteiten gevonden"}],copy:[{type:0,value:"Kopieer"}],use:[{type:0,value:"Gebruik"}]};var Pa={root:"Be",empty:"De"};import{jsx as Ds,jsxs as lm}from"react/jsx-runtime";var am=({onCopy:t})=>{let e=sm(null),o=h("EntitiesList",Pa),n=rm(Qo),{setSelected:s}=Me(),r=R(_s),i=im();return Ia(()=>{i(ae())},[]),Ia(()=>{e.current&&(e.current.focus(),s("entity-0"))},[e]),lm("div",{className:o.root,ref:e,tabIndex:-1,children:[n&&n.length>0&&Ds(D.List,{children:n.map((a,l)=>Ds(D.ListItem,{id:`entity-${l}`,closeOnSelect:!0,onClick:()=>t(a),children:a.text},a.text))},"entities"),n&&n.length===0&&Ds("p",{className:o.empty,children:r("noResults")})]})},La=am;import{Fragment as fm,useEffect as Jo,useRef as hm,useState as ym}from"react";import{useSelector as Da,useDispatch as vm}from"react-redux";import{createAsyncThunk as cm,createSlice as dm}from"@reduxjs/toolkit";var Aa={data:null,fetchState:"idle"},Ma=t=>t.summary.data,Na=t=>t.summary.fetchState==="error",xe=cm("summary/getSummary",async(t,e)=>{var d,u,g;let o=e.getState().profile.data,n=(d=e.getState().conversation.current)==null?void 0:d.sessionId,s=(g=(u=e.getState().info)==null?void 0:u.agentInfo)==null?void 0:g.agentId;if(!o)throw new Error("Profile is not defined");let{deepdeskAPI:r,dynamicThunkObject:i}=e.extra;if(!i.conversationQuery)return Promise.reject(new Error("setConversationQuery method is not defined"));let a=i.conversationQuery,l=await a();if(l.length===0)return Promise.reject(new Error("No messages are included"));let c=await r.getSummary(l,{externalConversationId:n,agentId:s,promptInstruction:o.summarizerPromptInstruction,model:o.summarizerModel});return c?{summary:c}:Promise.reject(new Error("Summary is not provided"))}),um=dm({name:"summary",initialState:Aa,reducers:{},extraReducers:t=>{t.addCase(xe.pending,e=>{e.data=null,e.fetchState="loading"}).addCase(xe.rejected,e=>{e.data=null,e.fetchState="error"}).addCase(xe.fulfilled,(e,o)=>{e.fetchState="done",o.payload&&(e.data=o.payload.summary)}).addCase(_,()=>Aa)}}),Oa=um.reducer;var Hs={};Z(Hs,{enUS:()=>pm,nlNL:()=>gm});var pm={copy:[{type:0,value:"Copy"}],error:[{type:0,value:"Could not generate a summary"}],loading:[{type:0,value:"Generating summary, this may take a few moments."}]},gm={copy:[{type:0,value:"Kopieer"}],error:[{type:0,value:"Kon helaas geen samenvatting genereren."}],loading:[{type:0,value:"Samenvatting wordt gemaakt, dit kan even duren."}]};var _a={root:"Ie",actions:"Oe",main:"Xe",textInput:"eo",loading:"Je",error:"Ke"};import{jsx as yt,jsxs as xm}from"react/jsx-runtime";var Sm=({onCopy:t})=>{let e=hm(null),o=h("SummaryForm",_a),[n,s]=ym(""),r=R(Hs),i=Da(Ma),a=Da(Na),l=vm(),c=()=>{l(G({name:"summary copied to clipboard",data:{originalText:i,finalText:n},options:{includeConversationData:!0}})),t(n)},d=()=>{let u=document.getSelection();u&&l(G({name:"summary copied to clipboard",data:{originalText:i,finalText:u==null?void 0:u.toString()},options:{includeConversationData:!0}}))};return Jo(()=>{l(xe())},[]),Jo(()=>{s(i||"")},[i]),Jo(()=>{e.current&&i&&e.current.focus()},[e,i]),Jo(()=>{let u=g=>{g.key==="Enter"&&g.shiftKey&&c()};return document.addEventListener("keydown",u),()=>{document.removeEventListener("keydown",u)}},[n]),yt("div",{className:o.root,tabIndex:-1,children:a?yt("p",{className:o.error,children:r("error")}):xm(fm,{children:[yt("div",{className:o.main,children:yt("textarea",{placeholder:i?void 0:r("loading"),disabled:!i,className:o.textInput,ref:e,value:n,onCopy:d,onChange:u=>s(u.target.value)})}),yt("div",{className:o.actions,children:yt(D.Button,{shortKeys:[8679,8629],onClick:c,children:r("copy")})})]})})},Ha=Sm;var Zt={};Z(Zt,{enUS:()=>bm,nlNL:()=>Cm});var bm={personalCollectionLink:[{type:0,value:"Go to Personal Collection"}],searchPlaceholder:[{type:0,value:"Start typing to search..."}],urlSuggestions:[{type:0,value:"Link suggestions"}],personalSuggestions:[{type:0,value:"Personal suggestions"}],pinnedMessages:[{type:0,value:"Pinned messages"}],imageSuggestions:[{type:0,value:"Images"}],typePlaceholder:[{type:0,value:"All types"}],navigation:[{type:0,value:"Navigation"}],entitiesClipboard:[{type:0,value:"Conversation clipper"}],entitiesTitle:[{type:0,value:"Copy to your clipboard"}],summaryClipboard:[{type:0,value:"Summarize conversation"}],summaryTitle:[{type:0,value:"Conversation summary"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Commands"}],use:[{type:0,value:"Use"}],preview:[{type:0,value:"Preview"}],warning:[{type:0,value:"Are you sure you want to discard the message?"}]},Cm={personalCollectionLink:[{type:0,value:"Ga naar persoonlijke collectie"}],searchPlaceholder:[{type:0,value:"Begin met typen om te zoeken..."}],personalSuggestions:[{type:0,value:"Persoonlijke suggesties"}],urlSuggestions:[{type:0,value:"Link suggesties"}],imageSuggestions:[{type:0,value:"Afbeeldingen"}],navigation:[{type:0,value:"Navigatie"}],typePlaceholder:[{type:0,value:"Alle types"}],pinnedMessages:[{type:0,value:"Actueel"}],entitiesClipboard:[{type:0,value:"Klembord"}],entitiesTitle:[{type:0,value:"Kopieer naar klembord"}],summaryClipboard:[{type:0,value:"Gesprek samenvatten"}],summaryTitle:[{type:0,value:"Gesprek samenvatting"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Acties"}],use:[{type:0,value:"Gebruik"}],preview:[{type:0,value:"Bewerk"}],warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}]};import _m,{useEffect as Ks,useRef as Dm}from"react";import{useDispatch as Hm,useSelector as Ga}from"react-redux";var Fs={};Z(Fs,{enUS:()=>wm,nlNL:()=>Tm});var wm={use:[{type:0,value:"Use"}],loading:[{type:0,value:"Loading..."}],error:[{type:0,value:"Something went wrong, please try again later."}],anotherQuestion:[{type:0,value:"Send a message..."}],reset:[{type:0,value:"Reset conversation"}]},Tm={use:[{type:0,value:"Gebruik"}],loading:[{type:0,value:"Laden..."}],error:[{type:0,value:"Er ging iets mis, probeer het later opnieuw."}],anotherQuestion:[{type:0,value:"Stuur een bericht..."}],reset:[{type:0,value:"Reset gesprek"}]};var Fa={root:"io",title:"Pe",empty:"Qe",status:"Ve",form:"ro",input:"to",submit:"We",question:"Ze",answer:"_e",alignRight:"oi"};import{createAction as Lm,createAsyncThunk as Am,createSlice as Mm}from"@reduxjs/toolkit";import{createAsyncThunk as km,createSlice as Rm}from"@reduxjs/toolkit";var Pm={data:null,fetchState:"idle"},Ba=t=>{var e;return(e=t.knowledgeAssistant)==null?void 0:e.data},Qt=km("knowledgeAssistant/getKnowledgeAssistant",async(t,e)=>{var i;let{deepdeskAPI:o}=e.extra,n=e.getState(),s=n.conversation.current;if(!s||!s.profileCode)throw new Error("No conversation of conversation profileCode found");let r=(i=n.profile.data)==null?void 0:i.knowledgeAssistant;return r?o.getKnowledgeAssistant(r):null}),Im=Rm({name:"knowledgeAssistant",initialState:Pm,reducers:{},extraReducers:t=>{t.addCase(Qt.pending,e=>{e.fetchState="loading"}).addCase(Qt.rejected,e=>{e.fetchState="error"}).addCase(Qt.fulfilled,(e,o)=>{e.fetchState="done",e.data=o.payload})}}),Ka=Im.reducer;var Bs={data:[],fetchState:"idle"},Ua=t=>{var e;return(e=t.answer)==null?void 0:e.data},za=t=>t.answer.fetchState,St=Lm("answer/resetKnowledgeSearch"),vt=Am("answer/getAnswer",async(t,e)=>{var l,c,d;let{deepdeskAPI:o}=e.extra,n=e.getState().answer.data,s=Ba(e.getState()),r=(l=e.getState().conversation.current)==null?void 0:l.sessionId,i=(d=(c=e.getState().info)==null?void 0:c.agentInfo)==null?void 0:d.agentId;if(!s)throw new Error("KnowledgeAssistant is not defined");let a=await o.knowledgeAssist({promptInstruction:s.prompt,question:t},n,s.code,{agentId:i,conversationId:r});return{question:t,answer:a}}),Nm=Mm({name:"answer",initialState:Bs,reducers:{},extraReducers:t=>{t.addCase(vt.pending,e=>{e.fetchState="loading"}).addCase(vt.rejected,e=>{e.fetchState="error"}).addCase(vt.fulfilled,(e,o)=>{e.fetchState="done",e.data=[...e.data,o.payload]}).addCase(_,()=>Bs).addCase(St,()=>Bs)}}),Va=Nm.reducer;import{jsx as $a,jsxs as Om}from"react/jsx-runtime";var qa=()=>Om("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 512 512","aria-labelledby":"paperPlaneTitle",children:[$a("title",{id:"paperPlaneTitle",children:"PaperPlane"}),$a("path",{d:"M498.1 5.6c10.1 7 15.4 19.1 13.5 31.2l-64 416c-1.5 9.7-7.4 18.2-16 23s-18.9 5.4-28 1.6L284 427.7l-68.5 74.1c-8.9 9.7-22.9 12.9-35.2 8.1S160 493.2 160 480V396.4c0-4 1.5-7.8 4.2-10.7L331.8 202.8c5.8-6.3 5.6-16-.4-22s-15.7-6.4-22-.7L106 360.8 17.7 316.6C7.1 311.3 .3 300.7 0 288.9s5.9-22.8 16.1-28.7l448-256c10.7-6.1 23.9-5.5 34 1.4z"})]});import{jsx as be,jsxs as ja}from"react/jsx-runtime";var Fm=({onUse:t,onResetQuestion:e,question:o})=>{let[n,s]=_m.useState(""),{setSelected:r}=Me(),i=Dm(null),a=h("EntitiesList",Fa),l=R(Fs),c=Hm(),d=Ga(Ua),u=Ga(za),g=async f=>{f.preventDefault(),f.stopPropagation(),n!==""&&c(vt(n))},p=(f,m)=>{c(G({name:"knowledge assist source viewed",data:{question:m,sourceViewed:f.url||f.name},options:{includeConversationData:!0}}))};return Ks(()=>{var f;o&&u==="idle"?c(vt(o)):(f=i.current)==null||f.focus()},[i,u]),Ks(()=>{u==="done"&&(c(G({name:"knowledge assist question answered",data:{question:n||o,sources:d[d.length-1].answer.sources,answer:d[d.length-1].answer.answer,isFollowUpQuestion:d.length>1},options:{includeConversationData:!0}})),r(`knowledge-assist-${d.length-1}`),s(""))},[u,d]),Ks(()=>{i.current&&i.current.scrollIntoView({behavior:"smooth"})},[i,d]),ja("div",{className:a.root,children:[d.length>0&&be("div",{className:a.alignRight,children:be(D.Button,{onClick:e,children:l("reset")})}),d.map(({question:f,answer:m},y)=>be(D.List,{children:be(D.ListItem,{id:`knowledge-assist-${y}`,"data-testid":"knowledge-search-answer",description:m.answer,closeOnSelect:!0,onClick:()=>t(m.answer),onSourceClick:E=>p(E,f),sources:m.sources,styles:{title:a.question,description:a.answer},children:f})},`${m.answer}_${y}`)),u==="loading"&&be("p",{className:a.status,children:l("loading")}),u==="error"&&be("p",{className:a.status,children:l("error")}),ja("form",{className:a.form,onSubmit:g,children:[be("input",{ref:i,placeholder:l("anotherQuestion"),className:a.input,type:"text",value:n,onFocus:()=>{r(void 0)},onChange:f=>{r(void 0),s(f.target.value)}}),be("button",{type:"submit",className:a.submit,children:be(qa,{})})]})]})},Wa=Fm;import{createAsyncThunk as Bm,createSlice as Km}from"@reduxjs/toolkit";var Um={data:null,fetchState:"idle"},Oe=t=>t.profile.data,Yo=t=>t.profile.data?t.profile.data.uiConfig.widget.types.filter(e=>e.isActive):[],Jt=Bm("profile/getProfile",async(t,e)=>{var r;let{deepdeskAPI:o}=e.extra,n=e.getState(),s=n.conversation.current;if(!s||!s.profileCode)throw new Error("No conversation of conversation profileCode found");return((r=n.profile.data)==null?void 0:r.code)===s.profileCode?n.profile.data:o.getProfile(s.profileCode)}),zm=Km({name:"profile",initialState:Um,reducers:{},extraReducers:t=>{t.addCase(Jt.pending,e=>{e.fetchState="loading"}).addCase(Jt.rejected,e=>{e.fetchState="error"}).addCase(Jt.fulfilled,(e,o)=>{e.fetchState="done",e.data=o.payload})}}),Xa=zm.reducer;import{useEffect as jm}from"react";import{useDispatch as Wm}from"react-redux";import{createAction as qm,createAsyncThunk as Ya,createSlice as Gm}from"@reduxjs/toolkit";var Vm=["{amount}"," {amount}","{date}","{email}","{iban}","{name}","{postal_code}","{street}","{tarif}","{usage}","{3_digits}","{4_digits}","{5_digits}","{6_digits}","{7_digits}","{8_digits}","{9_digits}","{10_digits}"],$m=new RegExp(Vm.map(t=>`(?:${t.replace("{","\\{").replace("}","\\}")})`).join("|"));function Za(t,e){let o=t.split($m),n=0,s=[];for(let r=0;r<o.length;r++){let i=o[r];if(s.push(i),r===o.length-1)break;if(e.indexOf(i)===-1)return t;let a=o[r+1],l=r===o.length-2;n+=i.length;let c=n;if(l){let u=a.charAt(0),g=0;do c=u?e.indexOf(u,c+1):-1,g+=1;while(c!==-1&&a.indexOf(e.slice(c))!==0);if(c===-1&&g>2)return t}else c=a&&a!==""?e.indexOf(a,n):-1;let d=c===-1?e.slice(n):e.slice(n,c);s.push(d),n=c}return s.join("")}function Qa(t,e){return typeof e=="boolean"?t:t.slice(0,e)}var el={suggestions:[],fetchState:"idle",isInitialRequest:null},Ja={default:el},tl=t=>e=>{var o;return((o=e.textSuggestions[t])==null?void 0:o.suggestions)??[]},ol=t=>{let e=Object.keys(t.textSuggestions).map(o=>{var n;return(n=t.textSuggestions[o])==null?void 0:n.fetchState});return e.length===0?!0:e.every(o=>o!=="done")},en=t=>t.textSuggestions,nl=t=>{let e=t.toLowerCase();return o=>{let n=o.text.toLowerCase();return n.startsWith(e)&&n.length>e.length}},tn=qm("textSuggestions/refresh"),le=Ya("textSuggestions/recommendations",async(t,e)=>{var c;let{deepdeskAPI:o}=e.extra,n=e.getState(),s=(c=n.conversation.current)==null?void 0:c.id,{textSuggestionsCount:r,inlineSuggestions:i}=n.settings,a=pt(n);if(!s)throw new Error("No current conversation to fetch text suggestions");let l=await o.getTextSuggestions(s,Kt(n),t);if(t==="default"){let d=i?l.filter(nl(a)):l;e.dispatch(ue(d.slice(0,r)))}return l}),Yt=Ya("textSuggestions/autocompletions",async(t,e)=>{var c;let{deepdeskAPI:o}=e.extra,n=e.getState(),s=(c=n.conversation.current)==null?void 0:c.id,{textSuggestionsCount:r,deanonymize:i,inlineSuggestions:a}=n.settings;if(!s)throw new Error("No current conversation to fetch text suggestions");let l=await o.getAutocompleteSuggestions(s,{...Kt(n),input:t});if(!e.getState().input.text)throw new Error("Abort");return a&&(l=l.filter(nl(t))),i&&(l=l.map(d=>({...d,text:d.source!=="trie-with-typos"?Za(d.text,t):d.text}))),l=Qa(l,r),e.dispatch(ue(l)),l}),sl=Gm({name:"textSuggestions",initialState:Ja,reducers:{setTextSuggestions:{reducer(t,e){let{contentType:o}=e.payload;t[o].fetchState="done",t[o].suggestions=e.payload.suggestions},prepare(t,e){return{payload:{contentType:t,suggestions:e}}}},setSuggestionState(t,e){return e.payload}},extraReducers:t=>{t.addCase(le.pending,(e,o)=>{let n=o.meta.arg,s=e[n]||el;return{...e,[n]:{...s,fetchState:"loading",isInitialRequest:s.isInitialRequest===null}}}).addCase(le.rejected,(e,o)=>{let n=o.meta.arg;e[n]&&(e[n].fetchState="error")}).addCase(le.fulfilled,(e,o)=>{let n=o.meta.arg;e[n]&&(e[n].fetchState="done",e[n].suggestions=o.payload)}).addCase(Yt.pending,e=>{e.default.fetchState="loading"}).addCase(Yt.rejected,e=>{e.default.fetchState="error"}).addCase(Yt.fulfilled,(e,o)=>{e.default.fetchState="done",e.default.suggestions=o.payload}).addCase(_,()=>Ja)}}),{setTextSuggestions:_T,setSuggestionState:DT}=sl.actions,rl=sl.reducer;import{useSelector as il}from"react-redux";import{jsx as on,jsxs as Zm}from"react/jsx-runtime";var Xm=({commands:t,onClick:e})=>{var a,l,c;let o=Wm(),n=R(Zt),s=il(Oe),r=il(en),i=((c=(l=(a=s==null?void 0:s.uiConfig)==null?void 0:a.search)==null?void 0:l.initialTypes)==null?void 0:c.filter(({isActive:d})=>d))||[];return jm(()=>{i.forEach(({type:d})=>{(!r[d]||r[d].suggestions.length===0)&&o(le(d))})},[]),Zm("div",{children:[t.length>0&&on(D.List,{heading:n("commands"),children:t.map((d,u)=>on(D.ListItem,{id:`command-${u}`,closeOnSelect:!1,onClick:d.onClick,children:d.label},d.label))}),i.map(({type:d,title:u})=>{var g;return on(D.List,{heading:u,orientation:"vertical",children:(g=r[d])==null?void 0:g.suggestions.map((p,f)=>on(D.ListItem,{id:`${d}-${f}`,closeOnSelect:!1,description:p.text,onClick:()=>e(p.text,p),"data-testid":"search-overlay-suggestion",children:p.title},`${p.id}-${p.text}`))},d)})]})},al=Xm;import{jsx as se,jsxs as $s}from"react/jsx-runtime";var tf=200,of=5,nf=4,ll=(t,e)=>!e||t.toLowerCase().includes(e.toLowerCase()),sf=()=>{let t=ef(),e=oe(),o=R(Zt),[n,s]=Vs(!1),[r,i]=Vs(""),a=Xe(Pi),l=Xe(Oe),[c,d]=Vs(),u=Xe(W),g=b("showSearch"),p=b("showEntitiesCommand"),f=b("showSummaryCommand"),m=b("showKnowledgeSearch"),y=b("showImageSearch"),E=b("searchTriggerKey"),S=Xe(ea),v=Xe(Ii),k=Xe(Li),x=Xe(Ri),w=C=>nt(v.filter(q=>q.type===C.toUpperCase()),C),N=[{value:"PERSONAL",label:o("personalSuggestions"),list:w("PERSONAL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"URL",label:o("urlSuggestions"),list:w("URL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"STICKYMESSAGE",label:o("pinnedMessages"),list:w("STICKYMESSAGE"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"IMAGE",label:o("imageSuggestions"),lineClamp:!1,list:w("IMAGE"),listOrientation:"horizontal",shouldShow:y}].filter(C=>C.shouldShow),U=[{label:o("entitiesClipboard"),onClick:()=>t(re("entities")),shouldShow:p&&ll(o("entitiesClipboard"),r)},{label:o("summaryClipboard"),onClick:()=>t(re("summary")),shouldShow:f&&ll(o("summaryClipboard"),r)},{label:r?`${o("knowledgeAssist")}: ${r}`:o("knowledgeAssist"),onClick:()=>t(re("knowledgeAssist")),shouldShow:m}].filter(C=>C.shouldShow),F=(S==null?void 0:S.map(C=>({value:C.code.toUpperCase(),label:`${C.name}s`,list:w(C.code.toUpperCase()),listOrientation:"vertical",lineClamp:!0})))||[],I=Us(Jm((C,q)=>{t(Ve({query:C,type:q,tags:["search-overlay"],size:c?50:20}))},tf),[c]),O=Us((C,q)=>{switch(q.type){case"IMAGE":e.send(cs,{suggestion:q});break;default:e.send(Ae,{text:C,suggestion:q})}t(Y(!1))},[t]),P=C=>{Ge(C.text),t(G({name:"entity copied",data:{entity:C,type:"copy"}})),t(Y(!1))},$=Us(C=>{t(G({name:"suggestion feedback",data:{text:C.text,source:"search",context:r},options:{includeConversationData:!0}}))},[r]),Un=C=>{e.send(Ae,{text:C,suggestion:{source:"knowledge-assist",text:C}}),t(G({name:"answer used",data:{originalText:C},options:{includeConversationData:!0}})),i(""),t(re("search")),t(St()),t(Y(!1))},zn=C=>{Ge(C),t(Y(!1))};function nt(C,q){return C.slice(0,c?10:q.toLowerCase()==="image"?nf:of)}function Ot(C){return q=>{n?window.confirm(o("warning"))&&(C(q),s(!1)):C(q)}}return zs(()=>{r?I(r,c):t(Mo())},[r,c]),zs(()=>{a==="search"&&t(St())},[a]),zs(()=>{u&&t(jt())},[u]),Ea(E,()=>t(Y(!0))),!g||!l?null:$s(D,{placeholder:o("searchPlaceholder"),typePlaceholder:o("typePlaceholder"),onChangeSearch:i,onChangeOpen:Ot(C=>t(Y(C))),onChangeType:C=>d(C),onChangePage:Ot(C=>t(re(C))),selectedType:c,search:r,page:a,isOpen:x,types:[...F,...N],children:[$s(D.Page,{id:"search",children:[r.length===0&&se(al,{commands:U,onClick:O}),r.length>0&&$s(Ym,{children:[U.length>0&&se(D.List,{heading:o("commands"),children:U.map((C,q)=>se(D.ListItem,{closeOnSelect:!1,onClick:C.onClick,id:`commands-${q}`,children:C.label},C.label))}),[...F,...N].map(({value:C,label:q,list:_r,lineClamp:tu,listOrientation:ou})=>se(D.List,{heading:q,orientation:ou==="horizontal"?"horizontal":"vertical",onShowAll:()=>d(C),hasMore:!c&&k[C.toLowerCase()]>nt(_r,C).length,children:nt(_r,C).map(J=>se(D.ListItem,{id:`${C}-${J.id}`,closeOnSelect:!1,lineClamp:tu,onClick:()=>O(J.text,J),description:C!=="IMAGE"?J.title&&J.text:void 0,onFeedback:C!=="IMAGE"?()=>$(J):void 0,children:C==="IMAGE"?se(D.Image,{title:J.title||J.text,src:J.image}):J.title||J.text},`${J.id}-${J.text}`))},C))]})]}),se(D.Page,{id:"entities",title:o("entitiesTitle"),onDismiss:Ot(()=>{t(re("search"))}),children:se(La,{onCopy:P})}),se(D.Page,{id:"summary",title:o("summaryTitle"),onDismiss:Ot(()=>{t(re("search"))}),children:se(Ha,{onCopy:zn})}),se(D.Page,{id:"knowledgeAssist",title:o("knowledgeAssist"),onDismiss:Ot(()=>{t(St()),t(re("search"))}),children:se(Wa,{question:r,onUse:Un,onResetQuestion:()=>{t(St()),i("")}})})]})},cl=sf;import{jsx as dl,jsxs as lf}from"react/jsx-runtime";var af=()=>{let t=b("showSearch"),e=b("isEmbedded");return lf(rf,{children:[t&&dl(cl,{}),e&&dl(Yi,{})]})},ul=af;import gf from"classnames";import{useSelector as mf}from"react-redux";import{jsx as qs}from"react/jsx-runtime";var pl=({className:t})=>qs("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",x:"0px",y:"0px",viewBox:"0 0 512 512",xmlSpace:"preserve",className:t,children:qs("g",{children:qs("path",{d:`M163.4,233h186v-70c0-25.6-9.4-47.8-27.3-65.7C304.2,79.4,282,70,256.4,70s-47.8,9.4-65.7,27.3
4
4
  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
5
5
  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
6
6
  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
7
- 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 pl}from"react/jsx-runtime";var nf={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},gl=({className:t,color:e})=>pl("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:pl("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:nf[e||"pink"]})});var ml={root:"j",text:"q",isLoggedIn:"Qe",isLoggedOut:"oo",icon:"Ve",logo:"We",lock:"Ze"};var $s={};Q($s,{enUS:()=>rf,nlNL:()=>af});var rf={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},af={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};import{useDispatch as df}from"react-redux";import{jsx as qs,jsxs as fl}from"react/jsx-runtime";var hl=({onLogIn:t})=>{let e=R($s),o=C("floatingMenu"),n=C("productName"),s=df(),r=cf(W),i=h("FloatingMenu",ml);if(r===null||o===!1)return null;let a=()=>{r===!0?s(ee(!0)):t()};return fl("button",{className:lf(i.root,{[i.isLoggedIn]:r,[i.isLoggedOut]:!r}),onClick:a,children:[qs("div",{className:i.text,children:e(r?"search":"signin",{productName:n})}),fl("div",{className:i.icon,children:[qs(gl,{className:i.logo,color:"pink"}),r===!1&&qs(ul,{className:i.lock})]})]})};import{useEffect as Mf,useRef as Nf}from"react";import{connect as Of,useDispatch as _f,useSelector as an}from"react-redux";import{useEffect as uf}from"react";function xt(t){uf(()=>{let e=o=>{o.isWithinRoot||t(o)};return document.body.addEventListener("mouseup",e),()=>{document.body.removeEventListener("mouseup",e)}},[t])}function Je(t){t.addEventListener("mouseup",e=>{e.isWithinRoot=!0},!0)}function bt(t){let{showMidSentenceSuggestions:e,showSuggestionsBeforePattern:o,showSuggestionsAfterPattern:n}=t.settings,{text:s,selection:r}=t.input.userCommitted;return r.start!==r.end?!1:r.end>=s.length?!0:e?o&&new RegExp(o).test(s.substring(r.end))||n&&new RegExp(n).test(s.substring(0,r.end))?!0:o===!1&&n===!1:!1}import{createSlice as pf}from"@reduxjs/toolkit";var gf={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var nn=({ui:t})=>t.overlayCollapsed;var yl=pf({name:"ui",initialState:gf,reducers:{setShowTabHint(t,e){t.showTabHint=e.payload},setInputHasFocus(t,e){t.overlayCollapsedUserOverwrite!==!0&&(e.payload===!0&&(t.overlayCollapsed=!1),t.inputHasFocus=e.payload)},setOverlayCollapsed(t,e){e.payload.collapse===!1&&(t.openOverlayWhenTyping=!1),!(e.payload.skipWhenInputFocus&&t.inputHasFocus)&&(t.overlayCollapsed=e.payload.collapse)},setOpenOverlayWhenTyping(t,e){t.openOverlayWhenTyping=e.payload},setOverlayCollapsedUserOverwrite(t,e){t.overlayCollapsedUserOverwrite=e.payload,t.overlayCollapsed=e.payload}}}),{setShowTabHint:eo,setInputHasFocus:Gs,setOverlayCollapsed:De,setOpenOverlayWhenTyping:vl,setOverlayCollapsedUserOverwrite:Sl}=yl.actions,xl=yl.reducer;import{Fragment as Pf,useMemo as If}from"react";import{Interweave as yf}from"interweave";import{useEffect as vf,useMemo as Sf,useRef as xf}from"react";import{useDispatch as bf,useSelector as Cf}from"react-redux";import{useEffect as mf}from"react";function bl(t,e,o){mf(()=>{let n=t.current;return n?(n.addEventListener(e,o),()=>{n.removeEventListener(e,o)}):()=>{}},[t,e,o])}var Cl={root:"_e",actions:"oi",badge:"ei",formattedText:"eo"};import{jsx as sn,jsxs as Rf}from"react/jsx-runtime";var wf=["search","personal-collection-search","search-autocomplete"];function Tf(t,e,o,n={}){let s="";return wf.includes(e)?s=na(Cs(t,o,{stripAgentPart:!0}),n.searchKeywords??[o]):s=Cs(t,o,n),n.placeholders===!0&&(s=sa(s)),s}var Ef=()=>{},kf=({index:t,selected:e,suggestion:o,onFeedback:n})=>{let s=C("inlineSuggestions"),r=Cf(pt),i=bf(),a=h("TextSuggestion",Cl),l=xf(null);vf(()=>{let d=setTimeout(()=>{i(ci({text:o.text,suggestion:o}))},500);return()=>{clearTimeout(d)}},[o]),bl(l,"click",()=>{i(Le(t)),i(ge({suggestion:o,text:o.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let c=Sf(()=>Tf(o.text,o.source,r,{stripAgentPart:s,placeholders:!0,searchKeywords:o.searchKeywords}),[s,o.text,o.source,r,o.searchKeywords]);return o.source==="gpt"&&!s?null:Rf("div",{className:a.root,onMouseEnter:()=>i(Le(t)),children:[sn(O,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:Ef,children:sn(yf,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:c})}),e&&n&&sn("div",{className:a.actions,children:sn(Xo,{onFeedback:()=>n(o),suggestion:o.text})})]})},wl=kf;import{jsx as Tl}from"react/jsx-runtime";var Af=({onFeedback:t,suggestions:e,selectedIndex:o,reverse:n})=>{let s=If(()=>{let r=e.map((i,a)=>Tl(wl,{index:a,selected:a===o,suggestion:i,onFeedback:t},`${i.text}-${i.source}`));return n?r.reverse():r},[e,o,n]);return Tl(Pf,{children:s})},rn=Af;var El={root:"ii",paper:"ri"};import{jsx as ln}from"react/jsx-runtime";var Df=({textSuggestions:t,selectedIndex:e})=>{let o=Nf(null),n=h("InlineSuggestionsOverlay",El),s=an(bt),r=_f(),i=an(W),a=an(dt),l=an(nn),c=C("showTextSuggestions");return xt(()=>{setTimeout(()=>{r(De({collapse:!0,skipWhenInputFocus:!0}))})}),Mf(()=>{let d=o.current;if(!d||!d.parentElement)return;d.parentElement.style.left="0px";let u=d.getBoundingClientRect();d.parentElement.style.left=`${Math.min(window.innerWidth-4-u.right,0)}px`}),l||!s||!c||t.length===0||i!==!0||a===!1?null:ln("div",{className:n.root,"data-variant":"inline",children:ln("div",{ref:o,className:n.paper,children:ln(oe,{children:ln(rn,{suggestions:t,selectedIndex:e})})})})},Hf=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),kl=Of(Hf)(Df);import{Provider as Ff}from"react-redux";import{jsx as cn}from"react/jsx-runtime";var Bf=({children:t})=>{let o=C("locale").replace("-","");return cn(fs.Provider,{value:o,children:t})},Kf=({store:t,customStyles:e={},children:o})=>cn(Ff,{store:t,children:cn(Bf,{children:cn(_t.Provider,{value:e,children:o})})}),Ye=Kf;import Qs from"classnames";import{useEffect as th,useRef as oh,useState as nh}from"react";import{connect as sh,useDispatch as rh,useSelector as to}from"react-redux";import{useState as Uf}from"react";function Rl(t,e){let[o,n]=Uf(()=>{if(typeof window>"u")return e;try{let r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return E.error(r),e}});return[o,r=>{try{let i=r instanceof Function?r(o):r;n(i),typeof window<"u"&&window.localStorage.setItem(t,JSON.stringify(i))}catch(i){E.error(i)}}]}var Pl=()=>/Mac/i.test(navigator.platform);import qf from"classnames";import{Fragment as Gf,useCallback as Ws,useMemo as Al}from"react";var js={};Q(js,{enUS:()=>zf,nlNL:()=>Vf});var zf={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Sign in"}]},{type:0,value:" to enable "},{type:1,value:"productName"},{type:0,value:"."}],snooze:[{type:0,value:"Snooze for "},{type:8,value:"min",children:[{type:0,value:"10 minutes"}]},{type:0,value:", "},{type:8,value:"hour",children:[{type:0,value:"1 hour"}]},{type:0,value:" or "},{type:8,value:"day",children:[{type:0,value:"1 day"}]}]},Vf={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Log in"}]},{type:0,value:" bij "},{type:1,value:"productName"},{type:0,value:"."}],snooze:[{type:0,value:"Snooze voor "},{type:8,value:"min",children:[{type:0,value:"10 minuten"}]},{type:0,value:", "},{type:8,value:"hour",children:[{type:0,value:"1 uur"}]},{type:0,value:" of "},{type:8,value:"day",children:[{type:0,value:"1 dag"}]}]};var Il={root:"ti",anchor:"ni",anchorButton:"ai"};import{jsx as dn,jsxs as Ll}from"react/jsx-runtime";var Xs=(t,e,o)=>n=>dn("button",{className:t.anchorButton,type:"button",value:e,onClick:o,children:n},e),jf=({className:t,loginUrl:e,isEmbedded:o,onSnooze:n,onLogIn:s})=>{let r=R(js),i=ae(),a=h("Login",Il),l=C("productName"),c=Ws(S=>{S.preventDefault(),n&&n(parseInt(S.target.value,10))},[]),d=Ws(S=>{S.preventDefault(),i.send(gt,!0)},[e]),u=Al(()=>S=>dn("a",{onClick:v=>{v.preventDefault(),s()},href:e,className:a.anchor,target:"_blank",rel:"noreferrer",children:S},"login"),[e]),p=Ws(S=>dn("button",{type:"button",className:a.anchorButton,onClick:d,children:S},"prompt"),[d]),{min:g,hour:f,day:m}=Al(()=>({min:Xs(a,60*10,c),hour:Xs(a,60*60,c),day:Xs(a,60*60*12,c)}),[]);return Ll("div",{className:qf(t,a.root),children:[r("loginPlease",{login:o?p:u,productName:l}),n&&Ll(Gf,{children:[dn("br",{}),r("snooze",{min:g,hour:f,day:m})]})]})},un=jf;import{useDispatch as Xf}from"react-redux";var Ml={root:"io",text:"di"};import{jsx as Nl,jsxs as Qf}from"react/jsx-runtime";var Zf=({title:t})=>{let e=h("SearchTrigger",Ml),o=Xf();return Qf("button",{type:"button",className:e.root,onClick:()=>o(ee(!0)),children:[Nl(mt,{}),Nl("span",{className:e.text,children:t})]})},Ol=Zf;var Zs={};Q(Zs,{enUS:()=>Jf,nlNL:()=>Yf});var Jf={arrowHint:[{type:0,value:"Tip: use arrow keys to navigate suggestions"}],searchHintWindows:[{type:0,value:"Press CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],searchHintMac:[{type:0,value:"Press CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Close"}],search:[{type:0,value:"Search"}]},Yf={arrowHint:[{type:0,value:"Tip: Selecteer suggesties met pijltoetsen"}],searchHintWindows:[{type:0,value:"Druk CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],searchHintMac:[{type:0,value:"Druk CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Sluiten"}],search:[{type:0,value:"Zoeken"}]};var _l={root:"pi",isInline:"C",toggleButton:"li",toggleButtonWrapper:"S",toggleButtonWrapperHidden:"si",isCollapsed:"ro",collapsible:"xi",hints:"to",hintsHidden:"ci",triggers:"no",triggersRight:"fi"};import{jsx as q,jsxs as oo}from"react/jsx-runtime";var ih=({textSuggestions:t,selectedIndex:e,onLogIn:o})=>{let n=h("SuggestionsOverlay",_l),s=R(Zs),r=to(bt),i=ri(),a=rh(),l=oh(null),c=C("searchTriggerKey"),d=C("productName"),u=to(nn),p=to(W),g=to(dt),[f,m]=nh(null),S=C("showSearch"),w=C("showTextSuggestions"),v=C("adminUrl"),y=C("isEmbedded"),[k,x]=Rl("dd-snooze-until-ms",0),T=u||k>Date.now(),L=to(V=>V.input.text),z=t.filter(V=>V.source!=="gpt").length,F=()=>{T&&x(0),a(Sl(!T))},P=V=>{a(G({name:"suggestion feedback",data:{text:V.text,source:"overlay",context:L},options:{includeConversationData:!0}}))},M=V=>{let Z=Date.now()+V*1e3;x(Z),E.info(`Snooze until: ${new Date(Z)}`),a(De({collapse:!0}))};return th(()=>{z===0&&m(null)},[t,z]),xt(()=>{a(De({collapse:!0,skipWhenInputFocus:!0}))}),p===null||g===!1?null:p===!1?oo("div",{ref:l,className:Qs(n.root,{[n.isCollapsed]:T}),children:[!T&&oo("div",{className:n.triggers,children:[q("div",{style:{flex:1}}),q("div",{className:n.triggersRight,children:q(it,{className:n.toggleButton,title:s("collapse"),onClick:F,isCollapsed:!1})})]}),q("div",{className:n.toggleButtonWrapper,children:q(it,{className:n.toggleButton,title:s("open",{productName:d}),onClick:F,isCollapsed:!0})}),q("div",{className:n.collapsible,children:q(un,{loginUrl:v,isEmbedded:y,onLogIn:o,onSnooze:M})})]}):!i||!r?null:oo("div",{ref:l,className:Qs(n.root,{[n.isCollapsed]:T}),children:[!T&&oo("div",{className:n.triggers,children:[q("div",{style:{flex:1},children:S&&q("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>m(s(Pl()?"searchHintMac":"searchHintWindows",{searchTriggerKey:c.toUpperCase()})),onMouseLeave:()=>m(null),children:q(Ol,{title:s("search")})})}),oo("div",{className:n.triggersRight,onFocus:()=>{},children:[q("div",{className:Qs(!f&&n.hintsHidden,n.hints),children:f}),q(it,{className:n.toggleButton,title:s("collapse"),onClick:F,isCollapsed:!1})]})]}),q("div",{className:n.toggleButtonWrapper,children:q(it,{className:n.toggleButton,title:s("open",{productName:d}),onClick:F,isCollapsed:!0})}),z>0&&w&&q("div",{className:n.collapsible,onFocus:()=>{},children:q(oe,{children:q(rn,{onFeedback:P,suggestions:t,selectedIndex:e,reverse:!0})})})]})},ah=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),Dl=sh(ah)(ih);import lr from"classnames";import{Interweave as ly}from"interweave";import{useCallback as cy,useEffect as dy,useMemo as ic,useRef as uy}from"react";import{connect as py}from"react-redux";import{useEffect as lh,useRef as ch,useState as dh}from"react";function pn(t){return t.contentEditable==="true"}function uh(t){let e=0,o=0,n=window.getSelection();if(n.rangeCount!==0){let s=n.getRangeAt(0),r=s.cloneRange();r.selectNodeContents(t),r.setEnd(s.endContainer,s.endOffset),o=r.toString().length,r.selectNodeContents(t),r.setEnd(s.startContainer,s.startOffset),e=r.toString().length}return{selectionStart:e,selectionEnd:o}}function Hl(t){let{selectionStart:e,selectionEnd:o}=pn(t)?uh(t):t;return[e,o]}function Fl(t){let[,e]=dh(),o=ch(null);return o.current=Hl(t),lh(()=>{let n=()=>{let[s,r]=o.current??[],i=Hl(t);(!i||s!==i[0]||r!==i[1])&&(o.current=i,e({}))};return t.addEventListener("keyup",n),t.addEventListener("click",n),t.addEventListener("focus",n),document.addEventListener("selectionchange",n),()=>{t.removeEventListener("keyup",n),t.removeEventListener("click",n),t.removeEventListener("focus",n),document.removeEventListener("selectionchange",n)}},[t]),o.current}function Bl(t,e){if(!e)return;let o=t,{value:n}=o,[s,r]=e,i=n.match(yo);if(!i||i.length===0)return;let a=0;i.find(l=>{let c=n.indexOf(l,a);return s>c&&r<c+l.length?(o.selectionStart=c,o.selectionEnd=c+l.length,!0):(a=c+l.length,!1)})}import{cloneElement as ph}from"react";var gh=["div","span","mark","strong","b","i","u","em"];function Js(t,e,o=0){var r;let n=t[t.length-1],s=typeof n=="object"&&n!==null?(r=n.props)==null?void 0:r.tagName:void 0;if(s==="br")return t.pop(),[...t,...e,n];if(gh.includes(s)){let i=Array.isArray(n.props.children)?n.props.children:[n.props.children];return[...t.slice(0,t.length-1),ph(n,{children:Js(i,e,o+1)})]}return[...t,...e]}function He(t){return t.tagName.toLowerCase()==="textarea"}var ue={root:"gi",container:"bi",agentText:"ao",tabText:"do",hint:"E",matchSelection:"po",focus:"hi",resetIndent:"mi",matchKeyword:"d",matchPlaceholder:"p",hover:"lo",hintText:"ui",popover:"yi",popoverRoot:"wi",popoverContentContainer:"so",popoverContent:"vi",selectionOptions:"ki",selectionOptionsIsHidden:"zi",selectionOptionsButton:"ji",caret:"qi",popoverSuggestionsRoot:"Ci",suggestionsOverlayInputStyles:"Si"};import Dh from"classnames";import{Matcher as Hh}from"interweave";import{useEffect as Fh,useMemo as Bh}from"react";import{useEffect as fh,useRef as hh,useState as yh}from"react";function Kl(t,e){let o;return[(...n)=>{window.cancelAnimationFrame(o);let s=e?e(...n):n;o=window.requestAnimationFrame(()=>{t(...s)})},()=>window.cancelAnimationFrame(o)]}function gn(t){let e=hh(null),[o,n]=yh(!1);return fh(()=>{let s=!1,r=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[i,a]=Kl((d,u)=>{let p=e.current;if(!p)return;let g=d/r,f=u/r,m=p.getBoundingClientRect(),S=g>m.x&&g<m.x+m.width&&f>m.y&&f<m.y+m.height;S&&!s?(s=!0,n(!0)):!S&&s&&(s=!1,n(!1))},({clientX:d,clientY:u})=>[d,u]),[l,c]=Kl(()=>{s=!1,n(!1)});return t.addEventListener("mousemove",i),t.addEventListener("mouseleave",l),()=>{a(),c(),t.removeEventListener("mousemove",i),t.removeEventListener("mouseleave",l)}},[e]),[e,o]}function Ul(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function mn(t){return e=>{t.forEach(o=>{typeof o=="function"?o(e):o!=null&&(o.current=e)})}}function zl(t){return t!=null}import jl from"classnames";import{createRef as Ih,useCallback as er,useMemo as Ah,useRef as Lh,useState as Mh}from"react";import{useState as vh,useLayoutEffect as Sh}from"react";var xh=["bottom","height","left","right","top","width"],bh=(t={},e={})=>xh.some(o=>t[o]!==e[o]),Te=new Map,Vl,$l=()=>{let t=[],e=[];Te.forEach((o,n)=>{if(n instanceof Element&&!n.isConnected){e.push(n);return}let s=n.getBoundingClientRect();bh(s,o.rect)&&(o.rect=s,t.push(o))}),e.forEach(o=>{Te.delete(o)}),t.forEach(o=>{o.callbacks.forEach(n=>n(o.rect))}),Vl=window.requestAnimationFrame($l)};function Ch(t,e){return{observe(){let o=Te.size===0;if(Te.has(t)){let n=Te.get(t);n.callbacks.push(e),n.rect&&e(n.rect)}else Te.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});o&&$l()},unobserve(){let o=Te.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||Te.delete(t),Te.size||cancelAnimationFrame(Vl)}}}}function Ys(t){let[e,o]=vh(null);return Sh(()=>{if(!t.current)return;let n=Ch(t.current,s=>{o(s)});return n.observe(),()=>{n.unobserve()}},[t]),e}import{useContext as Th,useLayoutEffect as Eh,useState as kh}from"react";import{createPortal as Rh}from"react-dom";var ql={root:"Ei"};var Gl=({children:t,parentNode:e})=>{let[o,n]=kh(null),s=Th(_t);return Eh(()=>{let r=document.createElement("div");return Je(r),r.classList.add(ql.root),s!=null&&s.portalRootNode&&r.classList.add(s==null?void 0:s.portalRootNode),(e||document.body).appendChild(r),n(r),()=>{r.isConnected&&r.remove()}},[]),o?Rh(t,o):null};var me={ref:"Gi",root:"o",positionAbove:"l",positionBelow:"s",positionLeft:"x",positionRight:"c",alignStart:"f",alignCenter:"g",alignEnd:"b"};import{jsx as tr}from"react/jsx-runtime";var fn=(t=!1)=>{let[e,o]=Mh(t),n=er(()=>o(!0),[]),s=er(()=>o(!1),[]),r=er(()=>o(a=>!a),[]),i=Lh(null);return{opened:e,open:n,close:s,toggle:r,triggerRef:i}};function or(t,e=null,o=0){if(!t)return{display:"none"};let n=e?t.top-e.top<0||t.top<e.top-o?e.top-o:t.top+t.height>e.top+e.height+o?e.top+e.height+o-t.height:t.top:t.top,s=e?t.left<e.left-o?e.left-o:t.left+t.width>e.left+e.width+o?e.left+e.width+o-t.width:t.left:t.left;return{top:n,left:s,height:t.height,width:t.width}}var Ct=({className:t,triggerRef:e,boundaryRef:o=Ih(),position:n="above",align:s="center",children:r,toStyle:i=or,parentNode:a,...l})=>{let c=Ys(e),d=Ys(o),u=Ah(()=>i(c,d,0),[c,d]);return tr(Gl,{parentNode:a,children:tr("div",{className:jl(me.ref,{[me.positionAbove]:n==="above",[me.positionBelow]:n==="below",[me.positionLeft]:n==="left",[me.positionRight]:n==="right",[me.alignStart]:s==="start",[me.alignCenter]:s==="center",[me.alignEnd]:s==="end"}),style:u,...l,role:"dialog",children:tr("div",{className:jl(t,me.root),children:r})})})};import Nh from"classnames";import{forwardRef as Oh,useRef as _h}from"react";import{jsx as Wl}from"react/jsx-runtime";var hn=Oh(({className:t,children:e,...o},n)=>{let s=_h(null),r=h("TabCompletion",ue);return Wl("div",{ref:mn([s,n]),className:Nh(t,r.popoverContentContainer),...o,children:Wl("div",{className:r.popoverContent,children:e})})});import{jsx as no,jsxs as zh}from"react/jsx-runtime";var Kh=t=>e=>{let o=or(e);return"top"in o&&(o.width=t.width-(e.left-t.left)-10),o},Uh=({inputElement:t,boundaryRef:e,inputStyle:o,children:n,suggestion:s})=>{let r=h("TabCompletion",ue),i=fn(),a=Bh(()=>Kh(t.getBoundingClientRect()),[t]),[l,c]=gn(t);return Fh(()=>{c?i.open():i.close()},[c]),zh("span",{children:[no("mark",{ref:mn([l,i.triggerRef]),className:Dh(r.matchKeyword,{[r.hover]:c}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:n}),i.opened&&no(Ct,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:no(hn,{style:o,children:no("div",{className:r.hintText,children:s})})})]})},yn=class extends Hh{keywordMatches=[];preparedKeywordMatches=[];usedKeywordMatches=new Set;onBeforeParse(e,o){return o.keywordMatches&&o.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=o.keywordMatches.map(n=>({...n,keywordRegex:new RegExp(`\\b${Ul(n.keyword)}\\b`,"i")})),this.keywordMatches=o.keywordMatches),this.usedKeywordMatches.clear(),e}match(e){let o=this.preparedKeywordMatches.map(s=>{if(this.usedKeywordMatches.has(s))return null;let r=e.match(s.keywordRegex);if(!r)return null;let i=e.charAt(r.index-1),a=e.charAt(r.index+s.keyword.length);return i==="{"&&a==="}"?null:{index:r.index,length:r[0].length,match:r[0],matchString:r[0],suggestion:s.suggestion,preparedKeywordMatch:s,valid:!0}}).filter(zl);if(o.length===0)return null;let n=o.reduce((s,r)=>r.index<s.index?r:s);return this.usedKeywordMatches.add(n.preparedKeywordMatch),n}replaceWith(e,o){return no(Uh,{inputElement:o.inputElement,suggestion:o.suggestion,inputStyle:o.inputStyle,boundaryRef:o.boundaryRef,children:e},`keyword_${o.matchString}_${o.key}`)}asTag(){return"mark"}};import{Matcher as Vh}from"interweave";import $h from"classnames";import{jsx as Xl}from"react/jsx-runtime";var qh=({inputElement:t,children:e})=>{let o=h("TabCompletion",ue),[n,s]=gn(t);return Xl("mark",{ref:n,className:$h(o.matchPlaceholder,{[o.hover]:s}),children:e})},vn=class extends Vh{match(e){let o=e.match(/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\}(?!\}))/);return o?{index:o.index,length:o[0].length,match:o[0],matchString:o[0],valid:!0}:null}replaceWith(e,o){return Xl(qh,{inputElement:o.inputElement,children:e},`placeholder_${o.matchString}_${o.key}`)}asTag(){return"mark"}};import ar from"classnames";import{Matcher as ty}from"interweave";import{createRef as oy,forwardRef as ny,useCallback as sy,useEffect as nc,useRef as sc,useState as rc}from"react";import{useDispatch as ry}from"react-redux";import{jsx as Zl}from"react/jsx-runtime";var Ql=()=>Zl("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:Zl("path",{fill:"currentColor",d:"M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"})});import{useCallback as jh,useEffect as Yl,useState as ec}from"react";import{useDispatch as Wh,useSelector as tc}from"react-redux";import Xh from"lodash.debounce";var Jl={root:"Ni",content:"Yi"};function Sn(t,e,o){var s;let n=((s=t.imageSizes)==null?void 0:s[e])||t.image||o;if(!n)return null;try{return new URL(n).toString()}catch{return null}}function nr(t){return t.replace("https://www.","").replace("https://","")}import{jsx as et,jsxs as sr}from"react/jsx-runtime";var Zh=3,Qh=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),Jh=({onSelectLink:t,onDismiss:e,placeholder:o,visitUrlText:n,linkCount:s=Zh})=>{let r=h("LinkSearch",Jl),[i,a]=ec(""),l=Wh(),c=tc(el("url")),d=tc(ki("URL",Qh)),[u,p]=ec(d.length-1),g=C("fallbackImage"),f=v=>{let y=v.target;a(y.value)},m=(v,y)=>{v.stopPropagation(),v.preventDefault(),window.open(y,"_blank")},S=v=>{var x;let y=u-1<0?d.length-1:u-1,k=u+1===d.length?0:u+1;v.code==="Escape"&&(a(""),e()),v.code==="ArrowUp"&&p(y),v.code==="ArrowDown"&&p(k),v.code==="Enter"&&t(((x=d[u])==null?void 0:x.text)||i)},w=jh(Xh(v=>{l(qe({query:v,type:"URL",tags:["link-search"]}))},300),[]);return Yl(()=>{i&&w(i)},[i]),Yl(()=>()=>{l(Mo())},[]),sr("div",{className:r.root,children:[et(oe,{withDivider:!0,children:(i?d:c).slice(0,s).map((v,y)=>et(O,{selected:u===y,onClick:()=>t(v.text),"data-testid":"linksearch-suggestion",children:sr(H,{children:[et(H.Image,{src:Sn(v,"small",g||void 0),title:v.title||v.text}),sr(H.Content,{className:r.content,cropText:!0,children:[et(H.Title,{children:v.title||nr(v.text)}),v.title&&nr(v.text)]}),et(O.Actions,{children:et(O.ActionButton,{label:n,onClick:k=>m(k,v.text)})})]})},v.text))}),et(Gt,{value:i,onChange:f,autoFocus:!0,placeholder:o,onKeyUp:S})]})},oc=Jh;var rr={};Q(rr,{enUS:()=>Yh,nlNL:()=>ey});var Yh={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},ey={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};import{jsx as fe,jsxs as ir}from"react/jsx-runtime";var iy=ny((t,e)=>{let o=h("TabCompletion",ue);return fe("mark",{ref:e,className:ar(o.matchSelection)},"selection-start")}),ay=({startRef:t,boundaryRef:e,inputStyle:o,inputElement:n,children:s})=>{let r=R(rr),i=h("TabCompletion",ue),a=sc(null),l=sc(null),[c,d]=rc(null),u=ry(),p=fn(document.activeElement===n),[g]=rc(()=>document.createRange());p.triggerRef.current=g,nc(()=>()=>g.detach(),[]),nc(()=>{let m=t.current,S=a.current;!m||!S||(g.setStart(m,0),g.setEnd(S,0))},[t.current,a.current]),xt(()=>{p.close()});let f=sy(m=>{let S=g.toString(),w=/^http(s?):\/\//.test(m)?m:`https://${m}`;u(Ro({text:`[${S}](${w})`,replace:"selection"}))},[]);return ir("span",{children:[fe("mark",{ref:a,className:ar(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":p.opened?"true":"false",children:s}),p.opened&&fe(Ct,{className:i.popoverRoot,triggerRef:p.triggerRef,boundaryRef:e,position:"above",align:"start",children:ir(hn,{style:o,ref:l,children:[fe("div",{className:ar(i.selectionOptions,{[i.selectionOptionsIsHidden]:c!==null}),children:ir("button",{type:"button",tabIndex:c===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>d("insertLink"),children:[fe(Ql,{}),fe("span",{children:"\xA0"}),fe("span",{children:r("insertLink")})]})}),c==="insertLink"&&fe(oc,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:f,onDismiss:()=>{d(null),p.close()}})]})})]},"selection-end")},xn=class extends ty{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(e,o){return this.props=o,this.charCount=0,this.startRef=oy(),this.foundIndex=0,e}match(e){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[o,n]=this.props.selection;if(o===n)return null;let s=this.foundIndex===0?o:n,r=s>=this.charCount&&s<=this.charCount+e.length?{index:s-this.charCount,length:0,match:"",valid:!0}:null;r&&this.foundIndex++;let i=this.foundIndex===1;return r&&i?this.charCount+=s-this.charCount:this.charCount+=e.length,r?{isStart:i,...r}:null}replaceWith(e,o){return o.isStart?fe(iy,{ref:this.startRef}):fe(ay,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};import{useSelector as gy}from"react-redux";import{jsx as wt,jsxs as hy}from"react/jsx-runtime";var my=({enabled:t,content:e,tabText:o,showTabHint:n,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:l})=>{let c=h("TabCompletion",ue),d=C("insertLink"),u=C("showMidSentenceSuggestions"),p=C("inlineSuggestions"),g=Fl(a),f=uy(null),m=gy(W);dy(()=>{He(a)&&g&&Bl(a,g)},[g]);let S=cy(y=>{if(!s||!o)return y;let k=[wt("span",{className:c.resetIndent,children:"\u200B"},"u200B"),wt("span",{"data-testid":"tab-completion",className:lr(c.tabText,c.resetIndent),"data-source":l,children:o},"tabText")];return n&&k.push(wt("span",{className:lr(c.hint,c.resetIndent),children:wt(Vn,{keyCode:"tab"},"tabHint")})),Js(y,k)},[s,o,n]),w=ic(()=>{let y=[];return d&&y.push(new xn("selection")),y.push(new vn("placeholders")),r&&y.push(new yn("keywords")),y},[p,d,r]),v=ic(()=>{let y=window.getComputedStyle(a);return{"--dd-color":y.color,"--dd-font-size":y.fontSize,"--dd-font-family":y.fontFamily,"--dd-font-variant":y.fontVariant}},[]);return!t||!m?null:hy("div",{ref:y=>{y!=null&&y.parentElement&&(f.current=y==null?void 0:y.parentElement)},className:c.root,style:v,children:[wt(ly,{tagName:"span",containerTagName:"div",className:lr(c.container,c.agentText),disableLineBreaks:He(a),content:e||"\u200B",onAfterParse:S,matchers:w,selection:g,keywordMatches:i,inputElement:a,inputStyle:v,boundaryRef:f,inlineSuggestionsOnlyAtEnd:!u}),wt("br",{})]})},fy=({input:t,ui:e,settings:o,styleSuggestions:n,conversation:s})=>{var m;let{tabCompletionSuggestion:r}=t,i=(r==null?void 0:r.text)||"",a=(r==null?void 0:r.source)||"",l=t.html??Xt(t.text),c=i.indexOf(t.text)===0?i.slice(t.text.length):"",{showTabHint:d}=e,{isSupported:u}=s,{showTabCompletion:p,visible:g,showStyleSuggestions:f}=o;return{showTabHint:d,showStyleSuggestions:f,showTabCompletion:p,content:l,tabText:c,source:a,keywordMatches:((m=n.list)==null?void 0:m.keywordMatches)??[],enabled:g&&u!==!1}},ac=py(fy)(my);import fv from"classnames";import{useEffect as hv}from"react";import{useDispatch as yv,useSelector as X}from"react-redux";import{createAsyncThunk as so,createSlice as yy}from"@reduxjs/toolkit";var lc={list:[],fetchState:"idle",isInitialRequest:null},dc=t=>t.autoflows.list||[],cc=t=>e=>{var o;return(o=e.list)==null?void 0:o.find(n=>n.triggerPayload===t)},Ee=so("autoflows/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getAutoflows(t)}),cr=so("autoflows/start",async(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");await n.startAutoflowSession(t),await o(Ee(t.platformSessionId))}),dr=so("autoflows/stop",async(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");await n.stopAutoflowSession(t.platformSessionId),await o(Ee(t.platformSessionId))}),vy=yy({name:"autoflows",initialState:lc,reducers:{},extraReducers:t=>{t.addCase(cr.pending,(e,o)=>{let n=cc(o.meta.arg.triggerPayload)(e);n.state="Started",n.isBusy=!0}),t.addCase(dr.pending,(e,o)=>{let n=cc(o.meta.arg.triggerPayload)(e);n.state="Aborted",n.isBusy=!0}),t.addCase(Ee.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}),t.addCase(Ee.rejected,e=>{e.fetchState="error"}),t.addCase(Ee.fulfilled,(e,o)=>{e.list=o.payload,e.fetchState="done"}),t.addCase(N,()=>lc)}}),uc=so("autoflows/openStream",(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");let s=n.openStream(t);s.on("sessionAborted",()=>{o(Ee(t))}),s.on("sessionCompleted",()=>{o(Ee(t))})}),pc=so("autoflows/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),gc=vy.reducer;import{createAsyncThunk as io,createSlice as Sy}from"@reduxjs/toolkit";var mc={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},fc=t=>t.customMessages.list,hc=t=>e=>!!e.customMessages.sentSuggestions.find(o=>o===t),yc=t=>e=>!!e.customMessages.answeredSuggestions.find(o=>o===t),vc=t=>e=>!!e.customMessages.errorSuggestions.find(o=>o===t),ro=io("customMessages/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getCustomMessages(t)}),bn=io("customMessages/send",async(t,e)=>{let{platformSessionId:o,suggestion:n}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.sendCustomMessage(o,n)}),Cn=io("customMessages/answer",async(t,e)=>{let{platformSessionId:o,reply:n}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.answerCustomMessage(o,n)}),Sc=Sy({name:"customMessages",initialState:mc,reducers:{onCustomMessage(t,e){Array.isArray(e.payload)?t.list=e.payload:t.list=[e.payload]}},extraReducers:t=>{t.addCase(ro.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(ro.rejected,e=>{e.fetchState="error"}).addCase(ro.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload||[]}).addCase(bn.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.errorSuggestions=e.errorSuggestions.filter(n=>o.meta.arg.suggestion.text!==n)}).addCase(bn.rejected,(e,o)=>{let n=e.sentSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1))}).addCase(Cn.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.answeredSuggestions.push(o.meta.arg.suggestion.text)}).addCase(Cn.rejected,(e,o)=>{let n=e.answeredSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1)),e.answeredSuggestions.splice(n,1)}).addCase(N,()=>mc)}}),xc=io("customMessages/openStream",(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.openStream(t).on("customMessageSuggestion",r=>{o(Sc.actions.onCustomMessage(r))})}),bc=io("customMessages/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),Cc=Sc.reducer;import{createAsyncThunk as wc,createSlice as xy}from"@reduxjs/toolkit";var by={token:null,accountUrl:null,interval:null},Tc=t=>e=>{let{passwordlessToken:{token:o,accountUrl:n}}=e;return o&&n?`${n}/apis/admin/session/passwordless/login/?token=${o}&redirect=${t}`:null},ur=wc("passwordlessToken/getTemporaryPasswordlessToken",async(t,e)=>{let{deepdeskAPI:o}=e.extra,n=await o.requestPasswordlessToken();return{accountUrl:o.client.baseUrl,token:n}}),pr=wc("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:o=1e3*60*10}=t,{dispatch:n}=e;return n(ur()),setInterval(()=>n(ur()),o)}),Ec=xy({name:"passwordlessToken",initialState:by,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(ur.fulfilled,(e,o)=>{e.token=o.payload.token,e.accountUrl=o.payload.accountUrl}),t.addCase(pr.fulfilled,(e,o)=>{e.interval=o.payload})}}),{stopPollPasswordlessToken:kc}=Ec.actions,Rc=Ec.reducer;function Pc(t){let{customMessages:e,autoflows:o}=t;return o.fetchState==="loading"&&o.isInitialRequest===!0||e.fetchState==="loading"&&e.isInitialRequest===!0}import{Fragment as Ny}from"react";import{connect as Oy}from"react-redux";import Ay from"classnames";import{Fragment as Ly}from"react";import wy from"classnames";var Ic={root:"Ai"};import{jsx as Ey}from"react/jsx-runtime";var Ty=({className:t,children:e})=>{let o=h("Unicode",Ic);return Ey("span",{className:wy(t,o.root),children:e})},Ac=Ty;var Lc={isDisabled:"Fi",buttonStart:"Hi",root:"Li",buttonStop:"xo",stateBadge:"h",isCompleted:"Mi",isStarted:"Ri",isAborted:"Ti"};var gr={};Q(gr,{enUS:()=>Ry,nlNL:()=>Py});var Ry={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]},Py={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]};import{jsx as tt,jsxs as wn}from"react/jsx-runtime";var My=({disabled:t,state:e,displayName:o,description:n,onStartAutoflow:s,onStopAutoflow:r})=>{let i=h("Autoflow",Lc),a=R(gr),l=e==="Started"?"stop":"start",c=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return wn(O,{className:Ay(i.root,{[i.isDisabled]:t,[i.isCompleted]:e==="Completed",[i.isAborted]:e==="Aborted",[i.isStarted]:e==="Started"}),children:[tt(H,{children:wn(H.Content,{children:[wn(H.Title,{children:[e&&tt("span",{className:i.stateBadge,children:a(e)}),o]}),tt("span",{children:n})]})}),tt(O.Actions,{fixed:e==="Started",children:tt(O.ActionButton,{primary:!0,className:l==="start"?i.buttonStart:i.buttonStop,onClick:e==="Started"?r:s,disabled:t,label:wn(Ly,{children:[tt(Ac,{children:c})," ",tt("span",{children:a(l)})]})})})]})},Mc=My;import{jsx as Nc}from"react/jsx-runtime";var _y=(t,e)=>{let o=e.filter(n=>n.state==="Started");return o.length>0?o.indexOf(t)===-1:!1},Dy=({autoflows:t,onStartAutoflow:e,onStopAutoflow:o,platformSessionId:n})=>Nc(Ny,{children:t.map(s=>Nc(Mc,{displayName:s.displayName,description:s.description,disabled:s.isBusy||_y(s,t),state:s.state,onStartAutoflow:()=>e({platformSessionId:n,triggerPayload:s.triggerPayload}),onStopAutoflow:()=>o({platformSessionId:n,triggerPayload:s.triggerPayload})},s.displayName))}),Hy=({autoflows:t,conversation:e})=>{var o;return{autoflows:t.list,platformSessionId:(o=e.current)==null?void 0:o.sessionId}},Fy={onStartAutoflow:cr,onStopAutoflow:dr},Oc=Oy(Hy,Fy)(Dy);import Ky from"classnames";import{useCallback as _c}from"react";import{useDispatch as Uy,useSelector as Tn}from"react-redux";var ke={root:"co",title:"fo",isUsed:"Ui",quickReplies:"Bi",quickReply:"Di",hasError:"Ii",label:"Oi",errorIcon:"Xi"};import{jsx as Fe,jsxs as En}from"react/jsx-runtime";var zy=({suggestion:t})=>{let e=R(Ze),o=Uy(),n=Tn(hc(t.text)),s=Tn(yc(t.text)),r=Tn(vc(t.text)),i=Tn(xo),{replyOptions:a}=t,l=_c(d=>{d.preventDefault(),d.stopPropagation(),!(n||!i)&&o(bn({platformSessionId:i,suggestion:t}))},[t,n,o,i]),c=_c(d=>{if(d.preventDefault(),d.stopPropagation(),!i||!a)return;let u=parseInt(d.target.dataset.index,10),p=a[u];o(Cn({platformSessionId:i,reply:p,suggestion:t}))},[t,n,o,i]);return En(O,{onClick:l,className:Ky(ke.root,{[ke.isUsed]:n,[ke.hasError]:r}),children:[Fe(H,{children:En(H.Content,{children:[En(H.Title,{className:ke.title,children:[t.text," ",Fe($n,{className:ke.label,children:"analyse tool"})," ",r&&Fe("span",{className:ke.errorIcon,role:"img","aria-label":e("sendingError"),title:e("sendingError"),children:"!"})]}),a&&a.length>0&&Fe("ul",{className:ke.quickReplies,children:a.map(d=>Fe("li",{className:ke.quickReply,children:d.title},d.title))})]})}),En(O.Actions,{fixed:r||n,children:[a&&a.length>0&&Fe(O.DropdownButton,{label:e("answer"),disabled:s,children:a.map((d,u)=>Fe(O.DropdownItem,{index:u,label:d.title,onClick:c},d.title))}),Fe(O.ActionButton,{primary:!0,disabled:n,onClick:l,label:e(n?"suggestionSent":r?"tryAgain":"sendSuggestion")})]})]})},Dc=zy;import{useEffect as $y,useState as qy}from"react";import{useDispatch as Gy}from"react-redux";import Bc from"classnames";import{jsx as Hc}from"react/jsx-runtime";var mr=()=>Hc("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:Hc("path",{d:"M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"})});var Fc={root:"Ji",entity:"r",entityText:"Ki",iconWrapper:"Pi",icon:"Qi",iconClicked:"Vi"};import{jsx as Tt,jsxs as Kc}from"react/jsx-runtime";var jy=({entities:t})=>{let e=h("EntitiesWidgetList",Fc),[o,n]=qy(void 0),s=Gy(),r=()=>{n(void 0)},i=a=>{t&&(n(t.indexOf(a)),We(a.text),s(G({name:"entity copied",data:{entity:a,type:"copy"}})))};return $y(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[o]),!t||t.length===0?null:Tt("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,l)=>Kc("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[Tt("span",{className:e.entityText,children:a.text}),Kc("span",{className:e.iconWrapper,children:[Tt("span",{className:Bc(e.icon),children:Tt(mr,{})}),Tt("span",{className:Bc(e.icon,o===l&&e.iconClicked),children:Tt(mr,{})})]})]},a.text))})},Uc=jy;import{jsx as zc}from"react/jsx-runtime";var Vc=()=>zc("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:zc("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});import{jsx as $c}from"react/jsx-runtime";var qc=()=>$c("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:$c("path",{d:"M543-340q16.595 0 28.798-12.202Q584-364.405 584-381t-12.202-28.798Q559.595-422 543-422t-28.798 12.202Q502-397.595 502-381t12.202 28.798Q526.405-340 543-340Zm-25-126h47q2-29 8.5-43t32.5-39q27-26 37.5-45.395Q654-612.79 654-639q0-45.882-31.5-74.941Q591-743 540-743q-38 0-68 20.5T428-665l45 19q11-25 27.5-38t39.5-13q29.778 0 48.389 17Q607-663 607-637q0 20-9 35t-32 32q-32 29-40 46.5t-8 57.5ZM260-200q-24 0-42-18t-18-42v-560q0-24 18-42t42-18h560q24 0 42 18t18 42v560q0 24-18 42t-42 18H260Zm0-60h560v-560H260v560ZM140-80q-24 0-42-18t-18-42v-620h60v620h620v60H140Zm120-740v560-560Z"})});import{jsx as Gc}from"react/jsx-runtime";var jc=()=>Gc("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:Gc("path",{d:"M319-250h322v-60H319v60Zm0-170h322v-60H319v60ZM220-80q-24 0-42-18t-18-42v-680q0-24 18-42t42-18h361l219 219v521q0 24-18 42t-42 18H220Zm331-554v-186H220v680h520v-494H551ZM220-820v186-186 680-680Z"})});import Xy from"dompurify";import{Fragment as Zy,useMemo as Qy,useRef as Jy,useState as Xc}from"react";import Yy from"snarkdown";var Wc={root:"i",popover:"Wi",options:"go",copyIcon:"Zi",option:"bo",divider:"_i"};import{jsx as ao,jsxs as Zc}from"react/jsx-runtime";var ev=t=>`<svg class=${t} version="1.1" x="0px" y="0px" viewBox="0 0 115.77 122.88" width="10px" height="10px" fill="black" fill-opacity="0.5" stroke-opacity="0.8"><g><path d="M89.62,13.96v7.73h12.19h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02v0.02 v73.27v0.01h-0.02c-0.01,3.84-1.57,7.33-4.1,9.86c-2.51,2.5-5.98,4.06-9.82,4.07v0.02h-0.02h-61.7H40.1v-0.02 c-3.84-0.01-7.34-1.57-9.86-4.1c-2.5-2.51-4.06-5.98-4.07-9.82h-0.02v-0.02V92.51H13.96h-0.01v-0.02c-3.84-0.01-7.34-1.57-9.86-4.1 c-2.5-2.51-4.06-5.98-4.07-9.82H0v-0.02V13.96v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07V0h0.02h61.7 h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02V13.96L89.62,13.96z M79.04,21.69v-7.73v-0.02h0.02 c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v64.59v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h12.19V35.65 v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07v-0.02h0.02H79.04L79.04,21.69z M105.18,108.92V35.65v-0.02 h0.02c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v73.27v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h61.7h0.02 v0.02c0.91,0,1.75-0.39,2.37-1.01c0.61-0.61,1-1.46,1-2.37h-0.02V108.92L105.18,108.92z"/></g></svg>`,tv=({content:t,useLabel:e,copyLabel:o,onCopy:n,onUse:s})=>{let r=h("Markdown",Wc),i=Jy(null),[a,l]=Xc(null),[c,d]=Xc(null),u=Qy(()=>{let S=Yy(t);return Xy.sanitize(S).replace(/<\/code>/g,`${ev(r.copyIcon)}</code>`)},[t]),p=()=>{l(null),d(null)},g=S=>{var y;let w=S.target,v=!!((y=i.current)!=null&&y.querySelector("code"));a||v&&w.tagName!=="CODE"||!v&&w!==i.current||(w.addEventListener("mouseleave",p,{once:!0}),d(w.textContent),l(w))},f=()=>{c&&n(c),p()},m=()=>{c&&s(c),p()};return Zc(Zy,{children:[a&&ao(Ct,{triggerRef:{current:a},parentNode:a,className:r.popover,children:Zc("div",{className:r.options,children:[ao("button",{type:"button",className:r.option,onClick:f,children:o}),ao("div",{className:r.divider}),ao("button",{type:"button",className:r.option,onClick:m,children:e})]})}),ao("div",{ref:i,className:r.root,dangerouslySetInnerHTML:{__html:u},onMouseOver:g})]})},Qc=tv;var fr={};Q(fr,{enUS:()=>ov,nlNL:()=>nv});var ov={useCue:[{type:0,value:"Copy"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}]},nv={useCue:[{type:0,value:"Gebruik"}],copyCue:[{type:0,value:"Kopieer"}],removeCue:[{type:0,value:"Sluiten"}]};import{jsx as kn,jsxs as Jc}from"react/jsx-runtime";var sv=({cue:t,onRemove:e,onCopy:o,onUse:n})=>{let s=R(fr),r=l=>{o&&o(l)},i=l=>{n&&n(l)},a=l=>{l.preventDefault(),l.stopPropagation(),e&&e(t.id)};return Jc(O,{"data-testid":"cue",children:[kn(H,{children:Jc(H.Content,{children:[t.title&&kn(H.Title,{"data-testid":"widget-cue-title",children:t.title}),kn(Qc,{content:t.text,useLabel:s("useCue"),copyLabel:s("copyCue"),onCopy:r,onUse:i})]})}),kn(O.CloseIcon,{title:s("removeCue"),onClick:a})]})},Yc=sv;import{Fragment as iv,jsx as ed}from"react/jsx-runtime";var rv=({cues:t,onCopyCue:e,onUseCue:o,onRemoveCue:n})=>ed(iv,{children:t.map(s=>ed(Yc,{cue:s,onRemove:n,onCopy:e,onUse:o},`${s.id}_${s.timestamp}`))}),td=rv;import{useCallback as lv}from"react";var av=/(https?:\/\/[^\s]+)/,od=t=>t.split(" ").find(e=>av.test(e));import{jsx as Et,jsxs as Rn}from"react/jsx-runtime";var cv=({suggestion:t,lines:e,onUse:o})=>{var d;let n=t.text||t.url||t.message,s=od(n),r=R(Ze),i=C("showImages"),a=C("fallbackImage"),l=u=>{u.preventDefault(),u.stopPropagation(),o(n)},c=lv(u=>{window.open(s,"_blank"),u.stopPropagation(),u.preventDefault()},[s]);return Rn(O,{onClick:l,"data-testid":"edit-suggestion",children:[Rn(H,{children:[i&&t.image&&Et(H.Image,{src:Sn(t,"small",a||void 0),title:t.title}),Rn(H.Content,{children:[t.title&&Et(H.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((d=t.searchKeywords)==null?void 0:d.length)>0&&Et(O.Labels,{labels:t.searchKeywords}),Et(H.Content,{cropText:e==="single",lineClamp:e==="multiple",children:n})]})]}),Rn(O.Actions,{children:[s&&Et(O.ActionButton,{onClick:c,label:r("visitUrl")}),Et(O.ActionButton,{primary:!0,onClick:l,label:r("useSuggestion")})]})]})},nd=cv;import{Fragment as uv,jsx as sd}from"react/jsx-runtime";var dv=({lines:t,suggestions:e})=>{let o=ae(),n=(s,r)=>{o.send(Me,{text:s,suggestion:{...r,source:r.source,sourceText:r.text}})};return sd(uv,{children:e.map(s=>sd(nd,{suggestion:s,lines:t,onUse:r=>n(r,s)},s.text||s.url||s.message))})},rd=dv;var hr={};Q(hr,{enUS:()=>pv,nlNL:()=>gv});var pv={waiting:[{type:0,value:"Loading\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"My "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Summarize"}],linkKnowledgeSearch:[{type:0,value:"Knowledge Assist"}],linkSearch:[{type:0,value:"Search"}]},gv={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"Mijn "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Gesprek samenvatten"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}]};var id={root:"or",loginText:"er",stateText:"ho",sectionList:"ir",shortcutList:"rr",shortcut:"tr",link:"mo"};import{jsx as A,jsxs as kt}from"react/jsx-runtime";var Pn=(t,e)=>{let o=X(W);hv(()=>o?e.every(n=>!!n)?t():()=>{}:()=>{},[...e,o])},vv=({onLogIn:t})=>{let e=R(hr),o=yv(),n=C("isEmbedded"),s=h("Widget",id),r=C("showAutoflows"),i=C("showCustomMessages"),a=C("showSummaryCommand"),l=C("showKnowledgeSearch"),c=C("showSearch"),d=X(_e),u=X(Yo),p=X(dc),g=X(Ii),f=X(Qo),m=X(fc),S=X(bo),w=X(dt),v=X(W),y=X(xo),k=X(Pc),x=X(en),T=ae(),L=X(tl),z=X(Tc("/admin/")),F=C("adminUrl"),P=C("productName"),M=ae();if(Pn(()=>(o(ro(y)),o(xc(y)),()=>{o(bc(y))}),[o,w,i,y]),Pn(()=>(o(Ee(y)),o(uc(y)),()=>{o(pc(y))}),[o,w,r,y]),Pn(()=>{u.forEach(({type:_})=>{o(_==="entities"?ce():de(_))})},[o,w,S,d]),Pn(()=>(o(pr()),()=>{o(kc())}),[o]),w===!1)return A("div",{className:s.stateText,children:A("div",{children:A("p",{children:e("notSupported")})})},"supported");if(v===!1)return A("div",{className:s.loginText,children:A("div",{children:A(un,{isEmbedded:n,loginUrl:F,onLogIn:t})})},"login");if(!d||!y||v===null||L||k)return A("div",{className:s.stateText,children:A("div",{children:A("p",{children:e("waiting")})})},"waiting");let V=_=>{M.send(Me,{text:_,suggestion:{source:"cue",sourceText:_}})},Z=c||a||l||z;return A("div",{className:fv(s.root),"data-testid":"widget",children:kt(Gn,{className:s.sectionList,children:[Z&&A(Re,{title:e("actions"),type:"shortcuts",children:kt("div",{className:s.shortcutList,children:[c&&kt("button",{className:s.shortcut,"data-testid":"shortcut-search",onClick:()=>T.send("ShowCommandPalette",{isOpen:!0}),children:[A(mt,{}),e("linkSearch")]}),a&&kt("button",{className:s.shortcut,"data-testid":"shortcut-summary",onClick:()=>T.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[A(jc,{}),e("linkSummary")]}),l&&kt("button",{className:s.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>T.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[A(qc,{}),e("linkKnowledgeSearch")]}),z&&kt("a",{className:s.shortcut,target:"_blank",href:z,"data-testid":"shortcut-studio-login",rel:"noreferrer",children:[A(Vc,{}),e("linkStudioLogin",{productName:P})]})]})}),i&&m.length>0&&A(Re,{type:"custom-messages","data-testid":"custom-messages",children:A(oe,{withDivider:!0,children:m.map(_=>A(Dc,{suggestion:_},_.text))})}),r&&p.length>0&&A(Re,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:A(oe,{withDivider:!0,children:A(Oc,{})})}),u.map(({type:_,title:Nt,amount:Ot,lines:Ue})=>{var b;switch(_){case"entities":return f&&f.length>0&&A(Re,{type:_,title:Nt,"data-testid":`type-${_}`,children:A(Uc,{entities:f})},_);case"cues":return g&&g.length>0&&A(Re,{type:_,title:Nt,"data-testid":`type-${_}`,children:A(oe,{withDivider:!0,children:A(td,{cues:g,onRemoveCue:B=>o(Li({id:B})),onCopyCue:B=>We(B),onUseCue:V})})},_);default:return((b=x[_])==null?void 0:b.fetchState)==="done"&&x[_].suggestions.length>0&&A(Re,{type:_,title:Nt,"data-testid":`type-${_}`,children:A(oe,{withDivider:!0,children:A(rd,{lines:Ue,contentType:_,suggestions:x[_].suggestions.slice(0,Ot)||[]})})},_)}})]})})},ad=vv;function co(t){let e=new Range;return e.selectNodeContents(t),e}function ld(t,e,o){try{return ot(t,e,o),!0}catch{return!1}}function In(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function An(t){return"tagName"in t&&t.tagName==="BR"}var lo=/[\u200B-\u200D\uFEFF]/g;function ot(t,e,o){let n=new Range;if(t.firstChild===null&&e===0&&o===0)return n.selectNodeContents(t),n;let s=0,r=!1;function i(l,c){let d=-1,u=/[\u200B-\u200D\uFEFF]/;if(!u.test(l))return c;for(let p=0;p<=l.length;p++)if(u.test(l[p])||d++,d===c)return p;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let c=l.textContent,d=c.replace(lo,""),u=s+d.length,p=e>=s&&e<=u,g=o>=s&&o<=u;if(p){let f=i(c,e-s);f===0&&!g?n.setStartBefore(l):n.setStart(l,f)}g&&(n.setEnd(l,i(c,o-s)),r=!0),s=u;break}case Node.ELEMENT_NODE:{if(An(l)&&(s===e&&n.setStartBefore(l),s++,s===o)){n.setEndAfter(l),r=!0;return}for(let d=0;d<l.childNodes.length&&(a(l.childNodes[d]),!r);d++);let c=l.lastChild;In(l)&&c&&!In(c)&&!An(c)&&s++;break}default:break}}if(a(t),n.startContainer===document)throw new Error("Offsets out of bound");return n}function Ln(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:o,startOffset:n,endContainer:s,endOffset:r,collapsed:i}=e,a,l,c=0;function d(u){let p=u===o,g=u===s;switch(u.nodeType){case Node.TEXT_NODE:{let f=u.textContent;p&&(a=c+f.substring(0,n).replace(lo,"").length),g&&(l=c+f.substring(0,r).replace(lo,"").length),c+=f.replace(lo,"").length;break}case Node.ELEMENT_NODE:{let f=u.nextSibling===null;An(u)&&!f&&c++;for(let m=0;m<u.childNodes.length;m++){let S=p&&m===n,w=g&&m===r;if(S&&(a=c),w&&(l=c),l!==void 0||((!S||!i)&&d(u.childNodes[m]),g&&m===r-1&&(l=c),l!==void 0))break}!g&&In(u)&&!f&&c++,g&&(l=c);break}default:break}}if(d(t),l===void 0)throw new Error("Could not determine start and end");return{start:a??l,end:l}}function Mn(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:o,startOffset:n,endContainer:s,endOffset:r}=e,i=-1,a="";function l(c){let d=c===o,u=c===s;switch(d&&i++,c.nodeType){case Node.TEXT_NODE:{if(i!==0)return;let p=d?n:0,g=u?r:void 0,f=c.textContent.replace(lo,"");p===0&&g===void 0?a+=f:a+=f.substring(p,g);break}case Node.ELEMENT_NODE:{let p=c.nextSibling===null;i===0&&An(c)&&!p&&(a+=`
8
- `);for(let g=d?n:0;g<(u?Math.min(r,c.childNodes.length):c.childNodes.length)&&(l(c.childNodes[g]),i!==1);g++);!u&&i===0&&In(c)&&!p&&(a+=`
9
- `);break}default:break}u&&i++}return l(t),a}var cd=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(cd||{}),Be=class{constructor(e){this.element=e;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(e,o){let n=s=>{o(s)};this.element.addEventListener(e,n),this.disposeHandlers.push(()=>{this.element.removeEventListener(e,n)})}removeEventListener(e,o){this.element.removeEventListener(e,o)}triggerChange(){let e=this.getText(),o=this.getHTML(),n=e!==this.currentText;this.isActive&&(e===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&n&&!this.isSubmitting&&this.emit("change",{plainText:e}),n&&(this.currentSelection=this.getSelection()),this.currentText=e,this.isSubmitting=!1,(this.currentHTML!==o||o===null&&n)&&(this.emit("updated",{plainText:e}),this.triggerCaretPosition(),this.currentHTML=o))}triggerSelection(){let e=this.getSelection();(e.start!==this.currentSelection.start||e.end!==this.currentSelection.end)&&(this.currentSelection=e,this.emit("selection",e),this.triggerCaretPosition())}triggerCaretPosition(){let e=this.getCaretPosition();Ie(e,this.currentCaret)||(this.currentCaret=e,this.emit("caret",e))}handleKeyUp(e){let{key:o,shiftKey:n}=e;(o==="Enter"&&n===!0||o==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(e){let{key:o,ctrlKey:n,metaKey:s}=e;this.isPossibleClearInputAction=Object.values(cd).includes(o)||o.toLowerCase()==="z"&&(n||s),this.emit("keydown",e)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){var n,s;let o=((n=e.clipboardData)==null?void 0:n.getData("text"))||((s=e.clipboardData)==null?void 0:s.getData("text/plain"))||"";this.emit("paste",{pastedText:o,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",o=>this.handleKeyDown(o)),this.addEventListener("keyup",o=>this.handleKeyUp(o)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",o=>this.handlePaste(o)),this.addEventListener("click",()=>this.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let e=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});e.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{e.disconnect()}),this.currentSelection=this.getSelection()}focus(){this.element.focus()}emit(e,...o){this.isDisposed||this.eventListeners[e]&&this.eventListeners[e].forEach(n=>{n(...o)})}on(e,o){this.isDisposed||(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o))}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};function dd(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var Rt=class extends Be{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),Mn(this.element,e)}getHTML(){return this.element.innerHTML||""}getRange(){var r;let e=this.getRootNode();if(e.activeElement!==this.element)return null;let o="getSelection"in e?e.getSelection():window.getSelection();if(!o)return null;let n="getComposedRanges"in o&&e instanceof ShadowRoot?(r=o.getComposedRanges(e))==null?void 0:r[0]:o.rangeCount>0?o.getRangeAt(0):null;if(!n)return null;let s=this.element.ownerDocument.createRange();return s.setStart(n==null?void 0:n.startContainer,n==null?void 0:n.startOffset),s.setEnd(n==null?void 0:n.endContainer,n==null?void 0:n.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let e=this.getRange();if(!e||!e.collapsed||!("getBoundingClientRect"in e))return null;let o=e.getBoundingClientRect();return!dd(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!dd(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return Ln(this.element,e);let o=this.lastKnownSelection;if(o&&ld(this.element,o.start,o.end))return o;let n=co(this.element);return n.collapse(!1),Ln(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return Mn(this.element,ot(this.element,e,o))}applyChanges(e){var s;if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return(s=this.observer)==null||s.takeRecords(),Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let e=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==e&&(e=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var Pt=class extends Be{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:e,selectionEnd:o}=this.element;return{start:e,end:o}}getSelectedText(){let e=this.getSelection();return e?this.getText().slice(e.start,e.end):""}getCaretPosition(){return null}applyChanges(e){if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let e=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=e==null?void 0:e.get)==null?void 0:s.call(this.element)},set:s=>{var r;(r=e==null?void 0:e.set)==null||r.call(this.element,s),this.triggerChange()}});let o=this.element.disabled,n=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>n.disconnect())}};function ud(t,e,o){let n=`deepdesk-iframe-${t}`,s=document.getElementById(n);if(s)return s;let r=document.createElement("iframe"),i=new URL(e);return Object.entries(o).forEach(([a,l])=>{i.searchParams.append(a,l)}),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=n,r.title=`iframe-${t}`,r.src=i.toString(),window.document.body.appendChild(r),r}function Sv(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}var yr=class{constructor(e){this.name=e;this.broadcastChannel=new BroadcastChannel(e)}broadcastChannel;disposeHandlers=[];onMessage(e){this.broadcastChannel.addEventListener("message",e),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",e)})}postMessage(e){this.broadcastChannel.postMessage(JSON.stringify(e))}close(){this.disposeHandlers.forEach(e=>e()),this.broadcastChannel.close()}},vr=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=ud(e,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var o;(o=this.iframe.contentWindow)==null||o.postMessage(JSON.stringify(e),this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(o=>o()),(e=this.iframe)==null||e.remove()}},Sr=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(e){this.sessionId!==e&&(this.cleanup(),E.info("Set sessionId",e),this.sessionId=e,this.channel=this.createChannel(e))}createChannel(e){let o=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new vr(e,this.deepdeskUrl,{debug:!0}):new yr(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=Sv(s.data);typeof r!="object"||r.type!=="event"||r.channel!==e||(E.info("Received broadcast event",this.sessionId,s),(a=(i=this.eventMap)[r.name])==null||a.call(i,r.payload))};return o.onMessage(n),o}send(e,o,n){var i,a;E.info("Broadcast event",{sessionId:this.sessionId,name:e,payload:o});let s={type:"event",name:e,payload:o};n!==!1&&((a=(i=this.eventMap)[e])==null||a.call(i,o));let r=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;r==null||r.postMessage({...s,channel:this.sessionId})}cleanup(e=!1){var o,n;(o=this.channel)==null||o.close(),delete this.channel,e&&((n=this.defaultChannel)==null||n.close(),delete this.defaultChannel)}},pd=Sr;var It=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var xr=t=>new Promise(e=>{setTimeout(e,t)});var At=class extends It{name="ClientError"},Cr=class extends It{name="ServerError"},br=new Map,he=class t{constructor(e="",o={}){this.baseUrl=e;this.options=o;o.fetch&&(this.fetch=o.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,o={}){return new Promise((n,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,l=o.method===void 0||o.method.toLowerCase()==="get",{useCache:c=!1,abortLatest:d=!1,attempts:u=1,retryDelay:p=500,refreshTokenOn401:g=!0,retryOnError:f=T=>T instanceof TypeError,retryOnResponse:m=T=>T.status>=500,version:S="v1",...w}=o;if(c)if(l){if(br.has(i)){n(br.get(i));return}}else throw new Error(`Can't use 'useCache' for ${o.method}`);let v={credentials:"include",...w,headers:{"Content-Type":"application/json",...w.headers}};!l&&this.csrfToken&&(v.headers={...v.headers,"X-CSRFToken":this.csrfToken}),typeof S=="string"&&(v.headers={...v.headers,"X-Deepdesk-API-Version":S});let y=u,k=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&d&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let x=async()=>(y--,a(i,v).then(async T=>m(T)&&!r.isAborted&&y>0?(await xr(p),x()):T.status===401&&g===!0&&k===!1?(k=!0,await this.refreshToken(),x()):T).catch(async T=>{if(f(T)&&!r.isAborted&&y>0)return await xr(p),x();throw T}));x().then(T=>T.json().catch(()=>null).then(L=>{T.status>=500?s(new Cr("Server Error",L)):T.status===401?s(new At("Unauthorized",L)):T.status===403?s(new At("Forbidden",L)):T.status===404?s(new At("Not Found",L)):T.status>=400&&s(new At("Bad Request",L)),delete this.latestRequestByUrl[i],c&&br.set(i,L),n(L)})).catch(T=>{s(T)})})}async validateToken(){let{has_valid_access_token:e}=await this.get("/auth/validate");if(!e)return!1;let{is_logged_in:o}=await this.get("/apis/admin/session/validate/",{version:null});return!!o}refreshToken(){return t.refreshingToken||(t.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{t.refreshingToken=null},1e3*60)})),t.refreshingToken}get(e,o){return this.request(e,o)}post(e,o,n){return this.request(e,{method:"POST",body:JSON.stringify(o),...n})}patch(e,o,n){return this.request(e,{method:"PATCH",body:JSON.stringify(o),...n})}put(e,o,n){return this.request(e,{method:"PUT",body:JSON.stringify(o),...n})}delete(e,o){return this.request(e,{method:"DELETE",...o})}};var xv;(e=>{let t;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||={})})(xv||={});function Nn(t){return{...I(t),tags:t.tags}}var Ke=class t{constructor(e,o={}){this.options=o;this.client=new he(e,{fetch:o.fetch}),this.client.patchFetch(n=>async(s,r)=>{let i=await n(s,r);return this.handleDeepdeskVersionHeaders(i),i})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=await this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(t.exchangeTokenPromise||(t.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),t.exchangeTokenPromise):Promise.resolve()}async createConversation(e){await this.preflight(),E.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...U(e),tags:e.tags},{version:"v2"});return Nn(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null,useCache:!0});return I(o)}async getKnowledgeAssistant(e){let o=await this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{version:null,useCache:!0});return I(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return I(e)}async getAccount(){let e=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return I(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null,useCache:!0});return I(e)}async checkUserExists(e){let{exists:o}=await this.client.get(`/apis/admin/users/exists?external_id=${e}`);return o}async getConversationBySessionId(e,o={}){await this.preflight(),E.info(`Getting conversation for session ${e}`);let{attempts:n=1,retryDelay:s=1e3}=o,r=await this.client.get(`/api/conversations/by_session_id/${e}`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"});return E.info(`Successfully retrieved conversation ${r.id} for session ${e}`),Nn(r)}async isConversationSupported(e,o={}){E.info(`Check if conversation for session ${e} is supported`);let{attempts:n=1,retryDelay:s=1e3}=o;return(await this.client.get(`/api/conversations/by_session_id/${e}/active_profile`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"})).has_active_profile}async updateConversation(e,o){let n=U(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return Nn(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...U(s),tags:s.tags})),{version:"v2"})).map(s=>Nn(s))}async sendEvent(e,o){let{data:n,...s}=o,r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((i,[a,l])=>({...i,[a]:l}),{});return this.client.post("/api/events",U({...r,...s,data:n,name:e}),{version:"v2"})}async sendEventV1(e,o){let n=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[r,i])=>({...s,[r]:i}),{});return this.client.post("/api/events",{event:e,data:U({...o,...n})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e.filter(n=>n.text)})).entities}async getSummary(e,o={}){return(await this.client.post("/api/summary",{conversation:{messages:e.filter(s=>s.text&&s.source),agent_id:o.agentId,id:o.externalConversationId},prompt_instruction:o.promptInstruction,model:o.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(e){return this.client.post("/apis/admin/session/jwt/",{jwt:e},{version:null}).catch(o=>{throw E.warn(`Invalid token '${e}'`),o})}async authenticateWithKey(e,o){await this.preflight(),await this.client.post("/apis/admin/session/api-key/",U(o),{version:null,refreshTokenOn401:!1,headers:{apikey:e}})}async getTextSuggestions(e,o={},n){return n==="sticky-messages"?this.getPinnedMessages(e):(await this.client.post(`/api/conversations/${e}/recommend/${n}`,U(o),{abortLatest:!0})).map(r=>({...I(r),text:r.text||r.url||r.message,source:n,type:n})).filter((r,i,a)=>i===a.findIndex(l=>l.text===r.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(e,o){return(await this.client.post(`/api/conversations/${e}/autocomplete`,U(o),{abortLatest:!0})).map(s=>({score:1,source:s.source,sourceText:s.source_text,text:s.label,trainingJobs:s.training_jobs,searchKeywords:s.search_keywords,type:s.source})).filter((s,r,i)=>r===i.findIndex(a=>a.text===s.text))}async getPinnedMessages(e){let o=await this.client.get(`/api/conversations/${e}/sticky-messages`,{abortLatest:!0});return I(o).map(n=>({...n,text:n.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(e){let o=await this.client.post("/api/style-suggestions",U(e),{abortLatest:!0});return I(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,U(e),{version:"v2"});return I(o)}async knowledgeAssist(e,o,n,s={}){let r=await this.client.post(`/api/knowledge-assist/assistants/${n}/search`,U({question:e.question,promptInstruction:e.promptInstruction,chatHistory:o.map(i=>({question:i.question,answer:i.answer.answer})),agentId:s.agentId,conversationId:s.conversationId}),{version:"v2"});return I(r)}async requestLoginByEmail(e){let o=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return I(o)}async requestPasswordlessToken(){let e=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return I(e.token)}async getCsrfToken(){let{token:e}=await this.client.get("/apis/admin/session/csrf/",{version:null});return e}async verifyLoginToken(e){let o=await this.client.post("/apis/admin/session/passwordless/login/",{token:e},{version:null});return I(o)}async evaluateRule(e,o,n,s={}){let r=new URLSearchParams;s.raiseForFailingConditions&&r.set("raise_for_failing_conditions","true");let i=await this.client.post(`/api/conversations/${o}/rules/${e}/evaluate?${r.toString()}`,n,{version:"v2"});return I(i.cues)}async getRules(){let e=new URLSearchParams,o=await this.client.get(`/apis/admin/rule-engine/rules/?${e.toString()}`,{version:null,useCache:!0});return I(o)}async translateMessages(e){let o=await this.client.post("/api/translate",U(e),{version:"v2"});return I(o)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(Vr);if(!o||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&o&&a!==o&&E.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(o)}`),this.latestReceivedDeepdeskVersions[i]=o})}};var uo=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(ts(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,I(s))}catch{E.warn(`Invalid JSON for ${e}: ${n}`)}})}connect(){clearTimeout(this.timeoutTimer);let e=new EventSource(this.url,{withCredentials:!0});this.eventSource=e;let o=!1;e.onopen=()=>{o=!0},e.onerror=()=>{o&&e.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{e.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(n=>{this.proxyEvent(n)})}disconnect(){var e;clearTimeout(this.timeoutTimer),this.eventListeners={},(e=this.eventSource)==null||e.close()}emit(e,o){this.eventListeners[e]&&this.eventListeners[e].forEach(n=>n(o))}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),this.proxyEvent(e),()=>{this.off(e,o)}}off(e,o){let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}};var bv;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(bv||={});var po=class{constructor(e,o={}){this.apiUrl=e;this.client=new he(e,o)}client;streams={};logger=E;async getCustomMessages(e){let o=await this.client.get(`/sessions/${e}/suggestions`);return I(o.suggestions)}async sendCustomMessage(e,o){let n=await this.client.post(`/sessions/${e}/messages`,U(o));return I(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,U(o))}async getAutoflows(e){let o=await this.client.get(`/sessions/${e}/autoflows`);return I(o.autoflows)}async startAutoflowSession(e){let o=await this.client.post("/autoflow-sessions",U(e));return I(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new uo(`${this.apiUrl}/sessions/${e}/events`),this.streams[e].connect()),this.streams[e]}closeStream(e){this.streams[e]||(this.streams[e].disconnect(),delete this.streams[e])}};import{combineReducers as Pv,configureStore as Iv}from"@reduxjs/toolkit";import{createSlice as Cv}from"@reduxjs/toolkit";var gd={startTime:null,stopTime:null},md=Cv({name:"handlingTime",initialState:gd,reducers:{handlingTimeStart(t){if(t.startTime&&!t.stopTime)throw new Error("Timing already started");t.startTime=new Date,t.stopTime=null},handlingTimeStop(t){if(!t.startTime)throw new Error("Timing not started");t.stopTime=new Date},handlingTimeReset(t){t.startTime=null,t.stopTime=null}},extraReducers:t=>{t.addCase(N,()=>gd)}}),{handlingTimeStart:fd,handlingTimeStop:On,handlingTimeReset:hd}=md.actions,yd=md.reducer;var vd=(t={})=>{let e={onAuthError:lt(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};import{createAsyncThunk as wv,createSlice as Tv}from"@reduxjs/toolkit";var _n={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var nt=wv("styleSuggestions/getAll",async({text:t},e)=>{var i;let{deepdeskAPI:o}=e.extra,n=e.getState(),{showStyleSuggestions:s}=n.settings,r=(i=n.conversation.current)==null?void 0:i.profileCode;if(!s)return _n.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),Ev=Tv({name:"styleSuggestions",initialState:_n,reducers:{},extraReducers:t=>{t.addCase(nt.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(nt.rejected,e=>{e.fetchState="error"}).addCase(nt.fulfilled,(e,o)=>{e.fetchState="done",Ie(e.list,o.payload)||(e.list=o.payload)}).addCase($e,e=>{e.list=_n.list}).addCase(N,()=>_n)}}),Sd=Ev.reducer;var xd=(t={})=>{let e,o=!0,n={getStyleSuggestions:nt,debounce:500,...t};return s=>r=>i=>{var g;let a=s.getState().input.text,l=r(i),c=s.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:d}=c.settings;if(!((g=c.conversation.current)==null?void 0:g.id)||!d)return l;let{text:p}=c.input;return p===a&&!o||(clearTimeout(e),p==="")||(e=setTimeout(()=>{o=!1,s.dispatch(n.getStyleSuggestions({text:p}))},t.debounce)),l}};function kv(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var bd=(t={})=>{let e={getTextSuggestions:de,getAutocompleteSuggestions:Yt,debounce:200,check:bt,...t},o;return n=>s=>r=>{var m;let{input:{userCommitted:i}}=n.getState(),a=s(r),l=n.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:d}=l.settings,u=(m=l.conversation.current)==null?void 0:m.id,p=r.type===tn.toString();if(!u||!c&&!d)return a;let{input:{userCommitted:g}}=l;return kv(g,i)&&!p||(clearTimeout(o),!e.check(l))||(o=setTimeout(()=>{let S=pt(l);S===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(S))},p?0:e.debounce)),a}};var Cd=nt.fulfilled.toString();function Rv(t,e){let o=new Set([...e.keywordMatches.map(s=>s.keyword)]),n=[];return o.forEach(s=>{let r=t.keywordMatches.filter(l=>l.keyword===s),i=e.keywordMatches.filter(l=>l.keyword===s),a=i.length-r.length;a<=0||n.push(...i.slice(0,a))}),n}var wd=t=>e=>o=>n=>{var c;if(n.type!==Cd){o(n);return}let s=e.getState().styleSuggestions.list;o(n);let r=e.getState(),i=r.styleSuggestions.list,a=(c=r.conversation)==null?void 0:c.current;if(s===i)return;let l=Rv(s,i);n.type===Cd&&l.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var Av=Pv({answer:za,auth:Jr,autoflows:gc,conversation:oi,contentTypes:ea,customMessages:Cc,passwordlessToken:Rc,entities:ka,knowledgeAssistant:Ba,handlingTime:yd,info:bi,input:yi,settings:qr,profile:Wa,search:Pi,summary:Na,styleSuggestions:Sd,ui:xl,rules:Mi,textSuggestions:sl});function Td(t){return Iv({reducer:Av,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),vd(),bd({debounce:200}),xd({debounce:500}),wd(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var Lv=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},Mv=t=>e=>o=>n=>{var a;let s=e.getState(),r=Xn("inlineSuggestions")(s);switch(n.type){case lt.toString():{!n.payload&&t.emit("logout",void 0);break}case ce.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:n.payload}});break;case Ce.fulfilled.toString():t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{summary:n.payload.summary}});break;case G.toString():t.sendEvent(n.payload.name,{conversationId:((a=n.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:n.payload.data});break;case Po.toString():t.handleKeyDown(n.payload);break;case $e.toString():t.logSendMessage(n.payload);break;case Io.toString():t.handleInputChanged(n.payload);break;case be.fulfilled.toString():t.broadcast(is,n.payload,!1),t.emit("cues",n.payload);break;default:break}let i=o(n);switch(n.type){case $e.toString():t.handleAfterSendMessage(n.payload);break;case eo.toString():t.onUpdateShowTabHint(n.payload);break;case On.toString():t.logHandlingTime();break;case ge.toString():{let{start:l,end:c}=s.input.selection;t.emit("select-suggestion",{type:Lv(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0}),r&&(e.dispatch(pe([])),e.dispatch(xe()));break}case Ro.toString():{let{start:l,end:c}=s.input.selection;t.emit("replace",{...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case Ft.toString():{let l=e.getState(),{text:c,selection:d}=l.input.userCommitted;t.emit("reset",{text:c,selectionAfter:d},{mayApplyChanges:!0});break}case Ao.toString():t.emit("select-image",n.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:s.conversation.current.id,data:{path:n.payload.suggestion.image,title:n.payload.suggestion.title}});break;case pe.toString():{r&&n.payload.length>0&&e.dispatch(Le(0));break}default:break}return i},Ed=Mv;function wr(t){return t.toISOString().replace("T"," ").replace("Z","")}function kd(t,e){var s,r,i;let{startTime:o,stopTime:n}=t.handlingTime;if(!o||!n)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:t.conversation.current.id,clientVersion:e.version,agentId:(s=t.info.agentInfo)==null?void 0:s.agentId,agentName:(r=t.info.agentInfo)==null?void 0:r.agentName,agentEmail:(i=t.info.agentInfo)==null?void 0:i.agentEmail,timeStart:wr(o),timeStop:wr(n)}}function Rd(t,e,o){var L,z,F;let{text:n,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:d,pastes:u,cuts:p,deletions:g,textSuggestions:f,offeredTextSuggestions:m}}=e[t],S=n.length,v=f.reduce((P,{text:M,searchTerm:V})=>P+M.length-(V?V.length:0),0),y=c??Date.now(),k=(Date.now()-y)/1e3+(d||0),x=s/k,T=f.reduce((P,{searchTerm:M})=>P+(M?M.length:0),0);return{conversationId:e.conversation.current.id,source:"agent",text:n,clientVersion:o.version,pastes:u,cuts:p,deletions:g,lenTextTyped:s+T,lenTextTotal:S,lenTextAssisted:v,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:k,charsPerSecond:x,numPastes:l,textSuggestionsV2:f,suggestionsCounters:[{source:"gpt",countOffered:m.filter(P=>P.source==="gpt").length}],agentId:(L=e.info.agentInfo)==null?void 0:L.agentId,agentName:(z=e.info.agentInfo)==null?void 0:z.agentName,agentEmail:(F=e.info.agentInfo)==null?void 0:F.agentEmail}}function Tr(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return Tr(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?Tr(s,e):null}function Pd(t,e){return Tr(t,e)}function Id(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function Nv(t){return typeof t=="object"&&t!==null&&"tagName"in t}function Er(t){return Nv(t)&&(He(t)||pn(t))}var Ad,ye=new Map,Ov=["bottom","height","left","right","top","width"],_v=(t={},e={})=>Ov.some(o=>t[o]!==e[o]);function Ld(t){var o,n;if(t.ownerDocument===document)return[];let e=((n=(o=t.ownerDocument)==null?void 0:o.defaultView)==null?void 0:n.frameElement)??null;return e?[e,...Ld(e)]:[]}function Md(t,e){return!t||!e?null:{...t,top:t.top+e.top,left:t.left+e.left}}var Dn=!1,Nd=()=>{Dn=!0;let t=[];if(ye.forEach((e,o)=>{if(!o.isConnected){e.rect=null,t.push(e),ye.delete(o);return}let n=o.getBoundingClientRect();_v(n,e.rect)&&(e.rect=n,t.push(e))}),t.forEach(e=>{let o=e.parentRects?e.parentRects.reduce(Md,e.rect):e.rect;e.callbacks.forEach(n=>n(o))}),ye.size===0){Dn=!1;return}Ad=window.requestAnimationFrame(Nd)};function kr(t,e){let o=Ld(t),n=[],s=o.map((r,i)=>kr(r,a=>{n[i]=a;let l=ye.get(t);if(!l)return;let c=n.reduce(Md,l.rect);l.callbacks.forEach(d=>d(c))}));return{observe(r=!0){if(s.forEach(i=>i.observe(!1)),ye.has(t)){let i=ye.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else ye.set(t,{rect:void 0,callbacks:[e],parentRects:n});r&&!Dn&&Nd()},unobserve(){s.forEach(i=>i.unobserve());let r=ye.get(t);if(r){let i=r.callbacks.indexOf(e);i>=0&&r.callbacks.splice(i,1),r.callbacks.length||ye.delete(t),ye.size||(cancelAnimationFrame(Ad),Dn=!1)}}}}var Od,ve=new Map,_d=()=>{ve.forEach((t,e)=>{if(!e.isConnected){ve.delete(e);return}let{clientHeight:o,scrollHeight:n}=e,s=n>o;t.visible!==s&&(t.visible=s,t.callbacks.forEach(r=>r(t.visible)))}),ve.size!==0&&(Od=window.requestAnimationFrame(_d))};function Dd(t,e){return{observe(){let o=ve.size===0;ve.has(t)?ve.get(t).callbacks.push(e):ve.set(t,{visible:void 0,callbacks:[e]}),o&&_d()},unobserve(){let o=ve.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||ve.delete(t),ve.size||cancelAnimationFrame(Od)}}}}var Rr=["borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth","borderStyle","boxSizing","color","overflowWrap","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontWeight","fontKerning","lineHeight","letterSpacing","paddingLeft","paddingTop","paddingRight","paddingBottom","width","height","textIndent","whiteSpace","wordBreak","wordSpacing","wordWrap"];function Pr(t,e,o){return o.forEach(n=>{e.style[n]=t[n]})}function Lt(t){return parseFloat(t)}function Hn(t){return Math.round(t*1e6)}function Hd(t){return t/1e6}function Ir(t,e,o){if(t.boxSizing==="content-box")return;let{clientWidth:n}=e,s=Lt(t.width),r=Lt(t.borderLeftWidth),i=Lt(t.borderRightWidth),a=Lt(t.paddingRight),l=Hd(Hn(s)-Hn(r)-Hn(i)),c=Hd(Hn(n));if(l-c>2){let d=l-c;o.style.paddingRight=`${a+d}px`}}function Fn(t,e={}){var d;let o=e.overlayContainer||document.createElement("div");o.style.display="none",o.style.position=e.position??"fixed",o.style.pointerEvents="none",o.style.borderColor="transparent",Je(o);let n=window.getComputedStyle(t),s=!0,r=()=>{o.scrollTop=t.scrollTop};Pr(n,o,Rr),Ir(n,t,o),e.mirrorOverflow&&(o.style.overflow="hidden",t.addEventListener("scroll",r));let i=Dd(t,()=>{Pr(n,o,Rr),Ir(n,t,o),r(),setTimeout(r,0)}),a,l=!0,c=kr(t,u=>{if(u===null){e.onRemove&&e.onRemove(),o.remove();return}if(!l&&e.onMoveStart&&(Promise.resolve().then(()=>e.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{e.onMoveEnd&&e.onMoveEnd(),l=!1},200),u.height===0&&u.width===0){if(s===!0)return;e.onHide&&e.onHide(),o.style.display="none",s=!0;return}if(Pr(n,o,Rr),Ir(n,t,o),r(),o.style.top=`${u.top}px`,o.style.left=`${u.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let p=e.closestScrollElement.getBoundingClientRect(),g=window.getComputedStyle(e.closestScrollElement),f=Lt(g.borderTopWidth),m=Lt(g.borderBottomWidth),S=p.top+f-u.top,w=u.top+u.height+-(p.top+p.height-m);o.style.clipPath=`inset(${S}px 0px ${w}px 0px)`}s&&(o.style.display="block",e.onShow&&e.onShow(),s=!1)});return e.appendTo?e.appendTo.appendChild(o):(d=t.parentElement)==null||d.appendChild(o),c.observe(),i.observe(),[o,()=>{t.removeEventListener("scroll",r),c.unobserve(),i.unobserve()}]}var Fd=(t,e)=>({value(){try{let o=sessionStorage.getItem(`dd-${t}`);if(!o)return e;try{return JSON.parse(o)}catch{return e}}catch{return e}},update(o){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(o))}catch{E.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function Dv(t){return t.offsetParent!==null}function Bd(t){if(!Dv(t))return!1;let e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}function Ar(t,e,o=100){let n=Bd(t);e({isVisible:n});let s=setInterval(()=>{let r=Bd(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}import{jsx as $}from"react/jsx-runtime";var Kd=Fd("showTabHint",!0),Kn=class t{static version="11.1.1-beta.2";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:l}){let c=e.replace(/\/api$/,"");this.deepdeskApi=new Ke(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let d={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Ed({broadcast:(u,p,g)=>{this.broadcastEvents.send(u,p,g)},emit:(u,p,g)=>this.emit(u,p,g),handleAfterSendMessage:u=>this.handleAfterSendMessage(u),handleInputChanged:u=>this.handleInputChanged(u),handleKeyDown:u=>this.handleKeyDown(u),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:u=>this.logSendMessage(u),onUpdateShowTabHint:u=>Kd.update(u),sendEvent:(u,p)=>this.deepdeskApi.sendEvent(u,p)})]};o&&Object.assign(d,{deepdeskBrokerAPI:new po(o)}),this.store=Td(d),this.broadcastEvents=new pd({debug:!0,deepdeskUrl:c,eventMap:Ni(this.store),createCustomChannel:l}),this.store.dispatch(eo(Kd.value())),this.store.dispatch(So({locale:s,adminUrl:c,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(E.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(E.warn("Profile has not been loaded (yet)"),!0):(E.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(lt(null)),this.store.dispatch(Se()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();W(n)&&Gr(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(Se())).payload}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(o){E.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(Jn({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Co(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(wo({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Yn(e))).payload}async postMessages(e){return(await this.store.dispatch(Eo(e))).payload}async updateConversation(e){return(await this.store.dispatch(To(e))).payload}resetConversation(){this.store.dispatch(N()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Ce());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(So(e))}setVisitorInfo(e){this.store.dispatch(xi(e))}async setAgentInfo(e){await this.store.dispatch(Bt(e))}async setAgentSettings(e){await this.store.dispatch(ns(e))}async getAgentSettings(){return(await this.store.dispatch(ss())).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(Io(e))}notifyKeyDown(e){this.store.dispatch(Po(e))}notifyPaste(e,o){this.store.dispatch(gi({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(ui(e))}notifyExternalSuggestion(e){this.store.dispatch(ge(e)),this.store.dispatch(xe())}async evaluateRule(e,o={}){let{payload:n,error:s}=await this.store.dispatch(be({label:e,params:o}));if(s)throw new Error(s.message);return n}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(De({collapse:!1})),this.inputMediator&&this.store.dispatch(ii({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(pe([])))}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(pi(ni(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(li()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},d=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(di()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Ft()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(e.key){case"Up":case"ArrowUp":i?d():c();return;case"Down":case"ArrowDown":{i?c():d();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(Le(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Le(-1)),this.store.dispatch(Ft()),e.preventDefault()):o||(this.store.dispatch(De({collapse:!0})),this.store.dispatch(vl(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:u}=this.state.input,p=u.text.substring(0,u.selection.end),{tabCompletionSuggestion:g}=this.state.input;this.store.dispatch(eo(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&g&&g.text.startsWith(p)&&(this.store.dispatch(ge({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(xe())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(mi()),this.store.dispatch(pe([]))}handlingTimeStart(){this.state.handlingTime.startTime||(E.info("Start handling time"),this.store.dispatch(fd()))}handlingTimeStop(){this.state.handlingTime.startTime&&(E.info("Stop handling time"),this.store.dispatch(On()))}logSendMessage(e){let o=Rd("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)}logHandlingTime(){let e=kd(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(hd())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(xe()),this.store.dispatch($e(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(ge({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){E.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),E.error(i)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=Fn(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{Bn(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]=Fn(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{Bn(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Je(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(()=>{Bn(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),E.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(E.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(hi(n.metrics))):E.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch{}}mount(e,o={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Er(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:d,isEmbedded:u,detectSubmit:p,insertLink:g,inputMediator:f,closestScrollSelector:m,appendOverlayTo:S,inlineSuggestions:w,floatingMenu:v}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:d,showTextSuggestions:i,insertLink:g,isEmbedded:u,inlineSuggestions:w,floatingMenu:!!v}),o.automaticHandlingTime&&this.setupHandlingTime(e),Je(e),this.inputMediator=f||(He(e)?new Pt(e):new Rt(e)),this.inputMediator.on("change",({plainText:x})=>{this.notifyInputChanged(x)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(fi({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",x=>{this.notifyKeyDown(x)}),this.inputMediator.on("paste",({pastedText:x,selectionText:T})=>{this.notifyPaste(x,T)}),this.inputMediator.on("cut",({selectionText:x})=>{this.notifyCut(x)});let y=m&&Pd(e,m)||void 0;if(w){let{customStyles:x,appendOverlayTo:T}=o;if(He(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let L=this.createInlineContainer(e,"deepdesk-caret");Mt($(Ye,{store:this.store,customStyles:x,children:$(Ge,{broadcastEvents:this.broadcastEvents,children:$(kl,{})})}),L),this.inputMediator.on("caret",F=>{this.store.dispatch(pe([])),F?(L.style.display="block",L.style.top=`${F.top}px`,L.style.left=`${F.left}px`):L.style.display="none"});let z=this.overlayContainerFactory("floating-menu",y||e,{appendTo:typeof v=="object"&&"appendOverlayTo"in v?v.appendOverlayTo:T},x==null?void 0:x.floatingMenuRootNode);Mt($(Ye,{store:this.store,customStyles:x,children:$(Ge,{broadcastEvents:this.broadcastEvents,children:$(hl,{onLogIn:()=>this.loginViaPopup().catch(F=>E.warn(F.message))})})}),z)}else{let x=this.overlayContainerFactory("deepdesk-tab-completion",y||e,{appendTo:S,closestScrollElement:y,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),T=this.overlayContainerFactory("deepdesk-suggestions-overlay",y||e,{appendTo:S},n==null?void 0:n.suggestionsRootNode);Mt($(Ye,{store:this.store,customStyles:n,children:$(Ge,{broadcastEvents:this.broadcastEvents,children:$(ac,{inputElement:e})})}),x),Mt($(Ye,{store:this.store,customStyles:n,children:$(Ge,{broadcastEvents:this.broadcastEvents,children:$(Dl,{onLogIn:()=>this.loginViaPopup().catch(L=>E.warn(L.message))})})}),T)}Mt($(Ye,{store:this.store,customStyles:n,children:$(Ge,{broadcastEvents:this.broadcastEvents,children:$(dl,{})})}),this.createContainer("deepdesk-overlays"));let k;this.inputMediator.on("selection",x=>{clearTimeout(k),x===null?k=setTimeout(()=>{x!==null&&this.store.dispatch(es(x))},500):this.store.dispatch(es(x))}),this.inputMediator.on("disabled",()=>{var x;(x=this.inputMediator)==null||x.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{p&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Gs(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Gs(!0))),this.store.dispatch(ai({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(xe()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var x;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((x=this.state.conversation.current)==null?void 0:x.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(o=>o()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,o={}){if(this.widgetRoot&&E.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:n,showImages:s,isEmbedded:r}=o;this.widgetRoot=e,this.configure({showImages:s,isEmbedded:r}),Mt($(Ye,{store:this.store,customStyles:n,children:$(Ge,{broadcastEvents:this.broadcastEvents,children:$(ad,{onLogIn:()=>this.loginViaPopup().catch(i=>E.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&Bn(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=Ar(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Id(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Jt());let e=_e(this.state);e&&(await this.store.dispatch(Qt()),this.store.dispatch(So({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(e){return new Promise((o,n)=>{let s=new MessageChannel,r=s.port1,i=this.state.settings.adminUrl,a=new URL(e!=null&&e.url?e==null?void 0:e.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,c=()=>{d&&!d.closed&&d.close(),window.removeEventListener("message",u),clearInterval(p)};r.onmessage=async g=>{var f,m;if((f=g.data)!=null&&f.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((m=g.data)==null?void 0:m.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Ut),l=!0,s.port1.close(),o()}catch(S){console.error(S),n(S)}finally{l=!0,c()}};let d=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");d===null&&n(new Error("Popup blocked by browser"));let u=async g=>{var f;if(g.origin===a.origin)switch((f=g.data)==null?void 0:f.type){case"deepdesk-popup-loaded":{try{let m=JSON.stringify({type:"deepdesk-popup-create-channel"});d==null||d.postMessage(m,a.origin,[s.port2])}catch(m){E.error("Error posting message to popup",m),n(m)}break}case"deepdesk-popup-error":{c(),g.data.message==="Timeout"&&E.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(g.data.message));break}}};window.addEventListener("message",u);let p=setInterval(()=>{d&&!d.closed||(c(),l||n(new Error("Popup closed by user")))},200);this.unmountHandlers.push(c)})}translateMessages(e){return this.deepdeskApi.translateMessages(e)}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(E.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(o){let{message:n}=o;E.info(n),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let o=Yo(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(ce()):this.store.dispatch(de(n))})}catch(n){this.handleError(n)}}};async function Hv(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 Fv(t,e,o={}){let n=o.replace?ot(t,o.replace.start,o.replace.end):co(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
- `).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?ot(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 Bv(t){let e=document.createElement("template");return e.innerHTML=t.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),e.content}function Kv(t){let e=document.createDocumentFragment();return t.split(`
11
- `).forEach((o,n)=>{n>0&&e.appendChild(document.createElement("br"));let s={index:0},r=0;for(;s=o.slice(r).match(/(\[([^\]]+)])\(([^)]+)\)/);){let i=document.createElement("a");i.href=s[3],i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),i.appendChild(document.createTextNode(s[2])),e.appendChild(document.createTextNode(o.slice(r,r+s.index))),e.appendChild(i),r=r+s.index+s[0].length}e.appendChild(document.createTextNode(o.slice(r)))}),e}function Ud(t,e){return!t.contains(e)||e===t?null:e.parentNode===t?e:Ud(t,e.parentNode)}async function Uv(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?Bv(e):Kv(e);if(o){let d=l.startContainer===t?t.childNodes[l.startOffset]:l.startContainer,u=Ud(t,d)??t.firstChild;t.insertBefore(c,(u==null?void 0:u.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 zv(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function Vv(t,e,o){await new Ke(t).authenticateWithKey(e,o)}async function $v(t){let o=await new he(t).get("/platform/config/",{version:null,useCache:!0});return I(o)}async function qv(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 Gv(t,e){let o=await qv(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,Rt as ContentEditableInput,Ke as DeepdeskAPI,Kn as DeepdeskSDK,he as HTTPClient,Be as InputMediator,at as InputType,Vn as KeyboardHint,$n as Label,vo as Locale,Re as Section,Gn as SectionList,Pe as Sources,O as Suggestion,oe as SuggestionList,Pt as TextAreaInput,it as ToggleButton,Gv as attachFile,Vv as authenticateWithKey,co as createFullRange,Fn as createOverlayContainer,ot as createRangeFromOffsets,Xt as escapeHTML,$v as fetchPlatformConfig,zv as formatTextMarkup,Ln as getRangeOffsets,Mn as getRangeText,Uv as insertCKEditor,ws as isHTML,Er as isSupportedInputElement,Fv as updateContentEditable,Hv as updateTextArea,h as useStyles,Ar as waitForElementVisibilityChange};
7
+ 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 gl}from"react/jsx-runtime";var cf={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},ml=({className:t,color:e})=>gl("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:gl("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:cf[e||"pink"]})});var fl={root:"j",text:"Y",isLoggedIn:"ei",isLoggedOut:"no",icon:"ii",logo:"ri",lock:"ti"};var Gs={};Z(Gs,{enUS:()=>uf,nlNL:()=>pf});var uf={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},pf={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};import{useDispatch as ff}from"react-redux";import{jsx as js,jsxs as hl}from"react/jsx-runtime";var yl=({onLogIn:t})=>{let e=R(Gs),o=b("floatingMenu"),n=b("productName"),s=ff(),r=mf(W),i=h("FloatingMenu",fl);if(r===null||o===!1)return null;let a=()=>{r===!0?s(Y(!0)):t()};return hl("button",{className:gf(i.root,{[i.isLoggedIn]:r,[i.isLoggedOut]:!r}),onClick:a,children:[js("div",{className:i.text,children:e(r?"search":"signin",{productName:n})}),hl("div",{className:i.icon,children:[js(ml,{className:i.logo,color:"pink"}),r===!1&&js(pl,{className:i.lock})]})]})};import{useEffect as Hf,useRef as Ff}from"react";import{connect as Bf,useDispatch as Kf,useSelector as an}from"react-redux";import{useEffect as hf}from"react";function xt(t){hf(()=>{let e=o=>{o.isWithinRoot||t(o)};return document.body.addEventListener("mouseup",e),()=>{document.body.removeEventListener("mouseup",e)}},[t])}function Ze(t){t.addEventListener("mouseup",e=>{e.isWithinRoot=!0},!0)}function bt(t){let{showMidSentenceSuggestions:e,showSuggestionsBeforePattern:o,showSuggestionsAfterPattern:n}=t.settings,{text:s,selection:r}=t.input.userCommitted;return r.start!==r.end?!1:r.end>=s.length?!0:e?o&&new RegExp(o).test(s.substring(r.end))||n&&new RegExp(n).test(s.substring(0,r.end))?!0:o===!1&&n===!1:!1}import{createSlice as yf}from"@reduxjs/toolkit";var vf={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var nn=({ui:t})=>t.overlayCollapsed;var vl=yf({name:"ui",initialState:vf,reducers:{setShowTabHint(t,e){t.showTabHint=e.payload},setInputHasFocus(t,e){t.overlayCollapsedUserOverwrite!==!0&&(e.payload===!0&&(t.overlayCollapsed=!1),t.inputHasFocus=e.payload)},setOverlayCollapsed(t,e){e.payload.collapse===!1&&(t.openOverlayWhenTyping=!1),!(e.payload.skipWhenInputFocus&&t.inputHasFocus)&&(t.overlayCollapsed=e.payload.collapse)},setOpenOverlayWhenTyping(t,e){t.openOverlayWhenTyping=e.payload},setOverlayCollapsedUserOverwrite(t,e){t.overlayCollapsedUserOverwrite=e.payload,t.overlayCollapsed=e.payload}}}),{setShowTabHint:eo,setInputHasFocus:Ws,setOverlayCollapsed:_e,setOpenOverlayWhenTyping:Sl,setOverlayCollapsedUserOverwrite:xl}=vl.actions,bl=vl.reducer;import{Fragment as Nf,useMemo as Of}from"react";import{Interweave as Cf}from"interweave";import{useEffect as wf,useMemo as Tf,useRef as Ef}from"react";import{useDispatch as kf,useSelector as Rf}from"react-redux";import{useEffect as Sf}from"react";function Cl(t,e,o){Sf(()=>{let n=t.current;return n?(n.addEventListener(e,o),()=>{n.removeEventListener(e,o)}):()=>{}},[t,e,o])}var wl={root:"ni",actions:"ai",badge:"pi",formattedText:"ao"};import{jsx as sn,jsxs as Mf}from"react/jsx-runtime";var Pf=["search","personal-collection-search","search-autocomplete"];function If(t,e,o,n={}){let s="";return Pf.includes(e)?s=sa(Ts(t,o,{stripAgentPart:!0}),n.searchKeywords??[o]):s=Ts(t,o,n),n.placeholders===!0&&(s=ra(s)),s}var Lf=()=>{},Af=({index:t,selected:e,suggestion:o,onFeedback:n})=>{let s=b("inlineSuggestions"),r=Rf(pt),i=kf(),a=h("TextSuggestion",wl),l=Ef(null);wf(()=>{let d=setTimeout(()=>{i(mi({text:o.text,suggestion:o}))},500);return()=>{clearTimeout(d)}},[o]),Cl(l,"click",()=>{i(Le(t)),i(pe({suggestion:o,text:o.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let c=Tf(()=>If(o.text,o.source,r,{stripAgentPart:s,placeholders:!0,searchKeywords:o.searchKeywords}),[s,o.text,o.source,r,o.searchKeywords]);return o.source==="gpt"&&!s?null:Mf("div",{className:a.root,onMouseEnter:()=>i(Le(t)),children:[sn(M,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:Lf,children:sn(Cf,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:c})}),e&&n&&sn("div",{className:a.actions,children:sn(Xo,{onFeedback:()=>n(o),suggestion:o.text})})]})},Tl=Af;import{jsx as El}from"react/jsx-runtime";var _f=({onFeedback:t,suggestions:e,selectedIndex:o,reverse:n})=>{let s=Of(()=>{let r=e.map((i,a)=>El(Tl,{index:a,selected:a===o,suggestion:i,onFeedback:t},`${i.text}-${i.source}`));return n?r.reverse():r},[e,o,n]);return El(Nf,{children:s})},rn=_f;var kl={root:"di",paper:"li"};import{jsx as ln}from"react/jsx-runtime";var Uf=({textSuggestions:t,selectedIndex:e})=>{let o=Ff(null),n=h("InlineSuggestionsOverlay",kl),s=an(bt),r=Kf(),i=an(W),a=an(dt),l=an(nn),c=b("showTextSuggestions");return xt(()=>{setTimeout(()=>{r(_e({collapse:!0,skipWhenInputFocus:!0}))})}),Hf(()=>{let d=o.current;if(!d||!d.parentElement)return;d.parentElement.style.left="0px";let u=d.getBoundingClientRect();d.parentElement.style.left=`${Math.min(window.innerWidth-4-u.right,0)}px`}),l||!s||!c||t.length===0||i!==!0||a===!1?null:ln("div",{className:n.root,"data-variant":"inline",children:ln("div",{ref:o,className:n.paper,children:ln(te,{children:ln(rn,{suggestions:t,selectedIndex:e})})})})},zf=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),Rl=Bf(zf)(Uf);import{Provider as Vf}from"react-redux";import{jsx as cn}from"react/jsx-runtime";var $f=({children:t})=>{let o=b("locale").replace("-","");return cn(ys.Provider,{value:o,children:t})},qf=({store:t,customStyles:e={},children:o})=>cn(Vf,{store:t,children:cn($f,{children:cn(_t.Provider,{value:e,children:o})})}),Qe=qf;import Ys from"classnames";import{useEffect as ih,useRef as ah,useState as lh}from"react";import{connect as ch,useDispatch as dh,useSelector as to}from"react-redux";import{useState as Gf}from"react";function Pl(t,e){let[o,n]=Gf(()=>{if(typeof window>"u")return e;try{let r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return T.error(r),e}});return[o,r=>{try{let i=r instanceof Function?r(o):r;n(i),typeof window<"u"&&window.localStorage.setItem(t,JSON.stringify(i))}catch(i){T.error(i)}}]}var Il=()=>/Mac/i.test(navigator.platform);import Zf from"classnames";import{Fragment as Qf,useCallback as Zs,useMemo as Al}from"react";var Xs={};Z(Xs,{enUS:()=>jf,nlNL:()=>Wf});var jf={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Sign in"}]},{type:0,value:" to enable "},{type:1,value:"productName"},{type:0,value:"."}],snooze:[{type:0,value:"Snooze for "},{type:8,value:"min",children:[{type:0,value:"10 minutes"}]},{type:0,value:", "},{type:8,value:"hour",children:[{type:0,value:"1 hour"}]},{type:0,value:" or "},{type:8,value:"day",children:[{type:0,value:"1 day"}]}]},Wf={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Log in"}]},{type:0,value:" bij "},{type:1,value:"productName"},{type:0,value:"."}],snooze:[{type:0,value:"Snooze voor "},{type:8,value:"min",children:[{type:0,value:"10 minuten"}]},{type:0,value:", "},{type:8,value:"hour",children:[{type:0,value:"1 uur"}]},{type:0,value:" of "},{type:8,value:"day",children:[{type:0,value:"1 dag"}]}]};var Ll={root:"si",anchor:"ci",anchorButton:"xi"};import{jsx as dn,jsxs as Ml}from"react/jsx-runtime";var Qs=(t,e,o)=>n=>dn("button",{className:t.anchorButton,type:"button",value:e,onClick:o,children:n},e),Jf=({className:t,loginUrl:e,isEmbedded:o,onSnooze:n,onLogIn:s})=>{let r=R(Xs),i=oe(),a=h("Login",Ll),l=b("productName"),c=Zs(y=>{y.preventDefault(),n&&n(parseInt(y.target.value,10))},[]),d=Zs(y=>{y.preventDefault(),i.send(gt,!0)},[e]),u=Al(()=>y=>dn("a",{onClick:S=>{S.preventDefault(),s()},href:e,className:a.anchor,target:"_blank",rel:"noreferrer",children:y},"login"),[e]),g=Zs(y=>dn("button",{type:"button",className:a.anchorButton,onClick:d,children:y},"prompt"),[d]),{min:p,hour:f,day:m}=Al(()=>({min:Qs(a,60*10,c),hour:Qs(a,60*60,c),day:Qs(a,60*60*12,c)}),[]);return Ml("div",{className:Zf(t,a.root),children:[r("loginPlease",{login:o?g:u,productName:l}),n&&Ml(Qf,{children:[dn("br",{}),r("snooze",{min:p,hour:f,day:m})]})]})},un=Jf;import{useDispatch as eh}from"react-redux";var Nl={root:"po",text:"fi"};import{jsx as Ol,jsxs as oh}from"react/jsx-runtime";var th=({title:t})=>{let e=h("SearchTrigger",Nl),o=eh();return oh("button",{type:"button",className:e.root,onClick:()=>o(Y(!0)),children:[Ol(mt,{}),Ol("span",{className:e.text,children:t})]})},_l=th;var Js={};Z(Js,{enUS:()=>nh,nlNL:()=>sh});var nh={arrowHint:[{type:0,value:"Tip: use arrow keys to navigate suggestions"}],searchHintWindows:[{type:0,value:"Press CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],searchHintMac:[{type:0,value:"Press CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Close"}],search:[{type:0,value:"Search"}]},sh={arrowHint:[{type:0,value:"Tip: Selecteer suggesties met pijltoetsen"}],searchHintWindows:[{type:0,value:"Druk CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],searchHintMac:[{type:0,value:"Druk CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Sluiten"}],search:[{type:0,value:"Zoeken"}]};var Dl={root:"gi",isInline:"q",toggleButton:"bi",toggleButtonWrapper:"C",toggleButtonWrapperHidden:"hi",isCollapsed:"do",collapsible:"mi",hints:"lo",hintsHidden:"ui",triggers:"so",triggersRight:"yi"};import{jsx as V,jsxs as oo}from"react/jsx-runtime";var uh=({textSuggestions:t,selectedIndex:e,onLogIn:o})=>{let n=h("SuggestionsOverlay",Dl),s=R(Js),r=to(bt),i=di(),a=dh(),l=ah(null),c=b("searchTriggerKey"),d=b("productName"),u=to(nn),g=to(W),p=to(dt),[f,m]=lh(null),y=b("showSearch"),E=b("showTextSuggestions"),S=b("adminUrl"),v=b("isEmbedded"),[k,x]=Pl("dd-snooze-until-ms",0),w=u||k>Date.now(),N=to(P=>P.input.text),U=t.filter(P=>P.source!=="gpt").length,F=()=>{w&&x(0),a(xl(!w))},I=P=>{a(G({name:"suggestion feedback",data:{text:P.text,source:"overlay",context:N},options:{includeConversationData:!0}}))},O=P=>{let $=Date.now()+P*1e3;x($),T.info(`Snooze until: ${new Date($)}`),a(_e({collapse:!0}))};return ih(()=>{U===0&&m(null)},[t,U]),xt(()=>{a(_e({collapse:!0,skipWhenInputFocus:!0}))}),g===null||p===!1?null:g===!1?oo("div",{ref:l,className:Ys(n.root,{[n.isCollapsed]:w}),children:[!w&&oo("div",{className:n.triggers,children:[V("div",{style:{flex:1}}),V("div",{className:n.triggersRight,children:V(it,{className:n.toggleButton,title:s("collapse"),onClick:F,isCollapsed:!1})})]}),V("div",{className:n.toggleButtonWrapper,children:V(it,{className:n.toggleButton,title:s("open",{productName:d}),onClick:F,isCollapsed:!0})}),V("div",{className:n.collapsible,children:V(un,{loginUrl:S,isEmbedded:v,onLogIn:o,onSnooze:O})})]}):!i||!r?null:oo("div",{ref:l,className:Ys(n.root,{[n.isCollapsed]:w}),children:[!w&&oo("div",{className:n.triggers,children:[V("div",{style:{flex:1},children:y&&V("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>m(s(Il()?"searchHintMac":"searchHintWindows",{searchTriggerKey:c.toUpperCase()})),onMouseLeave:()=>m(null),children:V(_l,{title:s("search")})})}),oo("div",{className:n.triggersRight,onFocus:()=>{},children:[V("div",{className:Ys(!f&&n.hintsHidden,n.hints),children:f}),V(it,{className:n.toggleButton,title:s("collapse"),onClick:F,isCollapsed:!1})]})]}),V("div",{className:n.toggleButtonWrapper,children:V(it,{className:n.toggleButton,title:s("open",{productName:d}),onClick:F,isCollapsed:!0})}),U>0&&E&&V("div",{className:n.collapsible,onFocus:()=>{},children:V(te,{children:V(rn,{onFeedback:I,suggestions:t,selectedIndex:e,reverse:!0})})})]})},ph=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),Hl=ch(ph)(uh);import dr from"classnames";import{Interweave as gy}from"interweave";import{useCallback as my,useEffect as fy,useMemo as ac,useRef as hy}from"react";import{connect as yy}from"react-redux";import{useEffect as gh,useRef as mh,useState as fh}from"react";function pn(t){return t.contentEditable==="true"}function hh(t){let e=0,o=0,n=window.getSelection();if(n.rangeCount!==0){let s=n.getRangeAt(0),r=s.cloneRange();r.selectNodeContents(t),r.setEnd(s.endContainer,s.endOffset),o=r.toString().length,r.selectNodeContents(t),r.setEnd(s.startContainer,s.startOffset),e=r.toString().length}return{selectionStart:e,selectionEnd:o}}function Fl(t){let{selectionStart:e,selectionEnd:o}=pn(t)?hh(t):t;return[e,o]}function Bl(t){let[,e]=fh(),o=mh(null);return o.current=Fl(t),gh(()=>{let n=()=>{let[s,r]=o.current??[],i=Fl(t);(!i||s!==i[0]||r!==i[1])&&(o.current=i,e({}))};return t.addEventListener("keyup",n),t.addEventListener("click",n),t.addEventListener("focus",n),document.addEventListener("selectionchange",n),()=>{t.removeEventListener("keyup",n),t.removeEventListener("click",n),t.removeEventListener("focus",n),document.removeEventListener("selectionchange",n)}},[t]),o.current}function Kl(t,e){if(!e)return;let o=t,{value:n}=o,[s,r]=e,i=n.match(yo);if(!i||i.length===0)return;let a=0;i.find(l=>{let c=n.indexOf(l,a);return s>c&&r<c+l.length?(o.selectionStart=c,o.selectionEnd=c+l.length,!0):(a=c+l.length,!1)})}import{cloneElement as yh}from"react";var vh=["div","span","mark","strong","b","i","u","em"];function er(t,e,o=0){var r;let n=t[t.length-1],s=typeof n=="object"&&n!==null?(r=n.props)==null?void 0:r.tagName:void 0;if(s==="br")return t.pop(),[...t,...e,n];if(vh.includes(s)){let i=Array.isArray(n.props.children)?n.props.children:[n.props.children];return[...t.slice(0,t.length-1),yh(n,{children:er(i,e,o+1)})]}return[...t,...e]}function De(t){return t.tagName.toLowerCase()==="textarea"}var ce={root:"wi",container:"vi",agentText:"co",tabText:"xo",hint:"S",matchSelection:"fo",focus:"ki",resetIndent:"zi",matchKeyword:"p",matchPlaceholder:"d",hover:"go",hintText:"ji",popover:"Yi",popoverRoot:"qi",popoverContentContainer:"bo",popoverContent:"Ci",selectionOptions:"Si",selectionOptionsIsHidden:"Ei",selectionOptionsButton:"Gi",caret:"Ni",popoverSuggestionsRoot:"Ai",suggestionsOverlayInputStyles:"Fi"};import Uh from"classnames";import{Matcher as zh}from"interweave";import{useEffect as Vh,useMemo as $h}from"react";import{useEffect as xh,useRef as bh,useState as Ch}from"react";function Ul(t,e){let o;return[(...n)=>{window.cancelAnimationFrame(o);let s=e?e(...n):n;o=window.requestAnimationFrame(()=>{t(...s)})},()=>window.cancelAnimationFrame(o)]}function gn(t){let e=bh(null),[o,n]=Ch(!1);return xh(()=>{let s=!1,r=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[i,a]=Ul((d,u)=>{let g=e.current;if(!g)return;let p=d/r,f=u/r,m=g.getBoundingClientRect(),y=p>m.x&&p<m.x+m.width&&f>m.y&&f<m.y+m.height;y&&!s?(s=!0,n(!0)):!y&&s&&(s=!1,n(!1))},({clientX:d,clientY:u})=>[d,u]),[l,c]=Ul(()=>{s=!1,n(!1)});return t.addEventListener("mousemove",i),t.addEventListener("mouseleave",l),()=>{a(),c(),t.removeEventListener("mousemove",i),t.removeEventListener("mouseleave",l)}},[e]),[e,o]}function zl(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function mn(t){return e=>{t.forEach(o=>{typeof o=="function"?o(e):o!=null&&(o.current=e)})}}function Vl(t){return t!=null}import Wl from"classnames";import{createRef as Oh,useCallback as or,useMemo as _h,useRef as Dh,useState as Hh}from"react";import{useState as wh,useLayoutEffect as Th}from"react";var Eh=["bottom","height","left","right","top","width"],kh=(t={},e={})=>Eh.some(o=>t[o]!==e[o]),Ce=new Map,$l,ql=()=>{let t=[],e=[];Ce.forEach((o,n)=>{if(n instanceof Element&&!n.isConnected){e.push(n);return}let s=n.getBoundingClientRect();kh(s,o.rect)&&(o.rect=s,t.push(o))}),e.forEach(o=>{Ce.delete(o)}),t.forEach(o=>{o.callbacks.forEach(n=>n(o.rect))}),$l=window.requestAnimationFrame(ql)};function Rh(t,e){return{observe(){let o=Ce.size===0;if(Ce.has(t)){let n=Ce.get(t);n.callbacks.push(e),n.rect&&e(n.rect)}else Ce.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});o&&ql()},unobserve(){let o=Ce.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||Ce.delete(t),Ce.size||cancelAnimationFrame($l)}}}}function tr(t){let[e,o]=wh(null);return Th(()=>{if(!t.current)return;let n=Rh(t.current,s=>{o(s)});return n.observe(),()=>{n.unobserve()}},[t]),e}import{useContext as Ih,useLayoutEffect as Lh,useState as Ah}from"react";import{createPortal as Mh}from"react-dom";var Gl={root:"Hi"};var jl=({children:t,parentNode:e})=>{let[o,n]=Ah(null),s=Ih(_t);return Lh(()=>{let r=document.createElement("div");return Ze(r),r.classList.add(Gl.root),s!=null&&s.portalRootNode&&r.classList.add(s==null?void 0:s.portalRootNode),(e||document.body).appendChild(r),n(r),()=>{r.isConnected&&r.remove()}},[]),o?Mh(t,o):null};var ge={ref:"Li",root:"o",positionAbove:"l",positionBelow:"s",positionLeft:"c",positionRight:"x",alignStart:"f",alignCenter:"g",alignEnd:"b"};import{jsx as nr}from"react/jsx-runtime";var fn=(t=!1)=>{let[e,o]=Hh(t),n=or(()=>o(!0),[]),s=or(()=>o(!1),[]),r=or(()=>o(a=>!a),[]),i=Dh(null);return{opened:e,open:n,close:s,toggle:r,triggerRef:i}};function sr(t,e=null,o=0){if(!t)return{display:"none"};let n=e?t.top-e.top<0||t.top<e.top-o?e.top-o:t.top+t.height>e.top+e.height+o?e.top+e.height+o-t.height:t.top:t.top,s=e?t.left<e.left-o?e.left-o:t.left+t.width>e.left+e.width+o?e.left+e.width+o-t.width:t.left:t.left;return{top:n,left:s,height:t.height,width:t.width}}var Ct=({className:t,triggerRef:e,boundaryRef:o=Oh(),position:n="above",align:s="center",children:r,toStyle:i=sr,parentNode:a,...l})=>{let c=tr(e),d=tr(o),u=_h(()=>i(c,d,0),[c,d]);return nr(jl,{parentNode:a,children:nr("div",{className:Wl(ge.ref,{[ge.positionAbove]:n==="above",[ge.positionBelow]:n==="below",[ge.positionLeft]:n==="left",[ge.positionRight]:n==="right",[ge.alignStart]:s==="start",[ge.alignCenter]:s==="center",[ge.alignEnd]:s==="end"}),style:u,...l,role:"dialog",children:nr("div",{className:Wl(t,ge.root),children:r})})})};import Fh from"classnames";import{forwardRef as Bh,useRef as Kh}from"react";import{jsx as Xl}from"react/jsx-runtime";var hn=Bh(({className:t,children:e,...o},n)=>{let s=Kh(null),r=h("TabCompletion",ce);return Xl("div",{ref:mn([s,n]),className:Fh(t,r.popoverContentContainer),...o,children:Xl("div",{className:r.popoverContent,children:e})})});import{jsx as no,jsxs as jh}from"react/jsx-runtime";var qh=t=>e=>{let o=sr(e);return"top"in o&&(o.width=t.width-(e.left-t.left)-10),o},Gh=({inputElement:t,boundaryRef:e,inputStyle:o,children:n,suggestion:s})=>{let r=h("TabCompletion",ce),i=fn(),a=$h(()=>qh(t.getBoundingClientRect()),[t]),[l,c]=gn(t);return Vh(()=>{c?i.open():i.close()},[c]),jh("span",{children:[no("mark",{ref:mn([l,i.triggerRef]),className:Uh(r.matchKeyword,{[r.hover]:c}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:n}),i.opened&&no(Ct,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:no(hn,{style:o,children:no("div",{className:r.hintText,children:s})})})]})},yn=class extends zh{keywordMatches=[];preparedKeywordMatches=[];usedKeywordMatches=new Set;onBeforeParse(e,o){return o.keywordMatches&&o.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=o.keywordMatches.map(n=>({...n,keywordRegex:new RegExp(`\\b${zl(n.keyword)}\\b`,"i")})),this.keywordMatches=o.keywordMatches),this.usedKeywordMatches.clear(),e}match(e){let o=this.preparedKeywordMatches.map(s=>{if(this.usedKeywordMatches.has(s))return null;let r=e.match(s.keywordRegex);if(!r)return null;let i=e.charAt(r.index-1),a=e.charAt(r.index+s.keyword.length);return i==="{"&&a==="}"?null:{index:r.index,length:r[0].length,match:r[0],matchString:r[0],suggestion:s.suggestion,preparedKeywordMatch:s,valid:!0}}).filter(Vl);if(o.length===0)return null;let n=o.reduce((s,r)=>r.index<s.index?r:s);return this.usedKeywordMatches.add(n.preparedKeywordMatch),n}replaceWith(e,o){return no(Gh,{inputElement:o.inputElement,suggestion:o.suggestion,inputStyle:o.inputStyle,boundaryRef:o.boundaryRef,children:e},`keyword_${o.matchString}_${o.key}`)}asTag(){return"mark"}};import{Matcher as Wh}from"interweave";import Xh from"classnames";import{jsx as Zl}from"react/jsx-runtime";var Zh=({inputElement:t,children:e})=>{let o=h("TabCompletion",ce),[n,s]=gn(t);return Zl("mark",{ref:n,className:Xh(o.matchPlaceholder,{[o.hover]:s}),children:e})},vn=class extends Wh{match(e){let o=e.match(/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\}(?!\}))/);return o?{index:o.index,length:o[0].length,match:o[0],matchString:o[0],valid:!0}:null}replaceWith(e,o){return Zl(Zh,{inputElement:o.inputElement,children:e},`placeholder_${o.matchString}_${o.key}`)}asTag(){return"mark"}};import cr from"classnames";import{Matcher as iy}from"interweave";import{createRef as ay,forwardRef as ly,useCallback as cy,useEffect as sc,useRef as rc,useState as ic}from"react";import{useDispatch as dy}from"react-redux";import{jsx as Ql}from"react/jsx-runtime";var Jl=()=>Ql("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:Ql("path",{fill:"currentColor",d:"M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"})});import{useCallback as Jh,useEffect as ec,useState as tc}from"react";import{useDispatch as Yh,useSelector as oc}from"react-redux";import ey from"lodash.debounce";var Yl={root:"Mi",content:"Ri"};function Sn(t,e,o){var s;let n=((s=t.imageSizes)==null?void 0:s[e])||t.image||o;if(!n)return null;try{return new URL(n).toString()}catch{return null}}function rr(t){return t.replace("https://www.","").replace("https://","")}import{jsx as Je,jsxs as ir}from"react/jsx-runtime";var ty=3,oy=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),ny=({onSelectLink:t,onDismiss:e,placeholder:o,visitUrlText:n,linkCount:s=ty})=>{let r=h("LinkSearch",Yl),[i,a]=tc(""),l=Yh(),c=oc(tl("url")),d=oc(Ai("URL",oy)),[u,g]=tc(d.length-1),p=b("fallbackImage"),f=S=>{let v=S.target;a(v.value)},m=(S,v)=>{S.stopPropagation(),S.preventDefault(),window.open(v,"_blank")},y=S=>{var x;let v=u-1<0?d.length-1:u-1,k=u+1===d.length?0:u+1;S.code==="Escape"&&(a(""),e()),S.code==="ArrowUp"&&g(v),S.code==="ArrowDown"&&g(k),S.code==="Enter"&&t(((x=d[u])==null?void 0:x.text)||i)},E=Jh(ey(S=>{l(Ve({query:S,type:"URL",tags:["link-search"]}))},300),[]);return ec(()=>{i&&E(i)},[i]),ec(()=>()=>{l(Mo())},[]),ir("div",{className:r.root,children:[Je(te,{withDivider:!0,children:(i?d:c).slice(0,s).map((S,v)=>Je(M,{selected:u===v,onClick:()=>t(S.text),"data-testid":"linksearch-suggestion",children:ir(H,{children:[Je(H.Image,{src:Sn(S,"small",p||void 0),title:S.title||S.text}),ir(H.Content,{className:r.content,cropText:!0,children:[Je(H.Title,{children:S.title||rr(S.text)}),S.title&&rr(S.text)]}),Je(M.Actions,{children:Je(M.ActionButton,{label:n,onClick:k=>m(k,S.text)})})]})},S.text))}),Je(Gt,{value:i,onChange:f,autoFocus:!0,placeholder:o,onKeyUp:y})]})},nc=ny;var ar={};Z(ar,{enUS:()=>sy,nlNL:()=>ry});var sy={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},ry={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};import{jsx as me,jsxs as lr}from"react/jsx-runtime";var uy=ly((t,e)=>{let o=h("TabCompletion",ce);return me("mark",{ref:e,className:cr(o.matchSelection)},"selection-start")}),py=({startRef:t,boundaryRef:e,inputStyle:o,inputElement:n,children:s})=>{let r=R(ar),i=h("TabCompletion",ce),a=rc(null),l=rc(null),[c,d]=ic(null),u=dy(),g=fn(document.activeElement===n),[p]=ic(()=>document.createRange());g.triggerRef.current=p,sc(()=>()=>p.detach(),[]),sc(()=>{let m=t.current,y=a.current;!m||!y||(p.setStart(m,0),p.setEnd(y,0))},[t.current,a.current]),xt(()=>{g.close()});let f=cy(m=>{let y=p.toString(),E=/^http(s?):\/\//.test(m)?m:`https://${m}`;u(Ro({text:`[${y}](${E})`,replace:"selection"}))},[]);return lr("span",{children:[me("mark",{ref:a,className:cr(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":g.opened?"true":"false",children:s}),g.opened&&me(Ct,{className:i.popoverRoot,triggerRef:g.triggerRef,boundaryRef:e,position:"above",align:"start",children:lr(hn,{style:o,ref:l,children:[me("div",{className:cr(i.selectionOptions,{[i.selectionOptionsIsHidden]:c!==null}),children:lr("button",{type:"button",tabIndex:c===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>d("insertLink"),children:[me(Jl,{}),me("span",{children:"\xA0"}),me("span",{children:r("insertLink")})]})}),c==="insertLink"&&me(nc,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:f,onDismiss:()=>{d(null),g.close()}})]})})]},"selection-end")},xn=class extends iy{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(e,o){return this.props=o,this.charCount=0,this.startRef=ay(),this.foundIndex=0,e}match(e){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[o,n]=this.props.selection;if(o===n)return null;let s=this.foundIndex===0?o:n,r=s>=this.charCount&&s<=this.charCount+e.length?{index:s-this.charCount,length:0,match:"",valid:!0}:null;r&&this.foundIndex++;let i=this.foundIndex===1;return r&&i?this.charCount+=s-this.charCount:this.charCount+=e.length,r?{isStart:i,...r}:null}replaceWith(e,o){return o.isStart?me(uy,{ref:this.startRef}):me(py,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};import{useSelector as vy}from"react-redux";import{jsx as wt,jsxs as by}from"react/jsx-runtime";var Sy=({enabled:t,content:e,tabText:o,showTabHint:n,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:l})=>{let c=h("TabCompletion",ce),d=b("insertLink"),u=b("showMidSentenceSuggestions"),g=b("inlineSuggestions"),p=Bl(a),f=hy(null),m=vy(W);fy(()=>{De(a)&&p&&Kl(a,p)},[p]);let y=my(v=>{if(!s||!o)return v;let k=[wt("span",{className:c.resetIndent,children:"\u200B"},"u200B"),wt("span",{"data-testid":"tab-completion",className:dr(c.tabText,c.resetIndent),"data-source":l,children:o},"tabText")];return n&&k.push(wt("span",{className:dr(c.hint,c.resetIndent),children:wt(qn,{keyCode:"tab"},"tabHint")})),er(v,k)},[s,o,n]),E=ac(()=>{let v=[];return d&&v.push(new xn("selection")),v.push(new vn("placeholders")),r&&v.push(new yn("keywords")),v},[g,d,r]),S=ac(()=>{let v=window.getComputedStyle(a);return{"--dd-color":v.color,"--dd-font-size":v.fontSize,"--dd-font-family":v.fontFamily,"--dd-font-variant":v.fontVariant}},[]);return!t||!m?null:by("div",{ref:v=>{v!=null&&v.parentElement&&(f.current=v==null?void 0:v.parentElement)},className:c.root,style:S,children:[wt(gy,{tagName:"span",containerTagName:"div",className:dr(c.container,c.agentText),disableLineBreaks:De(a),content:e||"\u200B",onAfterParse:y,matchers:E,selection:p,keywordMatches:i,inputElement:a,inputStyle:S,boundaryRef:f,inlineSuggestionsOnlyAtEnd:!u}),wt("br",{})]})},xy=({input:t,ui:e,settings:o,styleSuggestions:n,conversation:s})=>{var m;let{tabCompletionSuggestion:r}=t,i=(r==null?void 0:r.text)||"",a=(r==null?void 0:r.source)||"",l=t.html??Xt(t.text),c=i.indexOf(t.text)===0?i.slice(t.text.length):"",{showTabHint:d}=e,{isSupported:u}=s,{showTabCompletion:g,visible:p,showStyleSuggestions:f}=o;return{showTabHint:d,showStyleSuggestions:f,showTabCompletion:g,content:l,tabText:c,source:a,keywordMatches:((m=n.list)==null?void 0:m.keywordMatches)??[],enabled:p&&u!==!1}},lc=yy(xy)(Sy);import Mv from"classnames";import{useEffect as Nv}from"react";import{useDispatch as Ov,useSelector as X}from"react-redux";import{createAsyncThunk as so,createSlice as Cy}from"@reduxjs/toolkit";var cc={list:[],fetchState:"idle",isInitialRequest:null},uc=t=>t.autoflows.list||[],dc=t=>e=>{var o;return(o=e.list)==null?void 0:o.find(n=>n.triggerPayload===t)},we=so("autoflows/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getAutoflows(t)}),ur=so("autoflows/start",async(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");await n.startAutoflowSession(t),await o(we(t.platformSessionId))}),pr=so("autoflows/stop",async(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");await n.stopAutoflowSession(t.platformSessionId),await o(we(t.platformSessionId))}),wy=Cy({name:"autoflows",initialState:cc,reducers:{},extraReducers:t=>{t.addCase(ur.pending,(e,o)=>{let n=dc(o.meta.arg.triggerPayload)(e);n.state="Started",n.isBusy=!0}),t.addCase(pr.pending,(e,o)=>{let n=dc(o.meta.arg.triggerPayload)(e);n.state="Aborted",n.isBusy=!0}),t.addCase(we.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}),t.addCase(we.rejected,e=>{e.fetchState="error"}),t.addCase(we.fulfilled,(e,o)=>{e.list=o.payload,e.fetchState="done"}),t.addCase(_,()=>cc)}}),pc=so("autoflows/openStream",(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");let s=n.openStream(t);s.on("sessionAborted",()=>{o(we(t))}),s.on("sessionCompleted",()=>{o(we(t))})}),gc=so("autoflows/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),mc=wy.reducer;import{createAsyncThunk as io,createSlice as Ty}from"@reduxjs/toolkit";var fc={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},hc=t=>t.customMessages.list,yc=t=>e=>!!e.customMessages.sentSuggestions.find(o=>o===t),vc=t=>e=>!!e.customMessages.answeredSuggestions.find(o=>o===t),Sc=t=>e=>!!e.customMessages.errorSuggestions.find(o=>o===t),ro=io("customMessages/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getCustomMessages(t)}),bn=io("customMessages/send",async(t,e)=>{let{platformSessionId:o,suggestion:n}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.sendCustomMessage(o,n)}),Cn=io("customMessages/answer",async(t,e)=>{let{platformSessionId:o,reply:n}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.answerCustomMessage(o,n)}),xc=Ty({name:"customMessages",initialState:fc,reducers:{onCustomMessage(t,e){Array.isArray(e.payload)?t.list=e.payload:t.list=[e.payload]}},extraReducers:t=>{t.addCase(ro.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(ro.rejected,e=>{e.fetchState="error"}).addCase(ro.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload||[]}).addCase(bn.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.errorSuggestions=e.errorSuggestions.filter(n=>o.meta.arg.suggestion.text!==n)}).addCase(bn.rejected,(e,o)=>{let n=e.sentSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1))}).addCase(Cn.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.answeredSuggestions.push(o.meta.arg.suggestion.text)}).addCase(Cn.rejected,(e,o)=>{let n=e.answeredSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1)),e.answeredSuggestions.splice(n,1)}).addCase(_,()=>fc)}}),bc=io("customMessages/openStream",(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.openStream(t).on("customMessageSuggestion",r=>{o(xc.actions.onCustomMessage(r))})}),Cc=io("customMessages/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),wc=xc.reducer;import{createAsyncThunk as Tc,createSlice as Ey}from"@reduxjs/toolkit";var ky={token:null,accountUrl:null,interval:null},Ec=t=>e=>{let{passwordlessToken:{token:o,accountUrl:n}}=e;return o&&n?`${n}/apis/admin/session/passwordless/login/?token=${o}&redirect=${t}`:null},gr=Tc("passwordlessToken/getTemporaryPasswordlessToken",async(t,e)=>{let{deepdeskAPI:o}=e.extra,n=await o.requestPasswordlessToken();return{accountUrl:o.client.baseUrl,token:n}}),mr=Tc("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:o=1e3*60*10}=t,{dispatch:n}=e;return n(gr()),setInterval(()=>n(gr()),o)}),kc=Ey({name:"passwordlessToken",initialState:ky,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(gr.fulfilled,(e,o)=>{e.token=o.payload.token,e.accountUrl=o.payload.accountUrl}),t.addCase(mr.fulfilled,(e,o)=>{e.interval=o.payload})}}),{stopPollPasswordlessToken:Rc}=kc.actions,Pc=kc.reducer;import{createAction as Ry,createAsyncThunk as Py,createSlice as Iy}from"@reduxjs/toolkit";var fr={cues:[],fetchState:"idle"},Ic=t=>{var e;return(e=t.rules)==null?void 0:e.cues},Ly=Ry("rules/resetCues"),Ye=Py("rules/evaluate",async(t,e)=>{var a;let{deepdeskAPI:o}=e.extra,n=(a=e.getState().conversation.current)==null?void 0:a.id;if(!n)throw new Error("No current conversation to evaluate rules");if(!(await o.getAccount()).ruleEngine)throw new Error("Rule engine is not enabled for this account");if(!(await o.getRules()).some(l=>l.label===t.label))throw new Error(`No rules found with label: ${t.label}`);return await o.evaluateRule(t.label,n,t.params)}),Lc=Iy({name:"answer",initialState:fr,reducers:{removeCue(t,e){t.cues=t.cues.filter(o=>o.rule.id!==e.payload.id)}},extraReducers:t=>{t.addCase(Ye.pending,e=>{e.fetchState="loading"}).addCase(Ye.rejected,e=>{e.fetchState="error"}).addCase(Ye.fulfilled,(e,o)=>{let n=o.payload.map(r=>r.rule.id),s=e.cues.filter(r=>!n.includes(r.rule.id));e.fetchState="done",e.cues=[...o.payload,...s]}).addCase(_,()=>fr).addCase(Ly.toString(),()=>fr)}}),{removeCue:Ac}=Lc.actions,Mc=Lc.reducer;function Nc(t){let{customMessages:e,autoflows:o}=t;return o.fetchState==="loading"&&o.isInitialRequest===!0||e.fetchState==="loading"&&e.isInitialRequest===!0}import{Fragment as zy}from"react";import{connect as Vy}from"react-redux";import By from"classnames";import{Fragment as Ky}from"react";import My from"classnames";var Oc={root:"Ti"};import{jsx as Oy}from"react/jsx-runtime";var Ny=({className:t,children:e})=>{let o=h("Unicode",Oc);return Oy("span",{className:My(t,o.root),children:e})},_c=Ny;var Dc={isDisabled:"Ui",buttonStart:"Bi",root:"Di",buttonStop:"ho",stateBadge:"h",isCompleted:"Ii",isStarted:"Oi",isAborted:"Xi"};var hr={};Z(hr,{enUS:()=>Dy,nlNL:()=>Hy});var Dy={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]},Hy={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]};import{jsx as et,jsxs as wn}from"react/jsx-runtime";var Uy=({disabled:t,state:e,displayName:o,description:n,onStartAutoflow:s,onStopAutoflow:r})=>{let i=h("Autoflow",Dc),a=R(hr),l=e==="Started"?"stop":"start",c=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return wn(M,{className:By(i.root,{[i.isDisabled]:t,[i.isCompleted]:e==="Completed",[i.isAborted]:e==="Aborted",[i.isStarted]:e==="Started"}),children:[et(H,{children:wn(H.Content,{children:[wn(H.Title,{children:[e&&et("span",{className:i.stateBadge,children:a(e)}),o]}),et("span",{children:n})]})}),et(M.Actions,{fixed:e==="Started",children:et(M.ActionButton,{primary:!0,className:l==="start"?i.buttonStart:i.buttonStop,onClick:e==="Started"?r:s,disabled:t,label:wn(Ky,{children:[et(_c,{children:c})," ",et("span",{children:a(l)})]})})})]})},Hc=Uy;import{jsx as Fc}from"react/jsx-runtime";var $y=(t,e)=>{let o=e.filter(n=>n.state==="Started");return o.length>0?o.indexOf(t)===-1:!1},qy=({autoflows:t,onStartAutoflow:e,onStopAutoflow:o,platformSessionId:n})=>Fc(zy,{children:t.map(s=>Fc(Hc,{displayName:s.displayName,description:s.description,disabled:s.isBusy||$y(s,t),state:s.state,onStartAutoflow:()=>e({platformSessionId:n,triggerPayload:s.triggerPayload}),onStopAutoflow:()=>o({platformSessionId:n,triggerPayload:s.triggerPayload})},s.displayName))}),Gy=({autoflows:t,conversation:e})=>{var o;return{autoflows:t.list,platformSessionId:(o=e.current)==null?void 0:o.sessionId}},jy={onStartAutoflow:ur,onStopAutoflow:pr},Bc=Vy(Gy,jy)(qy);import Xy from"classnames";import{useCallback as Kc}from"react";import{useDispatch as Zy,useSelector as Tn}from"react-redux";var Te={root:"mo",title:"uo",isUsed:"Ji",quickReplies:"Ki",quickReply:"Pi",hasError:"Qi",label:"Vi",errorIcon:"Wi"};import{jsx as He,jsxs as En}from"react/jsx-runtime";var Qy=({suggestion:t})=>{let e=R(We),o=Zy(),n=Tn(yc(t.text)),s=Tn(vc(t.text)),r=Tn(Sc(t.text)),i=Tn(xo),{replyOptions:a}=t,l=Kc(d=>{d.preventDefault(),d.stopPropagation(),!(n||!i)&&o(bn({platformSessionId:i,suggestion:t}))},[t,n,o,i]),c=Kc(d=>{if(d.preventDefault(),d.stopPropagation(),!i||!a)return;let u=parseInt(d.target.dataset.index,10),g=a[u];o(Cn({platformSessionId:i,reply:g,suggestion:t}))},[t,n,o,i]);return En(M,{onClick:l,className:Xy(Te.root,{[Te.isUsed]:n,[Te.hasError]:r}),children:[He(H,{children:En(H.Content,{children:[En(H.Title,{className:Te.title,children:[t.text," ",He(Gn,{className:Te.label,children:"analyse tool"})," ",r&&He("span",{className:Te.errorIcon,role:"img","aria-label":e("sendingError"),title:e("sendingError"),children:"!"})]}),a&&a.length>0&&He("ul",{className:Te.quickReplies,children:a.map(d=>He("li",{className:Te.quickReply,children:d.title},d.title))})]})}),En(M.Actions,{fixed:r||n,children:[a&&a.length>0&&He(M.DropdownButton,{label:e("answer"),disabled:s,children:a.map((d,u)=>He(M.DropdownItem,{index:u,label:d.title,onClick:c},d.title))}),He(M.ActionButton,{primary:!0,disabled:n,onClick:l,label:e(n?"suggestionSent":r?"tryAgain":"sendSuggestion")})]})]})},Uc=Qy;import{useEffect as Yy,useState as ev}from"react";import{useDispatch as tv}from"react-redux";import $c from"classnames";import{jsx as zc}from"react/jsx-runtime";var yr=()=>zc("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:zc("path",{d:"M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"})});var Vc={root:"Zi",entity:"r",entityText:"_i",iconWrapper:"or",icon:"er",iconClicked:"ir"};import{jsx as Tt,jsxs as qc}from"react/jsx-runtime";var ov=({entities:t})=>{let e=h("EntitiesWidgetList",Vc),[o,n]=ev(void 0),s=tv(),r=()=>{n(void 0)},i=a=>{t&&(n(t.indexOf(a)),Ge(a.text),s(G({name:"entity copied",data:{entity:a,type:"copy"}})))};return Yy(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[o]),!t||t.length===0?null:Tt("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,l)=>qc("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[Tt("span",{className:e.entityText,children:a.text}),qc("span",{className:e.iconWrapper,children:[Tt("span",{className:$c(e.icon),children:Tt(yr,{})}),Tt("span",{className:$c(e.icon,o===l&&e.iconClicked),children:Tt(yr,{})})]})]},a.text))})},Gc=ov;import{jsx as jc}from"react/jsx-runtime";var Wc=()=>jc("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:jc("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});import{jsx as Xc}from"react/jsx-runtime";var Zc=()=>Xc("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:Xc("path",{d:"M543-340q16.595 0 28.798-12.202Q584-364.405 584-381t-12.202-28.798Q559.595-422 543-422t-28.798 12.202Q502-397.595 502-381t12.202 28.798Q526.405-340 543-340Zm-25-126h47q2-29 8.5-43t32.5-39q27-26 37.5-45.395Q654-612.79 654-639q0-45.882-31.5-74.941Q591-743 540-743q-38 0-68 20.5T428-665l45 19q11-25 27.5-38t39.5-13q29.778 0 48.389 17Q607-663 607-637q0 20-9 35t-32 32q-32 29-40 46.5t-8 57.5ZM260-200q-24 0-42-18t-18-42v-560q0-24 18-42t42-18h560q24 0 42 18t18 42v560q0 24-18 42t-42 18H260Zm0-60h560v-560H260v560ZM140-80q-24 0-42-18t-18-42v-620h60v620h620v60H140Zm120-740v560-560Z"})});import{jsx as Qc}from"react/jsx-runtime";var Jc=()=>Qc("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:Qc("path",{d:"M319-250h322v-60H319v60Zm0-170h322v-60H319v60ZM220-80q-24 0-42-18t-18-42v-680q0-24 18-42t42-18h361l219 219v521q0 24-18 42t-42 18H220Zm331-554v-186H220v680h520v-494H551ZM220-820v186-186 680-680Z"})});import{useDispatch as bv}from"react-redux";import{useDispatch as sv}from"react-redux";import{createAsyncThunk as nv}from"@reduxjs/toolkit";function Yc(t){return nv("analytics/logEvent",(e,o)=>{var r,i,a;let n=(i=(r=o.getState())==null?void 0:r.conversation.current)==null?void 0:i.id,s=(a=o.getState())==null?void 0:a.info.agentInfo;return o.extra.deepdeskAPI.sendEvent(e.name,{conversationId:n,...s,data:e.data})})(t)}function kn(){let t=sv();return async(e,o)=>{await t(Yc({name:e,data:o}))}}import dd from"classnames";import{useEffect as vv,useState as Sv}from"react";import{jsx as ed,jsxs as rv}from"react/jsx-runtime";var td=({className:t})=>rv("svg",{viewBox:"0 0 12 12",version:"1.1",xmlns:"http://www.w3.org/2000/svg",className:t,children:[ed("line",{x1:"2",y1:"10",x2:"10",y2:"2",stroke:"black",strokeWidth:"1"}),ed("line",{x1:"2",y1:"2",x2:"10",y2:"10",stroke:"black",strokeWidth:"1"})]});import{jsx as od}from"react/jsx-runtime";var nd=t=>od("svg",{width:"16",height:"16",fill:"#000000",...t,viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:od("path",{fillRule:"evenodd",d:"M6.57086468,14.9173453 C6.38997052,14.9711236 6.19835748,15 6,15 L4,15 C2.8954305,15 2,14.1045695 2,13 L2,4 C2,2.8954305 2.8954305,2 4,2 L6,2 C6.68685475,2 7.29284112,2.34623869 7.65294381,2.87370078 C7.95642355,2.67736738 8.29504785,2.51351337 8.66312366,2.3818197 C9.50544052,2.08044754 10.3408482,1.9879107 10.9989281,1.99971266 C11.0150698,2.00005426 13.3487605,2.00015005 18,2 C20.7551411,2 22,6.05643086 22,12 C22,13.6824804 20.8695981,15 19,15 L15.9269768,15 C15.9359266,15.0245465 15.9451954,15.0497804 15.9547911,15.0757271 C16.007193,15.2174219 16.2391583,15.8256341 16.2970775,15.9810953 C16.4872151,16.4914441 16.6259612,16.9026411 16.7382242,17.3098712 C16.9079007,17.9253665 17,18.4798886 17,19 C17,20.4720069 16.091867,21.3862822 14.748281,21.777514 C14.1422801,21.9539723 13.6147967,22.0000922 13.0076976,22.0000008 L12.5204954,22 L12.2202699,21.6261158 C11.2556275,20.4248034 7.64562469,16.4822788 6.57086468,14.9173453 Z M8,13 C8,13.2401953 8.04443154,13.4528921 8.14171093,13.6800176 C8.40663864,14.2985643 11.914268,18.1371493 13.4599624,19.9848695 C13.7113931,19.9660111 13.9483736,19.9273712 14.1891338,19.8572655 C14.7621788,19.6904035 15,19.4509737 15,19 C15,18.6834183 14.9359344,18.2976852 14.8101464,17.8413935 C14.7161494,17.500423 14.5944107,17.1396301 14.4229225,16.6793379 C14.3689242,16.5344009 14.1358033,15.923159 14.0789589,15.7694517 C13.9489218,15.4178313 13.8632547,15.1589343 13.8046536,14.9236885 C13.5555377,13.9236468 13.8054549,13 15,13 L19,13 C19.6912225,13 20,12.6401099 20,12 C20,7.20925475 19.015127,4 18,4 C15.9322103,4 15.9322103,4 10.9655994,3.99940813 C10.5253746,3.99154158 9.91062406,4.05963657 9.33687634,4.2649175 C8.45196659,4.58152894 8,5.09776992 8,6 L8,13 Z M4,4 L4,13 L6,13 L6,4 L4,4 Z"})});import{jsx as sd}from"react/jsx-runtime";var rd=t=>sd("svg",{width:"16",height:"16",fill:"#000000",...t,viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:sd("path",{fillRule:"evenodd",d:"M7.65336736,21.1256786 C7.2933164,21.6534897 6.68712411,22 6,22 L4,22 C2.8954305,22 2,21.1045695 2,20 L2,11 C2,9.8954305 2.8954305,9 4,9 L6,9 C6.198171,9 6.38961023,9.02882212 6.57035446,9.08250314 C7.6444817,7.51807482 11.2554748,3.57449216 12.2202699,2.37298955 L12.5204954,1.99910538 L13,1.99910538 C13.6147967,1.99901314 14.1422801,2.04513312 14.748281,2.22159137 C16.091867,2.61282321 17,3.52709845 17,4.99910538 C17,5.51921677 16.9079007,6.07373891 16.7382242,6.68923415 C16.6259612,7.09646424 16.4872151,7.50766133 16.2970775,8.01801005 C16.2391583,8.17347129 16.007193,8.78168345 15.9547911,8.92337824 C15.9451954,8.94932503 15.9359266,8.9745589 15.9269768,8.99910538 L19,8.99910538 C20.8695981,8.99910538 22,10.316625 22,11.9991054 C22,17.9426745 20.7551411,21.9991054 18,21.9991054 L11.0344006,21.9985135 C10.3408482,22.0111947 9.50544052,21.9186578 8.66312366,21.6172857 C8.29521907,21.4856533 7.9567386,21.3218904 7.65336736,21.1256786 Z M8,17.9991054 C8,18.9013355 8.45196659,19.4175764 9.33687634,19.7341879 C9.91062406,19.9394688 10.5253746,20.0075638 10.963066,19.9997143 C10.9703499,19.9995545 10.9703499,19.9995545 11,19.9991054 L18,19.9991054 C19.015127,19.9991054 20,16.7898506 20,11.9991054 C20,11.3589955 19.6912225,10.9991054 19,10.9991054 L15,10.9991054 C13.8054549,10.9991054 13.5555377,10.0754586 13.8046536,9.07541689 C13.8632547,8.84017106 13.9489218,8.5812741 14.0789589,8.22965366 C14.1358033,8.07594642 14.3689242,7.46470447 14.4229225,7.31976744 C14.5944107,6.85947528 14.7161494,6.4986824 14.8101464,6.1577119 C14.9359344,5.70142019 15,5.31568707 15,4.99910538 C15,4.54813166 14.7621788,4.30870189 14.1891338,4.1418399 C13.9483736,4.07173418 13.7113931,4.0330943 13.4599624,4.01423587 C11.914268,5.86195611 8.40663864,9.70054105 8.14171093,10.3190878 C8.04443154,10.5462133 8,10.7589101 8,10.9991054 L8,17.9991054 Z M4,11 L4,20 L6,20 L6,11 L4,11 Z"})});function Et(t,e){var n;let o=t.cloneNode(!0);o.style.top=`${t.offsetTop}px`,o.style.left=`${t.offsetLeft}px`,o.style.position="absolute",o.classList.add(e),o.addEventListener("animationend",()=>o.remove()),(n=t.parentElement)==null||n.appendChild(o)}import av from"dompurify";import{Fragment as lv,useMemo as cv,useRef as dv,useState as uv}from"react";import pv from"snarkdown";var id={fadeup:"E",root:"i",popover:"rr",options:"yo",copyIcon:"G",option:"wo",divider:"tr"};import{jsx as ao,jsxs as ad}from"react/jsx-runtime";function gv(t){return`<button type="button" class=${t}><svg version="1.1" x="0px" y="0px" viewBox="0 0 115.77 122.88" width="10px" height="10px" fill="black"><g><path d="M89.62,13.96v7.73h12.19h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02v0.02 v73.27v0.01h-0.02c-0.01,3.84-1.57,7.33-4.1,9.86c-2.51,2.5-5.98,4.06-9.82,4.07v0.02h-0.02h-61.7H40.1v-0.02 c-3.84-0.01-7.34-1.57-9.86-4.1c-2.5-2.51-4.06-5.98-4.07-9.82h-0.02v-0.02V92.51H13.96h-0.01v-0.02c-3.84-0.01-7.34-1.57-9.86-4.1 c-2.5-2.51-4.06-5.98-4.07-9.82H0v-0.02V13.96v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07V0h0.02h61.7 h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02V13.96L89.62,13.96z M79.04,21.69v-7.73v-0.02h0.02 c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v64.59v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h12.19V35.65 v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07v-0.02h0.02H79.04L79.04,21.69z M105.18,108.92V35.65v-0.02 h0.02c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v73.27v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h61.7h0.02 v0.02c0.91,0,1.75-0.39,2.37-1.01c0.61-0.61,1-1.46,1-2.37h-0.02V108.92L105.18,108.92z"/></g></svg></button>`}function vr(t){let e=t.cloneNode(!0);return e.querySelectorAll("div,button").forEach(o=>o.remove()),e.textContent??""}var mv=({content:t,useLabel:e,copyLabel:o,onCopy:n,onUse:s})=>{let r=h("Markdown",id),i=dv(null),[a,l]=uv(null),c=cv(()=>{let f=pv(t);return av.sanitize(f).replace(/<\/code>/g,`${gv(r.copyIcon)}</code>`)},[t]),d=f=>{var E;let m=f.target,y=!!((E=i.current)!=null&&E.querySelector("code"));a||y&&m.tagName!=="CODE"||!y&&m!==i.current||(m.addEventListener("mouseleave",()=>l(null),{once:!0}),l(m))},u=()=>{if(!a)return;l(null);let f=a.querySelector("button");f&&(Et(f,r.fadeup),n(vr(a)))},g=f=>{f.target.tagName.toLowerCase()==="button"&&(Et(f.target,r.fadeup),n(vr(f.target.parentElement)))},p=()=>{a&&(l(null),s(vr(a)))};return ad(lv,{children:[a&&ao(Ct,{triggerRef:{current:a},parentNode:a,className:r.popover,children:ad("div",{className:r.options,children:[ao("button",{type:"button",className:r.option,onClick:u,children:o}),ao("div",{className:r.divider}),ao("button",{type:"button",className:r.option,onClick:p,children:e})]})}),ao("div",{ref:i,className:r.root,dangerouslySetInnerHTML:{__html:c},onMouseOver:d,onClick:g})]})},ld=mv;var Sr={};Z(Sr,{enUS:()=>fv,nlNL:()=>hv});var fv={useCue:[{type:0,value:"Use"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},hv={useCue:[{type:0,value:"Gebruik"}],copyCue:[{type:0,value:"Kopieer"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var cd={fadeup:"N",fadedown:"A",selected:"vo",thumbsUp:"nr",thumbsDown:"ar"};import{jsx as Ee,jsxs as ud}from"react/jsx-runtime";var xv=({cue:t,onRemove:e,onCopy:o,onUse:n,onThumbsUp:s,onThumbsDown:r})=>{let i=h("WidgetCue",cd),a=R(Sr),l=kn(),[c,d]=Sv(null),u=y=>{o&&o(y,t)},g=y=>{n&&n(y,t)},p=y=>{y.preventDefault(),y.stopPropagation(),e(t)},f=y=>{y.preventDefault(),y.stopPropagation(),Et(y.target,i.fadeup),d("up"),s(t)},m=y=>{y.preventDefault(),y.stopPropagation(),Et(y.target,i.fadedown),d("down"),r(t)};return vv(()=>{l("Assistant response displayed",{name:t.rule.name,description:t.rule.description,group:t.rule.label})},[]),ud(M,{"data-testid":"cue",children:[Ee(H,{children:ud(H.Content,{children:[t.title&&Ee(H.Title,{"data-testid":"widget-cue-title",children:t.title}),Ee(ld,{content:t.text,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:u,onUse:g})]})}),Ee(M.IconButton,{title:a("thumbsUp"),onClick:f,icon:Ee(rd,{}),className:dd(i.thumbsUp,c==="up"&&i.selected),disabled:!!c}),Ee(M.IconButton,{title:a("thumbsDown"),onClick:m,icon:Ee(nd,{}),className:dd(i.thumbsDown,c==="down"&&i.selected),disabled:!!c}),Ee(M.IconButton,{title:a("removeCue"),onClick:p,icon:Ee(td,{})})]})},pd=xv;import{Fragment as wv,jsx as gd}from"react/jsx-runtime";var Cv=({cues:t})=>{let e=bv(),o=oe(),n=kn(),s=c=>{e(Ac({id:c.rule.id})),n("Assistant response closed",{name:c.rule.name,group:c.rule.label,description:c.rule.description})},r=(c,d)=>{Ge(c),n("Assistant response copied",{name:d.rule.name,group:d.rule.label,description:d.rule.description,copiedText:c})},i=(c,d)=>{o.send(Ae,{text:c,suggestion:{source:"cue",sourceText:c}}),n("Assistant response used",{name:d.rule.name,group:d.rule.label,description:d.rule.description,usedText:c})},a=c=>{n("Assistant response feedback",{name:c.rule.name,group:c.rule.label,description:c.rule.description,thumb:"up"})},l=c=>{n("Assistant response feedback",{name:c.rule.name,group:c.rule.label,description:c.rule.description,thumb:"down"})};return gd(wv,{children:t.map(c=>gd(pd,{cue:c,onRemove:s,onCopy:r,onUse:i,onThumbsDown:l,onThumbsUp:a},c.rule.id))})},md=Cv;import{useCallback as Ev}from"react";var Tv=/(https?:\/\/[^\s]+)/,fd=t=>t.split(" ").find(e=>Tv.test(e));import{jsx as kt,jsxs as Rn}from"react/jsx-runtime";var kv=({suggestion:t,lines:e,onUse:o})=>{var d;let n=t.text||t.url||t.message,s=fd(n),r=R(We),i=b("showImages"),a=b("fallbackImage"),l=u=>{u.preventDefault(),u.stopPropagation(),o(n)},c=Ev(u=>{window.open(s,"_blank"),u.stopPropagation(),u.preventDefault()},[s]);return Rn(M,{onClick:l,"data-testid":"edit-suggestion",children:[Rn(H,{children:[i&&t.image&&kt(H.Image,{src:Sn(t,"small",a||void 0),title:t.title}),Rn(H.Content,{children:[t.title&&kt(H.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((d=t.searchKeywords)==null?void 0:d.length)>0&&kt(M.Labels,{labels:t.searchKeywords}),kt(H.Content,{cropText:e==="single",lineClamp:e==="multiple",children:n})]})]}),Rn(M.Actions,{children:[s&&kt(M.ActionButton,{onClick:c,label:r("visitUrl")}),kt(M.ActionButton,{primary:!0,onClick:l,label:r("useSuggestion")})]})]})},hd=kv;import{Fragment as Pv,jsx as yd}from"react/jsx-runtime";var Rv=({lines:t,suggestions:e})=>{let o=oe(),n=(s,r)=>{o.send(Ae,{text:s,suggestion:{...r,source:r.source,sourceText:r.text}})};return yd(Pv,{children:e.map(s=>yd(hd,{suggestion:s,lines:t,onUse:r=>n(r,s)},s.text||s.url||s.message))})},vd=Rv;var xr={};Z(xr,{enUS:()=>Iv,nlNL:()=>Lv});var Iv={waiting:[{type:0,value:"Loading\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"My "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Summarize"}],linkKnowledgeSearch:[{type:0,value:"Knowledge Assist"}],linkSearch:[{type:0,value:"Search"}]},Lv={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"Mijn "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Gesprek samenvatten"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}]};var Sd={root:"pr",loginText:"dr",stateText:"ko",sectionList:"lr",shortcutList:"sr",shortcut:"cr",link:"zo"};import{jsx as A,jsxs as Rt}from"react/jsx-runtime";var Pn=(t,e)=>{let o=X(W);Nv(()=>o?e.every(n=>!!n)?t():()=>{}:()=>{},[...e,o])},_v=({onLogIn:t})=>{let e=R(xr),o=Ov(),n=b("isEmbedded"),s=h("Widget",Sd),r=b("showAutoflows"),i=b("showCustomMessages"),a=b("showSummaryCommand"),l=b("showKnowledgeSearch"),c=b("showSearch"),d=X(Oe),u=X(Yo),g=X(uc),p=X(Ic),f=X(Qo),m=X(hc),y=X(bo),E=X(dt),S=X(W),v=X(xo),k=X(Nc),x=X(en),w=oe(),N=X(ol),U=X(Ec("/admin/")),F=b("adminUrl"),I=b("productName");if(Pn(()=>(o(ro(v)),o(bc(v)),()=>{o(Cc(v))}),[o,E,i,v]),Pn(()=>(o(we(v)),o(pc(v)),()=>{o(gc(v))}),[o,E,r,v]),Pn(()=>{u.forEach(({type:P})=>{o(P==="entities"?ae():le(P))})},[o,E,y,d]),Pn(()=>(o(mr()),()=>{o(Rc())}),[o]),E===!1)return A("div",{className:s.stateText,children:A("div",{children:A("p",{children:e("notSupported")})})},"supported");if(S===!1)return A("div",{className:s.loginText,children:A("div",{children:A(un,{isEmbedded:n,loginUrl:F,onLogIn:t})})},"login");if(!d||!v||S===null||N||k)return A("div",{className:s.stateText,children:A("div",{children:A("p",{children:e("waiting")})})},"waiting");let O=c||a||l||U;return A("div",{className:Mv(s.root),"data-testid":"widget",children:Rt(Wn,{className:s.sectionList,children:[O&&A(ke,{title:e("actions"),type:"shortcuts",children:Rt("div",{className:s.shortcutList,children:[c&&Rt("button",{className:s.shortcut,"data-testid":"shortcut-search",onClick:()=>w.send("ShowCommandPalette",{isOpen:!0}),children:[A(mt,{}),e("linkSearch")]}),a&&Rt("button",{className:s.shortcut,"data-testid":"shortcut-summary",onClick:()=>w.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[A(Jc,{}),e("linkSummary")]}),l&&Rt("button",{className:s.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>w.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[A(Zc,{}),e("linkKnowledgeSearch")]}),U&&Rt("a",{className:s.shortcut,target:"_blank",href:U,"data-testid":"shortcut-studio-login",rel:"noreferrer",children:[A(Wc,{}),e("linkStudioLogin",{productName:I})]})]})}),i&&m.length>0&&A(ke,{type:"custom-messages","data-testid":"custom-messages",children:A(te,{withDivider:!0,children:m.map(P=>A(Uc,{suggestion:P},P.text))})}),r&&g.length>0&&A(ke,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:A(te,{withDivider:!0,children:A(Bc,{})})}),u.map(({type:P,title:$,amount:Un,lines:zn})=>{var nt;switch(P){case"entities":return f&&f.length>0&&A(ke,{type:P,title:$,"data-testid":`type-${P}`,children:A(Gc,{entities:f})},P);case"cues":return p&&p.length>0&&A(ke,{type:P,title:$,"data-testid":`type-${P}`,children:A(te,{withDivider:!0,children:A(md,{cues:p})})},P);default:return((nt=x[P])==null?void 0:nt.fetchState)==="done"&&x[P].suggestions.length>0&&A(ke,{type:P,title:$,"data-testid":`type-${P}`,children:A(te,{withDivider:!0,children:A(vd,{lines:zn,contentType:P,suggestions:x[P].suggestions.slice(0,Un)||[]})})},P)}})]})})},xd=_v;function co(t){let e=new Range;return e.selectNodeContents(t),e}function bd(t,e,o){try{return tt(t,e,o),!0}catch{return!1}}function In(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function Ln(t){return"tagName"in t&&t.tagName==="BR"}var lo=/[\u200B-\u200D\uFEFF]/g;function tt(t,e,o){let n=new Range;if(t.firstChild===null&&e===0&&o===0)return n.selectNodeContents(t),n;let s=0,r=!1;function i(l,c){let d=-1,u=/[\u200B-\u200D\uFEFF]/;if(!u.test(l))return c;for(let g=0;g<=l.length;g++)if(u.test(l[g])||d++,d===c)return g;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let c=l.textContent,d=c.replace(lo,""),u=s+d.length,g=e>=s&&e<=u,p=o>=s&&o<=u;if(g){let f=i(c,e-s);f===0&&!p?n.setStartBefore(l):n.setStart(l,f)}p&&(n.setEnd(l,i(c,o-s)),r=!0),s=u;break}case Node.ELEMENT_NODE:{if(Ln(l)&&(s===e&&n.setStartBefore(l),s++,s===o)){n.setEndAfter(l),r=!0;return}for(let d=0;d<l.childNodes.length&&(a(l.childNodes[d]),!r);d++);let c=l.lastChild;In(l)&&c&&!In(c)&&!Ln(c)&&s++;break}default:break}}if(a(t),n.startContainer===document)throw new Error("Offsets out of bound");return n}function An(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:o,startOffset:n,endContainer:s,endOffset:r,collapsed:i}=e,a,l,c=0;function d(u){let g=u===o,p=u===s;switch(u.nodeType){case Node.TEXT_NODE:{let f=u.textContent;g&&(a=c+f.substring(0,n).replace(lo,"").length),p&&(l=c+f.substring(0,r).replace(lo,"").length),c+=f.replace(lo,"").length;break}case Node.ELEMENT_NODE:{let f=u.nextSibling===null;Ln(u)&&!f&&c++;for(let m=0;m<u.childNodes.length;m++){let y=g&&m===n,E=p&&m===r;if(y&&(a=c),E&&(l=c),l!==void 0||((!y||!i)&&d(u.childNodes[m]),p&&m===r-1&&(l=c),l!==void 0))break}!p&&In(u)&&!f&&c++,p&&(l=c);break}default:break}}if(d(t),l===void 0)throw new Error("Could not determine start and end");return{start:a??l,end:l}}function Mn(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:o,startOffset:n,endContainer:s,endOffset:r}=e,i=-1,a="";function l(c){let d=c===o,u=c===s;switch(d&&i++,c.nodeType){case Node.TEXT_NODE:{if(i!==0)return;let g=d?n:0,p=u?r:void 0,f=c.textContent.replace(lo,"");g===0&&p===void 0?a+=f:a+=f.substring(g,p);break}case Node.ELEMENT_NODE:{let g=c.nextSibling===null;i===0&&Ln(c)&&!g&&(a+=`
8
+ `);for(let p=d?n:0;p<(u?Math.min(r,c.childNodes.length):c.childNodes.length)&&(l(c.childNodes[p]),i!==1);p++);!u&&i===0&&In(c)&&!g&&(a+=`
9
+ `);break}default:break}u&&i++}return l(t),a}var Cd=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(Cd||{}),Fe=class{constructor(e){this.element=e;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(e,o){let n=s=>{o(s)};this.element.addEventListener(e,n),this.disposeHandlers.push(()=>{this.element.removeEventListener(e,n)})}removeEventListener(e,o){this.element.removeEventListener(e,o)}triggerChange(){let e=this.getText(),o=this.getHTML(),n=e!==this.currentText;this.isActive&&(e===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&n&&!this.isSubmitting&&this.emit("change",{plainText:e}),n&&(this.currentSelection=this.getSelection()),this.currentText=e,this.isSubmitting=!1,(this.currentHTML!==o||o===null&&n)&&(this.emit("updated",{plainText:e}),this.triggerCaretPosition(),this.currentHTML=o))}triggerSelection(){let e=this.getSelection();(e.start!==this.currentSelection.start||e.end!==this.currentSelection.end)&&(this.currentSelection=e,this.emit("selection",e),this.triggerCaretPosition())}triggerCaretPosition(){let e=this.getCaretPosition();Pe(e,this.currentCaret)||(this.currentCaret=e,this.emit("caret",e))}handleKeyUp(e){let{key:o,shiftKey:n}=e;(o==="Enter"&&n===!0||o==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(e){let{key:o,ctrlKey:n,metaKey:s}=e;this.isPossibleClearInputAction=Object.values(Cd).includes(o)||o.toLowerCase()==="z"&&(n||s),this.emit("keydown",e)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){var n,s;let o=((n=e.clipboardData)==null?void 0:n.getData("text"))||((s=e.clipboardData)==null?void 0:s.getData("text/plain"))||"";this.emit("paste",{pastedText:o,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",o=>this.handleKeyDown(o)),this.addEventListener("keyup",o=>this.handleKeyUp(o)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",o=>this.handlePaste(o)),this.addEventListener("click",()=>this.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let e=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});e.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{e.disconnect()}),this.currentSelection=this.getSelection()}focus(){this.element.focus()}emit(e,...o){this.isDisposed||this.eventListeners[e]&&this.eventListeners[e].forEach(n=>{n(...o)})}on(e,o){this.isDisposed||(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o))}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};function wd(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var Pt=class extends Fe{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),Mn(this.element,e)}getHTML(){return this.element.innerHTML||""}getRange(){var r;let e=this.getRootNode();if(e.activeElement!==this.element)return null;let o="getSelection"in e?e.getSelection():window.getSelection();if(!o)return null;let n="getComposedRanges"in o&&e instanceof ShadowRoot?(r=o.getComposedRanges(e))==null?void 0:r[0]:o.rangeCount>0?o.getRangeAt(0):null;if(!n)return null;let s=this.element.ownerDocument.createRange();return s.setStart(n==null?void 0:n.startContainer,n==null?void 0:n.startOffset),s.setEnd(n==null?void 0:n.endContainer,n==null?void 0:n.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let e=this.getRange();if(!e||!e.collapsed||!("getBoundingClientRect"in e))return null;let o=e.getBoundingClientRect();return!wd(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!wd(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return An(this.element,e);let o=this.lastKnownSelection;if(o&&bd(this.element,o.start,o.end))return o;let n=co(this.element);return n.collapse(!1),An(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return Mn(this.element,tt(this.element,e,o))}applyChanges(e){var s;if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return(s=this.observer)==null||s.takeRecords(),Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let e=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==e&&(e=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var It=class extends Fe{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:e,selectionEnd:o}=this.element;return{start:e,end:o}}getSelectedText(){let e=this.getSelection();return e?this.getText().slice(e.start,e.end):""}getCaretPosition(){return null}applyChanges(e){if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let e=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=e==null?void 0:e.get)==null?void 0:s.call(this.element)},set:s=>{var r;(r=e==null?void 0:e.set)==null||r.call(this.element,s),this.triggerChange()}});let o=this.element.disabled,n=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>n.disconnect())}};function Td(t,e,o){let n=`deepdesk-iframe-${t}`,s=document.getElementById(n);if(s)return s;let r=document.createElement("iframe"),i=new URL(e);return Object.entries(o).forEach(([a,l])=>{i.searchParams.append(a,l)}),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=n,r.title=`iframe-${t}`,r.src=i.toString(),window.document.body.appendChild(r),r}function Dv(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}var br=class{constructor(e){this.name=e;this.broadcastChannel=new BroadcastChannel(e)}broadcastChannel;disposeHandlers=[];onMessage(e){this.broadcastChannel.addEventListener("message",e),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",e)})}postMessage(e){this.broadcastChannel.postMessage(JSON.stringify(e))}close(){this.disposeHandlers.forEach(e=>e()),this.broadcastChannel.close()}},Cr=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=Td(e,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var o;(o=this.iframe.contentWindow)==null||o.postMessage(JSON.stringify(e),this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(o=>o()),(e=this.iframe)==null||e.remove()}},wr=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(e){this.sessionId!==e&&(this.cleanup(),T.info("Set sessionId",e),this.sessionId=e,this.channel=this.createChannel(e))}createChannel(e){let o=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new Cr(e,this.deepdeskUrl,{debug:!0}):new br(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=Dv(s.data);typeof r!="object"||r.type!=="event"||r.channel!==e||(T.info("Received broadcast event",this.sessionId,s),(a=(i=this.eventMap)[r.name])==null||a.call(i,r.payload))};return o.onMessage(n),o}send(e,o,n){var i,a;T.info("Broadcast event",{sessionId:this.sessionId,name:e,payload:o});let s={type:"event",name:e,payload:o};n!==!1&&((a=(i=this.eventMap)[e])==null||a.call(i,o));let r=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;r==null||r.postMessage({...s,channel:this.sessionId})}cleanup(e=!1){var o,n;(o=this.channel)==null||o.close(),delete this.channel,e&&((n=this.defaultChannel)==null||n.close(),delete this.defaultChannel)}},Ed=wr;var Lt=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var Tr=t=>new Promise(e=>{setTimeout(e,t)});var At=class extends Lt{name="ClientError"},kr=class extends Lt{name="ServerError"},Er=new Map,fe=class t{constructor(e="",o={}){this.baseUrl=e;this.options=o;o.fetch&&(this.fetch=o.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,o={}){return new Promise((n,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,l=o.method===void 0||o.method.toLowerCase()==="get",{useCache:c=!1,abortLatest:d=!1,attempts:u=1,retryDelay:g=500,refreshTokenOn401:p=!0,retryOnError:f=w=>w instanceof TypeError,retryOnResponse:m=w=>w.status>=500,version:y="v1",...E}=o;if(c)if(l){if(Er.has(i)){n(Er.get(i));return}}else throw new Error(`Can't use 'useCache' for ${o.method}`);let S={credentials:"include",...E,headers:{"Content-Type":"application/json",...E.headers}};!l&&this.csrfToken&&(S.headers={...S.headers,"X-CSRFToken":this.csrfToken}),typeof y=="string"&&(S.headers={...S.headers,"X-Deepdesk-API-Version":y});let v=u,k=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&d&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let x=async()=>(v--,a(i,S).then(async w=>m(w)&&!r.isAborted&&v>0?(await Tr(g),x()):w.status===401&&p===!0&&k===!1?(k=!0,await this.refreshToken(),x()):w).catch(async w=>{if(f(w)&&!r.isAborted&&v>0)return await Tr(g),x();throw w}));x().then(w=>w.json().catch(()=>null).then(N=>{w.status>=500?s(new kr("Server Error",N)):w.status===401?s(new At("Unauthorized",N)):w.status===403?s(new At("Forbidden",N)):w.status===404?s(new At("Not Found",N)):w.status>=400&&s(new At("Bad Request",N)),delete this.latestRequestByUrl[i],c&&Er.set(i,N),n(N)})).catch(w=>{s(w)})})}async validateToken(){let{has_valid_access_token:e}=await this.get("/auth/validate");if(!e)return!1;let{is_logged_in:o}=await this.get("/apis/admin/session/validate/",{version:null});return!!o}refreshToken(){return t.refreshingToken||(t.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{t.refreshingToken=null},1e3*60)})),t.refreshingToken}get(e,o){return this.request(e,o)}post(e,o,n){return this.request(e,{method:"POST",body:JSON.stringify(o),...n})}patch(e,o,n){return this.request(e,{method:"PATCH",body:JSON.stringify(o),...n})}put(e,o,n){return this.request(e,{method:"PUT",body:JSON.stringify(o),...n})}delete(e,o){return this.request(e,{method:"DELETE",...o})}};var Hv;(e=>{let t;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||={})})(Hv||={});function Nn(t){return{...L(t),tags:t.tags}}var Be=class t{constructor(e,o={}){this.options=o;this.client=new fe(e,{fetch:o.fetch}),this.client.patchFetch(n=>async(s,r)=>{let i=await n(s,r);return this.handleDeepdeskVersionHeaders(i),i})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=await this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(t.exchangeTokenPromise||(t.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),t.exchangeTokenPromise):Promise.resolve()}async createConversation(e){await this.preflight(),T.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...K(e),tags:e.tags},{version:"v2"});return Nn(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null,useCache:!0});return L(o)}async getKnowledgeAssistant(e){let o=await this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{version:null,useCache:!0});return L(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return L(e)}async getAccount(){let e=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return L(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null,useCache:!0});return L(e)}async checkUserExists(e){let{exists:o}=await this.client.get(`/apis/admin/users/exists?external_id=${e}`);return o}async getConversationBySessionId(e,o={}){await this.preflight(),T.info(`Getting conversation for session ${e}`);let{attempts:n=1,retryDelay:s=1e3}=o,r=await this.client.get(`/api/conversations/by_session_id/${e}`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"});return T.info(`Successfully retrieved conversation ${r.id} for session ${e}`),Nn(r)}async isConversationSupported(e,o={}){T.info(`Check if conversation for session ${e} is supported`);let{attempts:n=1,retryDelay:s=1e3}=o;return(await this.client.get(`/api/conversations/by_session_id/${e}/active_profile`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"})).has_active_profile}async updateConversation(e,o){let n=K(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return Nn(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...K(s),tags:s.tags})),{version:"v2"})).map(s=>Nn(s))}async sendEvent(e,o){let{data:n,...s}=o,r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((i,[a,l])=>({...i,[a]:l}),{});return this.client.post("/api/events",K({...r,...s,data:n,name:e}),{version:"v2"})}async sendEventV1(e,o){let n=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[r,i])=>({...s,[r]:i}),{});return this.client.post("/api/events",{event:e,data:K({...o,...n})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e.filter(n=>n.text)})).entities}async getSummary(e,o={}){return(await this.client.post("/api/summary",{conversation:{messages:e.filter(s=>s.text&&s.source),agent_id:o.agentId,id:o.externalConversationId},prompt_instruction:o.promptInstruction,model:o.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(e){return this.client.post("/apis/admin/session/jwt/",{jwt:e},{version:null}).catch(o=>{throw T.warn(`Invalid token '${e}'`),o})}async authenticateWithKey(e,o){await this.preflight(),await this.client.post("/apis/admin/session/api-key/",K(o),{version:null,refreshTokenOn401:!1,headers:{apikey:e}})}async getTextSuggestions(e,o={},n){return n==="sticky-messages"?this.getPinnedMessages(e):(await this.client.post(`/api/conversations/${e}/recommend/${n}`,K(o),{abortLatest:!0})).map(r=>({...L(r),text:r.text||r.url||r.message,source:n,type:n})).filter((r,i,a)=>i===a.findIndex(l=>l.text===r.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(e,o){return(await this.client.post(`/api/conversations/${e}/autocomplete`,K(o),{abortLatest:!0})).map(s=>({score:1,source:s.source,sourceText:s.source_text,text:s.label,trainingJobs:s.training_jobs,searchKeywords:s.search_keywords,type:s.source})).filter((s,r,i)=>r===i.findIndex(a=>a.text===s.text))}async getPinnedMessages(e){let o=await this.client.get(`/api/conversations/${e}/sticky-messages`,{abortLatest:!0});return L(o).map(n=>({...n,text:n.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(e){let o=await this.client.post("/api/style-suggestions",K(e),{abortLatest:!0});return L(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,K(e),{version:"v2"});return L(o)}async knowledgeAssist(e,o,n,s={}){let r=await this.client.post(`/api/knowledge-assist/assistants/${n}/search`,K({question:e.question,promptInstruction:e.promptInstruction,chatHistory:o.map(i=>({question:i.question,answer:i.answer.answer})),agentId:s.agentId,conversationId:s.conversationId}),{version:"v2"});return L(r)}async requestLoginByEmail(e){let o=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return L(o)}async requestPasswordlessToken(){let e=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return L(e.token)}async getCsrfToken(){let{token:e}=await this.client.get("/apis/admin/session/csrf/",{version:null});return e}async verifyLoginToken(e){let o=await this.client.post("/apis/admin/session/passwordless/login/",{token:e},{version:null});return L(o)}async evaluateRule(e,o,n,s={}){let r=new URLSearchParams;s.raiseForFailingConditions&&r.set("raise_for_failing_conditions","true");let i=await this.client.post(`/api/conversations/${o}/rules/${e}/evaluate?${r.toString()}`,n,{version:"v2"});return L(i.cues)}async getRules(){let e=new URLSearchParams,o=await this.client.get(`/apis/admin/rule-engine/rules/?${e.toString()}`,{version:null,useCache:!0});return L(o)}async translateMessages(e){let o=await this.client.post("/api/translate",K(e),{version:"v2"});return L(o)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(Wr);if(!o||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&o&&a!==o&&T.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(o)}`),this.latestReceivedDeepdeskVersions[i]=o})}};var uo=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(ss(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,L(s))}catch{T.warn(`Invalid JSON for ${e}: ${n}`)}})}connect(){clearTimeout(this.timeoutTimer);let e=new EventSource(this.url,{withCredentials:!0});this.eventSource=e;let o=!1;e.onopen=()=>{o=!0},e.onerror=()=>{o&&e.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{e.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(n=>{this.proxyEvent(n)})}disconnect(){var e;clearTimeout(this.timeoutTimer),this.eventListeners={},(e=this.eventSource)==null||e.close()}emit(e,o){this.eventListeners[e]&&this.eventListeners[e].forEach(n=>n(o))}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),this.proxyEvent(e),()=>{this.off(e,o)}}off(e,o){let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}};var Fv;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(Fv||={});var po=class{constructor(e,o={}){this.apiUrl=e;this.client=new fe(e,o)}client;streams={};logger=T;async getCustomMessages(e){let o=await this.client.get(`/sessions/${e}/suggestions`);return L(o.suggestions)}async sendCustomMessage(e,o){let n=await this.client.post(`/sessions/${e}/messages`,K(o));return L(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,K(o))}async getAutoflows(e){let o=await this.client.get(`/sessions/${e}/autoflows`);return L(o.autoflows)}async startAutoflowSession(e){let o=await this.client.post("/autoflow-sessions",K(e));return L(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new uo(`${this.apiUrl}/sessions/${e}/events`),this.streams[e].connect()),this.streams[e]}closeStream(e){this.streams[e]||(this.streams[e].disconnect(),delete this.streams[e])}};import{combineReducers as qv,configureStore as Gv}from"@reduxjs/toolkit";import{createSlice as Bv}from"@reduxjs/toolkit";var kd={startTime:null,stopTime:null},Rd=Bv({name:"handlingTime",initialState:kd,reducers:{handlingTimeStart(t){if(t.startTime&&!t.stopTime)throw new Error("Timing already started");t.startTime=new Date,t.stopTime=null},handlingTimeStop(t){if(!t.startTime)throw new Error("Timing not started");t.stopTime=new Date},handlingTimeReset(t){t.startTime=null,t.stopTime=null}},extraReducers:t=>{t.addCase(_,()=>kd)}}),{handlingTimeStart:Pd,handlingTimeStop:On,handlingTimeReset:Id}=Rd.actions,Ld=Rd.reducer;var Ad=(t={})=>{let e={onAuthError:lt(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};import{createAsyncThunk as Kv,createSlice as Uv}from"@reduxjs/toolkit";var _n={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var ot=Kv("styleSuggestions/getAll",async({text:t},e)=>{var i;let{deepdeskAPI:o}=e.extra,n=e.getState(),{showStyleSuggestions:s}=n.settings,r=(i=n.conversation.current)==null?void 0:i.profileCode;if(!s)return _n.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),zv=Uv({name:"styleSuggestions",initialState:_n,reducers:{},extraReducers:t=>{t.addCase(ot.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(ot.rejected,e=>{e.fetchState="error"}).addCase(ot.fulfilled,(e,o)=>{e.fetchState="done",Pe(e.list,o.payload)||(e.list=o.payload)}).addCase(ze,e=>{e.list=_n.list}).addCase(_,()=>_n)}}),Md=zv.reducer;var Nd=(t={})=>{let e,o=!0,n={getStyleSuggestions:ot,debounce:500,...t};return s=>r=>i=>{var p;let a=s.getState().input.text,l=r(i),c=s.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:d}=c.settings;if(!((p=c.conversation.current)==null?void 0:p.id)||!d)return l;let{text:g}=c.input;return g===a&&!o||(clearTimeout(e),g==="")||(e=setTimeout(()=>{o=!1,s.dispatch(n.getStyleSuggestions({text:g}))},t.debounce)),l}};function Vv(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var Od=(t={})=>{let e={getTextSuggestions:le,getAutocompleteSuggestions:Yt,debounce:200,check:bt,...t},o;return n=>s=>r=>{var m;let{input:{userCommitted:i}}=n.getState(),a=s(r),l=n.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:d}=l.settings,u=(m=l.conversation.current)==null?void 0:m.id,g=r.type===tn.toString();if(!u||!c&&!d)return a;let{input:{userCommitted:p}}=l;return Vv(p,i)&&!g||(clearTimeout(o),!e.check(l))||(o=setTimeout(()=>{let y=pt(l);y===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(y))},g?0:e.debounce)),a}};var _d=ot.fulfilled.toString();function $v(t,e){let o=new Set([...e.keywordMatches.map(s=>s.keyword)]),n=[];return o.forEach(s=>{let r=t.keywordMatches.filter(l=>l.keyword===s),i=e.keywordMatches.filter(l=>l.keyword===s),a=i.length-r.length;a<=0||n.push(...i.slice(0,a))}),n}var Dd=t=>e=>o=>n=>{var c;if(n.type!==_d){o(n);return}let s=e.getState().styleSuggestions.list;o(n);let r=e.getState(),i=r.styleSuggestions.list,a=(c=r.conversation)==null?void 0:c.current;if(s===i)return;let l=$v(s,i);n.type===_d&&l.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var jv=qv({answer:Va,auth:ni,autoflows:mc,conversation:ai,contentTypes:ta,customMessages:wc,passwordlessToken:Pc,entities:Ra,knowledgeAssistant:Ka,handlingTime:Ld,info:ki,input:Ci,settings:Zr,profile:Xa,search:Ni,summary:Oa,styleSuggestions:Md,ui:bl,rules:Mc,textSuggestions:rl});function Hd(t){return Gv({reducer:jv,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),Ad(),Od({debounce:200}),Nd({debounce:500}),Dd(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var Wv=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},Xv=t=>e=>o=>n=>{var a;let s=e.getState(),r=Jn("inlineSuggestions")(s);switch(n.type){case lt.toString():{!n.payload&&t.emit("logout",void 0);break}case ae.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:n.payload}});break;case xe.fulfilled.toString():t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{summary:n.payload.summary}});break;case G.toString():t.sendEvent(n.payload.name,{conversationId:((a=n.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:n.payload.data});break;case Po.toString():t.handleKeyDown(n.payload);break;case ze.toString():t.logSendMessage(n.payload);break;case Io.toString():t.handleInputChanged(n.payload);break;case Ye.fulfilled.toString():n.isBroadcasted||t.broadcast(ls,n,!1),t.emit("cues",n.payload);break;default:break}let i=o(n);switch(n.type){case ze.toString():t.handleAfterSendMessage(n.payload);break;case eo.toString():t.onUpdateShowTabHint(n.payload);break;case On.toString():t.logHandlingTime();break;case pe.toString():{let{start:l,end:c}=s.input.selection;t.emit("select-suggestion",{type:Wv(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0}),r&&(e.dispatch(ue([])),e.dispatch(Se()));break}case Ro.toString():{let{start:l,end:c}=s.input.selection;t.emit("replace",{...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case Ft.toString():{let l=e.getState(),{text:c,selection:d}=l.input.userCommitted;t.emit("reset",{text:c,selectionAfter:d},{mayApplyChanges:!0});break}case Lo.toString():t.emit("select-image",n.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:s.conversation.current.id,data:{path:n.payload.suggestion.image,title:n.payload.suggestion.title}});break;case ue.toString():{r&&n.payload.length>0&&e.dispatch(Le(0));break}default:break}return i},Fd=Xv;function Rr(t){return t.toISOString().replace("T"," ").replace("Z","")}function Bd(t,e){var s,r,i;let{startTime:o,stopTime:n}=t.handlingTime;if(!o||!n)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:t.conversation.current.id,clientVersion:e.version,agentId:(s=t.info.agentInfo)==null?void 0:s.agentId,agentName:(r=t.info.agentInfo)==null?void 0:r.agentName,agentEmail:(i=t.info.agentInfo)==null?void 0:i.agentEmail,timeStart:Rr(o),timeStop:Rr(n)}}function Kd(t,e,o){var N,U,F;let{text:n,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:d,pastes:u,cuts:g,deletions:p,textSuggestions:f,offeredTextSuggestions:m}}=e[t],y=n.length,S=f.reduce((I,{text:O,searchTerm:P})=>I+O.length-(P?P.length:0),0),v=c??Date.now(),k=(Date.now()-v)/1e3+(d||0),x=s/k,w=f.reduce((I,{searchTerm:O})=>I+(O?O.length:0),0);return{conversationId:e.conversation.current.id,source:"agent",text:n,clientVersion:o.version,pastes:u,cuts:g,deletions:p,lenTextTyped:s+w,lenTextTotal:y,lenTextAssisted:S,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:k,charsPerSecond:x,numPastes:l,textSuggestionsV2:f,suggestionsCounters:[{source:"gpt",countOffered:m.filter(I=>I.source==="gpt").length}],agentId:(N=e.info.agentInfo)==null?void 0:N.agentId,agentName:(U=e.info.agentInfo)==null?void 0:U.agentName,agentEmail:(F=e.info.agentInfo)==null?void 0:F.agentEmail}}function Pr(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return Pr(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?Pr(s,e):null}function Ud(t,e){return Pr(t,e)}function zd(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function Zv(t){return typeof t=="object"&&t!==null&&"tagName"in t}function Ir(t){return Zv(t)&&(De(t)||pn(t))}var Vd,he=new Map,Qv=["bottom","height","left","right","top","width"],Jv=(t={},e={})=>Qv.some(o=>t[o]!==e[o]);function $d(t){var o,n;if(t.ownerDocument===document)return[];let e=((n=(o=t.ownerDocument)==null?void 0:o.defaultView)==null?void 0:n.frameElement)??null;return e?[e,...$d(e)]:[]}function qd(t,e){return!t||!e?null:{...t,top:t.top+e.top,left:t.left+e.left}}var Dn=!1,Gd=()=>{Dn=!0;let t=[];if(he.forEach((e,o)=>{if(!o.isConnected){e.rect=null,t.push(e),he.delete(o);return}let n=o.getBoundingClientRect();Jv(n,e.rect)&&(e.rect=n,t.push(e))}),t.forEach(e=>{let o=e.parentRects?e.parentRects.reduce(qd,e.rect):e.rect;e.callbacks.forEach(n=>n(o))}),he.size===0){Dn=!1;return}Vd=window.requestAnimationFrame(Gd)};function Lr(t,e){let o=$d(t),n=[],s=o.map((r,i)=>Lr(r,a=>{n[i]=a;let l=he.get(t);if(!l)return;let c=n.reduce(qd,l.rect);l.callbacks.forEach(d=>d(c))}));return{observe(r=!0){if(s.forEach(i=>i.observe(!1)),he.has(t)){let i=he.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else he.set(t,{rect:void 0,callbacks:[e],parentRects:n});r&&!Dn&&Gd()},unobserve(){s.forEach(i=>i.unobserve());let r=he.get(t);if(r){let i=r.callbacks.indexOf(e);i>=0&&r.callbacks.splice(i,1),r.callbacks.length||he.delete(t),he.size||(cancelAnimationFrame(Vd),Dn=!1)}}}}var jd,ye=new Map,Wd=()=>{ye.forEach((t,e)=>{if(!e.isConnected){ye.delete(e);return}let{clientHeight:o,scrollHeight:n}=e,s=n>o;t.visible!==s&&(t.visible=s,t.callbacks.forEach(r=>r(t.visible)))}),ye.size!==0&&(jd=window.requestAnimationFrame(Wd))};function Xd(t,e){return{observe(){let o=ye.size===0;ye.has(t)?ye.get(t).callbacks.push(e):ye.set(t,{visible:void 0,callbacks:[e]}),o&&Wd()},unobserve(){let o=ye.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||ye.delete(t),ye.size||cancelAnimationFrame(jd)}}}}var Ar=["borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth","borderStyle","boxSizing","color","overflowWrap","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontWeight","fontKerning","lineHeight","letterSpacing","paddingLeft","paddingTop","paddingRight","paddingBottom","width","height","textIndent","whiteSpace","wordBreak","wordSpacing","wordWrap"];function Mr(t,e,o){return o.forEach(n=>{e.style[n]=t[n]})}function Mt(t){return parseFloat(t)}function Hn(t){return Math.round(t*1e6)}function Zd(t){return t/1e6}function Nr(t,e,o){if(t.boxSizing==="content-box")return;let{clientWidth:n}=e,s=Mt(t.width),r=Mt(t.borderLeftWidth),i=Mt(t.borderRightWidth),a=Mt(t.paddingRight),l=Zd(Hn(s)-Hn(r)-Hn(i)),c=Zd(Hn(n));if(l-c>2){let d=l-c;o.style.paddingRight=`${a+d}px`}}function Fn(t,e={}){var d;let o=e.overlayContainer||document.createElement("div");o.style.display="none",o.style.position=e.position??"fixed",o.style.pointerEvents="none",o.style.borderColor="transparent",Ze(o);let n=window.getComputedStyle(t),s=!0,r=()=>{o.scrollTop=t.scrollTop};Mr(n,o,Ar),Nr(n,t,o),e.mirrorOverflow&&(o.style.overflow="hidden",t.addEventListener("scroll",r));let i=Xd(t,()=>{Mr(n,o,Ar),Nr(n,t,o),r(),setTimeout(r,0)}),a,l=!0,c=Lr(t,u=>{if(u===null){e.onRemove&&e.onRemove(),o.remove();return}if(!l&&e.onMoveStart&&(Promise.resolve().then(()=>e.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{e.onMoveEnd&&e.onMoveEnd(),l=!1},200),u.height===0&&u.width===0){if(s===!0)return;e.onHide&&e.onHide(),o.style.display="none",s=!0;return}if(Mr(n,o,Ar),Nr(n,t,o),r(),o.style.top=`${u.top}px`,o.style.left=`${u.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let g=e.closestScrollElement.getBoundingClientRect(),p=window.getComputedStyle(e.closestScrollElement),f=Mt(p.borderTopWidth),m=Mt(p.borderBottomWidth),y=g.top+f-u.top,E=u.top+u.height+-(g.top+g.height-m);o.style.clipPath=`inset(${y}px 0px ${E}px 0px)`}s&&(o.style.display="block",e.onShow&&e.onShow(),s=!1)});return e.appendTo?e.appendTo.appendChild(o):(d=t.parentElement)==null||d.appendChild(o),c.observe(),i.observe(),[o,()=>{t.removeEventListener("scroll",r),c.unobserve(),i.unobserve()}]}var Qd=(t,e)=>({value(){try{let o=sessionStorage.getItem(`dd-${t}`);if(!o)return e;try{return JSON.parse(o)}catch{return e}}catch{return e}},update(o){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(o))}catch{T.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function Yv(t){return t.offsetParent!==null}function Jd(t){if(!Yv(t))return!1;let e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}function Or(t,e,o=100){let n=Jd(t);e({isVisible:n});let s=setInterval(()=>{let r=Jd(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}import{jsx as z}from"react/jsx-runtime";var Yd=Qd("showTabHint",!0),Kn=class t{static version="11.1.1-beta.4";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 Be(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let d={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Fd({broadcast:(u,g,p)=>{this.broadcastEvents.send(u,g,p)},emit:(u,g,p)=>this.emit(u,g,p),handleAfterSendMessage:u=>this.handleAfterSendMessage(u),handleInputChanged:u=>this.handleInputChanged(u),handleKeyDown:u=>this.handleKeyDown(u),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:u=>this.logSendMessage(u),onUpdateShowTabHint:u=>Yd.update(u),sendEvent:(u,g)=>this.deepdeskApi.sendEvent(u,g)})]};o&&Object.assign(d,{deepdeskBrokerAPI:new po(o)}),this.store=Hd(d),this.broadcastEvents=new Ed({debug:!0,deepdeskUrl:c,eventMap:Oi(this.store),createCustomChannel:l}),this.store.dispatch(eo(Yd.value())),this.store.dispatch(So({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(lt(null)),this.store.dispatch(ve()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();W(n)&&Qr(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(ve())).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(ts({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Co(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(wo({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(os(e))).payload}async postMessages(e){return(await this.store.dispatch(Eo(e))).payload}async updateConversation(e){return(await this.store.dispatch(To(e))).payload}resetConversation(){this.store.dispatch(_()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(xe());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(So(e))}setVisitorInfo(e){this.store.dispatch(Ei(e))}async setAgentInfo(e){await this.store.dispatch(Bt(e))}async setAgentSettings(e){await this.store.dispatch(is(e))}async getAgentSettings(){return(await this.store.dispatch(as())).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(Io(e))}notifyKeyDown(e){this.store.dispatch(Po(e))}notifyPaste(e,o){this.store.dispatch(vi({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(hi(e))}notifyExternalSuggestion(e){this.store.dispatch(pe(e)),this.store.dispatch(Se())}async evaluateRule(e,o={}){let{payload:n,error:s}=await this.store.dispatch(Ye({label:e,params:o}));if(s)throw new Error(s.message);return n}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(_e({collapse:!1})),this.inputMediator&&this.store.dispatch(ui({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(ue([])))}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(yi(li(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(gi()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},d=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(fi()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Ft()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(e.key){case"Up":case"ArrowUp":i?d():c();return;case"Down":case"ArrowDown":{i?c():d();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(Le(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Le(-1)),this.store.dispatch(Ft()),e.preventDefault()):o||(this.store.dispatch(_e({collapse:!0})),this.store.dispatch(Sl(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:u}=this.state.input,g=u.text.substring(0,u.selection.end),{tabCompletionSuggestion:p}=this.state.input;this.store.dispatch(eo(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&p&&p.text.startsWith(g)&&(this.store.dispatch(pe({text:p.text,suggestion:p,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(Se())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Si()),this.store.dispatch(ue([]))}handlingTimeStart(){this.state.handlingTime.startTime||(T.info("Start handling time"),this.store.dispatch(Pd()))}handlingTimeStop(){this.state.handlingTime.startTime&&(T.info("Stop handling time"),this.store.dispatch(On()))}logSendMessage(e){let o=Kd("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)}logHandlingTime(){let e=Bd(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Id())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(Se()),this.store.dispatch(ze(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(pe({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]=Fn(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{Bn(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]=Fn(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{Bn(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Ze(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(()=>{Bn(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(!Ir(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:d,isEmbedded:u,detectSubmit:g,insertLink:p,inputMediator:f,closestScrollSelector:m,appendOverlayTo:y,inlineSuggestions:E,floatingMenu:S}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:d,showTextSuggestions:i,insertLink:p,isEmbedded:u,inlineSuggestions:E,floatingMenu:!!S}),o.automaticHandlingTime&&this.setupHandlingTime(e),Ze(e),this.inputMediator=f||(De(e)?new It(e):new Pt(e)),this.inputMediator.on("change",({plainText:x})=>{this.notifyInputChanged(x)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(xi({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",x=>{this.notifyKeyDown(x)}),this.inputMediator.on("paste",({pastedText:x,selectionText:w})=>{this.notifyPaste(x,w)}),this.inputMediator.on("cut",({selectionText:x})=>{this.notifyCut(x)});let v=m&&Ud(e,m)||void 0;if(E){let{customStyles:x,appendOverlayTo:w}=o;if(De(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let N=this.createInlineContainer(e,"deepdesk-caret");Nt(z(Qe,{store:this.store,customStyles:x,children:z($e,{broadcastEvents:this.broadcastEvents,children:z(Rl,{})})}),N),this.inputMediator.on("caret",F=>{this.store.dispatch(ue([])),F?(N.style.display="block",N.style.top=`${F.top}px`,N.style.left=`${F.left}px`):N.style.display="none"});let U=this.overlayContainerFactory("floating-menu",v||e,{appendTo:typeof S=="object"&&"appendOverlayTo"in S?S.appendOverlayTo:w},x==null?void 0:x.floatingMenuRootNode);Nt(z(Qe,{store:this.store,customStyles:x,children:z($e,{broadcastEvents:this.broadcastEvents,children:z(yl,{onLogIn:()=>this.loginViaPopup().catch(F=>T.warn(F.message))})})}),U)}else{let x=this.overlayContainerFactory("deepdesk-tab-completion",v||e,{appendTo:y,closestScrollElement:v,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),w=this.overlayContainerFactory("deepdesk-suggestions-overlay",v||e,{appendTo:y},n==null?void 0:n.suggestionsRootNode);Nt(z(Qe,{store:this.store,customStyles:n,children:z($e,{broadcastEvents:this.broadcastEvents,children:z(lc,{inputElement:e})})}),x),Nt(z(Qe,{store:this.store,customStyles:n,children:z($e,{broadcastEvents:this.broadcastEvents,children:z(Hl,{onLogIn:()=>this.loginViaPopup().catch(N=>T.warn(N.message))})})}),w)}Nt(z(Qe,{store:this.store,customStyles:n,children:z($e,{broadcastEvents:this.broadcastEvents,children:z(ul,{})})}),this.createContainer("deepdesk-overlays"));let k;this.inputMediator.on("selection",x=>{clearTimeout(k),x===null?k=setTimeout(()=>{x!==null&&this.store.dispatch(ns(x))},500):this.store.dispatch(ns(x))}),this.inputMediator.on("disabled",()=>{var x;(x=this.inputMediator)==null||x.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{g&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Ws(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Ws(!0))),this.store.dispatch(pi({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(Se()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var x;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((x=this.state.conversation.current)==null?void 0:x.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}),Nt(z(Qe,{store:this.store,customStyles:n,children:z($e,{broadcastEvents:this.broadcastEvents,children:z(xd,{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&&Bn(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=Or(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){zd(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Jt());let e=Oe(this.state);e&&(await this.store.dispatch(Qt()),this.store.dispatch(So({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(e){return new Promise((o,n)=>{let s=new MessageChannel,r=s.port1,i=this.state.settings.adminUrl,a=new URL(e!=null&&e.url?e==null?void 0:e.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,c=()=>{d&&!d.closed&&d.close(),window.removeEventListener("message",u),clearInterval(g)};r.onmessage=async p=>{var f,m;if((f=p.data)!=null&&f.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((m=p.data)==null?void 0:m.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Ut),l=!0,s.port1.close(),o()}catch(y){console.error(y),n(y)}finally{l=!0,c()}};let d=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");d===null&&n(new Error("Popup blocked by browser"));let u=async p=>{var f;if(p.origin===a.origin)switch((f=p.data)==null?void 0:f.type){case"deepdesk-popup-loaded":{try{let m=JSON.stringify({type:"deepdesk-popup-create-channel"});d==null||d.postMessage(m,a.origin,[s.port2])}catch(m){T.error("Error posting message to popup",m),n(m)}break}case"deepdesk-popup-error":{c(),p.data.message==="Timeout"&&T.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(p.data.message));break}}};window.addEventListener("message",u);let g=setInterval(()=>{d&&!d.closed||(c(),l||n(new Error("Popup closed by user")))},200);this.unmountHandlers.push(c)})}translateMessages(e){return this.deepdeskApi.translateMessages(e)}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=Yo(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(ae()):this.store.dispatch(le(n))})}catch(n){this.handleError(n)}}};async function eS(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 tS(t,e,o={}){let n=o.replace?tt(t,o.replace.start,o.replace.end):co(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
+ `).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?tt(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 oS(t){let e=document.createElement("template");return e.innerHTML=t.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),e.content}function nS(t){let e=document.createDocumentFragment();return t.split(`
11
+ `).forEach((o,n)=>{n>0&&e.appendChild(document.createElement("br"));let s={index:0},r=0;for(;s=o.slice(r).match(/(\[([^\]]+)])\(([^)]+)\)/);){let i=document.createElement("a");i.href=s[3],i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),i.appendChild(document.createTextNode(s[2])),e.appendChild(document.createTextNode(o.slice(r,r+s.index))),e.appendChild(i),r=r+s.index+s[0].length}e.appendChild(document.createTextNode(o.slice(r)))}),e}function eu(t,e){return!t.contains(e)||e===t?null:e.parentNode===t?e:eu(t,e.parentNode)}async function sS(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?oS(e):nS(e);if(o){let d=l.startContainer===t?t.childNodes[l.startOffset]:l.startContainer,u=eu(t,d)??t.firstChild;t.insertBefore(c,(u==null?void 0:u.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 rS(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function iS(t,e,o){await new Be(t).authenticateWithKey(e,o)}async function aS(t){let o=await new fe(t).get("/platform/config/",{version:null,useCache:!0});return L(o)}async function lS(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 cS(t,e){let o=await lS(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,Pt as ContentEditableInput,Be as DeepdeskAPI,Kn as DeepdeskSDK,fe as HTTPClient,Fe as InputMediator,at as InputType,qn as KeyboardHint,Gn as Label,vo as Locale,ke as Section,Wn as SectionList,Re as Sources,M as Suggestion,te as SuggestionList,It as TextAreaInput,it as ToggleButton,cS as attachFile,iS as authenticateWithKey,co as createFullRange,Fn as createOverlayContainer,tt as createRangeFromOffsets,Xt as escapeHTML,aS as fetchPlatformConfig,rS as formatTextMarkup,An as getRangeOffsets,Mn as getRangeText,sS as insertCKEditor,Es as isHTML,Ir as isSupportedInputElement,tS as updateContentEditable,eS as updateTextArea,h as useStyles,Or as waitForElementVisibilityChange};