@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.cjs.js CHANGED
@@ -1,11 +1,11 @@
1
- "use strict";var mp=Object.create;var vn=Object.defineProperty;var fp=Object.getOwnPropertyDescriptor;var hp=Object.getOwnPropertyNames;var yp=Object.getPrototypeOf,vp=Object.prototype.hasOwnProperty;var Y=(t,e)=>{for(var o in e)vn(t,o,{get:e[o],enumerable:!0})},_i=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of hp(e))!vp.call(t,s)&&s!==o&&vn(t,s,{get:()=>e[s],enumerable:!(n=fp(e,s))||n.enumerable});return t};var k=(t,e,o)=>(o=t!=null?mp(yp(t)):{},_i(e||!t||!t.__esModule?vn(o,"default",{value:t,enumerable:!0}):o,t)),Sp=t=>_i(vn({},"__esModule",{value:!0}),t);var xh={};Y(xh,{Card:()=>H,ContentEditableInput:()=>jt,DeepdeskAPI:()=>rt,DeepdeskSDK:()=>yn,HTTPClient:()=>Le,InputMediator:()=>st,InputType:()=>It,KeyboardHint:()=>wn,Label:()=>Tn,Locale:()=>Io,Section:()=>Ke,SectionList:()=>En,Sources:()=>Ue,Suggestion:()=>O,SuggestionList:()=>ce,TextAreaInput:()=>Wt,ToggleButton:()=>Pt,attachFile:()=>up,authenticateWithKey:()=>cp,createFullRange:()=>bo,createOverlayContainer:()=>hn,createRangeFromOffsets:()=>Ct,escapeHTML:()=>ro,fetchPlatformConfig:()=>dp,formatTextMarkup:()=>lp,getRangeOffsets:()=>pn,getRangeText:()=>gn,insertCKEditor:()=>ap,isHTML:()=>cs,isSupportedInputElement:()=>nr,updateContentEditable:()=>rp,updateTextArea:()=>sp,useStyles:()=>h,waitForElementVisibilityChange:()=>ir});module.exports=Sp(xh);var lr=k(require("classnames")),fe=k(require("react"));var Sn=k(require("react")),Di=k(require("classnames")),Ro=Sn.default.createContext({});function h(t,e){let{debug:o,...n}=(0,Sn.useContext)(Ro),s=n[t];return s?Object.entries(e).reduce((r,[i,a])=>{let l=s[i];return{...r,[i]:(0,Di.default)(a,l,o?`${t}__${i}`:!1)}},{}):e}var Hi={root:"uo"};var Tt=require("react/jsx-runtime"),xn=()=>(0,Tt.jsxs)("svg",{className:Hi.root,width:"185",height:"170",viewBox:"0 0 185 170",xmlns:"http://www.w3.org/2000/svg",children:[(0,Tt.jsx)("defs",{children:(0,Tt.jsx)("style",{children:".cls-1 { fill: #b3b3b3; }"})}),(0,Tt.jsx)("title",{children:"Failed loading image"}),(0,Tt.jsx)("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 ar={root:"yo",imageWrapper:"G",image:"wo",content:"m",title:"vo",contentIsCropped:"ko",lineClamp:"zo"};var Et=require("react/jsx-runtime"),bn=(0,fe.createContext)(ar),Cp=({title:t,src:e})=>{let o=(0,fe.useContext)(bn),[n,s]=(0,fe.useState)(!1);return(0,fe.useEffect)(()=>{s(!1)},[e]),(0,Et.jsx)("div",{className:o.imageWrapper,children:e&&!n?(0,Et.jsx)("img",{className:o.image,alt:t,src:e,onError:()=>s(!0)}):(0,Et.jsx)(xn,{})})},wp=({className:t,lineClamp:e=!1,cropText:o=!1,children:n})=>{let s=(0,fe.useContext)(bn);return(0,Et.jsx)("div",{className:(0,lr.default)(s.content,t,{[s.contentIsCropped]:o,[s.lineClamp]:e}),children:n})},Tp=({as:t="h1",cropText:e=!1,className:o,children:n,...s})=>{let r=(0,fe.useContext)(bn);return fe.default.createElement(t,{className:(0,lr.default)(r.title,o,{[r.contentIsCropped]:e}),...s},n)},Cn=({children:t})=>{let e=h("Card",ar);return(0,Et.jsx)("div",{className:e.root,children:(0,Et.jsx)(bn.Provider,{value:e,children:t})})};Cn.Image=Cp;Cn.Content=wp;Cn.Title=Tp;var H=Cn;var Bi=k(require("classnames"));var Fi={root:"N"};var Ki=require("react/jsx-runtime");var kp={"arrow-up":"\u25B2","arrow-down":"\u25BC",tab:"tab",esc:"Esc",enter:"\u21B5"},Rp=({className:t,keyCode:e,...o})=>{let n=h("KeyboardHint",Fi);return(0,Ki.jsx)("span",{"data-key":kp[e],className:(0,Bi.default)(t,n.root),...o})},wn=Rp;var zi=k(require("classnames"));var Ui={root:"jo"};var Vi=require("react/jsx-runtime"),Ip=({className:t,children:e,...o})=>{let n=h("Label",Ui);return(0,Vi.jsx)("span",{...o,className:(0,zi.default)(t,n.root),children:e})},Tn=Ip;var $i={root:"qo",subTitleContainer:"Co",subtitle:"So",suggestions:"Eo"};var Zt=require("react/jsx-runtime"),Lp=({title:t,children:e,type:o,...n})=>{let s=h("Section",$i);return(0,Zt.jsxs)("section",{...n,className:s.root,"data-section-type":o,children:[t&&(0,Zt.jsx)("div",{className:s.subTitleContainer,children:(0,Zt.jsx)("span",{className:s.subtitle,children:t})}),(0,Zt.jsx)("div",{className:s.suggestions,children:e})]})},Ke=Lp;var Gi=k(require("classnames")),ji=k(require("react"));var qi={root:"Go"};var Wi=require("react/jsx-runtime"),Np=ji.default.forwardRef(({className:t,children:e},o)=>{let n=h("SectionList",qi);return(0,Wi.jsx)("div",{ref:o,className:(0,Gi.default)(n.root,t),children:e})}),En=Np;var Qt=k(require("classnames")),le=k(require("react"));var Po=require("react/jsx-runtime"),Xi=({className:t})=>(0,Po.jsxs)("svg",{viewBox:"0 0 12 12",version:"1.1",xmlns:"http://www.w3.org/2000/svg",className:t,children:[(0,Po.jsx)("line",{x1:"1",y1:"11",x2:"11",y2:"1",stroke:"black",strokeWidth:"2"}),(0,Po.jsx)("line",{x1:"1",y1:"1",x2:"11",y2:"11",stroke:"black",strokeWidth:"2"})]});var cr={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"};var se=require("react/jsx-runtime"),kt=(0,le.createContext)(cr),_p=({fixed:t,children:e,...o})=>{let n=(0,le.useContext)(kt);return(0,se.jsx)("div",{...o,className:(0,Qt.default)(n.actions,{[n.actionsIsFixed]:t}),children:e})},Dp=({className:t,title:e,...o})=>{let n=(0,le.useContext)(kt);return(0,se.jsx)("div",{className:(0,Qt.default)(n.closeIcon,t),title:e,role:"button","aria-label":e,...o,children:(0,se.jsx)(Xi,{})})},Hp=({className:t,primary:e,disabled:o,label:n,children:s})=>{let r=(0,le.useContext)(kt);return(0,se.jsxs)("div",{className:(0,Qt.default)(t,r.actionButton,r.dropdownButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:o}),onMouseDown:i=>i.stopPropagation(),onClick:i=>i.stopPropagation(),children:[n,(0,se.jsx)("ul",{className:r.dropdownList,children:s})]})},Fp=({index:t,label:e,onClick:o})=>{let n=(0,le.useContext)(kt);return(0,se.jsx)("li",{className:n.dropdownItem,children:(0,se.jsx)("button",{className:n.dropdownItemButton,type:"button","data-index":t,onClick:o,children:e})})},Bp=({className:t,primary:e,disabled:o,onClick:n,label:s})=>{let r=(0,le.useContext)(kt);return(0,se.jsx)("button",{type:"button",className:(0,Qt.default)(t,r.actionButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:o}),onClick:n??(i=>i.stopPropagation()),disabled:o,"aria-hidden":o,children:s})},Kp=({labels:t})=>{let e=(0,le.useContext)(kt);return(0,se.jsx)("div",{className:e.labels,children:t.map(o=>(0,se.jsx)("span",{className:e.label,children:o},o))})},Rt=le.default.forwardRef(({className:t,selected:e,onClick:o,children:n,as:s="div",...r},i)=>{let a=h("Suggestion",cr),l=(0,le.useCallback)(c=>{c.preventDefault(),o&&o(c)},[o]);return(0,se.jsx)(s,{...r,ref:i,className:(0,Qt.default)(t,a.root,{[a.isSelected]:e,[a.isClickable]:!!o}),onClick:l,children:(0,se.jsx)(kt.Provider,{value:a,children:n})})});Rt.Labels=Kp;Rt.Actions=_p;Rt.ActionButton=Bp;Rt.DropdownButton=Hp;Rt.DropdownItem=Fp;Rt.CloseIcon=Dp;var O=Rt;var Qi=k(require("classnames"));var Zi={root:"Mo",isWithDivider:"Ro"};var Ji=require("react/jsx-runtime"),zp=({withDivider:t,children:e})=>{let o=h("SuggestionList",Zi);return(0,Ji.jsx)("div",{"data-testid":"suggestions-overlay-list",className:(0,Qi.default)(o.root,{[o.isWithDivider]:t}),children:e})},ce=zp;var ea=k(require("classnames"));var Yi={root:"u",isCollapsed:"T"};var kn=require("react/jsx-runtime"),$p=({className:t,isCollapsed:e,title:o,onClick:n})=>{let s=h("ToggleButton",Yi);return(0,kn.jsx)("button",{type:"button",className:(0,ea.default)(s.root,t,{[s.isCollapsed]:e}),onClick:n,title:o,children:(0,kn.jsx)("svg",{width:"14",height:"8",viewBox:"-2.5 -5 75 60",preserveAspectRatio:"none",children:(0,kn.jsx)("path",{d:"M0,0 l35,50 l35,-50",fill:"none",stroke:"grey",strokeLinecap:"round",strokeWidth:"6"})})})},Pt=$p;var ta=/(?:[.,;:!?\\n]|:\\)|:\\(|:-\\)|:-\\()/g,Rn=/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\})/g;var oa=/x-deepdesk-(([a-z0-9\-_])+-version)/,Ue=(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))(Ue||{}),It=(r=>(r.ENTER="enter",r.TAB="tab",r.ARROW="arrow",r.HOTKEY="hotkey",r.MOUSE="mouse",r))(It||{});var xe=require("react-dom");var Sc=require("react");var na=require("@reduxjs/toolkit"),sa=require("react-redux");var Io=(o=>(o.NL_NL="nl-NL",o.EN_US="en-US",o))(Io||{});var qp={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"},ra=(0,na.createSlice)({name:"settings",initialState:qp,reducers:{set(t,e){Object.entries(e.payload).forEach(o=>{let[n,s]=o;typeof s>"u"||(t[n]=s)})}}}),{set:Pn}=ra.actions,dr=t=>e=>e.settings[t],C=t=>(0,sa.useSelector)(dr(t)),ia=ra.reducer;var Lr=require("react-redux");var Jt=require("@reduxjs/toolkit");var Gp={isLoggedIn:!0,loginFetchState:"idle",verifyFetchState:"idle",showLoginOverlay:!1},ee=t=>t.auth.isLoggedIn,aa=t=>t.auth.loginFetchState,la=t=>t.auth.verifyFetchState,ca=t=>t.auth.showLoginOverlay,ze=(0,Jt.createAsyncThunk)("auth/validate",async(t,e)=>e.extra.deepdeskAPI.isLoggedIn()),da=(0,Jt.createAsyncThunk)("auth/requestLogin",async({email:t},e)=>{let{deepdeskAPI:o}=e.extra;return o.requestLoginByEmail(t)}),Ao=(0,Jt.createAsyncThunk)("auth/verifyLoginToken",async({token:t},e)=>{let{deepdeskAPI:o}=e.extra;return o.verifyLoginToken(t)}),ua=(0,Jt.createSlice)({name:"auth",initialState:Gp,reducers:{setIsLoggedIn(t,e){t.isLoggedIn=e.payload},setShowLoginOverlay(t,e){t.showLoginOverlay=e.payload}},extraReducers:t=>{t.addCase(ze.pending,e=>{e.loginFetchState="loading"}),t.addCase(ze.fulfilled,(e,{payload:o})=>{e.isLoggedIn=o,e.loginFetchState="done"}),t.addCase(ze.rejected,e=>{e.loginFetchState="error",e.isLoggedIn=!1}),t.addCase(Ao.pending,e=>{e.verifyFetchState="loading"}),t.addCase(Ao.rejected,e=>{e.verifyFetchState="error"}),t.addCase(Ao.fulfilled,(e,o)=>{o.payload.isLoggedIn?e.verifyFetchState="done":e.verifyFetchState="error"})}}),{setIsLoggedIn:Yt,setShowLoginOverlay:pa}=ua.actions,ga=ua.reducer;var Ve=require("@reduxjs/toolkit"),va=require("diff"),Sa=require("react-redux");function ma(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function it(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)=>it(r,e[i],o-1)):ma(t)&&ma(e)?Object.keys(t).length!==Object.keys(e).length?!1:Object.keys(t).every(i=>it(t[i],e[i],o-1)):!1}function jp(t){return Math.max(...t.map(e=>e.length))}function Wp(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 fa(t,e){let n=[...t.map(({text:s})=>s.split(/\b(\w+)\b/))];for(let s=0;s<jp(n);s++){let r=Wp(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 Xp=2;function ur(t,e=""){if(t.length===0)return;if(t.length===1)return t[0];let o=fa(t,Xp);return o&&o.text!==e?o:t[0]}var be=require("@reduxjs/toolkit");var Zp={info(...t){console.info("[Deepdesk]",...t)},warn(...t){console.warn("[Deepdesk]",...t)},error(...t){console.error("[Deepdesk]",...t)}},E=Zp;var ha={current:null,isSupported:null},_=(0,be.createAction)("resetConversation"),In=t=>{let{current:e}=t.conversation;return(e==null?void 0:e.sessionId)||null},An=t=>{let{current:e}=t.conversation;return(e==null?void 0:e.id)||null},eo=t=>t.conversation.isSupported,pr=(0,be.createAsyncThunk)("conversation/isSupported",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.isConversationSupported(t.sessionId,t.options)}),Ln=(0,be.createAsyncThunk)("conversation/create",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.createConversation(t)}),Mn=(0,be.createAsyncThunk)("conversation/bySessionId",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.getConversationBySessionId(t.sessionId,t.options)}),Nn=(0,be.createAsyncThunk)("conversation/update",(t,e)=>{let{deepdeskAPI:o}=e.extra,n=An(e.getState());if(!n)throw new Error("No current conversation to update");return o.updateConversation(n,t)}),gr=(0,be.createAsyncThunk)("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})})}),On=(0,be.createAsyncThunk)("conversation/postMessages",(t,e)=>{let{deepdeskAPI:o}=e.extra,n=An(e.getState());if(!n)throw new Error("No current conversation to update messages");return o.postMessages(n,t.map(s=>({...s})))}),Qp=[Ln.rejected,Mn.rejected,Nn.rejected,On.rejected].map(t=>t==null?void 0:t.toString()),Jp=(0,be.createSlice)({name:"conversation",initialState:ha,reducers:{},extraReducers:t=>{t.addCase(pr.fulfilled,(e,o)=>{e.isSupported=o.payload}).addCase(Ln.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(Mn.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(gr.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(Nn.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(On.fulfilled,(e,o)=>{e.current&&(e.current.messages=o.payload)}).addCase(_,()=>ha).addMatcher(e=>Qp.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)})}}),ya=Jp.reducer;var at={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 xa(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 Dn=(0,Ve.createAction)("input/replaceText"),Hn=(0,Ve.createAction)("input/keyDown"),At=(0,Ve.createAction)("input/sendMessage"),Fn=(0,Ve.createAction)("input/uiInputChange"),Bn=(0,Ve.createAction)("input/applyImageSuggestion"),Q=(0,Ve.createAction)("input/sendEvent");function _n(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 ba=(0,Ve.createSlice)({name:"input",initialState:at,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,{...at,selection:t.selection})},resetToCommitted(t){t.text=t.userCommitted.text,t.selection=t.userCommitted.selection,t.stagedSuggestion=null,t.tabCompletionSuggestion=ur(t.textSuggestions,t.userCommitted.text)},changeSelection(t,e){e.payload&&(it(t.selection,e.payload)||(t.selection=e.payload,t.userCommitted.selection=t.selection,t.stagedSuggestion&&_n(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=(0,va.diffChars)(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=at.metrics,t.textSuggestions=[],t.stagedSuggestion=null),t.text!==e.payload.text&&_n(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"&&_n(t)},commitSuggestion(t){_n(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=ur(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=at.tabCompletionSuggestion,e.previousKeyDownEvent=at.previousKeyDownEvent,e.textSuggestions=at.textSuggestions,e.selectedSuggestionIndex=at.selectedSuggestionIndex,e.metrics=at.metrics})}}),to=t=>t.input.userCommitted.text.substring(0,t.input.userCommitted.selection.end),Yp=t=>t.input.selection,Ca=()=>(0,Sa.useSelector)(Yp),{userInput:wa,changeSelection:mr,initialInput:Ta,nextTextSuggestionIndex:Ea,offeredTextSuggestion:ka,previousTextSuggestionIndex:Ra,registerCut:Pa,registerKeyDown:Ia,registerPaste:Aa,reset:La,resetToCommitted:Lo,platformInput:Ma,setSelectedTextSuggestionIndex:lt,setTextSuggestions:Me,stageSuggestion:Ne,commitSuggestion:$e,setMetrics:Na}=ba.actions,Oa=ba.reducer;var Un=require("@reduxjs/toolkit");var oo=require("@reduxjs/toolkit");function eg(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,[eg(o)]:L(t[o])}),{}):t}function fr(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function $(t){return Array.isArray(t)?t.map($):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,o)=>({...e,[fr(o)]:$(t[o])}),{}):t}var tg={agentInfo:void 0,agentSettings:{},visitorInfo:void 0,fetchState:"idle"},No=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)||""}},Mo=(0,oo.createAsyncThunk)("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))}),hr=(0,oo.createAsyncThunk)("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}),yr=(0,oo.createAsyncThunk)("info/getAgentSettings",async(t,e)=>{let{deepdeskAPI:o}=e.extra;return(await o.client.get("/apis/admin/session/me/",{version:null})).ui_config}),_a=t=>t.info.agentInfo,Da=(0,oo.createSlice)({name:"info",initialState:tg,reducers:{setVisitorInfo(t,e){t.visitorInfo={...t.visitorInfo,...e.payload}}},extraReducers:t=>{t.addCase(Mo.pending,(e,o)=>{e.fetchState="loading",e.agentInfo={...e.agentInfo,...o.meta.arg}}).addCase(Mo.rejected,e=>{e.fetchState="error"}).addCase(Mo.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(hr.fulfilled,(e,o)=>{e.agentSettings=o.payload}).addCase(yr.fulfilled,(e,o)=>{e.agentSettings=o.payload}).addCase(_,e=>{e.visitorInfo=void 0})}}),{setVisitorInfo:Ha}=Da.actions,Fa=Da.reducer;var Kn={list:[],fetchState:"idle",isOpen:!1,page:"search",aggregates:{}},Ba=t=>t.search.isOpen,Ka=t=>t.search.page,Ua=t=>t.search.list,za=t=>t.search.aggregates;function Va(t,e=o=>o){return o=>o.search.list.filter(n=>n.type===t).map(e)}var Lt=(0,Un.createAsyncThunk)("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:No(n)});return{results:r.map(l=>({...l,source:`search-${l.type.toLowerCase()}`,searchTerm:t.query})),aggregates:i}}),$a=(0,Un.createSlice)({name:"search",initialState:Kn,reducers:{setIsOpen(t,e){t.isOpen=e.payload},setPage(t,e){t.page=e.payload},resetSearch(t){t.fetchState=Kn.fetchState,t.list=Kn.list}},extraReducers:t=>{t.addCase(Lt.pending,e=>{e.fetchState="loading"}).addCase(Lt.rejected,(e,o)=>{e.fetchState="error",E.error(o.error)}).addCase(Lt.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload.results,e.aggregates=o.payload.aggregates||{}}).addCase(_,()=>Kn)}}),{resetSearch:zn,setIsOpen:de,setPage:Ce}=$a.actions,qa=$a.reducer;var no=require("@reduxjs/toolkit");var vr={cues:[],fetchState:"idle"},Ga=t=>{var e;return(e=t.rules)==null?void 0:e.cues},og=(0,no.createAction)("rules/resetCues"),qe=(0,no.createAsyncThunk)("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)}),ja=(0,no.createSlice)({name:"answer",initialState:vr,reducers:{removeCue(t,e){t.cues=t.cues.filter(o=>o.id!==e.payload.id)}},extraReducers:t=>{t.addCase(qe.pending,e=>{e.fetchState="loading"}).addCase(qe.rejected,e=>{e.fetchState="error"}).addCase(qe.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(_,()=>vr).addCase(og.toString(),()=>vr)}}),{removeCue:Wa}=ja.actions,Xa=ja.reducer;var Sr="SetCues",so="ShowLoginOverlay",Oo="UserLoggedIn",ng="UserLoggedOut",ct="ApplySuggestion",xr="ApplyImageSuggestion",sg="ShowCommandPalette",rg=t=>({[Sr]:e=>{t.dispatch({type:qe.fulfilled,payload:e})},[sg]:e=>{t.dispatch(de(e.isOpen)),e.page&&t.dispatch(Ce(e.page))},[so]:e=>{t.dispatch(pa(e))},[Oo]:()=>{t.dispatch(ze())},[ng]:()=>{t.dispatch(ze())},[xr]:e=>{t.dispatch(Bn({suggestion:e.suggestion}))},[ct]:e=>{t.dispatch(Ne({...e,eventMetrics:{inputType:"mouse"},replace:"selection"})),t.dispatch($e())}}),Za=rg;var _o=k(require("react")),Ja=require("react/jsx-runtime"),Qa=_o.default.createContext(null),Mt=({broadcastEvents:t,children:e})=>{let o=_o.default.useMemo(()=>t,[]);return(0,Ja.jsx)(Qa.Provider,{value:o,children:e})},we=()=>{let t=(0,_o.useContext)(Qa);if(!t)throw new Error("You should use the useBroadcastEvents within a BroadcastEventsProvider");return t};var rs=k(require("classnames")),Ee=require("react"),is=require("react-redux");var os=require("react");var br=function(t,e){return br=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])},br(t,e)};function Do(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");br(t,e);function o(){this.constructor=t}t.prototype=e===null?Object.create(e):(o.prototype=e.prototype,new o)}var ue=function(){return ue=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},ue.apply(this,arguments)};function Ya(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 Vn(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 $n;(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"})($n||($n={}));var qn=class{constructor(e){console.warn(`[vite-messages-plugin]: Message "${e}" was not precompiled. Did you use the correct extenstion *.messages.ts?`)}};var Te;(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"})(Te||(Te={}));var Gn;(function(t){t[t.number=0]="number",t[t.dateTime=1]="dateTime"})(Gn||(Gn={}));function Cr(t){return t.type===Te.literal}function el(t){return t.type===Te.argument}function jn(t){return t.type===Te.number}function Wn(t){return t.type===Te.date}function Xn(t){return t.type===Te.time}function Zn(t){return t.type===Te.select}function Qn(t){return t.type===Te.plural}function tl(t){return t.type===Te.pound}function Jn(t){return t.type===Te.tag}function Yn(t){return!!(t&&typeof t=="object"&&t.type===Gn.number)}function Ho(t){return!!(t&&typeof t=="object"&&t.type===Gn.dateTime)}function wr(t){t.forEach(function(e){if(delete e.location,Zn(e)||Qn(e))for(var o in e.options)delete e.options[o].location,wr(e.options[o].value);else jn(e)&&Yn(e.style)||(Wn(e)||Xn(e))&&Ho(e.style)?delete e.style.location:Jn(e)&&wr(e.children)})}function ol(t,e){e===void 0&&(e={}),e=ue({shouldParseSkeletons:!0,requiresOtherClause:!0},e);var o=new qn(t,e).parse();if(o.err){var n=SyntaxError($n[o.err.kind]);throw n.location=o.err.location,n.originalMessage=o.err.message,n}return e!=null&&e.captureLocation||wr(o.val),o.val}function es(t,e){var o=e&&e.cache?e.cache:ug,n=e&&e.serializer?e.serializer:dg,s=e&&e.strategy?e.strategy:ag;return s(t,{cache:o,serializer:n})}function ig(t){return t==null||typeof t=="number"||typeof t=="boolean"}function nl(t,e,o,n){var s=ig(n)?n:o(n),r=e.get(s);return typeof r>"u"&&(r=t.call(this,n),e.set(s,r)),r}function sl(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 Tr(t,e,o,n,s){return o.bind(e,t,n,s)}function ag(t,e){var o=t.length===1?nl:sl;return Tr(t,this,o,e.cache.create(),e.serializer)}function lg(t,e){return Tr(t,this,sl,e.cache.create(),e.serializer)}function cg(t,e){return Tr(t,this,nl,e.cache.create(),e.serializer)}var dg=function(){return JSON.stringify(arguments)};function Er(){this.cache=Object.create(null)}Er.prototype.get=function(t){return this.cache[t]};Er.prototype.set=function(t,e){this.cache[t]=e};var ug={create:function(){return new Er}},ts={variadic:lg,monadic:cg};var Nt;(function(t){t.MISSING_VALUE="MISSING_VALUE",t.INVALID_VALUE="INVALID_VALUE",t.MISSING_INTL_API="MISSING_INTL_API"})(Nt||(Nt={}));var Fo=function(t){Do(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 kr=function(t){Do(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('", "'),'"'),Nt.INVALID_VALUE,r)||this}return e}(Fo);var rl=function(t){Do(e,t);function e(o,n,s){return t.call(this,'Value for "'.concat(o,'" must be of type ').concat(n),Nt.INVALID_VALUE,s)||this}return e}(Fo);var il=function(t){Do(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,'"'),Nt.MISSING_VALUE,n)||this}return e}(Fo);var J;(function(t){t[t.literal=0]="literal",t[t.object=1]="object"})(J||(J={}));function pg(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 gg(t){return typeof t=="function"}function Bo(t,e,o,n,s,r,i){if(t.length===1&&Cr(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(Cr(d)){a.push({type:J.literal,value:d.value});continue}if(tl(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 il(u,i);var p=s[u];if(el(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(Wn(d)){var g=typeof d.style=="string"?n.date[d.style]:Ho(d.style)?d.style.parsedOptions:void 0;a.push({type:J.literal,value:o.getDateTimeFormat(e,g).format(p)});continue}if(Xn(d)){var g=typeof d.style=="string"?n.time[d.style]:Ho(d.style)?d.style.parsedOptions:n.time.medium;a.push({type:J.literal,value:o.getDateTimeFormat(e,g).format(p)});continue}if(jn(d)){var g=typeof d.style=="string"?n.number[d.style]:Yn(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(Jn(d)){var f=d.children,m=d.value,S=s[m];if(!gg(S))throw new rl(m,"function",i);var w=Bo(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(Zn(d)){var y=d.options[p]||d.options.other;if(!y)throw new kr(d.value,p,Object.keys(d.options),i);a.push.apply(a,Bo(y.value,e,o,n,s));continue}if(Qn(d)){var y=d.options["=".concat(p)];if(!y){if(!Intl.PluralRules)throw new Fo(`Intl.PluralRules is not available in this environment.
1
+ "use strict";var Lp=Object.create;var yn=Object.defineProperty;var Ap=Object.getOwnPropertyDescriptor;var Mp=Object.getOwnPropertyNames;var Np=Object.getPrototypeOf,Op=Object.prototype.hasOwnProperty;var Y=(t,e)=>{for(var o in e)yn(t,o,{get:e[o],enumerable:!0})},zi=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Mp(e))!Op.call(t,s)&&s!==o&&yn(t,s,{get:()=>e[s],enumerable:!(n=Ap(e,s))||n.enumerable});return t};var k=(t,e,o)=>(o=t!=null?Lp(Np(t)):{},zi(e||!t||!t.__esModule?yn(o,"default",{value:t,enumerable:!0}):o,t)),_p=t=>zi(yn({},"__esModule",{value:!0}),t);var Dh={};Y(Dh,{Card:()=>H,ContentEditableInput:()=>qt,DeepdeskAPI:()=>nt,DeepdeskSDK:()=>hn,HTTPClient:()=>Ae,InputMediator:()=>ot,InputType:()=>kt,KeyboardHint:()=>Cn,Label:()=>wn,Locale:()=>Ro,Section:()=>Ke,SectionList:()=>Tn,Sources:()=>Ue,Suggestion:()=>N,SuggestionList:()=>le,TextAreaInput:()=>Gt,ToggleButton:()=>Et,attachFile:()=>Rp,authenticateWithKey:()=>Ep,createFullRange:()=>bo,createOverlayContainer:()=>fn,createRangeFromOffsets:()=>xt,escapeHTML:()=>no,fetchPlatformConfig:()=>kp,formatTextMarkup:()=>Tp,getRangeOffsets:()=>un,getRangeText:()=>pn,insertCKEditor:()=>wp,isHTML:()=>ls,isSupportedInputElement:()=>sr,updateContentEditable:()=>bp,updateTextArea:()=>xp,useStyles:()=>h,waitForElementVisibilityChange:()=>ar});module.exports=_p(Dh);var ur=k(require("classnames")),fe=k(require("react"));var vn=k(require("react")),Vi=k(require("classnames")),ko=vn.default.createContext({});function h(t,e){let{debug:o,...n}=(0,vn.useContext)(ko),s=n[t];return s?Object.entries(e).reduce((r,[i,a])=>{let l=s[i];return{...r,[i]:(0,Vi.default)(a,l,o?`${t}__${i}`:!1)}},{}):e}var $i={root:"jo"};var bt=require("react/jsx-runtime"),Sn=()=>(0,bt.jsxs)("svg",{className:$i.root,width:"185",height:"170",viewBox:"0 0 185 170",xmlns:"http://www.w3.org/2000/svg",children:[(0,bt.jsx)("defs",{children:(0,bt.jsx)("style",{children:".cls-1 { fill: #b3b3b3; }"})}),(0,bt.jsx)("title",{children:"Failed loading image"}),(0,bt.jsx)("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 dr={root:"Yo",imageWrapper:"F",image:"qo",content:"m",title:"Co",contentIsCropped:"So",lineClamp:"Eo"};var Ct=require("react/jsx-runtime"),xn=(0,fe.createContext)(dr),Fp=({title:t,src:e})=>{let o=(0,fe.useContext)(xn),[n,s]=(0,fe.useState)(!1);return(0,fe.useEffect)(()=>{s(!1)},[e]),(0,Ct.jsx)("div",{className:o.imageWrapper,children:e&&!n?(0,Ct.jsx)("img",{className:o.image,alt:t,src:e,onError:()=>s(!0)}):(0,Ct.jsx)(Sn,{})})},Bp=({className:t,lineClamp:e=!1,cropText:o=!1,children:n})=>{let s=(0,fe.useContext)(xn);return(0,Ct.jsx)("div",{className:(0,ur.default)(s.content,t,{[s.contentIsCropped]:o,[s.lineClamp]:e}),children:n})},Kp=({as:t="h1",cropText:e=!1,className:o,children:n,...s})=>{let r=(0,fe.useContext)(xn);return fe.default.createElement(t,{className:(0,ur.default)(r.title,o,{[r.contentIsCropped]:e}),...s},n)},bn=({children:t})=>{let e=h("Card",dr);return(0,Ct.jsx)("div",{className:e.root,children:(0,Ct.jsx)(xn.Provider,{value:e,children:t})})};bn.Image=Fp;bn.Content=Bp;bn.Title=Kp;var H=bn;var Gi=k(require("classnames"));var qi={root:"H"};var ji=require("react/jsx-runtime");var zp={"arrow-up":"\u25B2","arrow-down":"\u25BC",tab:"tab",esc:"Esc",enter:"\u21B5"},Vp=({className:t,keyCode:e,...o})=>{let n=h("KeyboardHint",qi);return(0,ji.jsx)("span",{"data-key":zp[e],className:(0,Gi.default)(t,n.root),...o})},Cn=Vp;var Xi=k(require("classnames"));var Wi={root:"Go"};var Zi=require("react/jsx-runtime"),qp=({className:t,children:e,...o})=>{let n=h("Label",Wi);return(0,Zi.jsx)("span",{...o,className:(0,Xi.default)(t,n.root),children:e})},wn=qp;var Qi={root:"No",subTitleContainer:"Ao",subtitle:"Fo",suggestions:"Ho"};var Xt=require("react/jsx-runtime"),jp=({title:t,children:e,type:o,...n})=>{let s=h("Section",Qi);return(0,Xt.jsxs)("section",{...n,className:s.root,"data-section-type":o,children:[t&&(0,Xt.jsx)("div",{className:s.subTitleContainer,children:(0,Xt.jsx)("span",{className:s.subtitle,children:t})}),(0,Xt.jsx)("div",{className:s.suggestions,children:e})]})},Ke=jp;var Yi=k(require("classnames")),ea=k(require("react"));var Ji={root:"Lo"};var ta=require("react/jsx-runtime"),Xp=ea.default.forwardRef(({className:t,children:e},o)=>{let n=h("SectionList",Ji);return(0,ta.jsx)("div",{ref:o,className:(0,Yi.default)(n.root,t),children:e})}),Tn=Xp;var Zt=k(require("classnames")),ee=k(require("react"));var pr={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"};var se=require("react/jsx-runtime"),wt=(0,ee.createContext)(pr),Qp=({fixed:t,children:e,...o})=>{let n=(0,ee.useContext)(wt);return(0,se.jsx)("div",{...o,className:(0,Zt.default)(n.actions,{[n.actionsIsFixed]:t}),children:e})};function oa(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type===na}var na=({className:t,icon:e,title:o,...n})=>{let s=(0,ee.useContext)(wt);return(0,se.jsx)("button",{type:"button",className:(0,Zt.default)(s.iconButton,t),title:o,"aria-label":o,...n,children:e})},Jp=({className:t,primary:e,disabled:o,label:n,children:s})=>{let r=(0,ee.useContext)(wt);return(0,se.jsxs)("div",{className:(0,Zt.default)(t,r.actionButton,r.dropdownButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:o}),onMouseDown:i=>i.stopPropagation(),onClick:i=>i.stopPropagation(),children:[n,(0,se.jsx)("ul",{className:r.dropdownList,children:s})]})},Yp=({index:t,label:e,onClick:o})=>{let n=(0,ee.useContext)(wt);return(0,se.jsx)("li",{className:n.dropdownItem,children:(0,se.jsx)("button",{className:n.dropdownItemButton,type:"button","data-index":t,onClick:o,children:e})})},eg=({className:t,primary:e,disabled:o,onClick:n,label:s})=>{let r=(0,ee.useContext)(wt);return(0,se.jsx)("button",{type:"button",className:(0,Zt.default)(t,r.actionButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:o}),onClick:n??(i=>i.stopPropagation()),disabled:o,"aria-hidden":o,children:s})},tg=({labels:t})=>{let e=(0,ee.useContext)(wt);return(0,se.jsx)("div",{className:e.labels,children:t.map(o=>(0,se.jsx)("span",{className:e.label,children:o},o))})},Tt=ee.default.forwardRef(({className:t,selected:e,onClick:o,children:n,as:s="div",...r},i)=>{let a=h("Suggestion",pr),l=(0,ee.useCallback)(u=>{u.preventDefault(),o&&o(u)},[o]),c=ee.default.Children.toArray(n).filter(oa),d=ee.default.Children.toArray(n).filter(u=>!oa(u));return(0,se.jsx)(s,{...r,ref:i,className:(0,Zt.default)(t,a.root,{[a.isSelected]:e,[a.isClickable]:!!o}),onClick:l,children:(0,se.jsxs)(wt.Provider,{value:a,children:[d,(0,se.jsx)("div",{className:a.iconButtons,children:c})]})})});Tt.Labels=tg;Tt.Actions=Qp;Tt.ActionButton=eg;Tt.DropdownButton=Jp;Tt.DropdownItem=Yp;Tt.IconButton=na;var N=Tt;var ra=k(require("classnames"));var sa={root:"Io",isWithDivider:"Oo"};var ia=require("react/jsx-runtime"),ng=({withDivider:t,children:e})=>{let o=h("SuggestionList",sa);return(0,ia.jsx)("div",{"data-testid":"suggestions-overlay-list",className:(0,ra.default)(o.root,{[o.isWithDivider]:t}),children:e})},le=ng;var la=k(require("classnames"));var aa={root:"u",isCollapsed:"O"};var En=require("react/jsx-runtime"),rg=({className:t,isCollapsed:e,title:o,onClick:n})=>{let s=h("ToggleButton",aa);return(0,En.jsx)("button",{type:"button",className:(0,la.default)(s.root,t,{[s.isCollapsed]:e}),onClick:n,title:o,children:(0,En.jsx)("svg",{width:"14",height:"8",viewBox:"-2.5 -5 75 60",preserveAspectRatio:"none",children:(0,En.jsx)("path",{d:"M0,0 l35,50 l35,-50",fill:"none",stroke:"grey",strokeLinecap:"round",strokeWidth:"6"})})})},Et=rg;var ca=/(?:[.,;:!?\\n]|:\\)|:\\(|:-\\)|:-\\()/g,kn=/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\})/g;var da=/x-deepdesk-(([a-z0-9\-_])+-version)/,Ue=(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))(Ue||{}),kt=(r=>(r.ENTER="enter",r.TAB="tab",r.ARROW="arrow",r.HOTKEY="hotkey",r.MOUSE="mouse",r))(kt||{});var be=require("react-dom");var wc=require("react");var ua=require("@reduxjs/toolkit"),pa=require("react-redux");var Ro=(o=>(o.NL_NL="nl-NL",o.EN_US="en-US",o))(Ro||{});var ig={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"},ga=(0,ua.createSlice)({name:"settings",initialState:ig,reducers:{set(t,e){Object.entries(e.payload).forEach(o=>{let[n,s]=o;typeof s>"u"||(t[n]=s)})}}}),{set:Rn}=ga.actions,gr=t=>e=>e.settings[t],b=t=>(0,pa.useSelector)(gr(t)),ma=ga.reducer;var Nr=require("react-redux");var Qt=require("@reduxjs/toolkit");var ag={isLoggedIn:!0,loginFetchState:"idle",verifyFetchState:"idle",showLoginOverlay:!1},te=t=>t.auth.isLoggedIn,fa=t=>t.auth.loginFetchState,ha=t=>t.auth.verifyFetchState,ya=t=>t.auth.showLoginOverlay,ze=(0,Qt.createAsyncThunk)("auth/validate",async(t,e)=>e.extra.deepdeskAPI.isLoggedIn()),va=(0,Qt.createAsyncThunk)("auth/requestLogin",async({email:t},e)=>{let{deepdeskAPI:o}=e.extra;return o.requestLoginByEmail(t)}),Po=(0,Qt.createAsyncThunk)("auth/verifyLoginToken",async({token:t},e)=>{let{deepdeskAPI:o}=e.extra;return o.verifyLoginToken(t)}),Sa=(0,Qt.createSlice)({name:"auth",initialState:ag,reducers:{setIsLoggedIn(t,e){t.isLoggedIn=e.payload},setShowLoginOverlay(t,e){t.showLoginOverlay=e.payload}},extraReducers:t=>{t.addCase(ze.pending,e=>{e.loginFetchState="loading"}),t.addCase(ze.fulfilled,(e,{payload:o})=>{e.isLoggedIn=o,e.loginFetchState="done"}),t.addCase(ze.rejected,e=>{e.loginFetchState="error",e.isLoggedIn=!1}),t.addCase(Po.pending,e=>{e.verifyFetchState="loading"}),t.addCase(Po.rejected,e=>{e.verifyFetchState="error"}),t.addCase(Po.fulfilled,(e,o)=>{o.payload.isLoggedIn?e.verifyFetchState="done":e.verifyFetchState="error"})}}),{setIsLoggedIn:Jt,setShowLoginOverlay:xa}=Sa.actions,ba=Sa.reducer;var Ve=require("@reduxjs/toolkit"),ka=require("diff"),Ra=require("react-redux");function Ca(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function st(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)=>st(r,e[i],o-1)):Ca(t)&&Ca(e)?Object.keys(t).length!==Object.keys(e).length?!1:Object.keys(t).every(i=>st(t[i],e[i],o-1)):!1}function lg(t){return Math.max(...t.map(e=>e.length))}function cg(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 wa(t,e){let n=[...t.map(({text:s})=>s.split(/\b(\w+)\b/))];for(let s=0;s<lg(n);s++){let r=cg(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 dg=2;function mr(t,e=""){if(t.length===0)return;if(t.length===1)return t[0];let o=wa(t,dg);return o&&o.text!==e?o:t[0]}var Ce=require("@reduxjs/toolkit");var ug={info(...t){console.info("[Deepdesk]",...t)},warn(...t){console.warn("[Deepdesk]",...t)},error(...t){console.error("[Deepdesk]",...t)}},T=ug;var Ta={current:null,isSupported:null},D=(0,Ce.createAction)("resetConversation"),Pn=t=>{let{current:e}=t.conversation;return(e==null?void 0:e.sessionId)||null},In=t=>{let{current:e}=t.conversation;return(e==null?void 0:e.id)||null},Yt=t=>t.conversation.isSupported,fr=(0,Ce.createAsyncThunk)("conversation/isSupported",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.isConversationSupported(t.sessionId,t.options)}),Ln=(0,Ce.createAsyncThunk)("conversation/create",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.createConversation(t)}),An=(0,Ce.createAsyncThunk)("conversation/bySessionId",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.getConversationBySessionId(t.sessionId,t.options)}),Mn=(0,Ce.createAsyncThunk)("conversation/update",(t,e)=>{let{deepdeskAPI:o}=e.extra,n=In(e.getState());if(!n)throw new Error("No current conversation to update");return o.updateConversation(n,t)}),hr=(0,Ce.createAsyncThunk)("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})})}),Nn=(0,Ce.createAsyncThunk)("conversation/postMessages",(t,e)=>{let{deepdeskAPI:o}=e.extra,n=In(e.getState());if(!n)throw new Error("No current conversation to update messages");return o.postMessages(n,t.map(s=>({...s})))}),pg=[Ln.rejected,An.rejected,Mn.rejected,Nn.rejected].map(t=>t==null?void 0:t.toString()),gg=(0,Ce.createSlice)({name:"conversation",initialState:Ta,reducers:{},extraReducers:t=>{t.addCase(fr.fulfilled,(e,o)=>{e.isSupported=o.payload}).addCase(Ln.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(An.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(hr.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(Mn.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(Nn.fulfilled,(e,o)=>{e.current&&(e.current.messages=o.payload)}).addCase(D,()=>Ta).addMatcher(e=>pg.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)})}}),Ea=gg.reducer;var rt={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 Pa(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 _n=(0,Ve.createAction)("input/replaceText"),Dn=(0,Ve.createAction)("input/keyDown"),Rt=(0,Ve.createAction)("input/sendMessage"),Hn=(0,Ve.createAction)("input/uiInputChange"),Fn=(0,Ve.createAction)("input/applyImageSuggestion"),Q=(0,Ve.createAction)("input/sendEvent");function On(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 Ia=(0,Ve.createSlice)({name:"input",initialState:rt,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,{...rt,selection:t.selection})},resetToCommitted(t){t.text=t.userCommitted.text,t.selection=t.userCommitted.selection,t.stagedSuggestion=null,t.tabCompletionSuggestion=mr(t.textSuggestions,t.userCommitted.text)},changeSelection(t,e){e.payload&&(st(t.selection,e.payload)||(t.selection=e.payload,t.userCommitted.selection=t.selection,t.stagedSuggestion&&On(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=(0,ka.diffChars)(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=rt.metrics,t.textSuggestions=[],t.stagedSuggestion=null),t.text!==e.payload.text&&On(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"&&On(t)},commitSuggestion(t){On(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=mr(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(D,e=>{e.tabCompletionSuggestion=rt.tabCompletionSuggestion,e.previousKeyDownEvent=rt.previousKeyDownEvent,e.textSuggestions=rt.textSuggestions,e.selectedSuggestionIndex=rt.selectedSuggestionIndex,e.metrics=rt.metrics})}}),eo=t=>t.input.userCommitted.text.substring(0,t.input.userCommitted.selection.end),mg=t=>t.input.selection,La=()=>(0,Ra.useSelector)(mg),{userInput:Aa,changeSelection:yr,initialInput:Ma,nextTextSuggestionIndex:Na,offeredTextSuggestion:Oa,previousTextSuggestionIndex:_a,registerCut:Da,registerKeyDown:Ha,registerPaste:Fa,reset:Ba,resetToCommitted:Io,platformInput:Ka,setSelectedTextSuggestionIndex:it,setTextSuggestions:Me,stageSuggestion:Ne,commitSuggestion:$e,setMetrics:Ua}=Ia.actions,za=Ia.reducer;var Kn=require("@reduxjs/toolkit");var to=require("@reduxjs/toolkit");function fg(t){return t.replace(/(_\w)/g,e=>e[1].toUpperCase())}function M(t){return Array.isArray(t)?t.map(M):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,o)=>({...e,[fg(o)]:M(t[o])}),{}):t}function vr(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function V(t){return Array.isArray(t)?t.map(V):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,o)=>({...e,[vr(o)]:V(t[o])}),{}):t}var hg={agentInfo:void 0,agentSettings:{},visitorInfo:void 0,fetchState:"idle"},Ao=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)||""}},Lo=(0,to.createAsyncThunk)("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?M(n):(await o.client.patch("/apis/admin/session/me/",s,{version:null}),M(n))}),Sr=(0,to.createAsyncThunk)("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}),xr=(0,to.createAsyncThunk)("info/getAgentSettings",async(t,e)=>{let{deepdeskAPI:o}=e.extra;return(await o.client.get("/apis/admin/session/me/",{version:null})).ui_config}),Va=t=>t.info.agentInfo,$a=(0,to.createSlice)({name:"info",initialState:hg,reducers:{setVisitorInfo(t,e){t.visitorInfo={...t.visitorInfo,...e.payload}}},extraReducers:t=>{t.addCase(Lo.pending,(e,o)=>{e.fetchState="loading",e.agentInfo={...e.agentInfo,...o.meta.arg}}).addCase(Lo.rejected,e=>{e.fetchState="error"}).addCase(Lo.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(Sr.fulfilled,(e,o)=>{e.agentSettings=o.payload}).addCase(xr.fulfilled,(e,o)=>{e.agentSettings=o.payload}).addCase(D,e=>{e.visitorInfo=void 0})}}),{setVisitorInfo:qa}=$a.actions,Ga=$a.reducer;var Bn={list:[],fetchState:"idle",isOpen:!1,page:"search",aggregates:{}},ja=t=>t.search.isOpen,Wa=t=>t.search.page,Xa=t=>t.search.list,Za=t=>t.search.aggregates;function Qa(t,e=o=>o){return o=>o.search.list.filter(n=>n.type===t).map(e)}var Pt=(0,Kn.createAsyncThunk)("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:Ao(n)});return{results:r.map(l=>({...l,source:`search-${l.type.toLowerCase()}`,searchTerm:t.query})),aggregates:i}}),Ja=(0,Kn.createSlice)({name:"search",initialState:Bn,reducers:{setIsOpen(t,e){t.isOpen=e.payload},setPage(t,e){t.page=e.payload},resetSearch(t){t.fetchState=Bn.fetchState,t.list=Bn.list}},extraReducers:t=>{t.addCase(Pt.pending,e=>{e.fetchState="loading"}).addCase(Pt.rejected,(e,o)=>{e.fetchState="error",T.error(o.error)}).addCase(Pt.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload.results,e.aggregates=o.payload.aggregates||{}}).addCase(D,()=>Bn)}}),{resetSearch:Un,setIsOpen:ce,setPage:we}=Ja.actions,Ya=Ja.reducer;var br="SetCues",oo="ShowLoginOverlay",Mo="UserLoggedIn",yg="UserLoggedOut",at="ApplySuggestion",Cr="ApplyImageSuggestion",vg="ShowCommandPalette",Sg=t=>({[br]:e=>{t.dispatch({...e,isBroadcasted:!0})},[vg]:e=>{t.dispatch(ce(e.isOpen)),e.page&&t.dispatch(we(e.page))},[oo]:e=>{t.dispatch(xa(e))},[Mo]:()=>{t.dispatch(ze())},[yg]:()=>{t.dispatch(ze())},[Cr]:e=>{t.dispatch(Fn({suggestion:e.suggestion}))},[at]:e=>{t.dispatch(Ne({...e,eventMetrics:{inputType:"mouse"},replace:"selection"})),t.dispatch($e())}}),el=Sg;var No=k(require("react")),ol=require("react/jsx-runtime"),tl=No.default.createContext(null),It=({broadcastEvents:t,children:e})=>{let o=No.default.useMemo(()=>t,[]);return(0,ol.jsx)(tl.Provider,{value:o,children:e})},he=()=>{let t=(0,No.useContext)(tl);if(!t)throw new Error("You should use the useBroadcastEvents within a BroadcastEventsProvider");return t};var ss=k(require("classnames")),Ee=require("react"),rs=require("react-redux");var ts=require("react");var wr=function(t,e){return wr=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])},wr(t,e)};function Oo(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");wr(t,e);function o(){this.constructor=t}t.prototype=e===null?Object.create(e):(o.prototype=e.prototype,new o)}var de=function(){return de=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},de.apply(this,arguments)};function nl(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 zn(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 Vn;(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"})(Vn||(Vn={}));var $n=class{constructor(e){console.warn(`[vite-messages-plugin]: Message "${e}" was not precompiled. Did you use the correct extenstion *.messages.ts?`)}};var Te;(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"})(Te||(Te={}));var qn;(function(t){t[t.number=0]="number",t[t.dateTime=1]="dateTime"})(qn||(qn={}));function Tr(t){return t.type===Te.literal}function sl(t){return t.type===Te.argument}function Gn(t){return t.type===Te.number}function jn(t){return t.type===Te.date}function Wn(t){return t.type===Te.time}function Xn(t){return t.type===Te.select}function Zn(t){return t.type===Te.plural}function rl(t){return t.type===Te.pound}function Qn(t){return t.type===Te.tag}function Jn(t){return!!(t&&typeof t=="object"&&t.type===qn.number)}function _o(t){return!!(t&&typeof t=="object"&&t.type===qn.dateTime)}function Er(t){t.forEach(function(e){if(delete e.location,Xn(e)||Zn(e))for(var o in e.options)delete e.options[o].location,Er(e.options[o].value);else Gn(e)&&Jn(e.style)||(jn(e)||Wn(e))&&_o(e.style)?delete e.style.location:Qn(e)&&Er(e.children)})}function il(t,e){e===void 0&&(e={}),e=de({shouldParseSkeletons:!0,requiresOtherClause:!0},e);var o=new $n(t,e).parse();if(o.err){var n=SyntaxError(Vn[o.err.kind]);throw n.location=o.err.location,n.originalMessage=o.err.message,n}return e!=null&&e.captureLocation||Er(o.val),o.val}function Yn(t,e){var o=e&&e.cache?e.cache:Eg,n=e&&e.serializer?e.serializer:Tg,s=e&&e.strategy?e.strategy:bg;return s(t,{cache:o,serializer:n})}function xg(t){return t==null||typeof t=="number"||typeof t=="boolean"}function al(t,e,o,n){var s=xg(n)?n:o(n),r=e.get(s);return typeof r>"u"&&(r=t.call(this,n),e.set(s,r)),r}function ll(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 kr(t,e,o,n,s){return o.bind(e,t,n,s)}function bg(t,e){var o=t.length===1?al:ll;return kr(t,this,o,e.cache.create(),e.serializer)}function Cg(t,e){return kr(t,this,ll,e.cache.create(),e.serializer)}function wg(t,e){return kr(t,this,al,e.cache.create(),e.serializer)}var Tg=function(){return JSON.stringify(arguments)};function Rr(){this.cache=Object.create(null)}Rr.prototype.get=function(t){return this.cache[t]};Rr.prototype.set=function(t,e){this.cache[t]=e};var Eg={create:function(){return new Rr}},es={variadic:Cg,monadic:wg};var Lt;(function(t){t.MISSING_VALUE="MISSING_VALUE",t.INVALID_VALUE="INVALID_VALUE",t.MISSING_INTL_API="MISSING_INTL_API"})(Lt||(Lt={}));var Do=function(t){Oo(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 Pr=function(t){Oo(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('", "'),'"'),Lt.INVALID_VALUE,r)||this}return e}(Do);var cl=function(t){Oo(e,t);function e(o,n,s){return t.call(this,'Value for "'.concat(o,'" must be of type ').concat(n),Lt.INVALID_VALUE,s)||this}return e}(Do);var dl=function(t){Oo(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,'"'),Lt.MISSING_VALUE,n)||this}return e}(Do);var J;(function(t){t[t.literal=0]="literal",t[t.object=1]="object"})(J||(J={}));function kg(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 Rg(t){return typeof t=="function"}function Ho(t,e,o,n,s,r,i){if(t.length===1&&Tr(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(Tr(d)){a.push({type:J.literal,value:d.value});continue}if(rl(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 dl(u,i);var g=s[u];if(sl(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(jn(d)){var p=typeof d.style=="string"?n.date[d.style]:_o(d.style)?d.style.parsedOptions:void 0;a.push({type:J.literal,value:o.getDateTimeFormat(e,p).format(g)});continue}if(Wn(d)){var p=typeof d.style=="string"?n.time[d.style]:_o(d.style)?d.style.parsedOptions:n.time.medium;a.push({type:J.literal,value:o.getDateTimeFormat(e,p).format(g)});continue}if(Gn(d)){var p=typeof d.style=="string"?n.number[d.style]:Jn(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(Qn(d)){var f=d.children,m=d.value,y=s[m];if(!Rg(y))throw new cl(m,"function",i);var E=Ho(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(Xn(d)){var v=d.options[g]||d.options.other;if(!v)throw new Pr(d.value,g,Object.keys(d.options),i);a.push.apply(a,Ho(v.value,e,o,n,s));continue}if(Zn(d)){var v=d.options["=".concat(g)];if(!v){if(!Intl.PluralRules)throw new Do(`Intl.PluralRules is not available in this environment.
2
2
  Try polyfilling it using "@formatjs/intl-pluralrules"
3
- `,Nt.MISSING_INTL_API,i);var R=o.getPluralRules(e,{type:d.pluralType}).select(p-(d.offset||0));y=d.options[R]||d.options.other}if(!y)throw new kr(d.value,p,Object.keys(d.options),i);a.push.apply(a,Bo(y.value,e,o,n,s,p-(d.offset||0)));continue}}return pg(a)}function mg(t,e){return e?ue(ue(ue({},t||{}),e||{}),Object.keys(t).reduce(function(o,n){return o[n]=ue(ue({},t[n]),e[n]||{}),o},{})):t}function fg(t,e){return e?Object.keys(t).reduce(function(o,n){return o[n]=mg(t[n],e[n]),o},ue({},t)):t}function Rr(t){return{create:function(){return{get:function(e){return t[e]},set:function(e,o){t[e]=o}}}}}function hg(t){return t===void 0&&(t={number:{},dateTime:{},pluralRules:{}}),{getNumberFormat:es(function(){for(var e,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];return new((e=Intl.NumberFormat).bind.apply(e,Vn([void 0],o,!1)))},{cache:Rr(t.number),strategy:ts.variadic}),getDateTimeFormat:es(function(){for(var e,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];return new((e=Intl.DateTimeFormat).bind.apply(e,Vn([void 0],o,!1)))},{cache:Rr(t.dateTime),strategy:ts.variadic}),getPluralRules:es(function(){for(var e,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];return new((e=Intl.PluralRules).bind.apply(e,Vn([void 0],o,!1)))},{cache:Rr(t.pluralRules),strategy:ts.variadic})}}var al=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 Bo(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=Ya(i,["formatters"]);this.ast=t.__parse(e,ue(ue({},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=fg(t.formats,n),this.formatters=s&&s.formatters||hg(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=ol,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 yg(t,e){return e.split(".").reduce((o,n)=>o?o[n]:void 0,t)}var vg="dummy",Pr=(0,os.createContext)(null);function P(t){let e=(0,os.useContext)(Pr);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=yg(o,n);return r?new al(r).format(s):(e!==vg&&console.warn(`${n} does not exist in messages of ${e}`),`[${n}]`)}}var ns=require("react");var ll={root:"U",content:"To"};var Ir=require("react/jsx-runtime"),xg=({isOpen:t,autoFocus:e,children:o,onClose:n,onBack:s,onKeyDown:r,overlayAriaLabel:i,contentAriaLabel:a})=>{let l=(0,ns.useRef)(null),c=h("Dialog",ll),d=p=>{if(p.key==="Escape"){p.preventDefault(),p.stopPropagation(),s();return}r&&r(p)},u=p=>{p.target===l.current&&t&&n()};return(0,ns.useEffect)(()=>{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?(0,Ir.jsx)("div",{role:"dialog","data-testid":"dialog",className:c.root,"aria-label":i,ref:l,onKeyDown:d,onMouseDown:u,children:(0,Ir.jsx)("div",{"data-testid":"dialog-content",className:c.content,"aria-label":a,children:o})}):null},ss=xg;var dl=k(require("classnames"));var cl={root:"y"};var ul=require("react/jsx-runtime"),Cg=({className:t,value:e,...o})=>{let n=h("TextInput",cl);return(0,ul.jsx)("input",{className:(0,dl.default)(t,n.root),type:"text",value:e,...o})},Ko=Cg;var Ar={};Y(Ar,{enUS:()=>wg,nlNL:()=>Tg});var wg={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"}]},Tg={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 pl={root:"Uo",anchorButton:"Bo",errorMessage:"Do",title:"Io",subtitle:"Oo",text:"Xo",input:"Jo",actions:"Ko",button:"w",primaryButton:"Po"};var z=require("react/jsx-runtime");var kg=t=>{try{let e=new URL(t);return new URLSearchParams(e.search).get("token")||void 0}catch{return t}},Rg=({agentEmail:t,isOpen:e,origin:o="",onSuccess:n,onDismiss:s})=>{let r=P(Ar),i=h("LoginTokenDialog",pl),a=(0,is.useSelector)(la),l=(0,is.useDispatch)(),c=C("productName"),[d,u]=(0,Ee.useState)(t||""),[p,g]=(0,Ee.useState)(0),[f,m]=(0,Ee.useState)(""),S=(0,Ee.useCallback)(async R=>{R.preventDefault(),l(da({email:d})),g(1)},[o,d]),w=()=>{m(""),g(0)},v=(0,Ee.useCallback)(async R=>{R.preventDefault();let x=kg(R.target.elements.token.value);if(!x){m(r("verifyCodeError",{login:y}));return}l(Ao({token:x}))},[o]),y=(0,Ee.useMemo)(()=>R=>(0,z.jsx)("button",{type:"button","data-testid":"login-token-dialog-back-button",className:i.anchorButton,onClick:w,children:R},"back-button"),[]);return(0,Ee.useEffect)(()=>{a==="error"&&m(r("verifyCodeError",{login:y})),a==="done"&&n()},[a]),(0,z.jsx)(ss,{autoFocus:!0,isOpen:e,contentAriaLabel:r("promptTitle",{productName:c}),overlayAriaLabel:r("promptTitle",{productName:c}),onClose:s,onBack:s,children:(0,z.jsxs)("div",{className:i.root,children:[(0,z.jsx)("h1",{className:i.title,children:r("promptTitle",{productName:c})}),p===0&&(0,z.jsxs)("form",{onSubmit:S,children:[(0,z.jsx)("h2",{className:i.subtitle,children:r("requestCodeTitle")}),(0,z.jsx)("p",{className:i.text,children:r("requestCodeBody",{productName:c})}),(0,z.jsx)(Ko,{className:i.input,name:"email",placeholder:r("requestCodeInputPlaceholder"),value:d,onChange:R=>u(R.target.value)}),(0,z.jsx)("div",{className:i.actions,children:(0,z.jsx)("button",{type:"submit",className:(0,rs.default)(i.button,i.primaryButton),children:r("requestCodeSubmitLabel")})})]}),p===1&&(0,z.jsxs)("form",{onSubmit:v,children:[(0,z.jsx)("h2",{className:i.subtitle,children:r("verifyCodeTitle")}),(0,z.jsx)("p",{className:i.text,children:r("verifyCodeBody")}),(0,z.jsx)(Ko,{className:i.input,name:"token",placeholder:r("verifyCodeInputPlaceholder"),disabled:["loading","done"].includes(a)}),f&&(0,z.jsx)("div",{className:i.errorMessage,children:f}),(0,z.jsxs)("div",{className:i.actions,children:[(0,z.jsx)("button",{type:"button",className:(0,rs.default)(i.button),onClick:w,children:r("back")}),(0,z.jsx)("button",{type:"submit",className:(0,rs.default)(i.button,i.primaryButton),disabled:["loading","done"].includes(a),children:r("verifyCodeSubmitLabel")})]})]})]})})},gl=Rg;var fl=require("react/jsx-runtime"),Pg=()=>{let t=(0,Lr.useSelector)(ca),e=(0,Lr.useSelector)(_a),o=C("adminUrl"),n=we(),s=()=>n.send(so,!1),r=()=>{n.send(so,!1),n.send(Oo)};return(0,fl.jsx)(gl,{isOpen:t,agentEmail:e==null?void 0:e.agentEmail,origin:o,onDismiss:s,onSuccess:r})},ml=Pg;var yc=k(require("lodash.debounce")),re=require("react"),Oe=require("react-redux");var as=require("@reduxjs/toolkit");var Ig={data:null,fetchState:"idle"},hl=t=>t.contentTypes.data,Uo=(0,as.createAsyncThunk)("contentTypes/getContentTypes",async(t,e)=>e.extra.deepdeskAPI.getContentTypes()),Ag=(0,as.createSlice)({name:"contentTypes",initialState:Ig,reducers:{},extraReducers:t=>{t.addCase(Uo.pending,e=>{e.fetchState="loading"}).addCase(Uo.rejected,e=>{e.fetchState="error"}).addCase(Uo.fulfilled,(e,o)=>{e.fetchState="done",e.data=o.payload})}}),yl=Ag.reducer;function Ot(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()}var Ge=require("react");var vl=require("react"),ls=k(require("classnames"));var he={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 _t={};Y(_t,{enUS:()=>Mg,nlNL:()=>Ng});var Mg={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"}]};var dt=require("react/jsx-runtime"),Og=({src:t,title:e})=>{let o=h("CommandPalette",he),[n,s]=(0,vl.useState)("loading"),r=P(_t);return(0,dt.jsxs)("div",{className:o.image,children:[(0,dt.jsx)("img",{src:t,alt:e,onLoad:()=>s("done"),onError:()=>s("error"),className:(0,ls.default)(o.imageSrc,{[o.imageSrcHidden]:["loading","error"].includes(n)})}),n==="loading"&&(0,dt.jsx)("span",{className:(0,ls.default)(o.imageSrc,o.imageSrcStatus),children:r("loading")}),n==="error"&&(0,dt.jsx)("span",{className:(0,ls.default)(o.imageSrc,o.imageSrcStatus),children:(0,dt.jsx)(xn,{})}),e&&(0,dt.jsx)("span",{className:o.imageTitle,children:e})]})},Sl=Og;var xl=k(require("react")),bl=k(require("classnames"));var Dt=require("react/jsx-runtime");function Mr({children:t,heading:e,orientation:o,hasMore:n,onShowAll:s}){let r=P(_t),i=h("CommandPalette",he);return xl.default.Children.count(t)===0?null:(0,Dt.jsxs)("div",{"data-testid":"commandpalette-list",className:i.list,children:[(e||n)&&(0,Dt.jsxs)("div",{className:i.listHeader,children:[e&&(0,Dt.jsx)("h4",{className:i.listHeading,children:e}),n&&s&&(0,Dt.jsx)("button",{onClick:s,className:i.listMoreButton,type:"button",children:r("showAll")})]}),(0,Dt.jsx)("div",{className:(0,bl.default)(i.listWrapper,o==="horizontal"&&i.listHorizontal),children:t})]})}var zo=k(require("classnames")),Ml=require("interweave");var _g=/[.*+?^${}()|[\]\\]/g,Dg=/[^0-9A-Za-zÀ-ÖØ-öø-ÿ](?=[0-9A-Za-zÀ-ÖØ-öø-ÿ]*$)/;function Hg(t){return t.replace(_g,"\\$&")}function Fg(t,e){let o=t.split("").findIndex((n,s)=>n!==e[s]);return o>-1?o:Math.min(t.length,e.length)}function Bg(t){return t.search(Dg)}function Cl(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 wl(t){return t.replace(Rn,'<mark data-type="placeholder">$1</mark>')}function ro(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function Kg(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 Nr(t,e,o={}){if(e){let n=Fg(e.toLowerCase(),t.toLowerCase()),s=ro(t.substring(n,t.length));if(o.stripAgentPart){let l=t.substring(0,n),c=Bg(l);return`<span style="opacity: 0.5">${l.substring(c+1)}</span>${s}`}let i=e.split(ta).length>3||e.length>30?Kg(e.trim(),n):0;return`${`${i>0?"\u2026":""}${ro(t.substring(i,n))}`}<strong>${s}</strong>`}return t}var Ug=/(<\/[a-zA-Z]+[0-9]?>|<[a-zA-Z]+\s?\/>|<br>)/i;function cs(t){return Ug.test(t)}function Tl(t){let e=document.createElement("template");return e.innerHTML=t,e.content.textContent??""}var X=k(require("react")),El=k(require("classnames"));var Or={root:"Ge",trigger:"P",content:"Ne",contentOpen:"Ye",contentTop:"Ae",contentBottom:"Fe",item:"Q"};var Ht=require("react/jsx-runtime"),Vg=0,kl=X.default.createContext(null),$g=()=>{let t=(0,X.useContext)(kl);if(!t)throw new Error("Invalid DropdownContext");return t},Rl=({trigger:t,children:e,position:o="bottom"})=>{let n=(0,X.useMemo)(()=>++Vg,[]),s=(0,X.useRef)(null),r=(0,X.useRef)(null),i=h("Dropdown",Or),[a,l]=(0,X.useState)(!1),[c,d]=(0,X.useState)(o),u=g=>{g.preventDefault(),g.stopPropagation(),l(!a)},p=(0,X.useCallback)(([g])=>{!g.isIntersecting&&a&&d(c==="top"?"bottom":"top")},[a]);return(0,X.useEffect)(()=>{let g=f=>{s.current&&!s.current.contains(f.target)&&l(!1)};return document.addEventListener("click",g),()=>{document.removeEventListener("click",g)}},[]),(0,X.useEffect)(()=>{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]),(0,Ht.jsx)(kl.Provider,{value:{setIsOpen:l},children:(0,Ht.jsxs)("div",{ref:s,className:i.root,children:[(0,Ht.jsx)("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}),(0,Ht.jsx)("div",{"data-testid":"dropdown-content",ref:r,"aria-hidden":!a,"aria-labelledby":`dropdown-${n}`,className:(0,El.default)(i.content,{[i.contentOpen]:a,[i.contentTop]:c==="top",[i.contentBottom]:c==="bottom"}),children:e})]})})};function qg({as:t,children:e,onClick:o,...n}){let s=t||"button",r=h("Dropdown",Or),{setIsOpen:i}=$g(),a=l=>{i(!1),o(l),l.stopPropagation()};return(0,Ht.jsx)(s,{type:"button",className:r.item,onClick:a,...n,children:e})}Rl.Item=qg;var _r=Rl;var Dr=require("react/jsx-runtime"),Pl=t=>(0,Dr.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"16",width:"14",viewBox:"0 0 448 512",...t,children:(0,Dr.jsx)("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 Ft={};Y(Ft,{enUS:()=>Gg,nlNL:()=>jg});var Gg={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"}]},jg={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"}]};var ds=require("react/jsx-runtime"),Wg="%0d%0a%0d%0a%0d%0a",Xg=(t,e)=>{let o=[`Suggestie: ${encodeURIComponent(e)}`,"Beschrijf je feedback:"];return`mailto:${t.join(",")}?subject=Suggestie feedback&body=${o.join(Wg)}`},Zg=({suggestion:t,onFeedback:e})=>{let o=P(Ft),n=C("suggestionFeedbackEmailAddresses");return!n||n.length===0?null:(0,ds.jsx)(_r,{trigger:(0,ds.jsx)(Pl,{"data-testid":"feedback-dropdown-trigger"}),children:(0,ds.jsx)(_r.Item,{as:"a",href:Xg(n,t),onClick:e,children:o("giveFeedback")})})},us=Zg;var ps=k(require("react")),Ll=require("react/jsx-runtime"),Il=ps.default.createContext(void 0);function ut(){let t=ps.default.useContext(Il);if(t===void 0)throw new Error("useCommandPalette must be used within the CommandPalette component");return t}var Al=({children:t,page:e,isOpen:o,onChangeOpen:n,selected:s,setSelected:r})=>{let i=ps.default.useMemo(()=>({page:e,isOpen:o,onChangeOpen:n,selected:s,setSelected:r}),[o,e,s]);return(0,Ll.jsx)(Il.Provider,{value:i,children:t})};var pe=require("react/jsx-runtime");function Hr({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}=ut(),g=h("CommandPalette",he);function f(m){n(m),t&&p(!1)}return(0,pe.jsxs)("div",{className:(0,zo.default)(g.listItem,l===u&&g.listItemSelected),children:[(0,pe.jsx)("button",{type:"button",className:(0,zo.default)(g.listItemAction,g.listItemPrimaryAction),"aria-disabled":d.disabled??!1,onClick:f,"data-command-palette-item":!0,"data-item-id":l,...d,children:(0,pe.jsxs)("div",{className:g.listItemContent,children:[typeof o=="string"?(0,pe.jsx)("p",{className:(0,zo.default)(g.listItemText,g.truncate,c==null?void 0:c.title),children:o}):o,i&&(0,pe.jsx)(Ml.Interweave,{tagName:"p",allowList:[],content:cs(i)?Tl(i):i,className:(0,zo.default)(g.listItemDescription,c==null?void 0:c.description,e?g.lineClamp:g.truncate)})]})}),s&&(0,pe.jsx)("div",{className:g.listItemActions,children:(0,pe.jsx)(us,{suggestion:String(o),onFeedback:s})}),a&&(0,pe.jsxs)("div",{className:g.sources,children:[(0,pe.jsx)("span",{className:g.sourcesTitle,children:"Sources"}),a.map(m=>m.url?(0,pe.jsx)("a",{className:g.source,href:m.url,target:"_blank",title:m.url,rel:"noopener noreferrer",onClick:()=>r&&r(m),children:m.name},m.url):(0,pe.jsx)("span",{className:g.source,children:m.name},m.name))]})]})}var Vo=require("react/jsx-runtime"),Nl=()=>(0,Vo.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 256 512","aria-labelledby":"angleLeftTitle",children:[(0,Vo.jsx)("title",{id:"angleLeftTitle",children:"AngleLeft"}),(0,Vo.jsx)("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"})]});var Bt=require("react/jsx-runtime");function Fr({children:t,title:e,id:o,onDismiss:n}){let s=P(_t),r=h("CommandPalette",he),{page:i}=ut();return i!==o?null:(0,Bt.jsxs)("div",{className:r.page,id:`page_${o}`,tabIndex:-1,children:[n&&(0,Bt.jsxs)("div",{className:r.pageNav,children:[(0,Bt.jsxs)("button",{className:r.pageBackButton,type:"button",onClick:n,children:[(0,Bt.jsx)(Nl,{}),s("back")]}),e&&(0,Bt.jsx)("h3",{className:r.pageTitle,children:e})]}),t]})}var Ol=require("react");var $o=require("react/jsx-runtime"),io=()=>(0,$o.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 24 24",width:"1em",fill:"currentColor",children:[(0,$o.jsx)("path",{d:"M0 0h24v24H0z",fill:"none"}),(0,$o.jsx)("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"})]});var ke=require("react/jsx-runtime");function Qg({onChange:t,onChangeType:e,placeholder:o,typePlaceholder:n,types:s,value:r,selectedType:i},a){let l=h("CommandPalette",he);return(0,ke.jsxs)("div",{className:l.search,children:[(0,ke.jsx)("div",{className:l.searchIcon,children:(0,ke.jsx)(io,{})}),(0,ke.jsxs)("div",{className:l.searchInputWrapper,children:[(0,ke.jsx)("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&&(0,ke.jsx)("div",{className:l.selectWrapper,children:(0,ke.jsxs)("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&&(0,ke.jsx)("option",{children:n}),s.map(c=>(0,ke.jsx)("option",{value:c.value,children:c.label},c.value))]})})]})]})}var _l=(0,Ol.forwardRef)(Qg);var Br=k(require("classnames"));var gs=require("react/jsx-runtime"),Jg=({onClick:t,shortKeys:e,children:o,...n})=>{let s=h("CommandPalette",he);return(0,gs.jsxs)("button",{type:"button",...n,onClick:t,className:(0,Br.default)(s.actionButton,n.className,{[s.hasShortKeys]:e&&e.length>0}),children:[o,e&&e.map(r=>(0,gs.jsx)("span",{className:(0,Br.default)(s.actionShortcut,r===8629&&s.actionShortcutFixKerning),children:typeof r=="number"?String.fromCharCode(r):r},r))]})},Dl=Jg;var qo=require("react/jsx-runtime"),Yg="[data-command-palette-item]";function ao({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]=(0,Ge.useState)(),m=(0,Ge.useRef)(null),S=()=>{s&&s(o),i(void 0),r(""),a(!1)},w=()=>{var A;if(n!==o&&s){s(o);return}if(l&&i){i(void 0),(A=m.current)==null||A.focus();return}if(p.length>0){r("");return}a(!1)},v=()=>{let A=y();A.length!==0&&f(A[0].dataset.itemId)},y=()=>Array.from(document.querySelectorAll(Yg)||[]),R=A=>document.querySelector(`[data-item-id=${A}]`),x=A=>{let N=R(A);N&&f(N.dataset.itemId)},T=A=>{let N=R(A);N&&N.scrollIntoView({behavior:"smooth"})},M=()=>{if(!g)return;let A=y(),N=R(g);if(!N)return;let j=A.indexOf(N),ne=A[j+1];ne&&ne.dataset.itemId?x(ne.dataset.itemId):v()},G=()=>{if(!g)return;let A=y(),N=R(g);if(!N)return;let j=A.indexOf(N),ne=A[j-1];ne&&ne.dataset.itemId?x(ne.dataset.itemId):x(A[A.length-1].dataset.itemId)},K=(0,Ge.useCallback)(A=>{switch(A.key){case"ArrowDown":{A.preventDefault(),M();break}case"ArrowUp":{A.preventDefault(),G();break}case"Enter":{if(g){let N=R(g);N==null||N.click()}break}}},[g]);return(0,Ge.useEffect)(()=>{v()},[p,n,l,u]),(0,Ge.useEffect)(()=>{g&&T(g)},[g]),(0,qo.jsx)(ss,{autoFocus:!0,contentAriaLabel:"Search Results",overlayAriaLabel:"Command Palette",isOpen:u,onBack:w,onClose:S,onKeyDown:K,children:(0,qo.jsxs)(Al,{selected:g,setSelected:f,isOpen:u,onChangeOpen:a,page:n,children:[n===o&&(0,qo.jsx)(_l,{ref:m,onChange:r,onChangeType:i,placeholder:t,value:p,selectedType:l,types:c,typePlaceholder:e}),d]})})}ao.Page=Fr;ao.List=Mr;ao.Image=Sl;ao.ListItem=Hr;ao.Button=Dl;var F=ao;var Hl=require("react");function Fl(t,e){(0,Hl.useEffect)(()=>{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)}},[])}var Go=require("react"),hs=require("react-redux");var ms=require("@reduxjs/toolkit");var Bl={data:null,fetchState:"idle"},fs=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},Re=(0,ms.createAsyncThunk)("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)}),em=t=>t.filter((e,o)=>o===t.findIndex(n=>n.text===e.text)),tm=(0,ms.createSlice)({name:"entities",initialState:Bl,reducers:{},extraReducers:t=>{t.addCase(Re.pending,e=>{e.fetchState="loading"}).addCase(Re.rejected,e=>{e.fetchState="error"}).addCase(Re.fulfilled,(e,o)=>{e.fetchState="done",e.data=em(e.data?[...e.data,...o.payload]:o.payload)}).addCase(_,()=>Bl)}}),Kl=tm.reducer;var Kr={};Y(Kr,{enUS:()=>om,nlNL:()=>nm});var om={noResults:[{type:0,value:"No entities have been found"}],copy:[{type:0,value:"Copy"}],use:[{type:0,value:"Use"}]},nm={noResults:[{type:0,value:"Er zijn geen entiteiten gevonden"}],copy:[{type:0,value:"Kopieer"}],use:[{type:0,value:"Gebruik"}]};var Ul={root:"He",empty:"Le"};var lo=require("react/jsx-runtime"),rm=({onCopy:t})=>{let e=(0,Go.useRef)(null),o=h("EntitiesList",Ul),n=(0,hs.useSelector)(fs),{setSelected:s}=ut(),r=P(Kr),i=(0,hs.useDispatch)();return(0,Go.useEffect)(()=>{i(Re())},[]),(0,Go.useEffect)(()=>{e.current&&(e.current.focus(),s("entity-0"))},[e]),(0,lo.jsxs)("div",{className:o.root,ref:e,tabIndex:-1,children:[n&&n.length>0&&(0,lo.jsx)(F.List,{children:n.map((a,l)=>(0,lo.jsx)(F.ListItem,{id:`entity-${l}`,closeOnSelect:!0,onClick:()=>t(a),children:a.text},a.text))},"entities"),n&&n.length===0&&(0,lo.jsx)("p",{className:o.empty,children:r("noResults")})]})},zl=rm;var Pe=require("react"),jo=require("react-redux");var ys=require("@reduxjs/toolkit");var Vl={data:null,fetchState:"idle"},$l=t=>t.summary.data,ql=t=>t.summary.fetchState==="error",je=(0,ys.createAsyncThunk)("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=(0,ys.createSlice)({name:"summary",initialState:Vl,reducers:{},extraReducers:t=>{t.addCase(je.pending,e=>{e.data=null,e.fetchState="loading"}).addCase(je.rejected,e=>{e.data=null,e.fetchState="error"}).addCase(je.fulfilled,(e,o)=>{e.fetchState="done",o.payload&&(e.data=o.payload.summary)}).addCase(_,()=>Vl)}}),Gl=im.reducer;var Ur={};Y(Ur,{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 jl={root:"Me",actions:"Re",main:"Te",textInput:"V",loading:"Ue",error:"Be"};var We=require("react/jsx-runtime"),dm=({onCopy:t})=>{let e=(0,Pe.useRef)(null),o=h("SummaryForm",jl),[n,s]=(0,Pe.useState)(""),r=P(Ur),i=(0,jo.useSelector)($l),a=(0,jo.useSelector)(ql),l=(0,jo.useDispatch)(),c=()=>{l(Q({name:"summary copied to clipboard",data:{originalText:i,finalText:n},options:{includeConversationData:!0}})),t(n)},d=()=>{let u=document.getSelection();u&&l(Q({name:"summary copied to clipboard",data:{originalText:i,finalText:u==null?void 0:u.toString()},options:{includeConversationData:!0}}))};return(0,Pe.useEffect)(()=>{l(je())},[]),(0,Pe.useEffect)(()=>{s(i||"")},[i]),(0,Pe.useEffect)(()=>{e.current&&i&&e.current.focus()},[e,i]),(0,Pe.useEffect)(()=>{let u=p=>{p.key==="Enter"&&p.shiftKey&&c()};return document.addEventListener("keydown",u),()=>{document.removeEventListener("keydown",u)}},[n]),(0,We.jsx)("div",{className:o.root,tabIndex:-1,children:a?(0,We.jsx)("p",{className:o.error,children:r("error")}):(0,We.jsxs)(Pe.Fragment,{children:[(0,We.jsx)("div",{className:o.main,children:(0,We.jsx)("textarea",{placeholder:i?void 0:r("loading"),disabled:!i,className:o.textInput,ref:e,value:n,onCopy:d,onChange:u=>s(u.target.value)})}),(0,We.jsx)("div",{className:o.actions,children:(0,We.jsx)(F.Button,{shortKeys:[8679,8629],onClick:c,children:r("copy")})})]})})},Wl=dm;var Wo={};Y(Wo,{enUS:()=>um,nlNL:()=>pm});var um={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?"}]},pm={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?"}]};var pt=k(require("react")),Qo=require("react-redux");var zr={};Y(zr,{enUS:()=>gm,nlNL:()=>mm});var gm={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"}]},mm={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 Xl={root:"W",title:"De",empty:"Ie",status:"Oe",form:"Z",input:"_",submit:"Xe",question:"Je",answer:"Ke",alignRight:"Pe"};var uo=require("@reduxjs/toolkit");var vs=require("@reduxjs/toolkit");var hm={data:null,fetchState:"idle"},Zl=t=>{var e;return(e=t.knowledgeAssistant)==null?void 0:e.data},Xo=(0,vs.createAsyncThunk)("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}),ym=(0,vs.createSlice)({name:"knowledgeAssistant",initialState:hm,reducers:{},extraReducers:t=>{t.addCase(Xo.pending,e=>{e.fetchState="loading"}).addCase(Xo.rejected,e=>{e.fetchState="error"}).addCase(Xo.fulfilled,(e,o)=>{e.fetchState="done",e.data=o.payload})}}),Ql=ym.reducer;var Vr={data:[],fetchState:"idle"},Jl=t=>{var e;return(e=t.answer)==null?void 0:e.data},Yl=t=>t.answer.fetchState,po=(0,uo.createAction)("answer/resetKnowledgeSearch"),co=(0,uo.createAsyncThunk)("answer/getAnswer",async(t,e)=>{var l,c,d;let{deepdeskAPI:o}=e.extra,n=e.getState().answer.data,s=Zl(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}}),vm=(0,uo.createSlice)({name:"answer",initialState:Vr,reducers:{},extraReducers:t=>{t.addCase(co.pending,e=>{e.fetchState="loading"}).addCase(co.rejected,e=>{e.fetchState="error"}).addCase(co.fulfilled,(e,o)=>{e.fetchState="done",e.data=[...e.data,o.payload]}).addCase(_,()=>Vr).addCase(po,()=>Vr)}}),ec=vm.reducer;var Zo=require("react/jsx-runtime"),tc=()=>(0,Zo.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 512 512","aria-labelledby":"paperPlaneTitle",children:[(0,Zo.jsx)("title",{id:"paperPlaneTitle",children:"PaperPlane"}),(0,Zo.jsx)("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"})]});var ge=require("react/jsx-runtime"),Sm=({onUse:t,onResetQuestion:e,question:o})=>{let[n,s]=pt.default.useState(""),{setSelected:r}=ut(),i=(0,pt.useRef)(null),a=h("EntitiesList",Xl),l=P(zr),c=(0,Qo.useDispatch)(),d=(0,Qo.useSelector)(Jl),u=(0,Qo.useSelector)(Yl),p=async f=>{f.preventDefault(),f.stopPropagation(),n!==""&&c(co(n))},g=(f,m)=>{c(Q({name:"knowledge assist source viewed",data:{question:m,sourceViewed:f.url||f.name},options:{includeConversationData:!0}}))};return(0,pt.useEffect)(()=>{var f;o&&u==="idle"?c(co(o)):(f=i.current)==null||f.focus()},[i,u]),(0,pt.useEffect)(()=>{u==="done"&&(c(Q({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]),(0,pt.useEffect)(()=>{i.current&&i.current.scrollIntoView({behavior:"smooth"})},[i,d]),(0,ge.jsxs)("div",{className:a.root,children:[d.length>0&&(0,ge.jsx)("div",{className:a.alignRight,children:(0,ge.jsx)(F.Button,{onClick:e,children:l("reset")})}),d.map(({question:f,answer:m},S)=>(0,ge.jsx)(F.List,{children:(0,ge.jsx)(F.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"&&(0,ge.jsx)("p",{className:a.status,children:l("loading")}),u==="error"&&(0,ge.jsx)("p",{className:a.status,children:l("error")}),(0,ge.jsxs)("form",{className:a.form,onSubmit:p,children:[(0,ge.jsx)("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)}}),(0,ge.jsx)("button",{type:"submit",className:a.submit,children:(0,ge.jsx)(tc,{})})]})]})},oc=Sm;var Ss=require("@reduxjs/toolkit");var xm={data:null,fetchState:"idle"},gt=t=>t.profile.data,xs=t=>t.profile.data?t.profile.data.uiConfig.widget.types.filter(e=>e.isActive):[],Jo=(0,Ss.createAsyncThunk)("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)}),bm=(0,Ss.createSlice)({name:"profile",initialState:xm,reducers:{},extraReducers:t=>{t.addCase(Jo.pending,e=>{e.fetchState="loading"}).addCase(Jo.rejected,e=>{e.fetchState="error"}).addCase(Jo.fulfilled,(e,o)=>{e.fetchState="done",e.data=o.payload})}}),nc=bm.reducer;var gc=require("react");var mc=require("react-redux");var Kt=require("@reduxjs/toolkit");var Cm=["{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}"],wm=new RegExp(Cm.map(t=>`(?:${t.replace("{","\\{").replace("}","\\}")})`).join("|"));function sc(t,e){let o=t.split(wm),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 rc(t,e){return typeof e=="boolean"?t:t.slice(0,e)}var ac={suggestions:[],fetchState:"idle",isInitialRequest:null},ic={default:ac},lc=t=>e=>{var o;return((o=e.textSuggestions[t])==null?void 0:o.suggestions)??[]},cc=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")},bs=t=>t.textSuggestions,dc=t=>{let e=t.toLowerCase();return o=>{let n=o.text.toLowerCase();return n.startsWith(e)&&n.length>e.length}},Cs=(0,Kt.createAction)("textSuggestions/refresh"),Ie=(0,Kt.createAsyncThunk)("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=to(n);if(!s)throw new Error("No current conversation to fetch text suggestions");let l=await o.getTextSuggestions(s,No(n),t);if(t==="default"){let d=i?l.filter(dc(a)):l;e.dispatch(Me(d.slice(0,r)))}return l}),Yo=(0,Kt.createAsyncThunk)("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,{...No(n),input:t});if(!e.getState().input.text)throw new Error("Abort");return a&&(l=l.filter(dc(t))),i&&(l=l.map(d=>({...d,text:d.source!=="trie-with-typos"?sc(d.text,t):d.text}))),l=rc(l,r),e.dispatch(Me(l)),l}),uc=(0,Kt.createSlice)({name:"textSuggestions",initialState:ic,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(Ie.pending,(e,o)=>{let n=o.meta.arg,s=e[n]||ac;return{...e,[n]:{...s,fetchState:"loading",isInitialRequest:s.isInitialRequest===null}}}).addCase(Ie.rejected,(e,o)=>{let n=o.meta.arg;e[n]&&(e[n].fetchState="error")}).addCase(Ie.fulfilled,(e,o)=>{let n=o.meta.arg;e[n]&&(e[n].fetchState="done",e[n].suggestions=o.payload)}).addCase(Yo.pending,e=>{e.default.fetchState="loading"}).addCase(Yo.rejected,e=>{e.default.fetchState="error"}).addCase(Yo.fulfilled,(e,o)=>{e.default.fetchState="done",e.default.suggestions=o.payload}).addCase(_,()=>ic)}}),{setTextSuggestions:bb,setSuggestionState:Cb}=uc.actions,pc=uc.reducer;var $r=require("react-redux");var Ut=require("react/jsx-runtime"),Tm=({commands:t,onClick:e})=>{var a,l,c;let o=(0,mc.useDispatch)(),n=P(Wo),s=(0,$r.useSelector)(gt),r=(0,$r.useSelector)(bs),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(0,gc.useEffect)(()=>{i.forEach(({type:d})=>{(!r[d]||r[d].suggestions.length===0)&&o(Ie(d))})},[]),(0,Ut.jsxs)("div",{children:[t.length>0&&(0,Ut.jsx)(F.List,{heading:n("commands"),children:t.map((d,u)=>(0,Ut.jsx)(F.ListItem,{id:`command-${u}`,closeOnSelect:!1,onClick:d.onClick,children:d.label},d.label))}),i.map(({type:d,title:u})=>{var p;return(0,Ut.jsx)(F.List,{heading:u,orientation:"vertical",children:(p=r[d])==null?void 0:p.suggestions.map((g,f)=>(0,Ut.jsx)(F.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)})]})},fc=Tm;var Z=require("react/jsx-runtime"),km=200,Rm=5,Pm=4,hc=(t,e)=>!e||t.toLowerCase().includes(e.toLowerCase()),Im=()=>{let t=(0,Oe.useDispatch)(),e=we(),o=P(Wo),[n,s]=(0,re.useState)(!1),[r,i]=(0,re.useState)(""),a=(0,Oe.useSelector)(Ka),l=(0,Oe.useSelector)(gt),[c,d]=(0,re.useState)(),u=(0,Oe.useSelector)(ee),p=C("showSearch"),g=C("showEntitiesCommand"),f=C("showSummaryCommand"),m=C("showKnowledgeSearch"),S=C("showImageSearch"),w=C("searchTriggerKey"),v=(0,Oe.useSelector)(hl),y=(0,Oe.useSelector)(Ua),R=(0,Oe.useSelector)(za),x=(0,Oe.useSelector)(Ba),T=b=>ko(y.filter(U=>U.type===b.toUpperCase()),b),M=[{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),G=[{label:o("entitiesClipboard"),onClick:()=>t(Ce("entities")),shouldShow:g&&hc(o("entitiesClipboard"),r)},{label:o("summaryClipboard"),onClick:()=>t(Ce("summary")),shouldShow:f&&hc(o("summaryClipboard"),r)},{label:r?`${o("knowledgeAssist")}: ${r}`:o("knowledgeAssist"),onClick:()=>t(Ce("knowledgeAssist")),shouldShow:m}].filter(b=>b.shouldShow),K=(v==null?void 0:v.map(b=>({value:b.code.toUpperCase(),label:`${b.name}s`,list:T(b.code.toUpperCase()),listOrientation:"vertical",lineClamp:!0})))||[],A=(0,re.useCallback)((0,yc.default)((b,U)=>{t(Lt({query:b,type:U,tags:["search-overlay"],size:c?50:20}))},km),[c]),N=(0,re.useCallback)((b,U)=>{switch(U.type){case"IMAGE":e.send(xr,{suggestion:U});break;default:e.send(ct,{text:b,suggestion:U})}t(de(!1))},[t]),j=b=>{Ot(b.text),t(Q({name:"entity copied",data:{entity:b,type:"copy"}})),t(de(!1))},ne=(0,re.useCallback)(b=>{t(Q({name:"suggestion feedback",data:{text:b.text,source:"search",context:r},options:{includeConversationData:!0}}))},[r]),D=b=>{e.send(ct,{text:b,suggestion:{source:"knowledge-assist",text:b}}),t(Q({name:"answer used",data:{originalText:b},options:{includeConversationData:!0}})),i(""),t(Ce("search")),t(po()),t(de(!1))},Eo=b=>{Ot(b),t(de(!1))};function ko(b,U){return b.slice(0,c?10:U.toLowerCase()==="image"?Pm:Rm)}function wt(b){return U=>{n?window.confirm(o("warning"))&&(b(U),s(!1)):b(U)}}return(0,re.useEffect)(()=>{r?A(r,c):t(zn())},[r,c]),(0,re.useEffect)(()=>{a==="search"&&t(po())},[a]),(0,re.useEffect)(()=>{u&&t(Uo())},[u]),Fl(w,()=>t(de(!0))),!p||!l?null:(0,Z.jsxs)(F,{placeholder:o("searchPlaceholder"),typePlaceholder:o("typePlaceholder"),onChangeSearch:i,onChangeOpen:wt(b=>t(de(b))),onChangeType:b=>d(b),onChangePage:wt(b=>t(Ce(b))),selectedType:c,search:r,page:a,isOpen:x,types:[...K,...M],children:[(0,Z.jsxs)(F.Page,{id:"search",children:[r.length===0&&(0,Z.jsx)(fc,{commands:G,onClick:N}),r.length>0&&(0,Z.jsxs)(re.Fragment,{children:[G.length>0&&(0,Z.jsx)(F.List,{heading:o("commands"),children:G.map((b,U)=>(0,Z.jsx)(F.ListItem,{closeOnSelect:!1,onClick:b.onClick,id:`commands-${U}`,children:b.label},b.label))}),[...K,...M].map(({value:b,label:U,list:Oi,lineClamp:pp,listOrientation:gp})=>(0,Z.jsx)(F.List,{heading:U,orientation:gp==="horizontal"?"horizontal":"vertical",onShowAll:()=>d(b),hasMore:!c&&R[b.toLowerCase()]>ko(Oi,b).length,children:ko(Oi,b).map(ae=>(0,Z.jsx)(F.ListItem,{id:`${b}-${ae.id}`,closeOnSelect:!1,lineClamp:pp,onClick:()=>N(ae.text,ae),description:b!=="IMAGE"?ae.title&&ae.text:void 0,onFeedback:b!=="IMAGE"?()=>ne(ae):void 0,children:b==="IMAGE"?(0,Z.jsx)(F.Image,{title:ae.title||ae.text,src:ae.image}):ae.title||ae.text},`${ae.id}-${ae.text}`))},b))]})]}),(0,Z.jsx)(F.Page,{id:"entities",title:o("entitiesTitle"),onDismiss:wt(()=>{t(Ce("search"))}),children:(0,Z.jsx)(zl,{onCopy:j})}),(0,Z.jsx)(F.Page,{id:"summary",title:o("summaryTitle"),onDismiss:wt(()=>{t(Ce("search"))}),children:(0,Z.jsx)(Wl,{onCopy:Eo})}),(0,Z.jsx)(F.Page,{id:"knowledgeAssist",title:o("knowledgeAssist"),onDismiss:wt(()=>{t(po()),t(Ce("search"))}),children:(0,Z.jsx)(oc,{question:r,onUse:D,onResetQuestion:()=>{t(po()),i("")}})})]})},vc=Im;var en=require("react/jsx-runtime"),Am=()=>{let t=C("showSearch"),e=C("isEmbedded");return(0,en.jsxs)(Sc.Fragment,{children:[t&&(0,en.jsx)(vc,{}),e&&(0,en.jsx)(ml,{})]})},xc=Am;var Tc=k(require("classnames")),Ec=require("react-redux");var ws=require("react/jsx-runtime"),bc=({className:t})=>(0,ws.jsx)("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:(0,ws.jsx)("g",{children:(0,ws.jsx)("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
+ `,Lt.MISSING_INTL_API,i);var R=o.getPluralRules(e,{type:d.pluralType}).select(g-(d.offset||0));v=d.options[R]||d.options.other}if(!v)throw new Pr(d.value,g,Object.keys(d.options),i);a.push.apply(a,Ho(v.value,e,o,n,s,g-(d.offset||0)));continue}}return kg(a)}function Pg(t,e){return e?de(de(de({},t||{}),e||{}),Object.keys(t).reduce(function(o,n){return o[n]=de(de({},t[n]),e[n]||{}),o},{})):t}function Ig(t,e){return e?Object.keys(t).reduce(function(o,n){return o[n]=Pg(t[n],e[n]),o},de({},t)):t}function Ir(t){return{create:function(){return{get:function(e){return t[e]},set:function(e,o){t[e]=o}}}}}function Lg(t){return t===void 0&&(t={number:{},dateTime:{},pluralRules:{}}),{getNumberFormat:Yn(function(){for(var e,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];return new((e=Intl.NumberFormat).bind.apply(e,zn([void 0],o,!1)))},{cache:Ir(t.number),strategy:es.variadic}),getDateTimeFormat:Yn(function(){for(var e,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];return new((e=Intl.DateTimeFormat).bind.apply(e,zn([void 0],o,!1)))},{cache:Ir(t.dateTime),strategy:es.variadic}),getPluralRules:Yn(function(){for(var e,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];return new((e=Intl.PluralRules).bind.apply(e,zn([void 0],o,!1)))},{cache:Ir(t.pluralRules),strategy:es.variadic})}}var ul=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 Ho(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=nl(i,["formatters"]);this.ast=t.__parse(e,de(de({},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=Ig(t.formats,n),this.formatters=s&&s.formatters||Lg(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=il,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 Ag(t,e){return e.split(".").reduce((o,n)=>o?o[n]:void 0,t)}var Mg="dummy",Lr=(0,ts.createContext)(null);function P(t){let e=(0,ts.useContext)(Lr);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=Ag(o,n);return r?new ul(r).format(s):(e!==Mg&&console.warn(`${n} does not exist in messages of ${e}`),`[${n}]`)}}var os=require("react");var pl={root:"X",content:"Xo"};var Ar=require("react/jsx-runtime"),Og=({isOpen:t,autoFocus:e,children:o,onClose:n,onBack:s,onKeyDown:r,overlayAriaLabel:i,contentAriaLabel:a})=>{let l=(0,os.useRef)(null),c=h("Dialog",pl),d=g=>{if(g.key==="Escape"){g.preventDefault(),g.stopPropagation(),s();return}r&&r(g)},u=g=>{g.target===l.current&&t&&n()};return(0,os.useEffect)(()=>{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?(0,Ar.jsx)("div",{role:"dialog","data-testid":"dialog",className:c.root,"aria-label":i,ref:l,onKeyDown:d,onMouseDown:u,children:(0,Ar.jsx)("div",{"data-testid":"dialog-content",className:c.content,"aria-label":a,children:o})}):null},ns=Og;var ml=k(require("classnames"));var gl={root:"y"};var fl=require("react/jsx-runtime"),Dg=({className:t,value:e,...o})=>{let n=h("TextInput",gl);return(0,fl.jsx)("input",{className:(0,ml.default)(t,n.root),type:"text",value:e,...o})},Fo=Dg;var Mr={};Y(Mr,{enUS:()=>Hg,nlNL:()=>Fg});var Hg={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"}]},Fg={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 hl={root:"Jo",anchorButton:"Ko",errorMessage:"Po",title:"Qo",subtitle:"Vo",text:"Wo",input:"Zo",actions:"_o",button:"w",primaryButton:"oe"};var U=require("react/jsx-runtime");var Kg=t=>{try{let e=new URL(t);return new URLSearchParams(e.search).get("token")||void 0}catch{return t}},Ug=({agentEmail:t,isOpen:e,origin:o="",onSuccess:n,onDismiss:s})=>{let r=P(Mr),i=h("LoginTokenDialog",hl),a=(0,rs.useSelector)(ha),l=(0,rs.useDispatch)(),c=b("productName"),[d,u]=(0,Ee.useState)(t||""),[g,p]=(0,Ee.useState)(0),[f,m]=(0,Ee.useState)(""),y=(0,Ee.useCallback)(async R=>{R.preventDefault(),l(va({email:d})),p(1)},[o,d]),E=()=>{m(""),p(0)},S=(0,Ee.useCallback)(async R=>{R.preventDefault();let x=Kg(R.target.elements.token.value);if(!x){m(r("verifyCodeError",{login:v}));return}l(Po({token:x}))},[o]),v=(0,Ee.useMemo)(()=>R=>(0,U.jsx)("button",{type:"button","data-testid":"login-token-dialog-back-button",className:i.anchorButton,onClick:E,children:R},"back-button"),[]);return(0,Ee.useEffect)(()=>{a==="error"&&m(r("verifyCodeError",{login:v})),a==="done"&&n()},[a]),(0,U.jsx)(ns,{autoFocus:!0,isOpen:e,contentAriaLabel:r("promptTitle",{productName:c}),overlayAriaLabel:r("promptTitle",{productName:c}),onClose:s,onBack:s,children:(0,U.jsxs)("div",{className:i.root,children:[(0,U.jsx)("h1",{className:i.title,children:r("promptTitle",{productName:c})}),g===0&&(0,U.jsxs)("form",{onSubmit:y,children:[(0,U.jsx)("h2",{className:i.subtitle,children:r("requestCodeTitle")}),(0,U.jsx)("p",{className:i.text,children:r("requestCodeBody",{productName:c})}),(0,U.jsx)(Fo,{className:i.input,name:"email",placeholder:r("requestCodeInputPlaceholder"),value:d,onChange:R=>u(R.target.value)}),(0,U.jsx)("div",{className:i.actions,children:(0,U.jsx)("button",{type:"submit",className:(0,ss.default)(i.button,i.primaryButton),children:r("requestCodeSubmitLabel")})})]}),g===1&&(0,U.jsxs)("form",{onSubmit:S,children:[(0,U.jsx)("h2",{className:i.subtitle,children:r("verifyCodeTitle")}),(0,U.jsx)("p",{className:i.text,children:r("verifyCodeBody")}),(0,U.jsx)(Fo,{className:i.input,name:"token",placeholder:r("verifyCodeInputPlaceholder"),disabled:["loading","done"].includes(a)}),f&&(0,U.jsx)("div",{className:i.errorMessage,children:f}),(0,U.jsxs)("div",{className:i.actions,children:[(0,U.jsx)("button",{type:"button",className:(0,ss.default)(i.button),onClick:E,children:r("back")}),(0,U.jsx)("button",{type:"submit",className:(0,ss.default)(i.button,i.primaryButton),disabled:["loading","done"].includes(a),children:r("verifyCodeSubmitLabel")})]})]})]})})},yl=Ug;var Sl=require("react/jsx-runtime"),zg=()=>{let t=(0,Nr.useSelector)(ya),e=(0,Nr.useSelector)(Va),o=b("adminUrl"),n=he(),s=()=>n.send(oo,!1),r=()=>{n.send(oo,!1),n.send(Mo)};return(0,Sl.jsx)(yl,{isOpen:t,agentEmail:e==null?void 0:e.agentEmail,origin:o,onDismiss:s,onSuccess:r})},vl=zg;var bc=k(require("lodash.debounce")),re=require("react"),Oe=require("react-redux");var is=require("@reduxjs/toolkit");var Vg={data:null,fetchState:"idle"},xl=t=>t.contentTypes.data,Bo=(0,is.createAsyncThunk)("contentTypes/getContentTypes",async(t,e)=>e.extra.deepdeskAPI.getContentTypes()),$g=(0,is.createSlice)({name:"contentTypes",initialState:Vg,reducers:{},extraReducers:t=>{t.addCase(Bo.pending,e=>{e.fetchState="loading"}).addCase(Bo.rejected,e=>{e.fetchState="error"}).addCase(Bo.fulfilled,(e,o)=>{e.fetchState="done",e.data=o.payload})}}),bl=$g.reducer;function At(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()}var qe=require("react");var Cl=require("react"),as=k(require("classnames"));var ye={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 Mt={};Y(Mt,{enUS:()=>Gg,nlNL:()=>jg});var Gg={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"}]},jg={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"}]};var lt=require("react/jsx-runtime"),Wg=({src:t,title:e})=>{let o=h("CommandPalette",ye),[n,s]=(0,Cl.useState)("loading"),r=P(Mt);return(0,lt.jsxs)("div",{className:o.image,children:[(0,lt.jsx)("img",{src:t,alt:e,onLoad:()=>s("done"),onError:()=>s("error"),className:(0,as.default)(o.imageSrc,{[o.imageSrcHidden]:["loading","error"].includes(n)})}),n==="loading"&&(0,lt.jsx)("span",{className:(0,as.default)(o.imageSrc,o.imageSrcStatus),children:r("loading")}),n==="error"&&(0,lt.jsx)("span",{className:(0,as.default)(o.imageSrc,o.imageSrcStatus),children:(0,lt.jsx)(Sn,{})}),e&&(0,lt.jsx)("span",{className:o.imageTitle,children:e})]})},wl=Wg;var Tl=k(require("react")),El=k(require("classnames"));var Nt=require("react/jsx-runtime");function Or({children:t,heading:e,orientation:o,hasMore:n,onShowAll:s}){let r=P(Mt),i=h("CommandPalette",ye);return Tl.default.Children.count(t)===0?null:(0,Nt.jsxs)("div",{"data-testid":"commandpalette-list",className:i.list,children:[(e||n)&&(0,Nt.jsxs)("div",{className:i.listHeader,children:[e&&(0,Nt.jsx)("h4",{className:i.listHeading,children:e}),n&&s&&(0,Nt.jsx)("button",{onClick:s,className:i.listMoreButton,type:"button",children:r("showAll")})]}),(0,Nt.jsx)("div",{className:(0,El.default)(i.listWrapper,o==="horizontal"&&i.listHorizontal),children:t})]})}var Ko=k(require("classnames")),Dl=require("interweave");var Xg=/[.*+?^${}()|[\]\\]/g,Zg=/[^0-9A-Za-zÀ-ÖØ-öø-ÿ](?=[0-9A-Za-zÀ-ÖØ-öø-ÿ]*$)/;function Qg(t){return t.replace(Xg,"\\$&")}function Jg(t,e){let o=t.split("").findIndex((n,s)=>n!==e[s]);return o>-1?o:Math.min(t.length,e.length)}function Yg(t){return t.search(Zg)}function kl(t,e=[]){let o=t;return e.forEach(n=>{if(!n)return;let s=new RegExp(`\\b(${Qg(n)})\\b`,"gi");o=o.replace(s,"<strong>$1</strong>")}),o}function Rl(t){return t.replace(kn,'<mark data-type="placeholder">$1</mark>')}function no(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function em(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 _r(t,e,o={}){if(e){let n=Jg(e.toLowerCase(),t.toLowerCase()),s=no(t.substring(n,t.length));if(o.stripAgentPart){let l=t.substring(0,n),c=Yg(l);return`<span style="opacity: 0.5">${l.substring(c+1)}</span>${s}`}let i=e.split(ca).length>3||e.length>30?em(e.trim(),n):0;return`${`${i>0?"\u2026":""}${no(t.substring(i,n))}`}<strong>${s}</strong>`}return t}var tm=/(<\/[a-zA-Z]+[0-9]?>|<[a-zA-Z]+\s?\/>|<br>)/i;function ls(t){return tm.test(t)}function Pl(t){let e=document.createElement("template");return e.innerHTML=t,e.content.textContent??""}var j=k(require("react")),Il=k(require("classnames"));var Dr={root:"Le",trigger:"_",content:"Me",contentOpen:"Re",contentTop:"Te",contentBottom:"Ue",item:"oo"};var Ot=require("react/jsx-runtime"),nm=0,Ll=j.default.createContext(null),sm=()=>{let t=(0,j.useContext)(Ll);if(!t)throw new Error("Invalid DropdownContext");return t},Al=({trigger:t,children:e,position:o="bottom"})=>{let n=(0,j.useMemo)(()=>++nm,[]),s=(0,j.useRef)(null),r=(0,j.useRef)(null),i=h("Dropdown",Dr),[a,l]=(0,j.useState)(!1),[c,d]=(0,j.useState)(o),u=p=>{p.preventDefault(),p.stopPropagation(),l(!a)},g=(0,j.useCallback)(([p])=>{!p.isIntersecting&&a&&d(c==="top"?"bottom":"top")},[a]);return(0,j.useEffect)(()=>{let p=f=>{s.current&&!s.current.contains(f.target)&&l(!1)};return document.addEventListener("click",p),()=>{document.removeEventListener("click",p)}},[]),(0,j.useEffect)(()=>{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]),(0,Ot.jsx)(Ll.Provider,{value:{setIsOpen:l},children:(0,Ot.jsxs)("div",{ref:s,className:i.root,children:[(0,Ot.jsx)("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}),(0,Ot.jsx)("div",{"data-testid":"dropdown-content",ref:r,"aria-hidden":!a,"aria-labelledby":`dropdown-${n}`,className:(0,Il.default)(i.content,{[i.contentOpen]:a,[i.contentTop]:c==="top",[i.contentBottom]:c==="bottom"}),children:e})]})})};function rm({as:t,children:e,onClick:o,...n}){let s=t||"button",r=h("Dropdown",Dr),{setIsOpen:i}=sm(),a=l=>{i(!1),o(l),l.stopPropagation()};return(0,Ot.jsx)(s,{type:"button",className:r.item,onClick:a,...n,children:e})}Al.Item=rm;var Hr=Al;var Fr=require("react/jsx-runtime"),Ml=t=>(0,Fr.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"16",width:"14",viewBox:"0 0 448 512",...t,children:(0,Fr.jsx)("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 _t={};Y(_t,{enUS:()=>im,nlNL:()=>am});var im={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"}]},am={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"}]};var cs=require("react/jsx-runtime"),lm="%0d%0a%0d%0a%0d%0a",cm=(t,e)=>{let o=[`Suggestie: ${encodeURIComponent(e)}`,"Beschrijf je feedback:"];return`mailto:${t.join(",")}?subject=Suggestie feedback&body=${o.join(lm)}`},dm=({suggestion:t,onFeedback:e})=>{let o=P(_t),n=b("suggestionFeedbackEmailAddresses");return!n||n.length===0?null:(0,cs.jsx)(Hr,{trigger:(0,cs.jsx)(Ml,{"data-testid":"feedback-dropdown-trigger"}),children:(0,cs.jsx)(Hr.Item,{as:"a",href:cm(n,t),onClick:e,children:o("giveFeedback")})})},ds=dm;var us=k(require("react")),_l=require("react/jsx-runtime"),Nl=us.default.createContext(void 0);function ct(){let t=us.default.useContext(Nl);if(t===void 0)throw new Error("useCommandPalette must be used within the CommandPalette component");return t}var Ol=({children:t,page:e,isOpen:o,onChangeOpen:n,selected:s,setSelected:r})=>{let i=us.default.useMemo(()=>({page:e,isOpen:o,onChangeOpen:n,selected:s,setSelected:r}),[o,e,s]);return(0,_l.jsx)(Nl.Provider,{value:i,children:t})};var ue=require("react/jsx-runtime");function Br({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}=ct(),p=h("CommandPalette",ye);function f(m){n(m),t&&g(!1)}return(0,ue.jsxs)("div",{className:(0,Ko.default)(p.listItem,l===u&&p.listItemSelected),children:[(0,ue.jsx)("button",{type:"button",className:(0,Ko.default)(p.listItemAction,p.listItemPrimaryAction),"aria-disabled":d.disabled??!1,onClick:f,"data-command-palette-item":!0,"data-item-id":l,...d,children:(0,ue.jsxs)("div",{className:p.listItemContent,children:[typeof o=="string"?(0,ue.jsx)("p",{className:(0,Ko.default)(p.listItemText,p.truncate,c==null?void 0:c.title),children:o}):o,i&&(0,ue.jsx)(Dl.Interweave,{tagName:"p",allowList:[],content:ls(i)?Pl(i):i,className:(0,Ko.default)(p.listItemDescription,c==null?void 0:c.description,e?p.lineClamp:p.truncate)})]})}),s&&(0,ue.jsx)("div",{className:p.listItemActions,children:(0,ue.jsx)(ds,{suggestion:String(o),onFeedback:s})}),a&&(0,ue.jsxs)("div",{className:p.sources,children:[(0,ue.jsx)("span",{className:p.sourcesTitle,children:"Sources"}),a.map(m=>m.url?(0,ue.jsx)("a",{className:p.source,href:m.url,target:"_blank",title:m.url,rel:"noopener noreferrer",onClick:()=>r&&r(m),children:m.name},m.url):(0,ue.jsx)("span",{className:p.source,children:m.name},m.name))]})]})}var Uo=require("react/jsx-runtime"),Hl=()=>(0,Uo.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 256 512","aria-labelledby":"angleLeftTitle",children:[(0,Uo.jsx)("title",{id:"angleLeftTitle",children:"AngleLeft"}),(0,Uo.jsx)("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"})]});var Dt=require("react/jsx-runtime");function Kr({children:t,title:e,id:o,onDismiss:n}){let s=P(Mt),r=h("CommandPalette",ye),{page:i}=ct();return i!==o?null:(0,Dt.jsxs)("div",{className:r.page,id:`page_${o}`,tabIndex:-1,children:[n&&(0,Dt.jsxs)("div",{className:r.pageNav,children:[(0,Dt.jsxs)("button",{className:r.pageBackButton,type:"button",onClick:n,children:[(0,Dt.jsx)(Hl,{}),s("back")]}),e&&(0,Dt.jsx)("h3",{className:r.pageTitle,children:e})]}),t]})}var Fl=require("react");var zo=require("react/jsx-runtime"),so=()=>(0,zo.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 24 24",width:"1em",fill:"currentColor",children:[(0,zo.jsx)("path",{d:"M0 0h24v24H0z",fill:"none"}),(0,zo.jsx)("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"})]});var ke=require("react/jsx-runtime");function um({onChange:t,onChangeType:e,placeholder:o,typePlaceholder:n,types:s,value:r,selectedType:i},a){let l=h("CommandPalette",ye);return(0,ke.jsxs)("div",{className:l.search,children:[(0,ke.jsx)("div",{className:l.searchIcon,children:(0,ke.jsx)(so,{})}),(0,ke.jsxs)("div",{className:l.searchInputWrapper,children:[(0,ke.jsx)("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&&(0,ke.jsx)("div",{className:l.selectWrapper,children:(0,ke.jsxs)("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&&(0,ke.jsx)("option",{children:n}),s.map(c=>(0,ke.jsx)("option",{value:c.value,children:c.label},c.value))]})})]})]})}var Bl=(0,Fl.forwardRef)(um);var Ur=k(require("classnames"));var ps=require("react/jsx-runtime"),pm=({onClick:t,shortKeys:e,children:o,...n})=>{let s=h("CommandPalette",ye);return(0,ps.jsxs)("button",{type:"button",...n,onClick:t,className:(0,Ur.default)(s.actionButton,n.className,{[s.hasShortKeys]:e&&e.length>0}),children:[o,e&&e.map(r=>(0,ps.jsx)("span",{className:(0,Ur.default)(s.actionShortcut,r===8629&&s.actionShortcutFixKerning),children:typeof r=="number"?String.fromCharCode(r):r},r))]})},Kl=pm;var Vo=require("react/jsx-runtime"),gm="[data-command-palette-item]";function ro({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]=(0,qe.useState)(),m=(0,qe.useRef)(null),y=()=>{s&&s(o),i(void 0),r(""),a(!1)},E=()=>{var A;if(n!==o&&s){s(o);return}if(l&&i){i(void 0),(A=m.current)==null||A.focus();return}if(g.length>0){r("");return}a(!1)},S=()=>{let A=v();A.length!==0&&f(A[0].dataset.itemId)},v=()=>Array.from(document.querySelectorAll(gm)||[]),R=A=>document.querySelector(`[data-item-id=${A}]`),x=A=>{let _=R(A);_&&f(_.dataset.itemId)},w=A=>{let _=R(A);_&&_.scrollIntoView({behavior:"smooth"})},O=()=>{if(!p)return;let A=v(),_=R(p);if(!_)return;let I=A.indexOf(_),X=A[I+1];X&&X.dataset.itemId?x(X.dataset.itemId):S()},q=()=>{if(!p)return;let A=v(),_=R(p);if(!_)return;let I=A.indexOf(_),X=A[I-1];X&&X.dataset.itemId?x(X.dataset.itemId):x(A[A.length-1].dataset.itemId)},K=(0,qe.useCallback)(A=>{switch(A.key){case"ArrowDown":{A.preventDefault(),O();break}case"ArrowUp":{A.preventDefault(),q();break}case"Enter":{if(p){let _=R(p);_==null||_.click()}break}}},[p]);return(0,qe.useEffect)(()=>{S()},[g,n,l,u]),(0,qe.useEffect)(()=>{p&&w(p)},[p]),(0,Vo.jsx)(ns,{autoFocus:!0,contentAriaLabel:"Search Results",overlayAriaLabel:"Command Palette",isOpen:u,onBack:E,onClose:y,onKeyDown:K,children:(0,Vo.jsxs)(Ol,{selected:p,setSelected:f,isOpen:u,onChangeOpen:a,page:n,children:[n===o&&(0,Vo.jsx)(Bl,{ref:m,onChange:r,onChangeType:i,placeholder:t,value:g,selectedType:l,types:c,typePlaceholder:e}),d]})})}ro.Page=Kr;ro.List=Or;ro.Image=wl;ro.ListItem=Br;ro.Button=Kl;var F=ro;var Ul=require("react");function zl(t,e){(0,Ul.useEffect)(()=>{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)}},[])}var $o=require("react"),fs=require("react-redux");var gs=require("@reduxjs/toolkit");var Vl={data:null,fetchState:"idle"},ms=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},Re=(0,gs.createAsyncThunk)("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)}),mm=t=>t.filter((e,o)=>o===t.findIndex(n=>n.text===e.text)),fm=(0,gs.createSlice)({name:"entities",initialState:Vl,reducers:{},extraReducers:t=>{t.addCase(Re.pending,e=>{e.fetchState="loading"}).addCase(Re.rejected,e=>{e.fetchState="error"}).addCase(Re.fulfilled,(e,o)=>{e.fetchState="done",e.data=mm(e.data?[...e.data,...o.payload]:o.payload)}).addCase(D,()=>Vl)}}),$l=fm.reducer;var zr={};Y(zr,{enUS:()=>hm,nlNL:()=>ym});var hm={noResults:[{type:0,value:"No entities have been found"}],copy:[{type:0,value:"Copy"}],use:[{type:0,value:"Use"}]},ym={noResults:[{type:0,value:"Er zijn geen entiteiten gevonden"}],copy:[{type:0,value:"Kopieer"}],use:[{type:0,value:"Gebruik"}]};var ql={root:"Be",empty:"De"};var io=require("react/jsx-runtime"),Sm=({onCopy:t})=>{let e=(0,$o.useRef)(null),o=h("EntitiesList",ql),n=(0,fs.useSelector)(ms),{setSelected:s}=ct(),r=P(zr),i=(0,fs.useDispatch)();return(0,$o.useEffect)(()=>{i(Re())},[]),(0,$o.useEffect)(()=>{e.current&&(e.current.focus(),s("entity-0"))},[e]),(0,io.jsxs)("div",{className:o.root,ref:e,tabIndex:-1,children:[n&&n.length>0&&(0,io.jsx)(F.List,{children:n.map((a,l)=>(0,io.jsx)(F.ListItem,{id:`entity-${l}`,closeOnSelect:!0,onClick:()=>t(a),children:a.text},a.text))},"entities"),n&&n.length===0&&(0,io.jsx)("p",{className:o.empty,children:r("noResults")})]})},Gl=Sm;var Pe=require("react"),qo=require("react-redux");var hs=require("@reduxjs/toolkit");var jl={data:null,fetchState:"idle"},Wl=t=>t.summary.data,Xl=t=>t.summary.fetchState==="error",Ge=(0,hs.createAsyncThunk)("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"))}),xm=(0,hs.createSlice)({name:"summary",initialState:jl,reducers:{},extraReducers:t=>{t.addCase(Ge.pending,e=>{e.data=null,e.fetchState="loading"}).addCase(Ge.rejected,e=>{e.data=null,e.fetchState="error"}).addCase(Ge.fulfilled,(e,o)=>{e.fetchState="done",o.payload&&(e.data=o.payload.summary)}).addCase(D,()=>jl)}}),Zl=xm.reducer;var Vr={};Y(Vr,{enUS:()=>bm,nlNL:()=>Cm});var bm={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."}]},Cm={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 Ql={root:"Ie",actions:"Oe",main:"Xe",textInput:"eo",loading:"Je",error:"Ke"};var je=require("react/jsx-runtime"),Tm=({onCopy:t})=>{let e=(0,Pe.useRef)(null),o=h("SummaryForm",Ql),[n,s]=(0,Pe.useState)(""),r=P(Vr),i=(0,qo.useSelector)(Wl),a=(0,qo.useSelector)(Xl),l=(0,qo.useDispatch)(),c=()=>{l(Q({name:"summary copied to clipboard",data:{originalText:i,finalText:n},options:{includeConversationData:!0}})),t(n)},d=()=>{let u=document.getSelection();u&&l(Q({name:"summary copied to clipboard",data:{originalText:i,finalText:u==null?void 0:u.toString()},options:{includeConversationData:!0}}))};return(0,Pe.useEffect)(()=>{l(Ge())},[]),(0,Pe.useEffect)(()=>{s(i||"")},[i]),(0,Pe.useEffect)(()=>{e.current&&i&&e.current.focus()},[e,i]),(0,Pe.useEffect)(()=>{let u=g=>{g.key==="Enter"&&g.shiftKey&&c()};return document.addEventListener("keydown",u),()=>{document.removeEventListener("keydown",u)}},[n]),(0,je.jsx)("div",{className:o.root,tabIndex:-1,children:a?(0,je.jsx)("p",{className:o.error,children:r("error")}):(0,je.jsxs)(Pe.Fragment,{children:[(0,je.jsx)("div",{className:o.main,children:(0,je.jsx)("textarea",{placeholder:i?void 0:r("loading"),disabled:!i,className:o.textInput,ref:e,value:n,onCopy:d,onChange:u=>s(u.target.value)})}),(0,je.jsx)("div",{className:o.actions,children:(0,je.jsx)(F.Button,{shortKeys:[8679,8629],onClick:c,children:r("copy")})})]})})},Jl=Tm;var Go={};Y(Go,{enUS:()=>Em,nlNL:()=>km});var Em={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?"}]},km={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?"}]};var dt=k(require("react")),Xo=require("react-redux");var $r={};Y($r,{enUS:()=>Rm,nlNL:()=>Pm});var Rm={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"}]},Pm={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 Yl={root:"io",title:"Pe",empty:"Qe",status:"Ve",form:"ro",input:"to",submit:"We",question:"Ze",answer:"_e",alignRight:"oi"};var lo=require("@reduxjs/toolkit");var ys=require("@reduxjs/toolkit");var Lm={data:null,fetchState:"idle"},ec=t=>{var e;return(e=t.knowledgeAssistant)==null?void 0:e.data},jo=(0,ys.createAsyncThunk)("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}),Am=(0,ys.createSlice)({name:"knowledgeAssistant",initialState:Lm,reducers:{},extraReducers:t=>{t.addCase(jo.pending,e=>{e.fetchState="loading"}).addCase(jo.rejected,e=>{e.fetchState="error"}).addCase(jo.fulfilled,(e,o)=>{e.fetchState="done",e.data=o.payload})}}),tc=Am.reducer;var qr={data:[],fetchState:"idle"},oc=t=>{var e;return(e=t.answer)==null?void 0:e.data},nc=t=>t.answer.fetchState,co=(0,lo.createAction)("answer/resetKnowledgeSearch"),ao=(0,lo.createAsyncThunk)("answer/getAnswer",async(t,e)=>{var l,c,d;let{deepdeskAPI:o}=e.extra,n=e.getState().answer.data,s=ec(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}}),Mm=(0,lo.createSlice)({name:"answer",initialState:qr,reducers:{},extraReducers:t=>{t.addCase(ao.pending,e=>{e.fetchState="loading"}).addCase(ao.rejected,e=>{e.fetchState="error"}).addCase(ao.fulfilled,(e,o)=>{e.fetchState="done",e.data=[...e.data,o.payload]}).addCase(D,()=>qr).addCase(co,()=>qr)}}),sc=Mm.reducer;var Wo=require("react/jsx-runtime"),rc=()=>(0,Wo.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 512 512","aria-labelledby":"paperPlaneTitle",children:[(0,Wo.jsx)("title",{id:"paperPlaneTitle",children:"PaperPlane"}),(0,Wo.jsx)("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"})]});var pe=require("react/jsx-runtime"),Nm=({onUse:t,onResetQuestion:e,question:o})=>{let[n,s]=dt.default.useState(""),{setSelected:r}=ct(),i=(0,dt.useRef)(null),a=h("EntitiesList",Yl),l=P($r),c=(0,Xo.useDispatch)(),d=(0,Xo.useSelector)(oc),u=(0,Xo.useSelector)(nc),g=async f=>{f.preventDefault(),f.stopPropagation(),n!==""&&c(ao(n))},p=(f,m)=>{c(Q({name:"knowledge assist source viewed",data:{question:m,sourceViewed:f.url||f.name},options:{includeConversationData:!0}}))};return(0,dt.useEffect)(()=>{var f;o&&u==="idle"?c(ao(o)):(f=i.current)==null||f.focus()},[i,u]),(0,dt.useEffect)(()=>{u==="done"&&(c(Q({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]),(0,dt.useEffect)(()=>{i.current&&i.current.scrollIntoView({behavior:"smooth"})},[i,d]),(0,pe.jsxs)("div",{className:a.root,children:[d.length>0&&(0,pe.jsx)("div",{className:a.alignRight,children:(0,pe.jsx)(F.Button,{onClick:e,children:l("reset")})}),d.map(({question:f,answer:m},y)=>(0,pe.jsx)(F.List,{children:(0,pe.jsx)(F.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"&&(0,pe.jsx)("p",{className:a.status,children:l("loading")}),u==="error"&&(0,pe.jsx)("p",{className:a.status,children:l("error")}),(0,pe.jsxs)("form",{className:a.form,onSubmit:g,children:[(0,pe.jsx)("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)}}),(0,pe.jsx)("button",{type:"submit",className:a.submit,children:(0,pe.jsx)(rc,{})})]})]})},ic=Nm;var vs=require("@reduxjs/toolkit");var Om={data:null,fetchState:"idle"},ut=t=>t.profile.data,Ss=t=>t.profile.data?t.profile.data.uiConfig.widget.types.filter(e=>e.isActive):[],Zo=(0,vs.createAsyncThunk)("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)}),_m=(0,vs.createSlice)({name:"profile",initialState:Om,reducers:{},extraReducers:t=>{t.addCase(Zo.pending,e=>{e.fetchState="loading"}).addCase(Zo.rejected,e=>{e.fetchState="error"}).addCase(Zo.fulfilled,(e,o)=>{e.fetchState="done",e.data=o.payload})}}),ac=_m.reducer;var yc=require("react");var vc=require("react-redux");var Ht=require("@reduxjs/toolkit");var Dm=["{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}"],Hm=new RegExp(Dm.map(t=>`(?:${t.replace("{","\\{").replace("}","\\}")})`).join("|"));function lc(t,e){let o=t.split(Hm),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 cc(t,e){return typeof e=="boolean"?t:t.slice(0,e)}var uc={suggestions:[],fetchState:"idle",isInitialRequest:null},dc={default:uc},pc=t=>e=>{var o;return((o=e.textSuggestions[t])==null?void 0:o.suggestions)??[]},gc=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")},xs=t=>t.textSuggestions,mc=t=>{let e=t.toLowerCase();return o=>{let n=o.text.toLowerCase();return n.startsWith(e)&&n.length>e.length}},bs=(0,Ht.createAction)("textSuggestions/refresh"),Ie=(0,Ht.createAsyncThunk)("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=eo(n);if(!s)throw new Error("No current conversation to fetch text suggestions");let l=await o.getTextSuggestions(s,Ao(n),t);if(t==="default"){let d=i?l.filter(mc(a)):l;e.dispatch(Me(d.slice(0,r)))}return l}),Qo=(0,Ht.createAsyncThunk)("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,{...Ao(n),input:t});if(!e.getState().input.text)throw new Error("Abort");return a&&(l=l.filter(mc(t))),i&&(l=l.map(d=>({...d,text:d.source!=="trie-with-typos"?lc(d.text,t):d.text}))),l=cc(l,r),e.dispatch(Me(l)),l}),fc=(0,Ht.createSlice)({name:"textSuggestions",initialState:dc,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(Ie.pending,(e,o)=>{let n=o.meta.arg,s=e[n]||uc;return{...e,[n]:{...s,fetchState:"loading",isInitialRequest:s.isInitialRequest===null}}}).addCase(Ie.rejected,(e,o)=>{let n=o.meta.arg;e[n]&&(e[n].fetchState="error")}).addCase(Ie.fulfilled,(e,o)=>{let n=o.meta.arg;e[n]&&(e[n].fetchState="done",e[n].suggestions=o.payload)}).addCase(Qo.pending,e=>{e.default.fetchState="loading"}).addCase(Qo.rejected,e=>{e.default.fetchState="error"}).addCase(Qo.fulfilled,(e,o)=>{e.default.fetchState="done",e.default.suggestions=o.payload}).addCase(D,()=>dc)}}),{setTextSuggestions:L0,setSuggestionState:A0}=fc.actions,hc=fc.reducer;var Gr=require("react-redux");var Ft=require("react/jsx-runtime"),Fm=({commands:t,onClick:e})=>{var a,l,c;let o=(0,vc.useDispatch)(),n=P(Go),s=(0,Gr.useSelector)(ut),r=(0,Gr.useSelector)(xs),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(0,yc.useEffect)(()=>{i.forEach(({type:d})=>{(!r[d]||r[d].suggestions.length===0)&&o(Ie(d))})},[]),(0,Ft.jsxs)("div",{children:[t.length>0&&(0,Ft.jsx)(F.List,{heading:n("commands"),children:t.map((d,u)=>(0,Ft.jsx)(F.ListItem,{id:`command-${u}`,closeOnSelect:!1,onClick:d.onClick,children:d.label},d.label))}),i.map(({type:d,title:u})=>{var g;return(0,Ft.jsx)(F.List,{heading:u,orientation:"vertical",children:(g=r[d])==null?void 0:g.suggestions.map((p,f)=>(0,Ft.jsx)(F.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)})]})},Sc=Fm;var W=require("react/jsx-runtime"),Km=200,Um=5,zm=4,xc=(t,e)=>!e||t.toLowerCase().includes(e.toLowerCase()),Vm=()=>{let t=(0,Oe.useDispatch)(),e=he(),o=P(Go),[n,s]=(0,re.useState)(!1),[r,i]=(0,re.useState)(""),a=(0,Oe.useSelector)(Wa),l=(0,Oe.useSelector)(ut),[c,d]=(0,re.useState)(),u=(0,Oe.useSelector)(te),g=b("showSearch"),p=b("showEntitiesCommand"),f=b("showSummaryCommand"),m=b("showKnowledgeSearch"),y=b("showImageSearch"),E=b("searchTriggerKey"),S=(0,Oe.useSelector)(xl),v=(0,Oe.useSelector)(Xa),R=(0,Oe.useSelector)(Za),x=(0,Oe.useSelector)(ja),w=C=>Wt(v.filter(Z=>Z.type===C.toUpperCase()),C),O=[{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),q=[{label:o("entitiesClipboard"),onClick:()=>t(we("entities")),shouldShow:p&&xc(o("entitiesClipboard"),r)},{label:o("summaryClipboard"),onClick:()=>t(we("summary")),shouldShow:f&&xc(o("summaryClipboard"),r)},{label:r?`${o("knowledgeAssist")}: ${r}`:o("knowledgeAssist"),onClick:()=>t(we("knowledgeAssist")),shouldShow:m}].filter(C=>C.shouldShow),K=(S==null?void 0:S.map(C=>({value:C.code.toUpperCase(),label:`${C.name}s`,list:w(C.code.toUpperCase()),listOrientation:"vertical",lineClamp:!0})))||[],A=(0,re.useCallback)((0,bc.default)((C,Z)=>{t(Pt({query:C,type:Z,tags:["search-overlay"],size:c?50:20}))},Km),[c]),_=(0,re.useCallback)((C,Z)=>{switch(Z.type){case"IMAGE":e.send(Cr,{suggestion:Z});break;default:e.send(at,{text:C,suggestion:Z})}t(ce(!1))},[t]),I=C=>{At(C.text),t(Q({name:"entity copied",data:{entity:C,type:"copy"}})),t(ce(!1))},X=(0,re.useCallback)(C=>{t(Q({name:"suggestion feedback",data:{text:C.text,source:"search",context:r},options:{includeConversationData:!0}}))},[r]),lr=C=>{e.send(at,{text:C,suggestion:{source:"knowledge-assist",text:C}}),t(Q({name:"answer used",data:{originalText:C},options:{includeConversationData:!0}})),i(""),t(we("search")),t(co()),t(ce(!1))},cr=C=>{At(C),t(ce(!1))};function Wt(C,Z){return C.slice(0,c?10:Z.toLowerCase()==="image"?zm:Um)}function Eo(C){return Z=>{n?window.confirm(o("warning"))&&(C(Z),s(!1)):C(Z)}}return(0,re.useEffect)(()=>{r?A(r,c):t(Un())},[r,c]),(0,re.useEffect)(()=>{a==="search"&&t(co())},[a]),(0,re.useEffect)(()=>{u&&t(Bo())},[u]),zl(E,()=>t(ce(!0))),!g||!l?null:(0,W.jsxs)(F,{placeholder:o("searchPlaceholder"),typePlaceholder:o("typePlaceholder"),onChangeSearch:i,onChangeOpen:Eo(C=>t(ce(C))),onChangeType:C=>d(C),onChangePage:Eo(C=>t(we(C))),selectedType:c,search:r,page:a,isOpen:x,types:[...K,...O],children:[(0,W.jsxs)(F.Page,{id:"search",children:[r.length===0&&(0,W.jsx)(Sc,{commands:q,onClick:_}),r.length>0&&(0,W.jsxs)(re.Fragment,{children:[q.length>0&&(0,W.jsx)(F.List,{heading:o("commands"),children:q.map((C,Z)=>(0,W.jsx)(F.ListItem,{closeOnSelect:!1,onClick:C.onClick,id:`commands-${Z}`,children:C.label},C.label))}),[...K,...O].map(({value:C,label:Z,list:Ui,lineClamp:Pp,listOrientation:Ip})=>(0,W.jsx)(F.List,{heading:Z,orientation:Ip==="horizontal"?"horizontal":"vertical",onShowAll:()=>d(C),hasMore:!c&&R[C.toLowerCase()]>Wt(Ui,C).length,children:Wt(Ui,C).map(ae=>(0,W.jsx)(F.ListItem,{id:`${C}-${ae.id}`,closeOnSelect:!1,lineClamp:Pp,onClick:()=>_(ae.text,ae),description:C!=="IMAGE"?ae.title&&ae.text:void 0,onFeedback:C!=="IMAGE"?()=>X(ae):void 0,children:C==="IMAGE"?(0,W.jsx)(F.Image,{title:ae.title||ae.text,src:ae.image}):ae.title||ae.text},`${ae.id}-${ae.text}`))},C))]})]}),(0,W.jsx)(F.Page,{id:"entities",title:o("entitiesTitle"),onDismiss:Eo(()=>{t(we("search"))}),children:(0,W.jsx)(Gl,{onCopy:I})}),(0,W.jsx)(F.Page,{id:"summary",title:o("summaryTitle"),onDismiss:Eo(()=>{t(we("search"))}),children:(0,W.jsx)(Jl,{onCopy:cr})}),(0,W.jsx)(F.Page,{id:"knowledgeAssist",title:o("knowledgeAssist"),onDismiss:Eo(()=>{t(co()),t(we("search"))}),children:(0,W.jsx)(ic,{question:r,onUse:lr,onResetQuestion:()=>{t(co()),i("")}})})]})},Cc=Vm;var Jo=require("react/jsx-runtime"),$m=()=>{let t=b("showSearch"),e=b("isEmbedded");return(0,Jo.jsxs)(wc.Fragment,{children:[t&&(0,Jo.jsx)(Cc,{}),e&&(0,Jo.jsx)(vl,{})]})},Tc=$m;var Pc=k(require("classnames")),Ic=require("react-redux");var Cs=require("react/jsx-runtime"),Ec=({className:t})=>(0,Cs.jsx)("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:(0,Cs.jsx)("g",{children:(0,Cs.jsx)("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`})})});var qr=require("react/jsx-runtime"),Lm={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},Cc=({className:t,color:e})=>(0,qr.jsx)("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,qr.jsx)("path",{d:"M172.03 0.0199966H0V86.03C47.5 86.03 86 124.54 86 172.04C86 124.54 124.51 86.03 172.01 86.03C219.51 86.03 258.03 124.54 258.03 172.04C258.03 219.54 219.52 258.05 172.01 258.05C124.5 258.05 86 219.54 86 172.04C86 219.54 47.5 258.05 0 258.05V344.06H172.03C267.04 344.06 344.06 267.04 344.06 172.03C344.06 77.02 267.04 0 172.03 0V0.0199966Z",fill:Lm[e||"pink"]})});var wc={root:"j",text:"q",isLoggedIn:"Qe",isLoggedOut:"oo",icon:"Ve",logo:"We",lock:"Ze"};var Gr={};Y(Gr,{enUS:()=>Nm,nlNL:()=>Om});var Nm={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},Om={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var kc=require("react-redux"),zt=require("react/jsx-runtime"),Rc=({onLogIn:t})=>{let e=P(Gr),o=C("floatingMenu"),n=C("productName"),s=(0,kc.useDispatch)(),r=(0,Ec.useSelector)(ee),i=h("FloatingMenu",wc);if(r===null||o===!1)return null;let a=()=>{r===!0?s(de(!0)):t()};return(0,zt.jsxs)("button",{className:(0,Tc.default)(i.root,{[i.isLoggedIn]:r,[i.isLoggedOut]:!r}),onClick:a,children:[(0,zt.jsx)("div",{className:i.text,children:e(r?"search":"signin",{productName:n})}),(0,zt.jsxs)("div",{className:i.icon,children:[(0,zt.jsx)(Cc,{className:i.logo,color:"pink"}),r===!1&&(0,zt.jsx)(bc,{className:i.lock})]})]})};var Ps=require("react"),Xe=require("react-redux");var Pc=require("react");function go(t){(0,Pc.useEffect)(()=>{let e=o=>{o.isWithinRoot||t(o)};return document.body.addEventListener("mouseup",e),()=>{document.body.removeEventListener("mouseup",e)}},[t])}function Vt(t){t.addEventListener("mouseup",e=>{e.isWithinRoot=!0},!0)}function mo(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}var Ic=require("@reduxjs/toolkit"),_m={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var Ts=({ui:t})=>t.overlayCollapsed;var Ac=(0,Ic.createSlice)({name:"ui",initialState:_m,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:tn,setInputHasFocus:jr,setOverlayCollapsed:mt,setOpenOverlayWhenTyping:Lc,setOverlayCollapsedUserOverwrite:Mc}=Ac.actions,Nc=Ac.reducer;var ks=require("react");var Hc=require("interweave"),fo=require("react"),Es=require("react-redux");var Oc=require("react");function _c(t,e,o){(0,Oc.useEffect)(()=>{let n=t.current;return n?(n.addEventListener(e,o),()=>{n.removeEventListener(e,o)}):()=>{}},[t,e,o])}var Dc={root:"_e",actions:"oi",badge:"ei",formattedText:"eo"};var $t=require("react/jsx-runtime"),Fm=["search","personal-collection-search","search-autocomplete"];function Bm(t,e,o,n={}){let s="";return Fm.includes(e)?s=Cl(Nr(t,o,{stripAgentPart:!0}),n.searchKeywords??[o]):s=Nr(t,o,n),n.placeholders===!0&&(s=wl(s)),s}var Km=()=>{},Um=({index:t,selected:e,suggestion:o,onFeedback:n})=>{let s=C("inlineSuggestions"),r=(0,Es.useSelector)(to),i=(0,Es.useDispatch)(),a=h("TextSuggestion",Dc),l=(0,fo.useRef)(null);(0,fo.useEffect)(()=>{let d=setTimeout(()=>{i(ka({text:o.text,suggestion:o}))},500);return()=>{clearTimeout(d)}},[o]),_c(l,"click",()=>{i(lt(t)),i(Ne({suggestion:o,text:o.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let c=(0,fo.useMemo)(()=>Bm(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:(0,$t.jsxs)("div",{className:a.root,onMouseEnter:()=>i(lt(t)),children:[(0,$t.jsx)(O,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:Km,children:(0,$t.jsx)(Hc.Interweave,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:c})}),e&&n&&(0,$t.jsx)("div",{className:a.actions,children:(0,$t.jsx)(us,{onFeedback:()=>n(o),suggestion:o.text})})]})},Fc=Um;var Wr=require("react/jsx-runtime"),zm=({onFeedback:t,suggestions:e,selectedIndex:o,reverse:n})=>{let s=(0,ks.useMemo)(()=>{let r=e.map((i,a)=>(0,Wr.jsx)(Fc,{index:a,selected:a===o,suggestion:i,onFeedback:t},`${i.text}-${i.source}`));return n?r.reverse():r},[e,o,n]);return(0,Wr.jsx)(ks.Fragment,{children:s})},Rs=zm;var Bc={root:"ii",paper:"ri"};var on=require("react/jsx-runtime"),$m=({textSuggestions:t,selectedIndex:e})=>{let o=(0,Ps.useRef)(null),n=h("InlineSuggestionsOverlay",Bc),s=(0,Xe.useSelector)(mo),r=(0,Xe.useDispatch)(),i=(0,Xe.useSelector)(ee),a=(0,Xe.useSelector)(eo),l=(0,Xe.useSelector)(Ts),c=C("showTextSuggestions");return go(()=>{setTimeout(()=>{r(mt({collapse:!0,skipWhenInputFocus:!0}))})}),(0,Ps.useEffect)(()=>{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:(0,on.jsx)("div",{className:n.root,"data-variant":"inline",children:(0,on.jsx)("div",{ref:o,className:n.paper,children:(0,on.jsx)(ce,{children:(0,on.jsx)(Rs,{suggestions:t,selectedIndex:e})})})})},qm=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),Kc=(0,Xe.connect)(qm)($m);var Uc=require("react-redux");var nn=require("react/jsx-runtime"),Gm=({children:t})=>{let o=C("locale").replace("-","");return(0,nn.jsx)(Pr.Provider,{value:o,children:t})},jm=({store:t,customStyles:e={},children:o})=>(0,nn.jsx)(Uc.Provider,{store:t,children:(0,nn.jsx)(Gm,{children:(0,nn.jsx)(Ro.Provider,{value:e,children:o})})}),qt=jm;var As=k(require("classnames")),ho=require("react"),_e=require("react-redux");var zc=require("react");function Vc(t,e){let[o,n]=(0,zc.useState)(()=>{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 $c=()=>/Mac/i.test(navigator.platform);var Gc=k(require("classnames")),Ze=require("react");var Xr={};Y(Xr,{enUS:()=>Wm,nlNL:()=>Xm});var Wm={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"}]}]},Xm={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 qc={root:"ti",anchor:"ni",anchorButton:"ai"};var ft=require("react/jsx-runtime"),Zr=(t,e,o)=>n=>(0,ft.jsx)("button",{className:t.anchorButton,type:"button",value:e,onClick:o,children:n},e),Qm=({className:t,loginUrl:e,isEmbedded:o,onSnooze:n,onLogIn:s})=>{let r=P(Xr),i=we(),a=h("Login",qc),l=C("productName"),c=(0,Ze.useCallback)(S=>{S.preventDefault(),n&&n(parseInt(S.target.value,10))},[]),d=(0,Ze.useCallback)(S=>{S.preventDefault(),i.send(so,!0)},[e]),u=(0,Ze.useMemo)(()=>S=>(0,ft.jsx)("a",{onClick:v=>{v.preventDefault(),s()},href:e,className:a.anchor,target:"_blank",rel:"noreferrer",children:S},"login"),[e]),p=(0,Ze.useCallback)(S=>(0,ft.jsx)("button",{type:"button",className:a.anchorButton,onClick:d,children:S},"prompt"),[d]),{min:g,hour:f,day:m}=(0,Ze.useMemo)(()=>({min:Zr(a,60*10,c),hour:Zr(a,60*60,c),day:Zr(a,60*60*12,c)}),[]);return(0,ft.jsxs)("div",{className:(0,Gc.default)(t,a.root),children:[r("loginPlease",{login:o?p:u,productName:l}),n&&(0,ft.jsxs)(Ze.Fragment,{children:[(0,ft.jsx)("br",{}),r("snooze",{min:g,hour:f,day:m})]})]})},Is=Qm;var Wc=require("react-redux");var jc={root:"io",text:"di"};var sn=require("react/jsx-runtime"),Ym=({title:t})=>{let e=h("SearchTrigger",jc),o=(0,Wc.useDispatch)();return(0,sn.jsxs)("button",{type:"button",className:e.root,onClick:()=>o(de(!0)),children:[(0,sn.jsx)(io,{}),(0,sn.jsx)("span",{className:e.text,children:t})]})},Xc=Ym;var Qr={};Y(Qr,{enUS:()=>ef,nlNL:()=>tf});var ef={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"}]},tf={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 Zc={root:"pi",isInline:"C",toggleButton:"li",toggleButtonWrapper:"S",toggleButtonWrapperHidden:"si",isCollapsed:"ro",collapsible:"xi",hints:"to",hintsHidden:"ci",triggers:"no",triggersRight:"fi"};var B=require("react/jsx-runtime"),nf=({textSuggestions:t,selectedIndex:e,onLogIn:o})=>{let n=h("SuggestionsOverlay",Zc),s=P(Qr),r=(0,_e.useSelector)(mo),i=Ca(),a=(0,_e.useDispatch)(),l=(0,ho.useRef)(null),c=C("searchTriggerKey"),d=C("productName"),u=(0,_e.useSelector)(Ts),p=(0,_e.useSelector)(ee),g=(0,_e.useSelector)(eo),[f,m]=(0,ho.useState)(null),S=C("showSearch"),w=C("showTextSuggestions"),v=C("adminUrl"),y=C("isEmbedded"),[R,x]=Vc("dd-snooze-until-ms",0),T=u||R>Date.now(),M=(0,_e.useSelector)(j=>j.input.text),G=t.filter(j=>j.source!=="gpt").length,K=()=>{T&&x(0),a(Mc(!T))},A=j=>{a(Q({name:"suggestion feedback",data:{text:j.text,source:"overlay",context:M},options:{includeConversationData:!0}}))},N=j=>{let ne=Date.now()+j*1e3;x(ne),E.info(`Snooze until: ${new Date(ne)}`),a(mt({collapse:!0}))};return(0,ho.useEffect)(()=>{G===0&&m(null)},[t,G]),go(()=>{a(mt({collapse:!0,skipWhenInputFocus:!0}))}),p===null||g===!1?null:p===!1?(0,B.jsxs)("div",{ref:l,className:(0,As.default)(n.root,{[n.isCollapsed]:T}),children:[!T&&(0,B.jsxs)("div",{className:n.triggers,children:[(0,B.jsx)("div",{style:{flex:1}}),(0,B.jsx)("div",{className:n.triggersRight,children:(0,B.jsx)(Pt,{className:n.toggleButton,title:s("collapse"),onClick:K,isCollapsed:!1})})]}),(0,B.jsx)("div",{className:n.toggleButtonWrapper,children:(0,B.jsx)(Pt,{className:n.toggleButton,title:s("open",{productName:d}),onClick:K,isCollapsed:!0})}),(0,B.jsx)("div",{className:n.collapsible,children:(0,B.jsx)(Is,{loginUrl:v,isEmbedded:y,onLogIn:o,onSnooze:N})})]}):!i||!r?null:(0,B.jsxs)("div",{ref:l,className:(0,As.default)(n.root,{[n.isCollapsed]:T}),children:[!T&&(0,B.jsxs)("div",{className:n.triggers,children:[(0,B.jsx)("div",{style:{flex:1},children:S&&(0,B.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>m(s($c()?"searchHintMac":"searchHintWindows",{searchTriggerKey:c.toUpperCase()})),onMouseLeave:()=>m(null),children:(0,B.jsx)(Xc,{title:s("search")})})}),(0,B.jsxs)("div",{className:n.triggersRight,onFocus:()=>{},children:[(0,B.jsx)("div",{className:(0,As.default)(!f&&n.hintsHidden,n.hints),children:f}),(0,B.jsx)(Pt,{className:n.toggleButton,title:s("collapse"),onClick:K,isCollapsed:!1})]})]}),(0,B.jsx)("div",{className:n.toggleButtonWrapper,children:(0,B.jsx)(Pt,{className:n.toggleButton,title:s("open",{productName:d}),onClick:K,isCollapsed:!0})}),G>0&&w&&(0,B.jsx)("div",{className:n.collapsible,onFocus:()=>{},children:(0,B.jsx)(ce,{children:(0,B.jsx)(Rs,{onFeedback:A,suggestions:t,selectedIndex:e,reverse:!0})})})]})},sf=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),Qc=(0,_e.connect)(sf)(nf);var qs=k(require("classnames")),bd=require("interweave"),Ye=require("react"),Cd=require("react-redux");var yo=require("react");function Ls(t){return t.contentEditable==="true"}function rf(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 Jc(t){let{selectionStart:e,selectionEnd:o}=Ls(t)?rf(t):t;return[e,o]}function Yc(t){let[,e]=(0,yo.useState)(),o=(0,yo.useRef)(null);return o.current=Jc(t),(0,yo.useEffect)(()=>{let n=()=>{let[s,r]=o.current??[],i=Jc(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 ed(t,e){if(!e)return;let o=t,{value:n}=o,[s,r]=e,i=n.match(Rn);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)})}var td=require("react"),af=["div","span","mark","strong","b","i","u","em"];function Jr(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(af.includes(s)){let i=Array.isArray(n.props.children)?n.props.children:[n.props.children];return[...t.slice(0,t.length-1),(0,td.cloneElement)(n,{children:Jr(i,e,o+1)})]}return[...t,...e]}function ht(t){return t.tagName.toLowerCase()==="textarea"}var Ae={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"};var ud=k(require("classnames")),pd=require("interweave"),Ks=require("react");var vo=require("react");function od(t,e){let o;return[(...n)=>{window.cancelAnimationFrame(o);let s=e?e(...n):n;o=window.requestAnimationFrame(()=>{t(...s)})},()=>window.cancelAnimationFrame(o)]}function Ms(t){let e=(0,vo.useRef)(null),[o,n]=(0,vo.useState)(!1);return(0,vo.useEffect)(()=>{let s=!1,r=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[i,a]=od((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]=od(()=>{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 nd(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Ns(t){return e=>{t.forEach(o=>{typeof o=="function"?o(e):o!=null&&(o.current=e)})}}function sd(t){return t!=null}var ei=k(require("classnames")),ye=require("react");var Os=require("react"),cf=["bottom","height","left","right","top","width"],df=(t={},e={})=>cf.some(o=>t[o]!==e[o]),Qe=new Map,rd,id=()=>{let t=[],e=[];Qe.forEach((o,n)=>{if(n instanceof Element&&!n.isConnected){e.push(n);return}let s=n.getBoundingClientRect();df(s,o.rect)&&(o.rect=s,t.push(o))}),e.forEach(o=>{Qe.delete(o)}),t.forEach(o=>{o.callbacks.forEach(n=>n(o.rect))}),rd=window.requestAnimationFrame(id)};function uf(t,e){return{observe(){let o=Qe.size===0;if(Qe.has(t)){let n=Qe.get(t);n.callbacks.push(e),n.rect&&e(n.rect)}else Qe.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});o&&id()},unobserve(){let o=Qe.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||Qe.delete(t),Qe.size||cancelAnimationFrame(rd)}}}}function Yr(t){let[e,o]=(0,Os.useState)(null);return(0,Os.useLayoutEffect)(()=>{if(!t.current)return;let n=uf(t.current,s=>{o(s)});return n.observe(),()=>{n.unobserve()}},[t]),e}var So=require("react"),ld=require("react-dom");var ad={root:"Ei"};var cd=({children:t,parentNode:e})=>{let[o,n]=(0,So.useState)(null),s=(0,So.useContext)(Ro);return(0,So.useLayoutEffect)(()=>{let r=document.createElement("div");return Vt(r),r.classList.add(ad.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?(0,ld.createPortal)(t,o):null};var De={ref:"Gi",root:"o",positionAbove:"l",positionBelow:"s",positionLeft:"x",positionRight:"c",alignStart:"f",alignCenter:"g",alignEnd:"b"};var _s=require("react/jsx-runtime"),Ds=(t=!1)=>{let[e,o]=(0,ye.useState)(t),n=(0,ye.useCallback)(()=>o(!0),[]),s=(0,ye.useCallback)(()=>o(!1),[]),r=(0,ye.useCallback)(()=>o(a=>!a),[]),i=(0,ye.useRef)(null);return{opened:e,open:n,close:s,toggle:r,triggerRef:i}};function ti(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 xo=({className:t,triggerRef:e,boundaryRef:o=(0,ye.createRef)(),position:n="above",align:s="center",children:r,toStyle:i=ti,parentNode:a,...l})=>{let c=Yr(e),d=Yr(o),u=(0,ye.useMemo)(()=>i(c,d,0),[c,d]);return(0,_s.jsx)(cd,{parentNode:a,children:(0,_s.jsx)("div",{className:(0,ei.default)(De.ref,{[De.positionAbove]:n==="above",[De.positionBelow]:n==="below",[De.positionLeft]:n==="left",[De.positionRight]:n==="right",[De.alignStart]:s==="start",[De.alignCenter]:s==="center",[De.alignEnd]:s==="end"}),style:u,...l,role:"dialog",children:(0,_s.jsx)("div",{className:(0,ei.default)(t,De.root),children:r})})})};var dd=k(require("classnames")),Hs=require("react");var oi=require("react/jsx-runtime"),Fs=(0,Hs.forwardRef)(({className:t,children:e,...o},n)=>{let s=(0,Hs.useRef)(null),r=h("TabCompletion",Ae);return(0,oi.jsx)("div",{ref:Ns([s,n]),className:(0,dd.default)(t,r.popoverContentContainer),...o,children:(0,oi.jsx)("div",{className:r.popoverContent,children:e})})});var yt=require("react/jsx-runtime"),mf=t=>e=>{let o=ti(e);return"top"in o&&(o.width=t.width-(e.left-t.left)-10),o},ff=({inputElement:t,boundaryRef:e,inputStyle:o,children:n,suggestion:s})=>{let r=h("TabCompletion",Ae),i=Ds(),a=(0,Ks.useMemo)(()=>mf(t.getBoundingClientRect()),[t]),[l,c]=Ms(t);return(0,Ks.useEffect)(()=>{c?i.open():i.close()},[c]),(0,yt.jsxs)("span",{children:[(0,yt.jsx)("mark",{ref:Ns([l,i.triggerRef]),className:(0,ud.default)(r.matchKeyword,{[r.hover]:c}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:n}),i.opened&&(0,yt.jsx)(xo,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:(0,yt.jsx)(Fs,{style:o,children:(0,yt.jsx)("div",{className:r.hintText,children:s})})})]})},Bs=class extends pd.Matcher{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${nd(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(sd);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(0,yt.jsx)(ff,{inputElement:o.inputElement,suggestion:o.suggestion,inputStyle:o.inputStyle,boundaryRef:o.boundaryRef,children:e},`keyword_${o.matchString}_${o.key}`)}asTag(){return"mark"}};var gd=require("interweave"),md=k(require("classnames"));var ni=require("react/jsx-runtime"),hf=({inputElement:t,children:e})=>{let o=h("TabCompletion",Ae),[n,s]=Ms(t);return(0,ni.jsx)("mark",{ref:n,className:(0,md.default)(o.matchPlaceholder,{[o.hover]:s}),children:e})},Us=class extends gd.Matcher{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(0,ni.jsx)(hf,{inputElement:o.inputElement,children:e},`placeholder_${o.matchString}_${o.key}`)}asTag(){return"mark"}};var Vs=k(require("classnames")),Sd=require("interweave"),oe=require("react"),xd=require("react-redux");var si=require("react/jsx-runtime"),fd=()=>(0,si.jsx)("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:(0,si.jsx)("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"})});var vt=require("react"),rn=require("react-redux"),yd=k(require("lodash.debounce"));var hd={root:"Ni",content:"Yi"};function zs(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 ri(t){return t.replace("https://www.","").replace("https://","")}var ve=require("react/jsx-runtime"),vf=3,Sf=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),xf=({onSelectLink:t,onDismiss:e,placeholder:o,visitUrlText:n,linkCount:s=vf})=>{let r=h("LinkSearch",hd),[i,a]=(0,vt.useState)(""),l=(0,rn.useDispatch)(),c=(0,rn.useSelector)(lc("url")),d=(0,rn.useSelector)(Va("URL",Sf)),[u,p]=(0,vt.useState)(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,R=u+1===d.length?0:u+1;v.code==="Escape"&&(a(""),e()),v.code==="ArrowUp"&&p(y),v.code==="ArrowDown"&&p(R),v.code==="Enter"&&t(((x=d[u])==null?void 0:x.text)||i)},w=(0,vt.useCallback)((0,yd.default)(v=>{l(Lt({query:v,type:"URL",tags:["link-search"]}))},300),[]);return(0,vt.useEffect)(()=>{i&&w(i)},[i]),(0,vt.useEffect)(()=>()=>{l(zn())},[]),(0,ve.jsxs)("div",{className:r.root,children:[(0,ve.jsx)(ce,{withDivider:!0,children:(i?d:c).slice(0,s).map((v,y)=>(0,ve.jsx)(O,{selected:u===y,onClick:()=>t(v.text),"data-testid":"linksearch-suggestion",children:(0,ve.jsxs)(H,{children:[(0,ve.jsx)(H.Image,{src:zs(v,"small",g||void 0),title:v.title||v.text}),(0,ve.jsxs)(H.Content,{className:r.content,cropText:!0,children:[(0,ve.jsx)(H.Title,{children:v.title||ri(v.text)}),v.title&&ri(v.text)]}),(0,ve.jsx)(O.Actions,{children:(0,ve.jsx)(O.ActionButton,{label:n,onClick:R=>m(R,v.text)})})]})},v.text))}),(0,ve.jsx)(Ko,{value:i,onChange:f,autoFocus:!0,placeholder:o,onKeyUp:S})]})},vd=xf;var ii={};Y(ii,{enUS:()=>bf,nlNL:()=>Cf});var bf={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},Cf={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var te=require("react/jsx-runtime"),wf=(0,oe.forwardRef)((t,e)=>{let o=h("TabCompletion",Ae);return(0,te.jsx)("mark",{ref:e,className:(0,Vs.default)(o.matchSelection)},"selection-start")}),Tf=({startRef:t,boundaryRef:e,inputStyle:o,inputElement:n,children:s})=>{let r=P(ii),i=h("TabCompletion",Ae),a=(0,oe.useRef)(null),l=(0,oe.useRef)(null),[c,d]=(0,oe.useState)(null),u=(0,xd.useDispatch)(),p=Ds(document.activeElement===n),[g]=(0,oe.useState)(()=>document.createRange());p.triggerRef.current=g,(0,oe.useEffect)(()=>()=>g.detach(),[]),(0,oe.useEffect)(()=>{let m=t.current,S=a.current;!m||!S||(g.setStart(m,0),g.setEnd(S,0))},[t.current,a.current]),go(()=>{p.close()});let f=(0,oe.useCallback)(m=>{let S=g.toString(),w=/^http(s?):\/\//.test(m)?m:`https://${m}`;u(Dn({text:`[${S}](${w})`,replace:"selection"}))},[]);return(0,te.jsxs)("span",{children:[(0,te.jsx)("mark",{ref:a,className:(0,Vs.default)(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":p.opened?"true":"false",children:s}),p.opened&&(0,te.jsx)(xo,{className:i.popoverRoot,triggerRef:p.triggerRef,boundaryRef:e,position:"above",align:"start",children:(0,te.jsxs)(Fs,{style:o,ref:l,children:[(0,te.jsx)("div",{className:(0,Vs.default)(i.selectionOptions,{[i.selectionOptionsIsHidden]:c!==null}),children:(0,te.jsxs)("button",{type:"button",tabIndex:c===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>d("insertLink"),children:[(0,te.jsx)(fd,{}),(0,te.jsx)("span",{children:"\xA0"}),(0,te.jsx)("span",{children:r("insertLink")})]})}),c==="insertLink"&&(0,te.jsx)(vd,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:f,onDismiss:()=>{d(null),p.close()}})]})})]},"selection-end")},$s=class extends Sd.Matcher{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(e,o){return this.props=o,this.charCount=0,this.startRef=(0,oe.createRef)(),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?(0,te.jsx)(wf,{ref:this.startRef}):(0,te.jsx)(Tf,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};var wd=require("react-redux");var Je=require("react/jsx-runtime"),Ef=({enabled:t,content:e,tabText:o,showTabHint:n,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:l})=>{let c=h("TabCompletion",Ae),d=C("insertLink"),u=C("showMidSentenceSuggestions"),p=C("inlineSuggestions"),g=Yc(a),f=(0,Ye.useRef)(null),m=(0,wd.useSelector)(ee);(0,Ye.useEffect)(()=>{ht(a)&&g&&ed(a,g)},[g]);let S=(0,Ye.useCallback)(y=>{if(!s||!o)return y;let R=[(0,Je.jsx)("span",{className:c.resetIndent,children:"\u200B"},"u200B"),(0,Je.jsx)("span",{"data-testid":"tab-completion",className:(0,qs.default)(c.tabText,c.resetIndent),"data-source":l,children:o},"tabText")];return n&&R.push((0,Je.jsx)("span",{className:(0,qs.default)(c.hint,c.resetIndent),children:(0,Je.jsx)(wn,{keyCode:"tab"},"tabHint")})),Jr(y,R)},[s,o,n]),w=(0,Ye.useMemo)(()=>{let y=[];return d&&y.push(new $s("selection")),y.push(new Us("placeholders")),r&&y.push(new Bs("keywords")),y},[p,d,r]),v=(0,Ye.useMemo)(()=>{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:(0,Je.jsxs)("div",{ref:y=>{y!=null&&y.parentElement&&(f.current=y==null?void 0:y.parentElement)},className:c.root,style:v,children:[(0,Je.jsx)(bd.Interweave,{tagName:"span",containerTagName:"div",className:(0,qs.default)(c.container,c.agentText),disableLineBreaks:ht(a),content:e||"\u200B",onAfterParse:S,matchers:w,selection:g,keywordMatches:i,inputElement:a,inputStyle:v,boundaryRef:f,inlineSuggestionsOnlyAtEnd:!u}),(0,Je.jsx)("br",{})]})},kf=({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??ro(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}},Td=(0,Cd.connect)(kf)(Ef);var bu=k(require("classnames")),Cu=require("react"),W=require("react-redux");var St=require("@reduxjs/toolkit");var Ed={list:[],fetchState:"idle",isInitialRequest:null},Rd=t=>t.autoflows.list||[],kd=t=>e=>{var o;return(o=e.list)==null?void 0:o.find(n=>n.triggerPayload===t)},et=(0,St.createAsyncThunk)("autoflows/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getAutoflows(t)}),ai=(0,St.createAsyncThunk)("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(et(t.platformSessionId))}),li=(0,St.createAsyncThunk)("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(et(t.platformSessionId))}),Rf=(0,St.createSlice)({name:"autoflows",initialState:Ed,reducers:{},extraReducers:t=>{t.addCase(ai.pending,(e,o)=>{let n=kd(o.meta.arg.triggerPayload)(e);n.state="Started",n.isBusy=!0}),t.addCase(li.pending,(e,o)=>{let n=kd(o.meta.arg.triggerPayload)(e);n.state="Aborted",n.isBusy=!0}),t.addCase(et.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}),t.addCase(et.rejected,e=>{e.fetchState="error"}),t.addCase(et.fulfilled,(e,o)=>{e.list=o.payload,e.fetchState="done"}),t.addCase(_,()=>Ed)}}),Pd=(0,St.createAsyncThunk)("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(et(t))}),s.on("sessionCompleted",()=>{o(et(t))})}),Id=(0,St.createAsyncThunk)("autoflows/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),Ad=Rf.reducer;var xt=require("@reduxjs/toolkit");var Ld={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},Md=t=>t.customMessages.list,Nd=t=>e=>!!e.customMessages.sentSuggestions.find(o=>o===t),Od=t=>e=>!!e.customMessages.answeredSuggestions.find(o=>o===t),_d=t=>e=>!!e.customMessages.errorSuggestions.find(o=>o===t),an=(0,xt.createAsyncThunk)("customMessages/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getCustomMessages(t)}),Gs=(0,xt.createAsyncThunk)("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)}),js=(0,xt.createAsyncThunk)("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)}),Dd=(0,xt.createSlice)({name:"customMessages",initialState:Ld,reducers:{onCustomMessage(t,e){Array.isArray(e.payload)?t.list=e.payload:t.list=[e.payload]}},extraReducers:t=>{t.addCase(an.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(an.rejected,e=>{e.fetchState="error"}).addCase(an.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload||[]}).addCase(Gs.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.errorSuggestions=e.errorSuggestions.filter(n=>o.meta.arg.suggestion.text!==n)}).addCase(Gs.rejected,(e,o)=>{let n=e.sentSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1))}).addCase(js.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.answeredSuggestions.push(o.meta.arg.suggestion.text)}).addCase(js.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(_,()=>Ld)}}),Hd=(0,xt.createAsyncThunk)("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(Dd.actions.onCustomMessage(r))})}),Fd=(0,xt.createAsyncThunk)("customMessages/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),Bd=Dd.reducer;var ln=require("@reduxjs/toolkit"),Pf={token:null,accountUrl:null,interval:null},Kd=t=>e=>{let{passwordlessToken:{token:o,accountUrl:n}}=e;return o&&n?`${n}/apis/admin/session/passwordless/login/?token=${o}&redirect=${t}`:null},ci=(0,ln.createAsyncThunk)("passwordlessToken/getTemporaryPasswordlessToken",async(t,e)=>{let{deepdeskAPI:o}=e.extra,n=await o.requestPasswordlessToken();return{accountUrl:o.client.baseUrl,token:n}}),di=(0,ln.createAsyncThunk)("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:o=1e3*60*10}=t,{dispatch:n}=e;return n(ci()),setInterval(()=>n(ci()),o)}),Ud=(0,ln.createSlice)({name:"passwordlessToken",initialState:Pf,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(ci.fulfilled,(e,o)=>{e.token=o.payload.token,e.accountUrl=o.payload.accountUrl}),t.addCase(di.fulfilled,(e,o)=>{e.interval=o.payload})}}),{stopPollPasswordlessToken:zd}=Ud.actions,Vd=Ud.reducer;function $d(t){let{customMessages:e,autoflows:o}=t;return o.fetchState==="loading"&&o.isInitialRequest===!0||e.fetchState==="loading"&&e.isInitialRequest===!0}var Yd=require("react"),eu=require("react-redux");var Zd=k(require("classnames")),Qd=require("react");var Gd=k(require("classnames"));var qd={root:"Ai"};var Wd=require("react/jsx-runtime"),Af=({className:t,children:e})=>{let o=h("Unicode",qd);return(0,Wd.jsx)("span",{className:(0,Gd.default)(t,o.root),children:e})},jd=Af;var Xd={isDisabled:"Fi",buttonStart:"Hi",root:"Li",buttonStop:"xo",stateBadge:"h",isCompleted:"Mi",isStarted:"Ri",isAborted:"Ti"};var ui={};Y(ui,{enUS:()=>Mf,nlNL:()=>Nf});var Mf={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"}]},Nf={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"}]};var me=require("react/jsx-runtime"),_f=({disabled:t,state:e,displayName:o,description:n,onStartAutoflow:s,onStopAutoflow:r})=>{let i=h("Autoflow",Xd),a=P(ui),l=e==="Started"?"stop":"start",c=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return(0,me.jsxs)(O,{className:(0,Zd.default)(i.root,{[i.isDisabled]:t,[i.isCompleted]:e==="Completed",[i.isAborted]:e==="Aborted",[i.isStarted]:e==="Started"}),children:[(0,me.jsx)(H,{children:(0,me.jsxs)(H.Content,{children:[(0,me.jsxs)(H.Title,{children:[e&&(0,me.jsx)("span",{className:i.stateBadge,children:a(e)}),o]}),(0,me.jsx)("span",{children:n})]})}),(0,me.jsx)(O.Actions,{fixed:e==="Started",children:(0,me.jsx)(O.ActionButton,{primary:!0,className:l==="start"?i.buttonStart:i.buttonStop,onClick:e==="Started"?r:s,disabled:t,label:(0,me.jsxs)(Qd.Fragment,{children:[(0,me.jsx)(jd,{children:c})," ",(0,me.jsx)("span",{children:a(l)})]})})})]})},Jd=_f;var pi=require("react/jsx-runtime"),Df=(t,e)=>{let o=e.filter(n=>n.state==="Started");return o.length>0?o.indexOf(t)===-1:!1},Hf=({autoflows:t,onStartAutoflow:e,onStopAutoflow:o,platformSessionId:n})=>(0,pi.jsx)(Yd.Fragment,{children:t.map(s=>(0,pi.jsx)(Jd,{displayName:s.displayName,description:s.description,disabled:s.isBusy||Df(s,t),state:s.state,onStartAutoflow:()=>e({platformSessionId:n,triggerPayload:s.triggerPayload}),onStopAutoflow:()=>o({platformSessionId:n,triggerPayload:s.triggerPayload})},s.displayName))}),Ff=({autoflows:t,conversation:e})=>{var o;return{autoflows:t.list,platformSessionId:(o=e.current)==null?void 0:o.sessionId}},Bf={onStartAutoflow:ai,onStopAutoflow:li},tu=(0,eu.connect)(Ff,Bf)(Hf);var ou=k(require("classnames")),gi=require("react"),Gt=require("react-redux");var tt={root:"co",title:"fo",isUsed:"Ui",quickReplies:"Bi",quickReply:"Di",hasError:"Ii",label:"Oi",errorIcon:"Xi"};var ie=require("react/jsx-runtime"),Uf=({suggestion:t})=>{let e=P(Ft),o=(0,Gt.useDispatch)(),n=(0,Gt.useSelector)(Nd(t.text)),s=(0,Gt.useSelector)(Od(t.text)),r=(0,Gt.useSelector)(_d(t.text)),i=(0,Gt.useSelector)(In),{replyOptions:a}=t,l=(0,gi.useCallback)(d=>{d.preventDefault(),d.stopPropagation(),!(n||!i)&&o(Gs({platformSessionId:i,suggestion:t}))},[t,n,o,i]),c=(0,gi.useCallback)(d=>{if(d.preventDefault(),d.stopPropagation(),!i||!a)return;let u=parseInt(d.target.dataset.index,10),p=a[u];o(js({platformSessionId:i,reply:p,suggestion:t}))},[t,n,o,i]);return(0,ie.jsxs)(O,{onClick:l,className:(0,ou.default)(tt.root,{[tt.isUsed]:n,[tt.hasError]:r}),children:[(0,ie.jsx)(H,{children:(0,ie.jsxs)(H.Content,{children:[(0,ie.jsxs)(H.Title,{className:tt.title,children:[t.text," ",(0,ie.jsx)(Tn,{className:tt.label,children:"analyse tool"})," ",r&&(0,ie.jsx)("span",{className:tt.errorIcon,role:"img","aria-label":e("sendingError"),title:e("sendingError"),children:"!"})]}),a&&a.length>0&&(0,ie.jsx)("ul",{className:tt.quickReplies,children:a.map(d=>(0,ie.jsx)("li",{className:tt.quickReply,children:d.title},d.title))})]})}),(0,ie.jsxs)(O.Actions,{fixed:r||n,children:[a&&a.length>0&&(0,ie.jsx)(O.DropdownButton,{label:e("answer"),disabled:s,children:a.map((d,u)=>(0,ie.jsx)(O.DropdownItem,{index:u,label:d.title,onClick:c},d.title))}),(0,ie.jsx)(O.ActionButton,{primary:!0,disabled:n,onClick:l,label:e(n?"suggestionSent":r?"tryAgain":"sendSuggestion")})]})]})},nu=Uf;var Ws=require("react"),ru=require("react-redux"),hi=k(require("classnames"));var mi=require("react/jsx-runtime"),fi=()=>(0,mi.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,mi.jsx)("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 su={root:"Ji",entity:"r",entityText:"Ki",iconWrapper:"Pi",icon:"Qi",iconClicked:"Vi"};var He=require("react/jsx-runtime"),Vf=({entities:t})=>{let e=h("EntitiesWidgetList",su),[o,n]=(0,Ws.useState)(void 0),s=(0,ru.useDispatch)(),r=()=>{n(void 0)},i=a=>{t&&(n(t.indexOf(a)),Ot(a.text),s(Q({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,Ws.useEffect)(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[o]),!t||t.length===0?null:(0,He.jsx)("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,l)=>(0,He.jsxs)("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[(0,He.jsx)("span",{className:e.entityText,children:a.text}),(0,He.jsxs)("span",{className:e.iconWrapper,children:[(0,He.jsx)("span",{className:(0,hi.default)(e.icon),children:(0,He.jsx)(fi,{})}),(0,He.jsx)("span",{className:(0,hi.default)(e.icon,o===l&&e.iconClicked),children:(0,He.jsx)(fi,{})})]})]},a.text))})},iu=Vf;var yi=require("react/jsx-runtime"),au=()=>(0,yi.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,yi.jsx)("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});var vi=require("react/jsx-runtime"),lu=()=>(0,vi.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,vi.jsx)("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"})});var Si=require("react/jsx-runtime"),cu=()=>(0,Si.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Si.jsx)("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"})});var uu=k(require("dompurify")),nt=require("react"),pu=k(require("snarkdown"));var du={root:"i",popover:"Wi",options:"go",copyIcon:"Zi",option:"bo",divider:"_i"};var ot=require("react/jsx-runtime"),qf=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>`,Gf=({content:t,useLabel:e,copyLabel:o,onCopy:n,onUse:s})=>{let r=h("Markdown",du),i=(0,nt.useRef)(null),[a,l]=(0,nt.useState)(null),[c,d]=(0,nt.useState)(null),u=(0,nt.useMemo)(()=>{let S=(0,pu.default)(t);return uu.default.sanitize(S).replace(/<\/code>/g,`${qf(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(0,ot.jsxs)(nt.Fragment,{children:[a&&(0,ot.jsx)(xo,{triggerRef:{current:a},parentNode:a,className:r.popover,children:(0,ot.jsxs)("div",{className:r.options,children:[(0,ot.jsx)("button",{type:"button",className:r.option,onClick:f,children:o}),(0,ot.jsx)("div",{className:r.divider}),(0,ot.jsx)("button",{type:"button",className:r.option,onClick:m,children:e})]})}),(0,ot.jsx)("div",{ref:i,className:r.root,dangerouslySetInnerHTML:{__html:u},onMouseOver:g})]})},gu=Gf;var xi={};Y(xi,{enUS:()=>jf,nlNL:()=>Wf});var jf={useCue:[{type:0,value:"Copy"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}]},Wf={useCue:[{type:0,value:"Gebruik"}],copyCue:[{type:0,value:"Kopieer"}],removeCue:[{type:0,value:"Sluiten"}]};var bt=require("react/jsx-runtime"),Xf=({cue:t,onRemove:e,onCopy:o,onUse:n})=>{let s=P(xi),r=l=>{o&&o(l)},i=l=>{n&&n(l)},a=l=>{l.preventDefault(),l.stopPropagation(),e&&e(t.id)};return(0,bt.jsxs)(O,{"data-testid":"cue",children:[(0,bt.jsx)(H,{children:(0,bt.jsxs)(H.Content,{children:[t.title&&(0,bt.jsx)(H.Title,{"data-testid":"widget-cue-title",children:t.title}),(0,bt.jsx)(gu,{content:t.text,useLabel:s("useCue"),copyLabel:s("copyCue"),onCopy:r,onUse:i})]})}),(0,bt.jsx)(O.CloseIcon,{title:s("removeCue"),onClick:a})]})},mu=Xf;var cn=require("react/jsx-runtime"),Zf=({cues:t,onCopyCue:e,onUseCue:o,onRemoveCue:n})=>(0,cn.jsx)(cn.Fragment,{children:t.map(s=>(0,cn.jsx)(mu,{cue:s,onRemove:n,onCopy:e,onUse:o},`${s.id}_${s.timestamp}`))}),fu=Zf;var yu=require("react");var Qf=/(https?:\/\/[^\s]+)/,hu=t=>t.split(" ").find(e=>Qf.test(e));var Se=require("react/jsx-runtime"),Jf=({suggestion:t,lines:e,onUse:o})=>{var d;let n=t.text||t.url||t.message,s=hu(n),r=P(Ft),i=C("showImages"),a=C("fallbackImage"),l=u=>{u.preventDefault(),u.stopPropagation(),o(n)},c=(0,yu.useCallback)(u=>{window.open(s,"_blank"),u.stopPropagation(),u.preventDefault()},[s]);return(0,Se.jsxs)(O,{onClick:l,"data-testid":"edit-suggestion",children:[(0,Se.jsxs)(H,{children:[i&&t.image&&(0,Se.jsx)(H.Image,{src:zs(t,"small",a||void 0),title:t.title}),(0,Se.jsxs)(H.Content,{children:[t.title&&(0,Se.jsx)(H.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((d=t.searchKeywords)==null?void 0:d.length)>0&&(0,Se.jsx)(O.Labels,{labels:t.searchKeywords}),(0,Se.jsx)(H.Content,{cropText:e==="single",lineClamp:e==="multiple",children:n})]})]}),(0,Se.jsxs)(O.Actions,{children:[s&&(0,Se.jsx)(O.ActionButton,{onClick:c,label:r("visitUrl")}),(0,Se.jsx)(O.ActionButton,{primary:!0,onClick:l,label:r("useSuggestion")})]})]})},vu=Jf;var dn=require("react/jsx-runtime"),Yf=({lines:t,suggestions:e})=>{let o=we(),n=(s,r)=>{o.send(ct,{text:s,suggestion:{...r,source:r.source,sourceText:r.text}})};return(0,dn.jsx)(dn.Fragment,{children:e.map(s=>(0,dn.jsx)(vu,{suggestion:s,lines:t,onUse:r=>n(r,s)},s.text||s.url||s.message))})},Su=Yf;var bi={};Y(bi,{enUS:()=>eh,nlNL:()=>th});var eh={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"}]},th={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 xu={root:"or",loginText:"er",stateText:"ho",sectionList:"ir",shortcutList:"rr",shortcut:"tr",link:"mo"};var I=require("react/jsx-runtime"),Xs=(t,e)=>{let o=(0,W.useSelector)(ee);(0,Cu.useEffect)(()=>o?e.every(n=>!!n)?t():()=>{}:()=>{},[...e,o])},nh=({onLogIn:t})=>{let e=P(bi),o=(0,W.useDispatch)(),n=C("isEmbedded"),s=h("Widget",xu),r=C("showAutoflows"),i=C("showCustomMessages"),a=C("showSummaryCommand"),l=C("showKnowledgeSearch"),c=C("showSearch"),d=(0,W.useSelector)(gt),u=(0,W.useSelector)(xs),p=(0,W.useSelector)(Rd),g=(0,W.useSelector)(Ga),f=(0,W.useSelector)(fs),m=(0,W.useSelector)(Md),S=(0,W.useSelector)(An),w=(0,W.useSelector)(eo),v=(0,W.useSelector)(ee),y=(0,W.useSelector)(In),R=(0,W.useSelector)($d),x=(0,W.useSelector)(bs),T=we(),M=(0,W.useSelector)(cc),G=(0,W.useSelector)(Kd("/admin/")),K=C("adminUrl"),A=C("productName"),N=we();if(Xs(()=>(o(an(y)),o(Hd(y)),()=>{o(Fd(y))}),[o,w,i,y]),Xs(()=>(o(et(y)),o(Pd(y)),()=>{o(Id(y))}),[o,w,r,y]),Xs(()=>{u.forEach(({type:D})=>{o(D==="entities"?Re():Ie(D))})},[o,w,S,d]),Xs(()=>(o(di()),()=>{o(zd())}),[o]),w===!1)return(0,I.jsx)("div",{className:s.stateText,children:(0,I.jsx)("div",{children:(0,I.jsx)("p",{children:e("notSupported")})})},"supported");if(v===!1)return(0,I.jsx)("div",{className:s.loginText,children:(0,I.jsx)("div",{children:(0,I.jsx)(Is,{isEmbedded:n,loginUrl:K,onLogIn:t})})},"login");if(!d||!y||v===null||M||R)return(0,I.jsx)("div",{className:s.stateText,children:(0,I.jsx)("div",{children:(0,I.jsx)("p",{children:e("waiting")})})},"waiting");let j=D=>{N.send(ct,{text:D,suggestion:{source:"cue",sourceText:D}})},ne=c||a||l||G;return(0,I.jsx)("div",{className:(0,bu.default)(s.root),"data-testid":"widget",children:(0,I.jsxs)(En,{className:s.sectionList,children:[ne&&(0,I.jsx)(Ke,{title:e("actions"),type:"shortcuts",children:(0,I.jsxs)("div",{className:s.shortcutList,children:[c&&(0,I.jsxs)("button",{className:s.shortcut,"data-testid":"shortcut-search",onClick:()=>T.send("ShowCommandPalette",{isOpen:!0}),children:[(0,I.jsx)(io,{}),e("linkSearch")]}),a&&(0,I.jsxs)("button",{className:s.shortcut,"data-testid":"shortcut-summary",onClick:()=>T.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,I.jsx)(cu,{}),e("linkSummary")]}),l&&(0,I.jsxs)("button",{className:s.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>T.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,I.jsx)(lu,{}),e("linkKnowledgeSearch")]}),G&&(0,I.jsxs)("a",{className:s.shortcut,target:"_blank",href:G,"data-testid":"shortcut-studio-login",rel:"noreferrer",children:[(0,I.jsx)(au,{}),e("linkStudioLogin",{productName:A})]})]})}),i&&m.length>0&&(0,I.jsx)(Ke,{type:"custom-messages","data-testid":"custom-messages",children:(0,I.jsx)(ce,{withDivider:!0,children:m.map(D=>(0,I.jsx)(nu,{suggestion:D},D.text))})}),r&&p.length>0&&(0,I.jsx)(Ke,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:(0,I.jsx)(ce,{withDivider:!0,children:(0,I.jsx)(tu,{})})}),u.map(({type:D,title:Eo,amount:ko,lines:wt})=>{var b;switch(D){case"entities":return f&&f.length>0&&(0,I.jsx)(Ke,{type:D,title:Eo,"data-testid":`type-${D}`,children:(0,I.jsx)(iu,{entities:f})},D);case"cues":return g&&g.length>0&&(0,I.jsx)(Ke,{type:D,title:Eo,"data-testid":`type-${D}`,children:(0,I.jsx)(ce,{withDivider:!0,children:(0,I.jsx)(fu,{cues:g,onRemoveCue:U=>o(Wa({id:U})),onCopyCue:U=>Ot(U),onUseCue:j})})},D);default:return((b=x[D])==null?void 0:b.fetchState)==="done"&&x[D].suggestions.length>0&&(0,I.jsx)(Ke,{type:D,title:Eo,"data-testid":`type-${D}`,children:(0,I.jsx)(ce,{withDivider:!0,children:(0,I.jsx)(Su,{lines:wt,contentType:D,suggestions:x[D].suggestions.slice(0,ko)||[]})})},D)}})]})})},wu=nh;function bo(t){let e=new Range;return e.selectNodeContents(t),e}function Tu(t,e,o){try{return Ct(t,e,o),!0}catch{return!1}}function Zs(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function Qs(t){return"tagName"in t&&t.tagName==="BR"}var un=/[\u200B-\u200D\uFEFF]/g;function Ct(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(un,""),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(Qs(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;Zs(l)&&c&&!Zs(c)&&!Qs(c)&&s++;break}default:break}}if(a(t),n.startContainer===document)throw new Error("Offsets out of bound");return n}function pn(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(un,"").length),g&&(l=c+f.substring(0,r).replace(un,"").length),c+=f.replace(un,"").length;break}case Node.ELEMENT_NODE:{let f=u.nextSibling===null;Qs(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&&Zs(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 gn(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(un,"");p===0&&g===void 0?a+=f:a+=f.substring(p,g);break}case Node.ELEMENT_NODE:{let p=c.nextSibling===null;i===0&&Qs(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&&Zs(c)&&!p&&(a+=`
9
- `);break}default:break}u&&i++}return l(t),a}var Eu=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(Eu||{}),st=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();it(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(Eu).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 ku(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var jt=class extends st{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),gn(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!ku(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!ku(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return pn(this.element,e);let o=this.lastKnownSelection;if(o&&Tu(this.element,o.start,o.end))return o;let n=bo(this.element);return n.collapse(!1),pn(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return gn(this.element,Ct(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 Wt=class extends st{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 Ru(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 sh(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}var Ci=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()}},wi=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=Ru(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()}},Ti=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 wi(e,this.deepdeskUrl,{debug:!0}):new Ci(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=sh(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)}},Pu=Ti;var Co=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var Ei=t=>new Promise(e=>{setTimeout(e,t)});var wo=class extends Co{name="ClientError"},Ri=class extends Co{name="ServerError"},ki=new Map,Le=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(ki.has(i)){n(ki.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,R=!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 Ei(p),x()):T.status===401&&g===!0&&R===!1?(R=!0,await this.refreshToken(),x()):T).catch(async T=>{if(f(T)&&!r.isAborted&&y>0)return await Ei(p),x();throw T}));x().then(T=>T.json().catch(()=>null).then(M=>{T.status>=500?s(new Ri("Server Error",M)):T.status===401?s(new wo("Unauthorized",M)):T.status===403?s(new wo("Forbidden",M)):T.status===404?s(new wo("Not Found",M)):T.status>=400&&s(new wo("Bad Request",M)),delete this.latestRequestByUrl[i],c&&ki.set(i,M),n(M)})).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 rh;(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||={})})(rh||={});function Js(t){return{...L(t),tags:t.tags}}var rt=class t{constructor(e,o={}){this.options=o;this.client=new Le(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",{...$(e),tags:e.tags},{version:"v2"});return Js(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(),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}`),Js(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=$(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return Js(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...$(s),tags:s.tags})),{version:"v2"})).map(s=>Js(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",$({...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:$({...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/",$(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}`,$(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`,$(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",$(e),{abortLatest:!0});return L(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,$(e),{version:"v2"});return L(o)}async knowledgeAssist(e,o,n,s={}){let r=await this.client.post(`/api/knowledge-assist/assistants/${n}/search`,$({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",$(e),{version:"v2"});return L(o)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(oa);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 mn=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(fr(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,L(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 ih;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(ih||={});var fn=class{constructor(e,o={}){this.apiUrl=e;this.client=new Le(e,o)}client;streams={};logger=E;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`,$(o));return L(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,$(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",$(e));return L(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new mn(`${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])}};var or=require("@reduxjs/toolkit");var Au=require("@reduxjs/toolkit");var Iu={startTime:null,stopTime:null},Lu=(0,Au.createSlice)({name:"handlingTime",initialState:Iu,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(_,()=>Iu)}}),{handlingTimeStart:Mu,handlingTimeStop:Ys,handlingTimeReset:Nu}=Lu.actions,Ou=Lu.reducer;var _u=(t={})=>{let e={onAuthError:Yt(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};var tr=require("@reduxjs/toolkit");var er={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var Xt=(0,tr.createAsyncThunk)("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 er.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),ah=(0,tr.createSlice)({name:"styleSuggestions",initialState:er,reducers:{},extraReducers:t=>{t.addCase(Xt.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(Xt.rejected,e=>{e.fetchState="error"}).addCase(Xt.fulfilled,(e,o)=>{e.fetchState="done",it(e.list,o.payload)||(e.list=o.payload)}).addCase(At,e=>{e.list=er.list}).addCase(_,()=>er)}}),Du=ah.reducer;var Hu=(t={})=>{let e,o=!0,n={getStyleSuggestions:Xt,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 lh(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var Fu=(t={})=>{let e={getTextSuggestions:Ie,getAutocompleteSuggestions:Yo,debounce:200,check:mo,...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===Cs.toString();if(!u||!c&&!d)return a;let{input:{userCommitted:g}}=l;return lh(g,i)&&!p||(clearTimeout(o),!e.check(l))||(o=setTimeout(()=>{let S=to(l);S===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(S))},p?0:e.debounce)),a}};var Bu=Xt.fulfilled.toString();function ch(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 Ku=t=>e=>o=>n=>{var c;if(n.type!==Bu){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=ch(s,i);n.type===Bu&&l.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var dh=(0,or.combineReducers)({answer:ec,auth:ga,autoflows:Ad,conversation:ya,contentTypes:yl,customMessages:Bd,passwordlessToken:Vd,entities:Kl,knowledgeAssistant:Ql,handlingTime:Ou,info:Fa,input:Oa,settings:ia,profile:nc,search:qa,summary:Gl,styleSuggestions:Du,ui:Nc,rules:Xa,textSuggestions:pc});function Uu(t){return(0,or.configureStore)({reducer:dh,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),_u(),Fu({debounce:200}),Hu({debounce:500}),Ku(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var uh=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},ph=t=>e=>o=>n=>{var a;let s=e.getState(),r=dr("inlineSuggestions")(s);switch(n.type){case Yt.toString():{!n.payload&&t.emit("logout",void 0);break}case Re.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:n.payload}});break;case je.fulfilled.toString():t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{summary:n.payload.summary}});break;case Q.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 Hn.toString():t.handleKeyDown(n.payload);break;case At.toString():t.logSendMessage(n.payload);break;case Fn.toString():t.handleInputChanged(n.payload);break;case qe.fulfilled.toString():t.broadcast(Sr,n.payload,!1),t.emit("cues",n.payload);break;default:break}let i=o(n);switch(n.type){case At.toString():t.handleAfterSendMessage(n.payload);break;case tn.toString():t.onUpdateShowTabHint(n.payload);break;case Ys.toString():t.logHandlingTime();break;case Ne.toString():{let{start:l,end:c}=s.input.selection;t.emit("select-suggestion",{type:uh(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0}),r&&(e.dispatch(Me([])),e.dispatch($e()));break}case Dn.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 Lo.toString():{let l=e.getState(),{text:c,selection:d}=l.input.userCommitted;t.emit("reset",{text:c,selectionAfter:d},{mayApplyChanges:!0});break}case Bn.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 Me.toString():{r&&n.payload.length>0&&e.dispatch(lt(0));break}default:break}return i},zu=ph;function Pi(t){return t.toISOString().replace("T"," ").replace("Z","")}function Vu(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:Pi(o),timeStop:Pi(n)}}function $u(t,e,o){var M,G,K;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((A,{text:N,searchTerm:j})=>A+N.length-(j?j.length:0),0),y=c??Date.now(),R=(Date.now()-y)/1e3+(d||0),x=s/R,T=f.reduce((A,{searchTerm:N})=>A+(N?N.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:R,charsPerSecond:x,numPastes:l,textSuggestionsV2:f,suggestionsCounters:[{source:"gpt",countOffered:m.filter(A=>A.source==="gpt").length}],agentId:(M=e.info.agentInfo)==null?void 0:M.agentId,agentName:(G=e.info.agentInfo)==null?void 0:G.agentName,agentEmail:(K=e.info.agentInfo)==null?void 0:K.agentEmail}}function Ii(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return Ii(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?Ii(s,e):null}function qu(t,e){return Ii(t,e)}function Gu(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function gh(t){return typeof t=="object"&&t!==null&&"tagName"in t}function nr(t){return gh(t)&&(ht(t)||Ls(t))}var ju,Fe=new Map,mh=["bottom","height","left","right","top","width"],fh=(t={},e={})=>mh.some(o=>t[o]!==e[o]);function Wu(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,...Wu(e)]:[]}function Xu(t,e){return!t||!e?null:{...t,top:t.top+e.top,left:t.left+e.left}}var sr=!1,Zu=()=>{sr=!0;let t=[];if(Fe.forEach((e,o)=>{if(!o.isConnected){e.rect=null,t.push(e),Fe.delete(o);return}let n=o.getBoundingClientRect();fh(n,e.rect)&&(e.rect=n,t.push(e))}),t.forEach(e=>{let o=e.parentRects?e.parentRects.reduce(Xu,e.rect):e.rect;e.callbacks.forEach(n=>n(o))}),Fe.size===0){sr=!1;return}ju=window.requestAnimationFrame(Zu)};function Ai(t,e){let o=Wu(t),n=[],s=o.map((r,i)=>Ai(r,a=>{n[i]=a;let l=Fe.get(t);if(!l)return;let c=n.reduce(Xu,l.rect);l.callbacks.forEach(d=>d(c))}));return{observe(r=!0){if(s.forEach(i=>i.observe(!1)),Fe.has(t)){let i=Fe.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else Fe.set(t,{rect:void 0,callbacks:[e],parentRects:n});r&&!sr&&Zu()},unobserve(){s.forEach(i=>i.unobserve());let r=Fe.get(t);if(r){let i=r.callbacks.indexOf(e);i>=0&&r.callbacks.splice(i,1),r.callbacks.length||Fe.delete(t),Fe.size||(cancelAnimationFrame(ju),sr=!1)}}}}var Qu,Be=new Map,Ju=()=>{Be.forEach((t,e)=>{if(!e.isConnected){Be.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)))}),Be.size!==0&&(Qu=window.requestAnimationFrame(Ju))};function Yu(t,e){return{observe(){let o=Be.size===0;Be.has(t)?Be.get(t).callbacks.push(e):Be.set(t,{visible:void 0,callbacks:[e]}),o&&Ju()},unobserve(){let o=Be.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||Be.delete(t),Be.size||cancelAnimationFrame(Qu)}}}}var Li=["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 Mi(t,e,o){return o.forEach(n=>{e.style[n]=t[n]})}function To(t){return parseFloat(t)}function rr(t){return Math.round(t*1e6)}function ep(t){return t/1e6}function Ni(t,e,o){if(t.boxSizing==="content-box")return;let{clientWidth:n}=e,s=To(t.width),r=To(t.borderLeftWidth),i=To(t.borderRightWidth),a=To(t.paddingRight),l=ep(rr(s)-rr(r)-rr(i)),c=ep(rr(n));if(l-c>2){let d=l-c;o.style.paddingRight=`${a+d}px`}}function hn(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",Vt(o);let n=window.getComputedStyle(t),s=!0,r=()=>{o.scrollTop=t.scrollTop};Mi(n,o,Li),Ni(n,t,o),e.mirrorOverflow&&(o.style.overflow="hidden",t.addEventListener("scroll",r));let i=Yu(t,()=>{Mi(n,o,Li),Ni(n,t,o),r(),setTimeout(r,0)}),a,l=!0,c=Ai(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(Mi(n,o,Li),Ni(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=To(g.borderTopWidth),m=To(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 tp=(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 hh(t){return t.offsetParent!==null}function op(t){if(!hh(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 ir(t,e,o=100){let n=op(t);e({isVisible:n});let s=setInterval(()=>{let r=op(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}var q=require("react/jsx-runtime");var np=tp("showTabHint",!0),yn=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 rt(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let d={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[zu({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=>np.update(u),sendEvent:(u,p)=>this.deepdeskApi.sendEvent(u,p)})]};o&&Object.assign(d,{deepdeskBrokerAPI:new fn(o)}),this.store=Uu(d),this.broadcastEvents=new Pu({debug:!0,deepdeskUrl:c,eventMap:Za(this.store),createCustomChannel:l}),this.store.dispatch(tn(np.value())),this.store.dispatch(Pn({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(Yt(null)),this.store.dispatch(ze()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();ee(n)&&aa(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(ze())).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(pr({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Ln(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Mn({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(gr(e))).payload}async postMessages(e){return(await this.store.dispatch(On(e))).payload}async updateConversation(e){return(await this.store.dispatch(Nn(e))).payload}resetConversation(){this.store.dispatch(_()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(je());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(Pn(e))}setVisitorInfo(e){this.store.dispatch(Ha(e))}async setAgentInfo(e){await this.store.dispatch(Mo(e))}async setAgentSettings(e){await this.store.dispatch(hr(e))}async getAgentSettings(){return(await this.store.dispatch(yr())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(Cs()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Fn(e))}notifyKeyDown(e){this.store.dispatch(Hn(e))}notifyPaste(e,o){this.store.dispatch(Aa({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Pa(e))}notifyExternalSuggestion(e){this.store.dispatch(Ne(e)),this.store.dispatch($e())}async evaluateRule(e,o={}){let{payload:n,error:s}=await this.store.dispatch(qe({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(mt({collapse:!1})),this.inputMediator&&this.store.dispatch(wa({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(Me([])))}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(Ia(xa(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Ea()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},d=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(Ra()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Lo()):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(lt(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(lt(-1)),this.store.dispatch(Lo()),e.preventDefault()):o||(this.store.dispatch(mt({collapse:!0})),this.store.dispatch(Lc(!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(tn(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&g&&g.text.startsWith(p)&&(this.store.dispatch(Ne({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch($e())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(La()),this.store.dispatch(Me([]))}handlingTimeStart(){this.state.handlingTime.startTime||(E.info("Start handling time"),this.store.dispatch(Mu()))}handlingTimeStop(){this.state.handlingTime.startTime&&(E.info("Stop handling time"),this.store.dispatch(Ys()))}logSendMessage(e){let o=$u("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=Vu(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Nu())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch($e()),this.store.dispatch(At(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(Ne({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]=hn(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{(0,xe.unmountComponentAtNode)(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=hn(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{(0,xe.unmountComponentAtNode)(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Vt(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{(0,xe.unmountComponentAtNode)(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),E.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(E.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Na(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(!nr(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),Vt(e),this.inputMediator=f||(ht(e)?new Wt(e):new jt(e)),this.inputMediator.on("change",({plainText:x})=>{this.notifyInputChanged(x)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Ma({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&&qu(e,m)||void 0;if(w){let{customStyles:x,appendOverlayTo:T}=o;if(ht(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let M=this.createInlineContainer(e,"deepdesk-caret");(0,xe.render)((0,q.jsx)(qt,{store:this.store,customStyles:x,children:(0,q.jsx)(Mt,{broadcastEvents:this.broadcastEvents,children:(0,q.jsx)(Kc,{})})}),M),this.inputMediator.on("caret",K=>{this.store.dispatch(Me([])),K?(M.style.display="block",M.style.top=`${K.top}px`,M.style.left=`${K.left}px`):M.style.display="none"});let G=this.overlayContainerFactory("floating-menu",y||e,{appendTo:typeof v=="object"&&"appendOverlayTo"in v?v.appendOverlayTo:T},x==null?void 0:x.floatingMenuRootNode);(0,xe.render)((0,q.jsx)(qt,{store:this.store,customStyles:x,children:(0,q.jsx)(Mt,{broadcastEvents:this.broadcastEvents,children:(0,q.jsx)(Rc,{onLogIn:()=>this.loginViaPopup().catch(K=>E.warn(K.message))})})}),G)}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);(0,xe.render)((0,q.jsx)(qt,{store:this.store,customStyles:n,children:(0,q.jsx)(Mt,{broadcastEvents:this.broadcastEvents,children:(0,q.jsx)(Td,{inputElement:e})})}),x),(0,xe.render)((0,q.jsx)(qt,{store:this.store,customStyles:n,children:(0,q.jsx)(Mt,{broadcastEvents:this.broadcastEvents,children:(0,q.jsx)(Qc,{onLogIn:()=>this.loginViaPopup().catch(M=>E.warn(M.message))})})}),T)}(0,xe.render)((0,q.jsx)(qt,{store:this.store,customStyles:n,children:(0,q.jsx)(Mt,{broadcastEvents:this.broadcastEvents,children:(0,q.jsx)(xc,{})})}),this.createContainer("deepdesk-overlays"));let R;this.inputMediator.on("selection",x=>{clearTimeout(R),x===null?R=setTimeout(()=>{x!==null&&this.store.dispatch(mr(x))},500):this.store.dispatch(mr(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(jr(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(jr(!0))),this.store.dispatch(Ta({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch($e()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var 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}),(0,xe.render)((0,q.jsx)(qt,{store:this.store,customStyles:n,children:(0,q.jsx)(Mt,{broadcastEvents:this.broadcastEvents,children:(0,q.jsx)(wu,{onLogIn:()=>this.loginViaPopup().catch(i=>E.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&(0,xe.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=ir(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Gu(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Jo());let e=gt(this.state);e&&(await this.store.dispatch(Xo()),this.store.dispatch(Pn({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(Oo),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=xs(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(Re()):this.store.dispatch(Ie(n))})}catch(n){this.handleError(n)}}};async function sp(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 rp(t,e,o={}){let n=o.replace?Ct(t,o.replace.start,o.replace.end):bo(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?Ct(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 yh(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 vh(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 ip(t,e){return!t.contains(e)||e===t?null:e.parentNode===t?e:ip(t,e.parentNode)}async function ap(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?yh(e):vh(e);if(o){let d=l.startContainer===t?t.childNodes[l.startOffset]:l.startContainer,u=ip(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 lp(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function cp(t,e,o){await new rt(t).authenticateWithKey(e,o)}async function dp(t){let o=await new Le(t).get("/platform/config/",{version:null,useCache:!0});return L(o)}async function Sh(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 up(t,e){let o=await Sh(e),n=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[o]}),t.dispatchEvent(n)}finally{Object.hasOwn(t,"files")&&delete t.files}}0&&(module.exports={Card,ContentEditableInput,DeepdeskAPI,DeepdeskSDK,HTTPClient,InputMediator,InputType,KeyboardHint,Label,Locale,Section,SectionList,Sources,Suggestion,SuggestionList,TextAreaInput,ToggleButton,attachFile,authenticateWithKey,createFullRange,createOverlayContainer,createRangeFromOffsets,escapeHTML,fetchPlatformConfig,formatTextMarkup,getRangeOffsets,getRangeText,insertCKEditor,isHTML,isSupportedInputElement,updateContentEditable,updateTextArea,useStyles,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`})})});var jr=require("react/jsx-runtime"),qm={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},kc=({className:t,color:e})=>(0,jr.jsx)("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,jr.jsx)("path",{d:"M172.03 0.0199966H0V86.03C47.5 86.03 86 124.54 86 172.04C86 124.54 124.51 86.03 172.01 86.03C219.51 86.03 258.03 124.54 258.03 172.04C258.03 219.54 219.52 258.05 172.01 258.05C124.5 258.05 86 219.54 86 172.04C86 219.54 47.5 258.05 0 258.05V344.06H172.03C267.04 344.06 344.06 267.04 344.06 172.03C344.06 77.02 267.04 0 172.03 0V0.0199966Z",fill:qm[e||"pink"]})});var Rc={root:"j",text:"Y",isLoggedIn:"ei",isLoggedOut:"no",icon:"ii",logo:"ri",lock:"ti"};var Wr={};Y(Wr,{enUS:()=>jm,nlNL:()=>Wm});var jm={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},Wm={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Lc=require("react-redux"),Bt=require("react/jsx-runtime"),Ac=({onLogIn:t})=>{let e=P(Wr),o=b("floatingMenu"),n=b("productName"),s=(0,Lc.useDispatch)(),r=(0,Ic.useSelector)(te),i=h("FloatingMenu",Rc);if(r===null||o===!1)return null;let a=()=>{r===!0?s(ce(!0)):t()};return(0,Bt.jsxs)("button",{className:(0,Pc.default)(i.root,{[i.isLoggedIn]:r,[i.isLoggedOut]:!r}),onClick:a,children:[(0,Bt.jsx)("div",{className:i.text,children:e(r?"search":"signin",{productName:n})}),(0,Bt.jsxs)("div",{className:i.icon,children:[(0,Bt.jsx)(kc,{className:i.logo,color:"pink"}),r===!1&&(0,Bt.jsx)(Ec,{className:i.lock})]})]})};var Rs=require("react"),We=require("react-redux");var Mc=require("react");function uo(t){(0,Mc.useEffect)(()=>{let e=o=>{o.isWithinRoot||t(o)};return document.body.addEventListener("mouseup",e),()=>{document.body.removeEventListener("mouseup",e)}},[t])}function Kt(t){t.addEventListener("mouseup",e=>{e.isWithinRoot=!0},!0)}function po(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}var Nc=require("@reduxjs/toolkit"),Xm={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var ws=({ui:t})=>t.overlayCollapsed;var Oc=(0,Nc.createSlice)({name:"ui",initialState:Xm,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:Yo,setInputHasFocus:Xr,setOverlayCollapsed:pt,setOpenOverlayWhenTyping:_c,setOverlayCollapsedUserOverwrite:Dc}=Oc.actions,Hc=Oc.reducer;var Es=require("react");var Uc=require("interweave"),go=require("react"),Ts=require("react-redux");var Fc=require("react");function Bc(t,e,o){(0,Fc.useEffect)(()=>{let n=t.current;return n?(n.addEventListener(e,o),()=>{n.removeEventListener(e,o)}):()=>{}},[t,e,o])}var Kc={root:"ni",actions:"ai",badge:"pi",formattedText:"ao"};var Ut=require("react/jsx-runtime"),Jm=["search","personal-collection-search","search-autocomplete"];function Ym(t,e,o,n={}){let s="";return Jm.includes(e)?s=kl(_r(t,o,{stripAgentPart:!0}),n.searchKeywords??[o]):s=_r(t,o,n),n.placeholders===!0&&(s=Rl(s)),s}var ef=()=>{},tf=({index:t,selected:e,suggestion:o,onFeedback:n})=>{let s=b("inlineSuggestions"),r=(0,Ts.useSelector)(eo),i=(0,Ts.useDispatch)(),a=h("TextSuggestion",Kc),l=(0,go.useRef)(null);(0,go.useEffect)(()=>{let d=setTimeout(()=>{i(Oa({text:o.text,suggestion:o}))},500);return()=>{clearTimeout(d)}},[o]),Bc(l,"click",()=>{i(it(t)),i(Ne({suggestion:o,text:o.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let c=(0,go.useMemo)(()=>Ym(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:(0,Ut.jsxs)("div",{className:a.root,onMouseEnter:()=>i(it(t)),children:[(0,Ut.jsx)(N,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:ef,children:(0,Ut.jsx)(Uc.Interweave,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:c})}),e&&n&&(0,Ut.jsx)("div",{className:a.actions,children:(0,Ut.jsx)(ds,{onFeedback:()=>n(o),suggestion:o.text})})]})},zc=tf;var Zr=require("react/jsx-runtime"),of=({onFeedback:t,suggestions:e,selectedIndex:o,reverse:n})=>{let s=(0,Es.useMemo)(()=>{let r=e.map((i,a)=>(0,Zr.jsx)(zc,{index:a,selected:a===o,suggestion:i,onFeedback:t},`${i.text}-${i.source}`));return n?r.reverse():r},[e,o,n]);return(0,Zr.jsx)(Es.Fragment,{children:s})},ks=of;var Vc={root:"di",paper:"li"};var en=require("react/jsx-runtime"),sf=({textSuggestions:t,selectedIndex:e})=>{let o=(0,Rs.useRef)(null),n=h("InlineSuggestionsOverlay",Vc),s=(0,We.useSelector)(po),r=(0,We.useDispatch)(),i=(0,We.useSelector)(te),a=(0,We.useSelector)(Yt),l=(0,We.useSelector)(ws),c=b("showTextSuggestions");return uo(()=>{setTimeout(()=>{r(pt({collapse:!0,skipWhenInputFocus:!0}))})}),(0,Rs.useEffect)(()=>{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:(0,en.jsx)("div",{className:n.root,"data-variant":"inline",children:(0,en.jsx)("div",{ref:o,className:n.paper,children:(0,en.jsx)(le,{children:(0,en.jsx)(ks,{suggestions:t,selectedIndex:e})})})})},rf=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),$c=(0,We.connect)(rf)(sf);var qc=require("react-redux");var tn=require("react/jsx-runtime"),af=({children:t})=>{let o=b("locale").replace("-","");return(0,tn.jsx)(Lr.Provider,{value:o,children:t})},lf=({store:t,customStyles:e={},children:o})=>(0,tn.jsx)(qc.Provider,{store:t,children:(0,tn.jsx)(af,{children:(0,tn.jsx)(ko.Provider,{value:e,children:o})})}),zt=lf;var Is=k(require("classnames")),mo=require("react"),_e=require("react-redux");var Gc=require("react");function jc(t,e){let[o,n]=(0,Gc.useState)(()=>{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 Wc=()=>/Mac/i.test(navigator.platform);var Zc=k(require("classnames")),Xe=require("react");var Qr={};Y(Qr,{enUS:()=>cf,nlNL:()=>df});var cf={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"}]}]},df={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 Xc={root:"si",anchor:"ci",anchorButton:"xi"};var gt=require("react/jsx-runtime"),Jr=(t,e,o)=>n=>(0,gt.jsx)("button",{className:t.anchorButton,type:"button",value:e,onClick:o,children:n},e),pf=({className:t,loginUrl:e,isEmbedded:o,onSnooze:n,onLogIn:s})=>{let r=P(Qr),i=he(),a=h("Login",Xc),l=b("productName"),c=(0,Xe.useCallback)(y=>{y.preventDefault(),n&&n(parseInt(y.target.value,10))},[]),d=(0,Xe.useCallback)(y=>{y.preventDefault(),i.send(oo,!0)},[e]),u=(0,Xe.useMemo)(()=>y=>(0,gt.jsx)("a",{onClick:S=>{S.preventDefault(),s()},href:e,className:a.anchor,target:"_blank",rel:"noreferrer",children:y},"login"),[e]),g=(0,Xe.useCallback)(y=>(0,gt.jsx)("button",{type:"button",className:a.anchorButton,onClick:d,children:y},"prompt"),[d]),{min:p,hour:f,day:m}=(0,Xe.useMemo)(()=>({min:Jr(a,60*10,c),hour:Jr(a,60*60,c),day:Jr(a,60*60*12,c)}),[]);return(0,gt.jsxs)("div",{className:(0,Zc.default)(t,a.root),children:[r("loginPlease",{login:o?g:u,productName:l}),n&&(0,gt.jsxs)(Xe.Fragment,{children:[(0,gt.jsx)("br",{}),r("snooze",{min:p,hour:f,day:m})]})]})},Ps=pf;var Jc=require("react-redux");var Qc={root:"po",text:"fi"};var on=require("react/jsx-runtime"),mf=({title:t})=>{let e=h("SearchTrigger",Qc),o=(0,Jc.useDispatch)();return(0,on.jsxs)("button",{type:"button",className:e.root,onClick:()=>o(ce(!0)),children:[(0,on.jsx)(so,{}),(0,on.jsx)("span",{className:e.text,children:t})]})},Yc=mf;var Yr={};Y(Yr,{enUS:()=>ff,nlNL:()=>hf});var ff={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"}]},hf={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 ed={root:"gi",isInline:"q",toggleButton:"bi",toggleButtonWrapper:"C",toggleButtonWrapperHidden:"hi",isCollapsed:"do",collapsible:"mi",hints:"lo",hintsHidden:"ui",triggers:"so",triggersRight:"yi"};var B=require("react/jsx-runtime"),vf=({textSuggestions:t,selectedIndex:e,onLogIn:o})=>{let n=h("SuggestionsOverlay",ed),s=P(Yr),r=(0,_e.useSelector)(po),i=La(),a=(0,_e.useDispatch)(),l=(0,mo.useRef)(null),c=b("searchTriggerKey"),d=b("productName"),u=(0,_e.useSelector)(ws),g=(0,_e.useSelector)(te),p=(0,_e.useSelector)(Yt),[f,m]=(0,mo.useState)(null),y=b("showSearch"),E=b("showTextSuggestions"),S=b("adminUrl"),v=b("isEmbedded"),[R,x]=jc("dd-snooze-until-ms",0),w=u||R>Date.now(),O=(0,_e.useSelector)(I=>I.input.text),q=t.filter(I=>I.source!=="gpt").length,K=()=>{w&&x(0),a(Dc(!w))},A=I=>{a(Q({name:"suggestion feedback",data:{text:I.text,source:"overlay",context:O},options:{includeConversationData:!0}}))},_=I=>{let X=Date.now()+I*1e3;x(X),T.info(`Snooze until: ${new Date(X)}`),a(pt({collapse:!0}))};return(0,mo.useEffect)(()=>{q===0&&m(null)},[t,q]),uo(()=>{a(pt({collapse:!0,skipWhenInputFocus:!0}))}),g===null||p===!1?null:g===!1?(0,B.jsxs)("div",{ref:l,className:(0,Is.default)(n.root,{[n.isCollapsed]:w}),children:[!w&&(0,B.jsxs)("div",{className:n.triggers,children:[(0,B.jsx)("div",{style:{flex:1}}),(0,B.jsx)("div",{className:n.triggersRight,children:(0,B.jsx)(Et,{className:n.toggleButton,title:s("collapse"),onClick:K,isCollapsed:!1})})]}),(0,B.jsx)("div",{className:n.toggleButtonWrapper,children:(0,B.jsx)(Et,{className:n.toggleButton,title:s("open",{productName:d}),onClick:K,isCollapsed:!0})}),(0,B.jsx)("div",{className:n.collapsible,children:(0,B.jsx)(Ps,{loginUrl:S,isEmbedded:v,onLogIn:o,onSnooze:_})})]}):!i||!r?null:(0,B.jsxs)("div",{ref:l,className:(0,Is.default)(n.root,{[n.isCollapsed]:w}),children:[!w&&(0,B.jsxs)("div",{className:n.triggers,children:[(0,B.jsx)("div",{style:{flex:1},children:y&&(0,B.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>m(s(Wc()?"searchHintMac":"searchHintWindows",{searchTriggerKey:c.toUpperCase()})),onMouseLeave:()=>m(null),children:(0,B.jsx)(Yc,{title:s("search")})})}),(0,B.jsxs)("div",{className:n.triggersRight,onFocus:()=>{},children:[(0,B.jsx)("div",{className:(0,Is.default)(!f&&n.hintsHidden,n.hints),children:f}),(0,B.jsx)(Et,{className:n.toggleButton,title:s("collapse"),onClick:K,isCollapsed:!1})]})]}),(0,B.jsx)("div",{className:n.toggleButtonWrapper,children:(0,B.jsx)(Et,{className:n.toggleButton,title:s("open",{productName:d}),onClick:K,isCollapsed:!0})}),q>0&&E&&(0,B.jsx)("div",{className:n.collapsible,onFocus:()=>{},children:(0,B.jsx)(le,{children:(0,B.jsx)(ks,{onFeedback:A,suggestions:t,selectedIndex:e,reverse:!0})})})]})},Sf=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),td=(0,_e.connect)(Sf)(vf);var $s=k(require("classnames")),Ed=require("interweave"),Je=require("react"),kd=require("react-redux");var fo=require("react");function Ls(t){return t.contentEditable==="true"}function xf(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 od(t){let{selectionStart:e,selectionEnd:o}=Ls(t)?xf(t):t;return[e,o]}function nd(t){let[,e]=(0,fo.useState)(),o=(0,fo.useRef)(null);return o.current=od(t),(0,fo.useEffect)(()=>{let n=()=>{let[s,r]=o.current??[],i=od(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 sd(t,e){if(!e)return;let o=t,{value:n}=o,[s,r]=e,i=n.match(kn);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)})}var rd=require("react"),bf=["div","span","mark","strong","b","i","u","em"];function ei(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(bf.includes(s)){let i=Array.isArray(n.props.children)?n.props.children:[n.props.children];return[...t.slice(0,t.length-1),(0,rd.cloneElement)(n,{children:ei(i,e,o+1)})]}return[...t,...e]}function mt(t){return t.tagName.toLowerCase()==="textarea"}var Le={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"};var fd=k(require("classnames")),hd=require("interweave"),Bs=require("react");var ho=require("react");function id(t,e){let o;return[(...n)=>{window.cancelAnimationFrame(o);let s=e?e(...n):n;o=window.requestAnimationFrame(()=>{t(...s)})},()=>window.cancelAnimationFrame(o)]}function As(t){let e=(0,ho.useRef)(null),[o,n]=(0,ho.useState)(!1);return(0,ho.useEffect)(()=>{let s=!1,r=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[i,a]=id((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]=id(()=>{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 ad(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Ms(t){return e=>{t.forEach(o=>{typeof o=="function"?o(e):o!=null&&(o.current=e)})}}function ld(t){return t!=null}var oi=k(require("classnames")),ve=require("react");var Ns=require("react"),wf=["bottom","height","left","right","top","width"],Tf=(t={},e={})=>wf.some(o=>t[o]!==e[o]),Ze=new Map,cd,dd=()=>{let t=[],e=[];Ze.forEach((o,n)=>{if(n instanceof Element&&!n.isConnected){e.push(n);return}let s=n.getBoundingClientRect();Tf(s,o.rect)&&(o.rect=s,t.push(o))}),e.forEach(o=>{Ze.delete(o)}),t.forEach(o=>{o.callbacks.forEach(n=>n(o.rect))}),cd=window.requestAnimationFrame(dd)};function Ef(t,e){return{observe(){let o=Ze.size===0;if(Ze.has(t)){let n=Ze.get(t);n.callbacks.push(e),n.rect&&e(n.rect)}else Ze.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});o&&dd()},unobserve(){let o=Ze.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||Ze.delete(t),Ze.size||cancelAnimationFrame(cd)}}}}function ti(t){let[e,o]=(0,Ns.useState)(null);return(0,Ns.useLayoutEffect)(()=>{if(!t.current)return;let n=Ef(t.current,s=>{o(s)});return n.observe(),()=>{n.unobserve()}},[t]),e}var yo=require("react"),pd=require("react-dom");var ud={root:"Hi"};var gd=({children:t,parentNode:e})=>{let[o,n]=(0,yo.useState)(null),s=(0,yo.useContext)(ko);return(0,yo.useLayoutEffect)(()=>{let r=document.createElement("div");return Kt(r),r.classList.add(ud.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?(0,pd.createPortal)(t,o):null};var De={ref:"Li",root:"o",positionAbove:"l",positionBelow:"s",positionLeft:"c",positionRight:"x",alignStart:"f",alignCenter:"g",alignEnd:"b"};var Os=require("react/jsx-runtime"),_s=(t=!1)=>{let[e,o]=(0,ve.useState)(t),n=(0,ve.useCallback)(()=>o(!0),[]),s=(0,ve.useCallback)(()=>o(!1),[]),r=(0,ve.useCallback)(()=>o(a=>!a),[]),i=(0,ve.useRef)(null);return{opened:e,open:n,close:s,toggle:r,triggerRef:i}};function ni(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 vo=({className:t,triggerRef:e,boundaryRef:o=(0,ve.createRef)(),position:n="above",align:s="center",children:r,toStyle:i=ni,parentNode:a,...l})=>{let c=ti(e),d=ti(o),u=(0,ve.useMemo)(()=>i(c,d,0),[c,d]);return(0,Os.jsx)(gd,{parentNode:a,children:(0,Os.jsx)("div",{className:(0,oi.default)(De.ref,{[De.positionAbove]:n==="above",[De.positionBelow]:n==="below",[De.positionLeft]:n==="left",[De.positionRight]:n==="right",[De.alignStart]:s==="start",[De.alignCenter]:s==="center",[De.alignEnd]:s==="end"}),style:u,...l,role:"dialog",children:(0,Os.jsx)("div",{className:(0,oi.default)(t,De.root),children:r})})})};var md=k(require("classnames")),Ds=require("react");var si=require("react/jsx-runtime"),Hs=(0,Ds.forwardRef)(({className:t,children:e,...o},n)=>{let s=(0,Ds.useRef)(null),r=h("TabCompletion",Le);return(0,si.jsx)("div",{ref:Ms([s,n]),className:(0,md.default)(t,r.popoverContentContainer),...o,children:(0,si.jsx)("div",{className:r.popoverContent,children:e})})});var ft=require("react/jsx-runtime"),Pf=t=>e=>{let o=ni(e);return"top"in o&&(o.width=t.width-(e.left-t.left)-10),o},If=({inputElement:t,boundaryRef:e,inputStyle:o,children:n,suggestion:s})=>{let r=h("TabCompletion",Le),i=_s(),a=(0,Bs.useMemo)(()=>Pf(t.getBoundingClientRect()),[t]),[l,c]=As(t);return(0,Bs.useEffect)(()=>{c?i.open():i.close()},[c]),(0,ft.jsxs)("span",{children:[(0,ft.jsx)("mark",{ref:Ms([l,i.triggerRef]),className:(0,fd.default)(r.matchKeyword,{[r.hover]:c}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:n}),i.opened&&(0,ft.jsx)(vo,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:(0,ft.jsx)(Hs,{style:o,children:(0,ft.jsx)("div",{className:r.hintText,children:s})})})]})},Fs=class extends hd.Matcher{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${ad(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(ld);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(0,ft.jsx)(If,{inputElement:o.inputElement,suggestion:o.suggestion,inputStyle:o.inputStyle,boundaryRef:o.boundaryRef,children:e},`keyword_${o.matchString}_${o.key}`)}asTag(){return"mark"}};var yd=require("interweave"),vd=k(require("classnames"));var ri=require("react/jsx-runtime"),Lf=({inputElement:t,children:e})=>{let o=h("TabCompletion",Le),[n,s]=As(t);return(0,ri.jsx)("mark",{ref:n,className:(0,vd.default)(o.matchPlaceholder,{[o.hover]:s}),children:e})},Ks=class extends yd.Matcher{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(0,ri.jsx)(Lf,{inputElement:o.inputElement,children:e},`placeholder_${o.matchString}_${o.key}`)}asTag(){return"mark"}};var zs=k(require("classnames")),wd=require("interweave"),ne=require("react"),Td=require("react-redux");var ii=require("react/jsx-runtime"),Sd=()=>(0,ii.jsx)("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:(0,ii.jsx)("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"})});var ht=require("react"),nn=require("react-redux"),bd=k(require("lodash.debounce"));var xd={root:"Mi",content:"Ri"};function Us(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 ai(t){return t.replace("https://www.","").replace("https://","")}var Se=require("react/jsx-runtime"),Mf=3,Nf=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),Of=({onSelectLink:t,onDismiss:e,placeholder:o,visitUrlText:n,linkCount:s=Mf})=>{let r=h("LinkSearch",xd),[i,a]=(0,ht.useState)(""),l=(0,nn.useDispatch)(),c=(0,nn.useSelector)(pc("url")),d=(0,nn.useSelector)(Qa("URL",Nf)),[u,g]=(0,ht.useState)(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,R=u+1===d.length?0:u+1;S.code==="Escape"&&(a(""),e()),S.code==="ArrowUp"&&g(v),S.code==="ArrowDown"&&g(R),S.code==="Enter"&&t(((x=d[u])==null?void 0:x.text)||i)},E=(0,ht.useCallback)((0,bd.default)(S=>{l(Pt({query:S,type:"URL",tags:["link-search"]}))},300),[]);return(0,ht.useEffect)(()=>{i&&E(i)},[i]),(0,ht.useEffect)(()=>()=>{l(Un())},[]),(0,Se.jsxs)("div",{className:r.root,children:[(0,Se.jsx)(le,{withDivider:!0,children:(i?d:c).slice(0,s).map((S,v)=>(0,Se.jsx)(N,{selected:u===v,onClick:()=>t(S.text),"data-testid":"linksearch-suggestion",children:(0,Se.jsxs)(H,{children:[(0,Se.jsx)(H.Image,{src:Us(S,"small",p||void 0),title:S.title||S.text}),(0,Se.jsxs)(H.Content,{className:r.content,cropText:!0,children:[(0,Se.jsx)(H.Title,{children:S.title||ai(S.text)}),S.title&&ai(S.text)]}),(0,Se.jsx)(N.Actions,{children:(0,Se.jsx)(N.ActionButton,{label:n,onClick:R=>m(R,S.text)})})]})},S.text))}),(0,Se.jsx)(Fo,{value:i,onChange:f,autoFocus:!0,placeholder:o,onKeyUp:y})]})},Cd=Of;var li={};Y(li,{enUS:()=>_f,nlNL:()=>Df});var _f={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},Df={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var oe=require("react/jsx-runtime"),Hf=(0,ne.forwardRef)((t,e)=>{let o=h("TabCompletion",Le);return(0,oe.jsx)("mark",{ref:e,className:(0,zs.default)(o.matchSelection)},"selection-start")}),Ff=({startRef:t,boundaryRef:e,inputStyle:o,inputElement:n,children:s})=>{let r=P(li),i=h("TabCompletion",Le),a=(0,ne.useRef)(null),l=(0,ne.useRef)(null),[c,d]=(0,ne.useState)(null),u=(0,Td.useDispatch)(),g=_s(document.activeElement===n),[p]=(0,ne.useState)(()=>document.createRange());g.triggerRef.current=p,(0,ne.useEffect)(()=>()=>p.detach(),[]),(0,ne.useEffect)(()=>{let m=t.current,y=a.current;!m||!y||(p.setStart(m,0),p.setEnd(y,0))},[t.current,a.current]),uo(()=>{g.close()});let f=(0,ne.useCallback)(m=>{let y=p.toString(),E=/^http(s?):\/\//.test(m)?m:`https://${m}`;u(_n({text:`[${y}](${E})`,replace:"selection"}))},[]);return(0,oe.jsxs)("span",{children:[(0,oe.jsx)("mark",{ref:a,className:(0,zs.default)(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":g.opened?"true":"false",children:s}),g.opened&&(0,oe.jsx)(vo,{className:i.popoverRoot,triggerRef:g.triggerRef,boundaryRef:e,position:"above",align:"start",children:(0,oe.jsxs)(Hs,{style:o,ref:l,children:[(0,oe.jsx)("div",{className:(0,zs.default)(i.selectionOptions,{[i.selectionOptionsIsHidden]:c!==null}),children:(0,oe.jsxs)("button",{type:"button",tabIndex:c===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>d("insertLink"),children:[(0,oe.jsx)(Sd,{}),(0,oe.jsx)("span",{children:"\xA0"}),(0,oe.jsx)("span",{children:r("insertLink")})]})}),c==="insertLink"&&(0,oe.jsx)(Cd,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:f,onDismiss:()=>{d(null),g.close()}})]})})]},"selection-end")},Vs=class extends wd.Matcher{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(e,o){return this.props=o,this.charCount=0,this.startRef=(0,ne.createRef)(),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?(0,oe.jsx)(Hf,{ref:this.startRef}):(0,oe.jsx)(Ff,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};var Rd=require("react-redux");var Qe=require("react/jsx-runtime"),Bf=({enabled:t,content:e,tabText:o,showTabHint:n,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:l})=>{let c=h("TabCompletion",Le),d=b("insertLink"),u=b("showMidSentenceSuggestions"),g=b("inlineSuggestions"),p=nd(a),f=(0,Je.useRef)(null),m=(0,Rd.useSelector)(te);(0,Je.useEffect)(()=>{mt(a)&&p&&sd(a,p)},[p]);let y=(0,Je.useCallback)(v=>{if(!s||!o)return v;let R=[(0,Qe.jsx)("span",{className:c.resetIndent,children:"\u200B"},"u200B"),(0,Qe.jsx)("span",{"data-testid":"tab-completion",className:(0,$s.default)(c.tabText,c.resetIndent),"data-source":l,children:o},"tabText")];return n&&R.push((0,Qe.jsx)("span",{className:(0,$s.default)(c.hint,c.resetIndent),children:(0,Qe.jsx)(Cn,{keyCode:"tab"},"tabHint")})),ei(v,R)},[s,o,n]),E=(0,Je.useMemo)(()=>{let v=[];return d&&v.push(new Vs("selection")),v.push(new Ks("placeholders")),r&&v.push(new Fs("keywords")),v},[g,d,r]),S=(0,Je.useMemo)(()=>{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:(0,Qe.jsxs)("div",{ref:v=>{v!=null&&v.parentElement&&(f.current=v==null?void 0:v.parentElement)},className:c.root,style:S,children:[(0,Qe.jsx)(Ed.Interweave,{tagName:"span",containerTagName:"div",className:(0,$s.default)(c.container,c.agentText),disableLineBreaks:mt(a),content:e||"\u200B",onAfterParse:y,matchers:E,selection:p,keywordMatches:i,inputElement:a,inputStyle:S,boundaryRef:f,inlineSuggestionsOnlyAtEnd:!u}),(0,Qe.jsx)("br",{})]})},Kf=({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??no(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}},Pd=(0,kd.connect)(Kf)(Bf);var Hu=k(require("classnames")),Fu=require("react"),G=require("react-redux");var yt=require("@reduxjs/toolkit");var Id={list:[],fetchState:"idle",isInitialRequest:null},Ad=t=>t.autoflows.list||[],Ld=t=>e=>{var o;return(o=e.list)==null?void 0:o.find(n=>n.triggerPayload===t)},Ye=(0,yt.createAsyncThunk)("autoflows/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getAutoflows(t)}),ci=(0,yt.createAsyncThunk)("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(Ye(t.platformSessionId))}),di=(0,yt.createAsyncThunk)("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(Ye(t.platformSessionId))}),Uf=(0,yt.createSlice)({name:"autoflows",initialState:Id,reducers:{},extraReducers:t=>{t.addCase(ci.pending,(e,o)=>{let n=Ld(o.meta.arg.triggerPayload)(e);n.state="Started",n.isBusy=!0}),t.addCase(di.pending,(e,o)=>{let n=Ld(o.meta.arg.triggerPayload)(e);n.state="Aborted",n.isBusy=!0}),t.addCase(Ye.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}),t.addCase(Ye.rejected,e=>{e.fetchState="error"}),t.addCase(Ye.fulfilled,(e,o)=>{e.list=o.payload,e.fetchState="done"}),t.addCase(D,()=>Id)}}),Md=(0,yt.createAsyncThunk)("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(Ye(t))}),s.on("sessionCompleted",()=>{o(Ye(t))})}),Nd=(0,yt.createAsyncThunk)("autoflows/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),Od=Uf.reducer;var vt=require("@reduxjs/toolkit");var _d={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},Dd=t=>t.customMessages.list,Hd=t=>e=>!!e.customMessages.sentSuggestions.find(o=>o===t),Fd=t=>e=>!!e.customMessages.answeredSuggestions.find(o=>o===t),Bd=t=>e=>!!e.customMessages.errorSuggestions.find(o=>o===t),sn=(0,vt.createAsyncThunk)("customMessages/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getCustomMessages(t)}),qs=(0,vt.createAsyncThunk)("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)}),Gs=(0,vt.createAsyncThunk)("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)}),Kd=(0,vt.createSlice)({name:"customMessages",initialState:_d,reducers:{onCustomMessage(t,e){Array.isArray(e.payload)?t.list=e.payload:t.list=[e.payload]}},extraReducers:t=>{t.addCase(sn.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(sn.rejected,e=>{e.fetchState="error"}).addCase(sn.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload||[]}).addCase(qs.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.errorSuggestions=e.errorSuggestions.filter(n=>o.meta.arg.suggestion.text!==n)}).addCase(qs.rejected,(e,o)=>{let n=e.sentSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1))}).addCase(Gs.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.answeredSuggestions.push(o.meta.arg.suggestion.text)}).addCase(Gs.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(D,()=>_d)}}),Ud=(0,vt.createAsyncThunk)("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(Kd.actions.onCustomMessage(r))})}),zd=(0,vt.createAsyncThunk)("customMessages/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),Vd=Kd.reducer;var rn=require("@reduxjs/toolkit"),zf={token:null,accountUrl:null,interval:null},$d=t=>e=>{let{passwordlessToken:{token:o,accountUrl:n}}=e;return o&&n?`${n}/apis/admin/session/passwordless/login/?token=${o}&redirect=${t}`:null},ui=(0,rn.createAsyncThunk)("passwordlessToken/getTemporaryPasswordlessToken",async(t,e)=>{let{deepdeskAPI:o}=e.extra,n=await o.requestPasswordlessToken();return{accountUrl:o.client.baseUrl,token:n}}),pi=(0,rn.createAsyncThunk)("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:o=1e3*60*10}=t,{dispatch:n}=e;return n(ui()),setInterval(()=>n(ui()),o)}),qd=(0,rn.createSlice)({name:"passwordlessToken",initialState:zf,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(ui.fulfilled,(e,o)=>{e.token=o.payload.token,e.accountUrl=o.payload.accountUrl}),t.addCase(pi.fulfilled,(e,o)=>{e.interval=o.payload})}}),{stopPollPasswordlessToken:Gd}=qd.actions,jd=qd.reducer;var So=require("@reduxjs/toolkit");var gi={cues:[],fetchState:"idle"},Wd=t=>{var e;return(e=t.rules)==null?void 0:e.cues},Vf=(0,So.createAction)("rules/resetCues"),Vt=(0,So.createAsyncThunk)("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)}),Xd=(0,So.createSlice)({name:"answer",initialState:gi,reducers:{removeCue(t,e){t.cues=t.cues.filter(o=>o.rule.id!==e.payload.id)}},extraReducers:t=>{t.addCase(Vt.pending,e=>{e.fetchState="loading"}).addCase(Vt.rejected,e=>{e.fetchState="error"}).addCase(Vt.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(D,()=>gi).addCase(Vf.toString(),()=>gi)}}),{removeCue:Zd}=Xd.actions,Qd=Xd.reducer;function Jd(t){let{customMessages:e,autoflows:o}=t;return o.fetchState==="loading"&&o.isInitialRequest===!0||e.fetchState==="loading"&&e.isInitialRequest===!0}var au=require("react"),lu=require("react-redux");var su=k(require("classnames")),ru=require("react");var eu=k(require("classnames"));var Yd={root:"Ti"};var ou=require("react/jsx-runtime"),qf=({className:t,children:e})=>{let o=h("Unicode",Yd);return(0,ou.jsx)("span",{className:(0,eu.default)(t,o.root),children:e})},tu=qf;var nu={isDisabled:"Ui",buttonStart:"Bi",root:"Di",buttonStop:"ho",stateBadge:"h",isCompleted:"Ii",isStarted:"Oi",isAborted:"Xi"};var mi={};Y(mi,{enUS:()=>jf,nlNL:()=>Wf});var jf={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"}]},Wf={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"}]};var ge=require("react/jsx-runtime"),Zf=({disabled:t,state:e,displayName:o,description:n,onStartAutoflow:s,onStopAutoflow:r})=>{let i=h("Autoflow",nu),a=P(mi),l=e==="Started"?"stop":"start",c=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return(0,ge.jsxs)(N,{className:(0,su.default)(i.root,{[i.isDisabled]:t,[i.isCompleted]:e==="Completed",[i.isAborted]:e==="Aborted",[i.isStarted]:e==="Started"}),children:[(0,ge.jsx)(H,{children:(0,ge.jsxs)(H.Content,{children:[(0,ge.jsxs)(H.Title,{children:[e&&(0,ge.jsx)("span",{className:i.stateBadge,children:a(e)}),o]}),(0,ge.jsx)("span",{children:n})]})}),(0,ge.jsx)(N.Actions,{fixed:e==="Started",children:(0,ge.jsx)(N.ActionButton,{primary:!0,className:l==="start"?i.buttonStart:i.buttonStop,onClick:e==="Started"?r:s,disabled:t,label:(0,ge.jsxs)(ru.Fragment,{children:[(0,ge.jsx)(tu,{children:c})," ",(0,ge.jsx)("span",{children:a(l)})]})})})]})},iu=Zf;var fi=require("react/jsx-runtime"),Qf=(t,e)=>{let o=e.filter(n=>n.state==="Started");return o.length>0?o.indexOf(t)===-1:!1},Jf=({autoflows:t,onStartAutoflow:e,onStopAutoflow:o,platformSessionId:n})=>(0,fi.jsx)(au.Fragment,{children:t.map(s=>(0,fi.jsx)(iu,{displayName:s.displayName,description:s.description,disabled:s.isBusy||Qf(s,t),state:s.state,onStartAutoflow:()=>e({platformSessionId:n,triggerPayload:s.triggerPayload}),onStopAutoflow:()=>o({platformSessionId:n,triggerPayload:s.triggerPayload})},s.displayName))}),Yf=({autoflows:t,conversation:e})=>{var o;return{autoflows:t.list,platformSessionId:(o=e.current)==null?void 0:o.sessionId}},eh={onStartAutoflow:ci,onStopAutoflow:di},cu=(0,lu.connect)(Yf,eh)(Jf);var du=k(require("classnames")),hi=require("react"),$t=require("react-redux");var et={root:"mo",title:"uo",isUsed:"Ji",quickReplies:"Ki",quickReply:"Pi",hasError:"Qi",label:"Vi",errorIcon:"Wi"};var ie=require("react/jsx-runtime"),oh=({suggestion:t})=>{let e=P(_t),o=(0,$t.useDispatch)(),n=(0,$t.useSelector)(Hd(t.text)),s=(0,$t.useSelector)(Fd(t.text)),r=(0,$t.useSelector)(Bd(t.text)),i=(0,$t.useSelector)(Pn),{replyOptions:a}=t,l=(0,hi.useCallback)(d=>{d.preventDefault(),d.stopPropagation(),!(n||!i)&&o(qs({platformSessionId:i,suggestion:t}))},[t,n,o,i]),c=(0,hi.useCallback)(d=>{if(d.preventDefault(),d.stopPropagation(),!i||!a)return;let u=parseInt(d.target.dataset.index,10),g=a[u];o(Gs({platformSessionId:i,reply:g,suggestion:t}))},[t,n,o,i]);return(0,ie.jsxs)(N,{onClick:l,className:(0,du.default)(et.root,{[et.isUsed]:n,[et.hasError]:r}),children:[(0,ie.jsx)(H,{children:(0,ie.jsxs)(H.Content,{children:[(0,ie.jsxs)(H.Title,{className:et.title,children:[t.text," ",(0,ie.jsx)(wn,{className:et.label,children:"analyse tool"})," ",r&&(0,ie.jsx)("span",{className:et.errorIcon,role:"img","aria-label":e("sendingError"),title:e("sendingError"),children:"!"})]}),a&&a.length>0&&(0,ie.jsx)("ul",{className:et.quickReplies,children:a.map(d=>(0,ie.jsx)("li",{className:et.quickReply,children:d.title},d.title))})]})}),(0,ie.jsxs)(N.Actions,{fixed:r||n,children:[a&&a.length>0&&(0,ie.jsx)(N.DropdownButton,{label:e("answer"),disabled:s,children:a.map((d,u)=>(0,ie.jsx)(N.DropdownItem,{index:u,label:d.title,onClick:c},d.title))}),(0,ie.jsx)(N.ActionButton,{primary:!0,disabled:n,onClick:l,label:e(n?"suggestionSent":r?"tryAgain":"sendSuggestion")})]})]})},uu=oh;var js=require("react"),gu=require("react-redux"),Si=k(require("classnames"));var yi=require("react/jsx-runtime"),vi=()=>(0,yi.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,yi.jsx)("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 pu={root:"Zi",entity:"r",entityText:"_i",iconWrapper:"or",icon:"er",iconClicked:"ir"};var He=require("react/jsx-runtime"),sh=({entities:t})=>{let e=h("EntitiesWidgetList",pu),[o,n]=(0,js.useState)(void 0),s=(0,gu.useDispatch)(),r=()=>{n(void 0)},i=a=>{t&&(n(t.indexOf(a)),At(a.text),s(Q({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,js.useEffect)(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[o]),!t||t.length===0?null:(0,He.jsx)("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,l)=>(0,He.jsxs)("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[(0,He.jsx)("span",{className:e.entityText,children:a.text}),(0,He.jsxs)("span",{className:e.iconWrapper,children:[(0,He.jsx)("span",{className:(0,Si.default)(e.icon),children:(0,He.jsx)(vi,{})}),(0,He.jsx)("span",{className:(0,Si.default)(e.icon,o===l&&e.iconClicked),children:(0,He.jsx)(vi,{})})]})]},a.text))})},mu=sh;var xi=require("react/jsx-runtime"),fu=()=>(0,xi.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,xi.jsx)("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});var bi=require("react/jsx-runtime"),hu=()=>(0,bi.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,bi.jsx)("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"})});var Ci=require("react/jsx-runtime"),yu=()=>(0,Ci.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Ci.jsx)("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"})});var Lu=require("react-redux");var xu=require("react-redux");var vu=require("@reduxjs/toolkit");function Su(t){return(0,vu.createAsyncThunk)("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 Ws(){let t=(0,xu.useDispatch)();return async(e,o)=>{await t(Su({name:e,data:o}))}}var Ri=k(require("classnames")),Xs=require("react");var an=require("react/jsx-runtime"),bu=({className:t})=>(0,an.jsxs)("svg",{viewBox:"0 0 12 12",version:"1.1",xmlns:"http://www.w3.org/2000/svg",className:t,children:[(0,an.jsx)("line",{x1:"2",y1:"10",x2:"10",y2:"2",stroke:"black",strokeWidth:"1"}),(0,an.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10",stroke:"black",strokeWidth:"1"})]});var wi=require("react/jsx-runtime"),Cu=t=>(0,wi.jsx)("svg",{width:"16",height:"16",fill:"#000000",...t,viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,wi.jsx)("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"})});var Ti=require("react/jsx-runtime"),wu=t=>(0,Ti.jsx)("svg",{width:"16",height:"16",fill:"#000000",...t,viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,Ti.jsx)("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 xo(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)}var Eu=k(require("dompurify")),St=require("react"),ku=k(require("snarkdown"));var Tu={fadeup:"E",root:"i",popover:"rr",options:"yo",copyIcon:"G",option:"wo",divider:"tr"};var tt=require("react/jsx-runtime");function ih(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 Ei(t){let e=t.cloneNode(!0);return e.querySelectorAll("div,button").forEach(o=>o.remove()),e.textContent??""}var ah=({content:t,useLabel:e,copyLabel:o,onCopy:n,onUse:s})=>{let r=h("Markdown",Tu),i=(0,St.useRef)(null),[a,l]=(0,St.useState)(null),c=(0,St.useMemo)(()=>{let f=(0,ku.default)(t);return Eu.default.sanitize(f).replace(/<\/code>/g,`${ih(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&&(xo(f,r.fadeup),n(Ei(a)))},g=f=>{f.target.tagName.toLowerCase()==="button"&&(xo(f.target,r.fadeup),n(Ei(f.target.parentElement)))},p=()=>{a&&(l(null),s(Ei(a)))};return(0,tt.jsxs)(St.Fragment,{children:[a&&(0,tt.jsx)(vo,{triggerRef:{current:a},parentNode:a,className:r.popover,children:(0,tt.jsxs)("div",{className:r.options,children:[(0,tt.jsx)("button",{type:"button",className:r.option,onClick:u,children:o}),(0,tt.jsx)("div",{className:r.divider}),(0,tt.jsx)("button",{type:"button",className:r.option,onClick:p,children:e})]})}),(0,tt.jsx)("div",{ref:i,className:r.root,dangerouslySetInnerHTML:{__html:c},onMouseOver:d,onClick:g})]})},Ru=ah;var ki={};Y(ki,{enUS:()=>lh,nlNL:()=>ch});var lh={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"}]},ch={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 Pu={fadeup:"N",fadedown:"A",selected:"vo",thumbsUp:"nr",thumbsDown:"ar"};var me=require("react/jsx-runtime"),uh=({cue:t,onRemove:e,onCopy:o,onUse:n,onThumbsUp:s,onThumbsDown:r})=>{let i=h("WidgetCue",Pu),a=P(ki),l=Ws(),[c,d]=(0,Xs.useState)(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(),xo(y.target,i.fadeup),d("up"),s(t)},m=y=>{y.preventDefault(),y.stopPropagation(),xo(y.target,i.fadedown),d("down"),r(t)};return(0,Xs.useEffect)(()=>{l("Assistant response displayed",{name:t.rule.name,description:t.rule.description,group:t.rule.label})},[]),(0,me.jsxs)(N,{"data-testid":"cue",children:[(0,me.jsx)(H,{children:(0,me.jsxs)(H.Content,{children:[t.title&&(0,me.jsx)(H.Title,{"data-testid":"widget-cue-title",children:t.title}),(0,me.jsx)(Ru,{content:t.text,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:u,onUse:g})]})}),(0,me.jsx)(N.IconButton,{title:a("thumbsUp"),onClick:f,icon:(0,me.jsx)(wu,{}),className:(0,Ri.default)(i.thumbsUp,c==="up"&&i.selected),disabled:!!c}),(0,me.jsx)(N.IconButton,{title:a("thumbsDown"),onClick:m,icon:(0,me.jsx)(Cu,{}),className:(0,Ri.default)(i.thumbsDown,c==="down"&&i.selected),disabled:!!c}),(0,me.jsx)(N.IconButton,{title:a("removeCue"),onClick:p,icon:(0,me.jsx)(bu,{})})]})},Iu=uh;var ln=require("react/jsx-runtime"),ph=({cues:t})=>{let e=(0,Lu.useDispatch)(),o=he(),n=Ws(),s=c=>{e(Zd({id:c.rule.id})),n("Assistant response closed",{name:c.rule.name,group:c.rule.label,description:c.rule.description})},r=(c,d)=>{At(c),n("Assistant response copied",{name:d.rule.name,group:d.rule.label,description:d.rule.description,copiedText:c})},i=(c,d)=>{o.send(at,{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(0,ln.jsx)(ln.Fragment,{children:t.map(c=>(0,ln.jsx)(Iu,{cue:c,onRemove:s,onCopy:r,onUse:i,onThumbsDown:l,onThumbsUp:a},c.rule.id))})},Au=ph;var Nu=require("react");var gh=/(https?:\/\/[^\s]+)/,Mu=t=>t.split(" ").find(e=>gh.test(e));var xe=require("react/jsx-runtime"),mh=({suggestion:t,lines:e,onUse:o})=>{var d;let n=t.text||t.url||t.message,s=Mu(n),r=P(_t),i=b("showImages"),a=b("fallbackImage"),l=u=>{u.preventDefault(),u.stopPropagation(),o(n)},c=(0,Nu.useCallback)(u=>{window.open(s,"_blank"),u.stopPropagation(),u.preventDefault()},[s]);return(0,xe.jsxs)(N,{onClick:l,"data-testid":"edit-suggestion",children:[(0,xe.jsxs)(H,{children:[i&&t.image&&(0,xe.jsx)(H.Image,{src:Us(t,"small",a||void 0),title:t.title}),(0,xe.jsxs)(H.Content,{children:[t.title&&(0,xe.jsx)(H.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((d=t.searchKeywords)==null?void 0:d.length)>0&&(0,xe.jsx)(N.Labels,{labels:t.searchKeywords}),(0,xe.jsx)(H.Content,{cropText:e==="single",lineClamp:e==="multiple",children:n})]})]}),(0,xe.jsxs)(N.Actions,{children:[s&&(0,xe.jsx)(N.ActionButton,{onClick:c,label:r("visitUrl")}),(0,xe.jsx)(N.ActionButton,{primary:!0,onClick:l,label:r("useSuggestion")})]})]})},Ou=mh;var cn=require("react/jsx-runtime"),fh=({lines:t,suggestions:e})=>{let o=he(),n=(s,r)=>{o.send(at,{text:s,suggestion:{...r,source:r.source,sourceText:r.text}})};return(0,cn.jsx)(cn.Fragment,{children:e.map(s=>(0,cn.jsx)(Ou,{suggestion:s,lines:t,onUse:r=>n(r,s)},s.text||s.url||s.message))})},_u=fh;var Pi={};Y(Pi,{enUS:()=>hh,nlNL:()=>yh});var hh={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"}]},yh={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 Du={root:"pr",loginText:"dr",stateText:"ko",sectionList:"lr",shortcutList:"sr",shortcut:"cr",link:"zo"};var L=require("react/jsx-runtime"),Zs=(t,e)=>{let o=(0,G.useSelector)(te);(0,Fu.useEffect)(()=>o?e.every(n=>!!n)?t():()=>{}:()=>{},[...e,o])},Sh=({onLogIn:t})=>{let e=P(Pi),o=(0,G.useDispatch)(),n=b("isEmbedded"),s=h("Widget",Du),r=b("showAutoflows"),i=b("showCustomMessages"),a=b("showSummaryCommand"),l=b("showKnowledgeSearch"),c=b("showSearch"),d=(0,G.useSelector)(ut),u=(0,G.useSelector)(Ss),g=(0,G.useSelector)(Ad),p=(0,G.useSelector)(Wd),f=(0,G.useSelector)(ms),m=(0,G.useSelector)(Dd),y=(0,G.useSelector)(In),E=(0,G.useSelector)(Yt),S=(0,G.useSelector)(te),v=(0,G.useSelector)(Pn),R=(0,G.useSelector)(Jd),x=(0,G.useSelector)(xs),w=he(),O=(0,G.useSelector)(gc),q=(0,G.useSelector)($d("/admin/")),K=b("adminUrl"),A=b("productName");if(Zs(()=>(o(sn(v)),o(Ud(v)),()=>{o(zd(v))}),[o,E,i,v]),Zs(()=>(o(Ye(v)),o(Md(v)),()=>{o(Nd(v))}),[o,E,r,v]),Zs(()=>{u.forEach(({type:I})=>{o(I==="entities"?Re():Ie(I))})},[o,E,y,d]),Zs(()=>(o(pi()),()=>{o(Gd())}),[o]),E===!1)return(0,L.jsx)("div",{className:s.stateText,children:(0,L.jsx)("div",{children:(0,L.jsx)("p",{children:e("notSupported")})})},"supported");if(S===!1)return(0,L.jsx)("div",{className:s.loginText,children:(0,L.jsx)("div",{children:(0,L.jsx)(Ps,{isEmbedded:n,loginUrl:K,onLogIn:t})})},"login");if(!d||!v||S===null||O||R)return(0,L.jsx)("div",{className:s.stateText,children:(0,L.jsx)("div",{children:(0,L.jsx)("p",{children:e("waiting")})})},"waiting");let _=c||a||l||q;return(0,L.jsx)("div",{className:(0,Hu.default)(s.root),"data-testid":"widget",children:(0,L.jsxs)(Tn,{className:s.sectionList,children:[_&&(0,L.jsx)(Ke,{title:e("actions"),type:"shortcuts",children:(0,L.jsxs)("div",{className:s.shortcutList,children:[c&&(0,L.jsxs)("button",{className:s.shortcut,"data-testid":"shortcut-search",onClick:()=>w.send("ShowCommandPalette",{isOpen:!0}),children:[(0,L.jsx)(so,{}),e("linkSearch")]}),a&&(0,L.jsxs)("button",{className:s.shortcut,"data-testid":"shortcut-summary",onClick:()=>w.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,L.jsx)(yu,{}),e("linkSummary")]}),l&&(0,L.jsxs)("button",{className:s.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>w.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,L.jsx)(hu,{}),e("linkKnowledgeSearch")]}),q&&(0,L.jsxs)("a",{className:s.shortcut,target:"_blank",href:q,"data-testid":"shortcut-studio-login",rel:"noreferrer",children:[(0,L.jsx)(fu,{}),e("linkStudioLogin",{productName:A})]})]})}),i&&m.length>0&&(0,L.jsx)(Ke,{type:"custom-messages","data-testid":"custom-messages",children:(0,L.jsx)(le,{withDivider:!0,children:m.map(I=>(0,L.jsx)(uu,{suggestion:I},I.text))})}),r&&g.length>0&&(0,L.jsx)(Ke,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:(0,L.jsx)(le,{withDivider:!0,children:(0,L.jsx)(cu,{})})}),u.map(({type:I,title:X,amount:lr,lines:cr})=>{var Wt;switch(I){case"entities":return f&&f.length>0&&(0,L.jsx)(Ke,{type:I,title:X,"data-testid":`type-${I}`,children:(0,L.jsx)(mu,{entities:f})},I);case"cues":return p&&p.length>0&&(0,L.jsx)(Ke,{type:I,title:X,"data-testid":`type-${I}`,children:(0,L.jsx)(le,{withDivider:!0,children:(0,L.jsx)(Au,{cues:p})})},I);default:return((Wt=x[I])==null?void 0:Wt.fetchState)==="done"&&x[I].suggestions.length>0&&(0,L.jsx)(Ke,{type:I,title:X,"data-testid":`type-${I}`,children:(0,L.jsx)(le,{withDivider:!0,children:(0,L.jsx)(_u,{lines:cr,contentType:I,suggestions:x[I].suggestions.slice(0,lr)||[]})})},I)}})]})})},Bu=Sh;function bo(t){let e=new Range;return e.selectNodeContents(t),e}function Ku(t,e,o){try{return xt(t,e,o),!0}catch{return!1}}function Qs(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function Js(t){return"tagName"in t&&t.tagName==="BR"}var dn=/[\u200B-\u200D\uFEFF]/g;function xt(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(dn,""),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(Js(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;Qs(l)&&c&&!Qs(c)&&!Js(c)&&s++;break}default:break}}if(a(t),n.startContainer===document)throw new Error("Offsets out of bound");return n}function un(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(dn,"").length),p&&(l=c+f.substring(0,r).replace(dn,"").length),c+=f.replace(dn,"").length;break}case Node.ELEMENT_NODE:{let f=u.nextSibling===null;Js(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&&Qs(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 pn(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(dn,"");g===0&&p===void 0?a+=f:a+=f.substring(g,p);break}case Node.ELEMENT_NODE:{let g=c.nextSibling===null;i===0&&Js(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&&Qs(c)&&!g&&(a+=`
9
+ `);break}default:break}u&&i++}return l(t),a}var Uu=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(Uu||{}),ot=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();st(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(Uu).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 zu(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var qt=class extends ot{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),pn(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!zu(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!zu(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return un(this.element,e);let o=this.lastKnownSelection;if(o&&Ku(this.element,o.start,o.end))return o;let n=bo(this.element);return n.collapse(!1),un(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return pn(this.element,xt(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 Gt=class extends ot{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 Vu(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 xh(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}var Ii=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()}},Li=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=Vu(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()}},Ai=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 Li(e,this.deepdeskUrl,{debug:!0}):new Ii(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=xh(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)}},$u=Ai;var Co=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var Mi=t=>new Promise(e=>{setTimeout(e,t)});var wo=class extends Co{name="ClientError"},Oi=class extends Co{name="ServerError"},Ni=new Map,Ae=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(Ni.has(i)){n(Ni.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,R=!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 Mi(g),x()):w.status===401&&p===!0&&R===!1?(R=!0,await this.refreshToken(),x()):w).catch(async w=>{if(f(w)&&!r.isAborted&&v>0)return await Mi(g),x();throw w}));x().then(w=>w.json().catch(()=>null).then(O=>{w.status>=500?s(new Oi("Server Error",O)):w.status===401?s(new wo("Unauthorized",O)):w.status===403?s(new wo("Forbidden",O)):w.status===404?s(new wo("Not Found",O)):w.status>=400&&s(new wo("Bad Request",O)),delete this.latestRequestByUrl[i],c&&Ni.set(i,O),n(O)})).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 bh;(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||={})})(bh||={});function Ys(t){return{...M(t),tags:t.tags}}var nt=class t{constructor(e,o={}){this.options=o;this.client=new Ae(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",{...V(e),tags:e.tags},{version:"v2"});return Ys(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null,useCache:!0});return M(o)}async getKnowledgeAssistant(e){let o=await this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{version:null,useCache:!0});return M(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return M(e)}async getAccount(){let e=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return M(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null,useCache:!0});return M(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}`),Ys(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=V(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return Ys(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...V(s),tags:s.tags})),{version:"v2"})).map(s=>Ys(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",V({...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:V({...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/",V(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}`,V(o),{abortLatest:!0})).map(r=>({...M(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`,V(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 M(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",V(e),{abortLatest:!0});return M(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,V(e),{version:"v2"});return M(o)}async knowledgeAssist(e,o,n,s={}){let r=await this.client.post(`/api/knowledge-assist/assistants/${n}/search`,V({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 M(r)}async requestLoginByEmail(e){let o=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return M(o)}async requestPasswordlessToken(){let e=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return M(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 M(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 M(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 M(o)}async translateMessages(e){let o=await this.client.post("/api/translate",V(e),{version:"v2"});return M(o)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(da);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 gn=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(vr(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,M(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 Ch;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(Ch||={});var mn=class{constructor(e,o={}){this.apiUrl=e;this.client=new Ae(e,o)}client;streams={};logger=T;async getCustomMessages(e){let o=await this.client.get(`/sessions/${e}/suggestions`);return M(o.suggestions)}async sendCustomMessage(e,o){let n=await this.client.post(`/sessions/${e}/messages`,V(o));return M(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,V(o))}async getAutoflows(e){let o=await this.client.get(`/sessions/${e}/autoflows`);return M(o.autoflows)}async startAutoflowSession(e){let o=await this.client.post("/autoflow-sessions",V(e));return M(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new gn(`${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])}};var nr=require("@reduxjs/toolkit");var Gu=require("@reduxjs/toolkit");var qu={startTime:null,stopTime:null},ju=(0,Gu.createSlice)({name:"handlingTime",initialState:qu,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(D,()=>qu)}}),{handlingTimeStart:Wu,handlingTimeStop:er,handlingTimeReset:Xu}=ju.actions,Zu=ju.reducer;var Qu=(t={})=>{let e={onAuthError:Jt(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};var or=require("@reduxjs/toolkit");var tr={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var jt=(0,or.createAsyncThunk)("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 tr.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),wh=(0,or.createSlice)({name:"styleSuggestions",initialState:tr,reducers:{},extraReducers:t=>{t.addCase(jt.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(jt.rejected,e=>{e.fetchState="error"}).addCase(jt.fulfilled,(e,o)=>{e.fetchState="done",st(e.list,o.payload)||(e.list=o.payload)}).addCase(Rt,e=>{e.list=tr.list}).addCase(D,()=>tr)}}),Ju=wh.reducer;var Yu=(t={})=>{let e,o=!0,n={getStyleSuggestions:jt,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 Th(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var ep=(t={})=>{let e={getTextSuggestions:Ie,getAutocompleteSuggestions:Qo,debounce:200,check:po,...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===bs.toString();if(!u||!c&&!d)return a;let{input:{userCommitted:p}}=l;return Th(p,i)&&!g||(clearTimeout(o),!e.check(l))||(o=setTimeout(()=>{let y=eo(l);y===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(y))},g?0:e.debounce)),a}};var tp=jt.fulfilled.toString();function Eh(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 op=t=>e=>o=>n=>{var c;if(n.type!==tp){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=Eh(s,i);n.type===tp&&l.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var kh=(0,nr.combineReducers)({answer:sc,auth:ba,autoflows:Od,conversation:Ea,contentTypes:bl,customMessages:Vd,passwordlessToken:jd,entities:$l,knowledgeAssistant:tc,handlingTime:Zu,info:Ga,input:za,settings:ma,profile:ac,search:Ya,summary:Zl,styleSuggestions:Ju,ui:Hc,rules:Qd,textSuggestions:hc});function np(t){return(0,nr.configureStore)({reducer:kh,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),Qu(),ep({debounce:200}),Yu({debounce:500}),op(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var Rh=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},Ph=t=>e=>o=>n=>{var a;let s=e.getState(),r=gr("inlineSuggestions")(s);switch(n.type){case Jt.toString():{!n.payload&&t.emit("logout",void 0);break}case Re.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:n.payload}});break;case Ge.fulfilled.toString():t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{summary:n.payload.summary}});break;case Q.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 Dn.toString():t.handleKeyDown(n.payload);break;case Rt.toString():t.logSendMessage(n.payload);break;case Hn.toString():t.handleInputChanged(n.payload);break;case Vt.fulfilled.toString():n.isBroadcasted||t.broadcast(br,n,!1),t.emit("cues",n.payload);break;default:break}let i=o(n);switch(n.type){case Rt.toString():t.handleAfterSendMessage(n.payload);break;case Yo.toString():t.onUpdateShowTabHint(n.payload);break;case er.toString():t.logHandlingTime();break;case Ne.toString():{let{start:l,end:c}=s.input.selection;t.emit("select-suggestion",{type:Rh(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0}),r&&(e.dispatch(Me([])),e.dispatch($e()));break}case _n.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 Io.toString():{let l=e.getState(),{text:c,selection:d}=l.input.userCommitted;t.emit("reset",{text:c,selectionAfter:d},{mayApplyChanges:!0});break}case Fn.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 Me.toString():{r&&n.payload.length>0&&e.dispatch(it(0));break}default:break}return i},sp=Ph;function _i(t){return t.toISOString().replace("T"," ").replace("Z","")}function rp(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:_i(o),timeStop:_i(n)}}function ip(t,e,o){var O,q,K;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((A,{text:_,searchTerm:I})=>A+_.length-(I?I.length:0),0),v=c??Date.now(),R=(Date.now()-v)/1e3+(d||0),x=s/R,w=f.reduce((A,{searchTerm:_})=>A+(_?_.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:R,charsPerSecond:x,numPastes:l,textSuggestionsV2:f,suggestionsCounters:[{source:"gpt",countOffered:m.filter(A=>A.source==="gpt").length}],agentId:(O=e.info.agentInfo)==null?void 0:O.agentId,agentName:(q=e.info.agentInfo)==null?void 0:q.agentName,agentEmail:(K=e.info.agentInfo)==null?void 0:K.agentEmail}}function Di(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return Di(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?Di(s,e):null}function ap(t,e){return Di(t,e)}function lp(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function Ih(t){return typeof t=="object"&&t!==null&&"tagName"in t}function sr(t){return Ih(t)&&(mt(t)||Ls(t))}var cp,Fe=new Map,Lh=["bottom","height","left","right","top","width"],Ah=(t={},e={})=>Lh.some(o=>t[o]!==e[o]);function dp(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,...dp(e)]:[]}function up(t,e){return!t||!e?null:{...t,top:t.top+e.top,left:t.left+e.left}}var rr=!1,pp=()=>{rr=!0;let t=[];if(Fe.forEach((e,o)=>{if(!o.isConnected){e.rect=null,t.push(e),Fe.delete(o);return}let n=o.getBoundingClientRect();Ah(n,e.rect)&&(e.rect=n,t.push(e))}),t.forEach(e=>{let o=e.parentRects?e.parentRects.reduce(up,e.rect):e.rect;e.callbacks.forEach(n=>n(o))}),Fe.size===0){rr=!1;return}cp=window.requestAnimationFrame(pp)};function Hi(t,e){let o=dp(t),n=[],s=o.map((r,i)=>Hi(r,a=>{n[i]=a;let l=Fe.get(t);if(!l)return;let c=n.reduce(up,l.rect);l.callbacks.forEach(d=>d(c))}));return{observe(r=!0){if(s.forEach(i=>i.observe(!1)),Fe.has(t)){let i=Fe.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else Fe.set(t,{rect:void 0,callbacks:[e],parentRects:n});r&&!rr&&pp()},unobserve(){s.forEach(i=>i.unobserve());let r=Fe.get(t);if(r){let i=r.callbacks.indexOf(e);i>=0&&r.callbacks.splice(i,1),r.callbacks.length||Fe.delete(t),Fe.size||(cancelAnimationFrame(cp),rr=!1)}}}}var gp,Be=new Map,mp=()=>{Be.forEach((t,e)=>{if(!e.isConnected){Be.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)))}),Be.size!==0&&(gp=window.requestAnimationFrame(mp))};function fp(t,e){return{observe(){let o=Be.size===0;Be.has(t)?Be.get(t).callbacks.push(e):Be.set(t,{visible:void 0,callbacks:[e]}),o&&mp()},unobserve(){let o=Be.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||Be.delete(t),Be.size||cancelAnimationFrame(gp)}}}}var Fi=["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 Bi(t,e,o){return o.forEach(n=>{e.style[n]=t[n]})}function To(t){return parseFloat(t)}function ir(t){return Math.round(t*1e6)}function hp(t){return t/1e6}function Ki(t,e,o){if(t.boxSizing==="content-box")return;let{clientWidth:n}=e,s=To(t.width),r=To(t.borderLeftWidth),i=To(t.borderRightWidth),a=To(t.paddingRight),l=hp(ir(s)-ir(r)-ir(i)),c=hp(ir(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",Kt(o);let n=window.getComputedStyle(t),s=!0,r=()=>{o.scrollTop=t.scrollTop};Bi(n,o,Fi),Ki(n,t,o),e.mirrorOverflow&&(o.style.overflow="hidden",t.addEventListener("scroll",r));let i=fp(t,()=>{Bi(n,o,Fi),Ki(n,t,o),r(),setTimeout(r,0)}),a,l=!0,c=Hi(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(Bi(n,o,Fi),Ki(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=To(p.borderTopWidth),m=To(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 yp=(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 Mh(t){return t.offsetParent!==null}function vp(t){if(!Mh(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=vp(t);e({isVisible:n});let s=setInterval(()=>{let r=vp(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}var $=require("react/jsx-runtime");var Sp=yp("showTabHint",!0),hn=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 nt(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let d={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[sp({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=>Sp.update(u),sendEvent:(u,g)=>this.deepdeskApi.sendEvent(u,g)})]};o&&Object.assign(d,{deepdeskBrokerAPI:new mn(o)}),this.store=np(d),this.broadcastEvents=new $u({debug:!0,deepdeskUrl:c,eventMap:el(this.store),createCustomChannel:l}),this.store.dispatch(Yo(Sp.value())),this.store.dispatch(Rn({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(Jt(null)),this.store.dispatch(ze()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();te(n)&&fa(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(ze())).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(fr({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Ln(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(An({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(hr(e))).payload}async postMessages(e){return(await this.store.dispatch(Nn(e))).payload}async updateConversation(e){return(await this.store.dispatch(Mn(e))).payload}resetConversation(){this.store.dispatch(D()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Ge());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(Rn(e))}setVisitorInfo(e){this.store.dispatch(qa(e))}async setAgentInfo(e){await this.store.dispatch(Lo(e))}async setAgentSettings(e){await this.store.dispatch(Sr(e))}async getAgentSettings(){return(await this.store.dispatch(xr())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(bs()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Hn(e))}notifyKeyDown(e){this.store.dispatch(Dn(e))}notifyPaste(e,o){this.store.dispatch(Fa({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Da(e))}notifyExternalSuggestion(e){this.store.dispatch(Ne(e)),this.store.dispatch($e())}async evaluateRule(e,o={}){let{payload:n,error:s}=await this.store.dispatch(Vt({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(pt({collapse:!1})),this.inputMediator&&this.store.dispatch(Aa({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(Me([])))}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(Ha(Pa(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Na()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},d=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(_a()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Io()):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(it(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(it(-1)),this.store.dispatch(Io()),e.preventDefault()):o||(this.store.dispatch(pt({collapse:!0})),this.store.dispatch(_c(!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(Yo(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&p&&p.text.startsWith(g)&&(this.store.dispatch(Ne({text:p.text,suggestion:p,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch($e())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Ba()),this.store.dispatch(Me([]))}handlingTimeStart(){this.state.handlingTime.startTime||(T.info("Start handling time"),this.store.dispatch(Wu()))}handlingTimeStop(){this.state.handlingTime.startTime&&(T.info("Stop handling time"),this.store.dispatch(er()))}logSendMessage(e){let o=ip("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=rp(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Xu())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch($e()),this.store.dispatch(Rt(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(Ne({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(()=>{(0,be.unmountComponentAtNode)(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=fn(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{(0,be.unmountComponentAtNode)(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Kt(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{(0,be.unmountComponentAtNode)(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),T.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(T.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Ua(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(!sr(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),Kt(e),this.inputMediator=f||(mt(e)?new Gt(e):new qt(e)),this.inputMediator.on("change",({plainText:x})=>{this.notifyInputChanged(x)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Ka({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&&ap(e,m)||void 0;if(E){let{customStyles:x,appendOverlayTo:w}=o;if(mt(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let O=this.createInlineContainer(e,"deepdesk-caret");(0,be.render)((0,$.jsx)(zt,{store:this.store,customStyles:x,children:(0,$.jsx)(It,{broadcastEvents:this.broadcastEvents,children:(0,$.jsx)($c,{})})}),O),this.inputMediator.on("caret",K=>{this.store.dispatch(Me([])),K?(O.style.display="block",O.style.top=`${K.top}px`,O.style.left=`${K.left}px`):O.style.display="none"});let q=this.overlayContainerFactory("floating-menu",v||e,{appendTo:typeof S=="object"&&"appendOverlayTo"in S?S.appendOverlayTo:w},x==null?void 0:x.floatingMenuRootNode);(0,be.render)((0,$.jsx)(zt,{store:this.store,customStyles:x,children:(0,$.jsx)(It,{broadcastEvents:this.broadcastEvents,children:(0,$.jsx)(Ac,{onLogIn:()=>this.loginViaPopup().catch(K=>T.warn(K.message))})})}),q)}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);(0,be.render)((0,$.jsx)(zt,{store:this.store,customStyles:n,children:(0,$.jsx)(It,{broadcastEvents:this.broadcastEvents,children:(0,$.jsx)(Pd,{inputElement:e})})}),x),(0,be.render)((0,$.jsx)(zt,{store:this.store,customStyles:n,children:(0,$.jsx)(It,{broadcastEvents:this.broadcastEvents,children:(0,$.jsx)(td,{onLogIn:()=>this.loginViaPopup().catch(O=>T.warn(O.message))})})}),w)}(0,be.render)((0,$.jsx)(zt,{store:this.store,customStyles:n,children:(0,$.jsx)(It,{broadcastEvents:this.broadcastEvents,children:(0,$.jsx)(Tc,{})})}),this.createContainer("deepdesk-overlays"));let R;this.inputMediator.on("selection",x=>{clearTimeout(R),x===null?R=setTimeout(()=>{x!==null&&this.store.dispatch(yr(x))},500):this.store.dispatch(yr(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(Xr(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Xr(!0))),this.store.dispatch(Ma({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch($e()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var 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}),(0,be.render)((0,$.jsx)(zt,{store:this.store,customStyles:n,children:(0,$.jsx)(It,{broadcastEvents:this.broadcastEvents,children:(0,$.jsx)(Bu,{onLogIn:()=>this.loginViaPopup().catch(i=>T.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&(0,be.unmountComponentAtNode)(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){lp(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Zo());let e=ut(this.state);e&&(await this.store.dispatch(jo()),this.store.dispatch(Rn({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(Mo),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=Ss(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(Re()):this.store.dispatch(Ie(n))})}catch(n){this.handleError(n)}}};async function xp(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 bp(t,e,o={}){let n=o.replace?xt(t,o.replace.start,o.replace.end):bo(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?xt(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 Nh(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 Oh(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 Cp(t,e){return!t.contains(e)||e===t?null:e.parentNode===t?e:Cp(t,e.parentNode)}async function wp(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?Nh(e):Oh(e);if(o){let d=l.startContainer===t?t.childNodes[l.startOffset]:l.startContainer,u=Cp(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 Tp(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function Ep(t,e,o){await new nt(t).authenticateWithKey(e,o)}async function kp(t){let o=await new Ae(t).get("/platform/config/",{version:null,useCache:!0});return M(o)}async function _h(t){let o=await(t.fetch??window.fetch)(t.url),n=await o.blob();return new File([n],t.name,{type:t.mimeType??o.headers.get("Content-Type")??"image/jpeg"})}async function Rp(t,e){let o=await _h(e),n=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[o]}),t.dispatchEvent(n)}finally{Object.hasOwn(t,"files")&&delete t.files}}0&&(module.exports={Card,ContentEditableInput,DeepdeskAPI,DeepdeskSDK,HTTPClient,InputMediator,InputType,KeyboardHint,Label,Locale,Section,SectionList,Sources,Suggestion,SuggestionList,TextAreaInput,ToggleButton,attachFile,authenticateWithKey,createFullRange,createOverlayContainer,createRangeFromOffsets,escapeHTML,fetchPlatformConfig,formatTextMarkup,getRangeOffsets,getRangeText,insertCKEditor,isHTML,isSupportedInputElement,updateContentEditable,updateTextArea,useStyles,waitForElementVisibilityChange});