@deepdesk/deepdesk-sdk 14.2.1-beta.3 → 14.2.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 +2 -2
- package/dist/index.d.mts +5 -2
- package/dist/index.d.ts +5 -2
- package/dist/index.esm.js +2 -2
- package/dist/index.iife.js +2 -2
- package/package.json +1 -1
package/dist/index.iife.js
CHANGED
|
@@ -10,7 +10,7 @@ Add a <Suspense fallback=...> component higher in the tree to provide a loading
|
|
|
10
10
|
The error may be correlated with this previous error:
|
|
11
11
|
${rs.current.stack}
|
|
12
12
|
|
|
13
|
-
`),Fe}ei(()=>{rs.current=void 0,Te.current=void 0,Dt.current=uo});let xn=(0,de.useMemo)(()=>de.default.createElement(p,Qn({},uo,{ref:_})),[_,p,uo]);return(0,de.useMemo)(()=>v?de.default.createElement(V.Provider,{value:J},xn):xn,[V,xn,J])}let b=de.default.memo(x);if(b.WrappedComponent=p,b.displayName=x.displayName=h,l){let N=de.default.forwardRef(function(Q,V){return de.default.createElement(b,Qn({},Q,{reactReduxForwardedRef:V}))});return N.displayName=h,N.WrappedComponent=p,(0,Yg.default)(N,p)}return(0,Yg.default)(b,p)}}var Xn=iI;var ja=w(F());function aI({store:e,context:t,children:n,serverState:r,stabilityCheck:o="once",noopCheck:s="once"}){let i=(0,ja.useMemo)(()=>{let u=Zc(e);return{store:e,subscription:u,getServerState:r?()=>r:void 0,stabilityCheck:o,noopCheck:s}},[e,r,o,s]),a=(0,ja.useMemo)(()=>e.getState(),[e]);ei(()=>{let{subscription:u}=i;return u.onStateChange=u.notifyNestedSubs,u.trySubscribe(),a!==e.getState()&&u.notifyNestedSubs(),()=>{u.tryUnsubscribe(),u.onStateChange=void 0}},[i,a]);let l=t||ot;return ja.default.createElement(l.Provider,{value:i},n)}var Qg=aI;function ed(e=ot){let t=e===ot?Ac:Ha(e);return function(){let{store:r}=t();return r}}var Xg=ed();function f1(e=ot){let t=e===ot?Xg:ed(e);return function(){return t().dispatch}}var X=f1();zx(m1.useSyncExternalStoreWithSelector);d1(p1.useSyncExternalStore);Mx(Ug.unstable_batchedUpdates);var Ba=(n=>(n.NL_NL="nl-NL",n.EN_US="en-US",n))(Ba||{});var lI={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,enableSuggestionFeedback:!1,enableFeedbackForm:!1,adminUrl:void 0,productName:"Deepdesk",hasKeyboardInput:!0},g1=ee({name:"settings",initialState:lI,reducers:{set(e,t){Object.entries(t.payload).forEach(n=>{let[r,o]=n;typeof o!="undefined"&&(e[r]=o)})}}}),{set:td}=g1.actions,Zg=e=>t=>t.settings[e],z=e=>M(Zg(e)),h1=g1.reducer;var uI={isLoggedIn:!0,loginFetchState:"idle",verifyFetchState:"idle",showLoginOverlay:!1},ut=e=>e.auth.isLoggedIn,y1=e=>e.auth.loginFetchState,v1=e=>e.auth.verifyFetchState,S1=e=>e.auth.showLoginOverlay,Zn=B("auth/validate",(e,t)=>P(void 0,null,function*(){return t.extra.deepdeskAPI.isLoggedIn()})),w1=B("auth/requestLogin",(n,r)=>P(void 0,[n,r],function*({email:e},t){let{deepdeskAPI:o}=t.extra;return o.requestLoginByEmail(e)})),Va=B("auth/verifyLoginToken",(n,r)=>P(void 0,[n,r],function*({token:e},t){let{deepdeskAPI:o}=t.extra;return o.verifyLoginToken(e)})),x1=ee({name:"auth",initialState:uI,reducers:{setIsLoggedIn(e,t){e.isLoggedIn=t.payload},setShowLoginOverlay(e,t){e.showLoginOverlay=t.payload}},extraReducers:e=>{e.addCase(Zn.pending,t=>{t.loginFetchState="loading"}),e.addCase(Zn.fulfilled,(t,{payload:n})=>{t.isLoggedIn=n,t.loginFetchState="done"}),e.addCase(Zn.rejected,t=>{t.loginFetchState="error",t.isLoggedIn=!1}),e.addCase(Va.pending,t=>{t.verifyFetchState="loading"}),e.addCase(Va.rejected,t=>{t.verifyFetchState="error"}),e.addCase(Va.fulfilled,(t,n)=>{n.payload.isLoggedIn?t.verifyFetchState="done":t.verifyFetchState="error"})}}),{setIsLoggedIn:ni,setShowLoginOverlay:E1}=x1.actions,b1=x1.reducer;function Jn(){}Jn.prototype={diff:function(t,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},o=r.callback;typeof r=="function"&&(o=r,r={}),this.options=r;var s=this;function i(y){return o?(setTimeout(function(){o(void 0,y)},0),!0):y}t=this.castInput(t),n=this.castInput(n),t=this.removeEmpty(this.tokenize(t)),n=this.removeEmpty(this.tokenize(n));var a=n.length,l=t.length,u=1,c=a+l;r.maxEditLength&&(c=Math.min(c,r.maxEditLength));var f=[{newPos:-1,components:[]}],d=this.extractCommon(f[0],n,t,0);if(f[0].newPos+1>=a&&d+1>=l)return i([{value:this.join(n),count:n.length}]);function m(){for(var y=-1*u;y<=u;y+=2){var p=void 0,g=f[y-1],h=f[y+1],S=(h?h.newPos:0)-y;g&&(f[y-1]=void 0);var x=g&&g.newPos+1<a,k=h&&0<=S&&S<l;if(!x&&!k){f[y]=void 0;continue}if(!x||k&&g.newPos<h.newPos?(p=dI(h),s.pushComponent(p.components,void 0,!0)):(p=g,p.newPos++,s.pushComponent(p.components,!0,void 0)),S=s.extractCommon(p,n,t,y),p.newPos+1>=a&&S+1>=l)return i(cI(s,p.components,n,t,s.useLongestToken));f[y]=p}u++}if(o)(function y(){setTimeout(function(){if(u>c)return o();m()||y()},0)})();else for(;u<=c;){var v=m();if(v)return v}},pushComponent:function(t,n,r){var o=t[t.length-1];o&&o.added===n&&o.removed===r?t[t.length-1]={count:o.count+1,added:n,removed:r}:t.push({count:1,added:n,removed:r})},extractCommon:function(t,n,r,o){for(var s=n.length,i=r.length,a=t.newPos,l=a-o,u=0;a+1<s&&l+1<i&&this.equals(n[a+1],r[l+1]);)a++,l++,u++;return u&&t.components.push({count:u}),t.newPos=a,l},equals:function(t,n){return this.options.comparator?this.options.comparator(t,n):t===n||this.options.ignoreCase&&t.toLowerCase()===n.toLowerCase()},removeEmpty:function(t){for(var n=[],r=0;r<t.length;r++)t[r]&&n.push(t[r]);return n},castInput:function(t){return t},tokenize:function(t){return t.split("")},join:function(t){return t.join("")}};function cI(e,t,n,r,o){for(var s=0,i=t.length,a=0,l=0;s<i;s++){var u=t[s];if(u.removed){if(u.value=e.join(r.slice(l,l+u.count)),l+=u.count,s&&t[s-1].added){var f=t[s-1];t[s-1]=t[s],t[s]=f}}else{if(!u.added&&o){var c=n.slice(a,a+u.count);c=c.map(function(m,v){var y=r[l+v];return y.length>m.length?y:m}),u.value=e.join(c)}else u.value=e.join(n.slice(a,a+u.count));a+=u.count,u.added||(l+=u.count)}}var d=t[i-1];return i>1&&typeof d.value=="string"&&(d.added||d.removed)&&e.equals("",d.value)&&(t[i-2].value+=d.value,t.pop()),t}function dI(e){return{newPos:e.newPos,components:e.components.slice(0)}}var fI=new Jn;function k1(e,t,n){return fI.diff(e,t,n)}var C1=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,T1=/\S/,P1=new Jn;P1.equals=function(e,t){return this.options.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||this.options.ignoreWhitespace&&!T1.test(e)&&!T1.test(t)};P1.tokenize=function(e){for(var t=e.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),n=0;n<t.length-1;n++)!t[n+1]&&t[n+2]&&C1.test(t[n])&&C1.test(t[n+2])&&(t[n]+=t[n+2],t.splice(n+1,2),n--);return t};var R1=new Jn;R1.tokenize=function(e){var t=[],n=e.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(var r=0;r<n.length;r++){var o=n[r];r%2&&!this.options.newlineIsToken?t[t.length-1]+=o:(this.options.ignoreWhitespace&&(o=o.trim()),t.push(o))}return t};var pI=new Jn;pI.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var mI=new Jn;mI.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function nd(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?nd=function(t){return typeof t}:nd=function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},nd(e)}var gI=Object.prototype.toString,Ka=new Jn;Ka.useLongestToken=!0;Ka.tokenize=R1.tokenize;Ka.castInput=function(e){var t=this.options,n=t.undefinedReplacement,r=t.stringifyReplacer,o=r===void 0?function(s,i){return typeof i=="undefined"?n:i}:r;return typeof e=="string"?e:JSON.stringify(Jg(e,null,null,o),o," ")};Ka.equals=function(e,t){return Jn.prototype.equals.call(Ka,e.replace(/,([\r\n])/g,"$1"),t.replace(/,([\r\n])/g,"$1"))};function Jg(e,t,n,r,o){t=t||[],n=n||[],r&&(e=r(o,e));var s;for(s=0;s<t.length;s+=1)if(t[s]===e)return n[s];var i;if(gI.call(e)==="[object Array]"){for(t.push(e),i=new Array(e.length),n.push(i),s=0;s<e.length;s+=1)i[s]=Jg(e[s],t,n,r,o);return t.pop(),n.pop(),i}if(e&&e.toJSON&&(e=e.toJSON()),nd(e)==="object"&&e!==null){t.push(e),i={},n.push(i);var a=[],l;for(l in e)e.hasOwnProperty(l)&&a.push(l);for(a.sort(),s=0;s<a.length;s+=1)l=a[s],i[l]=Jg(e[l],t,n,r,l);t.pop(),n.pop()}else i=e;return i}var eh=new Jn;eh.tokenize=function(e){return e.slice()};eh.join=eh.removeEmpty=function(e){return e};function A1(e){return typeof e=="object"&&!Array.isArray(e)&&e!==null}function $r(e,t,n=10){let r=typeof e,o=typeof t;if(n===0)throw new Error("Max depth deepEqual, possible circular references?");return r!==o?!1:e==null||r==="string"||r==="number"||r==="boolean"?e===t:Array.isArray(e)&&Array.isArray(t)?e.length!==t.length?!1:e.every((s,i)=>$r(s,t[i],n-1)):A1(e)&&A1(t)?Object.keys(e).length!==Object.keys(t).length?!1:Object.keys(e).every(i=>$r(e[i],t[i],n-1)):!1}function hI(e){return Math.max(...e.map(t=>t.length))}function yI(e,t){let n=e.reduce((r,o)=>{if(o){let s=r[o]?r[o]+1:1;return I(T({},r),{[o]:s})}return r},{});return Object.keys(n).reduce((r,o)=>(n[o]<t&&r.push(o),r),[])}function L1(e,t){let r=[...e.map(({text:o})=>o.split(/\b(\w+)\b/))];for(let o=0;o<hI(r);o++){let s=yI(r.map(a=>a[o]),t),i=r.filter(a=>!s.includes(a[o]));if(i.length>=t)r=i;else return{text:r[0].slice(0,o).join("").replace(/ (\?| |!|\.|,|\n)/g,"$1").trimEnd(),source:"mixed"}}}var vI=2;function I1(e,t=""){if(e.length===0)return;if(e.length===1)return e[0];let n=L1(e,vI);return n&&n.text!==t?n:e[0]}var SI={info(...e){console.info("[Deepdesk]",...e)},warn(...e){console.warn("[Deepdesk]",...e)},error(...e){console.error("[Deepdesk]",...e)}},H=SI;var O1={current:null,isSupported:null},fe=be("resetConversation"),ri=e=>{let{current:t}=e.conversation;return(t==null?void 0:t.sessionId)||null},qr=e=>{let{current:t}=e.conversation;return(t==null?void 0:t.id)||null},oi=e=>e.conversation.isSupported,th=B("conversation/isSupported",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.isConversationSupported(e.sessionId,e.options)}),rd=B("conversation/create",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.createConversation(e)}),od=B("conversation/bySessionId",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.getConversationBySessionId(e.sessionId,e.options)}),sd=B("conversation/update",(e,t)=>{let{deepdeskAPI:n}=t.extra,r=qr(t.getState());if(!r)throw new Error("No current conversation to update");return n.updateConversation(r,e)}),nh=B("conversation/upsert",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.getConversationBySessionId(e.sessionId).catch(()=>null).then(r=>{if(!r)return n.createConversation(e);let{agentId:o,agentName:s,agentEmail:i,agentNickname:a,tags:l}=e;return n.updateConversation(r.id,{agentId:o,agentEmail:i,agentName:s,agentNickname:a,tags:l})})}),id=B("conversation/postMessages",(e,t)=>{let{deepdeskAPI:n}=t.extra,r=qr(t.getState());if(!r)throw new Error("No current conversation to update messages");return n.postMessages(r,e.map(o=>T({},o)))}),wI=[rd.rejected,od.rejected,sd.rejected,id.rejected].map(e=>e==null?void 0:e.toString()),xI=ee({name:"conversation",initialState:O1,reducers:{},extraReducers:e=>{e.addCase(th.fulfilled,(t,n)=>{t.isSupported=n.payload}).addCase(rd.fulfilled,(t,n)=>{var r,o;t.current=n.payload,t.isSupported=(o=(r=n.payload)==null?void 0:r.hasActiveProfile)!=null?o:null}).addCase(od.fulfilled,(t,n)=>{var r,o;t.current=n.payload,t.isSupported=(o=(r=n.payload)==null?void 0:r.hasActiveProfile)!=null?o:null}).addCase(nh.fulfilled,(t,n)=>{var r,o;t.current=n.payload,t.isSupported=(o=(r=n.payload)==null?void 0:r.hasActiveProfile)!=null?o:null}).addCase(sd.fulfilled,(t,n)=>{var r,o;t.current=n.payload,t.isSupported=(o=(r=n.payload)==null?void 0:r.hasActiveProfile)!=null?o:null}).addCase(id.fulfilled,(t,n)=>{t.current&&(t.current.messages=n.payload)}).addCase(fe,()=>O1).addMatcher(t=>wI.includes(t.type),(t,n)=>{var r;throw H.info("Conversation action rejected",n.type,((r=n.error)==null?void 0:r.message)||"No message"),new Error(n.error.message)})}}),N1=xI.reducer;var Lo={text:"",html:null,selection:{start:0,end:0},beforeInputChange:null,mixedSuggestion: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 rh(e){let{key:t,shiftKey:n,ctrlKey:r,metaKey:o,altKey:s}=e;return{key:t,shiftKey:n,ctrlKey:r,metaKey:o,altKey:s}}var ad=be("input/replaceText"),Io=be("input/sendMessage"),ld=be("input/applyImageSuggestion"),ct=be("input/sendEvent"),M1=ee({name:"input",initialState:Lo,reducers:{setInput(e,t){var s,i;let{beforeInputChange:n}=e,{text:r,html:o}=t.payload;if(e.text=r,e.html=o!=null?o:null,r==="")e.metrics=Lo.metrics,e.textSuggestions=[],e.mixedSuggestion=null;else if(n!==null&&e.text!==n.text){let{key:a,shiftKey:l,ctrlKey:u,metaKey:c,altKey:f}=n.keyDown;switch(a){case"Enter":l&&(e.metrics.numCharsTyped+=1);break;case"Backspace":case"Delete":{let{text:d}=e,m=k1(n.text,d);n.text.length-d.length>1&&e.metrics.deletions.push(...m.filter(v=>v.removed).map(v=>v.value)),e.metrics.numCharsDeleted+=n.text.length-d.length;break}case"Shift":case"Meta":case"Tab":break;case"C":case"V":case"X":case"c":case"v":case"x":if(u||c)break;default:if(!u&&!c&&!f){e.metrics.numCharsTyped+=1;let d=((s=n.selection)==null?void 0:s.start)!==void 0&&((i=n.selection)==null?void 0:i.end)!==void 0?n.text.substring(n.selection.start,n.selection.end):null;d&&d.length>0&&(e.metrics.numCharsDeleted+=d.length,e.metrics.deletions.push(d))}}e.metrics.agentStartedTypingTimestamp||(e.metrics.agentStartedTypingTimestamp=Date.now())}e.beforeInputChange=null},setSelection(e,t){t.payload!==null&&($r(e.selection,t.payload)||(e.selection=t.payload))},commitSuggestion(e,t){let n=t.payload,{text:r,suggestion:{source:o,abVariant:s,abTestName:i,trainingJobs:a,sourceText:l,searchTerm:u,text:c},eventMetrics:{inputType:f},replace:d}=n,m=o==="search"||o==="personal-collection-search",v=r.slice(e.text.substring(0,e.selection.start).length);(m||d==="selection")&&(v=r),n.suggestion.source==="search-overlay"&&(v=c),e.metrics.textSuggestions.push({text:v,source:o,abVariant:s,abTestName:i,inputType:f,sourceText:l,trainingJobs:a||[],searchTerm:m?e.text:u}),e.textSuggestions=[],e.selectedSuggestionIndex=-1},offeredTextSuggestion(e,t){let{text:n,suggestion:{source:r}}=t.payload;e.metrics.offeredTextSuggestions.find(s=>s.text===n)||e.metrics.offeredTextSuggestions.push({text:n,source:r})},registerKeyDown(e,t){let{key:n}=t.payload;["Control","Meta","Shift","Alt"].includes(n)||(e.beforeInputChange={text:e.text,selection:e.selection,keyDown:t.payload})},registerKeyUp(e,t){},registerCut(e,t){let{metrics:n}=e,r=t.payload;e.metrics=I(T({},e.metrics),{numCharsCut:n.numCharsCut+r.length,cuts:[...n.cuts,r]})},registerPaste(e,t){let{metrics:n}=e,{text:r,selectionText:o}=t.payload,s=n.numCharsDeleted+(o&&o.length?o.length:0),i=o&&o.length?[...n.deletions,o]:n.deletions;e.metrics=I(T({},e.metrics),{numCharsDeleted:s,deletions:i,numCharsPasted:n.numCharsPasted+r.length,numPaste:n.numPaste+1,pastes:[...n.pastes,r]})},selectNextTextSuggestion(e){let t=e.textSuggestions.length;e.selectedSuggestionIndex=e.selectedSuggestionIndex<t-1?e.selectedSuggestionIndex+1:e.selectedSuggestionIndex},selectPreviousTextSuggestion(e){e.selectedSuggestionIndex=e.selectedSuggestionIndex>=0?e.selectedSuggestionIndex-1:e.selectedSuggestionIndex},selectTextSuggestionByIndex(e,t){e.selectedSuggestionIndex=t.payload},setTextSuggestions(e,t){if(e.selectedSuggestionIndex=-1,e.textSuggestions=t.payload,t.payload.length===0){e.mixedSuggestion=null;return}let n=e.text.substring(0,e.selection.end),r=I1(t.payload,n);e.mixedSuggestion=r!=null&&r.text.includes(n)?r:null},setMetrics(e,{payload:t}){e.metrics=t},resetMetrics(e){e.metrics=Lo.metrics}},extraReducers:e=>{e.addCase(fe,t=>{t.mixedSuggestion=Lo.mixedSuggestion,t.textSuggestions=Lo.textSuggestions,t.selectedSuggestionIndex=Lo.selectedSuggestionIndex,t.metrics=Lo.metrics})}}),si=e=>e.input.text.substring(0,e.input.selection.end),EI=e=>e.input.selection,ii=e=>{let{mixedSuggestion:t,selectedSuggestionIndex:n,textSuggestions:r}=e.input;return n>-1?r[n]:t},_1=()=>M(EI),{commitSuggestion:un,offeredTextSuggestion:D1,registerCut:F1,registerKeyDown:H1,registerKeyUp:U1,registerPaste:z1,selectNextTextSuggestion:j1,selectPreviousTextSuggestion:B1,selectTextSuggestionByIndex:ud,setInput:cd,setMetrics:V1,setSelection:dd,setTextSuggestions:Gr,resetMetrics:K1}=M1.actions,W1=M1.reducer;var bI={agentInfo:void 0,agentSettings:{},visitorInfo:void 0,customData:void 0,platformVariables:void 0,fetchState:"idle"},$a=e=>{var t,n,r;return{timezone:((t=e.info.visitorInfo)==null?void 0:t.visitorTimeZone)||Intl.DateTimeFormat().resolvedOptions().timeZone,agentName:((n=e.info.agentInfo)==null?void 0:n.agentNickname)||"",visitorName:((r=e.info.visitorInfo)==null?void 0:r.visitorName)||""}},CI=[["agentNickname","nickname"],["agentDefaultLocale","defaultLocale"],["agentEmail","email"]],Wa=B("info/setAgentInfo",(e,t)=>P(void 0,null,function*(){var i,a,l;let{deepdeskAPI:n}=t.extra,r=yield n.getMe(),o=[];e.agentId&&o.push(n.postIdentity({externalId:e.agentId}));let s=CI.reduce((u,[c,f])=>!r[f]&&c in e?I(T({},u),{[f]:e[c]}):u,{});return Object.keys(s).length>0&&o.push(n.patchMe(s).then(u=>r=u)),o.length>0&&(yield Promise.all(o)),{agentId:e.agentId,agentName:e.agentName,agentNickname:(i=e.agentNickname)!=null?i:r.nickname,agentEmail:(a=e.agentEmail)!=null?a:r.email,agentDefaultLocale:(l=e.agentDefaultLocale)!=null?l:r.defaultLocale,agentTimeZone:e.agentTimeZone}})),oh=B("info/setAgentSettings",(e,t)=>P(void 0,null,function*(){let{deepdeskAPI:n}=t.extra,r=yield n.getMe(),o=T(T({},typeof r.uiConfig=="object"?r.uiConfig:{}),e);return yield n.patchMe({uiConfig:o}),o})),sh=B("info/getAgentSettings",(e,t)=>P(void 0,null,function*(){let{deepdeskAPI:n}=t.extra;return(yield n.getMe()).uiConfig})),$1=e=>e.info.agentInfo,q1=e=>e.info.customData,G1=ee({name:"info",initialState:bI,reducers:{setVisitorInfo(e,t){e.visitorInfo=T(T({},e.visitorInfo),t.payload)},setCustomData(e,t){e.customData=t.payload},setPlatformVariables(e,t){e.platformVariables=t.payload}},extraReducers:e=>{e.addCase(Wa.pending,(t,n)=>{t.fetchState="loading",t.agentInfo=T(T({},t.agentInfo),n.meta.arg)}).addCase(Wa.rejected,t=>{t.fetchState="error"}).addCase(Wa.fulfilled,(t,n)=>{t.fetchState="done",t.agentInfo=n.payload}).addCase(oh.fulfilled,(t,n)=>{t.agentSettings=n.payload}).addCase(sh.fulfilled,(t,n)=>{t.agentSettings=n.payload}).addCase(fe,t=>{t.visitorInfo=void 0})}}),{setVisitorInfo:Y1,setCustomData:Q1,setPlatformVariables:X1}=G1.actions,Z1=G1.reducer;function $e(e,t){return Object.entries(t).reduce((n,[r,o])=>n.replaceAll(r,o),e)}var fd={list:[],fetchState:"idle",isOpen:!1,page:"search",aggregates:{}},J1=e=>e.search.isOpen,eE=e=>e.search.page,tE=e=>e.search.list,nE=e=>e.search.aggregates;function rE(e,t=n=>n){return n=>n.search.list.filter(r=>r.type===e).map(t)}var Oo=B("search/getAll",(e,t)=>P(void 0,null,function*(){var l;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=(l=r.conversation.current)==null?void 0:l.profileCode,{platformVariables:s}=r.info;if(!o)throw new Error("Profile should be provided in order to be able to search");let{results:i,aggregates:a}=yield n.search({profile:o,query:e.query,tags:e.tags,size:e.size,current:e.current,filters:{type:e.type},params:$a(r)});return{results:i.map(u=>I(T(T({},u),u.title&&s?{title:$e(u.title,s)}:{}),{text:$e(u.text,s!=null?s:{}),source:`search-${u.type.toLowerCase()}`,searchTerm:e.query})),aggregates:a}})),oE=ee({name:"search",initialState:fd,reducers:{setIsOpen(e,t){e.isOpen=t.payload},setPage(e,t){e.page=t.payload},resetSearch(e){e.fetchState=fd.fetchState,e.list=fd.list}},extraReducers:e=>{e.addCase(Oo.pending,t=>{t.fetchState="loading"}).addCase(Oo.rejected,(t,n)=>{t.fetchState="error",H.error(n.error)}).addCase(Oo.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload.results,t.aggregates=n.payload.aggregates||{}}).addCase(fe,()=>fd)}}),{resetSearch:pd,setIsOpen:Ot,setPage:cn}=oE.actions,sE=oE.reducer;var ih="SetCues",ah="SetOutputs",ai="ShowLoginOverlay",qa="UserLoggedIn",TI="UserLoggedOut",Yr="ApplySuggestion",lh="ApplyImageSuggestion",kI="ShowCommandPalette",PI=e=>({[ih]:t=>{e.dispatch(I(T({},t),{isBroadcasted:!0}))},[ah]:t=>{e.dispatch(I(T({},t),{isBroadcasted:!0}))},[kI]:t=>{e.dispatch(Ot(t.isOpen)),t.page&&e.dispatch(cn(t.page))},[ai]:t=>{e.dispatch(E1(t))},[qa]:()=>{e.dispatch(Zn())},[TI]:()=>{e.dispatch(Zn())},[lh]:t=>{e.dispatch(ld({suggestion:t.suggestion}))},[Yr]:t=>{e.dispatch(un(I(T({},t),{eventMetrics:{inputType:"mouse"},replace:"selection"})))}}),iE=PI;var Ga=w(F()),lE=w(C()),aE=Ga.default.createContext(null),No=({broadcastEvents:e,children:t})=>{let n=Ga.default.useMemo(()=>e,[]);return(0,lE.jsx)(aE.Provider,{value:n,children:t})},Yt=()=>{let e=(0,Ga.useContext)(aE);if(!e)throw new Error("You should use the useBroadcastEvents within a BroadcastEventsProvider");return e};var Ld=w(se()),fn=w(F());var Pd=w(F());var uh=function(e,t){return uh=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[o]=r[o])},uh(e,t)};function Ya(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");uh(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var Nt=function(){return Nt=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},Nt.apply(this,arguments)};function uE(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function md(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}var gd;(function(e){e[e.EXPECT_ARGUMENT_CLOSING_BRACE=1]="EXPECT_ARGUMENT_CLOSING_BRACE",e[e.EMPTY_ARGUMENT=2]="EMPTY_ARGUMENT",e[e.MALFORMED_ARGUMENT=3]="MALFORMED_ARGUMENT",e[e.EXPECT_ARGUMENT_TYPE=4]="EXPECT_ARGUMENT_TYPE",e[e.INVALID_ARGUMENT_TYPE=5]="INVALID_ARGUMENT_TYPE",e[e.EXPECT_ARGUMENT_STYLE=6]="EXPECT_ARGUMENT_STYLE",e[e.INVALID_NUMBER_SKELETON=7]="INVALID_NUMBER_SKELETON",e[e.INVALID_DATE_TIME_SKELETON=8]="INVALID_DATE_TIME_SKELETON",e[e.EXPECT_NUMBER_SKELETON=9]="EXPECT_NUMBER_SKELETON",e[e.EXPECT_DATE_TIME_SKELETON=10]="EXPECT_DATE_TIME_SKELETON",e[e.UNCLOSED_QUOTE_IN_ARGUMENT_STYLE=11]="UNCLOSED_QUOTE_IN_ARGUMENT_STYLE",e[e.EXPECT_SELECT_ARGUMENT_OPTIONS=12]="EXPECT_SELECT_ARGUMENT_OPTIONS",e[e.EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE=13]="EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE",e[e.INVALID_PLURAL_ARGUMENT_OFFSET_VALUE=14]="INVALID_PLURAL_ARGUMENT_OFFSET_VALUE",e[e.EXPECT_SELECT_ARGUMENT_SELECTOR=15]="EXPECT_SELECT_ARGUMENT_SELECTOR",e[e.EXPECT_PLURAL_ARGUMENT_SELECTOR=16]="EXPECT_PLURAL_ARGUMENT_SELECTOR",e[e.EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT=17]="EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT",e[e.EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT=18]="EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT",e[e.INVALID_PLURAL_ARGUMENT_SELECTOR=19]="INVALID_PLURAL_ARGUMENT_SELECTOR",e[e.DUPLICATE_PLURAL_ARGUMENT_SELECTOR=20]="DUPLICATE_PLURAL_ARGUMENT_SELECTOR",e[e.DUPLICATE_SELECT_ARGUMENT_SELECTOR=21]="DUPLICATE_SELECT_ARGUMENT_SELECTOR",e[e.MISSING_OTHER_CLAUSE=22]="MISSING_OTHER_CLAUSE",e[e.INVALID_TAG=23]="INVALID_TAG",e[e.INVALID_TAG_NAME=25]="INVALID_TAG_NAME",e[e.UNMATCHED_CLOSING_TAG=26]="UNMATCHED_CLOSING_TAG",e[e.UNCLOSED_TAG=27]="UNCLOSED_TAG"})(gd||(gd={}));var hd=class{constructor(t){console.warn(`[vite-messages-plugin]: Message "${t}" was not precompiled. Did you use the correct extenstion *.messages.ts?`)}};var dn;(function(e){e[e.literal=0]="literal",e[e.argument=1]="argument",e[e.number=2]="number",e[e.date=3]="date",e[e.time=4]="time",e[e.select=5]="select",e[e.plural=6]="plural",e[e.pound=7]="pound",e[e.tag=8]="tag"})(dn||(dn={}));var yd;(function(e){e[e.number=0]="number",e[e.dateTime=1]="dateTime"})(yd||(yd={}));function ch(e){return e.type===dn.literal}function cE(e){return e.type===dn.argument}function vd(e){return e.type===dn.number}function Sd(e){return e.type===dn.date}function wd(e){return e.type===dn.time}function xd(e){return e.type===dn.select}function Ed(e){return e.type===dn.plural}function dE(e){return e.type===dn.pound}function bd(e){return e.type===dn.tag}function Cd(e){return!!(e&&typeof e=="object"&&e.type===yd.number)}function Qa(e){return!!(e&&typeof e=="object"&&e.type===yd.dateTime)}function dh(e){e.forEach(function(t){if(delete t.location,xd(t)||Ed(t))for(var n in t.options)delete t.options[n].location,dh(t.options[n].value);else vd(t)&&Cd(t.style)||(Sd(t)||wd(t))&&Qa(t.style)?delete t.style.location:bd(t)&&dh(t.children)})}function fE(e,t){t===void 0&&(t={}),t=Nt({shouldParseSkeletons:!0,requiresOtherClause:!0},t);var n=new hd(e,t).parse();if(n.err){var r=SyntaxError(gd[n.err.kind]);throw r.location=n.err.location,r.originalMessage=n.err.message,r}return t!=null&&t.captureLocation||dh(n.val),n.val}function Td(e,t){var n=t&&t.cache?t.cache:NI,r=t&&t.serializer?t.serializer:OI,o=t&&t.strategy?t.strategy:AI;return o(e,{cache:n,serializer:r})}function RI(e){return e==null||typeof e=="number"||typeof e=="boolean"}function pE(e,t,n,r){var o=RI(r)?r:n(r),s=t.get(o);return typeof s=="undefined"&&(s=e.call(this,r),t.set(o,s)),s}function mE(e,t,n){var r=Array.prototype.slice.call(arguments,3),o=n(r),s=t.get(o);return typeof s=="undefined"&&(s=e.apply(this,r),t.set(o,s)),s}function fh(e,t,n,r,o){return n.bind(t,e,r,o)}function AI(e,t){var n=e.length===1?pE:mE;return fh(e,this,n,t.cache.create(),t.serializer)}function LI(e,t){return fh(e,this,mE,t.cache.create(),t.serializer)}function II(e,t){return fh(e,this,pE,t.cache.create(),t.serializer)}var OI=function(){return JSON.stringify(arguments)};function ph(){this.cache=Object.create(null)}ph.prototype.get=function(e){return this.cache[e]};ph.prototype.set=function(e,t){this.cache[e]=t};var NI={create:function(){return new ph}},kd={variadic:LI,monadic:II};var Mo;(function(e){e.MISSING_VALUE="MISSING_VALUE",e.INVALID_VALUE="INVALID_VALUE",e.MISSING_INTL_API="MISSING_INTL_API"})(Mo||(Mo={}));var Xa=function(e){Ya(t,e);function t(n,r,o){var s=e.call(this,n)||this;return s.code=r,s.originalMessage=o,s}return t.prototype.toString=function(){return"[formatjs Error: ".concat(this.code,"] ").concat(this.message)},t}(Error);var mh=function(e){Ya(t,e);function t(n,r,o,s){return e.call(this,'Invalid values for "'.concat(n,'": "').concat(r,'". Options are "').concat(Object.keys(o).join('", "'),'"'),Mo.INVALID_VALUE,s)||this}return t}(Xa);var gE=function(e){Ya(t,e);function t(n,r,o){return e.call(this,'Value for "'.concat(n,'" must be of type ').concat(r),Mo.INVALID_VALUE,o)||this}return t}(Xa);var hE=function(e){Ya(t,e);function t(n,r){return e.call(this,'The intl string context variable "'.concat(n,'" was not provided to the string "').concat(r,'"'),Mo.MISSING_VALUE,r)||this}return t}(Xa);var st;(function(e){e[e.literal=0]="literal",e[e.object=1]="object"})(st||(st={}));function MI(e){return e.length<2?e:e.reduce(function(t,n){var r=t[t.length-1];return!r||r.type!==st.literal||n.type!==st.literal?t.push(n):r.value+=n.value,t},[])}function _I(e){return typeof e=="function"}function Za(e,t,n,r,o,s,i){if(e.length===1&&ch(e[0]))return[{type:st.literal,value:e[0].value}];for(var a=[],l=0,u=e;l<u.length;l++){var c=u[l];if(ch(c)){a.push({type:st.literal,value:c.value});continue}if(dE(c)){typeof s=="number"&&a.push({type:st.literal,value:n.getNumberFormat(t).format(s)});continue}var f=c.value;if(!(o&&f in o))throw new hE(f,i);var d=o[f];if(cE(c)){(!d||typeof d=="string"||typeof d=="number")&&(d=typeof d=="string"||typeof d=="number"?String(d):""),a.push({type:typeof d=="string"?st.literal:st.object,value:d});continue}if(Sd(c)){var m=typeof c.style=="string"?r.date[c.style]:Qa(c.style)?c.style.parsedOptions:void 0;a.push({type:st.literal,value:n.getDateTimeFormat(t,m).format(d)});continue}if(wd(c)){var m=typeof c.style=="string"?r.time[c.style]:Qa(c.style)?c.style.parsedOptions:r.time.medium;a.push({type:st.literal,value:n.getDateTimeFormat(t,m).format(d)});continue}if(vd(c)){var m=typeof c.style=="string"?r.number[c.style]:Cd(c.style)?c.style.parsedOptions:void 0;m&&m.scale&&(d=d*(m.scale||1)),a.push({type:st.literal,value:n.getNumberFormat(t,m).format(d)});continue}if(bd(c)){var v=c.children,y=c.value,p=o[y];if(!_I(p))throw new gE(y,"function",i);var g=Za(v,t,n,r,o,s),h=p(g.map(function(k){return k.value}));Array.isArray(h)||(h=[h]),a.push.apply(a,h.map(function(k){return{type:typeof k=="string"?st.literal:st.object,value:k}}))}if(xd(c)){var S=c.options[d]||c.options.other;if(!S)throw new mh(c.value,d,Object.keys(c.options),i);a.push.apply(a,Za(S.value,t,n,r,o));continue}if(Ed(c)){var S=c.options["=".concat(d)];if(!S){if(!Intl.PluralRules)throw new Xa(`Intl.PluralRules is not available in this environment.
|
|
13
|
+
`),Fe}ei(()=>{rs.current=void 0,Te.current=void 0,Dt.current=uo});let xn=(0,de.useMemo)(()=>de.default.createElement(p,Qn({},uo,{ref:_})),[_,p,uo]);return(0,de.useMemo)(()=>v?de.default.createElement(V.Provider,{value:J},xn):xn,[V,xn,J])}let b=de.default.memo(x);if(b.WrappedComponent=p,b.displayName=x.displayName=h,l){let N=de.default.forwardRef(function(Q,V){return de.default.createElement(b,Qn({},Q,{reactReduxForwardedRef:V}))});return N.displayName=h,N.WrappedComponent=p,(0,Yg.default)(N,p)}return(0,Yg.default)(b,p)}}var Xn=iI;var ja=w(F());function aI({store:e,context:t,children:n,serverState:r,stabilityCheck:o="once",noopCheck:s="once"}){let i=(0,ja.useMemo)(()=>{let u=Zc(e);return{store:e,subscription:u,getServerState:r?()=>r:void 0,stabilityCheck:o,noopCheck:s}},[e,r,o,s]),a=(0,ja.useMemo)(()=>e.getState(),[e]);ei(()=>{let{subscription:u}=i;return u.onStateChange=u.notifyNestedSubs,u.trySubscribe(),a!==e.getState()&&u.notifyNestedSubs(),()=>{u.tryUnsubscribe(),u.onStateChange=void 0}},[i,a]);let l=t||ot;return ja.default.createElement(l.Provider,{value:i},n)}var Qg=aI;function ed(e=ot){let t=e===ot?Ac:Ha(e);return function(){let{store:r}=t();return r}}var Xg=ed();function f1(e=ot){let t=e===ot?Xg:ed(e);return function(){return t().dispatch}}var X=f1();zx(m1.useSyncExternalStoreWithSelector);d1(p1.useSyncExternalStore);Mx(Ug.unstable_batchedUpdates);var Ba=(n=>(n.NL_NL="nl-NL",n.EN_US="en-US",n))(Ba||{});var lI={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,enableSuggestionFeedback:!1,enableFeedbackForm:!1,adminUrl:void 0,productName:"Deepdesk",hasKeyboardInput:!0},g1=ee({name:"settings",initialState:lI,reducers:{set(e,t){Object.entries(t.payload).forEach(n=>{let[r,o]=n;typeof o!="undefined"&&(e[r]=o)})}}}),{set:td}=g1.actions,Zg=e=>t=>t.settings[e],z=e=>M(Zg(e)),h1=g1.reducer;var uI={isLoggedIn:!0,loginFetchState:"idle",verifyFetchState:"idle",showLoginOverlay:!1},ut=e=>e.auth.isLoggedIn,y1=e=>e.auth.loginFetchState,v1=e=>e.auth.verifyFetchState,S1=e=>e.auth.showLoginOverlay,Zn=B("auth/validate",(e,t)=>P(void 0,null,function*(){return t.extra.deepdeskAPI.isLoggedIn()})),w1=B("auth/requestLogin",(n,r)=>P(void 0,[n,r],function*({email:e},t){let{deepdeskAPI:o}=t.extra;return o.requestLoginByEmail(e)})),Va=B("auth/verifyLoginToken",(n,r)=>P(void 0,[n,r],function*({token:e},t){let{deepdeskAPI:o}=t.extra;return o.verifyLoginToken(e)})),x1=ee({name:"auth",initialState:uI,reducers:{setIsLoggedIn(e,t){e.isLoggedIn=t.payload},setShowLoginOverlay(e,t){e.showLoginOverlay=t.payload}},extraReducers:e=>{e.addCase(Zn.pending,t=>{t.loginFetchState="loading"}),e.addCase(Zn.fulfilled,(t,{payload:n})=>{t.isLoggedIn=n,t.loginFetchState="done"}),e.addCase(Zn.rejected,t=>{t.loginFetchState="error",t.isLoggedIn=!1}),e.addCase(Va.pending,t=>{t.verifyFetchState="loading"}),e.addCase(Va.rejected,t=>{t.verifyFetchState="error"}),e.addCase(Va.fulfilled,(t,n)=>{n.payload.isLoggedIn?t.verifyFetchState="done":t.verifyFetchState="error"})}}),{setIsLoggedIn:ni,setShowLoginOverlay:E1}=x1.actions,b1=x1.reducer;function Jn(){}Jn.prototype={diff:function(t,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},o=r.callback;typeof r=="function"&&(o=r,r={}),this.options=r;var s=this;function i(y){return o?(setTimeout(function(){o(void 0,y)},0),!0):y}t=this.castInput(t),n=this.castInput(n),t=this.removeEmpty(this.tokenize(t)),n=this.removeEmpty(this.tokenize(n));var a=n.length,l=t.length,u=1,c=a+l;r.maxEditLength&&(c=Math.min(c,r.maxEditLength));var f=[{newPos:-1,components:[]}],d=this.extractCommon(f[0],n,t,0);if(f[0].newPos+1>=a&&d+1>=l)return i([{value:this.join(n),count:n.length}]);function m(){for(var y=-1*u;y<=u;y+=2){var p=void 0,g=f[y-1],h=f[y+1],S=(h?h.newPos:0)-y;g&&(f[y-1]=void 0);var x=g&&g.newPos+1<a,k=h&&0<=S&&S<l;if(!x&&!k){f[y]=void 0;continue}if(!x||k&&g.newPos<h.newPos?(p=dI(h),s.pushComponent(p.components,void 0,!0)):(p=g,p.newPos++,s.pushComponent(p.components,!0,void 0)),S=s.extractCommon(p,n,t,y),p.newPos+1>=a&&S+1>=l)return i(cI(s,p.components,n,t,s.useLongestToken));f[y]=p}u++}if(o)(function y(){setTimeout(function(){if(u>c)return o();m()||y()},0)})();else for(;u<=c;){var v=m();if(v)return v}},pushComponent:function(t,n,r){var o=t[t.length-1];o&&o.added===n&&o.removed===r?t[t.length-1]={count:o.count+1,added:n,removed:r}:t.push({count:1,added:n,removed:r})},extractCommon:function(t,n,r,o){for(var s=n.length,i=r.length,a=t.newPos,l=a-o,u=0;a+1<s&&l+1<i&&this.equals(n[a+1],r[l+1]);)a++,l++,u++;return u&&t.components.push({count:u}),t.newPos=a,l},equals:function(t,n){return this.options.comparator?this.options.comparator(t,n):t===n||this.options.ignoreCase&&t.toLowerCase()===n.toLowerCase()},removeEmpty:function(t){for(var n=[],r=0;r<t.length;r++)t[r]&&n.push(t[r]);return n},castInput:function(t){return t},tokenize:function(t){return t.split("")},join:function(t){return t.join("")}};function cI(e,t,n,r,o){for(var s=0,i=t.length,a=0,l=0;s<i;s++){var u=t[s];if(u.removed){if(u.value=e.join(r.slice(l,l+u.count)),l+=u.count,s&&t[s-1].added){var f=t[s-1];t[s-1]=t[s],t[s]=f}}else{if(!u.added&&o){var c=n.slice(a,a+u.count);c=c.map(function(m,v){var y=r[l+v];return y.length>m.length?y:m}),u.value=e.join(c)}else u.value=e.join(n.slice(a,a+u.count));a+=u.count,u.added||(l+=u.count)}}var d=t[i-1];return i>1&&typeof d.value=="string"&&(d.added||d.removed)&&e.equals("",d.value)&&(t[i-2].value+=d.value,t.pop()),t}function dI(e){return{newPos:e.newPos,components:e.components.slice(0)}}var fI=new Jn;function k1(e,t,n){return fI.diff(e,t,n)}var C1=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,T1=/\S/,P1=new Jn;P1.equals=function(e,t){return this.options.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||this.options.ignoreWhitespace&&!T1.test(e)&&!T1.test(t)};P1.tokenize=function(e){for(var t=e.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),n=0;n<t.length-1;n++)!t[n+1]&&t[n+2]&&C1.test(t[n])&&C1.test(t[n+2])&&(t[n]+=t[n+2],t.splice(n+1,2),n--);return t};var R1=new Jn;R1.tokenize=function(e){var t=[],n=e.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(var r=0;r<n.length;r++){var o=n[r];r%2&&!this.options.newlineIsToken?t[t.length-1]+=o:(this.options.ignoreWhitespace&&(o=o.trim()),t.push(o))}return t};var pI=new Jn;pI.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var mI=new Jn;mI.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function nd(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?nd=function(t){return typeof t}:nd=function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},nd(e)}var gI=Object.prototype.toString,Ka=new Jn;Ka.useLongestToken=!0;Ka.tokenize=R1.tokenize;Ka.castInput=function(e){var t=this.options,n=t.undefinedReplacement,r=t.stringifyReplacer,o=r===void 0?function(s,i){return typeof i=="undefined"?n:i}:r;return typeof e=="string"?e:JSON.stringify(Jg(e,null,null,o),o," ")};Ka.equals=function(e,t){return Jn.prototype.equals.call(Ka,e.replace(/,([\r\n])/g,"$1"),t.replace(/,([\r\n])/g,"$1"))};function Jg(e,t,n,r,o){t=t||[],n=n||[],r&&(e=r(o,e));var s;for(s=0;s<t.length;s+=1)if(t[s]===e)return n[s];var i;if(gI.call(e)==="[object Array]"){for(t.push(e),i=new Array(e.length),n.push(i),s=0;s<e.length;s+=1)i[s]=Jg(e[s],t,n,r,o);return t.pop(),n.pop(),i}if(e&&e.toJSON&&(e=e.toJSON()),nd(e)==="object"&&e!==null){t.push(e),i={},n.push(i);var a=[],l;for(l in e)e.hasOwnProperty(l)&&a.push(l);for(a.sort(),s=0;s<a.length;s+=1)l=a[s],i[l]=Jg(e[l],t,n,r,l);t.pop(),n.pop()}else i=e;return i}var eh=new Jn;eh.tokenize=function(e){return e.slice()};eh.join=eh.removeEmpty=function(e){return e};function A1(e){return typeof e=="object"&&!Array.isArray(e)&&e!==null}function $r(e,t,n=10){let r=typeof e,o=typeof t;if(n===0)throw new Error("Max depth deepEqual, possible circular references?");return r!==o?!1:e==null||r==="string"||r==="number"||r==="boolean"?e===t:Array.isArray(e)&&Array.isArray(t)?e.length!==t.length?!1:e.every((s,i)=>$r(s,t[i],n-1)):A1(e)&&A1(t)?Object.keys(e).length!==Object.keys(t).length?!1:Object.keys(e).every(i=>$r(e[i],t[i],n-1)):!1}function hI(e){return Math.max(...e.map(t=>t.length))}function yI(e,t){let n=e.reduce((r,o)=>{if(o){let s=r[o]?r[o]+1:1;return I(T({},r),{[o]:s})}return r},{});return Object.keys(n).reduce((r,o)=>(n[o]<t&&r.push(o),r),[])}function L1(e,t){let r=[...e.map(({text:o})=>o.split(/\b(\w+)\b/))];for(let o=0;o<hI(r);o++){let s=yI(r.map(a=>a[o]),t),i=r.filter(a=>!s.includes(a[o]));if(i.length>=t)r=i;else return{text:r[0].slice(0,o).join("").replace(/ (\?| |!|\.|,|\n)/g,"$1").trimEnd(),source:"mixed"}}}var vI=2;function I1(e,t=""){if(e.length===0)return;if(e.length===1)return e[0];let n=L1(e,vI);return n&&n.text!==t?n:e[0]}var SI={info(...e){console.info("[Deepdesk]",...e)},warn(...e){console.warn("[Deepdesk]",...e)},error(...e){console.error("[Deepdesk]",...e)}},H=SI;var O1={current:null,isSupported:null},fe=be("resetConversation"),ri=e=>{let{current:t}=e.conversation;return(t==null?void 0:t.sessionId)||null},qr=e=>{let{current:t}=e.conversation;return(t==null?void 0:t.id)||null},oi=e=>e.conversation.isSupported,th=B("conversation/isSupported",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.isConversationSupported(e.sessionId,e.options)}),rd=B("conversation/create",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.createConversation(e)}),od=B("conversation/bySessionId",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.getConversationBySessionId(e.sessionId,e.options)}),sd=B("conversation/update",(e,t)=>{let{deepdeskAPI:n}=t.extra,r=qr(t.getState());if(!r)throw new Error("No current conversation to update");return n.updateConversation(r,e)}),nh=B("conversation/upsert",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.getConversationBySessionId(e.sessionId).catch(()=>null).then(r=>{if(!r)return n.createConversation(e);let{agentId:o,agentName:s,agentEmail:i,agentNickname:a,tags:l}=e;return n.updateConversation(r.id,{agentId:o,agentEmail:i,agentName:s,agentNickname:a,tags:l})})}),id=B("conversation/postMessages",(e,t)=>{let{deepdeskAPI:n}=t.extra,r=qr(t.getState());if(!r)throw new Error("No current conversation to update messages");return n.postMessages(r,e.map(o=>T({},o)))}),wI=[rd.rejected,od.rejected,sd.rejected,id.rejected].map(e=>e==null?void 0:e.toString()),xI=ee({name:"conversation",initialState:O1,reducers:{},extraReducers:e=>{e.addCase(th.fulfilled,(t,n)=>{t.isSupported=n.payload}).addCase(rd.fulfilled,(t,n)=>{var r,o;t.current=n.payload,t.isSupported=(o=(r=n.payload)==null?void 0:r.hasActiveProfile)!=null?o:null}).addCase(od.fulfilled,(t,n)=>{var r,o;t.current=n.payload,t.isSupported=(o=(r=n.payload)==null?void 0:r.hasActiveProfile)!=null?o:null}).addCase(nh.fulfilled,(t,n)=>{var r,o;t.current=n.payload,t.isSupported=(o=(r=n.payload)==null?void 0:r.hasActiveProfile)!=null?o:null}).addCase(sd.fulfilled,(t,n)=>{var r,o;t.current=n.payload,t.isSupported=(o=(r=n.payload)==null?void 0:r.hasActiveProfile)!=null?o:null}).addCase(id.fulfilled,(t,n)=>{t.current&&(t.current.messages=n.payload)}).addCase(fe,()=>O1).addMatcher(t=>wI.includes(t.type),(t,n)=>{var r;throw H.info("Conversation action rejected",n.type,((r=n.error)==null?void 0:r.message)||"No message"),new Error(n.error.message)})}}),N1=xI.reducer;var Lo={text:"",html:null,selection:{start:0,end:0},beforeInputChange:null,mixedSuggestion: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 rh(e){let{key:t,shiftKey:n,ctrlKey:r,metaKey:o,altKey:s}=e;return{key:t,shiftKey:n,ctrlKey:r,metaKey:o,altKey:s}}var ad=be("input/replaceText"),Io=be("input/sendMessage"),ld=be("input/applyImageSuggestion"),ct=be("input/sendEvent"),M1=ee({name:"input",initialState:Lo,reducers:{setInput(e,t){var s,i;let{beforeInputChange:n}=e,{text:r,html:o}=t.payload;if(e.text=r,e.html=o!=null?o:null,r==="")e.metrics=Lo.metrics,e.textSuggestions=[],e.mixedSuggestion=null;else if(n!==null&&e.text!==n.text){let{key:a,shiftKey:l,ctrlKey:u,metaKey:c,altKey:f}=n.keyDown;switch(a){case"Enter":l&&(e.metrics.numCharsTyped+=1);break;case"Backspace":case"Delete":{let{text:d}=e,m=k1(n.text,d);n.text.length-d.length>1&&e.metrics.deletions.push(...m.filter(v=>v.removed).map(v=>v.value)),e.metrics.numCharsDeleted+=n.text.length-d.length;break}case"Shift":case"Meta":case"Tab":break;case"C":case"V":case"X":case"c":case"v":case"x":if(u||c)break;default:if(!u&&!c&&!f){e.metrics.numCharsTyped+=1;let d=((s=n.selection)==null?void 0:s.start)!==void 0&&((i=n.selection)==null?void 0:i.end)!==void 0?n.text.substring(n.selection.start,n.selection.end):null;d&&d.length>0&&(e.metrics.numCharsDeleted+=d.length,e.metrics.deletions.push(d))}}e.metrics.agentStartedTypingTimestamp||(e.metrics.agentStartedTypingTimestamp=Date.now())}e.beforeInputChange=null},setSelection(e,t){t.payload!==null&&($r(e.selection,t.payload)||(e.selection=t.payload))},commitSuggestion(e,t){let n=t.payload,{text:r,suggestion:{source:o,abVariant:s,abTestName:i,trainingJobs:a,sourceText:l,searchTerm:u,text:c},eventMetrics:{inputType:f},replace:d}=n,m=o==="search"||o==="personal-collection-search",v=r.slice(e.text.substring(0,e.selection.start).length);(m||d==="selection")&&(v=r),n.suggestion.source==="search-overlay"&&(v=c),e.metrics.textSuggestions.push({text:v,source:o,abVariant:s,abTestName:i,inputType:f,sourceText:l,trainingJobs:a||[],searchTerm:m?e.text:u}),e.textSuggestions=[],e.selectedSuggestionIndex=-1},offeredTextSuggestion(e,t){let{text:n,suggestion:{source:r}}=t.payload;e.metrics.offeredTextSuggestions.find(s=>s.text===n)||e.metrics.offeredTextSuggestions.push({text:n,source:r})},registerKeyDown(e,t){let{key:n}=t.payload;["Control","Meta","Shift","Alt"].includes(n)||(e.beforeInputChange={text:e.text,selection:e.selection,keyDown:t.payload})},registerKeyUp(e,t){},registerCut(e,t){let{metrics:n}=e,r=t.payload;e.metrics=I(T({},e.metrics),{numCharsCut:n.numCharsCut+r.length,cuts:[...n.cuts,r]})},registerPaste(e,t){let{metrics:n}=e,{text:r,selectionText:o}=t.payload,s=n.numCharsDeleted+(o&&o.length?o.length:0),i=o&&o.length?[...n.deletions,o]:n.deletions;e.metrics=I(T({},e.metrics),{numCharsDeleted:s,deletions:i,numCharsPasted:n.numCharsPasted+r.length,numPaste:n.numPaste+1,pastes:[...n.pastes,r]})},selectNextTextSuggestion(e){let t=e.textSuggestions.length;e.selectedSuggestionIndex=e.selectedSuggestionIndex<t-1?e.selectedSuggestionIndex+1:e.selectedSuggestionIndex},selectPreviousTextSuggestion(e){e.selectedSuggestionIndex=e.selectedSuggestionIndex>=0?e.selectedSuggestionIndex-1:e.selectedSuggestionIndex},selectTextSuggestionByIndex(e,t){e.selectedSuggestionIndex=t.payload},setTextSuggestions(e,t){if(e.selectedSuggestionIndex=-1,e.textSuggestions=t.payload,t.payload.length===0){e.mixedSuggestion=null;return}let n=e.text.substring(0,e.selection.end),r=I1(t.payload,n);e.mixedSuggestion=r!=null&&r.text.includes(n)?r:null},setMetrics(e,{payload:t}){e.metrics=t},resetMetrics(e){e.metrics=Lo.metrics}},extraReducers:e=>{e.addCase(fe,t=>{t.mixedSuggestion=Lo.mixedSuggestion,t.textSuggestions=Lo.textSuggestions,t.selectedSuggestionIndex=Lo.selectedSuggestionIndex,t.metrics=Lo.metrics})}}),si=e=>e.input.text.substring(0,e.input.selection.end),EI=e=>e.input.selection,ii=e=>{let{mixedSuggestion:t,selectedSuggestionIndex:n,textSuggestions:r}=e.input;return n>-1?r[n]:t},_1=()=>M(EI),{commitSuggestion:un,offeredTextSuggestion:D1,registerCut:F1,registerKeyDown:H1,registerKeyUp:U1,registerPaste:z1,selectNextTextSuggestion:j1,selectPreviousTextSuggestion:B1,selectTextSuggestionByIndex:ud,setInput:cd,setMetrics:V1,setSelection:dd,setTextSuggestions:Gr,resetMetrics:K1}=M1.actions,W1=M1.reducer;var bI={agentInfo:void 0,agentSettings:{},visitorInfo:void 0,customData:void 0,platformVariables:void 0,fetchState:"idle"},$a=e=>{var t,n,r;return{timezone:((t=e.info.visitorInfo)==null?void 0:t.visitorTimeZone)||Intl.DateTimeFormat().resolvedOptions().timeZone,agentName:((n=e.info.agentInfo)==null?void 0:n.agentNickname)||"",visitorName:((r=e.info.visitorInfo)==null?void 0:r.visitorName)||""}},CI=[["agentNickname","nickname"],["agentDefaultLocale","defaultLocale"],["agentEmail","email"]],Wa=B("info/setAgentInfo",(e,t)=>P(void 0,null,function*(){var s,i,a;let{deepdeskAPI:n}=t.extra,r=yield n.getMe(),o=[];if(e.agentId&&e.skipSync!==!0&&o.push(n.postIdentity({externalId:e.agentId})),e.skipSync!==!0){let l=CI.reduce((u,[c,f])=>!r[f]&&c in e?I(T({},u),{[f]:e[c]}):u,{});Object.keys(l).length>0&&o.push(n.patchMe(l).then(u=>r=u))}return o.length>0&&(yield Promise.all(o)),{agentId:e.agentId,agentName:e.agentName,agentNickname:(s=e.agentNickname)!=null?s:r.nickname,agentEmail:(i=e.agentEmail)!=null?i:r.email,agentDefaultLocale:(a=e.agentDefaultLocale)!=null?a:r.defaultLocale,agentTimeZone:e.agentTimeZone}})),oh=B("info/setAgentSettings",(e,t)=>P(void 0,null,function*(){let{deepdeskAPI:n}=t.extra,r=yield n.getMe(),o=T(T({},typeof r.uiConfig=="object"?r.uiConfig:{}),e);return yield n.patchMe({uiConfig:o}),o})),sh=B("info/getAgentSettings",(e,t)=>P(void 0,null,function*(){let{deepdeskAPI:n}=t.extra;return(yield n.getMe()).uiConfig})),$1=e=>e.info.agentInfo,q1=e=>e.info.customData,G1=ee({name:"info",initialState:bI,reducers:{setVisitorInfo(e,t){e.visitorInfo=T(T({},e.visitorInfo),t.payload)},setCustomData(e,t){e.customData=t.payload},setPlatformVariables(e,t){e.platformVariables=t.payload}},extraReducers:e=>{e.addCase(Wa.pending,(t,n)=>{t.fetchState="loading",t.agentInfo=T(T({},t.agentInfo),n.meta.arg)}).addCase(Wa.rejected,t=>{t.fetchState="error"}).addCase(Wa.fulfilled,(t,n)=>{t.fetchState="done",t.agentInfo=n.payload}).addCase(oh.fulfilled,(t,n)=>{t.agentSettings=n.payload}).addCase(sh.fulfilled,(t,n)=>{t.agentSettings=n.payload}).addCase(fe,t=>{t.visitorInfo=void 0})}}),{setVisitorInfo:Y1,setCustomData:Q1,setPlatformVariables:X1}=G1.actions,Z1=G1.reducer;function $e(e,t){return Object.entries(t).reduce((n,[r,o])=>n.replaceAll(r,o),e)}var fd={list:[],fetchState:"idle",isOpen:!1,page:"search",aggregates:{}},J1=e=>e.search.isOpen,eE=e=>e.search.page,tE=e=>e.search.list,nE=e=>e.search.aggregates;function rE(e,t=n=>n){return n=>n.search.list.filter(r=>r.type===e).map(t)}var Oo=B("search/getAll",(e,t)=>P(void 0,null,function*(){var l;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=(l=r.conversation.current)==null?void 0:l.profileCode,{platformVariables:s}=r.info;if(!o)throw new Error("Profile should be provided in order to be able to search");let{results:i,aggregates:a}=yield n.search({profile:o,query:e.query,tags:e.tags,size:e.size,current:e.current,filters:{type:e.type},params:$a(r)});return{results:i.map(u=>I(T(T({},u),u.title&&s?{title:$e(u.title,s)}:{}),{text:$e(u.text,s!=null?s:{}),source:`search-${u.type.toLowerCase()}`,searchTerm:e.query})),aggregates:a}})),oE=ee({name:"search",initialState:fd,reducers:{setIsOpen(e,t){e.isOpen=t.payload},setPage(e,t){e.page=t.payload},resetSearch(e){e.fetchState=fd.fetchState,e.list=fd.list}},extraReducers:e=>{e.addCase(Oo.pending,t=>{t.fetchState="loading"}).addCase(Oo.rejected,(t,n)=>{t.fetchState="error",H.error(n.error)}).addCase(Oo.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload.results,t.aggregates=n.payload.aggregates||{}}).addCase(fe,()=>fd)}}),{resetSearch:pd,setIsOpen:Ot,setPage:cn}=oE.actions,sE=oE.reducer;var ih="SetCues",ah="SetOutputs",ai="ShowLoginOverlay",qa="UserLoggedIn",TI="UserLoggedOut",Yr="ApplySuggestion",lh="ApplyImageSuggestion",kI="ShowCommandPalette",PI=e=>({[ih]:t=>{e.dispatch(I(T({},t),{isBroadcasted:!0}))},[ah]:t=>{e.dispatch(I(T({},t),{isBroadcasted:!0}))},[kI]:t=>{e.dispatch(Ot(t.isOpen)),t.page&&e.dispatch(cn(t.page))},[ai]:t=>{e.dispatch(E1(t))},[qa]:()=>{e.dispatch(Zn())},[TI]:()=>{e.dispatch(Zn())},[lh]:t=>{e.dispatch(ld({suggestion:t.suggestion}))},[Yr]:t=>{e.dispatch(un(I(T({},t),{eventMetrics:{inputType:"mouse"},replace:"selection"})))}}),iE=PI;var Ga=w(F()),lE=w(C()),aE=Ga.default.createContext(null),No=({broadcastEvents:e,children:t})=>{let n=Ga.default.useMemo(()=>e,[]);return(0,lE.jsx)(aE.Provider,{value:n,children:t})},Yt=()=>{let e=(0,Ga.useContext)(aE);if(!e)throw new Error("You should use the useBroadcastEvents within a BroadcastEventsProvider");return e};var Ld=w(se()),fn=w(F());var Pd=w(F());var uh=function(e,t){return uh=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[o]=r[o])},uh(e,t)};function Ya(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");uh(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var Nt=function(){return Nt=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},Nt.apply(this,arguments)};function uE(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function md(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}var gd;(function(e){e[e.EXPECT_ARGUMENT_CLOSING_BRACE=1]="EXPECT_ARGUMENT_CLOSING_BRACE",e[e.EMPTY_ARGUMENT=2]="EMPTY_ARGUMENT",e[e.MALFORMED_ARGUMENT=3]="MALFORMED_ARGUMENT",e[e.EXPECT_ARGUMENT_TYPE=4]="EXPECT_ARGUMENT_TYPE",e[e.INVALID_ARGUMENT_TYPE=5]="INVALID_ARGUMENT_TYPE",e[e.EXPECT_ARGUMENT_STYLE=6]="EXPECT_ARGUMENT_STYLE",e[e.INVALID_NUMBER_SKELETON=7]="INVALID_NUMBER_SKELETON",e[e.INVALID_DATE_TIME_SKELETON=8]="INVALID_DATE_TIME_SKELETON",e[e.EXPECT_NUMBER_SKELETON=9]="EXPECT_NUMBER_SKELETON",e[e.EXPECT_DATE_TIME_SKELETON=10]="EXPECT_DATE_TIME_SKELETON",e[e.UNCLOSED_QUOTE_IN_ARGUMENT_STYLE=11]="UNCLOSED_QUOTE_IN_ARGUMENT_STYLE",e[e.EXPECT_SELECT_ARGUMENT_OPTIONS=12]="EXPECT_SELECT_ARGUMENT_OPTIONS",e[e.EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE=13]="EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE",e[e.INVALID_PLURAL_ARGUMENT_OFFSET_VALUE=14]="INVALID_PLURAL_ARGUMENT_OFFSET_VALUE",e[e.EXPECT_SELECT_ARGUMENT_SELECTOR=15]="EXPECT_SELECT_ARGUMENT_SELECTOR",e[e.EXPECT_PLURAL_ARGUMENT_SELECTOR=16]="EXPECT_PLURAL_ARGUMENT_SELECTOR",e[e.EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT=17]="EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT",e[e.EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT=18]="EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT",e[e.INVALID_PLURAL_ARGUMENT_SELECTOR=19]="INVALID_PLURAL_ARGUMENT_SELECTOR",e[e.DUPLICATE_PLURAL_ARGUMENT_SELECTOR=20]="DUPLICATE_PLURAL_ARGUMENT_SELECTOR",e[e.DUPLICATE_SELECT_ARGUMENT_SELECTOR=21]="DUPLICATE_SELECT_ARGUMENT_SELECTOR",e[e.MISSING_OTHER_CLAUSE=22]="MISSING_OTHER_CLAUSE",e[e.INVALID_TAG=23]="INVALID_TAG",e[e.INVALID_TAG_NAME=25]="INVALID_TAG_NAME",e[e.UNMATCHED_CLOSING_TAG=26]="UNMATCHED_CLOSING_TAG",e[e.UNCLOSED_TAG=27]="UNCLOSED_TAG"})(gd||(gd={}));var hd=class{constructor(t){console.warn(`[vite-messages-plugin]: Message "${t}" was not precompiled. Did you use the correct extenstion *.messages.ts?`)}};var dn;(function(e){e[e.literal=0]="literal",e[e.argument=1]="argument",e[e.number=2]="number",e[e.date=3]="date",e[e.time=4]="time",e[e.select=5]="select",e[e.plural=6]="plural",e[e.pound=7]="pound",e[e.tag=8]="tag"})(dn||(dn={}));var yd;(function(e){e[e.number=0]="number",e[e.dateTime=1]="dateTime"})(yd||(yd={}));function ch(e){return e.type===dn.literal}function cE(e){return e.type===dn.argument}function vd(e){return e.type===dn.number}function Sd(e){return e.type===dn.date}function wd(e){return e.type===dn.time}function xd(e){return e.type===dn.select}function Ed(e){return e.type===dn.plural}function dE(e){return e.type===dn.pound}function bd(e){return e.type===dn.tag}function Cd(e){return!!(e&&typeof e=="object"&&e.type===yd.number)}function Qa(e){return!!(e&&typeof e=="object"&&e.type===yd.dateTime)}function dh(e){e.forEach(function(t){if(delete t.location,xd(t)||Ed(t))for(var n in t.options)delete t.options[n].location,dh(t.options[n].value);else vd(t)&&Cd(t.style)||(Sd(t)||wd(t))&&Qa(t.style)?delete t.style.location:bd(t)&&dh(t.children)})}function fE(e,t){t===void 0&&(t={}),t=Nt({shouldParseSkeletons:!0,requiresOtherClause:!0},t);var n=new hd(e,t).parse();if(n.err){var r=SyntaxError(gd[n.err.kind]);throw r.location=n.err.location,r.originalMessage=n.err.message,r}return t!=null&&t.captureLocation||dh(n.val),n.val}function Td(e,t){var n=t&&t.cache?t.cache:NI,r=t&&t.serializer?t.serializer:OI,o=t&&t.strategy?t.strategy:AI;return o(e,{cache:n,serializer:r})}function RI(e){return e==null||typeof e=="number"||typeof e=="boolean"}function pE(e,t,n,r){var o=RI(r)?r:n(r),s=t.get(o);return typeof s=="undefined"&&(s=e.call(this,r),t.set(o,s)),s}function mE(e,t,n){var r=Array.prototype.slice.call(arguments,3),o=n(r),s=t.get(o);return typeof s=="undefined"&&(s=e.apply(this,r),t.set(o,s)),s}function fh(e,t,n,r,o){return n.bind(t,e,r,o)}function AI(e,t){var n=e.length===1?pE:mE;return fh(e,this,n,t.cache.create(),t.serializer)}function LI(e,t){return fh(e,this,mE,t.cache.create(),t.serializer)}function II(e,t){return fh(e,this,pE,t.cache.create(),t.serializer)}var OI=function(){return JSON.stringify(arguments)};function ph(){this.cache=Object.create(null)}ph.prototype.get=function(e){return this.cache[e]};ph.prototype.set=function(e,t){this.cache[e]=t};var NI={create:function(){return new ph}},kd={variadic:LI,monadic:II};var Mo;(function(e){e.MISSING_VALUE="MISSING_VALUE",e.INVALID_VALUE="INVALID_VALUE",e.MISSING_INTL_API="MISSING_INTL_API"})(Mo||(Mo={}));var Xa=function(e){Ya(t,e);function t(n,r,o){var s=e.call(this,n)||this;return s.code=r,s.originalMessage=o,s}return t.prototype.toString=function(){return"[formatjs Error: ".concat(this.code,"] ").concat(this.message)},t}(Error);var mh=function(e){Ya(t,e);function t(n,r,o,s){return e.call(this,'Invalid values for "'.concat(n,'": "').concat(r,'". Options are "').concat(Object.keys(o).join('", "'),'"'),Mo.INVALID_VALUE,s)||this}return t}(Xa);var gE=function(e){Ya(t,e);function t(n,r,o){return e.call(this,'Value for "'.concat(n,'" must be of type ').concat(r),Mo.INVALID_VALUE,o)||this}return t}(Xa);var hE=function(e){Ya(t,e);function t(n,r){return e.call(this,'The intl string context variable "'.concat(n,'" was not provided to the string "').concat(r,'"'),Mo.MISSING_VALUE,r)||this}return t}(Xa);var st;(function(e){e[e.literal=0]="literal",e[e.object=1]="object"})(st||(st={}));function MI(e){return e.length<2?e:e.reduce(function(t,n){var r=t[t.length-1];return!r||r.type!==st.literal||n.type!==st.literal?t.push(n):r.value+=n.value,t},[])}function _I(e){return typeof e=="function"}function Za(e,t,n,r,o,s,i){if(e.length===1&&ch(e[0]))return[{type:st.literal,value:e[0].value}];for(var a=[],l=0,u=e;l<u.length;l++){var c=u[l];if(ch(c)){a.push({type:st.literal,value:c.value});continue}if(dE(c)){typeof s=="number"&&a.push({type:st.literal,value:n.getNumberFormat(t).format(s)});continue}var f=c.value;if(!(o&&f in o))throw new hE(f,i);var d=o[f];if(cE(c)){(!d||typeof d=="string"||typeof d=="number")&&(d=typeof d=="string"||typeof d=="number"?String(d):""),a.push({type:typeof d=="string"?st.literal:st.object,value:d});continue}if(Sd(c)){var m=typeof c.style=="string"?r.date[c.style]:Qa(c.style)?c.style.parsedOptions:void 0;a.push({type:st.literal,value:n.getDateTimeFormat(t,m).format(d)});continue}if(wd(c)){var m=typeof c.style=="string"?r.time[c.style]:Qa(c.style)?c.style.parsedOptions:r.time.medium;a.push({type:st.literal,value:n.getDateTimeFormat(t,m).format(d)});continue}if(vd(c)){var m=typeof c.style=="string"?r.number[c.style]:Cd(c.style)?c.style.parsedOptions:void 0;m&&m.scale&&(d=d*(m.scale||1)),a.push({type:st.literal,value:n.getNumberFormat(t,m).format(d)});continue}if(bd(c)){var v=c.children,y=c.value,p=o[y];if(!_I(p))throw new gE(y,"function",i);var g=Za(v,t,n,r,o,s),h=p(g.map(function(k){return k.value}));Array.isArray(h)||(h=[h]),a.push.apply(a,h.map(function(k){return{type:typeof k=="string"?st.literal:st.object,value:k}}))}if(xd(c)){var S=c.options[d]||c.options.other;if(!S)throw new mh(c.value,d,Object.keys(c.options),i);a.push.apply(a,Za(S.value,t,n,r,o));continue}if(Ed(c)){var S=c.options["=".concat(d)];if(!S){if(!Intl.PluralRules)throw new Xa(`Intl.PluralRules is not available in this environment.
|
|
14
14
|
Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
15
15
|
`,Mo.MISSING_INTL_API,i);var x=n.getPluralRules(t,{type:c.pluralType}).select(d-(c.offset||0));S=c.options[x]||c.options.other}if(!S)throw new mh(c.value,d,Object.keys(c.options),i);a.push.apply(a,Za(S.value,t,n,r,o,d-(c.offset||0)));continue}}return MI(a)}function DI(e,t){return t?Nt(Nt(Nt({},e||{}),t||{}),Object.keys(e).reduce(function(n,r){return n[r]=Nt(Nt({},e[r]),t[r]||{}),n},{})):e}function FI(e,t){return t?Object.keys(e).reduce(function(n,r){return n[r]=DI(e[r],t[r]),n},Nt({},e)):e}function gh(e){return{create:function(){return{get:function(t){return e[t]},set:function(t,n){e[t]=n}}}}}function HI(e){return e===void 0&&(e={number:{},dateTime:{},pluralRules:{}}),{getNumberFormat:Td(function(){for(var t,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];return new((t=Intl.NumberFormat).bind.apply(t,md([void 0],n,!1)))},{cache:gh(e.number),strategy:kd.variadic}),getDateTimeFormat:Td(function(){for(var t,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];return new((t=Intl.DateTimeFormat).bind.apply(t,md([void 0],n,!1)))},{cache:gh(e.dateTime),strategy:kd.variadic}),getPluralRules:Td(function(){for(var t,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];return new((t=Intl.PluralRules).bind.apply(t,md([void 0],n,!1)))},{cache:gh(e.pluralRules),strategy:kd.variadic})}}var yE=function(){function e(t,n,r,o){n===void 0&&(n=e.defaultLocale);var s=this;if(this.formatterCache={number:{},dateTime:{},pluralRules:{}},this.format=function(u){var c=s.formatToParts(u);if(c.length===1)return c[0].value;var f=c.reduce(function(d,m){return!d.length||m.type!==st.literal||typeof d[d.length-1]!="string"?d.push(m.value):d[d.length-1]+=m.value,d},[]);return f.length<=1?f[0]||"":f},this.formatToParts=function(u){return Za(s.ast,s.locales,s.formatters,s.formats,u,void 0,s.message)},this.resolvedOptions=function(){var u;return{locale:((u=s.resolvedLocale)===null||u===void 0?void 0:u.toString())||Intl.NumberFormat.supportedLocalesOf(s.locales)[0]}},this.getAst=function(){return s.ast},this.locales=n,this.resolvedLocale=e.resolveLocale(n),typeof t=="string"){if(this.message=t,!e.__parse)throw new TypeError("IntlMessageFormat.__parse must be set to process `message` of type `string`");var i=o||{},a=i.formatters,l=uE(i,["formatters"]);this.ast=e.__parse(t,Nt(Nt({},l),{locale:this.resolvedLocale}))}else this.ast=t;if(!Array.isArray(this.ast))throw new TypeError("A message must be provided as a String or AST.");this.formats=FI(e.formats,r),this.formatters=o&&o.formatters||HI(this.formatterCache)}return Object.defineProperty(e,"defaultLocale",{get:function(){return e.memoizedDefaultLocale||(e.memoizedDefaultLocale=new Intl.NumberFormat().resolvedOptions().locale),e.memoizedDefaultLocale},enumerable:!1,configurable:!0}),e.memoizedDefaultLocale=null,e.resolveLocale=function(t){if(typeof Intl.Locale!="undefined"){var n=Intl.NumberFormat.supportedLocalesOf(t);return n.length>0?new Intl.Locale(n[0]):new Intl.Locale(typeof t=="string"?t:t[0])}},e.__parse=fE,e.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"}}},e}();function UI(e,t){return t.split(".").reduce((n,r)=>n?n[r]:void 0,e)}var zI="dummy",hh=(0,Pd.createContext)(null);function Y(e){var r;let t=(0,Pd.useContext)(hh);if(!t)throw new Error("useTranslator() may be used only in the context of a <LocaleContext> component.");let n=(r=e[t])!=null?r:{};return(o,s)=>{let i=UI(n,o);return i?new yE(i).format(s):(t!==zI&&console.warn(`${o} does not exist in messages of ${t}`),`[${o}]`)}}var Rd=w(F());var vE={root:"dd-tvkOF",content:"dd-eXA1D"};var yh=w(C()),jI=({isOpen:e,autoFocus:t,children:n,onClose:r,onBack:o,onKeyDown:s,overlayAriaLabel:i,contentAriaLabel:a})=>{let l=(0,Rd.useRef)(null),u=L("Dialog",vE),c=d=>{if(d.key==="Escape"){d.preventDefault(),d.stopPropagation(),o();return}s&&s(d)},f=d=>{d.target===l.current&&e&&r()};return(0,Rd.useEffect)(()=>{var d,m;!l.current||!e||!t||(m=(d=l.current)==null?void 0:d.querySelector("input, textarea"))==null||m.focus()},[e,t,l]),e?(0,yh.jsx)("div",{role:"dialog","data-testid":"dialog",className:u.root,"aria-label":i,ref:l,onKeyDown:c,onMouseDown:f,children:(0,yh.jsx)("div",{"data-testid":"dialog-content",className:u.content,"aria-label":a,children:n})}):null},Ad=jI;var wE=w(se());var SE={root:"dd-ranhW"};var xE=w(C()),BI=r=>{var o=r,{className:e,value:t}=o,n=ne(o,["className","value"]);let s=L("TextInput",SE);return(0,xE.jsx)("input",T({className:(0,wE.default)(e,s.root),type:"text",value:t},n))},Ja=BI;var vh={};Xe(vh,{enUS:()=>VI,nlNL:()=>KI});var VI={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"}]},KI={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 EE={root:"dd-lWxnE",anchorButton:"dd-TZ4in",errorMessage:"dd-fIsPg",title:"dd-pGhJx",subtitle:"dd-f5l29",text:"dd-iamoD",input:"dd-uhQZ3",actions:"dd-lubvx",button:"dd-CJsNI",primaryButton:"dd-MWBfl"};var Ie=w(C());var WI=e=>{try{let t=new URL(e);return new URLSearchParams(t.search).get("token")||void 0}catch(t){return e}},$I=({agentEmail:e,isOpen:t,origin:n="",onSuccess:r,onDismiss:o})=>{let s=Y(vh),i=L("LoginTokenDialog",EE),a=M(v1),l=X(),u=z("productName"),[c,f]=(0,fn.useState)(e||""),[d,m]=(0,fn.useState)(0),[v,y]=(0,fn.useState)(""),p=(0,fn.useCallback)(x=>P(void 0,null,function*(){x.preventDefault(),l(w1({email:c})),m(1)}),[n,c]),g=()=>{y(""),m(0)},h=(0,fn.useCallback)(x=>P(void 0,null,function*(){x.preventDefault();let k=WI(x.target.elements.token.value);if(!k){y(s("verifyCodeError",{login:S}));return}l(Va({token:k}))}),[n]),S=(0,fn.useMemo)(()=>x=>(0,Ie.jsx)("button",{type:"button","data-testid":"login-token-dialog-back-button",className:i.anchorButton,onClick:g,children:x},"back-button"),[]);return(0,fn.useEffect)(()=>{a==="error"&&y(s("verifyCodeError",{login:S})),a==="done"&&r()},[a]),(0,Ie.jsx)(Ad,{autoFocus:!0,isOpen:t,contentAriaLabel:s("promptTitle",{productName:u}),overlayAriaLabel:s("promptTitle",{productName:u}),onClose:o,onBack:o,children:(0,Ie.jsxs)("div",{className:i.root,children:[(0,Ie.jsx)("h1",{className:i.title,children:s("promptTitle",{productName:u})}),d===0&&(0,Ie.jsxs)("form",{onSubmit:p,children:[(0,Ie.jsx)("h2",{className:i.subtitle,children:s("requestCodeTitle")}),(0,Ie.jsx)("p",{className:i.text,children:s("requestCodeBody",{productName:u})}),(0,Ie.jsx)(Ja,{className:i.input,name:"email",placeholder:s("requestCodeInputPlaceholder"),value:c,onChange:x=>f(x.target.value)}),(0,Ie.jsx)("div",{className:i.actions,children:(0,Ie.jsx)("button",{type:"submit",className:(0,Ld.default)(i.button,i.primaryButton),children:s("requestCodeSubmitLabel")})})]}),d===1&&(0,Ie.jsxs)("form",{onSubmit:h,children:[(0,Ie.jsx)("h2",{className:i.subtitle,children:s("verifyCodeTitle")}),(0,Ie.jsx)("p",{className:i.text,children:s("verifyCodeBody")}),(0,Ie.jsx)(Ja,{className:i.input,name:"token",placeholder:s("verifyCodeInputPlaceholder"),disabled:["loading","done"].includes(a)}),v&&(0,Ie.jsx)("div",{className:i.errorMessage,children:v}),(0,Ie.jsxs)("div",{className:i.actions,children:[(0,Ie.jsx)("button",{type:"button",className:(0,Ld.default)(i.button),onClick:g,children:s("back")}),(0,Ie.jsx)("button",{type:"submit",className:(0,Ld.default)(i.button,i.primaryButton),disabled:["loading","done"].includes(a),children:s("verifyCodeSubmitLabel")})]})]})]})})},bE=$I;var TE=w(C()),qI=()=>{let e=M(S1),t=M($1),n=z("adminUrl"),r=Yt(),o=()=>r.send(ai,!1),s=()=>{r.send(ai,!1),r.send(qa)};return(0,TE.jsx)(bE,{isOpen:e,agentEmail:t==null?void 0:t.agentEmail,origin:n,onDismiss:o,onSuccess:s})},CE=qI;var Ub=w(xh()),ft=w(F());var dO={data:null,fetchState:"idle"},AE=e=>e.contentTypes.data,el=B("contentTypes/getContentTypes",(e,t)=>P(void 0,null,function*(){return t.extra.deepdeskAPI.getContentTypes()})),fO=ee({name:"contentTypes",initialState:dO,reducers:{},extraReducers:e=>{e.addCase(el.pending,t=>{t.fetchState="loading"}).addCase(el.rejected,t=>{t.fetchState="error"}).addCase(el.fulfilled,(t,n)=>{t.fetchState="done",t.data=n.payload})}}),LE=fO.reducer;function er(e){let t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.left="-999999px",t.style.top="-999999px",document.body.appendChild(t),t.focus(),t.select(),document.execCommand("copy"),t.remove()}var or=w(F());var IE=w(F()),Id=w(se());var Mt={root:"dd-U2SX4",list:"dd-cYTlj",listWrapper:"dd-GLQFR",listHorizontal:"dd-x-knl",page:"dd-1F4vk",search:"dd-nvbxc",pageNav:"dd-sRUuT",pageTitle:"dd-t-MKS",pageBackButton:"dd-cjptm",listHeader:"dd-Fg666",listHeading:"dd-w-xhJ",listMoreButton:"dd--mKep",listItem:"dd-wpvuA",listItemContent:"dd-V-mKo",listItemText:"dd-ukCHL",listItemDescription:"dd-sSyu4",listItemActions:"dd-xelho",truncate:"dd-IlopJ",lineClamp:"dd-Twaca",listItemTitle:"dd-lMGHq",listItemAction:"dd-xPLAs",listItemSelected:"dd-jFX0Y",sources:"dd-pZx4v",sourcesTitle:"dd-phYVd",source:"dd-DaR6h",sourceShowMore:"dd-M1-8j",icon:"dd-m6yxD",searchIcon:"dd-0AU-O",searchInputWrapper:"dd-DUFcE",searchInput:"dd-ukrlD",select:"dd--Tifv",selectType:"dd-IkZb2",selectWrapper:"dd-J14mx",image:"dd-RQgsB",imageSrc:"dd-jxh8F",imageSrcHidden:"dd-e20Jk",imageSrcStatus:"dd-j50Tt",imageTitle:"dd-qCjfW",actions:"dd-3mfWc",actionsWrapper:"dd-TjDyI",actionsBar:"dd-LiA35",actionButton:"dd-4wk0u",hasShortKeys:"dd-XilV-",actionShortcut:"dd-s4Mla",actionShortcutFixKerning:"dd-lyh5e"};var tr={};Xe(tr,{enUS:()=>pO,nlNL:()=>mO});var pO={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"}],sources:[{type:0,value:"Sources"}],showMore:[{type:0,value:"Show "},{type:1,value:"amount"},{type:0,value:" more"}]},mO={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"}],sources:[{type:0,value:"Bronnen"}],showMore:[{type:0,value:"Toon "},{type:1,value:"amount"},{type:0,value:" meer"}]};var Qr=w(C()),gO=({src:e,title:t})=>{let n=L("CommandPalette",Mt),[r,o]=(0,IE.useState)("loading"),s=Y(tr);return(0,Qr.jsxs)("div",{className:n.image,children:[(0,Qr.jsx)("img",{src:e,alt:t,onLoad:()=>o("done"),onError:()=>o("error"),className:(0,Id.default)(n.imageSrc,{[n.imageSrcHidden]:["loading","error"].includes(r)})}),r==="loading"&&(0,Qr.jsx)("span",{className:(0,Id.default)(n.imageSrc,n.imageSrcStatus),children:s("loading")}),r==="error"&&(0,Qr.jsx)("span",{className:(0,Id.default)(n.imageSrc,n.imageSrcStatus),children:(0,Qr.jsx)(Zl,{})}),t&&(0,Qr.jsx)("span",{className:n.imageTitle,children:t})]})},OE=gO;var NE=w(F()),ME=w(se());var _o=w(C());function Eh({children:e,heading:t,orientation:n,hasMore:r,onShowAll:o}){let s=Y(tr),i=L("CommandPalette",Mt);return NE.default.Children.count(e)===0?null:(0,_o.jsxs)("div",{"data-testid":"commandpalette-list",className:i.list,children:[(t||r)&&(0,_o.jsxs)("div",{className:i.listHeader,children:[t&&(0,_o.jsx)("h4",{className:i.listHeading,children:t}),r&&o&&(0,_o.jsx)("button",{onClick:o,className:i.listMoreButton,type:"button",children:s("showAll")})]}),(0,_o.jsx)("div",{className:(0,ME.default)(i.listWrapper,n==="horizontal"&&i.listHorizontal),children:e})]})}var sl=w(se());var Od=w(F());function tl(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var le=1,Ch=2,Th=4,Me=8,Nd=16,nl=32,pn=64,bh={a:{content:le|Me,self:!1,type:le|Me|nl|pn},address:{invalid:["h1","h2","h3","h4","h5","h6","address","article","aside","section","div","header","footer"],self:!1},audio:{children:["track","source"]},br:{type:le|Me,void:!0},body:{content:le|Ch|Th|Me|Nd|nl|pn},button:{content:Me,type:le|Me|nl|pn},caption:{content:le,parent:["table"]},col:{parent:["colgroup"],void:!0},colgroup:{children:["col"],parent:["table"]},details:{children:["summary"],type:le|nl|pn},dd:{content:le,parent:["dl"]},dl:{children:["dt","dd"],type:le},dt:{content:le,invalid:["footer","header"],parent:["dl"]},figcaption:{content:le,parent:["figure"]},footer:{invalid:["footer","header"]},header:{invalid:["footer","header"]},hr:{type:le,void:!0},img:{void:!0},li:{content:le,parent:["ul","ol","menu"]},main:{self:!1},ol:{children:["li"],type:le},picture:{children:["source","img"],type:le|Me|Nd},rb:{parent:["ruby","rtc"]},rp:{parent:["ruby","rtc"]},rt:{content:Me,parent:["ruby","rtc"]},rtc:{content:Me,parent:["ruby"]},ruby:{children:["rb","rp","rt","rtc"]},source:{parent:["audio","video","picture"],void:!0},summary:{content:Me,parent:["details"]},table:{children:["caption","colgroup","thead","tbody","tfoot","tr"],type:le},tbody:{parent:["table"],children:["tr"]},td:{content:le,parent:["tr"]},tfoot:{parent:["table"],children:["tr"]},th:{content:le,parent:["tr"]},thead:{parent:["table"],children:["tr"]},tr:{parent:["table","tbody","thead","tfoot"],children:["th","td"]},track:{parent:["audio","video"],void:!0},ul:{children:["li"],type:le},video:{children:["track","source"]},wbr:{type:le|Me,void:!0}};function Fo(e){return t=>{bh[t]=T(T({},e),bh[t])}}["address","main","div","figure","p","pre"].forEach(Fo({content:le,type:le|pn}));["abbr","b","bdi","bdo","cite","code","data","dfn","em","i","kbd","mark","q","ruby","samp","strong","sub","sup","time","u","var"].forEach(Fo({content:Me,type:le|Me|pn}));["p","pre"].forEach(Fo({content:Me,type:le|pn}));["s","small","span","del","ins"].forEach(Fo({content:Me,type:le|Me}));["article","aside","footer","header","nav","section","blockquote"].forEach(Fo({content:le,type:le|Ch|pn}));["h1","h2","h3","h4","h5","h6"].forEach(Fo({content:Me,type:le|Th|pn}));["audio","canvas","iframe","img","video"].forEach(Fo({type:le|Me|Nd|pn}));var ol=Object.freeze(bh),kh=["applet","base","body","command","embed","frame","frameset","head","html","link","meta","noscript","object","script","style","title"],Ph=Object.keys(ol).filter(e=>e!=="canvas"&&e!=="iframe"),pe=1,Rh=2,Do=3,Xr=4,_d=5,Dd=Object.freeze({alt:pe,cite:pe,class:pe,colspan:Do,controls:Xr,datetime:pe,default:Xr,disabled:Xr,dir:pe,height:pe,href:pe,id:pe,kind:pe,label:pe,lang:pe,loading:pe,loop:Xr,media:pe,muted:Xr,poster:pe,rel:pe,role:pe,rowspan:Do,scope:pe,sizes:pe,span:Do,start:Do,style:_d,src:pe,srclang:pe,srcset:pe,tabindex:pe,target:pe,title:pe,type:pe,width:pe}),Ah=Object.freeze({class:"className",colspan:"colSpan",datetime:"dateTime",rowspan:"rowSpan",srclang:"srcLang",srcset:"srcSet",tabindex:"tabIndex"});function Md(){return Md=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Md.apply(this,arguments)}function Fd({attributes:e={},className:t,children:n=null,selfClose:r=!1,tagName:o}){let s=o;return r?Od.default.createElement(s,Md({className:t},e)):Od.default.createElement(s,Md({className:t},e),n)}var rl=class{attribute(t,n){return n}node(t,n){return n}};function _E(e,t,n,r=!1){let o=e.match(t instanceof RegExp?t:new RegExp(t,"i"));return o?I(T({match:o[0],void:r},n(o)),{index:o.index,length:o[0].length,valid:!0}):null}var nr=class{constructor(t,n,r){tl(this,"greedy",!1),tl(this,"options",void 0),tl(this,"propName",void 0),tl(this,"inverseName",void 0),tl(this,"factory",void 0),this.options=T({},n),this.propName=t,this.inverseName=`no${t.charAt(0).toUpperCase()+t.slice(1)}`,this.factory=r!=null?r:null}createElement(t,n){return this.factory?Od.default.createElement(this.factory,n,t):this.replaceWith(t,n)}doMatch(t,n,r,o=!1){return _E(t,n,r,o)}onBeforeParse(t,n){return t}onAfterParse(t,n){return t}};var Ho=w(F()),UE=w(FE());function rr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var vO=/(url|image|image-set)\(/i,Lh=class extends rl{attribute(t,n){return t==="style"&&Object.keys(n).forEach(r=>{String(n[r]).match(vO)&&delete n[r]}),n}},HE=1,SO=3,wO=/^<(!doctype|(html|head|body)(\s|>))/i,xO=/^(aria-|data-|\w+:)/iu,EO=/{{{(\w+)\/?}}}/;function bO(){if(!(typeof window=="undefined"||typeof document=="undefined"))return document.implementation.createHTMLDocument("Interweave")}var Hd=class{constructor(t,n={},r=[],o=[]){var s;rr(this,"allowed",void 0),rr(this,"banned",void 0),rr(this,"blocked",void 0),rr(this,"container",void 0),rr(this,"content",[]),rr(this,"props",void 0),rr(this,"matchers",void 0),rr(this,"filters",void 0),rr(this,"keyIndex",void 0),this.props=n,this.matchers=r,this.filters=[...o,new Lh],this.keyIndex=-1,this.container=this.createContainer(t||""),this.allowed=new Set((s=n.allowList)!==null&&s!==void 0?s:Ph),this.banned=new Set(kh),this.blocked=new Set(n.blockList)}applyAttributeFilters(t,n){return this.filters.reduce((r,o)=>r!==null&&typeof o.attribute=="function"?o.attribute(t,r):r,n)}applyNodeFilters(t,n){return this.filters.reduce((r,o)=>r!==null&&typeof o.node=="function"?o.node(t,r):r,n)}applyMatchers(t,n){let r={},{props:o}=this,s=t,i=0,a=null;return this.matchers.forEach(l=>{let u=l.asTag().toLowerCase(),c=this.getTagConfig(u);if(o[l.inverseName]||!this.isTagAllowed(u)||!this.canRenderChild(n,c))return;let f="";for(;s&&(a=l.match(s));){let d=a,{index:m,length:v,match:y,valid:p,void:g}=d,h=ne(d,["index","length","match","valid","void"]),S=l.propName+String(i);m>0&&(f+=s.slice(0,m)),p?(f+=g?`{{{${S}/}}}`:`{{{${S}}}}${y}{{{/${S}}}}`,this.keyIndex+=1,i+=1,r[S]={children:y,matcher:l,props:I(T(T({},o),h),{key:this.keyIndex})}):f+=y,l.greedy?(s=f+s.slice(m+v),f=""):s=s.slice(m+(v||y.length))}l.greedy||(s=f+s)}),i===0?t:this.replaceTokens(s,r)}canRenderChild(t,n){return!t.tagName||!n.tagName||t.void?!1:t.children.length>0?t.children.includes(n.tagName):t.invalid.length>0&&t.invalid.includes(n.tagName)?!1:n.parent.length>0?n.parent.includes(t.tagName):!t.self&&t.tagName===n.tagName?!1:!!(t&&t.content&n.type)}convertLineBreaks(t){let{noHtml:n,disableLineBreaks:r}=this.props;if(n||r||t.match(/<((?:\/[ a-z]+)|(?:[ a-z]+\/))>/gi))return t;let o=t.replace(/\r\n/g,`
|
|
16
16
|
`);return o=o.replace(/\n{3,}/g,`
|
|
@@ -24,7 +24,7 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
|
24
24
|
`+yt),xn&&bf([V,W,me],vt=>{yt=Cl(yt,vt," ")}),S&&Bl?S.createHTML(yt):yt},t.setConfig=function(){let j=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Vf(j),Hn=!0},t.clearConfig=function(){us=null,Hn=!1},t.isValidAttribute=function(j,E,A){us||Vf({});let U=He(j),Z=He(E);return av(U,Z,A)},t.addHook=function(j,E){typeof E=="function"&&(Q[j]=Q[j]||[],bl(Q[j],E))},t.removeHook=function(j){if(Q[j])return bT(Q[j])},t.removeHooks=function(j){Q[j]&&(Q[j]=[])},t.removeAllHooks=function(){Q={}},t}var DT=_T();var gr=w(F());var HM={"":["<em>","</em>"],_:["<strong>","</strong>"],"*":["<strong>","</strong>"],"~":["<s>","</s>"],"\n":["<br />"]," ":["<br />"],"-":["<hr />"]};function FT(e){return e.replace(RegExp("^"+(e.match(/^(\t| )+/)||"")[0],"gm"),"")}function kl(e){return(e+"").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Pl(e,t){var n,r,o,s,i,a=/((?:^|\n+)(?:\n---+|\* \*(?: \*)+)\n)|(?:^``` *(\w*)\n([\s\S]*?)\n```$)|((?:(?:^|\n+)(?:\t| {2,}).+)+\n*)|((?:(?:^|\n)([>*+-]|\d+\.)\s+.*)+)|(?:!\[([^\]]*?)\]\(([^)]+?)\))|(\[)|(\](?:\(([^)]+?)\))?)|(?:(?:^|\n+)([^\s].*)\n(-{3,}|={3,})(?:\n+|$))|(?:(?:^|\n+)(#{1,6})\s*(.+)(?:\n+|$))|(?:`([^`].*?)`)|( \n\n*|\n{2,}|__|\*\*|[_*]|~~)/gm,l=[],u="",c=t||{},f=0;function d(v){var y=HM[v[1]||""],p=l[l.length-1]==v;return y?y[1]?(p?l.pop():l.push(v),y[0|p]):y[0]:v}function m(){for(var v="";l.length;)v+=d(l[l.length-1]);return v}for(e=e.replace(/^\[(.+?)\]:\s*(.+)$/gm,function(v,y,p){return c[y.toLowerCase()]=p,""}).replace(/^\n+|\n+$/g,"");o=a.exec(e);)r=e.substring(f,o.index),f=a.lastIndex,n=o[0],r.match(/[^\\](\\\\)*\\$/)||((i=o[3]||o[4])?n='<pre class="code '+(o[4]?"poetry":o[2].toLowerCase())+'"><code'+(o[2]?' class="language-'+o[2].toLowerCase()+'"':"")+">"+FT(kl(i).replace(/^\n+|\n+$/g,""))+"</code></pre>":(i=o[6])?(i.match(/\./)&&(o[5]=o[5].replace(/^\d+/gm,"")),s=Pl(FT(o[5].replace(/^\s*[>*+.-]/gm,""))),i==">"?i="blockquote":(i=i.match(/\./)?"ol":"ul",s=s.replace(/^(.*)(\n|$)/gm,"<li>$1</li>")),n="<"+i+">"+s+"</"+i+">"):o[8]?n='<img src="'+kl(o[8])+'" alt="'+kl(o[7])+'">':o[10]?(u=u.replace("<a>",'<a href="'+kl(o[11]||c[r.toLowerCase()])+'">'),n=m()+"</a>"):o[9]?n="<a>":o[12]||o[14]?n="<"+(i="h"+(o[14]?o[14].length:o[13]>"="?1:2))+">"+Pl(o[12]||o[15],c)+"</"+i+">":o[16]?n="<code>"+kl(o[16])+"</code>":(o[17]||o[1])&&(n=d(o[17]||"--"))),u+=r,u+=n;return(u+e.substring(f)+m()).replace(/^\n+|\n+$/g,"")}var HT={root:"dd-L7b3z",popover:"dd-OQOTB",options:"dd-Y12RE",arrow:"dd-cv33T",copyIcon:"dd-6xOsH",option:"dd-9oFX4",divider:"dd-aiZf8",fadeup:"dd-Jq9pd"};var vn=w(C());function UM(e){return`<button type="button" data-copy-icon class=${e}><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 Ay(e){var n;let t=e.cloneNode(!0);return t.querySelectorAll("div,button").forEach(r=>r.remove()),(n=t.textContent)!=null?n:""}function zM(e){return e.replace(/\r\n/g,`
|
|
25
25
|
`)}function jM(e){return e.replace(new RegExp("(?<!\\]\\()(https?:\\/\\/[^\\s]+)","g"),"[$1]($1)")}var BM=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let s=L("Markdown",HT),i=(0,gr.useRef)(null),[a,l]=(0,gr.useState)(null),u=(0,gr.useMemo)(()=>{let y=Pl(jM(zM(e)));return DT.sanitize(y).replaceAll("</code>",`${UM(s.copyIcon)}</code>`).replaceAll('<a href="','<a target="_blank" rel="noreferrer noopener" href="')},[e]),c=y=>{var h;let p=y.target,g=!!((h=i.current)!=null&&h.querySelector("code"));if(["A","BUTTON"].includes(p.tagName)){l(null);return}a||g&&p.tagName!=="CODE"||!g&&p!==i.current||(p.addEventListener("mouseleave",()=>l(null),{once:!0}),l(p))},f=()=>{if(!a)return;l(null);let y=a.querySelector("button");y&&(pi(y,s.fadeup),r(Ay(a)))},d=y=>{let p=y.target;if(p.tagName==="A"){y.stopPropagation();return}"copyIcon"in p.dataset&&(pi(p,s.fadeup),r(Ay(p.parentElement)))},m=()=>{!a||!o||(l(null),o(Ay(a)))},v=y=>{if(y===null)return;let p=y.getBoundingClientRect();p.left<0?y.style.transform=`translateX(${-p.left+2}px)`:p.right>window.innerWidth&&(y.style.transform=`translateX(${window.innerWidth-p.right-2}px)`)};return(0,vn.jsxs)(gr.Fragment,{children:[a&&(0,vn.jsxs)(bi,{triggerRef:{current:a},className:s.popover,parentNode:a,children:[(0,vn.jsxs)("div",{className:s.options,ref:v,children:[(0,vn.jsx)("button",{type:"button",className:s.option,onClick:f,children:n}),o&&(0,vn.jsxs)(gr.Fragment,{children:[(0,vn.jsx)("div",{className:s.divider}),(0,vn.jsx)("button",{type:"button",className:s.option,onClick:m,children:t})]})]}),(0,vn.jsx)("div",{className:s.arrow})]}),(0,vn.jsx)("div",{ref:i,className:s.root,dangerouslySetInnerHTML:{__html:u},onMouseOver:c,onClick:d})]})},UT=BM;var Ly={};Xe(Ly,{enUS:()=>VM,nlNL:()=>KM});var VM={useCue:[{type:0,value:"Add to message"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},KM={useCue:[{type:0,value:"Voeg toe aan bericht"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var zT={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",actions:"dd-9Iqn9",thumbsUp:"dd-6QwVx",thumbsDown:"dd-d3E8l"};var tn=w(C()),WM=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o})=>{let s=L("WidgetCue",zT),i=Y(Ly),a=mi(),l=z("hasKeyboardInput"),u=()=>{t&&t(e),n(e)},c=m=>{r&&r(m,e)},f=m=>{o&&o(m,e)},d=m=>{m.preventDefault(),m.stopPropagation(),n(e)};return(0,jT.useEffect)(()=>{a("Assistant response displayed",{name:e.rule.name,description:e.rule.description,group:e.rule.label,cueText:e.text})},[]),(0,tn.jsxs)(oe,{"data-testid":"cue",children:[(0,tn.jsx)(ve,{children:(0,tn.jsxs)(ve.Content,{children:[e.title&&(0,tn.jsx)(ve.Title,{className:s.title,"data-testid":"widget-cue-title",children:e.title}),(0,tn.jsx)(UT,{content:e.text,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:c,onUse:l?f:void 0})]})}),(0,tn.jsxs)(oe.ButtonsContainer,{children:[(0,tn.jsxs)("div",{className:s.actions,children:[e.callToAction&&(0,tn.jsx)(oe.Button,{onClick:u,children:e.callToAction.label}),(0,tn.jsx)(oe.Button,{onClick:d,children:i("removeCue")})]}),(0,tn.jsx)(hi,{eventName:"Assistant response feedback",eventData:{name:e.rule.name,group:e.rule.label,description:e.rule.description,cueText:e.text},feedbackText:e.text,feedbackType:"assistant"})]})]})},BT=WM;var Rl=w(C()),$M=({cues:e})=>{let t=X(),n=Yt(),r=mi(),o=l=>{t(nT({id:l.rule.id})),t(ib({code:l.rule.label})),r("Assistant response closed",{name:l.rule.name,group:l.rule.label,description:l.rule.description,cueText:l.text})},s=(l,u)=>{er(l),r("Assistant response copied",{name:u.rule.name,group:u.rule.label,description:u.rule.description,copiedText:l})},i=l=>{l.callToAction&&(t(Vd(l)),r("Assistant call to action",{name:l.rule.name,group:l.rule.label,description:l.rule.description,eventName:l.callToAction.event,value:l.callToAction.value}))},a=(l,u)=>{n.send(Yr,{text:l,suggestion:{source:"cue",sourceText:l}}),r("Assistant response used",{name:u.rule.name,group:u.rule.label,description:u.rule.description,usedText:l})};return(0,Rl.jsx)(Rl.Fragment,{children:e.map(l=>(0,Rl.jsx)(BT,{cue:l,onCallToAction:i,onRemove:o,onCopy:s,onUse:a},l.rule.id))})},VT=$M;var Pf=w(F());var KT={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var Sn=w(C());function qM(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var WT=({data:e,schema:t})=>{let n=L("WidgetCustomData",KT),r=o=>{er(o)};return(0,Pf.useEffect)(()=>{H.info("Custom data",e,t)},[e]),(0,Sn.jsx)("dl",{className:n.root,children:t.map(o=>{let s=qM(e,o.path);return(0,Sn.jsxs)(Pf.Fragment,{children:[(0,Sn.jsx)("dt",{className:n.label,children:o.label}),(0,Sn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&s?(0,Sn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!s?(0,Sn.jsx)("span",{className:n.isFalse,children:o.falseValue}):s?(0,Sn.jsxs)("button",{type:"button",onClick:()=>r(s),className:n.copyButton,children:[(0,Sn.jsx)("span",{className:n.copyButtonText,children:s}),(0,Sn.jsx)(El,{})]}):"-"})]},o.label)})})};var qT=w(F());var GM=/(https?:\/\/[^\s]+)/,$T=e=>e.split(" ").find(t=>GM.test(t));var nn=w(C()),YM=({suggestion:e,lines:t,onUse:n})=>{var f;let r=e.text||e.url||e.message,o=$T(r),s=Y(Vo),i=z("showImages"),a=z("fallbackImage"),l=z("hasKeyboardInput"),u=d=>{d.preventDefault(),d.stopPropagation(),l&&n(r)},c=(0,qT.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,nn.jsxs)(oe,{onClick:l?u:void 0,"data-testid":"edit-suggestion",children:[(0,nn.jsxs)(ve,{children:[i&&e.image&&(0,nn.jsx)(ve.Image,{src:hf(e,"small",a||void 0),title:e.title}),(0,nn.jsxs)(ve.Content,{children:[e.title&&(0,nn.jsx)(ve.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((f=e.searchKeywords)==null?void 0:f.length)>0&&(0,nn.jsx)(oe.Labels,{labels:e.searchKeywords}),(0,nn.jsx)(ve.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,nn.jsxs)(oe.Actions,{children:[o&&(0,nn.jsx)(oe.ActionButton,{onClick:c,label:s("visitUrl")}),l&&(0,nn.jsx)(oe.ActionButton,{primary:!0,onClick:u,label:s("useSuggestion")})]})]})},GT=YM;var Al=w(C()),QM=({lines:e,suggestions:t})=>{let n=Yt(),r=(o,s)=>{n.send(Yr,{text:o,suggestion:I(T({},s),{source:s.source,sourceText:s.text})})};return(0,Al.jsx)(Al.Fragment,{children:t.map(o=>(0,Al.jsx)(GT,{suggestion:o,lines:e,onUse:s=>r(s,o)},o.text||o.url||o.message))})},YT=QM;var Ll={};Xe(Ll,{enUS:()=>XM,nlNL:()=>ZM});var XM={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"}]},ZM={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 Il={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",sectionList:"dd-bF9pF",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",link:"dd-DRo0x"};var q=w(C()),Rf=(e,t)=>{let n=M(ut);(0,Ci.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},JM=({onLogIn:e})=>{let t=L("Widget",Il),n=z("isEmbedded"),r=z("adminUrl");return(0,q.jsx)("div",{className:t.loginText,children:(0,q.jsx)("div",{children:(0,q.jsx)(nf,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},QT=({text:e})=>{let t=L("Widget",Il);return(0,q.jsx)("div",{className:t.stateText,children:(0,q.jsx)("div",{children:(0,q.jsx)("p",{children:e})})},"notification")},e_=()=>{let e=Y(Ll),t=X(),n=L("Widget",Il),r=z("showSearch"),o=z("showSummaryCommand"),s=z("showKnowledgeSearch"),i=z("isEmbedded"),a=M(gi("/admin/")),l=Yt(),u=z("productName"),c=z("hasKeyboardInput"),f=r||o||s||a;return Rf(()=>{if(i)return t(fy()),()=>{t(XC())}},[t,i]),!f||!c?null:(0,q.jsx)(En,{title:e("actions"),type:"shortcuts",children:(0,q.jsxs)("div",{className:n.shortcutList,children:[r&&(0,q.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-search","aria-label":e("linkSearch"),onClick:()=>l.send("ShowCommandPalette",{isOpen:!0}),children:[(0,q.jsx)(ci,{}),e("linkSearch")]}),o&&(0,q.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-summary","aria-label":e("linkSummary"),onClick:()=>l.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,q.jsx)(xT,{}),e("linkSummary")]}),s&&(0,q.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-knowledge-assist","aria-label":e("linkKnowledgeSearch"),onClick:()=>l.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,q.jsx)(wT,{}),e("linkKnowledgeSearch")]}),a&&(0,q.jsxs)("a",{className:n.shortcut,target:"_blank",href:a,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:u}),rel:"noreferrer",children:[(0,q.jsx)(ST,{}),e("linkStudioLogin",{productName:u})]})]})})},t_=()=>{let e=X(),t=z("showCustomMessages"),n=M(BC),r=M(ri);return Rf(()=>(e(xl(r)),e(qC(r)),()=>{e(GC(r))}),[e,t,r]),!t||n.length===0?null:(0,q.jsx)(En,{type:"custom-messages","data-testid":"custom-messages",children:(0,q.jsx)(xt,{withDivider:!0,children:n.map(o=>(0,q.jsx)(hT,{suggestion:o},o.text))})})},n_=()=>{let e=Y(Ll),t=X(),n=z("showAutoflows"),r=M(FC),o=M(ri);return Rf(()=>(t(pr(o)),t(HC(o)),()=>{t(UC(o))}),[t,n,o]),!n||r.length===0?null:(0,q.jsx)(En,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:(0,q.jsx)(xt,{withDivider:!0,children:(0,q.jsx)(mT,{})})})},r_=()=>{let e=X(),t=M(Wd),n=M(pb),r=M(oT),o=M(q1),s=M(Bd),i=M($d),a=M(ir),l=M(qr);return(0,Ci.useEffect)(()=>{!!o&&!n&&H.warn("Custom data provided, but no schema.")},[o,n]),Rf(()=>{t.forEach(({type:u})=>{u==="entities"?e(gn()):iu.includes(u)||e(hn(u))})},[e,l,a]),(0,Ci.useEffect)(()=>{r.length>0&&!t.some(u=>u.type==="cues")&&H.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,q.jsx)(Ci.Fragment,{children:t.map(({type:u,title:c,amount:f,lines:d,schema:m})=>{var v,y;switch(u){case"entities":return s&&s.length>0&&(0,q.jsx)(En,{type:u,title:c,"data-testid":`type-${u}`,children:(0,q.jsx)(vT,{entities:s})},u);case"cues":return r&&r.length>0&&(0,q.jsx)(En,{type:u,title:c,"data-testid":`type-${u}`,children:(0,q.jsx)(xt,{withDivider:!0,children:(0,q.jsx)(VT,{cues:r})})},u);case"custom-data":return o&&m&&(0,q.jsx)(En,{type:u,title:c,"data-testid":`type-${u}`,children:(0,q.jsx)(xt,{withDivider:!0,children:(0,q.jsx)(WT,{data:o,schema:m})})},u);default:return((y=(v=i[u])==null?void 0:v.suggestions)==null?void 0:y.length)>0&&(0,q.jsx)(En,{type:u,title:c,"data-testid":`type-${u}`,children:(0,q.jsx)(xt,{withDivider:!0,children:(0,q.jsx)(YT,{lines:d,contentType:u,suggestions:i[u].suggestions.slice(0,f)||[]})})},u)}})})},o_=({onLogIn:e})=>{let t=Y(Ll),n=L("Widget",Il),r=M(oi),o=M(ut),s=M(ri),i=M(ir);return r===!1?(0,q.jsx)(QT,{text:t("notSupported")}):o===!1?(0,q.jsx)(JM,{onLogIn:e}):!i||!s||o===null?(0,q.jsx)(QT,{text:t("waiting")}):(0,q.jsx)("div",{className:(0,XT.default)(n.root),"data-testid":"widget",children:(0,q.jsxs)(ru,{className:n.sectionList,children:[(0,q.jsx)(e_,{}),(0,q.jsx)(t_,{}),(0,q.jsx)(n_,{}),(0,q.jsx)(r_,{})]})})},ZT=o_;function Ti(e){let t=new Range;return t.selectNodeContents(e),t}function JT(e,t,n){try{return so(e,t,n),!0}catch(r){return!1}}function Af(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function Lf(e){return"tagName"in e&&e.tagName==="BR"}var Ol=/[\u200B-\u200D\uFEFF]/g;function so(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,s=!1;function i(l,u){let c=-1,f=/[\u200B-\u200D\uFEFF]/;if(!f.test(l))return u;for(let d=0;d<=l.length;d++)if(f.test(l[d])||c++,c===u)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let u=l.textContent,c=u.replace(Ol,""),f=o+c.length,d=t>=o&&t<=f,m=n>=o&&n<=f;if(d){let v=i(u,t-o);v===0&&!m?r.setStartBefore(l):r.setStart(l,v)}m&&(r.setEnd(l,i(u,n-o)),s=!0),o=f;break}case Node.ELEMENT_NODE:{if(Lf(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),s=!0;return}for(let c=0;c<l.childNodes.length&&(a(l.childNodes[c]),!s);c++);let u=l.lastChild;Af(l)&&u&&!Af(u)&&!Lf(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function Nl(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:s,collapsed:i}=t,a,l,u=0;function c(f){let d=f===e,m=f===n,v=f===o;switch(f.nodeType){case Node.TEXT_NODE:{let y=f.textContent;m&&(a=u+y.substring(0,r).replace(Ol,"").length),v&&(l=u+y.substring(0,s).replace(Ol,"").length),u+=y.replace(Ol,"").length;break}case Node.ELEMENT_NODE:{if(Lf(f)&&f.nextSibling){u++;break}!d&&Af(f)&&f.previousSibling&&u++;for(let y=0;y<f.childNodes.length;y++){let p=m&&y===r,g=v&&y===s;if(p&&(a=u),g&&(l=u),l!==void 0||((!p||!i)&&c(f.childNodes[y]),v&&y===s-1&&(l=u),l!==void 0))break}v&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:l,end:l}}function Ml(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:s,collapsed:i}=t,a=0,l="";function u(c){let f=c===e,d=c===n,m=c===o;switch(d&&(a=1),c.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let v=d?r:0,y=m?s:void 0;l+=c.textContent.replace(Ol,"").substring(v,y);break}case Node.ELEMENT_NODE:{if(!i&&a===1&&Lf(c)&&c.nextSibling){l+=`
|
|
26
26
|
`;break}!f&&!i&&a===1&&Af(c)&&c.previousSibling&&(l+=`
|
|
27
|
-
`);let v=d?r:0,y=m?Math.min(s,c.childNodes.length):c.childNodes.length;for(let p=v;p<y&&(u(c.childNodes[p]),a!==2);p++);break}default:break}m&&(a=2)}return u(e),l}var ek=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(ek||{}),hr=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let s=this.getCaretPosition();$r(s,this.cachedCaretPosition)||(this.cachedCaretPosition=s,this.emit("caretposition",s))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(ek).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function tk(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Zo=class extends hr{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Ml(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(i=r.getComposedRanges(n))==null?void 0:i[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let s=this.element.ownerDocument.createRange();return s.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),s.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!tk(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!tk(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return Nl(this.element,n);let r=this.lastKnownSelection;if(r&&JT(this.element,r.start,r.end))return r;let o=Ti(this.element);return o.collapse(!1),Nl(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Ml(this.element,so(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var s_=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function nk(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,s=window.getComputedStyle(e),i=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",s_.forEach(function(c){o[c]=s[c]}),n?e.scrollHeight>parseInt(s.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),i.appendChild(r);let l=e.getBoundingClientRect(),u={top:l.top-e.scrollTop+a.offsetTop+parseInt(s.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+parseInt(s.borderLeftWidth)};return i.removeChild(r),u}var Jo=class extends hr{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return nk(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function rk(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let s=document.createElement("iframe"),i=new URL(t);return Object.entries(n).forEach(([a,l])=>{i.searchParams.append(a,l)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=r,s.title=`iframe-${e}`,s.src=i.toString(),window.document.body.appendChild(s),s}function i_(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var Iy=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Oy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=rk(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},Ny=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),H.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Oy(t,this.deepdeskUrl,{debug:!0}):new Iy(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=i_(o.data);typeof s!="object"||s.type!=="event"||s.channel!==t||(H.info("Received broadcast event",this.sessionId,o),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(r),n}send(t,n,r){var i,a;H.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(i=this.eventMap)[t])==null||a.call(i,n));let s=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(I(T({},o),{channel:this.sessionId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},ok=Ny;function a_(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function ie(e){return Array.isArray(e)?e.map(ie):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(T({},t),{[a_(n)]:ie(e[n])}),{}):e}function My(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Le(e){return Array.isArray(e)?e.map(Le):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(T({},t),{[My(n)]:Le(e[n])}),{}):e}var ki=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var _y=e=>new Promise(t=>{setTimeout(t,e)});var Pi=class extends ki{constructor(){super(...arguments);this.name="ClientError"}},Fy=class extends ki{constructor(){super(...arguments);this.name="ServerError"}},Dy=new Map;function l_(e){return P(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(H.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var io=class io{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let s={isAborted:!1,reject:o},i=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",b=n,{useCache:u=!1,abortLatest:c=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:m=!0,retryOnError:v=R=>R instanceof TypeError,retryOnResponse:y=R=>R.status>=500,version:p=null}=b,g=ne(b,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(Dy.has(i)){r(Dy.get(i));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h=I(T({credentials:"include"},g),{headers:T({Accept:"application/json","Content-Type":"application/json"},g.headers)});!l&&this.csrfToken&&(h.headers=I(T({},h.headers),{"X-CSRFToken":this.csrfToken})),typeof p=="string"&&(h.headers=I(T({},h.headers),{"X-Deepdesk-API-Version":p}));let S=f,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let k=()=>P(this,null,function*(){return S--,a(i,h).then(R=>P(this,null,function*(){return y(R)&&!s.isAborted&&S>0?(yield _y(d),k()):R.status===401&&m===!0&&x===!1?(x=!0,yield this.refreshToken(),k()):R})).catch(R=>P(this,null,function*(){if(v(R)&&!s.isAborted&&S>0)return yield _y(d),k();throw R}))});k().then(R=>P(this,null,function*(){let N=yield l_(R);if(delete this.latestRequestByUrl[i],R.status>=500){o(new Fy("Server Error",N));return}else if(R.status===401){o(new Pi("Unauthorized",N));return}else if(R.status===403){o(new Pi("Forbidden",N));return}else if(R.status===404){o(new Pi("Not Found",N));return}else if(R.status>=400){o(new Pi("Bad Request",N));return}u&&Dy.set(i,N),r(N)})).catch(R=>{o(R)})})}validateToken(){return P(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)try{yield this.refreshToken()}catch(r){return!1}let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/");return!!n})}refreshToken(){return io.refreshingToken||(io.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{io.refreshingToken=null},1e3*60)})),io.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,T({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,T({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,T({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,T({method:"DELETE"},n))}};io.refreshingToken=null;var yr=io;var sk;(t=>{let e;(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"))(e=t.EventType||(t.EventType={}))})(sk||(sk={}));function If(e){return I(T({},ie(e)),{tags:e.tags})}var es=class es{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new yr(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,s)=>P(this,null,function*(){let i=yield r(o,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return P(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(es.exchangeTokenPromise||(es.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),es.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return P(this,null,function*(){yield this.preflight(),H.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",I(T({},Le(t)),{tags:t.tags}),{version:"v2"});return If(n)})}getMe(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return ie(t)})}postIdentity(t){return P(this,null,function*(){yield this.client.post("/apis/admin/session/me/identities/",Le(t))})}patchMe(t){return P(this,null,function*(){let n=yield this.client.patch("/apis/admin/session/me/",Le(t));return ie(n)})}getProfile(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return ie(n)})}getKnowledgeAssistant(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return ie(n)})}getContentTypes(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return ie(t)})}getAccount(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return ie(t)})}getPlatformConfig(t){return P(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return ie(r)})}checkUserExists(t){return P(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationBySessionId(r){return P(this,arguments,function*(t,n={}){yield this.preflight(),H.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return H.info(`Successfully retrieved conversation ${i.id} for session ${t}`),If(i)})}isConversationSupported(r){return P(this,arguments,function*(t,n={}){H.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return P(this,null,function*(){let r=Le(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return If(o)})}postMessages(t,n){return P(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>I(T({},Le(o)),{tags:o.tags})),{version:"v2"})).map(o=>If(o))})}sendEvent(t,n){return P(this,null,function*(){let i=n,{data:r}=i,o=ne(i,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>I(T({},a),{[l]:u}),{});return this.client.post("/api/events",Le(I(T(T({},s),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return P(this,null,function*(){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[s,i])=>I(T({},o),{[s]:i}),{});return this.client.post("/api/events",{event:t,data:Le(T(T({},n),r))},{version:"v1"})})}getEntities(t){return P(this,null,function*(){return(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)},{version:"v1"})).entities})}getTemporaryExchangeToken(){return P(this,null,function*(){return(yield this.client.get("/auth/exchange-token")).jwt})}exchangeTokenForAccessCookie(t){return P(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw H.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return P(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Le(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return P(this,arguments,function*(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(yield this.client.post(`/api/conversations/${t}/recommend/${r}`,Le(n),{abortLatest:!0,version:"v1"})).map(i=>I(T({},ie(i)),{text:i.text||i.url||i.message,source:r,type:r})).filter((i,a,l)=>a===l.findIndex(u=>u.text===i.text))})}isLoggedIn(){return P(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return P(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/autocomplete`,Le(n),{abortLatest:!0,version:"v1"})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,s,i)=>s===i.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return P(this,null,function*(){let n=yield this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0,version:"v1"});return ie(n).map(r=>I(T({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return P(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",Le(t),{abortLatest:!0,version:"v1"});return ie(n)})}search(t){return P(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,Le(t),{version:"v2"});return ie(n)})}knowledgeAssist(s,i,a){return P(this,arguments,function*(t,n,r,o={}){let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Le({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(u=>({question:u.question,answer:u.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return ie(l)})}requestLoginByEmail(t){return P(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return ie(n)})}requestPasswordlessToken(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return ie(t.token)})}getCsrfToken(){return P(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return P(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return ie(n)})}evaluateRule(s,i,a){return P(this,arguments,function*(t,n,r,o={}){let l=new URLSearchParams;o.raiseForFailingConditions&&l.set("raise_for_failing_conditions","true");let u=yield this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${l.toString()}`,r,{version:"v2"});return u?ie(u.cues):[]})}getSummary(r){return P(this,arguments,function*(t,n={}){let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(s=>s.text&&s.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return ie(o)})}evaluateAssistant(t,n){return P(this,null,function*(){var i;let r=new URLSearchParams,{expectFormat:o="text"}=n||{};o.startsWith("json-schema:")?r.append("expect_response_format_schema",o.replace("json-schema:","")):r.append("expect_response_format",o),n!=null&&n.conversationId&&r.append("conversation_id",n.conversationId);let s=yield this.client.post(`/api/v2/assistants/${t}/evaluate?${r.toString()}`,{input:(i=n==null?void 0:n.input)!=null?i:{},conversation:n==null?void 0:n.transcript});return ie(s.output)})}getRules(){return P(this,null,function*(){let t=new URLSearchParams,n=yield this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{useCache:!0});return ie(n)})}translateMessages(t){return P(this,null,function*(){let n=yield this.client.post("/api/translate",Le(t),{version:"v2"});return ie(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(r0);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&H.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};es.exchangeTokenPromise=null;var vr=es;var _l=class{constructor(t,n){this.url=t;this.eventListeners={};this.options=T({timeout:25e3},n)}proxyEvent(t){this.eventSource.addEventListener(My(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,ie(o))}catch(o){H.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var ik;(t=>{let e;(s=>(s.Started="Started",s.Aborted="Aborted",s.Completed="Completed"))(e=t.AutoflowSessionState||(t.AutoflowSessionState={}))})(ik||(ik={}));var Dl=class{constructor(t,n={}){this.apiUrl=t;this.streams={};this.logger=H;this.client=new yr(t,n)}getCustomMessages(t){return P(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/suggestions`);return ie(n.suggestions)})}sendCustomMessage(t,n){return P(this,null,function*(){let r=yield this.client.post(`/sessions/${t}/messages`,Le(n));return ie(r)})}answerCustomMessage(t,n){return P(this,null,function*(){yield this.client.post(`/sessions/${t}/answers`,Le(n))})}getAutoflows(t){return P(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/autoflows`);return ie(n.autoflows)})}startAutoflowSession(t){return P(this,null,function*(){let n=yield this.client.post("/autoflow-sessions",Le(t));return ie(n)})}stopAutoflowSession(t){return P(this,null,function*(){yield this.client.delete(`/autoflow-sessions/${t}`)})}openStream(t){return this.streams[t]||(this.streams[t]=new _l(`${this.apiUrl}/sessions/${t}/events`),this.streams[t].connect()),this.streams[t]}closeStream(t){this.streams[t]||(this.streams[t].disconnect(),delete this.streams[t])}};var ak={startTime:null,stopTime:null},lk=ee({name:"handlingTime",initialState:ak,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(fe,()=>ak)}}),{handlingTimeStart:uk,handlingTimeStop:Of,handlingTimeReset:ck}=lk.actions,dk=lk.reducer;var fk=(e={})=>{let t=T({onAuthError:ni(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Nf={list:{keywordMatches:[]},fetchState:"idle"};var ts=B("styleSuggestions/getAll",(n,r)=>P(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,s=t.getState(),{showStyleSuggestions:i}=s.settings,a=(l=s.conversation.current)==null?void 0:l.profileCode;if(!i)return Nf.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),u_=ee({name:"styleSuggestions",initialState:Nf,reducers:{},extraReducers:e=>{e.addCase(ts.pending,t=>{t.fetchState="loading"}).addCase(ts.rejected,t=>{t.fetchState="error"}).addCase(ts.fulfilled,(t,n)=>{t.fetchState="done",$r(t.list,n.payload)||(t.list=n.payload)}).addCase(Io,t=>{t.list=Nf.list}).addCase(fe,()=>Nf)}}),pk=u_.reducer;var mk=(e={})=>{let t,n=!0,r=T({getStyleSuggestions:ts,debounce:500},e);return o=>s=>i=>{var m;let a=o.getState().input.text,l=s(i),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((m=u.conversation.current)==null?void 0:m.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function c_(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var gk=(e={})=>{let t=T({getTextSuggestions:hn,getAutocompleteSuggestions:gl,debounce:200,check:On},e),n;return r=>o=>s=>{var y;let{input:i}=r.getState(),a=o(s),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,f=(y=l.conversation.current)==null?void 0:y.id,d=s.type===qd.toString();if(!f||!u&&!c)return a;let{input:m}=l;return c_(m,i)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let p=si(l);p===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(p))},d?0:t.debounce)),a}};var hk=ts.fulfilled.toString();function d_(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let s=e.keywordMatches.filter(l=>l.keyword===o),i=t.keywordMatches.filter(l=>l.keyword===o),a=i.length-s.length;a<=0||r.push(...i.slice(0,a))}),r}var yk=e=>t=>n=>r=>{var u;if(r.type!==hk){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let s=t.getState(),i=s.styleSuggestions.list,a=(u=s.conversation)==null?void 0:u.current;if(o===i)return;let l=d_(o,i);r.type===hk&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var f_=kc({assistants:ab,answer:xb,auth:b1,autoflows:zC,conversation:N1,contentTypes:LE,customMessages:YC,passwordlessToken:ZC,entities:tb,knowledgeAssistant:vb,handlingTime:dk,info:Z1,input:W1,settings:h1,profile:mb,search:sE,styleSuggestions:pk,ui:Zb,rules:rT,textSuggestions:Ib});function vk(e){return Ex({reducer:f_,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),fk(),gk({debounce:200}),mk({debounce:500}),yk(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var p_=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},m_=e=>t=>n=>r=>{var a,l,u,c,f,d,m;let o=t.getState(),s=Zg("inlineSuggestions")(o);switch(r.type){case ni.toString():{!r.payload&&e.emit("logout",void 0);break}case gn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case ct.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Io.toString():e.logSendMessage(r.payload);break;case Yo.fulfilled.toString():r.isBroadcasted||e.broadcast(ih,r,!1),(c=r.payload.options)!=null&&c.shouldEmit&&e.emit("cues",r.payload.cues);break;case Vd.toString():e.emit("call-to-action",{cue:r.payload});break;case Jr.fulfilled.toString():r.isBroadcasted||e.broadcast(ah,r,!1);break;default:break}let i=n(r);switch(r.type){case Io.toString():e.handleAfterSendMessage(r.payload);break;case yl.toString():e.onUpdateShowTabHint(r.payload);break;case Of.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case ad.toString():{let{start:v,end:y}=o.input.selection;e.emit("replace",I(T({},r.payload),{replace:r.payload.replace==="selection"?{start:v,end:y}:{start:0,end:y}}));break}case un.toString():{let{start:v,end:y}=o.input.selection;e.emit("select-suggestion",I(T({type:p_(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:v,end:y}:{start:0,end:y}})),s&&t.dispatch(Gr([]));break}case ld.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Gr.toString():{s&&r.payload.length>0&&t.dispatch(ud(0));break}case fi.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(d=o.conversation.current)==null?void 0:d.id,data:{summary:r.payload,assistant:(m=t.getState().profile.data)==null?void 0:m.summarizerAssistantNew}});break}default:break}return i},Sk=m_;function Hy(e){return e.toISOString().replace("T"," ").replace("Z","")}function wk(e,t){var s,i,a,l;let n=(s=e.conversation.current)==null?void 0:s.id;if(!n)return H.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:o}=e.handlingTime;return!r||!o?(H.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:n,clientVersion:t.version,agentId:(i=e.info.agentInfo)==null?void 0:i.agentId,agentName:(a=e.info.agentInfo)==null?void 0:a.agentName,agentEmail:(l=e.info.agentInfo)==null?void 0:l.agentEmail,timeStart:Hy(r),timeStop:Hy(o)}}function xk(e,t,n){var N,_,Q,V;let r=(N=t.conversation.current)==null?void 0:N.id;if(!r)return H.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:s,numCharsPasted:i,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:f,pastes:d,cuts:m,deletions:v,textSuggestions:y,offeredTextSuggestions:p}}=t[e],g=o.length,S=y.reduce((W,{text:me,searchTerm:Ge})=>W+me.length-(Ge?Ge.length:0),0),x=c!=null?c:Date.now(),k=(Date.now()-x)/1e3+(f||0),b=s/k,R=y.reduce((W,{searchTerm:me})=>W+(me?me.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:m,deletions:v,lenTextTyped:s+R,lenTextTotal:g,lenTextAssisted:S,lenTextPasted:i,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:k,charsPerSecond:b,numPastes:u,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:p.filter(W=>W.source==="gpt").length}],agentId:(_=t.info.agentInfo)==null?void 0:_.agentId,agentName:(Q=t.info.agentInfo)==null?void 0:Q.agentName,agentEmail:(V=t.info.agentInfo)==null?void 0:V.agentEmail}}function Uy(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Uy(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?Uy(o,t):null}function Ek(e,t){return Uy(e,t)}function bk(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function g_(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Mf(e){return g_(e)&&(Go(e)||of(e))}var Tk,_n=new Map,h_=["bottom","height","left","right","top","width"],Ck=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:h_.some(n=>e[n]!==t[n]);function kk(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...kk(t)]:[]}function Pk(e,t){return!e||!t?null:I(T({},e),{top:e.top+t.top,left:e.left+t.left})}var _f=!1,Rk=()=>{_f=!0;let e=[];if(_n.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),_n.delete(n);return}let r=n.getBoundingClientRect();Ck(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(Pk,t.rect):t.rect;Ck(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),_n.size===0){_f=!1;return}Tk=window.requestAnimationFrame(Rk)};function zy(e,t){let n=kk(e),r=[],o=n.map((s,i)=>zy(s,a=>{r[i]=a;let l=_n.get(e);if(!l)return;let u=r.reduce(Pk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),_n.has(e)){let i=_n.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else _n.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!_f&&Rk()},unobserve(){o.forEach(i=>i.unobserve());let s=_n.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||_n.delete(e),_n.size||(cancelAnimationFrame(Tk),_f=!1)}}}}var Ak,Dn=new Map,Lk=()=>{Dn.forEach((e,t)=>{if(!t.isConnected){Dn.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(s=>s(e.visible)))}),Dn.size!==0&&(Ak=window.requestAnimationFrame(Lk))};function Ik(e,t){return{observe(){let n=Dn.size===0;Dn.has(e)?Dn.get(e).callbacks.push(t):Dn.set(e,{visible:void 0,callbacks:[t]}),n&&Lk()},unobserve(){let n=Dn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Dn.delete(e),Dn.size||cancelAnimationFrame(Ak)}}}}var jy=["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 By(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Ri(e){return parseFloat(e)}function Df(e){return Math.round(e*1e6)}function Ok(e){return e/1e6}function Vy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Ri(e.width),s=Ri(e.borderLeftWidth),i=Ri(e.borderRightWidth),a=Ri(e.paddingRight),l=Ok(Df(o)-Df(s)-Df(i)),u=Ok(Df(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function Fl(e,t={}){var c,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Wo(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};By(r,n,jy),Vy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=Ik(e,()=>{By(r,n,jy),Vy(r,e,n),s(),setTimeout(s,0)}),a,l=!0,u=zy(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(By(r,n,jy),Vy(r,e,n),s(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let m=t.closestScrollElement.getBoundingClientRect(),v=window.getComputedStyle(t.closestScrollElement),y=Ri(v.borderTopWidth),p=Ri(v.borderBottomWidth),g=m.top+y-d.top,h=d.top+d.height+-(m.top+m.height-p);n.style.clipPath=`inset(${g}px 0px ${h}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),u.observe(),i.observe(),[n,()=>{e.removeEventListener("scroll",s),u.unobserve(),i.unobserve()}]}var Nk=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){H.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function y_(e){return e.offsetParent!==null}function Mk(e){if(!y_(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function Ff(e,t,n=100){let r=Mk(e);t({isVisible:r});let o=setInterval(()=>{let s=Mk(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var De=w(C());var _k=Nk("showTabHint",!0),Ai=class Ai{constructor({deepdeskUrl:t,brokerUrl:n,version:r=Ai.version||"unknown",locale:o="en-US",token:s,fetch:i,productName:a,createCustomChannel:l}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let u=t.replace(/\/api$/,"");this.deepdeskApi=new vr(u,{token:s,fetch:i}),this.version=r,this.instanceId=Ai.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Sk({broadcast:(f,d,m)=>{this.broadcastEvents.send(f,d,m)},emit:(f,d)=>this.emit(f,d),handleAfterSendMessage:f=>this.handleAfterSendMessage(f),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:f=>this.logSendMessage(f),onUpdateShowTabHint:f=>_k.update(f),sendEvent:(f,d)=>this.deepdeskApi.sendEvent(f,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Dl(n)}),this.store=vk(c),this.broadcastEvents=new ok({debug:!0,deepdeskUrl:u,eventMap:iE(this.store),createCustomChannel:l}),this.store.dispatch(yl(_k.value())),this.store.dispatch(td({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(H.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(H.warn("Profile has not been loaded (yet)"),!0):(H.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(ni(null)),this.store.dispatch(Zn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();ut(r)&&y1(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return P(this,null,function*(){return(yield this.store.dispatch(Zn())).payload})}isConversationSupported(t,n){return P(this,null,function*(){return(yield this.store.dispatch(th({sessionId:t,options:n}))).payload})}createConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(rd(t))).payload})}getConversationBySessionId(t,n){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(od({sessionId:t,options:n}))).payload})}upsertConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(nh(t))).payload})}postMessages(t){return P(this,null,function*(){return(yield this.store.dispatch(id(t))).payload})}updateConversation(t){return P(this,null,function*(){return(yield this.store.dispatch(sd(t))).payload})}resetConversation(){this.store.dispatch(fe()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(td(t))}setVisitorInfo(t){this.store.dispatch(Y1(t))}setCustomData(t){this.store.dispatch(Q1(t))}setAgentInfo(t){return P(this,null,function*(){yield this.store.dispatch(Wa(t))})}setAgentSettings(t){return P(this,null,function*(){yield this.store.dispatch(oh(t))})}getAgentSettings(){return P(this,null,function*(){return(yield this.store.dispatch(sh())).payload})}refresh(){return P(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(cd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(qd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(un(t))}evaluateRule(o){return P(this,arguments,function*(t,n={},r=JC){return(yield this.store.dispatch(Yo({label:t,params:n,options:r}))).payload.cues})}evaluateAssistant(t,n){return P(this,null,function*(){let c=n||{},{input:r={},transcript:o,showCuesInWidget:s=!0,includeTags:i,expectFormat:a}=c,l=ne(c,["input","transcript","showCuesInWidget","includeTags","expectFormat"]);Object.assign(r,l);let u=yield this.store.dispatch(Jr({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeTags:i,input:r,skipState:!s}));if(u.error)throw new Error(u.error.message);return u.payload})}evaluateConversationAssistant(t,n){return P(this,null,function*(){yield this.loadProfileConfig();let r={accepted:"conversationAcceptedAssistant","new-message":"conversationNewMessageAssistant",ended:"conversationEndedAssistant"},o=this.state.profile.data[r[t]];if(!o){H.warn(`No assistant set in profile for conversation event "${t}"`);return}yield this.evaluateAssistant(o,T({transcript:"stored-transcript",includeTags:!0},n))})}getSummary(){return P(this,null,function*(){var n;if(!this.hasConversation())return H.warn("No conversation to create summary for."),null;(n=this.state.profile.data)!=null&&n.summarizerAssistantNew||H.warn("No profile loaded yet, or no summarizer assistant set in profile");let t=yield this.store.dispatch(fi({}));if(t.error)throw new Error(t.error.message);return t.payload})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.state.settings,u=a?"below":"above",c=o.length>0;if(!On(this.state)||(this.store.dispatch(H1(rh(t))),t.key!=="Tab"&&!l))return;let f=()=>{n||!c||i&&(t.shiftKey||(this.store.dispatch(j1()),t.preventDefault()))},d=()=>{n||!c||a&&s<=0||i&&(t.shiftKey||(this.store.dispatch(B1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():f();break;case"ArrowDown":{u==="below"?f():d();break}case"Escape":{n||(this.store.dispatch(ud(-1)),this.store.dispatch(to({collapse:!0})),this.store.dispatch(Qb(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let m=ii(this.state);if(!m)return;this.store.dispatch(yl(!1)),this.store.dispatch(un({text:m.text,suggestion:m,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.state.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let m=ii(this.state);if(!m)return;this.store.dispatch(un({text:m.text,suggestion:m,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.state.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let m=ii(this.state);if(!m)return;this.store.dispatch(un({text:m.text,suggestion:m,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(to({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Gr([]))}handlingTimeStart(){this.state.handlingTime.startTime||(H.info("Start handling time"),this.store.dispatch(uk()))}handlingTimeStop(){this.state.handlingTime.startTime&&(H.info("Stop handling time"),this.store.dispatch(Of()))}logSendMessage(t){let n=xk("input",this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n))}logHandlingTime(){let t=wk(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(ck()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Io((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(K1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(s){H.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),H.error(s)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}setPlatformVariables(t){this.store.dispatch(X1(t))}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[s,i]=Fl(n,r);return s.setAttribute("translate","no"),s.dataset.testid=t,o&&s.classList.add(o),this.unmountHandlers.push(()=>{(0,rn.unmountComponentAtNode)(s),i(),s.remove()}),s}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let s=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[l,u]=Fl(s,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{(0,rn.unmountComponentAtNode)(o),u()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Wo(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,rn.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),H.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(H.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(V1(r.metrics))):H.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Mf(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:s,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:f,detectSubmit:d,insertLink:m,inputMediator:v,closestScrollSelector:y,appendOverlayTo:p,inlineSuggestions:g,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:i,insertLink:m,isEmbedded:f,inlineSuggestions:g,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Wo(t),this.inputMediator=v||(Go(t)?new Jo(t):new Zo(t)),this.inputMediator.on("change",({plainText:k,rawHTML:b})=>{this.store.dispatch(cd({text:k,html:b}))}),this.inputMediator.on("keyup",k=>{this.store.dispatch(U1(rh(k)))}),this.inputMediator.on("keydown",k=>{this.handleKeyDown(k)}),this.inputMediator.on("paste",({pastedText:k,selectionText:b})=>{this.store.dispatch(z1({text:k,selectionText:b}))}),this.inputMediator.on("cut",({selectionText:k})=>{this.store.dispatch(F1(k))});let S;this.inputMediator.on("selection",k=>{clearTimeout(S),k===null?S=setTimeout(()=>{k!==null&&this.store.dispatch(dd(k))},500):this.store.dispatch(dd(k))}),this.inputMediator.on("disabled",()=>{var k;(k=this.inputMediator)==null||k.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(Zd(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Zd(!0))});let x=y&&Ek(t,y)||void 0;if(g){let{customStyles:k,appendOverlayTo:b}=n,R=this.createInlineContainer(t,"deepdesk-caret");(0,rn.render)((0,De.jsx)(qo,{store:this.store,customStyles:k,children:(0,De.jsx)(No,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(oC,{})})}),R),this.inputMediator.on("caretposition",_=>{_?(R.style.display="block",R.style.top=`${_.top}px`,R.style.left=`${_.left}px`):R.style.display="none"});let N=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:b},k==null?void 0:k.floatingMenuRootNode);(0,rn.render)((0,De.jsx)(qo,{store:this.store,customStyles:k,children:(0,De.jsx)(No,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(qb,{onLogIn:()=>this.loginViaPopup().catch(_=>H.warn(_.message))})})}),N)}else{let k=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:p,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),b=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:p},r==null?void 0:r.suggestionsRootNode);(0,rn.render)((0,De.jsx)(qo,{store:this.store,customStyles:r,children:(0,De.jsx)(No,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(MC,{inputElement:t})})}),k),(0,rn.render)((0,De.jsx)(qo,{store:this.store,customStyles:r,children:(0,De.jsx)(No,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(pC,{onLogIn:()=>this.loginViaPopup().catch(R=>H.warn(R.message))})})}),b)}(0,rn.render)((0,De.jsx)(qo,{store:this.store,customStyles:r,children:(0,De.jsx)(No,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(Bb,{})})}),this.createContainer("deepdesk-overlays")),this.store.dispatch(cd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(dd(this.inputMediator.getSelection())),this.store.dispatch(Zd(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var k;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((k=this.state.conversation.current)==null?void 0:k.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&H.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:s}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:s}),(0,rn.render)((0,De.jsx)(qo,{store:this.store,customStyles:r,children:(0,De.jsx)(No,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(ZT,{onLogIn:()=>this.loginViaPopup().catch(i=>H.warn(i.message))})})}),t),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&(0,rn.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Ff(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){bk(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>P(this,null,function*(){yield this.store.dispatch(cl());let t=ir(this.state);t&&(yield this.store.dispatch(fl()),this.store.dispatch(td({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew||t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))})),this.loadProfileConfigPromise)}loginViaPopup(t){return P(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,s=o.port1,i=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",f),clearInterval(d)};s.onmessage=m=>P(this,null,function*(){var v,y;if((v=m.data)!=null&&v.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((y=m.data)==null?void 0:y.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(qa),l=!0,o.port1.close(),n()}catch(p){console.error(p),r(p)}finally{l=!0,u()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let f=m=>P(this,null,function*(){var v;if(m.origin===a.origin)switch((v=m.data)==null?void 0:v.type){case"deepdesk-popup-loaded":{try{let y=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(y,a.origin,[o.port2])}catch(y){H.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-error":{u(),m.data.message==="Timeout"&&H.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(m.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}checkForTrialMode(t){return P(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(H.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;H.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return P(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Wd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(gn()):iu.includes(r)||this.store.dispatch(hn(r))})}catch(r){this.handleError(r)}})}};Ai.version="14.2.1-beta.3",Ai.count=0;var Hl=Ai;function v_(e){return P(this,null,function*(){var o,s,i;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(i=(s=e.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function Dk(e,t){return P(this,null,function*(){let n=yield v_(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}})}function Fk(e,t,n){return P(this,null,function*(){yield new vr(e).authenticateWithKey(t,n)})}function Hk(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function Uk(r,o){return P(this,arguments,function*(e,t,n={}){var f,d;let{value:s}=e,{start:i,end:a}=(f=n.replace)!=null?f:{start:0,end:s.length},l=`${s.slice(0,i)}${t}${s.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:i+t.length,end:i+t.length},c=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(c()).then(()=>{e.selectionStart=u.start,e.selectionEnd=u.end,e.blur(),e.focus()})})}function zk(r,o){return P(this,arguments,function*(e,t,n={}){let s=n.replace?so(e,n.replace.start,n.replace.end):Ti(e),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?t.split(`
|
|
27
|
+
`);let v=d?r:0,y=m?Math.min(s,c.childNodes.length):c.childNodes.length;for(let p=v;p<y&&(u(c.childNodes[p]),a!==2);p++);break}default:break}m&&(a=2)}return u(e),l}var ek=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(ek||{}),hr=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let s=this.getCaretPosition();$r(s,this.cachedCaretPosition)||(this.cachedCaretPosition=s,this.emit("caretposition",s))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(ek).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function tk(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Zo=class extends hr{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Ml(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(i=r.getComposedRanges(n))==null?void 0:i[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let s=this.element.ownerDocument.createRange();return s.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),s.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!tk(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!tk(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return Nl(this.element,n);let r=this.lastKnownSelection;if(r&&JT(this.element,r.start,r.end))return r;let o=Ti(this.element);return o.collapse(!1),Nl(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Ml(this.element,so(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var s_=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function nk(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,s=window.getComputedStyle(e),i=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",s_.forEach(function(c){o[c]=s[c]}),n?e.scrollHeight>parseInt(s.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),i.appendChild(r);let l=e.getBoundingClientRect(),u={top:l.top-e.scrollTop+a.offsetTop+parseInt(s.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+parseInt(s.borderLeftWidth)};return i.removeChild(r),u}var Jo=class extends hr{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return nk(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function rk(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let s=document.createElement("iframe"),i=new URL(t);return Object.entries(n).forEach(([a,l])=>{i.searchParams.append(a,l)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=r,s.title=`iframe-${e}`,s.src=i.toString(),window.document.body.appendChild(s),s}function i_(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var Iy=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Oy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=rk(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},Ny=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),H.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Oy(t,this.deepdeskUrl,{debug:!0}):new Iy(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=i_(o.data);typeof s!="object"||s.type!=="event"||s.channel!==t||(H.info("Received broadcast event",this.sessionId,o),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(r),n}send(t,n,r){var i,a;H.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(i=this.eventMap)[t])==null||a.call(i,n));let s=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(I(T({},o),{channel:this.sessionId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},ok=Ny;function a_(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function ie(e){return Array.isArray(e)?e.map(ie):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(T({},t),{[a_(n)]:ie(e[n])}),{}):e}function My(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Le(e){return Array.isArray(e)?e.map(Le):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(T({},t),{[My(n)]:Le(e[n])}),{}):e}var ki=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var _y=e=>new Promise(t=>{setTimeout(t,e)});var Pi=class extends ki{constructor(){super(...arguments);this.name="ClientError"}},Fy=class extends ki{constructor(){super(...arguments);this.name="ServerError"}},Dy=new Map;function l_(e){return P(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(H.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var io=class io{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let s={isAborted:!1,reject:o},i=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",b=n,{useCache:u=!1,abortLatest:c=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:m=!0,retryOnError:v=R=>R instanceof TypeError,retryOnResponse:y=R=>R.status>=500,version:p=null}=b,g=ne(b,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(Dy.has(i)){r(Dy.get(i));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h=I(T({credentials:"include"},g),{headers:T({Accept:"application/json","Content-Type":"application/json"},g.headers)});!l&&this.csrfToken&&(h.headers=I(T({},h.headers),{"X-CSRFToken":this.csrfToken})),typeof p=="string"&&(h.headers=I(T({},h.headers),{"X-Deepdesk-API-Version":p}));let S=f,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let k=()=>P(this,null,function*(){return S--,a(i,h).then(R=>P(this,null,function*(){return y(R)&&!s.isAborted&&S>0?(yield _y(d),k()):R.status===401&&m===!0&&x===!1?(x=!0,yield this.refreshToken(),k()):R})).catch(R=>P(this,null,function*(){if(v(R)&&!s.isAborted&&S>0)return yield _y(d),k();throw R}))});k().then(R=>P(this,null,function*(){let N=yield l_(R);if(delete this.latestRequestByUrl[i],R.status>=500){o(new Fy("Server Error",N));return}else if(R.status===401){o(new Pi("Unauthorized",N));return}else if(R.status===403){o(new Pi("Forbidden",N));return}else if(R.status===404){o(new Pi("Not Found",N));return}else if(R.status>=400){o(new Pi("Bad Request",N));return}u&&Dy.set(i,N),r(N)})).catch(R=>{o(R)})})}validateToken(){return P(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)try{yield this.refreshToken()}catch(r){return!1}let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/");return!!n})}refreshToken(){return io.refreshingToken||(io.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{io.refreshingToken=null},1e3*60)})),io.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,T({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,T({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,T({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,T({method:"DELETE"},n))}};io.refreshingToken=null;var yr=io;var sk;(t=>{let e;(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"))(e=t.EventType||(t.EventType={}))})(sk||(sk={}));function If(e){return I(T({},ie(e)),{tags:e.tags})}var es=class es{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new yr(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,s)=>P(this,null,function*(){let i=yield r(o,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return P(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(es.exchangeTokenPromise||(es.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),es.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return P(this,null,function*(){yield this.preflight(),H.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",I(T({},Le(t)),{tags:t.tags}),{version:"v2"});return If(n)})}getMe(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return ie(t)})}postIdentity(t){return P(this,null,function*(){yield this.client.post("/apis/admin/session/me/identities/",Le(t))})}patchMe(t){return P(this,null,function*(){let n=yield this.client.patch("/apis/admin/session/me/",Le(t));return ie(n)})}getProfile(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return ie(n)})}getKnowledgeAssistant(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return ie(n)})}getContentTypes(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return ie(t)})}getAccount(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return ie(t)})}getPlatformConfig(t){return P(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return ie(r)})}checkUserExists(t){return P(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationBySessionId(r){return P(this,arguments,function*(t,n={}){yield this.preflight(),H.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return H.info(`Successfully retrieved conversation ${i.id} for session ${t}`),If(i)})}isConversationSupported(r){return P(this,arguments,function*(t,n={}){H.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return P(this,null,function*(){let r=Le(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return If(o)})}postMessages(t,n){return P(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>I(T({},Le(o)),{tags:o.tags})),{version:"v2"})).map(o=>If(o))})}sendEvent(t,n){return P(this,null,function*(){let i=n,{data:r}=i,o=ne(i,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>I(T({},a),{[l]:u}),{});return this.client.post("/api/events",Le(I(T(T({},s),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return P(this,null,function*(){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[s,i])=>I(T({},o),{[s]:i}),{});return this.client.post("/api/events",{event:t,data:Le(T(T({},n),r))},{version:"v1"})})}getEntities(t){return P(this,null,function*(){return(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)},{version:"v1"})).entities})}getTemporaryExchangeToken(){return P(this,null,function*(){return(yield this.client.get("/auth/exchange-token")).jwt})}exchangeTokenForAccessCookie(t){return P(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw H.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return P(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Le(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return P(this,arguments,function*(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(yield this.client.post(`/api/conversations/${t}/recommend/${r}`,Le(n),{abortLatest:!0,version:"v1"})).map(i=>I(T({},ie(i)),{text:i.text||i.url||i.message,source:r,type:r})).filter((i,a,l)=>a===l.findIndex(u=>u.text===i.text))})}isLoggedIn(){return P(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return P(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/autocomplete`,Le(n),{abortLatest:!0,version:"v1"})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,s,i)=>s===i.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return P(this,null,function*(){let n=yield this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0,version:"v1"});return ie(n).map(r=>I(T({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return P(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",Le(t),{abortLatest:!0,version:"v1"});return ie(n)})}search(t){return P(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,Le(t),{version:"v2"});return ie(n)})}knowledgeAssist(s,i,a){return P(this,arguments,function*(t,n,r,o={}){let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Le({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(u=>({question:u.question,answer:u.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return ie(l)})}requestLoginByEmail(t){return P(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return ie(n)})}requestPasswordlessToken(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return ie(t.token)})}getCsrfToken(){return P(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return P(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return ie(n)})}evaluateRule(s,i,a){return P(this,arguments,function*(t,n,r,o={}){let l=new URLSearchParams;o.raiseForFailingConditions&&l.set("raise_for_failing_conditions","true");let u=yield this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${l.toString()}`,r,{version:"v2"});return u?ie(u.cues):[]})}getSummary(r){return P(this,arguments,function*(t,n={}){let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(s=>s.text&&s.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return ie(o)})}evaluateAssistant(t,n){return P(this,null,function*(){var i;let r=new URLSearchParams,{expectFormat:o="text"}=n||{};o.startsWith("json-schema:")?r.append("expect_response_format_schema",o.replace("json-schema:","")):r.append("expect_response_format",o),n!=null&&n.conversationId&&r.append("conversation_id",n.conversationId);let s=yield this.client.post(`/api/v2/assistants/${t}/evaluate?${r.toString()}`,{input:(i=n==null?void 0:n.input)!=null?i:{},conversation:n==null?void 0:n.transcript});return ie(s.output)})}getRules(){return P(this,null,function*(){let t=new URLSearchParams,n=yield this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{useCache:!0});return ie(n)})}translateMessages(t){return P(this,null,function*(){let n=yield this.client.post("/api/translate",Le(t),{version:"v2"});return ie(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(r0);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&H.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};es.exchangeTokenPromise=null;var vr=es;var _l=class{constructor(t,n){this.url=t;this.eventListeners={};this.options=T({timeout:25e3},n)}proxyEvent(t){this.eventSource.addEventListener(My(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,ie(o))}catch(o){H.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var ik;(t=>{let e;(s=>(s.Started="Started",s.Aborted="Aborted",s.Completed="Completed"))(e=t.AutoflowSessionState||(t.AutoflowSessionState={}))})(ik||(ik={}));var Dl=class{constructor(t,n={}){this.apiUrl=t;this.streams={};this.logger=H;this.client=new yr(t,n)}getCustomMessages(t){return P(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/suggestions`);return ie(n.suggestions)})}sendCustomMessage(t,n){return P(this,null,function*(){let r=yield this.client.post(`/sessions/${t}/messages`,Le(n));return ie(r)})}answerCustomMessage(t,n){return P(this,null,function*(){yield this.client.post(`/sessions/${t}/answers`,Le(n))})}getAutoflows(t){return P(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/autoflows`);return ie(n.autoflows)})}startAutoflowSession(t){return P(this,null,function*(){let n=yield this.client.post("/autoflow-sessions",Le(t));return ie(n)})}stopAutoflowSession(t){return P(this,null,function*(){yield this.client.delete(`/autoflow-sessions/${t}`)})}openStream(t){return this.streams[t]||(this.streams[t]=new _l(`${this.apiUrl}/sessions/${t}/events`),this.streams[t].connect()),this.streams[t]}closeStream(t){this.streams[t]||(this.streams[t].disconnect(),delete this.streams[t])}};var ak={startTime:null,stopTime:null},lk=ee({name:"handlingTime",initialState:ak,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(fe,()=>ak)}}),{handlingTimeStart:uk,handlingTimeStop:Of,handlingTimeReset:ck}=lk.actions,dk=lk.reducer;var fk=(e={})=>{let t=T({onAuthError:ni(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Nf={list:{keywordMatches:[]},fetchState:"idle"};var ts=B("styleSuggestions/getAll",(n,r)=>P(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,s=t.getState(),{showStyleSuggestions:i}=s.settings,a=(l=s.conversation.current)==null?void 0:l.profileCode;if(!i)return Nf.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),u_=ee({name:"styleSuggestions",initialState:Nf,reducers:{},extraReducers:e=>{e.addCase(ts.pending,t=>{t.fetchState="loading"}).addCase(ts.rejected,t=>{t.fetchState="error"}).addCase(ts.fulfilled,(t,n)=>{t.fetchState="done",$r(t.list,n.payload)||(t.list=n.payload)}).addCase(Io,t=>{t.list=Nf.list}).addCase(fe,()=>Nf)}}),pk=u_.reducer;var mk=(e={})=>{let t,n=!0,r=T({getStyleSuggestions:ts,debounce:500},e);return o=>s=>i=>{var m;let a=o.getState().input.text,l=s(i),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((m=u.conversation.current)==null?void 0:m.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function c_(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var gk=(e={})=>{let t=T({getTextSuggestions:hn,getAutocompleteSuggestions:gl,debounce:200,check:On},e),n;return r=>o=>s=>{var y;let{input:i}=r.getState(),a=o(s),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,f=(y=l.conversation.current)==null?void 0:y.id,d=s.type===qd.toString();if(!f||!u&&!c)return a;let{input:m}=l;return c_(m,i)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let p=si(l);p===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(p))},d?0:t.debounce)),a}};var hk=ts.fulfilled.toString();function d_(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let s=e.keywordMatches.filter(l=>l.keyword===o),i=t.keywordMatches.filter(l=>l.keyword===o),a=i.length-s.length;a<=0||r.push(...i.slice(0,a))}),r}var yk=e=>t=>n=>r=>{var u;if(r.type!==hk){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let s=t.getState(),i=s.styleSuggestions.list,a=(u=s.conversation)==null?void 0:u.current;if(o===i)return;let l=d_(o,i);r.type===hk&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var f_=kc({assistants:ab,answer:xb,auth:b1,autoflows:zC,conversation:N1,contentTypes:LE,customMessages:YC,passwordlessToken:ZC,entities:tb,knowledgeAssistant:vb,handlingTime:dk,info:Z1,input:W1,settings:h1,profile:mb,search:sE,styleSuggestions:pk,ui:Zb,rules:rT,textSuggestions:Ib});function vk(e){return Ex({reducer:f_,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),fk(),gk({debounce:200}),mk({debounce:500}),yk(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var p_=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},m_=e=>t=>n=>r=>{var a,l,u,c,f,d,m;let o=t.getState(),s=Zg("inlineSuggestions")(o);switch(r.type){case ni.toString():{!r.payload&&e.emit("logout",void 0);break}case gn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case ct.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Io.toString():e.logSendMessage(r.payload);break;case Yo.fulfilled.toString():r.isBroadcasted||e.broadcast(ih,r,!1),(c=r.payload.options)!=null&&c.shouldEmit&&e.emit("cues",r.payload.cues);break;case Vd.toString():e.emit("call-to-action",{cue:r.payload});break;case Jr.fulfilled.toString():r.isBroadcasted||e.broadcast(ah,r,!1);break;default:break}let i=n(r);switch(r.type){case Io.toString():e.handleAfterSendMessage(r.payload);break;case yl.toString():e.onUpdateShowTabHint(r.payload);break;case Of.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case ad.toString():{let{start:v,end:y}=o.input.selection;e.emit("replace",I(T({},r.payload),{replace:r.payload.replace==="selection"?{start:v,end:y}:{start:0,end:y}}));break}case un.toString():{let{start:v,end:y}=o.input.selection;e.emit("select-suggestion",I(T({type:p_(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:v,end:y}:{start:0,end:y}})),s&&t.dispatch(Gr([]));break}case ld.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Gr.toString():{s&&r.payload.length>0&&t.dispatch(ud(0));break}case fi.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(d=o.conversation.current)==null?void 0:d.id,data:{summary:r.payload,assistant:(m=t.getState().profile.data)==null?void 0:m.summarizerAssistantNew}});break}default:break}return i},Sk=m_;function Hy(e){return e.toISOString().replace("T"," ").replace("Z","")}function wk(e,t){var s,i,a,l;let n=(s=e.conversation.current)==null?void 0:s.id;if(!n)return H.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:o}=e.handlingTime;return!r||!o?(H.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:n,clientVersion:t.version,agentId:(i=e.info.agentInfo)==null?void 0:i.agentId,agentName:(a=e.info.agentInfo)==null?void 0:a.agentName,agentEmail:(l=e.info.agentInfo)==null?void 0:l.agentEmail,timeStart:Hy(r),timeStop:Hy(o)}}function xk(e,t,n){var N,_,Q,V;let r=(N=t.conversation.current)==null?void 0:N.id;if(!r)return H.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:s,numCharsPasted:i,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:f,pastes:d,cuts:m,deletions:v,textSuggestions:y,offeredTextSuggestions:p}}=t[e],g=o.length,S=y.reduce((W,{text:me,searchTerm:Ge})=>W+me.length-(Ge?Ge.length:0),0),x=c!=null?c:Date.now(),k=(Date.now()-x)/1e3+(f||0),b=s/k,R=y.reduce((W,{searchTerm:me})=>W+(me?me.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:m,deletions:v,lenTextTyped:s+R,lenTextTotal:g,lenTextAssisted:S,lenTextPasted:i,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:k,charsPerSecond:b,numPastes:u,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:p.filter(W=>W.source==="gpt").length}],agentId:(_=t.info.agentInfo)==null?void 0:_.agentId,agentName:(Q=t.info.agentInfo)==null?void 0:Q.agentName,agentEmail:(V=t.info.agentInfo)==null?void 0:V.agentEmail}}function Uy(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Uy(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?Uy(o,t):null}function Ek(e,t){return Uy(e,t)}function bk(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function g_(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Mf(e){return g_(e)&&(Go(e)||of(e))}var Tk,_n=new Map,h_=["bottom","height","left","right","top","width"],Ck=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:h_.some(n=>e[n]!==t[n]);function kk(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...kk(t)]:[]}function Pk(e,t){return!e||!t?null:I(T({},e),{top:e.top+t.top,left:e.left+t.left})}var _f=!1,Rk=()=>{_f=!0;let e=[];if(_n.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),_n.delete(n);return}let r=n.getBoundingClientRect();Ck(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(Pk,t.rect):t.rect;Ck(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),_n.size===0){_f=!1;return}Tk=window.requestAnimationFrame(Rk)};function zy(e,t){let n=kk(e),r=[],o=n.map((s,i)=>zy(s,a=>{r[i]=a;let l=_n.get(e);if(!l)return;let u=r.reduce(Pk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),_n.has(e)){let i=_n.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else _n.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!_f&&Rk()},unobserve(){o.forEach(i=>i.unobserve());let s=_n.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||_n.delete(e),_n.size||(cancelAnimationFrame(Tk),_f=!1)}}}}var Ak,Dn=new Map,Lk=()=>{Dn.forEach((e,t)=>{if(!t.isConnected){Dn.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(s=>s(e.visible)))}),Dn.size!==0&&(Ak=window.requestAnimationFrame(Lk))};function Ik(e,t){return{observe(){let n=Dn.size===0;Dn.has(e)?Dn.get(e).callbacks.push(t):Dn.set(e,{visible:void 0,callbacks:[t]}),n&&Lk()},unobserve(){let n=Dn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Dn.delete(e),Dn.size||cancelAnimationFrame(Ak)}}}}var jy=["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 By(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Ri(e){return parseFloat(e)}function Df(e){return Math.round(e*1e6)}function Ok(e){return e/1e6}function Vy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Ri(e.width),s=Ri(e.borderLeftWidth),i=Ri(e.borderRightWidth),a=Ri(e.paddingRight),l=Ok(Df(o)-Df(s)-Df(i)),u=Ok(Df(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function Fl(e,t={}){var c,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Wo(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};By(r,n,jy),Vy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=Ik(e,()=>{By(r,n,jy),Vy(r,e,n),s(),setTimeout(s,0)}),a,l=!0,u=zy(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(By(r,n,jy),Vy(r,e,n),s(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let m=t.closestScrollElement.getBoundingClientRect(),v=window.getComputedStyle(t.closestScrollElement),y=Ri(v.borderTopWidth),p=Ri(v.borderBottomWidth),g=m.top+y-d.top,h=d.top+d.height+-(m.top+m.height-p);n.style.clipPath=`inset(${g}px 0px ${h}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),u.observe(),i.observe(),[n,()=>{e.removeEventListener("scroll",s),u.unobserve(),i.unobserve()}]}var Nk=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){H.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function y_(e){return e.offsetParent!==null}function Mk(e){if(!y_(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function Ff(e,t,n=100){let r=Mk(e);t({isVisible:r});let o=setInterval(()=>{let s=Mk(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var De=w(C());var _k=Nk("showTabHint",!0),Ai=class Ai{constructor({deepdeskUrl:t,brokerUrl:n,version:r=Ai.version||"unknown",locale:o="en-US",token:s,fetch:i,productName:a,createCustomChannel:l}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let u=t.replace(/\/api$/,"");this.deepdeskApi=new vr(u,{token:s,fetch:i}),this.version=r,this.instanceId=Ai.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Sk({broadcast:(f,d,m)=>{this.broadcastEvents.send(f,d,m)},emit:(f,d)=>this.emit(f,d),handleAfterSendMessage:f=>this.handleAfterSendMessage(f),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:f=>this.logSendMessage(f),onUpdateShowTabHint:f=>_k.update(f),sendEvent:(f,d)=>this.deepdeskApi.sendEvent(f,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Dl(n)}),this.store=vk(c),this.broadcastEvents=new ok({debug:!0,deepdeskUrl:u,eventMap:iE(this.store),createCustomChannel:l}),this.store.dispatch(yl(_k.value())),this.store.dispatch(td({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(H.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(H.warn("Profile has not been loaded (yet)"),!0):(H.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(ni(null)),this.store.dispatch(Zn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();ut(r)&&y1(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return P(this,null,function*(){return(yield this.store.dispatch(Zn())).payload})}isConversationSupported(t,n){return P(this,null,function*(){return(yield this.store.dispatch(th({sessionId:t,options:n}))).payload})}createConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(rd(t))).payload})}getConversationBySessionId(t,n){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(od({sessionId:t,options:n}))).payload})}upsertConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(nh(t))).payload})}postMessages(t){return P(this,null,function*(){return(yield this.store.dispatch(id(t))).payload})}updateConversation(t){return P(this,null,function*(){return(yield this.store.dispatch(sd(t))).payload})}resetConversation(){this.store.dispatch(fe()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(td(t))}setVisitorInfo(t){this.store.dispatch(Y1(t))}setCustomData(t){this.store.dispatch(Q1(t))}setAgentInfo(t,n){return P(this,null,function*(){yield this.store.dispatch(Wa(T(T({},t),n)))})}setAgentSettings(t){return P(this,null,function*(){yield this.store.dispatch(oh(t))})}getAgentSettings(){return P(this,null,function*(){return(yield this.store.dispatch(sh())).payload})}refresh(){return P(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(cd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(qd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(un(t))}evaluateRule(o){return P(this,arguments,function*(t,n={},r=JC){return(yield this.store.dispatch(Yo({label:t,params:n,options:r}))).payload.cues})}evaluateAssistant(t,n){return P(this,null,function*(){let c=n||{},{input:r={},transcript:o,showCuesInWidget:s=!0,includeTags:i,expectFormat:a}=c,l=ne(c,["input","transcript","showCuesInWidget","includeTags","expectFormat"]);Object.assign(r,l);let u=yield this.store.dispatch(Jr({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeTags:i,input:r,skipState:!s}));if(u.error)throw new Error(u.error.message);return u.payload})}evaluateConversationAssistant(t,n){return P(this,null,function*(){yield this.loadProfileConfig();let r={accepted:"conversationAcceptedAssistant","new-message":"conversationNewMessageAssistant",ended:"conversationEndedAssistant"},o=this.state.profile.data[r[t]];if(!o){H.warn(`No assistant set in profile for conversation event "${t}"`);return}yield this.evaluateAssistant(o,T({transcript:"stored-transcript",includeTags:!0},n))})}getSummary(){return P(this,null,function*(){var n;if(!this.hasConversation())return H.warn("No conversation to create summary for."),null;(n=this.state.profile.data)!=null&&n.summarizerAssistantNew||H.warn("No profile loaded yet, or no summarizer assistant set in profile");let t=yield this.store.dispatch(fi({}));if(t.error)throw new Error(t.error.message);return t.payload})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.state.settings,u=a?"below":"above",c=o.length>0;if(!On(this.state)||(this.store.dispatch(H1(rh(t))),t.key!=="Tab"&&!l))return;let f=()=>{n||!c||i&&(t.shiftKey||(this.store.dispatch(j1()),t.preventDefault()))},d=()=>{n||!c||a&&s<=0||i&&(t.shiftKey||(this.store.dispatch(B1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():f();break;case"ArrowDown":{u==="below"?f():d();break}case"Escape":{n||(this.store.dispatch(ud(-1)),this.store.dispatch(to({collapse:!0})),this.store.dispatch(Qb(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let m=ii(this.state);if(!m)return;this.store.dispatch(yl(!1)),this.store.dispatch(un({text:m.text,suggestion:m,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.state.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let m=ii(this.state);if(!m)return;this.store.dispatch(un({text:m.text,suggestion:m,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.state.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let m=ii(this.state);if(!m)return;this.store.dispatch(un({text:m.text,suggestion:m,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(to({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Gr([]))}handlingTimeStart(){this.state.handlingTime.startTime||(H.info("Start handling time"),this.store.dispatch(uk()))}handlingTimeStop(){this.state.handlingTime.startTime&&(H.info("Stop handling time"),this.store.dispatch(Of()))}logSendMessage(t){let n=xk("input",this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n))}logHandlingTime(){let t=wk(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(ck()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Io((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(K1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(s){H.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),H.error(s)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}setPlatformVariables(t){this.store.dispatch(X1(t))}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[s,i]=Fl(n,r);return s.setAttribute("translate","no"),s.dataset.testid=t,o&&s.classList.add(o),this.unmountHandlers.push(()=>{(0,rn.unmountComponentAtNode)(s),i(),s.remove()}),s}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let s=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[l,u]=Fl(s,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{(0,rn.unmountComponentAtNode)(o),u()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Wo(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,rn.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),H.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(H.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(V1(r.metrics))):H.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Mf(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:s,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:f,detectSubmit:d,insertLink:m,inputMediator:v,closestScrollSelector:y,appendOverlayTo:p,inlineSuggestions:g,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:i,insertLink:m,isEmbedded:f,inlineSuggestions:g,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Wo(t),this.inputMediator=v||(Go(t)?new Jo(t):new Zo(t)),this.inputMediator.on("change",({plainText:k,rawHTML:b})=>{this.store.dispatch(cd({text:k,html:b}))}),this.inputMediator.on("keyup",k=>{this.store.dispatch(U1(rh(k)))}),this.inputMediator.on("keydown",k=>{this.handleKeyDown(k)}),this.inputMediator.on("paste",({pastedText:k,selectionText:b})=>{this.store.dispatch(z1({text:k,selectionText:b}))}),this.inputMediator.on("cut",({selectionText:k})=>{this.store.dispatch(F1(k))});let S;this.inputMediator.on("selection",k=>{clearTimeout(S),k===null?S=setTimeout(()=>{k!==null&&this.store.dispatch(dd(k))},500):this.store.dispatch(dd(k))}),this.inputMediator.on("disabled",()=>{var k;(k=this.inputMediator)==null||k.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(Zd(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Zd(!0))});let x=y&&Ek(t,y)||void 0;if(g){let{customStyles:k,appendOverlayTo:b}=n,R=this.createInlineContainer(t,"deepdesk-caret");(0,rn.render)((0,De.jsx)(qo,{store:this.store,customStyles:k,children:(0,De.jsx)(No,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(oC,{})})}),R),this.inputMediator.on("caretposition",_=>{_?(R.style.display="block",R.style.top=`${_.top}px`,R.style.left=`${_.left}px`):R.style.display="none"});let N=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:b},k==null?void 0:k.floatingMenuRootNode);(0,rn.render)((0,De.jsx)(qo,{store:this.store,customStyles:k,children:(0,De.jsx)(No,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(qb,{onLogIn:()=>this.loginViaPopup().catch(_=>H.warn(_.message))})})}),N)}else{let k=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:p,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),b=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:p},r==null?void 0:r.suggestionsRootNode);(0,rn.render)((0,De.jsx)(qo,{store:this.store,customStyles:r,children:(0,De.jsx)(No,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(MC,{inputElement:t})})}),k),(0,rn.render)((0,De.jsx)(qo,{store:this.store,customStyles:r,children:(0,De.jsx)(No,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(pC,{onLogIn:()=>this.loginViaPopup().catch(R=>H.warn(R.message))})})}),b)}(0,rn.render)((0,De.jsx)(qo,{store:this.store,customStyles:r,children:(0,De.jsx)(No,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(Bb,{})})}),this.createContainer("deepdesk-overlays")),this.store.dispatch(cd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(dd(this.inputMediator.getSelection())),this.store.dispatch(Zd(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var k;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((k=this.state.conversation.current)==null?void 0:k.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&H.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:s}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:s}),(0,rn.render)((0,De.jsx)(qo,{store:this.store,customStyles:r,children:(0,De.jsx)(No,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(ZT,{onLogIn:()=>this.loginViaPopup().catch(i=>H.warn(i.message))})})}),t),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&(0,rn.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Ff(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){bk(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>P(this,null,function*(){yield this.store.dispatch(cl());let t=ir(this.state);t&&(yield this.store.dispatch(fl()),this.store.dispatch(td({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew||t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))})),this.loadProfileConfigPromise)}loginViaPopup(t){return P(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,s=o.port1,i=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",f),clearInterval(d)};s.onmessage=m=>P(this,null,function*(){var v,y;if((v=m.data)!=null&&v.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((y=m.data)==null?void 0:y.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(qa),l=!0,o.port1.close(),n()}catch(p){console.error(p),r(p)}finally{l=!0,u()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let f=m=>P(this,null,function*(){var v;if(m.origin===a.origin)switch((v=m.data)==null?void 0:v.type){case"deepdesk-popup-loaded":{try{let y=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(y,a.origin,[o.port2])}catch(y){H.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-error":{u(),m.data.message==="Timeout"&&H.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(m.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}checkForTrialMode(t){return P(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(H.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;H.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return P(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Wd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(gn()):iu.includes(r)||this.store.dispatch(hn(r))})}catch(r){this.handleError(r)}})}};Ai.version="14.2.1-beta.4",Ai.count=0;var Hl=Ai;function v_(e){return P(this,null,function*(){var o,s,i;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(i=(s=e.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function Dk(e,t){return P(this,null,function*(){let n=yield v_(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}})}function Fk(e,t,n){return P(this,null,function*(){yield new vr(e).authenticateWithKey(t,n)})}function Hk(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function Uk(r,o){return P(this,arguments,function*(e,t,n={}){var f,d;let{value:s}=e,{start:i,end:a}=(f=n.replace)!=null?f:{start:0,end:s.length},l=`${s.slice(0,i)}${t}${s.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:i+t.length,end:i+t.length},c=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(c()).then(()=>{e.selectionStart=u.start,e.selectionEnd=u.end,e.blur(),e.focus()})})}function zk(r,o){return P(this,arguments,function*(e,t,n={}){let s=n.replace?so(e,n.replace.start,n.replace.end):Ti(e),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?t.split(`
|
|
28
28
|
`).reverse().forEach((l,u)=>{u>0&&s.insertNode(document.createElement("br")),s.insertNode(document.createTextNode(l))}):s.insertNode(document.createTextNode(t))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let l=n.selectionAfter?so(e,n.selectionAfter.start,n.selectionAfter.end):(s.collapse(!1),s),u=window.getSelection();u==null||u.removeAllRanges(),u==null||u.addRange(l)}if(!i)return;i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}function S_(e){let t=document.createElement("template");return t.innerHTML=e.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),t.content}function w_(e){let t=document.createDocumentFragment();return e.split(`
|
|
29
29
|
`).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},s=0;for(;o=n.slice(s).match(/(\[([^\]]+)])\(([^)]+)\)/);){let i=document.createElement("a");i.href=o[3],i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),i.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(s,s+o.index))),t.appendChild(i),s=s+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(s)))}),t}function jk(e,t){let n=e.parentElement;if(!n){console.warn("No insert point found");return}let{display:r}=window.getComputedStyle(n);r.includes("block")||r==="table-cell"?n==null||n.insertBefore(t,e.nextSibling):jk(n,t)}function Bk(o,s){return P(this,arguments,function*(e,t,{isBlock:n,isHTML:r}={}){let i;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let a=()=>{var d;let l=(d=e.ownerDocument.defaultView)!=null?d:window,u=l.getSelection();if((!u||u.rangeCount===0)&&(e.focus(),u=l.getSelection()),!u||u.rangeCount===0)return;let c=u.getRangeAt(0);if(!c)return;i=document.createElement("span"),c.insertNode(i);let f=r?S_(t):w_(t);n?jk(c.startContainer,f):(c.insertNode(f),c.collapse(!1))};return Promise.resolve(a()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!i)try{i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}return rP(x_);})();
|
|
30
30
|
/*! Bundled license information:
|