@deepdesk/deepdesk-sdk 11.6.1-beta.2 → 11.6.1-beta.3
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 +2 -0
- package/dist/index.d.ts +2 -0
- 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
|
${oo.current.stack}
|
|
12
12
|
|
|
13
|
-
`),it}Ki(()=>{oo.current=void 0,q.current=void 0,he.current=qt});let Gt=(0,ae.useMemo)(()=>ae.default.createElement(g,Bn({},qt,{ref:O})),[O,g,qt]);return(0,ae.useMemo)(()=>v?ae.default.createElement(W.Provider,{value:fr},Gt):Gt,[W,Gt,fr])}let b=ae.default.memo(w);if(b.WrappedComponent=g,b.displayName=w.displayName=h,l){let I=ae.default.forwardRef(function(M,W){return ae.default.createElement(b,Bn({},M,{reactReduxForwardedRef:W}))});return I.displayName=h,I.WrappedComponent=g,(0,Dg.default)(I,g)}return(0,Dg.default)(b,g)}}var jn=zL;var Aa=x(_());function BL({store:e,context:t,children:n,serverState:r,stabilityCheck:o="once",noopCheck:i="once"}){let s=(0,Aa.useMemo)(()=>{let u=jc(e);return{store:e,subscription:u,getServerState:r?()=>r:void 0,stabilityCheck:o,noopCheck:i}},[e,r,o,i]),a=(0,Aa.useMemo)(()=>e.getState(),[e]);Ki(()=>{let{subscription:u}=s;return u.onStateChange=u.notifyNestedSubs,u.trySubscribe(),a!==e.getState()&&u.notifyNestedSubs(),()=>{u.tryUnsubscribe(),u.onStateChange=void 0}},[s,a]);let l=t||Xe;return Aa.default.createElement(l.Provider,{value:s},n)}var Fg=BL;function Kc(e=Xe){let t=e===Xe?Sc:ka(e);return function(){let{store:r}=t();return r}}var Hg=Kc();function Gw(e=Xe){let t=e===Xe?Hg:Kc(e);return function(){return t().dispatch}}var $=Gw();Ew(Yw.useSyncExternalStoreWithSelector);qw(Xw.useSyncExternalStore);hw(kg.unstable_batchedUpdates);var La=(n=>(n.NL_NL="nl-NL",n.EN_US="en-US",n))(La||{});var jL={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"},Qw=G({name:"settings",initialState:jL,reducers:{set(e,t){Object.entries(t.payload).forEach(n=>{let[r,o]=n;typeof o>"u"||(e[r]=o)})}}}),{set:Wc}=Qw.actions,Ug=e=>t=>t.settings[e],z=e=>L(Ug(e)),Zw=Qw.reducer;var VL={isLoggedIn:!0,loginFetchState:"idle",verifyFetchState:"idle",showLoginOverlay:!1},Je=e=>e.auth.isLoggedIn,Jw=e=>e.auth.loginFetchState,e1=e=>e.auth.verifyFetchState,t1=e=>e.auth.showLoginOverlay,Vn=B("auth/validate",async(e,t)=>t.extra.deepdeskAPI.isLoggedIn()),n1=B("auth/requestLogin",async({email:e},t)=>{let{deepdeskAPI:n}=t.extra;return n.requestLoginByEmail(e)}),Ia=B("auth/verifyLoginToken",async({token:e},t)=>{let{deepdeskAPI:n}=t.extra;return n.verifyLoginToken(e)}),r1=G({name:"auth",initialState:VL,reducers:{setIsLoggedIn(e,t){e.isLoggedIn=t.payload},setShowLoginOverlay(e,t){e.showLoginOverlay=t.payload}},extraReducers:e=>{e.addCase(Vn.pending,t=>{t.loginFetchState="loading"}),e.addCase(Vn.fulfilled,(t,{payload:n})=>{t.isLoggedIn=n,t.loginFetchState="done"}),e.addCase(Vn.rejected,t=>{t.loginFetchState="error",t.isLoggedIn=!1}),e.addCase(Ia.pending,t=>{t.verifyFetchState="loading"}),e.addCase(Ia.rejected,t=>{t.verifyFetchState="error"}),e.addCase(Ia.fulfilled,(t,n)=>{n.payload.isLoggedIn?t.verifyFetchState="done":t.verifyFetchState="error"})}}),{setIsLoggedIn:$i,setShowLoginOverlay:o1}=r1.actions,i1=r1.reducer;function Kn(){}Kn.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 i=this;function s(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 p=[{newPos:-1,components:[]}],d=this.extractCommon(p[0],n,t,0);if(p[0].newPos+1>=a&&d+1>=l)return s([{value:this.join(n),count:n.length}]);function m(){for(var y=-1*u;y<=u;y+=2){var g=void 0,f=p[y-1],h=p[y+1],S=(h?h.newPos:0)-y;f&&(p[y-1]=void 0);var w=f&&f.newPos+1<a,T=h&&0<=S&&S<l;if(!w&&!T){p[y]=void 0;continue}if(!w||T&&f.newPos<h.newPos?(g=WL(h),i.pushComponent(g.components,void 0,!0)):(g=f,g.newPos++,i.pushComponent(g.components,!0,void 0)),S=i.extractCommon(g,n,t,y),g.newPos+1>=a&&S+1>=l)return s(KL(i,g.components,n,t,i.useLongestToken));p[y]=g}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 i=n.length,s=r.length,a=t.newPos,l=a-o,u=0;a+1<i&&l+1<s&&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 KL(e,t,n,r,o){for(var i=0,s=t.length,a=0,l=0;i<s;i++){var u=t[i];if(u.removed){if(u.value=e.join(r.slice(l,l+u.count)),l+=u.count,i&&t[i-1].added){var p=t[i-1];t[i-1]=t[i],t[i]=p}}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[s-1];return s>1&&typeof d.value=="string"&&(d.added||d.removed)&&e.equals("",d.value)&&(t[s-2].value+=d.value,t.pop()),t}function WL(e){return{newPos:e.newPos,components:e.components.slice(0)}}var $L=new Kn;function l1(e,t,n){return $L.diff(e,t,n)}var s1=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,a1=/\S/,u1=new Kn;u1.equals=function(e,t){return this.options.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||this.options.ignoreWhitespace&&!a1.test(e)&&!a1.test(t)};u1.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]&&s1.test(t[n])&&s1.test(t[n+2])&&(t[n]+=t[n+2],t.splice(n+1,2),n--);return t};var c1=new Kn;c1.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 qL=new Kn;qL.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var GL=new Kn;GL.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function $c(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?$c=function(t){return typeof t}:$c=function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},$c(e)}var XL=Object.prototype.toString,Oa=new Kn;Oa.useLongestToken=!0;Oa.tokenize=c1.tokenize;Oa.castInput=function(e){var t=this.options,n=t.undefinedReplacement,r=t.stringifyReplacer,o=r===void 0?function(i,s){return typeof s>"u"?n:s}:r;return typeof e=="string"?e:JSON.stringify(zg(e,null,null,o),o," ")};Oa.equals=function(e,t){return Kn.prototype.equals.call(Oa,e.replace(/,([\r\n])/g,"$1"),t.replace(/,([\r\n])/g,"$1"))};function zg(e,t,n,r,o){t=t||[],n=n||[],r&&(e=r(o,e));var i;for(i=0;i<t.length;i+=1)if(t[i]===e)return n[i];var s;if(XL.call(e)==="[object Array]"){for(t.push(e),s=new Array(e.length),n.push(s),i=0;i<e.length;i+=1)s[i]=zg(e[i],t,n,r,o);return t.pop(),n.pop(),s}if(e&&e.toJSON&&(e=e.toJSON()),$c(e)==="object"&&e!==null){t.push(e),s={},n.push(s);var a=[],l;for(l in e)e.hasOwnProperty(l)&&a.push(l);for(a.sort(),i=0;i<a.length;i+=1)l=a[i],s[l]=zg(e[l],t,n,r,l);t.pop(),n.pop()}else s=e;return s}var Bg=new Kn;Bg.tokenize=function(e){return e.slice()};Bg.join=Bg.removeEmpty=function(e){return e};function d1(e){return typeof e=="object"&&!Array.isArray(e)&&e!==null}function jr(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((i,s)=>jr(i,t[s],n-1)):d1(e)&&d1(t)?Object.keys(e).length!==Object.keys(t).length?!1:Object.keys(e).every(s=>jr(e[s],t[s],n-1)):!1}function YL(e){return Math.max(...e.map(t=>t.length))}function QL(e,t){let n=e.reduce((r,o)=>{if(o){let i=r[o]?r[o]+1:1;return{...r,[o]:i}}return r},{});return Object.keys(n).reduce((r,o)=>(n[o]<t&&r.push(o),r),[])}function f1(e,t){let r=[...e.map(({text:o})=>o.split(/\b(\w+)\b/))];for(let o=0;o<YL(r);o++){let i=QL(r.map(a=>a[o]),t),s=r.filter(a=>!i.includes(a[o]));if(s.length>=t)r=s;else return{text:r[0].slice(0,o).join("").replace(/ (\?| |!|\.|,|\n)/g,"$1").trimEnd(),source:"mixed"}}}var ZL=2;function jg(e,t=""){if(e.length===0)return;if(e.length===1)return e[0];let n=f1(e,ZL);return n&&n.text!==t?n:e[0]}var JL={info(...e){console.info("[Deepdesk]",...e)},warn(...e){console.warn("[Deepdesk]",...e)},error(...e){console.error("[Deepdesk]",...e)}},F=JL;var p1={current:null,isSupported:null},le=xe("resetConversation"),qi=e=>{let{current:t}=e.conversation;return(t==null?void 0:t.sessionId)||null},Vr=e=>{let{current:t}=e.conversation;return(t==null?void 0:t.id)||null},Gi=e=>e.conversation.isSupported,Vg=B("conversation/isSupported",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.isConversationSupported(e.sessionId,e.options)}),qc=B("conversation/create",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.createConversation(e)}),Gc=B("conversation/bySessionId",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.getConversationBySessionId(e.sessionId,e.options)}),Xc=B("conversation/update",(e,t)=>{let{deepdeskAPI:n}=t.extra,r=Vr(t.getState());if(!r)throw new Error("No current conversation to update");return n.updateConversation(r,e)}),Kg=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:i,agentEmail:s,agentNickname:a,tags:l}=e;return n.updateConversation(r.id,{agentId:o,agentEmail:s,agentName:i,agentNickname:a,tags:l})})}),Yc=B("conversation/postMessages",(e,t)=>{let{deepdeskAPI:n}=t.extra,r=Vr(t.getState());if(!r)throw new Error("No current conversation to update messages");return n.postMessages(r,e.map(o=>({...o})))}),eI=[qc.rejected,Gc.rejected,Xc.rejected,Yc.rejected].map(e=>e==null?void 0:e.toString()),tI=G({name:"conversation",initialState:p1,reducers:{},extraReducers:e=>{e.addCase(Vg.fulfilled,(t,n)=>{t.isSupported=n.payload}).addCase(qc.fulfilled,(t,n)=>{var r;t.current=n.payload,t.isSupported=((r=n.payload)==null?void 0:r.hasActiveProfile)??null}).addCase(Gc.fulfilled,(t,n)=>{var r;t.current=n.payload,t.isSupported=((r=n.payload)==null?void 0:r.hasActiveProfile)??null}).addCase(Kg.fulfilled,(t,n)=>{var r;t.current=n.payload,t.isSupported=((r=n.payload)==null?void 0:r.hasActiveProfile)??null}).addCase(Xc.fulfilled,(t,n)=>{var r;t.current=n.payload,t.isSupported=((r=n.payload)==null?void 0:r.hasActiveProfile)??null}).addCase(Yc.fulfilled,(t,n)=>{t.current&&(t.current.messages=n.payload)}).addCase(le,()=>p1).addMatcher(t=>eI.includes(t.type),(t,n)=>{var r;throw F.info("Conversation action rejected",n.type,((r=n.error)==null?void 0:r.message)||"No message"),new Error(n.error.message)})}}),m1=tI.reducer;var Kr={text:"",html:null,selection:{start:0,end:0},stagedSuggestion:null,userCommitted:{text:"",selection:{start:0,end:0}},tabCompletionSuggestion:void 0,previousKeyDownEvent:null,textSuggestions:[],selectedSuggestionIndex:-1,metrics:{numCharsTyped:0,numCharsPasted:0,numCharsCut:0,numCharsDeleted:0,numPaste:0,agentStartedTypingTimestamp:null,externalTimeTotalSeconds:null,pastes:[],deletions:[],offeredTextSuggestions:[],textSuggestions:[],cuts:[]}};function g1(e){let{key:t,shiftKey:n,ctrlKey:r,metaKey:o,altKey:i}=e;return{key:t,shiftKey:n,ctrlKey:r,metaKey:o,altKey:i}}var Zc=xe("input/replaceText"),Jc=xe("input/keyDown"),Ro=xe("input/sendMessage"),ed=xe("input/uiInputChange"),td=xe("input/applyImageSuggestion"),et=xe("input/sendEvent");function Qc(e){if(!e.stagedSuggestion)return;let{text:t,suggestion:{source:n,abVariant:r,abTestName:o,trainingJobs:i,sourceText:s,searchTerm:a,text:l},eventMetrics:{inputType:u},replace:c}=e.stagedSuggestion,p=n==="search"||n==="personal-collection-search",d=t.slice(e.userCommitted.text.substring(0,e.userCommitted.selection.start).length);(p||c==="selection")&&(d=t),e.stagedSuggestion.suggestion.source==="search-overlay"&&(d=l),e.userCommitted.text=e.text,e.userCommitted.selection=e.selection,e.metrics.textSuggestions.push({text:d,source:n,abVariant:r,abTestName:o,inputType:u,sourceText:s,trainingJobs:i||[],searchTerm:p?e.userCommitted.text:a}),e.stagedSuggestion=null,e.textSuggestions=[],e.selectedSuggestionIndex=-1}var h1=G({name:"input",initialState:Kr,reducers:{initialInput(e,t){let{text:n,selection:r,html:o}=t.payload;e.text=n,e.selection.start=(r==null?void 0:r.start)??n.length,e.selection.end=(r==null?void 0:r.end)??n.length,e.userCommitted.text=n,e.userCommitted.selection.start=(r==null?void 0:r.start)??n.length,e.userCommitted.selection.end=(r==null?void 0:r.end)??n.length,e.html=o||null},reset(e){Object.assign(e,{...Kr,selection:e.selection})},resetToCommitted(e){e.text=e.userCommitted.text,e.selection=e.userCommitted.selection,e.stagedSuggestion=null,e.tabCompletionSuggestion=jg(e.textSuggestions,e.userCommitted.text)},changeSelection(e,t){t.payload&&(jr(e.selection,t.payload)||(e.selection=t.payload,e.userCommitted.selection=e.selection,e.stagedSuggestion&&Qc(e)))},platformInput(e,t){let{text:n,html:r,selection:o}=t.payload;o&&(e.selection.start=o.start,e.selection.end=o.end),e.text=n,e.html=r||null},userInput(e,t){var i,s,a,l;if(e.previousKeyDownEvent){let{key:u,shiftKey:c,ctrlKey:p,metaKey:d,altKey:m}=e.previousKeyDownEvent;switch(u){case"Enter":c&&(e.metrics.numCharsTyped+=1);break;case"Backspace":case"Delete":{let{text:v}=e,{text:y}=t.payload,g=l1(v,y);v.length-y.length>1&&e.metrics.deletions.push(...g.filter(f=>f.removed).map(f=>f.value)),e.metrics.numCharsDeleted+=v.length-y.length;break}case"C":case"V":case"X":if(!p&&!d){e.metrics.numCharsTyped+=1;let v=((i=e.selection)==null?void 0:i.start)!==void 0&&((s=e.selection)==null?void 0:s.end)!==void 0?e.text.substring(e.selection.start,e.selection.end):null;v&&v.length>0&&(e.metrics.numCharsDeleted+=v.length,e.metrics.deletions.push(v))}break;case"Shift":break;default:if(!p&&!d&&!m){e.metrics.numCharsTyped+=1;let v=((a=e.selection)==null?void 0:a.start)!==void 0&&((l=e.selection)==null?void 0:l.end)!==void 0?e.text.substring(e.selection.start,e.selection.end):null;v&&v.length>0&&(e.metrics.numCharsDeleted+=v.length,e.metrics.deletions.push(v))}}}!e.metrics.agentStartedTypingTimestamp&&t.payload.text!==e.text&&(e.metrics.agentStartedTypingTimestamp=Date.now()),t.payload.text===""&&(e.metrics=Kr.metrics,e.textSuggestions=[],e.stagedSuggestion=null),e.text!==t.payload.text&&Qc(e);let{text:n,html:r,selection:o}=t.payload;o&&(e.selection.start=o.start,e.selection.end=o.end,e.userCommitted.selection.start=o.start,e.userCommitted.selection.end=o.end),e.text=n,e.html=r||null,e.userCommitted.text=n,e.previousKeyDownEvent=null},stageSuggestion(e,t){let{text:n}=t.payload;switch(e.stagedSuggestion=t.payload,e.tabCompletionSuggestion=void 0,t.payload.replace){case"selection":e.text=`${e.text.slice(0,e.selection.start)}${n}${e.text.slice(e.selection.end)}`,e.selection.end=e.selection.start+n.length,e.selection.start+=n.length;break;case"until-selection-end":e.text=`${n}${e.text.slice(e.selection.end)}`,e.selection.start=n.length,e.selection.end=n.length;break;default:throw new Error(`Unknown replace ${t.payload.replace}`)}t.payload.eventMetrics.inputType==="tab"&&Qc(e)},commitSuggestion(e){Qc(e)},offeredTextSuggestion(e,t){let{text:n,suggestion:{source:r}}=t.payload;e.metrics.offeredTextSuggestions.find(i=>i.text===n)||e.metrics.offeredTextSuggestions.push({text:n,source:r})},registerCut(e,t){let{metrics:n}=e,r=t.payload;e.metrics={...e.metrics,numCharsCut:n.numCharsCut+r.length,cuts:[...n.cuts,r]}},registerPaste(e,t){let{metrics:n}=e,{text:r,selectionText:o}=t.payload,i=n.numCharsDeleted+(o&&o.length?o.length:0),s=o&&o.length?[...n.deletions,o]:n.deletions;e.metrics={...e.metrics,numCharsDeleted:i,deletions:s,numCharsPasted:n.numCharsPasted+r.length,numPaste:n.numPaste+1,pastes:[...n.pastes,r]}},registerKeyDown(e,t){e.previousKeyDownEvent=t.payload},nextTextSuggestionIndex(e){let t=e.textSuggestions.length;e.selectedSuggestionIndex=e.selectedSuggestionIndex<t-1?e.selectedSuggestionIndex+1:e.selectedSuggestionIndex},previousTextSuggestionIndex(e){e.selectedSuggestionIndex=e.selectedSuggestionIndex>=0?e.selectedSuggestionIndex-1:e.selectedSuggestionIndex},setTextSuggestions(e,t){if(e.selectedSuggestionIndex=-1,e.textSuggestions=t.payload,t.payload.length===0){e.tabCompletionSuggestion=void 0;return}let n=e.userCommitted.text.substring(0,e.userCommitted.selection.end),r=jg(t.payload,n);e.tabCompletionSuggestion=r!=null&&r.text.includes(n)?r:void 0},setSelectedTextSuggestionIndex(e,t){e.selectedSuggestionIndex=t.payload},setMetrics(e,{payload:t}){e.metrics=t}},extraReducers:e=>{e.addCase(le,t=>{t.tabCompletionSuggestion=Kr.tabCompletionSuggestion,t.previousKeyDownEvent=Kr.previousKeyDownEvent,t.textSuggestions=Kr.textSuggestions,t.selectedSuggestionIndex=Kr.selectedSuggestionIndex,t.metrics=Kr.metrics})}}),Xi=e=>e.input.userCommitted.text.substring(0,e.input.userCommitted.selection.end),nI=e=>e.input.selection,y1=()=>L(nI),{userInput:v1,changeSelection:Wg,initialInput:S1,nextTextSuggestionIndex:x1,offeredTextSuggestion:w1,previousTextSuggestionIndex:E1,registerCut:C1,registerKeyDown:b1,registerPaste:T1,reset:k1,resetToCommitted:Ma,platformInput:P1,setSelectedTextSuggestionIndex:Wr,setTextSuggestions:En,stageSuggestion:Cn,commitSuggestion:Wn,setMetrics:R1}=h1.actions,A1=h1.reducer;function rI(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function J(e){return Array.isArray(e)?e.map(J):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>({...t,[rI(n)]:J(e[n])}),{}):e}function $g(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Re(e){return Array.isArray(e)?e.map(Re):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>({...t,[$g(n)]:Re(e[n])}),{}):e}var oI={agentInfo:void 0,agentSettings:{},visitorInfo:void 0,customData: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)||""}},Na=B("info/setAgentInfo",async(e,t)=>{let{deepdeskAPI:n}=t.extra;if(!e.agentId&&!e.agentNickname)throw new Error("At least provide agentId or agentNickname");let r=await n.client.get("/apis/admin/session/me/",{version:null}),o={};return r.external_id||(o.external_id=e.agentId),r.nickname||(o.nickname=e.agentNickname),!o.external_id&&!o.nickname?J(r):(await n.client.patch("/apis/admin/session/me/",o,{version:null}),J(r))}),qg=B("info/setAgentSettings",async(e,t)=>{let{deepdeskAPI:n}=t.extra,r=await n.client.get("/apis/admin/session/me/",{version:null}),o={...typeof r.ui_config=="object"?r.ui_config:{},...e};return await n.client.patch("/apis/admin/session/me/",{ui_config:o}),o}),Gg=B("info/getAgentSettings",async(e,t)=>{let{deepdeskAPI:n}=t.extra;return(await n.client.get("/apis/admin/session/me/",{version:null})).ui_config}),L1=e=>e.info.agentInfo,I1=e=>e.info.customData,O1=G({name:"info",initialState:oI,reducers:{setVisitorInfo(e,t){e.visitorInfo={...e.visitorInfo,...t.payload}},setCustomData(e,t){e.customData=t.payload}},extraReducers:e=>{e.addCase(Na.pending,(t,n)=>{t.fetchState="loading",t.agentInfo={...t.agentInfo,...n.meta.arg}}).addCase(Na.rejected,t=>{t.fetchState="error"}).addCase(Na.fulfilled,(t,n)=>{t.fetchState="done",t.agentInfo={...t.agentInfo,...n.meta.arg,agentId:n.payload.externalId||n.meta.arg.agentId||"",agentNickname:n.payload.nickname||n.meta.arg.agentNickname||""}}).addCase(qg.fulfilled,(t,n)=>{t.agentSettings=n.payload}).addCase(Gg.fulfilled,(t,n)=>{t.agentSettings=n.payload}).addCase(le,t=>{t.visitorInfo=void 0})}}),{setVisitorInfo:M1,setCustomData:N1}=O1.actions,_1=O1.reducer;var nd={list:[],fetchState:"idle",isOpen:!1,page:"search",aggregates:{}},D1=e=>e.search.isOpen,F1=e=>e.search.page,H1=e=>e.search.list,U1=e=>e.search.aggregates;function z1(e,t=n=>n){return n=>n.search.list.filter(r=>r.type===e).map(t)}var Ao=B("search/getAll",async(e,t)=>{var a;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=(a=r.conversation.current)==null?void 0:a.profileCode;if(!o)throw new Error("Profile should be provided in order to be able to search");let{results:i,aggregates:s}=await 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(l=>({...l,source:`search-${l.type.toLowerCase()}`,searchTerm:e.query})),aggregates:s}}),B1=G({name:"search",initialState:nd,reducers:{setIsOpen(e,t){e.isOpen=t.payload},setPage(e,t){e.page=t.payload},resetSearch(e){e.fetchState=nd.fetchState,e.list=nd.list}},extraReducers:e=>{e.addCase(Ao.pending,t=>{t.fetchState="loading"}).addCase(Ao.rejected,(t,n)=>{t.fetchState="error",F.error(n.error)}).addCase(Ao.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload.results,t.aggregates=n.payload.aggregates||{}}).addCase(le,()=>nd)}}),{resetSearch:rd,setIsOpen:xt,setPage:Jt}=B1.actions,j1=B1.reducer;var Xg="SetCues",Yi="ShowLoginOverlay",Da="UserLoggedIn",iI="UserLoggedOut",$r="ApplySuggestion",Yg="ApplyImageSuggestion",sI="ShowCommandPalette",aI=e=>({[Xg]:t=>{e.dispatch({...t,isBroadcasted:!0})},[sI]:t=>{e.dispatch(xt(t.isOpen)),t.page&&e.dispatch(Jt(t.page))},[Yi]:t=>{e.dispatch(o1(t))},[Da]:()=>{e.dispatch(Vn())},[iI]:()=>{e.dispatch(Vn())},[Yg]:t=>{e.dispatch(td({suggestion:t.suggestion}))},[$r]:t=>{e.dispatch(Cn({...t,eventMetrics:{inputType:"mouse"},replace:"selection"})),e.dispatch(Wn())}}),V1=aI;var Fa=x(_()),W1=x(C()),K1=Fa.default.createContext(null),Lo=({broadcastEvents:e,children:t})=>{let n=Fa.default.useMemo(()=>e,[]);return(0,W1.jsx)(K1.Provider,{value:n,children:t})},Bt=()=>{let e=(0,Fa.useContext)(K1);if(!e)throw new Error("You should use the useBroadcastEvents within a BroadcastEventsProvider");return e};var xd=x(te()),tn=x(_());var yd=x(_());var Qg=function(e,t){return Qg=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])},Qg(e,t)};function Ha(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");Qg(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var wt=function(){return wt=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},wt.apply(this,arguments)};function $1(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 od(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,i;r<o;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))}var id;(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"})(id||(id={}));var sd=class{constructor(t){console.warn(`[vite-messages-plugin]: Message "${t}" was not precompiled. Did you use the correct extenstion *.messages.ts?`)}};var en;(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"})(en||(en={}));var ad;(function(e){e[e.number=0]="number",e[e.dateTime=1]="dateTime"})(ad||(ad={}));function Zg(e){return e.type===en.literal}function q1(e){return e.type===en.argument}function ld(e){return e.type===en.number}function ud(e){return e.type===en.date}function cd(e){return e.type===en.time}function dd(e){return e.type===en.select}function fd(e){return e.type===en.plural}function G1(e){return e.type===en.pound}function pd(e){return e.type===en.tag}function md(e){return!!(e&&typeof e=="object"&&e.type===ad.number)}function Ua(e){return!!(e&&typeof e=="object"&&e.type===ad.dateTime)}function Jg(e){e.forEach(function(t){if(delete t.location,dd(t)||fd(t))for(var n in t.options)delete t.options[n].location,Jg(t.options[n].value);else ld(t)&&md(t.style)||(ud(t)||cd(t))&&Ua(t.style)?delete t.style.location:pd(t)&&Jg(t.children)})}function X1(e,t){t===void 0&&(t={}),t=wt({shouldParseSkeletons:!0,requiresOtherClause:!0},t);var n=new sd(e,t).parse();if(n.err){var r=SyntaxError(id[n.err.kind]);throw r.location=n.err.location,r.originalMessage=n.err.message,r}return t!=null&&t.captureLocation||Jg(n.val),n.val}function gd(e,t){var n=t&&t.cache?t.cache:pI,r=t&&t.serializer?t.serializer:fI,o=t&&t.strategy?t.strategy:uI;return o(e,{cache:n,serializer:r})}function lI(e){return e==null||typeof e=="number"||typeof e=="boolean"}function Y1(e,t,n,r){var o=lI(r)?r:n(r),i=t.get(o);return typeof i>"u"&&(i=e.call(this,r),t.set(o,i)),i}function Q1(e,t,n){var r=Array.prototype.slice.call(arguments,3),o=n(r),i=t.get(o);return typeof i>"u"&&(i=e.apply(this,r),t.set(o,i)),i}function eh(e,t,n,r,o){return n.bind(t,e,r,o)}function uI(e,t){var n=e.length===1?Y1:Q1;return eh(e,this,n,t.cache.create(),t.serializer)}function cI(e,t){return eh(e,this,Q1,t.cache.create(),t.serializer)}function dI(e,t){return eh(e,this,Y1,t.cache.create(),t.serializer)}var fI=function(){return JSON.stringify(arguments)};function th(){this.cache=Object.create(null)}th.prototype.get=function(e){return this.cache[e]};th.prototype.set=function(e,t){this.cache[e]=t};var pI={create:function(){return new th}},hd={variadic:cI,monadic:dI};var Io;(function(e){e.MISSING_VALUE="MISSING_VALUE",e.INVALID_VALUE="INVALID_VALUE",e.MISSING_INTL_API="MISSING_INTL_API"})(Io||(Io={}));var za=function(e){Ha(t,e);function t(n,r,o){var i=e.call(this,n)||this;return i.code=r,i.originalMessage=o,i}return t.prototype.toString=function(){return"[formatjs Error: ".concat(this.code,"] ").concat(this.message)},t}(Error);var nh=function(e){Ha(t,e);function t(n,r,o,i){return e.call(this,'Invalid values for "'.concat(n,'": "').concat(r,'". Options are "').concat(Object.keys(o).join('", "'),'"'),Io.INVALID_VALUE,i)||this}return t}(za);var Z1=function(e){Ha(t,e);function t(n,r,o){return e.call(this,'Value for "'.concat(n,'" must be of type ').concat(r),Io.INVALID_VALUE,o)||this}return t}(za);var J1=function(e){Ha(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,'"'),Io.MISSING_VALUE,r)||this}return t}(za);var Ye;(function(e){e[e.literal=0]="literal",e[e.object=1]="object"})(Ye||(Ye={}));function mI(e){return e.length<2?e:e.reduce(function(t,n){var r=t[t.length-1];return!r||r.type!==Ye.literal||n.type!==Ye.literal?t.push(n):r.value+=n.value,t},[])}function gI(e){return typeof e=="function"}function Ba(e,t,n,r,o,i,s){if(e.length===1&&Zg(e[0]))return[{type:Ye.literal,value:e[0].value}];for(var a=[],l=0,u=e;l<u.length;l++){var c=u[l];if(Zg(c)){a.push({type:Ye.literal,value:c.value});continue}if(G1(c)){typeof i=="number"&&a.push({type:Ye.literal,value:n.getNumberFormat(t).format(i)});continue}var p=c.value;if(!(o&&p in o))throw new J1(p,s);var d=o[p];if(q1(c)){(!d||typeof d=="string"||typeof d=="number")&&(d=typeof d=="string"||typeof d=="number"?String(d):""),a.push({type:typeof d=="string"?Ye.literal:Ye.object,value:d});continue}if(ud(c)){var m=typeof c.style=="string"?r.date[c.style]:Ua(c.style)?c.style.parsedOptions:void 0;a.push({type:Ye.literal,value:n.getDateTimeFormat(t,m).format(d)});continue}if(cd(c)){var m=typeof c.style=="string"?r.time[c.style]:Ua(c.style)?c.style.parsedOptions:r.time.medium;a.push({type:Ye.literal,value:n.getDateTimeFormat(t,m).format(d)});continue}if(ld(c)){var m=typeof c.style=="string"?r.number[c.style]:md(c.style)?c.style.parsedOptions:void 0;m&&m.scale&&(d=d*(m.scale||1)),a.push({type:Ye.literal,value:n.getNumberFormat(t,m).format(d)});continue}if(pd(c)){var v=c.children,y=c.value,g=o[y];if(!gI(g))throw new Z1(y,"function",s);var f=Ba(v,t,n,r,o,i),h=g(f.map(function(T){return T.value}));Array.isArray(h)||(h=[h]),a.push.apply(a,h.map(function(T){return{type:typeof T=="string"?Ye.literal:Ye.object,value:T}}))}if(dd(c)){var S=c.options[d]||c.options.other;if(!S)throw new nh(c.value,d,Object.keys(c.options),s);a.push.apply(a,Ba(S.value,t,n,r,o));continue}if(fd(c)){var S=c.options["=".concat(d)];if(!S){if(!Intl.PluralRules)throw new za(`Intl.PluralRules is not available in this environment.
|
|
13
|
+
`),it}Ki(()=>{oo.current=void 0,q.current=void 0,he.current=qt});let Gt=(0,ae.useMemo)(()=>ae.default.createElement(g,Bn({},qt,{ref:O})),[O,g,qt]);return(0,ae.useMemo)(()=>v?ae.default.createElement(W.Provider,{value:fr},Gt):Gt,[W,Gt,fr])}let b=ae.default.memo(w);if(b.WrappedComponent=g,b.displayName=w.displayName=h,l){let I=ae.default.forwardRef(function(M,W){return ae.default.createElement(b,Bn({},M,{reactReduxForwardedRef:W}))});return I.displayName=h,I.WrappedComponent=g,(0,Dg.default)(I,g)}return(0,Dg.default)(b,g)}}var jn=zL;var Aa=x(_());function BL({store:e,context:t,children:n,serverState:r,stabilityCheck:o="once",noopCheck:i="once"}){let s=(0,Aa.useMemo)(()=>{let u=jc(e);return{store:e,subscription:u,getServerState:r?()=>r:void 0,stabilityCheck:o,noopCheck:i}},[e,r,o,i]),a=(0,Aa.useMemo)(()=>e.getState(),[e]);Ki(()=>{let{subscription:u}=s;return u.onStateChange=u.notifyNestedSubs,u.trySubscribe(),a!==e.getState()&&u.notifyNestedSubs(),()=>{u.tryUnsubscribe(),u.onStateChange=void 0}},[s,a]);let l=t||Xe;return Aa.default.createElement(l.Provider,{value:s},n)}var Fg=BL;function Kc(e=Xe){let t=e===Xe?Sc:ka(e);return function(){let{store:r}=t();return r}}var Hg=Kc();function Gw(e=Xe){let t=e===Xe?Hg:Kc(e);return function(){return t().dispatch}}var $=Gw();Ew(Yw.useSyncExternalStoreWithSelector);qw(Xw.useSyncExternalStore);hw(kg.unstable_batchedUpdates);var La=(n=>(n.NL_NL="nl-NL",n.EN_US="en-US",n))(La||{});var jL={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"},Qw=G({name:"settings",initialState:jL,reducers:{set(e,t){Object.entries(t.payload).forEach(n=>{let[r,o]=n;typeof o>"u"||(e[r]=o)})}}}),{set:Wc}=Qw.actions,Ug=e=>t=>t.settings[e],z=e=>L(Ug(e)),Zw=Qw.reducer;var VL={isLoggedIn:!0,loginFetchState:"idle",verifyFetchState:"idle",showLoginOverlay:!1},Je=e=>e.auth.isLoggedIn,Jw=e=>e.auth.loginFetchState,e1=e=>e.auth.verifyFetchState,t1=e=>e.auth.showLoginOverlay,Vn=B("auth/validate",async(e,t)=>t.extra.deepdeskAPI.isLoggedIn()),n1=B("auth/requestLogin",async({email:e},t)=>{let{deepdeskAPI:n}=t.extra;return n.requestLoginByEmail(e)}),Ia=B("auth/verifyLoginToken",async({token:e},t)=>{let{deepdeskAPI:n}=t.extra;return n.verifyLoginToken(e)}),r1=G({name:"auth",initialState:VL,reducers:{setIsLoggedIn(e,t){e.isLoggedIn=t.payload},setShowLoginOverlay(e,t){e.showLoginOverlay=t.payload}},extraReducers:e=>{e.addCase(Vn.pending,t=>{t.loginFetchState="loading"}),e.addCase(Vn.fulfilled,(t,{payload:n})=>{t.isLoggedIn=n,t.loginFetchState="done"}),e.addCase(Vn.rejected,t=>{t.loginFetchState="error",t.isLoggedIn=!1}),e.addCase(Ia.pending,t=>{t.verifyFetchState="loading"}),e.addCase(Ia.rejected,t=>{t.verifyFetchState="error"}),e.addCase(Ia.fulfilled,(t,n)=>{n.payload.isLoggedIn?t.verifyFetchState="done":t.verifyFetchState="error"})}}),{setIsLoggedIn:$i,setShowLoginOverlay:o1}=r1.actions,i1=r1.reducer;function Kn(){}Kn.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 i=this;function s(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 p=[{newPos:-1,components:[]}],d=this.extractCommon(p[0],n,t,0);if(p[0].newPos+1>=a&&d+1>=l)return s([{value:this.join(n),count:n.length}]);function m(){for(var y=-1*u;y<=u;y+=2){var g=void 0,f=p[y-1],h=p[y+1],S=(h?h.newPos:0)-y;f&&(p[y-1]=void 0);var w=f&&f.newPos+1<a,T=h&&0<=S&&S<l;if(!w&&!T){p[y]=void 0;continue}if(!w||T&&f.newPos<h.newPos?(g=WL(h),i.pushComponent(g.components,void 0,!0)):(g=f,g.newPos++,i.pushComponent(g.components,!0,void 0)),S=i.extractCommon(g,n,t,y),g.newPos+1>=a&&S+1>=l)return s(KL(i,g.components,n,t,i.useLongestToken));p[y]=g}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 i=n.length,s=r.length,a=t.newPos,l=a-o,u=0;a+1<i&&l+1<s&&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 KL(e,t,n,r,o){for(var i=0,s=t.length,a=0,l=0;i<s;i++){var u=t[i];if(u.removed){if(u.value=e.join(r.slice(l,l+u.count)),l+=u.count,i&&t[i-1].added){var p=t[i-1];t[i-1]=t[i],t[i]=p}}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[s-1];return s>1&&typeof d.value=="string"&&(d.added||d.removed)&&e.equals("",d.value)&&(t[s-2].value+=d.value,t.pop()),t}function WL(e){return{newPos:e.newPos,components:e.components.slice(0)}}var $L=new Kn;function l1(e,t,n){return $L.diff(e,t,n)}var s1=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,a1=/\S/,u1=new Kn;u1.equals=function(e,t){return this.options.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||this.options.ignoreWhitespace&&!a1.test(e)&&!a1.test(t)};u1.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]&&s1.test(t[n])&&s1.test(t[n+2])&&(t[n]+=t[n+2],t.splice(n+1,2),n--);return t};var c1=new Kn;c1.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 qL=new Kn;qL.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var GL=new Kn;GL.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function $c(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?$c=function(t){return typeof t}:$c=function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},$c(e)}var XL=Object.prototype.toString,Oa=new Kn;Oa.useLongestToken=!0;Oa.tokenize=c1.tokenize;Oa.castInput=function(e){var t=this.options,n=t.undefinedReplacement,r=t.stringifyReplacer,o=r===void 0?function(i,s){return typeof s>"u"?n:s}:r;return typeof e=="string"?e:JSON.stringify(zg(e,null,null,o),o," ")};Oa.equals=function(e,t){return Kn.prototype.equals.call(Oa,e.replace(/,([\r\n])/g,"$1"),t.replace(/,([\r\n])/g,"$1"))};function zg(e,t,n,r,o){t=t||[],n=n||[],r&&(e=r(o,e));var i;for(i=0;i<t.length;i+=1)if(t[i]===e)return n[i];var s;if(XL.call(e)==="[object Array]"){for(t.push(e),s=new Array(e.length),n.push(s),i=0;i<e.length;i+=1)s[i]=zg(e[i],t,n,r,o);return t.pop(),n.pop(),s}if(e&&e.toJSON&&(e=e.toJSON()),$c(e)==="object"&&e!==null){t.push(e),s={},n.push(s);var a=[],l;for(l in e)e.hasOwnProperty(l)&&a.push(l);for(a.sort(),i=0;i<a.length;i+=1)l=a[i],s[l]=zg(e[l],t,n,r,l);t.pop(),n.pop()}else s=e;return s}var Bg=new Kn;Bg.tokenize=function(e){return e.slice()};Bg.join=Bg.removeEmpty=function(e){return e};function d1(e){return typeof e=="object"&&!Array.isArray(e)&&e!==null}function jr(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((i,s)=>jr(i,t[s],n-1)):d1(e)&&d1(t)?Object.keys(e).length!==Object.keys(t).length?!1:Object.keys(e).every(s=>jr(e[s],t[s],n-1)):!1}function YL(e){return Math.max(...e.map(t=>t.length))}function QL(e,t){let n=e.reduce((r,o)=>{if(o){let i=r[o]?r[o]+1:1;return{...r,[o]:i}}return r},{});return Object.keys(n).reduce((r,o)=>(n[o]<t&&r.push(o),r),[])}function f1(e,t){let r=[...e.map(({text:o})=>o.split(/\b(\w+)\b/))];for(let o=0;o<YL(r);o++){let i=QL(r.map(a=>a[o]),t),s=r.filter(a=>!i.includes(a[o]));if(s.length>=t)r=s;else return{text:r[0].slice(0,o).join("").replace(/ (\?| |!|\.|,|\n)/g,"$1").trimEnd(),source:"mixed"}}}var ZL=2;function jg(e,t=""){if(e.length===0)return;if(e.length===1)return e[0];let n=f1(e,ZL);return n&&n.text!==t?n:e[0]}var JL={info(...e){console.info("[Deepdesk]",...e)},warn(...e){console.warn("[Deepdesk]",...e)},error(...e){console.error("[Deepdesk]",...e)}},F=JL;var p1={current:null,isSupported:null},le=xe("resetConversation"),qi=e=>{let{current:t}=e.conversation;return(t==null?void 0:t.sessionId)||null},Vr=e=>{let{current:t}=e.conversation;return(t==null?void 0:t.id)||null},Gi=e=>e.conversation.isSupported,Vg=B("conversation/isSupported",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.isConversationSupported(e.sessionId,e.options)}),qc=B("conversation/create",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.createConversation(e)}),Gc=B("conversation/bySessionId",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.getConversationBySessionId(e.sessionId,e.options)}),Xc=B("conversation/update",(e,t)=>{let{deepdeskAPI:n}=t.extra,r=Vr(t.getState());if(!r)throw new Error("No current conversation to update");return n.updateConversation(r,e)}),Kg=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:i,agentEmail:s,agentNickname:a,tags:l}=e;return n.updateConversation(r.id,{agentId:o,agentEmail:s,agentName:i,agentNickname:a,tags:l})})}),Yc=B("conversation/postMessages",(e,t)=>{let{deepdeskAPI:n}=t.extra,r=Vr(t.getState());if(!r)throw new Error("No current conversation to update messages");return n.postMessages(r,e.map(o=>({...o})))}),eI=[qc.rejected,Gc.rejected,Xc.rejected,Yc.rejected].map(e=>e==null?void 0:e.toString()),tI=G({name:"conversation",initialState:p1,reducers:{},extraReducers:e=>{e.addCase(Vg.fulfilled,(t,n)=>{t.isSupported=n.payload}).addCase(qc.fulfilled,(t,n)=>{var r;t.current=n.payload,t.isSupported=((r=n.payload)==null?void 0:r.hasActiveProfile)??null}).addCase(Gc.fulfilled,(t,n)=>{var r;t.current=n.payload,t.isSupported=((r=n.payload)==null?void 0:r.hasActiveProfile)??null}).addCase(Kg.fulfilled,(t,n)=>{var r;t.current=n.payload,t.isSupported=((r=n.payload)==null?void 0:r.hasActiveProfile)??null}).addCase(Xc.fulfilled,(t,n)=>{var r;t.current=n.payload,t.isSupported=((r=n.payload)==null?void 0:r.hasActiveProfile)??null}).addCase(Yc.fulfilled,(t,n)=>{t.current&&(t.current.messages=n.payload)}).addCase(le,()=>p1).addMatcher(t=>eI.includes(t.type),(t,n)=>{var r;throw F.info("Conversation action rejected",n.type,((r=n.error)==null?void 0:r.message)||"No message"),new Error(n.error.message)})}}),m1=tI.reducer;var Kr={text:"",html:null,selection:{start:0,end:0},stagedSuggestion:null,userCommitted:{text:"",selection:{start:0,end:0}},tabCompletionSuggestion:void 0,previousKeyDownEvent:null,textSuggestions:[],selectedSuggestionIndex:-1,metrics:{numCharsTyped:0,numCharsPasted:0,numCharsCut:0,numCharsDeleted:0,numPaste:0,agentStartedTypingTimestamp:null,externalTimeTotalSeconds:null,pastes:[],deletions:[],offeredTextSuggestions:[],textSuggestions:[],cuts:[]}};function g1(e){let{key:t,shiftKey:n,ctrlKey:r,metaKey:o,altKey:i}=e;return{key:t,shiftKey:n,ctrlKey:r,metaKey:o,altKey:i}}var Zc=xe("input/replaceText"),Jc=xe("input/keyDown"),Ro=xe("input/sendMessage"),ed=xe("input/uiInputChange"),td=xe("input/applyImageSuggestion"),et=xe("input/sendEvent");function Qc(e){if(!e.stagedSuggestion)return;let{text:t,suggestion:{source:n,abVariant:r,abTestName:o,trainingJobs:i,sourceText:s,searchTerm:a,text:l},eventMetrics:{inputType:u},replace:c}=e.stagedSuggestion,p=n==="search"||n==="personal-collection-search",d=t.slice(e.userCommitted.text.substring(0,e.userCommitted.selection.start).length);(p||c==="selection")&&(d=t),e.stagedSuggestion.suggestion.source==="search-overlay"&&(d=l),e.userCommitted.text=e.text,e.userCommitted.selection=e.selection,e.metrics.textSuggestions.push({text:d,source:n,abVariant:r,abTestName:o,inputType:u,sourceText:s,trainingJobs:i||[],searchTerm:p?e.userCommitted.text:a}),e.stagedSuggestion=null,e.textSuggestions=[],e.selectedSuggestionIndex=-1}var h1=G({name:"input",initialState:Kr,reducers:{initialInput(e,t){let{text:n,selection:r,html:o}=t.payload;e.text=n,e.selection.start=(r==null?void 0:r.start)??n.length,e.selection.end=(r==null?void 0:r.end)??n.length,e.userCommitted.text=n,e.userCommitted.selection.start=(r==null?void 0:r.start)??n.length,e.userCommitted.selection.end=(r==null?void 0:r.end)??n.length,e.html=o||null},reset(e){Object.assign(e,{...Kr,selection:e.selection})},resetToCommitted(e){e.text=e.userCommitted.text,e.selection=e.userCommitted.selection,e.stagedSuggestion=null,e.tabCompletionSuggestion=jg(e.textSuggestions,e.userCommitted.text)},changeSelection(e,t){t.payload&&(jr(e.selection,t.payload)||(e.selection=t.payload,e.userCommitted.selection=e.selection,e.stagedSuggestion&&Qc(e)))},platformInput(e,t){let{text:n,html:r,selection:o}=t.payload;o&&(e.selection.start=o.start,e.selection.end=o.end),e.text=n,e.html=r||null},userInput(e,t){var i,s,a,l;if(e.previousKeyDownEvent){let{key:u,shiftKey:c,ctrlKey:p,metaKey:d,altKey:m}=e.previousKeyDownEvent;switch(u){case"Enter":c&&(e.metrics.numCharsTyped+=1);break;case"Backspace":case"Delete":{let{text:v}=e,{text:y}=t.payload,g=l1(v,y);v.length-y.length>1&&e.metrics.deletions.push(...g.filter(f=>f.removed).map(f=>f.value)),e.metrics.numCharsDeleted+=v.length-y.length;break}case"C":case"V":case"X":if(!p&&!d){e.metrics.numCharsTyped+=1;let v=((i=e.selection)==null?void 0:i.start)!==void 0&&((s=e.selection)==null?void 0:s.end)!==void 0?e.text.substring(e.selection.start,e.selection.end):null;v&&v.length>0&&(e.metrics.numCharsDeleted+=v.length,e.metrics.deletions.push(v))}break;case"Shift":break;default:if(!p&&!d&&!m){e.metrics.numCharsTyped+=1;let v=((a=e.selection)==null?void 0:a.start)!==void 0&&((l=e.selection)==null?void 0:l.end)!==void 0?e.text.substring(e.selection.start,e.selection.end):null;v&&v.length>0&&(e.metrics.numCharsDeleted+=v.length,e.metrics.deletions.push(v))}}}!e.metrics.agentStartedTypingTimestamp&&t.payload.text!==e.text&&(e.metrics.agentStartedTypingTimestamp=Date.now()),t.payload.text===""&&(e.metrics=Kr.metrics,e.textSuggestions=[],e.stagedSuggestion=null),e.text!==t.payload.text&&Qc(e);let{text:n,html:r,selection:o}=t.payload;o&&(e.selection.start=o.start,e.selection.end=o.end,e.userCommitted.selection.start=o.start,e.userCommitted.selection.end=o.end),e.text=n,e.html=r||null,e.userCommitted.text=n,e.previousKeyDownEvent=null},stageSuggestion(e,t){let{text:n}=t.payload;switch(e.stagedSuggestion=t.payload,e.tabCompletionSuggestion=void 0,t.payload.replace){case"selection":e.text=`${e.text.slice(0,e.selection.start)}${n}${e.text.slice(e.selection.end)}`,e.selection.end=e.selection.start+n.length,e.selection.start+=n.length;break;case"until-selection-end":e.text=`${n}${e.text.slice(e.selection.end)}`,e.selection.start=n.length,e.selection.end=n.length;break;default:throw new Error(`Unknown replace ${t.payload.replace}`)}t.payload.eventMetrics.inputType==="tab"&&Qc(e)},commitSuggestion(e){Qc(e)},offeredTextSuggestion(e,t){let{text:n,suggestion:{source:r}}=t.payload;e.metrics.offeredTextSuggestions.find(i=>i.text===n)||e.metrics.offeredTextSuggestions.push({text:n,source:r})},registerCut(e,t){let{metrics:n}=e,r=t.payload;e.metrics={...e.metrics,numCharsCut:n.numCharsCut+r.length,cuts:[...n.cuts,r]}},registerPaste(e,t){let{metrics:n}=e,{text:r,selectionText:o}=t.payload,i=n.numCharsDeleted+(o&&o.length?o.length:0),s=o&&o.length?[...n.deletions,o]:n.deletions;e.metrics={...e.metrics,numCharsDeleted:i,deletions:s,numCharsPasted:n.numCharsPasted+r.length,numPaste:n.numPaste+1,pastes:[...n.pastes,r]}},registerKeyDown(e,t){e.previousKeyDownEvent=t.payload},nextTextSuggestionIndex(e){let t=e.textSuggestions.length;e.selectedSuggestionIndex=e.selectedSuggestionIndex<t-1?e.selectedSuggestionIndex+1:e.selectedSuggestionIndex},previousTextSuggestionIndex(e){e.selectedSuggestionIndex=e.selectedSuggestionIndex>=0?e.selectedSuggestionIndex-1:e.selectedSuggestionIndex},setTextSuggestions(e,t){if(e.selectedSuggestionIndex=-1,e.textSuggestions=t.payload,t.payload.length===0){e.tabCompletionSuggestion=void 0;return}let n=e.userCommitted.text.substring(0,e.userCommitted.selection.end),r=jg(t.payload,n);e.tabCompletionSuggestion=r!=null&&r.text.includes(n)?r:void 0},setSelectedTextSuggestionIndex(e,t){e.selectedSuggestionIndex=t.payload},setMetrics(e,{payload:t}){e.metrics=t}},extraReducers:e=>{e.addCase(le,t=>{t.tabCompletionSuggestion=Kr.tabCompletionSuggestion,t.previousKeyDownEvent=Kr.previousKeyDownEvent,t.textSuggestions=Kr.textSuggestions,t.selectedSuggestionIndex=Kr.selectedSuggestionIndex,t.metrics=Kr.metrics})}}),Xi=e=>e.input.userCommitted.text.substring(0,e.input.userCommitted.selection.end),nI=e=>e.input.selection,y1=()=>L(nI),{userInput:v1,changeSelection:Wg,initialInput:S1,nextTextSuggestionIndex:x1,offeredTextSuggestion:w1,previousTextSuggestionIndex:E1,registerCut:C1,registerKeyDown:b1,registerPaste:T1,reset:k1,resetToCommitted:Ma,platformInput:P1,setSelectedTextSuggestionIndex:Wr,setTextSuggestions:En,stageSuggestion:Cn,commitSuggestion:Wn,setMetrics:R1}=h1.actions,A1=h1.reducer;function rI(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function J(e){return Array.isArray(e)?e.map(J):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>({...t,[rI(n)]:J(e[n])}),{}):e}function $g(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Re(e){return Array.isArray(e)?e.map(Re):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>({...t,[$g(n)]:Re(e[n])}),{}):e}var oI={agentInfo:void 0,agentSettings:{},visitorInfo:void 0,customData: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)||""}},Na=B("info/setAgentInfo",async(e,t)=>{let{deepdeskAPI:n}=t.extra;if(!e.agentId&&!e.agentNickname)throw new Error("At least provide agentId or agentNickname");let r=await n.client.get("/apis/admin/session/me/",{version:null}),o={};return r.external_id||(o.external_id=e.agentId),r.nickname||(o.nickname=e.agentNickname),!o.external_id&&!o.nickname?J(r):(await n.client.patch("/apis/admin/session/me/",o,{version:null}),J(r))}),qg=B("info/setAgentSettings",async(e,t)=>{let{deepdeskAPI:n}=t.extra,r=await n.client.get("/apis/admin/session/me/",{version:null}),o={...typeof r.ui_config=="object"?r.ui_config:{},...e};return await n.client.patch("/apis/admin/session/me/",{ui_config:o}),o}),Gg=B("info/getAgentSettings",async(e,t)=>{let{deepdeskAPI:n}=t.extra;return(await n.client.get("/apis/admin/session/me/",{version:null})).ui_config}),L1=e=>e.info.agentInfo,I1=e=>e.info.customData,O1=G({name:"info",initialState:oI,reducers:{setVisitorInfo(e,t){e.visitorInfo={...e.visitorInfo,...t.payload}},setCustomData(e,t){e.customData=t.payload}},extraReducers:e=>{e.addCase(Na.pending,(t,n)=>{t.fetchState="loading",t.agentInfo={...t.agentInfo,...n.meta.arg}}).addCase(Na.rejected,t=>{t.fetchState="error"}).addCase(Na.fulfilled,(t,n)=>{t.fetchState="done",t.agentInfo={...t.agentInfo,...n.meta.arg,agentDefaultLocale:n.payload.defaultLocale,agentId:n.payload.externalId||n.meta.arg.agentId||"",agentNickname:n.payload.nickname||n.meta.arg.agentNickname||""}}).addCase(qg.fulfilled,(t,n)=>{t.agentSettings=n.payload}).addCase(Gg.fulfilled,(t,n)=>{t.agentSettings=n.payload}).addCase(le,t=>{t.visitorInfo=void 0})}}),{setVisitorInfo:M1,setCustomData:N1}=O1.actions,_1=O1.reducer;var nd={list:[],fetchState:"idle",isOpen:!1,page:"search",aggregates:{}},D1=e=>e.search.isOpen,F1=e=>e.search.page,H1=e=>e.search.list,U1=e=>e.search.aggregates;function z1(e,t=n=>n){return n=>n.search.list.filter(r=>r.type===e).map(t)}var Ao=B("search/getAll",async(e,t)=>{var a;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=(a=r.conversation.current)==null?void 0:a.profileCode;if(!o)throw new Error("Profile should be provided in order to be able to search");let{results:i,aggregates:s}=await 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(l=>({...l,source:`search-${l.type.toLowerCase()}`,searchTerm:e.query})),aggregates:s}}),B1=G({name:"search",initialState:nd,reducers:{setIsOpen(e,t){e.isOpen=t.payload},setPage(e,t){e.page=t.payload},resetSearch(e){e.fetchState=nd.fetchState,e.list=nd.list}},extraReducers:e=>{e.addCase(Ao.pending,t=>{t.fetchState="loading"}).addCase(Ao.rejected,(t,n)=>{t.fetchState="error",F.error(n.error)}).addCase(Ao.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload.results,t.aggregates=n.payload.aggregates||{}}).addCase(le,()=>nd)}}),{resetSearch:rd,setIsOpen:xt,setPage:Jt}=B1.actions,j1=B1.reducer;var Xg="SetCues",Yi="ShowLoginOverlay",Da="UserLoggedIn",iI="UserLoggedOut",$r="ApplySuggestion",Yg="ApplyImageSuggestion",sI="ShowCommandPalette",aI=e=>({[Xg]:t=>{e.dispatch({...t,isBroadcasted:!0})},[sI]:t=>{e.dispatch(xt(t.isOpen)),t.page&&e.dispatch(Jt(t.page))},[Yi]:t=>{e.dispatch(o1(t))},[Da]:()=>{e.dispatch(Vn())},[iI]:()=>{e.dispatch(Vn())},[Yg]:t=>{e.dispatch(td({suggestion:t.suggestion}))},[$r]:t=>{e.dispatch(Cn({...t,eventMetrics:{inputType:"mouse"},replace:"selection"})),e.dispatch(Wn())}}),V1=aI;var Fa=x(_()),W1=x(C()),K1=Fa.default.createContext(null),Lo=({broadcastEvents:e,children:t})=>{let n=Fa.default.useMemo(()=>e,[]);return(0,W1.jsx)(K1.Provider,{value:n,children:t})},Bt=()=>{let e=(0,Fa.useContext)(K1);if(!e)throw new Error("You should use the useBroadcastEvents within a BroadcastEventsProvider");return e};var xd=x(te()),tn=x(_());var yd=x(_());var Qg=function(e,t){return Qg=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])},Qg(e,t)};function Ha(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");Qg(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var wt=function(){return wt=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},wt.apply(this,arguments)};function $1(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 od(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,i;r<o;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))}var id;(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"})(id||(id={}));var sd=class{constructor(t){console.warn(`[vite-messages-plugin]: Message "${t}" was not precompiled. Did you use the correct extenstion *.messages.ts?`)}};var en;(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"})(en||(en={}));var ad;(function(e){e[e.number=0]="number",e[e.dateTime=1]="dateTime"})(ad||(ad={}));function Zg(e){return e.type===en.literal}function q1(e){return e.type===en.argument}function ld(e){return e.type===en.number}function ud(e){return e.type===en.date}function cd(e){return e.type===en.time}function dd(e){return e.type===en.select}function fd(e){return e.type===en.plural}function G1(e){return e.type===en.pound}function pd(e){return e.type===en.tag}function md(e){return!!(e&&typeof e=="object"&&e.type===ad.number)}function Ua(e){return!!(e&&typeof e=="object"&&e.type===ad.dateTime)}function Jg(e){e.forEach(function(t){if(delete t.location,dd(t)||fd(t))for(var n in t.options)delete t.options[n].location,Jg(t.options[n].value);else ld(t)&&md(t.style)||(ud(t)||cd(t))&&Ua(t.style)?delete t.style.location:pd(t)&&Jg(t.children)})}function X1(e,t){t===void 0&&(t={}),t=wt({shouldParseSkeletons:!0,requiresOtherClause:!0},t);var n=new sd(e,t).parse();if(n.err){var r=SyntaxError(id[n.err.kind]);throw r.location=n.err.location,r.originalMessage=n.err.message,r}return t!=null&&t.captureLocation||Jg(n.val),n.val}function gd(e,t){var n=t&&t.cache?t.cache:pI,r=t&&t.serializer?t.serializer:fI,o=t&&t.strategy?t.strategy:uI;return o(e,{cache:n,serializer:r})}function lI(e){return e==null||typeof e=="number"||typeof e=="boolean"}function Y1(e,t,n,r){var o=lI(r)?r:n(r),i=t.get(o);return typeof i>"u"&&(i=e.call(this,r),t.set(o,i)),i}function Q1(e,t,n){var r=Array.prototype.slice.call(arguments,3),o=n(r),i=t.get(o);return typeof i>"u"&&(i=e.apply(this,r),t.set(o,i)),i}function eh(e,t,n,r,o){return n.bind(t,e,r,o)}function uI(e,t){var n=e.length===1?Y1:Q1;return eh(e,this,n,t.cache.create(),t.serializer)}function cI(e,t){return eh(e,this,Q1,t.cache.create(),t.serializer)}function dI(e,t){return eh(e,this,Y1,t.cache.create(),t.serializer)}var fI=function(){return JSON.stringify(arguments)};function th(){this.cache=Object.create(null)}th.prototype.get=function(e){return this.cache[e]};th.prototype.set=function(e,t){this.cache[e]=t};var pI={create:function(){return new th}},hd={variadic:cI,monadic:dI};var Io;(function(e){e.MISSING_VALUE="MISSING_VALUE",e.INVALID_VALUE="INVALID_VALUE",e.MISSING_INTL_API="MISSING_INTL_API"})(Io||(Io={}));var za=function(e){Ha(t,e);function t(n,r,o){var i=e.call(this,n)||this;return i.code=r,i.originalMessage=o,i}return t.prototype.toString=function(){return"[formatjs Error: ".concat(this.code,"] ").concat(this.message)},t}(Error);var nh=function(e){Ha(t,e);function t(n,r,o,i){return e.call(this,'Invalid values for "'.concat(n,'": "').concat(r,'". Options are "').concat(Object.keys(o).join('", "'),'"'),Io.INVALID_VALUE,i)||this}return t}(za);var Z1=function(e){Ha(t,e);function t(n,r,o){return e.call(this,'Value for "'.concat(n,'" must be of type ').concat(r),Io.INVALID_VALUE,o)||this}return t}(za);var J1=function(e){Ha(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,'"'),Io.MISSING_VALUE,r)||this}return t}(za);var Ye;(function(e){e[e.literal=0]="literal",e[e.object=1]="object"})(Ye||(Ye={}));function mI(e){return e.length<2?e:e.reduce(function(t,n){var r=t[t.length-1];return!r||r.type!==Ye.literal||n.type!==Ye.literal?t.push(n):r.value+=n.value,t},[])}function gI(e){return typeof e=="function"}function Ba(e,t,n,r,o,i,s){if(e.length===1&&Zg(e[0]))return[{type:Ye.literal,value:e[0].value}];for(var a=[],l=0,u=e;l<u.length;l++){var c=u[l];if(Zg(c)){a.push({type:Ye.literal,value:c.value});continue}if(G1(c)){typeof i=="number"&&a.push({type:Ye.literal,value:n.getNumberFormat(t).format(i)});continue}var p=c.value;if(!(o&&p in o))throw new J1(p,s);var d=o[p];if(q1(c)){(!d||typeof d=="string"||typeof d=="number")&&(d=typeof d=="string"||typeof d=="number"?String(d):""),a.push({type:typeof d=="string"?Ye.literal:Ye.object,value:d});continue}if(ud(c)){var m=typeof c.style=="string"?r.date[c.style]:Ua(c.style)?c.style.parsedOptions:void 0;a.push({type:Ye.literal,value:n.getDateTimeFormat(t,m).format(d)});continue}if(cd(c)){var m=typeof c.style=="string"?r.time[c.style]:Ua(c.style)?c.style.parsedOptions:r.time.medium;a.push({type:Ye.literal,value:n.getDateTimeFormat(t,m).format(d)});continue}if(ld(c)){var m=typeof c.style=="string"?r.number[c.style]:md(c.style)?c.style.parsedOptions:void 0;m&&m.scale&&(d=d*(m.scale||1)),a.push({type:Ye.literal,value:n.getNumberFormat(t,m).format(d)});continue}if(pd(c)){var v=c.children,y=c.value,g=o[y];if(!gI(g))throw new Z1(y,"function",s);var f=Ba(v,t,n,r,o,i),h=g(f.map(function(T){return T.value}));Array.isArray(h)||(h=[h]),a.push.apply(a,h.map(function(T){return{type:typeof T=="string"?Ye.literal:Ye.object,value:T}}))}if(dd(c)){var S=c.options[d]||c.options.other;if(!S)throw new nh(c.value,d,Object.keys(c.options),s);a.push.apply(a,Ba(S.value,t,n,r,o));continue}if(fd(c)){var S=c.options["=".concat(d)];if(!S){if(!Intl.PluralRules)throw new za(`Intl.PluralRules is not available in this environment.
|
|
14
14
|
Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
15
15
|
`,Io.MISSING_INTL_API,s);var w=n.getPluralRules(t,{type:c.pluralType}).select(d-(c.offset||0));S=c.options[w]||c.options.other}if(!S)throw new nh(c.value,d,Object.keys(c.options),s);a.push.apply(a,Ba(S.value,t,n,r,o,d-(c.offset||0)));continue}}return mI(a)}function hI(e,t){return t?wt(wt(wt({},e||{}),t||{}),Object.keys(e).reduce(function(n,r){return n[r]=wt(wt({},e[r]),t[r]||{}),n},{})):e}function yI(e,t){return t?Object.keys(e).reduce(function(n,r){return n[r]=hI(e[r],t[r]),n},wt({},e)):e}function rh(e){return{create:function(){return{get:function(t){return e[t]},set:function(t,n){e[t]=n}}}}}function vI(e){return e===void 0&&(e={number:{},dateTime:{},pluralRules:{}}),{getNumberFormat:gd(function(){for(var t,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];return new((t=Intl.NumberFormat).bind.apply(t,od([void 0],n,!1)))},{cache:rh(e.number),strategy:hd.variadic}),getDateTimeFormat:gd(function(){for(var t,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];return new((t=Intl.DateTimeFormat).bind.apply(t,od([void 0],n,!1)))},{cache:rh(e.dateTime),strategy:hd.variadic}),getPluralRules:gd(function(){for(var t,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];return new((t=Intl.PluralRules).bind.apply(t,od([void 0],n,!1)))},{cache:rh(e.pluralRules),strategy:hd.variadic})}}var eE=function(){function e(t,n,r,o){n===void 0&&(n=e.defaultLocale);var i=this;if(this.formatterCache={number:{},dateTime:{},pluralRules:{}},this.format=function(u){var c=i.formatToParts(u);if(c.length===1)return c[0].value;var p=c.reduce(function(d,m){return!d.length||m.type!==Ye.literal||typeof d[d.length-1]!="string"?d.push(m.value):d[d.length-1]+=m.value,d},[]);return p.length<=1?p[0]||"":p},this.formatToParts=function(u){return Ba(i.ast,i.locales,i.formatters,i.formats,u,void 0,i.message)},this.resolvedOptions=function(){var u;return{locale:((u=i.resolvedLocale)===null||u===void 0?void 0:u.toString())||Intl.NumberFormat.supportedLocalesOf(i.locales)[0]}},this.getAst=function(){return i.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 s=o||{},a=s.formatters,l=$1(s,["formatters"]);this.ast=e.__parse(t,wt(wt({},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=yI(e.formats,r),this.formatters=o&&o.formatters||vI(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>"u")){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=X1,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 SI(e,t){return t.split(".").reduce((n,r)=>n?n[r]:void 0,e)}var xI="dummy",oh=(0,yd.createContext)(null);function K(e){let t=(0,yd.useContext)(oh);if(!t)throw new Error("useTranslator() may be used only in the context of a <LocaleContext> component.");let n=e[t]??{};return(r,o)=>{let i=SI(n,r);return i?new eE(i).format(o):(t!==xI&&console.warn(`${r} does not exist in messages of ${t}`),`[${r}]`)}}var vd=x(_());var tE={root:"dd-tvkOF",content:"dd-eXA1D"};var ih=x(C()),wI=({isOpen:e,autoFocus:t,children:n,onClose:r,onBack:o,onKeyDown:i,overlayAriaLabel:s,contentAriaLabel:a})=>{let l=(0,vd.useRef)(null),u=P("Dialog",tE),c=d=>{if(d.key==="Escape"){d.preventDefault(),d.stopPropagation(),o();return}i&&i(d)},p=d=>{d.target===l.current&&e&&r()};return(0,vd.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,ih.jsx)("div",{role:"dialog","data-testid":"dialog",className:u.root,"aria-label":s,ref:l,onKeyDown:c,onMouseDown:p,children:(0,ih.jsx)("div",{"data-testid":"dialog-content",className:u.content,"aria-label":a,children:n})}):null},Sd=wI;var rE=x(te());var nE={root:"dd-ranhW"};var oE=x(C()),EI=({className:e,value:t,...n})=>{let r=P("TextInput",nE);return(0,oE.jsx)("input",{className:(0,rE.default)(e,r.root),type:"text",value:t,...n})},ja=EI;var sh={};je(sh,{enUS:()=>CI,nlNL:()=>bI});var CI={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"}]},bI={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 iE={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 Te=x(C());var TI=e=>{try{let t=new URL(e);return new URLSearchParams(t.search).get("token")||void 0}catch{return e}},kI=({agentEmail:e,isOpen:t,origin:n="",onSuccess:r,onDismiss:o})=>{let i=K(sh),s=P("LoginTokenDialog",iE),a=L(e1),l=$(),u=z("productName"),[c,p]=(0,tn.useState)(e||""),[d,m]=(0,tn.useState)(0),[v,y]=(0,tn.useState)(""),g=(0,tn.useCallback)(async w=>{w.preventDefault(),l(n1({email:c})),m(1)},[n,c]),f=()=>{y(""),m(0)},h=(0,tn.useCallback)(async w=>{w.preventDefault();let T=TI(w.target.elements.token.value);if(!T){y(i("verifyCodeError",{login:S}));return}l(Ia({token:T}))},[n]),S=(0,tn.useMemo)(()=>w=>(0,Te.jsx)("button",{type:"button","data-testid":"login-token-dialog-back-button",className:s.anchorButton,onClick:f,children:w},"back-button"),[]);return(0,tn.useEffect)(()=>{a==="error"&&y(i("verifyCodeError",{login:S})),a==="done"&&r()},[a]),(0,Te.jsx)(Sd,{autoFocus:!0,isOpen:t,contentAriaLabel:i("promptTitle",{productName:u}),overlayAriaLabel:i("promptTitle",{productName:u}),onClose:o,onBack:o,children:(0,Te.jsxs)("div",{className:s.root,children:[(0,Te.jsx)("h1",{className:s.title,children:i("promptTitle",{productName:u})}),d===0&&(0,Te.jsxs)("form",{onSubmit:g,children:[(0,Te.jsx)("h2",{className:s.subtitle,children:i("requestCodeTitle")}),(0,Te.jsx)("p",{className:s.text,children:i("requestCodeBody",{productName:u})}),(0,Te.jsx)(ja,{className:s.input,name:"email",placeholder:i("requestCodeInputPlaceholder"),value:c,onChange:w=>p(w.target.value)}),(0,Te.jsx)("div",{className:s.actions,children:(0,Te.jsx)("button",{type:"submit",className:(0,xd.default)(s.button,s.primaryButton),children:i("requestCodeSubmitLabel")})})]}),d===1&&(0,Te.jsxs)("form",{onSubmit:h,children:[(0,Te.jsx)("h2",{className:s.subtitle,children:i("verifyCodeTitle")}),(0,Te.jsx)("p",{className:s.text,children:i("verifyCodeBody")}),(0,Te.jsx)(ja,{className:s.input,name:"token",placeholder:i("verifyCodeInputPlaceholder"),disabled:["loading","done"].includes(a)}),v&&(0,Te.jsx)("div",{className:s.errorMessage,children:v}),(0,Te.jsxs)("div",{className:s.actions,children:[(0,Te.jsx)("button",{type:"button",className:(0,xd.default)(s.button),onClick:f,children:i("back")}),(0,Te.jsx)("button",{type:"submit",className:(0,xd.default)(s.button,s.primaryButton),disabled:["loading","done"].includes(a),children:i("verifyCodeSubmitLabel")})]})]})]})})},sE=kI;var lE=x(C()),PI=()=>{let e=L(t1),t=L(L1),n=z("adminUrl"),r=Bt(),o=()=>r.send(Yi,!1),i=()=>{r.send(Yi,!1),r.send(Da)};return(0,lE.jsx)(sE,{isOpen:e,agentEmail:t==null?void 0:t.agentEmail,origin:n,onDismiss:o,onSuccess:i})},aE=PI;var CC=x(uh()),Ct=x(_());var WI={data:null,fetchState:"idle"},fE=e=>e.contentTypes.data,Va=B("contentTypes/getContentTypes",async(e,t)=>t.extra.deepdeskAPI.getContentTypes()),$I=G({name:"contentTypes",initialState:WI,reducers:{},extraReducers:e=>{e.addCase(Va.pending,t=>{t.fetchState="loading"}).addCase(Va.rejected,t=>{t.fetchState="error"}).addCase(Va.fulfilled,(t,n)=>{t.fetchState="done",t.data=n.payload})}}),pE=$I.reducer;function $n(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 Yn=x(_());var mE=x(_()),wd=x(te());var Et={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",listItemPrimaryAction:"dd-LdJ8w",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 qn={};je(qn,{enUS:()=>qI,nlNL:()=>GI});var qI={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"}]},GI={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=x(C()),XI=({src:e,title:t})=>{let n=P("CommandPalette",Et),[r,o]=(0,mE.useState)("loading"),i=K(qn);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,wd.default)(n.imageSrc,{[n.imageSrcHidden]:["loading","error"].includes(r)})}),r==="loading"&&(0,qr.jsx)("span",{className:(0,wd.default)(n.imageSrc,n.imageSrcStatus),children:i("loading")}),r==="error"&&(0,qr.jsx)("span",{className:(0,wd.default)(n.imageSrc,n.imageSrcStatus),children:(0,qr.jsx)(jl,{})}),t&&(0,qr.jsx)("span",{className:n.imageTitle,children:t})]})},gE=XI;var hE=x(_()),yE=x(te());var Oo=x(C());function ch({children:e,heading:t,orientation:n,hasMore:r,onShowAll:o}){let i=K(qn),s=P("CommandPalette",Et);return hE.default.Children.count(e)===0?null:(0,Oo.jsxs)("div",{"data-testid":"commandpalette-list",className:s.list,children:[(t||r)&&(0,Oo.jsxs)("div",{className:s.listHeader,children:[t&&(0,Oo.jsx)("h4",{className:s.listHeading,children:t}),r&&o&&(0,Oo.jsx)("button",{onClick:o,className:s.listMoreButton,type:"button",children:i("showAll")})]}),(0,Oo.jsx)("div",{className:(0,yE.default)(s.listWrapper,n==="horizontal"&&s.listHorizontal),children:e})]})}var Ji=x(te());var Ed=x(_());function Ka(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var oe=1,fh=2,ph=4,Ae=8,Cd=16,Wa=32,nn=64,dh={a:{content:oe|Ae,self:!1,type:oe|Ae|Wa|nn},address:{invalid:["h1","h2","h3","h4","h5","h6","address","article","aside","section","div","header","footer"],self:!1},audio:{children:["track","source"]},br:{type:oe|Ae,void:!0},body:{content:oe|fh|ph|Ae|Cd|Wa|nn},button:{content:Ae,type:oe|Ae|Wa|nn},caption:{content:oe,parent:["table"]},col:{parent:["colgroup"],void:!0},colgroup:{children:["col"],parent:["table"]},details:{children:["summary"],type:oe|Wa|nn},dd:{content:oe,parent:["dl"]},dl:{children:["dt","dd"],type:oe},dt:{content:oe,invalid:["footer","header"],parent:["dl"]},figcaption:{content:oe,parent:["figure"]},footer:{invalid:["footer","header"]},header:{invalid:["footer","header"]},hr:{type:oe,void:!0},img:{void:!0},li:{content:oe,parent:["ul","ol","menu"]},main:{self:!1},ol:{children:["li"],type:oe},picture:{children:["source","img"],type:oe|Ae|Cd},rb:{parent:["ruby","rtc"]},rp:{parent:["ruby","rtc"]},rt:{content:Ae,parent:["ruby","rtc"]},rtc:{content:Ae,parent:["ruby"]},ruby:{children:["rb","rp","rt","rtc"]},source:{parent:["audio","video","picture"],void:!0},summary:{content:Ae,parent:["details"]},table:{children:["caption","colgroup","thead","tbody","tfoot","tr"],type:oe},tbody:{parent:["table"],children:["tr"]},td:{content:oe,parent:["tr"]},tfoot:{parent:["table"],children:["tr"]},th:{content:oe,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:oe},video:{children:["track","source"]},wbr:{type:oe|Ae,void:!0}};function No(e){return t=>{dh[t]={...e,...dh[t]}}}["address","main","div","figure","p","pre"].forEach(No({content:oe,type:oe|nn}));["abbr","b","bdi","bdo","cite","code","data","dfn","em","i","kbd","mark","q","ruby","samp","strong","sub","sup","time","u","var"].forEach(No({content:Ae,type:oe|Ae|nn}));["p","pre"].forEach(No({content:Ae,type:oe|nn}));["s","small","span","del","ins"].forEach(No({content:Ae,type:oe|Ae}));["article","aside","footer","header","nav","section","blockquote"].forEach(No({content:oe,type:oe|fh|nn}));["h1","h2","h3","h4","h5","h6"].forEach(No({content:Ae,type:oe|ph|nn}));["audio","canvas","iframe","img","video"].forEach(No({type:oe|Ae|Cd|nn}));var qa=Object.freeze(dh),mh=["applet","base","body","command","embed","frame","frameset","head","html","link","meta","noscript","object","script","style","title"],gh=Object.keys(qa).filter(e=>e!=="canvas"&&e!=="iframe"),ue=1,hh=2,Mo=3,Gr=4,Td=5,kd=Object.freeze({alt:ue,cite:ue,class:ue,colspan:Mo,controls:Gr,datetime:ue,default:Gr,disabled:Gr,dir:ue,height:ue,href:ue,id:ue,kind:ue,label:ue,lang:ue,loading:ue,loop:Gr,media:ue,muted:Gr,poster:ue,rel:ue,role:ue,rowspan:Mo,scope:ue,sizes:ue,span:Mo,start:Mo,style:Td,src:ue,srclang:ue,srcset:ue,tabindex:ue,target:ue,title:ue,type:ue,width:ue}),yh=Object.freeze({class:"className",colspan:"colSpan",datetime:"dateTime",rowspan:"rowSpan",srclang:"srcLang",srcset:"srcSet",tabindex:"tabIndex"});function bd(){return bd=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},bd.apply(this,arguments)}function Pd({attributes:e={},className:t,children:n=null,selfClose:r=!1,tagName:o}){let i=o;return r?Ed.default.createElement(i,bd({className:t},e)):Ed.default.createElement(i,bd({className:t},e),n)}var $a=class{attribute(t,n){return n}node(t,n){return n}};function vE(e,t,n,r=!1){let o=e.match(t instanceof RegExp?t:new RegExp(t,"i"));return o?{match:o[0],void:r,...n(o),index:o.index,length:o[0].length,valid:!0}:null}var Gn=class{constructor(t,n,r){Ka(this,"greedy",!1),Ka(this,"options",void 0),Ka(this,"propName",void 0),Ka(this,"inverseName",void 0),Ka(this,"factory",void 0),this.options={...n},this.propName=t,this.inverseName=`no${t.charAt(0).toUpperCase()+t.slice(1)}`,this.factory=r??null}createElement(t,n){return this.factory?Ed.default.createElement(this.factory,n,t):this.replaceWith(t,n)}doMatch(t,n,r,o=!1){return vE(t,n,r,o)}onBeforeParse(t,n){return t}onAfterParse(t,n){return t}};var _o=x(_()),EE=x(xE());function Xn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var ZI=/(url|image|image-set)\(/i,vh=class extends $a{attribute(t,n){return t==="style"&&Object.keys(n).forEach(r=>{String(n[r]).match(ZI)&&delete n[r]}),n}},wE=1,JI=3,eO=/^<(!doctype|(html|head|body)(\s|>))/i,tO=/^(aria-|data-|\w+:)/iu,nO=/{{{(\w+)\/?}}}/;function rO(){if(!(typeof window>"u"||typeof document>"u"))return document.implementation.createHTMLDocument("Interweave")}var Rd=class{constructor(t,n={},r=[],o=[]){var i;Xn(this,"allowed",void 0),Xn(this,"banned",void 0),Xn(this,"blocked",void 0),Xn(this,"container",void 0),Xn(this,"content",[]),Xn(this,"props",void 0),Xn(this,"matchers",void 0),Xn(this,"filters",void 0),Xn(this,"keyIndex",void 0),this.props=n,this.matchers=r,this.filters=[...o,new vh],this.keyIndex=-1,this.container=this.createContainer(t||""),this.allowed=new Set((i=n.allowList)!==null&&i!==void 0?i:gh),this.banned=new Set(mh),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,i=t,s=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 p="";for(;i&&(a=l.match(i));){let{index:d,length:m,match:v,valid:y,void:g,...f}=a,h=l.propName+String(s);d>0&&(p+=i.slice(0,d)),y?(p+=g?`{{{${h}/}}}`:`{{{${h}}}}${v}{{{/${h}}}}`,this.keyIndex+=1,s+=1,r[h]={children:v,matcher:l,props:{...o,...f,key:this.keyIndex}}):p+=v,l.greedy?(i=p+i.slice(d+m),p=""):i=i.slice(d+(m||v.length))}l.greedy||(i=p+i)}),s===0?t:this.replaceTokens(i,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
|
`+st),qt&&df([W,X,ne],so=>{st=pl(st,so," ")}),S&&Ml?S.createHTML(st):st},t.setConfig=function(){let U=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Lf(U),Il=!0},t.clearConfig=function(){ei=null,Il=!1},t.isValidAttribute=function(U,E,A){ei||Lf({});let D=Oe(U),ce=Oe(E);return Wy(D,ce,A)},t.addHook=function(U,E){typeof E=="function"&&(M[U]=M[U]||[],fl(M[U],E))},t.removeHook=function(U){if(M[U])return aT(M[U])},t.removeHooks=function(U){M[U]&&(M[U]=[])},t.removeAllHooks=function(){M={}},t}var vT=yT();var no=x(_());var yN={"":["<em>","</em>"],_:["<strong>","</strong>"],"*":["<strong>","</strong>"],"~":["<s>","</s>"],"\n":["<br />"]," ":["<br />"],"-":["<hr />"]};function ST(e){return e.replace(RegExp("^"+(e.match(/^(\t| )+/)||"")[0],"gm"),"")}function gl(e){return(e+"").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function hl(e,t){var n,r,o,i,s,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||{},p=0;function d(v){var y=yN[v[1]||""],g=l[l.length-1]==v;return y?y[1]?(g?l.pop():l.push(v),y[0|g]):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,g){return c[y.toLowerCase()]=g,""}).replace(/^\n+|\n+$/g,"");o=a.exec(e);)r=e.substring(p,o.index),p=a.lastIndex,n=o[0],r.match(/[^\\](\\\\)*\\$/)||((s=o[3]||o[4])?n='<pre class="code '+(o[4]?"poetry":o[2].toLowerCase())+'"><code'+(o[2]?' class="language-'+o[2].toLowerCase()+'"':"")+">"+ST(gl(s).replace(/^\n+|\n+$/g,""))+"</code></pre>":(s=o[6])?(s.match(/\./)&&(o[5]=o[5].replace(/^\d+/gm,"")),i=hl(ST(o[5].replace(/^\s*[>*+.-]/gm,""))),s==">"?s="blockquote":(s=s.match(/\./)?"ol":"ul",i=i.replace(/^(.*)(\n|$)/gm,"<li>$1</li>")),n="<"+s+">"+i+"</"+s+">"):o[8]?n='<img src="'+gl(o[8])+'" alt="'+gl(o[7])+'">':o[10]?(u=u.replace("<a>",'<a href="'+gl(o[11]||c[r.toLowerCase()])+'">'),n=m()+"</a>"):o[9]?n="<a>":o[12]||o[14]?n="<"+(s="h"+(o[14]?o[14].length:o[13]>"="?1:2))+">"+hl(o[12]||o[15],c)+"</"+s+">":o[16]?n="<code>"+gl(o[16])+"</code>":(o[17]||o[1])&&(n=d(o[17]||"--"))),u+=r,u+=n;return(u+e.substring(p)+m()).replace(/^\n+|\n+$/g,"")}var xT={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 Pn=x(C());function vN(e){return`<button type="button" 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 hy(e){let t=e.cloneNode(!0);return t.querySelectorAll("div,button").forEach(n=>n.remove()),t.textContent??""}function SN(e){return e.replace(/\r\n/g,`
|
|
25
25
|
`)}var xN=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let i=P("Markdown",xT),s=(0,no.useRef)(null),[a,l]=(0,no.useState)(null),u=(0,no.useMemo)(()=>{let y=hl(SN(e));return vT.sanitize(y).replace(/<\/code>/g,`${vN(i.copyIcon)}</code>`)},[e]),c=y=>{var h;let g=y.target,f=!!((h=s.current)!=null&&h.querySelector("code"));a||f&&g.tagName!=="CODE"||!f&&g!==s.current||(g.addEventListener("mouseleave",()=>l(null),{once:!0}),l(g))},p=()=>{if(!a)return;l(null);let y=a.querySelector("button");y&&(ns(y,i.fadeup),r(hy(a)))},d=y=>{y.target.tagName.toLowerCase()==="button"&&(ns(y.target,i.fadeup),r(hy(y.target.parentElement)))},m=()=>{a&&(l(null),o(hy(a)))},v=y=>{if(y===null)return;let g=y.getBoundingClientRect();g.left<0?y.style.transform=`translateX(${-g.left+2}px)`:g.right>window.innerWidth&&(y.style.transform=`translateX(${window.innerWidth-g.right-2}px)`)};return(0,Pn.jsxs)(no.Fragment,{children:[a&&(0,Pn.jsxs)(ps,{triggerRef:{current:a},className:i.popover,parentNode:a,children:[(0,Pn.jsxs)("div",{className:i.options,ref:v,children:[(0,Pn.jsx)("button",{type:"button",className:i.option,onClick:p,children:n}),(0,Pn.jsx)("div",{className:i.divider}),(0,Pn.jsx)("button",{type:"button",className:i.option,onClick:m,children:t})]}),(0,Pn.jsx)("div",{className:i.arrow})]}),(0,Pn.jsx)("div",{ref:s,className:i.root,dangerouslySetInnerHTML:{__html:u},onMouseOver:c,onClick:d})]})},wT=xN;var yy={};je(yy,{enUS:()=>wN,nlNL:()=>EN});var wN={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"}]},EN={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 ET={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",thumbsUp:"dd-6QwVx",thumbsDown:"dd-d3E8l"};var cn=x(C()),CN=({cue:e,onRemove:t,onCopy:n,onUse:r})=>{let o=P("WidgetCue",ET),i=K(yy),s=rs(),a=c=>{n&&n(c,e)},l=c=>{r&&r(c,e)},u=c=>{c.preventDefault(),c.stopPropagation(),t(e)};return(0,CT.useEffect)(()=>{s("Assistant response displayed",{name:e.rule.name,description:e.rule.description,group:e.rule.label,cueText:e.text})},[]),(0,cn.jsxs)(ee,{"data-testid":"cue",children:[(0,cn.jsx)(pe,{children:(0,cn.jsxs)(pe.Content,{children:[e.title&&(0,cn.jsx)(pe.Title,{className:o.title,"data-testid":"widget-cue-title",children:e.title}),(0,cn.jsx)(wT,{content:e.text,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:a,onUse:l})]})}),(0,cn.jsxs)(ee.IconButtonContainer,{children:[(0,cn.jsx)(is,{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"}),(0,cn.jsx)(ee.IconButton,{title:i("removeCue"),onClick:u,icon:(0,cn.jsx)(iT,{})})]})]})},bT=CN;var yl=x(C()),bN=({cues:e})=>{let t=$(),n=Bt(),r=rs(),o=a=>{t(zb({id:a.rule.id})),r("Assistant response closed",{name:a.rule.name,group:a.rule.label,description:a.rule.description,cueText:a.text})},i=(a,l)=>{$n(a),r("Assistant response copied",{name:l.rule.name,group:l.rule.label,description:l.rule.description,copiedText:a})},s=(a,l)=>{n.send($r,{text:a,suggestion:{source:"cue",sourceText:a}}),r("Assistant response used",{name:l.rule.name,group:l.rule.label,description:l.rule.description,usedText:a})};return(0,yl.jsx)(yl.Fragment,{children:e.map(a=>(0,yl.jsx)(bT,{cue:a,onRemove:o,onCopy:i,onUse:s},a.rule.id))})},TT=bN;var gf=x(_());var kT={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var dn=x(C());function TN(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var PT=({data:e,schema:t})=>{let n=P("WidgetCustomData",kT),r=o=>{$n(o)};return(0,gf.useEffect)(()=>{F.info("Custom data",e,t)},[e]),(0,dn.jsx)("dl",{className:n.root,children:t.map(o=>{let i=TN(e,o.path);return(0,dn.jsxs)(gf.Fragment,{children:[(0,dn.jsx)("dt",{className:n.label,children:o.label}),(0,dn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&i?(0,dn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!i?(0,dn.jsx)("span",{className:n.isFalse,children:o.falseValue}):i?(0,dn.jsxs)("button",{type:"button",onClick:()=>r(i),className:n.copyButton,children:[(0,dn.jsx)("span",{children:i}),(0,dn.jsx)(cl,{})]}):"-"})]},o.label)})})};var AT=x(_());var kN=/(https?:\/\/[^\s]+)/,RT=e=>e.split(" ").find(t=>kN.test(t));var Wt=x(C()),PN=({suggestion:e,lines:t,onUse:n})=>{var c;let r=e.text||e.url||e.message,o=RT(r),i=K(zo),s=z("showImages"),a=z("fallbackImage"),l=p=>{p.preventDefault(),p.stopPropagation(),n(r)},u=(0,AT.useCallback)(p=>{window.open(o,"_blank"),p.stopPropagation(),p.preventDefault()},[o]);return(0,Wt.jsxs)(ee,{onClick:l,"data-testid":"edit-suggestion",children:[(0,Wt.jsxs)(pe,{children:[s&&e.image&&(0,Wt.jsx)(pe.Image,{src:rf(e,"small",a||void 0),title:e.title}),(0,Wt.jsxs)(pe.Content,{children:[e.title&&(0,Wt.jsx)(pe.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((c=e.searchKeywords)==null?void 0:c.length)>0&&(0,Wt.jsx)(ee.Labels,{labels:e.searchKeywords}),(0,Wt.jsx)(pe.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,Wt.jsxs)(ee.Actions,{children:[o&&(0,Wt.jsx)(ee.ActionButton,{onClick:u,label:i("visitUrl")}),(0,Wt.jsx)(ee.ActionButton,{primary:!0,onClick:l,label:i("useSuggestion")})]})]})},LT=PN;var vl=x(C()),RN=({lines:e,suggestions:t})=>{let n=Bt(),r=(o,i)=>{n.send($r,{text:o,suggestion:{...i,source:i.source,sourceText:i.text}})};return(0,vl.jsx)(vl.Fragment,{children:t.map(o=>(0,vl.jsx)(LT,{suggestion:o,lines:e,onUse:i=>r(i,o)},o.text||o.url||o.message))})},IT=RN;var Sl={};je(Sl,{enUS:()=>AN,nlNL:()=>LN});var AN={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"}]},LN={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 xl={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",sectionList:"dd-bF9pF",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",link:"dd-DRo0x"};var V=x(C()),hf=(e,t)=>{let n=L(Je);(0,wl.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},IN=({onLogIn:e})=>{let t=P("Widget",xl),n=z("isEmbedded"),r=z("adminUrl");return(0,V.jsx)("div",{className:t.loginText,children:(0,V.jsx)("div",{children:(0,V.jsx)(Kd,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},OT=({text:e})=>{let t=P("Widget",xl);return(0,V.jsx)("div",{className:t.stateText,children:(0,V.jsx)("div",{children:(0,V.jsx)("p",{children:e})})},"notification")},ON=()=>{let e=K(Sl),t=$(),n=P("Widget",xl),r=z("showSearch"),o=z("showSummaryCommand"),i=z("showKnowledgeSearch"),s=L(os("/admin/")),a=Bt(),l=z("productName"),u=r||o||i||s;return hf(()=>(t(Jh()),()=>{t(_b())}),[t]),u?(0,V.jsx)(pn,{title:e("actions"),type:"shortcuts",children:(0,V.jsxs)("div",{className:n.shortcutList,children:[r&&(0,V.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-search","aria-label":e("linkSearch"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0}),children:[(0,V.jsx)(es,{}),e("linkSearch")]}),o&&(0,V.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-summary","aria-label":e("linkSummary"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,V.jsx)(oT,{}),e("linkSummary")]}),i&&(0,V.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-knowledge-assist","aria-label":e("linkKnowledgeSearch"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,V.jsx)(rT,{}),e("linkKnowledgeSearch")]}),s&&(0,V.jsxs)("a",{className:n.shortcut,target:"_blank",href:s,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:l}),rel:"noreferrer",children:[(0,V.jsx)(nT,{}),e("linkStudioLogin",{productName:l})]})]})}):null},MN=()=>{let e=$(),t=z("showCustomMessages"),n=L(kb),r=L(qi);return hf(()=>(e(ul(r)),e(Ib(r)),()=>{e(Ob(r))}),[e,t,r]),!t||n.length===0?null:(0,V.jsx)(pn,{type:"custom-messages","data-testid":"custom-messages",children:(0,V.jsx)(ct,{withDivider:!0,children:n.map(o=>(0,V.jsx)(Jb,{suggestion:o},o.text))})})},NN=()=>{let e=K(Sl),t=$(),n=z("showAutoflows"),r=L(wb),o=L(qi);return hf(()=>(t(sr(o)),t(Eb(o)),()=>{t(Cb(o))}),[t,n,o]),!n||r.length===0?null:(0,V.jsx)(pn,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:(0,V.jsx)(ct,{withDivider:!0,children:(0,V.jsx)(Qb,{})})})},_N=()=>{let e=$(),t=L(Nd),n=L(sC),r=L(Hb),o=L(I1),i=L(Od),s=L(_d),a=L(er),l=L(Vr);return(0,wl.useEffect)(()=>{!!o&&!n&&F.warn("Custom data provided, but no schema.")},[o,n]),hf(()=>{t.forEach(({type:u})=>{u==="entities"?e(on()):Yl.includes(u)||e(an(u))})},[e,l,a]),(0,V.jsx)(wl.Fragment,{children:t.map(({type:u,title:c,amount:p,lines:d,schema:m})=>{var v,y;switch(u){case"entities":return i&&i.length>0&&(0,V.jsx)(pn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,V.jsx)(tT,{entities:i})},u);case"cues":return r&&r.length>0&&(0,V.jsx)(pn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,V.jsx)(ct,{withDivider:!0,children:(0,V.jsx)(TT,{cues:r})})},u);case"custom-data":return o&&m&&(0,V.jsx)(pn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,V.jsx)(ct,{withDivider:!0,children:(0,V.jsx)(PT,{data:o,schema:m})})},u);default:return((y=(v=s[u])==null?void 0:v.suggestions)==null?void 0:y.length)>0&&(0,V.jsx)(pn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,V.jsx)(ct,{withDivider:!0,children:(0,V.jsx)(IT,{lines:d,contentType:u,suggestions:s[u].suggestions.slice(0,p)||[]})})},u)}})})},DN=({onLogIn:e})=>{let t=K(Sl),n=P("Widget",xl),r=L(Gi),o=L(Je),i=L(qi),s=L(er);return r===!1?(0,V.jsx)(OT,{text:t("notSupported")}):o===!1?(0,V.jsx)(IN,{onLogIn:e}):!s||!i||o===null?(0,V.jsx)(OT,{text:t("waiting")}):(0,V.jsx)("div",{className:(0,MT.default)(n.root),"data-testid":"widget",children:(0,V.jsxs)(ql,{className:n.sectionList,children:[(0,V.jsx)(ON,{}),(0,V.jsx)(MN,{}),(0,V.jsx)(NN,{}),(0,V.jsx)(_N,{})]})})},NT=DN;function ms(e){let t=new Range;return t.selectNodeContents(e),t}function _T(e,t,n){try{return ro(e,t,n),!0}catch{return!1}}function yf(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function vf(e){return"tagName"in e&&e.tagName==="BR"}var El=/[\u200B-\u200D\uFEFF]/g;function ro(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,i=!1;function s(l,u){let c=-1,p=/[\u200B-\u200D\uFEFF]/;if(!p.test(l))return u;for(let d=0;d<=l.length;d++)if(p.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(El,""),p=o+c.length,d=t>=o&&t<=p,m=n>=o&&n<=p;if(d){let v=s(u,t-o);v===0&&!m?r.setStartBefore(l):r.setStart(l,v)}m&&(r.setEnd(l,s(u,n-o)),i=!0),o=p;break}case Node.ELEMENT_NODE:{if(vf(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),i=!0;return}for(let c=0;c<l.childNodes.length&&(a(l.childNodes[c]),!i);c++);let u=l.lastChild;yf(l)&&u&&!yf(u)&&!vf(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function Cl(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:i,collapsed:s}=t,a,l,u=0;function c(p){let d=p===n,m=p===o;switch(p.nodeType){case Node.TEXT_NODE:{let v=p.textContent;d&&(a=u+v.substring(0,r).replace(El,"").length),m&&(l=u+v.substring(0,i).replace(El,"").length),u+=v.replace(El,"").length;break}case Node.ELEMENT_NODE:{let v=p.nextSibling===null;vf(p)&&!v&&u++;for(let y=0;y<p.childNodes.length;y++){let g=d&&y===r,f=m&&y===i;if(g&&(a=u),f&&(l=u),l!==void 0||((!g||!s)&&c(p.childNodes[y]),m&&y===i-1&&(l=u),l!==void 0))break}!m&&yf(p)&&!v&&u++,m&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a??l,end:l}}function bl(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:i}=t,s=-1,a="";function l(u){let c=u===n,p=u===o;switch(c&&s++,u.nodeType){case Node.TEXT_NODE:{if(s!==0)return;let d=c?r:0,m=p?i:void 0,v=u.textContent.replace(El,"");d===0&&m===void 0?a+=v:a+=v.substring(d,m);break}case Node.ELEMENT_NODE:{let d=u.nextSibling===null;s===0&&vf(u)&&!d&&(a+=`
|
|
26
26
|
`);for(let m=c?r:0;m<(p?Math.min(i,u.childNodes.length):u.childNodes.length)&&(l(u.childNodes[m]),s!==1);m++);!p&&s===0&&yf(u)&&!d&&(a+=`
|
|
27
|
-
`);break}default:break}p&&s++}return l(e),a}var DT=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(DT||{}),lr=class{constructor(t){this.element=t;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(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)}triggerChange(){let t=this.getText(),n=this.getHTML(),r=t!==this.currentText;this.isActive&&(t===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&r&&!this.isSubmitting&&this.emit("change",{plainText:t}),r&&(this.currentSelection=this.getSelection()),this.currentText=t,this.isSubmitting=!1,(this.currentHTML!==n||n===null&&r)&&(this.emit("updated",{plainText:t}),this.triggerCaretPosition(),this.currentHTML=n))}triggerSelection(){let t=this.getSelection();(t.start!==this.currentSelection.start||t.end!==this.currentSelection.end)&&(this.currentSelection=t,this.emit("selection",t),this.triggerCaretPosition())}triggerCaretPosition(){let t=this.getCaretPosition();jr(t,this.currentCaret)||(this.currentCaret=t,this.emit("caret",t))}handleKeyUp(t){let{key:n,shiftKey:r}=t;(n==="Enter"&&r===!0||n==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(DT).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",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(t={shouldObserve:!0}){this.addEventListener("keydown",r=>this.handleKeyDown(r)),this.addEventListener("keyup",r=>this.handleKeyUp(r)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",r=>this.handlePaste(r)),this.addEventListener("click",()=>this.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let n=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t!=null&&t.shouldObserve&&n.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{n.disconnect()}),this.currentSelection=this.getSelection()}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.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function FT(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var qo=class extends lr{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),bl(this.element,t)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let t=this.getRootNode();if(t.activeElement!==this.element)return null;let n="getSelection"in t?t.getSelection():window.getSelection();if(!n)return null;let r="getComposedRanges"in n&&t instanceof ShadowRoot?(i=n.getComposedRanges(t))==null?void 0:i[0]:n.rangeCount>0?n.getRangeAt(0):null;if(!r)return null;let o=this.element.ownerDocument.createRange();return o.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),o.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!o||!this.element.contains(o.startContainer)||!this.element.contains(o.endContainer)?null:o}getCaretPosition(){let t=this.getRange();if(!t||!t.collapsed||!("getBoundingClientRect"in t))return null;let n=t.getBoundingClientRect();return!FT(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!FT(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return Cl(this.element,t);let n=this.lastKnownSelection;if(n&&_T(this.element,n.start,n.end))return n;let r=ms(this.element);return r.collapse(!1),Cl(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return bl(this.element,ro(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(t={shouldObserve:!0}){super.listen(t),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),t!=null&&t.shouldObserve&&this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let n=this.element.isContentEditable,r=new MutationObserver(()=>{this.element.isContentEditable!==n&&(n=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>r.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var Go=class extends lr{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:t,selectionEnd:n}=this.element;return{start:t,end:n}}getSelectedText(){let t=this.getSelection();return t?this.getText().slice(t.start,t.end):""}getCaretPosition(){return null}applyChanges(t){if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let t=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var o;return(o=t==null?void 0:t.get)==null?void 0:o.call(this.element)},set:o=>{var i;(i=t==null?void 0:t.set)==null||i.call(this.element,o),this.triggerChange()}});let n=this.element.disabled,r=new MutationObserver(()=>{this.element.disabled!==n&&(n=this.element.disabled,this.emit(n?"disabled":"enabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>r.disconnect())}};function HT(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function FN(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}var vy=class{constructor(t){this.name=t;this.broadcastChannel=new BroadcastChannel(t)}broadcastChannel;disposeHandlers=[];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()}},Sy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=HT(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];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()}},xy=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),F.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 Sy(t,this.deepdeskUrl,{debug:!0}):new vy(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=FN(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(F.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;F.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage({...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)}},UT=xy;var gs=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var wy=e=>new Promise(t=>{setTimeout(t,e)});var hs=class extends gs{name="ClientError"},Cy=class extends gs{name="ServerError"},Ey=new Map;async function HN(e){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=await e.text();return n===""?null:(F.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))}var fn=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",{useCache:u=!1,abortLatest:c=!1,attempts:p=1,retryDelay:d=500,refreshTokenOn401:m=!0,retryOnError:v=b=>b instanceof TypeError,retryOnResponse:y=b=>b.status>=500,version:g="v1",...f}=n;if(u)if(l){if(Ey.has(s)){r(Ey.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h={credentials:"include",...f,headers:{"Content-Type":"application/json",...f.headers}};!l&&this.csrfToken&&(h.headers={...h.headers,"X-CSRFToken":this.csrfToken}),typeof g=="string"&&(h.headers={...h.headers,"X-Deepdesk-API-Version":g});let S=p,w=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&c&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let T=async()=>(S--,a(s,h).then(async b=>y(b)&&!i.isAborted&&S>0?(await wy(d),T()):b.status===401&&m===!0&&w===!1?(w=!0,await this.refreshToken(),T()):b).catch(async b=>{if(v(b)&&!i.isAborted&&S>0)return await wy(d),T();throw b}));T().then(async b=>{let k=await HN(b);if(delete this.latestRequestByUrl[s],b.status>=500){o(new Cy("Server Error",k));return}else if(b.status===401){o(new hs("Unauthorized",k));return}else if(b.status===403){o(new hs("Forbidden",k));return}else if(b.status===404){o(new hs("Not Found",k));return}else if(b.status>=400){o(new hs("Bad Request",k));return}u&&Ey.set(s,k),r(k)}).catch(b=>{o(b)})})}async validateToken(){let{has_valid_access_token:t}=await this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return e.refreshingToken||(e.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{e.refreshingToken=null},1e3*60)})),e.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,{method:"POST",body:JSON.stringify(n),...r})}patch(t,n,r){return this.request(t,{method:"PATCH",body:JSON.stringify(n),...r})}put(t,n,r){return this.request(t,{method:"PUT",body:JSON.stringify(n),...r})}delete(t,n){return this.request(t,{method:"DELETE",...n})}};var UN;(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||={})})(UN||={});function Sf(e){return{...J(e),tags:e.tags}}var ur=class e{constructor(t,n={}){this.options=n;this.client=new fn(t,{fetch:n.fetch}),this.client.patchFetch(r=>async(o,i)=>{let s=await r(o,i);return this.handleDeepdeskVersionHeaders(s),s})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=await this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(e.exchangeTokenPromise||(e.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),e.exchangeTokenPromise):Promise.resolve()}async createConversation(t){await this.preflight(),F.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...Re(t),tags:t.tags},{version:"v2"});return Sf(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null,useCache:!0});return J(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null,useCache:!0});return J(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return J(t)}async getAccount(){let t=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return J(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null,useCache:!0});return J(t)}async checkUserExists(t){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n}async getConversationBySessionId(t,n={}){await this.preflight(),F.info(`Getting conversation for session ${t}`);let{attempts:r=1,retryDelay:o=1e3}=n,i=await this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"});return F.info(`Successfully retrieved conversation ${i.id} for session ${t}`),Sf(i)}async isConversationSupported(t,n={}){F.info(`Check if conversation for session ${t} is supported`);let{attempts:r=1,retryDelay:o=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"})).has_active_profile}async updateConversation(t,n){let r=Re(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Sf(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...Re(o),tags:o.tags})),{version:"v2"})).map(o=>Sf(o))}async sendEvent(t,n){let{data:r,...o}=n,i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[a,l])=>({...s,[a]:l}),{});return this.client.post("/api/events",Re({...i,...o,data:r,name:t}),{version:"v2"})}async sendEventV1(t,n){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>({...o,[i]:s}),{});return this.client.post("/api/events",{event:t,data:Re({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){let r=await this.client.post("/api/summary",{conversation:{messages:t.filter(o=>o.text&&o.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model});return J(r)}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(t){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw F.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.preflight(),await this.client.post("/apis/admin/session/api-key/",Re(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})}async getTextSuggestions(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(await this.client.post(`/api/conversations/${t}/recommend/${r}`,Re(n),{abortLatest:!0})).map(i=>({...J(i),text:i.text||i.url||i.message,source:r,type:r})).filter((i,s,a)=>s===a.findIndex(l=>l.text===i.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(t,n){return(await this.client.post(`/api/conversations/${t}/autocomplete`,Re(n),{abortLatest:!0})).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,i,s)=>i===s.findIndex(a=>a.text===o.text))}async getPinnedMessages(t){let n=await this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return J(n).map(r=>({...r,text:r.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(t){let n=await this.client.post("/api/style-suggestions",Re(t),{abortLatest:!0});return J(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,Re(t),{version:"v2"});return J(n)}async knowledgeAssist(t,n,r,o={}){let i=await this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Re({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(s=>({question:s.question,answer:s.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return J(i)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return J(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return J(t.token)}async getCsrfToken(){let{token:t}=await this.client.get("/apis/admin/session/csrf/",{version:null});return t}async verifyLoginToken(t){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return J(n)}async evaluateRule(t,n,r,o={}){let i=new URLSearchParams;o.raiseForFailingConditions&&i.set("raise_for_failing_conditions","true");let s=await this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${i.toString()}`,r,{version:"v2"});return J(s.cues)}async getRules(){let t=new URLSearchParams,n=await this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{version:null,useCache:!0});return J(n)}async translateMessages(t){let n=await this.client.post("/api/translate",Re(t),{version:"v2"});return J(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Uv);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&F.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var Tl=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener($g(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,J(o))}catch{F.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 zN;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(zN||={});var kl=class{constructor(t,n={}){this.apiUrl=t;this.client=new fn(t,n)}client;streams={};logger=F;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return J(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,Re(n));return J(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,Re(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return J(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",Re(t));return J(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new Tl(`${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 zT={startTime:null,stopTime:null},BT=G({name:"handlingTime",initialState:zT,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(le,()=>zT)}}),{handlingTimeStart:jT,handlingTimeStop:xf,handlingTimeReset:VT}=BT.actions,KT=BT.reducer;var WT=(e={})=>{let t={onAuthError:$i(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var wf={list:{keywordMatches:[]},fetchState:"idle"};var Xo=B("styleSuggestions/getAll",async({text:e},t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),{showStyleSuggestions:o}=r.settings,i=(s=r.conversation.current)==null?void 0:s.profileCode;if(!o)return wf.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),BN=G({name:"styleSuggestions",initialState:wf,reducers:{},extraReducers:e=>{e.addCase(Xo.pending,t=>{t.fetchState="loading"}).addCase(Xo.rejected,t=>{t.fetchState="error"}).addCase(Xo.fulfilled,(t,n)=>{t.fetchState="done",jr(t.list,n.payload)||(t.list=n.payload)}).addCase(Ro,t=>{t.list=wf.list}).addCase(le,()=>wf)}}),$T=BN.reducer;var qT=(e={})=>{let t,n=!0,r={getStyleSuggestions:Xo,debounce:500,...e};return o=>i=>s=>{var m;let a=o.getState().input.text,l=i(s),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 jN(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var GT=(e={})=>{let t={getTextSuggestions:an,getAutocompleteSuggestions:rl,debounce:200,check:as,...e},n;return r=>o=>i=>{var y;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,p=(y=l.conversation.current)==null?void 0:y.id,d=i.type===Dd.toString();if(!p||!u&&!c)return a;let{input:{userCommitted:m}}=l;return jN(m,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let g=Xi(l);g===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(g))},d?0:t.debounce)),a}};var XT=Xo.fulfilled.toString();function VN(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var YT=e=>t=>n=>r=>{var u;if(r.type!==XT){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=VN(o,s);r.type===XT&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var KN=hc({answer:rC,auth:i1,autoflows:bb,conversation:m1,contentTypes:pE,customMessages:Mb,passwordlessToken:Db,entities:HE,knowledgeAssistant:eC,handlingTime:KT,info:_1,input:A1,settings:Zw,profile:aC,search:j1,summary:WE,styleSuggestions:$T,ui:DC,rules:Bb,textSuggestions:gC});function QT(e){return ow({reducer:KN,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),WT(),GT({debounce:200}),qT({debounce:500}),YT(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var WN=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},$N=e=>t=>n=>r=>{var a,l,u,c,p,d;let o=t.getState(),i=Ug("inlineSuggestions")(o);switch(r.type){case $i.toString():{!r.payload&&e.emit("logout",void 0);break}case on.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 et.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 Jc.toString():e.handleKeyDown(r.payload);break;case Ro.toString():e.logSendMessage(r.payload);break;case ed.toString():e.handleInputChanged(r.payload);break;case Wo.fulfilled.toString():r.isBroadcasted||e.broadcast(Xg,r,!1),(c=r.payload.options)!=null&&c.shouldEmit&&e.emit("cues",r.payload.cues);break;default:break}let s=n(r);switch(r.type){case Ro.toString():e.handleAfterSendMessage(r.payload);break;case il.toString():e.onUpdateShowTabHint(r.payload);break;case xf.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case Cn.toString():{let{start:m,end:v}=o.input.selection;e.emit("select-suggestion",{type:WN(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:m,end:v}:{start:0,end:v}},{mayApplyChanges:!0}),i&&(t.dispatch(En([])),t.dispatch(Wn()));break}case Zc.toString():{let{start:m,end:v}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:m,end:v}:{start:0,end:v}},{mayApplyChanges:!0});break}case Ma.toString():{let m=t.getState(),{text:v,selection:y}=m.input.userCommitted;e.emit("reset",{text:v,selectionAfter:y},{mayApplyChanges:!0});break}case td.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:(p=o.conversation.current)==null?void 0:p.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case En.toString():{i&&r.payload.length>0&&t.dispatch(Wr(0));break}case Qn.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(d=o.conversation.current)==null?void 0:d.id,data:{summary:r.payload.summary,model:t.getState().summary.model}});break}default:break}return s},ZT=$N;function by(e){return e.toISOString().replace("T"," ").replace("Z","")}function JT(e,t){var i,s,a,l;let n=(i=e.conversation.current)==null?void 0:i.id;if(!n)return F.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:o}=e.handlingTime;return!r||!o?(F.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:n,clientVersion:t.version,agentId:(s=e.info.agentInfo)==null?void 0:s.agentId,agentName:(a=e.info.agentInfo)==null?void 0:a.agentName,agentEmail:(l=e.info.agentInfo)==null?void 0:l.agentEmail,timeStart:by(r),timeStop:by(o)}}function ek(e,t,n){var I,O,M,W;let r=(I=t.conversation.current)==null?void 0:I.id;if(!r)return F.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:i,numCharsPasted:s,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:d,cuts:m,deletions:v,textSuggestions:y,offeredTextSuggestions:g}}=t[e],f=o.length,S=y.reduce((X,{text:ne,searchTerm:cr})=>X+ne.length-(cr?cr.length:0),0),w=c??Date.now(),T=(Date.now()-w)/1e3+(p||0),b=i/T,k=y.reduce((X,{searchTerm:ne})=>X+(ne?ne.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:m,deletions:v,lenTextTyped:i+k,lenTextTotal:f,lenTextAssisted:S,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:T,charsPerSecond:b,numPastes:u,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:g.filter(X=>X.source==="gpt").length}],agentId:(O=t.info.agentInfo)==null?void 0:O.agentId,agentName:(M=t.info.agentInfo)==null?void 0:M.agentName,agentEmail:(W=t.info.agentInfo)==null?void 0:W.agentEmail}}function Ty(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Ty(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Ty(o,t):null}function tk(e,t){return Ty(e,t)}function nk(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function qN(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Ef(e){return qN(e)&&(Jr(e)||$d(e))}var ok,Rn=new Map,GN=["bottom","height","left","right","top","width"],rk=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:GN.some(n=>e[n]!==t[n]);function ik(e){var n,r;if(e.ownerDocument===document)return[];let t=((r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)??null;return t?[t,...ik(t)]:[]}function sk(e,t){return!e||!t?null:{...e,top:e.top+t.top,left:e.left+t.left}}var Cf=!1,ak=()=>{Cf=!0;let e=[];if(Rn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Rn.delete(n);return}let r=n.getBoundingClientRect();rk(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(sk,t.rect):t.rect;rk(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Rn.size===0){Cf=!1;return}ok=window.requestAnimationFrame(ak)};function ky(e,t){let n=ik(e),r=[],o=n.map((i,s)=>ky(i,a=>{r[s]=a;let l=Rn.get(e);if(!l)return;let u=r.reduce(sk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Rn.has(e)){let s=Rn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Rn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!Cf&&ak()},unobserve(){o.forEach(s=>s.unobserve());let i=Rn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Rn.delete(e),Rn.size||(cancelAnimationFrame(ok),Cf=!1)}}}}var lk,An=new Map,uk=()=>{An.forEach((e,t)=>{if(!t.isConnected){An.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),An.size!==0&&(lk=window.requestAnimationFrame(uk))};function ck(e,t){return{observe(){let n=An.size===0;An.has(e)?An.get(e).callbacks.push(t):An.set(e,{visible:void 0,callbacks:[t]}),n&&uk()},unobserve(){let n=An.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||An.delete(e),An.size||cancelAnimationFrame(lk)}}}}var Py=["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 Ry(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function ys(e){return parseFloat(e)}function bf(e){return Math.round(e*1e6)}function dk(e){return e/1e6}function Ay(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=ys(e.width),i=ys(e.borderLeftWidth),s=ys(e.borderRightWidth),a=ys(e.paddingRight),l=dk(bf(o)-bf(i)-bf(s)),u=dk(bf(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function Pl(e,t={}){var c;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=t.position??"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",jo(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};Ry(r,n,Py),Ay(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=ck(e,()=>{Ry(r,n,Py),Ay(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=ky(e,p=>{if(p===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),p.height===0&&p.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(Ry(r,n,Py),Ay(r,e,n),i(),n.style.top=`${p.top}px`,n.style.left=`${p.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let d=t.closestScrollElement.getBoundingClientRect(),m=window.getComputedStyle(t.closestScrollElement),v=ys(m.borderTopWidth),y=ys(m.borderBottomWidth),g=d.top+v-p.top,f=p.top+p.height+-(d.top+d.height-y);n.style.clipPath=`inset(${g}px 0px ${f}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(c=e.parentElement)==null||c.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var fk=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch{return t}}catch{return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch{F.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function XN(e){return e.offsetParent!==null}function pk(e){if(!XN(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 Tf(e,t,n=100){let r=pk(e);t({isVisible:r});let o=setInterval(()=>{let i=pk(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Ie=x(C());var mk=fk("showTabHint",!0),Rl=class e{static version="11.6.1-beta.2";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new ur(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[ZT({broadcast:(p,d,m)=>{this.broadcastEvents.send(p,d,m)},emit:(p,d,m)=>this.emit(p,d,m),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),onUpdateShowTabHint:p=>mk.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new kl(n)}),this.store=QT(c),this.broadcastEvents=new UT({debug:!0,deepdeskUrl:u,eventMap:V1(this.store),createCustomChannel:l}),this.store.dispatch(il(mk.value())),this.store.dispatch(Wc({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(F.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(F.warn("Profile has not been loaded (yet)"),!0):(F.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch($i(null)),this.store.dispatch(Vn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();Je(r)&&Jw(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(Vn())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){F.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Vg({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(qc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(Gc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Kg(t))).payload}async postMessages(t){return(await this.store.dispatch(Yc(t))).payload}async updateConversation(t){return(await this.store.dispatch(Xc(t))).payload}resetConversation(){this.store.dispatch(le()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(Qn());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(Wc(t))}setVisitorInfo(t){this.store.dispatch(M1(t))}setCustomData(t){this.store.dispatch(N1(t))}async setAgentInfo(t){await this.store.dispatch(Na(t))}async setAgentSettings(t){await this.store.dispatch(qg(t))}async getAgentSettings(){return(await this.store.dispatch(Gg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(Dd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(ed(t))}notifyKeyDown(t){this.store.dispatch(Jc(t))}notifyPaste(t,n){this.store.dispatch(T1({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(C1(t))}notifyExternalSuggestion(t){this.store.dispatch(Cn(t)),this.store.dispatch(Wn())}async evaluateRule(t,n={},r=Fb){return(await this.store.dispatch(Wo({label:t,params:n,options:r}))).payload.cues}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(Qr({collapse:!1})),this.inputMediator&&this.store.dispatch(v1({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(En([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(b1(g1(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(x1()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(E1()),t.preventDefault(),!s&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Ma()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(Wr(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Wr(-1)),this.store.dispatch(Ma()),t.preventDefault()):n||(this.store.dispatch(Qr({collapse:!0})),this.store.dispatch(NC(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:m}=this.state.input;this.store.dispatch(il(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&m&&m.text.startsWith(d)&&(this.store.dispatch(Cn({text:m.text,suggestion:m,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(Wn())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(k1()),this.store.dispatch(En([]))}handlingTimeStart(){this.state.handlingTime.startTime||(F.info("Start handling time"),this.store.dispatch(jT()))}handlingTimeStop(){this.state.handlingTime.startTime&&(F.info("Stop handling time"),this.store.dispatch(xf()))}logSendMessage(t){let n=ek("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=JT(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(VT()))}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(Wn()),this.store.dispatch(Ro(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Cn({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{let i=this.eventListeners[t];i&&i.forEach(s=>{try{s(n)}catch(a){F.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),F.error(a)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=Pl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,$t.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=Pl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,$t.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return jo(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,$t.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),F.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(F.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(R1(r.metrics))):F.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Ef(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:d,insertLink:m,inputMediator:v,closestScrollSelector:y,appendOverlayTo:g,inlineSuggestions:f,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:m,isEmbedded:p,inlineSuggestions:f,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),jo(t),this.inputMediator=v||(Jr(t)?new Go(t):new qo(t)),this.inputMediator.on("change",({plainText:T})=>{this.notifyInputChanged(T)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(P1({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",T=>{this.notifyKeyDown(T)}),this.inputMediator.on("paste",({pastedText:T,selectionText:b})=>{this.notifyPaste(T,b)}),this.inputMediator.on("cut",({selectionText:T})=>{this.notifyCut(T)});let S=y&&tk(t,y)||void 0;if(f){let{customStyles:T,appendOverlayTo:b}=n;if(Jr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let k=this.createInlineContainer(t,"deepdesk-caret");(0,$t.render)((0,Ie.jsx)(Ko,{store:this.store,customStyles:T,children:(0,Ie.jsx)(Lo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(jC,{})})}),k),this.inputMediator.on("caret",O=>{this.store.dispatch(En([])),O?(k.style.display="block",k.style.top=`${O.top}px`,k.style.left=`${O.left}px`):k.style.display="none"});let I=this.overlayContainerFactory("floating-menu",S||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:b},T==null?void 0:T.floatingMenuRootNode);(0,$t.render)((0,Ie.jsx)(Ko,{store:this.store,customStyles:T,children:(0,Ie.jsx)(Lo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(IC,{onLogIn:()=>this.loginViaPopup().catch(O=>F.warn(O.message))})})}),I)}else{let T=this.overlayContainerFactory("deepdesk-tab-completion",S||t,{appendTo:g,closestScrollElement:S,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),b=this.overlayContainerFactory("deepdesk-suggestions-overlay",S||t,{appendTo:g},r==null?void 0:r.suggestionsRootNode);(0,$t.render)((0,Ie.jsx)(Ko,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Lo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(vb,{inputElement:t})})}),T),(0,$t.render)((0,Ie.jsx)(Ko,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Lo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(QC,{onLogIn:()=>this.loginViaPopup().catch(k=>F.warn(k.message))})})}),b)}(0,$t.render)((0,Ie.jsx)(Ko,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Lo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(kC,{})})}),this.createContainer("deepdesk-overlays"));let w;this.inputMediator.on("selection",T=>{clearTimeout(w),T===null?w=setTimeout(()=>{T!==null&&this.store.dispatch(Wg(T))},500):this.store.dispatch(Wg(T))}),this.inputMediator.on("disabled",()=>{var T;(T=this.inputMediator)==null||T.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(Dh(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Dh(!0))),this.store.dispatch(S1({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(Wn()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var T;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((T=this.state.conversation.current)==null?void 0:T.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&&F.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,$t.render)((0,Ie.jsx)(Ko,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Lo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(NT,{onLogIn:()=>this.loginViaPopup().catch(s=>F.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,$t.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Tf(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){nk(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(nl());let t=er(this.state);t&&(await this.store.dispatch(Ja()),this.store.dispatch(Wc({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(t){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};i.onmessage=async m=>{var v,y;if((v=m.data)!=null&&v.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((y=m.data)==null?void 0:y.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Da),l=!0,o.port1.close(),n()}catch(g){console.error(g),r(g)}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 p=async m=>{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){F.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-error":{u(),m.data.message==="Timeout"&&F.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(m.data.message));break}}};window.addEventListener("message",p);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)}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(F.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;F.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Nd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(on()):Yl.includes(r)||this.store.dispatch(an(r))})}catch(r){this.handleError(r)}}};async function gk(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function hk(e,t,n={}){let r=n.replace?ro(e,n.replace.start,n.replace.end):ms(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
|
|
27
|
+
`);break}default:break}p&&s++}return l(e),a}var DT=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(DT||{}),lr=class{constructor(t){this.element=t;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(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)}triggerChange(){let t=this.getText(),n=this.getHTML(),r=t!==this.currentText;this.isActive&&(t===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&r&&!this.isSubmitting&&this.emit("change",{plainText:t}),r&&(this.currentSelection=this.getSelection()),this.currentText=t,this.isSubmitting=!1,(this.currentHTML!==n||n===null&&r)&&(this.emit("updated",{plainText:t}),this.triggerCaretPosition(),this.currentHTML=n))}triggerSelection(){let t=this.getSelection();(t.start!==this.currentSelection.start||t.end!==this.currentSelection.end)&&(this.currentSelection=t,this.emit("selection",t),this.triggerCaretPosition())}triggerCaretPosition(){let t=this.getCaretPosition();jr(t,this.currentCaret)||(this.currentCaret=t,this.emit("caret",t))}handleKeyUp(t){let{key:n,shiftKey:r}=t;(n==="Enter"&&r===!0||n==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(DT).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",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(t={shouldObserve:!0}){this.addEventListener("keydown",r=>this.handleKeyDown(r)),this.addEventListener("keyup",r=>this.handleKeyUp(r)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",r=>this.handlePaste(r)),this.addEventListener("click",()=>this.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let n=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t!=null&&t.shouldObserve&&n.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{n.disconnect()}),this.currentSelection=this.getSelection()}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.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function FT(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var qo=class extends lr{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),bl(this.element,t)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let t=this.getRootNode();if(t.activeElement!==this.element)return null;let n="getSelection"in t?t.getSelection():window.getSelection();if(!n)return null;let r="getComposedRanges"in n&&t instanceof ShadowRoot?(i=n.getComposedRanges(t))==null?void 0:i[0]:n.rangeCount>0?n.getRangeAt(0):null;if(!r)return null;let o=this.element.ownerDocument.createRange();return o.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),o.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!o||!this.element.contains(o.startContainer)||!this.element.contains(o.endContainer)?null:o}getCaretPosition(){let t=this.getRange();if(!t||!t.collapsed||!("getBoundingClientRect"in t))return null;let n=t.getBoundingClientRect();return!FT(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!FT(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return Cl(this.element,t);let n=this.lastKnownSelection;if(n&&_T(this.element,n.start,n.end))return n;let r=ms(this.element);return r.collapse(!1),Cl(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return bl(this.element,ro(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(t={shouldObserve:!0}){super.listen(t),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),t!=null&&t.shouldObserve&&this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let n=this.element.isContentEditable,r=new MutationObserver(()=>{this.element.isContentEditable!==n&&(n=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>r.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var Go=class extends lr{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:t,selectionEnd:n}=this.element;return{start:t,end:n}}getSelectedText(){let t=this.getSelection();return t?this.getText().slice(t.start,t.end):""}getCaretPosition(){return null}applyChanges(t){if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let t=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var o;return(o=t==null?void 0:t.get)==null?void 0:o.call(this.element)},set:o=>{var i;(i=t==null?void 0:t.set)==null||i.call(this.element,o),this.triggerChange()}});let n=this.element.disabled,r=new MutationObserver(()=>{this.element.disabled!==n&&(n=this.element.disabled,this.emit(n?"disabled":"enabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>r.disconnect())}};function HT(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function FN(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}var vy=class{constructor(t){this.name=t;this.broadcastChannel=new BroadcastChannel(t)}broadcastChannel;disposeHandlers=[];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()}},Sy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=HT(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];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()}},xy=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),F.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 Sy(t,this.deepdeskUrl,{debug:!0}):new vy(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=FN(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(F.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;F.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage({...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)}},UT=xy;var gs=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var wy=e=>new Promise(t=>{setTimeout(t,e)});var hs=class extends gs{name="ClientError"},Cy=class extends gs{name="ServerError"},Ey=new Map;async function HN(e){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=await e.text();return n===""?null:(F.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))}var fn=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",{useCache:u=!1,abortLatest:c=!1,attempts:p=1,retryDelay:d=500,refreshTokenOn401:m=!0,retryOnError:v=b=>b instanceof TypeError,retryOnResponse:y=b=>b.status>=500,version:g="v1",...f}=n;if(u)if(l){if(Ey.has(s)){r(Ey.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h={credentials:"include",...f,headers:{"Content-Type":"application/json",...f.headers}};!l&&this.csrfToken&&(h.headers={...h.headers,"X-CSRFToken":this.csrfToken}),typeof g=="string"&&(h.headers={...h.headers,"X-Deepdesk-API-Version":g});let S=p,w=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&c&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let T=async()=>(S--,a(s,h).then(async b=>y(b)&&!i.isAborted&&S>0?(await wy(d),T()):b.status===401&&m===!0&&w===!1?(w=!0,await this.refreshToken(),T()):b).catch(async b=>{if(v(b)&&!i.isAborted&&S>0)return await wy(d),T();throw b}));T().then(async b=>{let k=await HN(b);if(delete this.latestRequestByUrl[s],b.status>=500){o(new Cy("Server Error",k));return}else if(b.status===401){o(new hs("Unauthorized",k));return}else if(b.status===403){o(new hs("Forbidden",k));return}else if(b.status===404){o(new hs("Not Found",k));return}else if(b.status>=400){o(new hs("Bad Request",k));return}u&&Ey.set(s,k),r(k)}).catch(b=>{o(b)})})}async validateToken(){let{has_valid_access_token:t}=await this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return e.refreshingToken||(e.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{e.refreshingToken=null},1e3*60)})),e.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,{method:"POST",body:JSON.stringify(n),...r})}patch(t,n,r){return this.request(t,{method:"PATCH",body:JSON.stringify(n),...r})}put(t,n,r){return this.request(t,{method:"PUT",body:JSON.stringify(n),...r})}delete(t,n){return this.request(t,{method:"DELETE",...n})}};var UN;(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||={})})(UN||={});function Sf(e){return{...J(e),tags:e.tags}}var ur=class e{constructor(t,n={}){this.options=n;this.client=new fn(t,{fetch:n.fetch}),this.client.patchFetch(r=>async(o,i)=>{let s=await r(o,i);return this.handleDeepdeskVersionHeaders(s),s})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=await this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(e.exchangeTokenPromise||(e.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),e.exchangeTokenPromise):Promise.resolve()}async createConversation(t){await this.preflight(),F.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...Re(t),tags:t.tags},{version:"v2"});return Sf(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null,useCache:!0});return J(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null,useCache:!0});return J(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return J(t)}async getAccount(){let t=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return J(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null,useCache:!0});return J(t)}async checkUserExists(t){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n}async getConversationBySessionId(t,n={}){await this.preflight(),F.info(`Getting conversation for session ${t}`);let{attempts:r=1,retryDelay:o=1e3}=n,i=await this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"});return F.info(`Successfully retrieved conversation ${i.id} for session ${t}`),Sf(i)}async isConversationSupported(t,n={}){F.info(`Check if conversation for session ${t} is supported`);let{attempts:r=1,retryDelay:o=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"})).has_active_profile}async updateConversation(t,n){let r=Re(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Sf(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...Re(o),tags:o.tags})),{version:"v2"})).map(o=>Sf(o))}async sendEvent(t,n){let{data:r,...o}=n,i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[a,l])=>({...s,[a]:l}),{});return this.client.post("/api/events",Re({...i,...o,data:r,name:t}),{version:"v2"})}async sendEventV1(t,n){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>({...o,[i]:s}),{});return this.client.post("/api/events",{event:t,data:Re({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){let r=await this.client.post("/api/summary",{conversation:{messages:t.filter(o=>o.text&&o.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model});return J(r)}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(t){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw F.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.preflight(),await this.client.post("/apis/admin/session/api-key/",Re(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})}async getTextSuggestions(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(await this.client.post(`/api/conversations/${t}/recommend/${r}`,Re(n),{abortLatest:!0})).map(i=>({...J(i),text:i.text||i.url||i.message,source:r,type:r})).filter((i,s,a)=>s===a.findIndex(l=>l.text===i.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(t,n){return(await this.client.post(`/api/conversations/${t}/autocomplete`,Re(n),{abortLatest:!0})).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,i,s)=>i===s.findIndex(a=>a.text===o.text))}async getPinnedMessages(t){let n=await this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return J(n).map(r=>({...r,text:r.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(t){let n=await this.client.post("/api/style-suggestions",Re(t),{abortLatest:!0});return J(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,Re(t),{version:"v2"});return J(n)}async knowledgeAssist(t,n,r,o={}){let i=await this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Re({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(s=>({question:s.question,answer:s.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return J(i)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return J(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return J(t.token)}async getCsrfToken(){let{token:t}=await this.client.get("/apis/admin/session/csrf/",{version:null});return t}async verifyLoginToken(t){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return J(n)}async evaluateRule(t,n,r,o={}){let i=new URLSearchParams;o.raiseForFailingConditions&&i.set("raise_for_failing_conditions","true");let s=await this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${i.toString()}`,r,{version:"v2"});return s?J(s.cues):[]}async getRules(){let t=new URLSearchParams,n=await this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{version:null,useCache:!0});return J(n)}async translateMessages(t){let n=await this.client.post("/api/translate",Re(t),{version:"v2"});return J(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Uv);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&F.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var Tl=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener($g(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,J(o))}catch{F.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 zN;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(zN||={});var kl=class{constructor(t,n={}){this.apiUrl=t;this.client=new fn(t,n)}client;streams={};logger=F;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return J(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,Re(n));return J(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,Re(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return J(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",Re(t));return J(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new Tl(`${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 zT={startTime:null,stopTime:null},BT=G({name:"handlingTime",initialState:zT,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(le,()=>zT)}}),{handlingTimeStart:jT,handlingTimeStop:xf,handlingTimeReset:VT}=BT.actions,KT=BT.reducer;var WT=(e={})=>{let t={onAuthError:$i(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var wf={list:{keywordMatches:[]},fetchState:"idle"};var Xo=B("styleSuggestions/getAll",async({text:e},t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),{showStyleSuggestions:o}=r.settings,i=(s=r.conversation.current)==null?void 0:s.profileCode;if(!o)return wf.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),BN=G({name:"styleSuggestions",initialState:wf,reducers:{},extraReducers:e=>{e.addCase(Xo.pending,t=>{t.fetchState="loading"}).addCase(Xo.rejected,t=>{t.fetchState="error"}).addCase(Xo.fulfilled,(t,n)=>{t.fetchState="done",jr(t.list,n.payload)||(t.list=n.payload)}).addCase(Ro,t=>{t.list=wf.list}).addCase(le,()=>wf)}}),$T=BN.reducer;var qT=(e={})=>{let t,n=!0,r={getStyleSuggestions:Xo,debounce:500,...e};return o=>i=>s=>{var m;let a=o.getState().input.text,l=i(s),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 jN(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var GT=(e={})=>{let t={getTextSuggestions:an,getAutocompleteSuggestions:rl,debounce:200,check:as,...e},n;return r=>o=>i=>{var y;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,p=(y=l.conversation.current)==null?void 0:y.id,d=i.type===Dd.toString();if(!p||!u&&!c)return a;let{input:{userCommitted:m}}=l;return jN(m,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let g=Xi(l);g===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(g))},d?0:t.debounce)),a}};var XT=Xo.fulfilled.toString();function VN(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var YT=e=>t=>n=>r=>{var u;if(r.type!==XT){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=VN(o,s);r.type===XT&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var KN=hc({answer:rC,auth:i1,autoflows:bb,conversation:m1,contentTypes:pE,customMessages:Mb,passwordlessToken:Db,entities:HE,knowledgeAssistant:eC,handlingTime:KT,info:_1,input:A1,settings:Zw,profile:aC,search:j1,summary:WE,styleSuggestions:$T,ui:DC,rules:Bb,textSuggestions:gC});function QT(e){return ow({reducer:KN,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),WT(),GT({debounce:200}),qT({debounce:500}),YT(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var WN=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},$N=e=>t=>n=>r=>{var a,l,u,c,p,d;let o=t.getState(),i=Ug("inlineSuggestions")(o);switch(r.type){case $i.toString():{!r.payload&&e.emit("logout",void 0);break}case on.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 et.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 Jc.toString():e.handleKeyDown(r.payload);break;case Ro.toString():e.logSendMessage(r.payload);break;case ed.toString():e.handleInputChanged(r.payload);break;case Wo.fulfilled.toString():r.isBroadcasted||e.broadcast(Xg,r,!1),(c=r.payload.options)!=null&&c.shouldEmit&&e.emit("cues",r.payload.cues);break;default:break}let s=n(r);switch(r.type){case Ro.toString():e.handleAfterSendMessage(r.payload);break;case il.toString():e.onUpdateShowTabHint(r.payload);break;case xf.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case Cn.toString():{let{start:m,end:v}=o.input.selection;e.emit("select-suggestion",{type:WN(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:m,end:v}:{start:0,end:v}},{mayApplyChanges:!0}),i&&(t.dispatch(En([])),t.dispatch(Wn()));break}case Zc.toString():{let{start:m,end:v}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:m,end:v}:{start:0,end:v}},{mayApplyChanges:!0});break}case Ma.toString():{let m=t.getState(),{text:v,selection:y}=m.input.userCommitted;e.emit("reset",{text:v,selectionAfter:y},{mayApplyChanges:!0});break}case td.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:(p=o.conversation.current)==null?void 0:p.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case En.toString():{i&&r.payload.length>0&&t.dispatch(Wr(0));break}case Qn.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(d=o.conversation.current)==null?void 0:d.id,data:{summary:r.payload.summary,model:t.getState().summary.model}});break}default:break}return s},ZT=$N;function by(e){return e.toISOString().replace("T"," ").replace("Z","")}function JT(e,t){var i,s,a,l;let n=(i=e.conversation.current)==null?void 0:i.id;if(!n)return F.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:o}=e.handlingTime;return!r||!o?(F.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:n,clientVersion:t.version,agentId:(s=e.info.agentInfo)==null?void 0:s.agentId,agentName:(a=e.info.agentInfo)==null?void 0:a.agentName,agentEmail:(l=e.info.agentInfo)==null?void 0:l.agentEmail,timeStart:by(r),timeStop:by(o)}}function ek(e,t,n){var I,O,M,W;let r=(I=t.conversation.current)==null?void 0:I.id;if(!r)return F.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:i,numCharsPasted:s,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:d,cuts:m,deletions:v,textSuggestions:y,offeredTextSuggestions:g}}=t[e],f=o.length,S=y.reduce((X,{text:ne,searchTerm:cr})=>X+ne.length-(cr?cr.length:0),0),w=c??Date.now(),T=(Date.now()-w)/1e3+(p||0),b=i/T,k=y.reduce((X,{searchTerm:ne})=>X+(ne?ne.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:m,deletions:v,lenTextTyped:i+k,lenTextTotal:f,lenTextAssisted:S,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:T,charsPerSecond:b,numPastes:u,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:g.filter(X=>X.source==="gpt").length}],agentId:(O=t.info.agentInfo)==null?void 0:O.agentId,agentName:(M=t.info.agentInfo)==null?void 0:M.agentName,agentEmail:(W=t.info.agentInfo)==null?void 0:W.agentEmail}}function Ty(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Ty(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Ty(o,t):null}function tk(e,t){return Ty(e,t)}function nk(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function qN(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Ef(e){return qN(e)&&(Jr(e)||$d(e))}var ok,Rn=new Map,GN=["bottom","height","left","right","top","width"],rk=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:GN.some(n=>e[n]!==t[n]);function ik(e){var n,r;if(e.ownerDocument===document)return[];let t=((r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)??null;return t?[t,...ik(t)]:[]}function sk(e,t){return!e||!t?null:{...e,top:e.top+t.top,left:e.left+t.left}}var Cf=!1,ak=()=>{Cf=!0;let e=[];if(Rn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Rn.delete(n);return}let r=n.getBoundingClientRect();rk(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(sk,t.rect):t.rect;rk(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Rn.size===0){Cf=!1;return}ok=window.requestAnimationFrame(ak)};function ky(e,t){let n=ik(e),r=[],o=n.map((i,s)=>ky(i,a=>{r[s]=a;let l=Rn.get(e);if(!l)return;let u=r.reduce(sk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Rn.has(e)){let s=Rn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Rn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!Cf&&ak()},unobserve(){o.forEach(s=>s.unobserve());let i=Rn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Rn.delete(e),Rn.size||(cancelAnimationFrame(ok),Cf=!1)}}}}var lk,An=new Map,uk=()=>{An.forEach((e,t)=>{if(!t.isConnected){An.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),An.size!==0&&(lk=window.requestAnimationFrame(uk))};function ck(e,t){return{observe(){let n=An.size===0;An.has(e)?An.get(e).callbacks.push(t):An.set(e,{visible:void 0,callbacks:[t]}),n&&uk()},unobserve(){let n=An.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||An.delete(e),An.size||cancelAnimationFrame(lk)}}}}var Py=["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 Ry(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function ys(e){return parseFloat(e)}function bf(e){return Math.round(e*1e6)}function dk(e){return e/1e6}function Ay(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=ys(e.width),i=ys(e.borderLeftWidth),s=ys(e.borderRightWidth),a=ys(e.paddingRight),l=dk(bf(o)-bf(i)-bf(s)),u=dk(bf(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function Pl(e,t={}){var c;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=t.position??"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",jo(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};Ry(r,n,Py),Ay(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=ck(e,()=>{Ry(r,n,Py),Ay(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=ky(e,p=>{if(p===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),p.height===0&&p.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(Ry(r,n,Py),Ay(r,e,n),i(),n.style.top=`${p.top}px`,n.style.left=`${p.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let d=t.closestScrollElement.getBoundingClientRect(),m=window.getComputedStyle(t.closestScrollElement),v=ys(m.borderTopWidth),y=ys(m.borderBottomWidth),g=d.top+v-p.top,f=p.top+p.height+-(d.top+d.height-y);n.style.clipPath=`inset(${g}px 0px ${f}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(c=e.parentElement)==null||c.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var fk=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch{return t}}catch{return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch{F.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function XN(e){return e.offsetParent!==null}function pk(e){if(!XN(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 Tf(e,t,n=100){let r=pk(e);t({isVisible:r});let o=setInterval(()=>{let i=pk(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Ie=x(C());var mk=fk("showTabHint",!0),Rl=class e{static version="11.6.1-beta.3";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new ur(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[ZT({broadcast:(p,d,m)=>{this.broadcastEvents.send(p,d,m)},emit:(p,d,m)=>this.emit(p,d,m),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),onUpdateShowTabHint:p=>mk.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new kl(n)}),this.store=QT(c),this.broadcastEvents=new UT({debug:!0,deepdeskUrl:u,eventMap:V1(this.store),createCustomChannel:l}),this.store.dispatch(il(mk.value())),this.store.dispatch(Wc({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(F.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(F.warn("Profile has not been loaded (yet)"),!0):(F.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch($i(null)),this.store.dispatch(Vn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();Je(r)&&Jw(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(Vn())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){F.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Vg({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(qc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(Gc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Kg(t))).payload}async postMessages(t){return(await this.store.dispatch(Yc(t))).payload}async updateConversation(t){return(await this.store.dispatch(Xc(t))).payload}resetConversation(){this.store.dispatch(le()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(Qn());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(Wc(t))}setVisitorInfo(t){this.store.dispatch(M1(t))}setCustomData(t){this.store.dispatch(N1(t))}async setAgentInfo(t){await this.store.dispatch(Na(t))}async setAgentSettings(t){await this.store.dispatch(qg(t))}async getAgentSettings(){return(await this.store.dispatch(Gg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(Dd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(ed(t))}notifyKeyDown(t){this.store.dispatch(Jc(t))}notifyPaste(t,n){this.store.dispatch(T1({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(C1(t))}notifyExternalSuggestion(t){this.store.dispatch(Cn(t)),this.store.dispatch(Wn())}async evaluateRule(t,n={},r=Fb){return(await this.store.dispatch(Wo({label:t,params:n,options:r}))).payload.cues}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(Qr({collapse:!1})),this.inputMediator&&this.store.dispatch(v1({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(En([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(b1(g1(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(x1()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(E1()),t.preventDefault(),!s&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Ma()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(Wr(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Wr(-1)),this.store.dispatch(Ma()),t.preventDefault()):n||(this.store.dispatch(Qr({collapse:!0})),this.store.dispatch(NC(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:m}=this.state.input;this.store.dispatch(il(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&m&&m.text.startsWith(d)&&(this.store.dispatch(Cn({text:m.text,suggestion:m,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(Wn())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(k1()),this.store.dispatch(En([]))}handlingTimeStart(){this.state.handlingTime.startTime||(F.info("Start handling time"),this.store.dispatch(jT()))}handlingTimeStop(){this.state.handlingTime.startTime&&(F.info("Stop handling time"),this.store.dispatch(xf()))}logSendMessage(t){let n=ek("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=JT(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(VT()))}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(Wn()),this.store.dispatch(Ro(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Cn({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{let i=this.eventListeners[t];i&&i.forEach(s=>{try{s(n)}catch(a){F.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),F.error(a)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=Pl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,$t.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=Pl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,$t.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return jo(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,$t.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),F.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(F.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(R1(r.metrics))):F.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Ef(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:d,insertLink:m,inputMediator:v,closestScrollSelector:y,appendOverlayTo:g,inlineSuggestions:f,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:m,isEmbedded:p,inlineSuggestions:f,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),jo(t),this.inputMediator=v||(Jr(t)?new Go(t):new qo(t)),this.inputMediator.on("change",({plainText:T})=>{this.notifyInputChanged(T)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(P1({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",T=>{this.notifyKeyDown(T)}),this.inputMediator.on("paste",({pastedText:T,selectionText:b})=>{this.notifyPaste(T,b)}),this.inputMediator.on("cut",({selectionText:T})=>{this.notifyCut(T)});let S=y&&tk(t,y)||void 0;if(f){let{customStyles:T,appendOverlayTo:b}=n;if(Jr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let k=this.createInlineContainer(t,"deepdesk-caret");(0,$t.render)((0,Ie.jsx)(Ko,{store:this.store,customStyles:T,children:(0,Ie.jsx)(Lo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(jC,{})})}),k),this.inputMediator.on("caret",O=>{this.store.dispatch(En([])),O?(k.style.display="block",k.style.top=`${O.top}px`,k.style.left=`${O.left}px`):k.style.display="none"});let I=this.overlayContainerFactory("floating-menu",S||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:b},T==null?void 0:T.floatingMenuRootNode);(0,$t.render)((0,Ie.jsx)(Ko,{store:this.store,customStyles:T,children:(0,Ie.jsx)(Lo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(IC,{onLogIn:()=>this.loginViaPopup().catch(O=>F.warn(O.message))})})}),I)}else{let T=this.overlayContainerFactory("deepdesk-tab-completion",S||t,{appendTo:g,closestScrollElement:S,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),b=this.overlayContainerFactory("deepdesk-suggestions-overlay",S||t,{appendTo:g},r==null?void 0:r.suggestionsRootNode);(0,$t.render)((0,Ie.jsx)(Ko,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Lo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(vb,{inputElement:t})})}),T),(0,$t.render)((0,Ie.jsx)(Ko,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Lo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(QC,{onLogIn:()=>this.loginViaPopup().catch(k=>F.warn(k.message))})})}),b)}(0,$t.render)((0,Ie.jsx)(Ko,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Lo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(kC,{})})}),this.createContainer("deepdesk-overlays"));let w;this.inputMediator.on("selection",T=>{clearTimeout(w),T===null?w=setTimeout(()=>{T!==null&&this.store.dispatch(Wg(T))},500):this.store.dispatch(Wg(T))}),this.inputMediator.on("disabled",()=>{var T;(T=this.inputMediator)==null||T.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(Dh(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Dh(!0))),this.store.dispatch(S1({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(Wn()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var T;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((T=this.state.conversation.current)==null?void 0:T.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&&F.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,$t.render)((0,Ie.jsx)(Ko,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Lo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(NT,{onLogIn:()=>this.loginViaPopup().catch(s=>F.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,$t.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Tf(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){nk(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(nl());let t=er(this.state);t&&(await this.store.dispatch(Ja()),this.store.dispatch(Wc({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(t){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};i.onmessage=async m=>{var v,y;if((v=m.data)!=null&&v.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((y=m.data)==null?void 0:y.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Da),l=!0,o.port1.close(),n()}catch(g){console.error(g),r(g)}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 p=async m=>{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){F.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-error":{u(),m.data.message==="Timeout"&&F.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(m.data.message));break}}};window.addEventListener("message",p);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)}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(F.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;F.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Nd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(on()):Yl.includes(r)||this.store.dispatch(an(r))})}catch(r){this.handleError(r)}}};async function gk(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function hk(e,t,n={}){let r=n.replace?ro(e,n.replace.start,n.replace.end):ms(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
|
|
28
28
|
`).reverse().forEach((s,a)=>{a>0&&r.insertNode(document.createElement("br")),r.insertNode(document.createTextNode(s))}):r.insertNode(document.createTextNode(t))};return Promise.resolve(i()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let s=n.selectionAfter?ro(e,n.selectionAfter.start,n.selectionAfter.end):(r.collapse(!1),r),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(s)}if(!o)return;o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function YN(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 QN(e){let t=document.createDocumentFragment();return e.split(`
|
|
29
29
|
`).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},i=0;for(;o=n.slice(i).match(/(\[([^\]]+)])\(([^)]+)\)/);){let s=document.createElement("a");s.href=o[3],s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer"),s.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(i,i+o.index))),t.appendChild(s),i=i+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(i)))}),t}function yk(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):yk(n,t)}async function vk(e,t,{isBlock:n,isHTML:r}={}){let o;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let i=()=>{let s=e.ownerDocument.defaultView??window,a=s.getSelection();if((!a||a.rangeCount===0)&&(e.focus(),a=s.getSelection()),!a||a.rangeCount===0)return;let l=a.getRangeAt(0);if(!l)return;o=document.createElement("span"),l.insertNode(o);let u=r?YN(t):QN(t);n?yk(l.startContainer,u):(l.insertNode(u),l.collapse(!1))};return Promise.resolve(i()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!o)try{o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function Sk(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function xk(e,t,n){await new ur(e).authenticateWithKey(t,n)}async function wk(e){let n=await new fn(e).get("/platform/config/",{version:null,useCache:!0});return J(n)}async function ZN(e){let n=await(e.fetch??window.fetch)(e.url),r=await n.blob();return new File([r],e.name,{type:e.mimeType??n.headers.get("Content-Type")??"image/jpeg"})}async function Ek(e,t){let n=await ZN(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}}return Fk(JN);})();
|
|
30
30
|
/*! Bundled license information:
|