@deepdesk/deepdesk-sdk 10.1.0 → 10.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.iife.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -2,5 +2,5 @@
|
|
|
2
2
|
Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
3
3
|
`,vt.MISSING_INTL_API,i);var C=n.getPluralRules(e,{type:u.pluralType}).select(p-(u.offset||0));v=u.options[C]||u.options.other}if(!v)throw new yr(u.value,p,Object.keys(u.options),i);a.push.apply(a,_n(v.value,e,n,o,s,p-(u.offset||0)));continue}}return Id(a)}function Ld(t,e){return e?oe(oe(oe({},t||{}),e||{}),Object.keys(t).reduce(function(n,o){return n[o]=oe(oe({},t[o]),e[o]||{}),n},{})):t}function Md(t,e){return e?Object.keys(t).reduce(function(n,o){return n[o]=Ld(t[o],e[o]),n},oe({},t)):t}function Sr(t){return{create:function(){return{get:function(e){return t[e]},set:function(e,n){t[e]=n}}}}}function Od(t){return t===void 0&&(t={number:{},dateTime:{},pluralRules:{}}),{getNumberFormat:jo(function(){for(var e,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];return new((e=Intl.NumberFormat).bind.apply(e,Mo([void 0],n,!1)))},{cache:Sr(t.number),strategy:zo.variadic}),getDateTimeFormat:jo(function(){for(var e,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];return new((e=Intl.DateTimeFormat).bind.apply(e,Mo([void 0],n,!1)))},{cache:Sr(t.dateTime),strategy:zo.variadic}),getPluralRules:jo(function(){for(var e,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];return new((e=Intl.PluralRules).bind.apply(e,Mo([void 0],n,!1)))},{cache:Sr(t.pluralRules),strategy:zo.variadic})}}var Ta=function(){function t(e,n,o,s){n===void 0&&(n=t.defaultLocale);var r=this;if(this.formatterCache={number:{},dateTime:{},pluralRules:{}},this.format=function(c){var u=r.formatToParts(c);if(u.length===1)return u[0].value;var d=u.reduce(function(p,m){return!p.length||m.type!==j.literal||typeof p[p.length-1]!="string"?p.push(m.value):p[p.length-1]+=m.value,p},[]);return d.length<=1?d[0]||"":d},this.formatToParts=function(c){return _n(r.ast,r.locales,r.formatters,r.formats,c,void 0,r.message)},this.resolvedOptions=function(){var c;return{locale:((c=r.resolvedLocale)===null||c===void 0?void 0:c.toString())||Intl.NumberFormat.supportedLocalesOf(r.locales)[0]}},this.getAst=function(){return r.ast},this.locales=n,this.resolvedLocale=t.resolveLocale(n),typeof e=="string"){if(this.message=e,!t.__parse)throw new TypeError("IntlMessageFormat.__parse must be set to process `message` of type `string`");var i=s||{},a=i.formatters,l=ga(i,["formatters"]);this.ast=t.__parse(e,oe(oe({},l),{locale:this.resolvedLocale}))}else this.ast=e;if(!Array.isArray(this.ast))throw new TypeError("A message must be provided as a String or AST.");this.formats=Md(t.formats,o),this.formatters=s&&s.formatters||Od(this.formatterCache)}return Object.defineProperty(t,"defaultLocale",{get:function(){return t.memoizedDefaultLocale||(t.memoizedDefaultLocale=new Intl.NumberFormat().resolvedOptions().locale),t.memoizedDefaultLocale},enumerable:!1,configurable:!0}),t.memoizedDefaultLocale=null,t.resolveLocale=function(e){if(!(typeof Intl.Locale>"u")){var n=Intl.NumberFormat.supportedLocalesOf(e);return n.length>0?new Intl.Locale(n[0]):new Intl.Locale(typeof e=="string"?e:e[0])}},t.__parse=ya,t.formats={number:{integer:{maximumFractionDigits:0},currency:{style:"currency"},percent:{style:"percent"}},date:{short:{month:"numeric",day:"numeric",year:"2-digit"},medium:{month:"short",day:"numeric",year:"numeric"},long:{month:"long",day:"numeric",year:"numeric"},full:{weekday:"long",month:"long",day:"numeric",year:"numeric"}},time:{short:{hour:"numeric",minute:"numeric"},medium:{hour:"numeric",minute:"numeric",second:"numeric"},long:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"},full:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"}}},t}();function Nd(t,e){return e.split(".").reduce((n,o)=>n?n[o]:void 0,t)}var Dd="dummy",vr=(0,Wo.createContext)(null);function _(t){let e=(0,Wo.useContext)(vr);if(!e)throw new Error("useTranslator() may be used only in the context of a <LocaleContext> component.");let n=t[e]??{};return(o,s)=>{let r=Nd(n,o);return r?new Ta(r).format(s):(e!==Dd&&console.warn(`${o} does not exist in messages of ${e}`),`[${o}]`)}}var Pn=require("react/jsx-runtime"),Go=()=>(0,Pn.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 256 512","aria-labelledby":"angleLeftTitle",children:[(0,Pn.jsx)("title",{id:"angleLeftTitle",children:"AngleLeft"}),(0,Pn.jsx)("path",{d:"M192 448c-8.188 0-16.38-3.125-22.62-9.375l-160-160c-12.5-12.5-12.5-32.75 0-45.25l160-160c12.5-12.5 32.75-12.5 45.25 0s12.5 32.75 0 45.25L77.25 256l137.4 137.4c12.5 12.5 12.5 32.75 0 45.25C208.4 444.9 200.2 448 192 448z"})]});var kn=require("react/jsx-runtime"),wa=()=>(0,kn.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 256 512","aria-labelledby":"angleRightTitle",children:[(0,kn.jsx)("title",{id:"angleRightTitle",children:"AngleRight"}),(0,kn.jsx)("path",{d:"M64 448c-8.188 0-16.38-3.125-22.62-9.375c-12.5-12.5-12.5-32.75 0-45.25L178.8 256L41.38 118.6c-12.5-12.5-12.5-32.75 0-45.25s32.75-12.5 45.25 0l160 160c12.5 12.5 12.5 32.75 0 45.25l-160 160C80.38 444.9 72.19 448 64 448z"})]});var Rn=E(require("classnames")),ue=E(require("react"));var xr={root:"_root_9kn3u_10",fadein:"_fadein_9kn3u_1",isClickable:"_isClickable_9kn3u_47",isSelected:"_isSelected_9kn3u_52",actions:"_actions_9kn3u_76",actionsIsFixed:"_actionsIsFixed_9kn3u_98",actionButton:"_actionButton_9kn3u_106",dropdownList:"_dropdownList_9kn3u_127",dropdownButton:"_dropdownButton_9kn3u_142",dropdownItem:"_dropdownItem_9kn3u_152",dropdownItemButton:"_dropdownItemButton_9kn3u_161",actionButtonIsPrimary:"_actionButtonIsPrimary_9kn3u_175",actionButtonIsDisabled:"_actionButtonIsDisabled_9kn3u_179",labels:"_labels_9kn3u_187",label:"_label_9kn3u_187"};var ce=require("react/jsx-runtime"),Kt=(0,ue.createContext)(xr),Hd=({fixed:t,children:e,...n})=>{let o=(0,ue.useContext)(Kt);return(0,ce.jsx)("div",{...n,className:(0,Rn.default)(o.actions,{[o.actionsIsFixed]:t}),children:e})},Fd=({className:t,primary:e,disabled:n,label:o,children:s})=>{let r=(0,ue.useContext)(Kt);return(0,ce.jsxs)("div",{className:(0,Rn.default)(t,r.actionButton,r.dropdownButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:n}),onMouseDown:i=>i.stopPropagation(),onClick:i=>i.stopPropagation(),children:[o,(0,ce.jsx)("ul",{className:r.dropdownList,children:s})]})},Bd=({index:t,label:e,onClick:n})=>{let o=(0,ue.useContext)(Kt);return(0,ce.jsx)("li",{className:o.dropdownItem,children:(0,ce.jsx)("button",{className:o.dropdownItemButton,type:"button","data-index":t,onClick:n,children:e})})},Kd=({className:t,primary:e,disabled:n,onClick:o,label:s})=>{let r=(0,ue.useContext)(Kt);return(0,ce.jsx)("button",{type:"button",className:(0,Rn.default)(t,r.actionButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:n}),onClick:o??(i=>i.stopPropagation()),disabled:n,"aria-hidden":n,children:s})},Cr=({labels:t})=>{let e=(0,ue.useContext)(Kt);return(0,ce.jsx)("div",{className:e.labels,children:t.map(n=>(0,ce.jsx)("span",{className:e.label,children:n},n))})},Ut=ue.default.forwardRef(({className:t,selected:e,onClick:n,children:o,as:s="div",...r},i)=>{let a=y("Suggestion",xr),l=(0,ue.useCallback)(c=>{c.preventDefault(),n&&n(c)},[n]);return(0,ce.jsx)(s,{...r,ref:i,className:(0,Rn.default)(t,a.root,{[a.isSelected]:e,[a.isClickable]:!!n}),onClick:l,children:(0,ce.jsx)(Kt.Provider,{value:a,children:o})})});Ut.Labels=Cr;Ut.Actions=Hd;Ut.ActionButton=Kd;Ut.DropdownButton=Fd;Ut.DropdownItem=Bd;var N=Ut;var de=require("react"),Ba=require("react-redux"),Ka=require("interweave"),Rr=E(require("classnames"));var Tr={root:"_root_7hhs4_1",agentText:"_agentText_7hhs4_3",textInput:"_textInput_7hhs4_8",textInputWrapper:"_textInputWrapper_7hhs4_27",alert:"_alert_7hhs4_31",alertText:"_alertText_7hhs4_50",warning:"_warning_7hhs4_60",success:"_success_7hhs4_69"};var Ea=require("interweave"),_a=E(require("classnames"));var qt=require("react");function ba(t,e){let n;return[(...o)=>{window.cancelAnimationFrame(n);let s=e?e(...o):o;n=window.requestAnimationFrame(()=>{t(...s)})},()=>window.cancelAnimationFrame(n)]}function $o(t){let e=(0,qt.useRef)(null),[n,o]=(0,qt.useState)(!1);return(0,qt.useEffect)(()=>{let s=!1,r=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[i,a]=ba((u,d)=>{let p=e.current;if(!p)return;let m=u/r,g=d/r,f=p.getBoundingClientRect(),x=m>f.x&&m<f.x+f.width&&g>f.y&&g<f.y+f.height;x&&!s?(s=!0,o(!0)):!x&&s&&(s=!1,o(!1))},({clientX:u,clientY:d})=>[u,d]),[l,c]=ba(()=>{s=!1,o(!1)});return t.addEventListener("mousemove",i),t.addEventListener("mouseleave",l),()=>{a(),c(),t.removeEventListener("mousemove",i),t.removeEventListener("mouseleave",l)}},[e]),[e,n]}var pe={root:"_root_kpc8q_1",agentText:"_agentText_kpc8q_4",tabText:"_tabText_kpc8q_9",hint:"_hint_kpc8q_10",matchSelection:"_matchSelection_kpc8q_14",focus:"_focus_kpc8q_20",resetIndent:"_resetIndent_kpc8q_24",matchKeyword:"_matchKeyword_kpc8q_28",matchPlaceholder:"_matchPlaceholder_kpc8q_29",hover:"_hover_kpc8q_35",hintText:"_hintText_kpc8q_67",popover:"_popover_kpc8q_75",popoverRoot:"_popoverRoot_kpc8q_80",popoverContentContainer:"_popoverContentContainer_kpc8q_84",popoverContent:"_popoverContent_kpc8q_84",selectionOptions:"_selectionOptions_kpc8q_110",selectionOptionsIsHidden:"_selectionOptionsIsHidden_kpc8q_115",selectionOptionsButton:"_selectionOptionsButton_kpc8q_119",caret:"_caret_kpc8q_135",popoverSuggestionsRoot:"_popoverSuggestionsRoot_kpc8q_139",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_kpc8q_144"};var wr=require("react/jsx-runtime"),Ud=({inputElement:t,children:e})=>{let n=y("TabCompletion",pe),[o,s]=$o(t);return(0,wr.jsx)("mark",{ref:o,className:(0,_a.default)(n.matchPlaceholder,{[n.hover]:s}),children:e})},Vt=class extends Ea.Matcher{match(e){let n=e.match(/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\}(?!\}))/);return n?{index:n.index,length:n[0].length,match:n[0],matchString:n[0],valid:!0}:null}replaceWith(e,n){return(0,wr.jsx)(Ud,{inputElement:n.inputElement,children:e},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var jt=require("react");function Xo(t){return t.contentEditable==="true"}function qd(t){let e=0,n=0,o=window.getSelection();if(o.rangeCount!==0){let s=o.getRangeAt(0),r=s.cloneRange();r.selectNodeContents(t),r.setEnd(s.endContainer,s.endOffset),n=r.toString().length,r.selectNodeContents(t),r.setEnd(s.startContainer,s.startOffset),e=r.toString().length}return{selectionStart:e,selectionEnd:n}}function Pa(t){let{selectionStart:e,selectionEnd:n}=Xo(t)?qd(t):t;return[e,n]}function Qo(t){let[,e]=(0,jt.useState)(),n=(0,jt.useRef)(null);return n.current=Pa(t),(0,jt.useEffect)(()=>{let o=()=>{let[s,r]=n.current??[],i=Pa(t);(!i||s!==i[0]||r!==i[1])&&(n.current=i,e({}))};return t.addEventListener("keyup",o),t.addEventListener("click",o),t.addEventListener("focus",o),document.addEventListener("selectionchange",o),()=>{t.removeEventListener("keyup",o),t.removeEventListener("click",o),t.removeEventListener("focus",o),document.removeEventListener("selectionchange",o)}},[t]),n.current}function Zo(t,e){if(!e)return;let n=t,{value:o}=n,[s,r]=e,i=o.match(Dt);if(!i||i.length===0)return;let a=0;i.find(l=>{let c=o.indexOf(l,a);return s>c&&r<c+l.length?(n.selectionStart=c,n.selectionEnd=c+l.length,!0):(a=c+l.length,!1)})}var ka=require("react");function zt(t){(0,ka.useEffect)(()=>{let e=n=>{n.isWithinRoot||t(n)};return document.body.addEventListener("mouseup",e),()=>{document.body.removeEventListener("mouseup",e)}},[t])}function xt(t){t.addEventListener("mouseup",e=>{e.isWithinRoot=!0},!0)}var Ra,Ie=new Map,Vd=["bottom","height","left","right","top","width"],jd=(t={},e={})=>Vd.some(n=>t[n]!==e[n]),Ia=()=>{let t=[];Ie.forEach((e,n)=>{if(!n.isConnected){e.rect=null,t.push(e),Ie.delete(n);return}let o=n.getBoundingClientRect();jd(o,e.rect)&&(e.rect=o,t.push(e))}),t.forEach(e=>{e.callbacks.forEach(n=>n(e.rect))}),Ie.size!==0&&(Ra=window.requestAnimationFrame(Ia))};function Aa(t,e){return{observe(){let n=Ie.size===0;if(Ie.has(t)){let o=Ie.get(t);o.callbacks.push(e),o.rect&&e(o.rect)}else Ie.set(t,{rect:void 0,callbacks:[e]});n&&Ia()},unobserve(){let n=Ie.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||Ie.delete(t),Ie.size||cancelAnimationFrame(Ra)}}}}var La,Ae=new Map,Ma=()=>{Ae.forEach((t,e)=>{if(!e.isConnected){Ae.delete(e);return}let{clientHeight:n,scrollHeight:o}=e,s=o>n;t.visible!==s&&(t.visible=s,t.callbacks.forEach(r=>r(t.visible)))}),Ae.size!==0&&(La=window.requestAnimationFrame(Ma))};function Oa(t,e){return{observe(){let n=Ae.size===0;Ae.has(t)?Ae.get(t).callbacks.push(e):Ae.set(t,{visible:void 0,callbacks:[e]}),n&&Ma()},unobserve(){let n=Ae.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||Ae.delete(t),Ae.size||cancelAnimationFrame(La)}}}}var br=["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 Er(t,e,n){return n.forEach(o=>{e.style[o]=t[o]})}function Wt(t){return parseFloat(t)}function Jo(t){return Math.round(t*1e6)}function Na(t){return t/1e6}function _r(t,e,n){if(t.boxSizing==="content-box")return;let{clientWidth:o}=e,s=Wt(t.width),r=Wt(t.borderLeftWidth),i=Wt(t.borderRightWidth),a=Wt(t.paddingRight),l=Na(Jo(s)-Jo(r)-Jo(i)),c=Na(Jo(o));if(l-c>2){let u=l-c;n.style.paddingRight=`${a+u}px`}}function Gt(t,e={}){var l;let n=e.overlayContainer||document.createElement("div");n.style.display="none",n.style.position="fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",xt(n);let o=window.getComputedStyle(t),s=!0,r=()=>{n.scrollTop=t.scrollTop};Er(o,n,br),_r(o,t,n),e.mirrorOverflow&&(n.style.overflow="hidden",t.addEventListener("scroll",r));let i=Oa(t,()=>{Er(o,n,br),_r(o,t,n),r(),setTimeout(r,0)}),a=Aa(t,c=>{if(c===null){e.onRemove&&e.onRemove(),n.remove();return}if(c.height===0&&c.width===0){if(s===!0)return;e.onHide&&e.onHide(),n.style.display="none",s=!0;return}if(Er(o,n,br),_r(o,t,n),r(),n.style.top=`${c.top}px`,n.style.left=`${c.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let u=e.closestScrollElement.getBoundingClientRect(),d=window.getComputedStyle(e.closestScrollElement),p=Wt(d.borderTopWidth),m=Wt(d.borderBottomWidth),g=u.top+p-c.top,f=c.top+c.height+-(u.top+u.height-m);n.style.clipPath=`inset(${g}px 0px ${f}px 0px)`}s&&(n.style.display="block",e.onShow&&e.onShow(),s=!1)});return e.appendTo?e.appendTo.appendChild(n):(l=t.parentElement)==null||l.appendChild(n),a.observe(),i.observe(),[n,()=>{t.removeEventListener("scroll",r),a.unobserve(),i.unobserve()}]}var Pr={};q(Pr,{enUS:()=>zd,nlNL:()=>Wd});var zd={placeholders:[{type:6,value:"placeholderSize",options:{"=0":{value:[{type:0,value:"No placeholders found"}]},one:{value:[{type:0,value:"There is one placeholder in your message"}]},other:{value:[{type:0,value:"There are "},{type:7},{type:0,value:" placeholders in your message"}]}},offset:0,pluralType:"cardinal"}]},Wd={placeholders:[{type:6,value:"placeholderSize",options:{"=0":{value:[{type:0,value:"Alle placeholders zijn uit je bericht"}]},one:{value:[{type:0,value:"Er is 1 placeholder in jouw bericht"}]},other:{value:[{type:0,value:"Er zijn "},{type:7},{type:0,value:" placeholders in jouw bericht"}]}},offset:0,pluralType:"cardinal"}]};var In=require("react/jsx-runtime"),Da=()=>(0,In.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 512 512","aria-labelledby":"circleCheckTitle",children:[(0,In.jsx)("title",{id:"circleCheckTitle",children:"Check"}),(0,In.jsx)("path",{d:"M243.8 339.8C232.9 350.7 215.1 350.7 204.2 339.8L140.2 275.8C129.3 264.9 129.3 247.1 140.2 236.2C151.1 225.3 168.9 225.3 179.8 236.2L224 280.4L332.2 172.2C343.1 161.3 360.9 161.3 371.8 172.2C382.7 183.1 382.7 200.9 371.8 211.8L243.8 339.8zM512 256C512 397.4 397.4 512 256 512C114.6 512 0 397.4 0 256C0 114.6 114.6 0 256 0C397.4 0 512 114.6 512 256zM256 48C141.1 48 48 141.1 48 256C48 370.9 141.1 464 256 464C370.9 464 464 370.9 464 256C464 141.1 370.9 48 256 48z"})]});var kr=require("react/jsx-runtime"),Ha=()=>(0,kr.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",fill:"currentColor",children:(0,kr.jsx)("path",{d:"M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224c0-17.7-14.3-32-32-32s-32 14.3-32 32s14.3 32 32 32s32-14.3 32-32z"})});var Fa=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(Fa||{}),Ne=class{constructor(e){this.element=e;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentHTML="";currentSelection=null;isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(e,n){let o=s=>{n(s)};this.element.addEventListener(e,o),this.disposeHandlers.push(()=>{this.element.removeEventListener(e,o)})}removeEventListener(e,n){this.element.removeEventListener(e,n)}triggerChange(){let e=this.getText(),n=this.getHTML(),o=e!==this.currentText;this.isActive&&(e===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&o&&!this.isSubmitting&&this.emit("change",{plainText:e,rawHtml:n}),this.currentText=e,this.isSubmitting=!1,(this.currentHTML!==n||n===null&&o)&&(this.emit("updated",{plainText:e,rawHtml:n}),this.currentHTML=n))}handleKeyUp(e){let{key:n,shiftKey:o}=e;(n==="Enter"&&o===!0||n==="Backspace")&&this.triggerChange()}handleFocus(){this.isFocused||this.emit("focus"),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(e){let{key:n,ctrlKey:o,metaKey:s}=e;this.isPossibleClearInputAction=Object.values(Fa).includes(n)||n.toLowerCase()==="z"&&(o||s),this.emit("keydown",e)}handleCut(){let e=this.currentSelection;this.isPossibleClearInputAction=!0,e&&this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){let n=(e.clipboardData||window.clipboardData).getData("text");this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){let e=()=>{let o=document.activeElement===this.element?this.getSelection():null;st(this.currentSelection,o)||(this.currentSelection=o,this.emit("selection",o))};document.addEventListener("selectionchange",e),this.disposeHandlers.push(()=>{window.document&&document.removeEventListener("selectionchange",e)}),this.addEventListener("keydown",o=>this.handleKeyDown(o)),this.addEventListener("keyup",o=>this.handleKeyUp(o)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",o=>this.handlePaste(o)),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let n=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});n.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{n.disconnect()})}focus(){this.element.focus()}emit(e,...n){this.isDisposed||this.eventListeners[e]&&this.eventListeners[e].forEach(o=>{o(...n)})}on(e,n){this.isDisposed||(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n))}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};var De=class extends Ne{getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:e,selectionEnd:n}=this.element;return{start:e,end:n}}getSelectedText(){return this.currentSelection?this.getText().slice(this.currentSelection.start,this.currentSelection.end):""}applyChanges(e){if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),o=e(this.element);Promise.resolve(o).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let e=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=e==null?void 0:e.get)==null?void 0:s.call(this.element)},set:s=>{var r;(r=e==null?void 0:e.set)==null||r.call(this.element,s),this.triggerChange()}});let n=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==n&&(n=this.element.disabled,this.emit(n?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};var Z=require("react/jsx-runtime"),Gd=({value:t,onUse:e,...n})=>{var u;let o=_(Pr),s=(0,Ba.useDispatch)(),r=y("EditSuggestionTextInput",Tr),[i,a]=(0,de.useState)(null),l=(0,de.useRef)(null),c=((u=t.match(Dt))==null?void 0:u.length)||0;return(0,de.useEffect)(()=>{let d;return l.current&&(a(l.current),d=new De(l.current),d.on("change",({plainText:p})=>{s(Q.actions.userInput({text:p,selection:d.getSelection()}))}),d.on("keydown",p=>{s(Q.actions.registerKeyDown(Eo(p))),p.code==="Enter"&&p.shiftKey&&e(d.getText())}),d.on("paste",({pastedText:p,selectionText:m})=>{s(Q.actions.registerPaste({text:p,selectionText:m}))}),d.on("cut",({selectionText:p})=>{s(Q.actions.registerCut(p))})),()=>{s(Q.actions.reset()),d.dispose(),d.deactivate()}},[l]),(0,de.useEffect)(()=>{t&&l.current&&(l.current.value=t)},[t,l]),(0,de.useEffect)(()=>{l.current&&setTimeout(()=>{if(!l.current)return;let d=l.current.value.length;l.current.setSelectionRange(d,d),l.current.focus()},0)},[l]),(0,Z.jsxs)("div",{className:r.textInputWrapper,children:[(0,Z.jsx)("textarea",{...n,ref:l,"data-testid":"edit-suggestion-dialog-textarea",className:r.textInput,defaultValue:t,onChange:()=>{}}),i&&(0,Z.jsx)($d,{inputElement:l.current,value:t}),(0,Z.jsxs)("div",{className:(0,Rr.default)(r.alert,c===0?r.success:r.warning),children:[(0,Z.jsx)("div",{className:r.alertText,children:o("placeholders",{placeholderSize:c})}),c===0?(0,Z.jsx)(Da,{}):(0,Z.jsx)(Ha,{})]})]})},$d=({inputElement:t,value:e})=>{let n=y("EditSuggestionTextInput",Tr),o=(0,de.useRef)(null),s=Qo(t);return(0,de.useEffect)(()=>{Zo(t,s)},[s,t]),(0,Z.jsx)(Xd,{inputElement:t,children:(0,Z.jsxs)("div",{ref:o,className:(0,Rr.default)(n.root,n.agentText),children:[(0,Z.jsx)(Ka.Interweave,{tagName:"span",disableLineBreaks:!0,content:e,matchers:[new Vt("placeholders")],inputElement:t,boundaryRef:o}),(0,Z.jsx)("br",{})]})})},Xd=({inputElement:t,children:e})=>{let n=(0,de.useRef)(null);return(0,de.useEffect)(()=>{if(!n.current)return()=>{};let[o,s]=Gt(t,{overlayContainer:n.current,mirrorOverflow:!0});return()=>{s()}},[n.current]),(0,Z.jsx)("div",{ref:n,children:e})},Ua=Gd;var Zt=require("react");var J={root:"_root_m5usm_1",list:"_list_m5usm_2",listWrapper:"_listWrapper_m5usm_6",listHorizontal:"_listHorizontal_m5usm_10",page:"_page_m5usm_19",search:"_search_m5usm_25",pageNav:"_pageNav_m5usm_33",pageTitle:"_pageTitle_m5usm_41",pageBackButton:"_pageBackButton_m5usm_48",listHeading:"_listHeading_m5usm_62",listItem:"_listItem_m5usm_70",listItemContent:"_listItemContent_m5usm_79",listItemText:"_listItemText_m5usm_97",listItemDescription:"_listItemDescription_m5usm_105",truncate:"_truncate_m5usm_112",lineClamp:"_lineClamp_m5usm_118",listItemTitle:"_listItemTitle_m5usm_125",listItemAction:"_listItemAction_m5usm_132",listItemPrimaryAction:"_listItemPrimaryAction_m5usm_146",listItemSelected:"_listItemSelected_m5usm_151",sources:"_sources_m5usm_155",sourcesTitle:"_sourcesTitle_m5usm_162",source:"_source_m5usm_155",icon:"_icon_m5usm_177",searchIcon:"_searchIcon_m5usm_194",searchInputWrapper:"_searchInputWrapper_m5usm_199",searchInput:"_searchInput_m5usm_199",select:"_select_m5usm_220",selectType:"_selectType_m5usm_237",selectWrapper:"_selectWrapper_m5usm_241",image:"_image_m5usm_271",imageSrc:"_imageSrc_m5usm_278",imageTitle:"_imageTitle_m5usm_289",actions:"_actions_m5usm_294",actionsWrapper:"_actionsWrapper_m5usm_298",actionsBar:"_actionsBar_m5usm_304",actionButton:"_actionButton_m5usm_313",actionShortcut:"_actionShortcut_m5usm_331",actionShortcutFixKerning:"_actionShortcutFixKerning_m5usm_338"};var An=require("react/jsx-runtime"),Qd=({src:t,title:e})=>{let n=y("CommandPalette",J);return(0,An.jsxs)("div",{className:n.image,children:[(0,An.jsx)("img",{src:t,alt:e,className:n.imageSrc}),e&&(0,An.jsx)("span",{className:n.imageTitle,children:e})]})},qa=Qd;var Va=E(require("react")),ja=E(require("classnames"));var Ln=require("react/jsx-runtime");function Ir({children:t,heading:e,orientation:n}){let o=y("CommandPalette",J);return Va.default.Children.count(t)===0?null:(0,Ln.jsxs)("div",{"data-testid":"commandpalette-list",className:o.list,children:[e&&(0,Ln.jsx)("h4",{className:o.listHeading,children:e}),(0,Ln.jsx)("div",{className:(0,ja.default)(o.listWrapper,n==="horizontal"&&o.listHorizontal),children:t})]})}var Mn=E(require("classnames"));var za={root:"_root_nkim0_1"};var Ar={};q(Ar,{enUS:()=>Zd,nlNL:()=>Jd});var Zd={experimental:[{type:0,value:"Experimental"}]},Jd={experimental:[{type:0,value:"Experimenteel"}]};var Lr=require("react/jsx-runtime"),Wa=({children:t})=>{let e=y("Chip",za);return(0,Lr.jsx)("span",{className:e.root,children:t})},Yo=()=>{let t=_(Ar);return(0,Lr.jsx)(Wa,{children:t("experimental")})},Ga=Wa;var es=E(require("react")),Qa=require("react/jsx-runtime"),$a=es.default.createContext(void 0);function lt(){let t=es.default.useContext($a);if(t===void 0)throw new Error("useCommandPalette must be used within the CommandPalette component");return t}var Xa=({children:t,page:e,isOpen:n,onChangeOpen:o,selected:s,setSelected:r})=>{let i=es.default.useMemo(()=>({page:e,isOpen:n,onChangeOpen:o,selected:s,setSelected:r}),[n,e,s]);return(0,Qa.jsx)($a.Provider,{value:i,children:t})};var me=require("react/jsx-runtime");function Mr({closeOnSelect:t=!0,lineClamp:e,children:n,onClick:o,index:s,isExperimental:r,description:i,sources:a,styles:l,...c}){let{selected:u,onChangeOpen:d}=lt(),p=y("CommandPalette",J);function m(g){o(g),t&&d(!1)}return(0,me.jsxs)("div",{className:(0,Mn.default)(p.listItem,u===s&&p.listItemSelected),children:[(0,me.jsxs)("button",{type:"button",className:(0,Mn.default)("command-palette-list-item",p.listItemAction,p.listItemPrimaryAction),"aria-disabled":c.disabled??!1,onClick:m,...c,children:[(0,me.jsxs)("div",{className:p.listItemContent,children:[typeof n=="string"?(0,me.jsx)("p",{className:(0,Mn.default)(p.listItemText,p.truncate,l==null?void 0:l.title),children:n}):n,i&&(0,me.jsx)("p",{className:(0,Mn.default)(p.listItemDescription,l==null?void 0:l.description,e?p.lineClamp:p.truncate),children:i})]}),r&&(0,me.jsx)(Yo,{})]}),a&&(0,me.jsxs)("div",{className:p.sources,children:[(0,me.jsx)("span",{className:p.sourcesTitle,children:"Sources"}),a.map(g=>g.url?(0,me.jsx)("a",{className:p.source,href:g.url,target:"_blank",title:g.url,rel:"noopener noreferrer",children:g.name},g.url):(0,me.jsx)("span",{className:p.source,children:g.name},g.name))]})]})}var On={};q(On,{enUS:()=>Yd,nlNL:()=>em});var Yd={visitUrl:[{type:0,value:"Visit"}],back:[{type:0,value:"Back"}]},em={visitUrl:[{type:0,value:"Bekijk"}],back:[{type:0,value:"Terug"}]};var ct=require("react/jsx-runtime");function Or({children:t,title:e,id:n,onDismiss:o,isExperimental:s}){let r=_(On),i=y("CommandPalette",J),{page:a}=lt();return a!==n?null:(0,ct.jsxs)("div",{className:i.page,id:`page_${n}`,tabIndex:-1,children:[o&&(0,ct.jsxs)("div",{className:i.pageNav,children:[(0,ct.jsxs)("button",{className:i.pageBackButton,type:"button",onClick:o,children:[(0,ct.jsx)(Go,{}),r("back")]}),e&&(0,ct.jsx)("h3",{className:i.pageTitle,children:e}),s&&(0,ct.jsx)(Yo,{})]}),t]})}var ut=require("react");var ts=()=>/Mac/i.test(navigator.platform);var os=require("@reduxjs/toolkit");var tm={info(...t){console.info("[Deepdesk]",...t)},warn(...t){console.warn("[Deepdesk]",...t)},error(...t){console.error("[Deepdesk]",...t)}},P=tm;var $t=require("@reduxjs/toolkit");function nm(t){return t.replace(/(_\w)/g,e=>e[1].toUpperCase())}function O(t){return Array.isArray(t)?t.map(O):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>({...e,[nm(n)]:O(t[n])}),{}):t}function Nr(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function K(t){return Array.isArray(t)?t.map(K):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>({...e,[Nr(n)]:K(t[n])}),{}):t}var om={agentInfo:void 0,agentSettings:{},visitorInfo:void 0,fetchState:"idle"},Dn=t=>{var e,n,o;return{timezone:((e=t.info.visitorInfo)==null?void 0:e.visitorTimeZone)||Intl.DateTimeFormat().resolvedOptions().timeZone,agentName:((n=t.info.agentInfo)==null?void 0:n.agentNickname)||"",visitorName:((o=t.info.visitorInfo)==null?void 0:o.visitorName)||""}},Nn=(0,$t.createAsyncThunk)("info/setAgentInfo",async(t,e)=>{let{deepdeskAPI:n}=e.extra;if(!t.agentId&&!t.agentNickname)throw new Error("At least provide agentId or agentNickname");let o=await n.client.get("/apis/admin/session/me/",{version:null}),s={};return o.external_id||(s.external_id=t.agentId),o.nickname||(s.nickname=t.agentNickname),!s.external_id&&!s.nickname?O(o):(await n.client.patch("/apis/admin/session/me/",s,{version:null}),O(o))}),Dr=(0,$t.createAsyncThunk)("info/setAgentSettings",async(t,e)=>{let{deepdeskAPI:n}=e.extra,o=await n.client.get("/apis/admin/session/me/",{version:null}),s={...typeof o.ui_config=="object"?o.ui_config:{},...t};return await n.client.patch("/apis/admin/session/me/",{ui_config:s}),s}),Hr=(0,$t.createAsyncThunk)("info/getAgentSettings",async(t,e)=>{let{deepdeskAPI:n}=e.extra;return(await n.client.get("/apis/admin/session/me/",{version:null})).ui_config}),Za=t=>t.info.agentInfo,Ja=(0,$t.createSlice)({name:"info",initialState:om,reducers:{setVisitorInfo(t,e){t.visitorInfo={...t.visitorInfo,...e.payload}}},extraReducers:t=>{t.addCase(Nn.pending,(e,n)=>{e.fetchState="loading",e.agentInfo={...e.agentInfo,...n.meta.arg}}).addCase(Nn.rejected,e=>{e.fetchState="error"}).addCase(Nn.fulfilled,(e,n)=>{e.fetchState="done",e.agentInfo={...e.agentInfo,...n.meta.arg,agentId:n.payload.externalId||n.meta.arg.agentId||"",agentNickname:n.payload.nickname||n.meta.arg.agentNickname||""}}).addCase(Dr.fulfilled,(e,n)=>{e.agentSettings=n.payload}).addCase(Hr.fulfilled,(e,n)=>{e.agentSettings=n.payload}).addCase(A,e=>{e.visitorInfo=void 0})}}),{setVisitorInfo:Ya}=Ja.actions,el=Ja.reducer;var ns={list:[],fetchState:"idle",isOpen:!1,page:"search"},tl=t=>t.search.isOpen,nl=t=>t.search.page,ol=t=>t.search.list;function sl(t,e=n=>n){return n=>n.search.list.filter(o=>o.type===t).map(e)}var Ct=(0,os.createAsyncThunk)("search/getAll",async(t,e)=>{var i;let{deepdeskAPI:n}=e.extra,o=e.getState(),s=(i=o.conversation.current)==null?void 0:i.profileCode;if(!s)throw new Error("Profile should be provided in order to be able to search");let{results:r}=await n.search({profile:s,query:t.query,filters:{type:t.type},params:Dn(o),tags:t.tags});return r}),rl=(0,os.createSlice)({name:"search",initialState:ns,reducers:{setIsOpen(t,e){t.isOpen=e.payload},setPage(t,e){t.page=e.payload},resetSearch(t){t.fetchState=ns.fetchState,t.list=ns.list}},extraReducers:t=>{t.addCase(Ct.pending,e=>{e.fetchState="loading"}).addCase(Ct.rejected,(e,n)=>{e.fetchState="error",P.error(n.error)}).addCase(Ct.fulfilled,(e,n)=>{e.fetchState="done",e.list=n.payload}).addCase(A,()=>ns)}}),{resetSearch:ss,setIsOpen:se,setPage:G}=rl.actions,il=rl.reducer;var sm=/(https?:\/\/[^\s]+)/,rs=t=>t.split(" ").find(e=>sm.test(e));var Fr=E(require("classnames"));var is=require("react/jsx-runtime"),rm=({onClick:t,shortKeys:e,children:n,...o})=>{let s=y("CommandPalette",J);return(0,is.jsxs)("button",{type:"button",...o,onClick:t,className:(0,Fr.default)(s.actionButton,o.className),children:[n,e&&e.map(r=>(0,is.jsx)("span",{className:(0,Fr.default)(s.actionShortcut,r===8629&&s.actionShortcutFixKerning),children:typeof r=="number"?String.fromCharCode(r):r},r))]})},Xt=rm;var He=require("react/jsx-runtime"),im=({children:t,primaryLabel:e,secondaryLabel:n,onPrimary:o,onSecondary:s,list:r})=>{let i=y("CommandPalette",J),a=_(On),{selected:l,setSelected:c}=lt(),u=r[l],d=u&&typeof u.text=="string"&&rs(u.text),p=(0,ut.useRef)(null);function m(v){if(!p.current)return;let C=p.current.querySelectorAll(".command-palette-list-item"),k=0,w=0;v==="down"?(C.forEach((te,R)=>{R===l&&(k=R)}),w=k===C.length-1?0:k+1):v==="up"?(C.forEach((te,R)=>{R===l&&(k=R)}),w=k?k-1:C.length-1):c(0);let H=C[w];H&&typeof w=="number"&&(c(w),H.scrollIntoView&&H.scrollIntoView({behavior:"smooth",block:w?"center":"end"}))}function g(){if(!p.current)return;let v=p.current.querySelectorAll(".command-palette-list-item"),C=0;v.forEach((w,H)=>{H===l&&(C=H)});let k=v[C];k&&k.click()}let f=()=>{d&&window.open(d,"_blank")},x=()=>{u&&o(u,l)},b=()=>{!u.type||["IMAGE","command"].includes(u.type)||s&&s(u,l)},h=(0,ut.useCallback)(v=>{if(v.key==="Enter"&&v.altKey&&d){f();return}if(v.key==="Enter"&&v.shiftKey){b();return}if(v.key==="ArrowDown"){v.preventDefault(),v.stopPropagation(),m("down");return}if(v.key==="ArrowUp"){v.preventDefault(),v.stopPropagation(),m("up");return}v.key==="Enter"&&l!==-1&&(v.preventDefault(),v.stopPropagation(),g())},[l]);return(0,ut.useEffect)(()=>(window.addEventListener("keyup",h),()=>{window.removeEventListener("keyup",h)}),[h]),(0,He.jsxs)("div",{className:i.actions,children:[(0,He.jsx)("div",{className:i.actionsWrapper,ref:p,children:t}),(0,He.jsxs)("div",{className:i.actionsBar,children:[d&&(0,He.jsx)(Xt,{onClick:f,shortKeys:[ts()?8997:"ALT",8629],children:a("visitUrl")}),u&&(0,He.jsxs)(ut.Fragment,{children:[s&&u.type&&!["command","image"].includes(u.type.toLowerCase())&&(0,He.jsx)(Xt,{onClick:b,shortKeys:[8679,8629],children:n}),(0,He.jsx)(Xt,{onClick:x,shortKeys:[8629],children:e})]})]})]})},ll=im;var cl=require("react");var Hn=require("react/jsx-runtime"),Qt=()=>(0,Hn.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"24px",viewBox:"0 0 24 24",width:"24px",fill:"currentColor",children:[(0,Hn.jsx)("path",{d:"M0 0h24v24H0z",fill:"none"}),(0,Hn.jsx)("path",{d:"M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"})]});var we=require("react/jsx-runtime");function am({onChange:t,onChangeType:e,placeholder:n,typePlaceholder:o,types:s,value:r,selectedType:i},a){let l=y("CommandPalette",J);return(0,we.jsxs)("div",{className:l.search,children:[(0,we.jsx)("div",{className:l.searchIcon,children:(0,we.jsx)(Qt,{})}),(0,we.jsxs)("div",{className:l.searchInputWrapper,children:[(0,we.jsx)("input",{ref:a,spellCheck:!1,onChange:c=>{t(c.currentTarget.value)},onFocus:c=>{c.currentTarget.select()},className:l.searchInput,placeholder:n,value:r,type:"text",id:"command-palette-search-input",autoFocus:!0}),s&&s.length>0&&(0,we.jsx)("div",{className:l.selectWrapper,children:(0,we.jsxs)("select",{"data-testid":"command-palette-type-select",className:l.select,onChange:c=>e(c.target.value===o?void 0:c.target.value),value:i||o,children:[o&&(0,we.jsx)("option",{children:o}),s.map(c=>(0,we.jsx)("option",{value:c.value,children:c.label},c.value))]})})]})]})}var ul=(0,cl.forwardRef)(am);var Fn=require("react/jsx-runtime");function Tt({placeholder:t="Start typing to search...",typePlaceholder:e="All types",defaultPage:n="search",page:o,onChangePage:s,onChangeSearch:r,onChangeType:i,onChangeOpen:a,selectedType:l,types:c,children:u,isOpen:d,search:p}){let[m,g]=(0,Zt.useState)(0),f=(0,Zt.useRef)(null),x=()=>{s&&s(n),i(void 0),r(""),a(!1)},b=()=>{var h;if(o!==n&&s){s(n);return}if(l&&i){i(void 0),(h=f.current)==null||h.focus();return}if(p.length>0){r("");return}a(!1)};return(0,Zt.useEffect)(()=>{g(0)},[p,o]),(0,Fn.jsx)(Bt,{autoFocus:!0,contentAriaLabel:"Search Results",overlayAriaLabel:"Command Palette",isOpen:d,onBack:b,onClose:x,children:(0,Fn.jsxs)(Xa,{selected:m,setSelected:g,isOpen:d,onChangeOpen:a,page:o,children:[o===n&&(0,Fn.jsx)(ul,{ref:f,onChange:r,onChangeType:i,placeholder:t,value:p,selectedType:l,types:c,typePlaceholder:e}),u]})})}Tt.Page=Or;Tt.List=Ir;Tt.Image=qa;Tt.ListItem=Mr;Tt.ActionsBar=ll;Tt.Button=Xt;var L=Tt;var W=require("react/jsx-runtime"),lm=({suggestion:t,onUse:e,onDismiss:n,onTouched:o,onNext:s,onPrevious:r})=>{let i=t.text||t.url||t.message,a=y("EditSuggestionForm",ma),l=(0,as.useDispatch)(),c=_(pr),u=(0,as.useSelector)(g=>g.overlayInput.text);(0,Br.useEffect)(()=>{t&&(l(Q.actions.reset()),l(Q.actions.stageSuggestion({text:i,suggestion:t,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"})),l(Q.actions.commitSuggestion()))},[t]);let d=g=>{g.preventDefault(),p(u)},p=g=>{l(ko(g)),e(g)},m=g=>f=>{u!==i?window.confirm(c("warning"))&&g(f):g(f)};return(0,Br.useEffect)(()=>{o&&o(u!==i)},[o,t,u]),(0,W.jsxs)("div",{className:a.root,children:[(0,W.jsxs)("div",{className:a.content,children:[t.title&&(0,W.jsx)("h3",{className:a.title,children:t.title}),t.searchKeywords&&t.searchKeywords.length>0&&(0,W.jsx)(Cr,{labels:t.searchKeywords}),(0,W.jsx)(Ua,{onUse:p,value:u})]}),(0,W.jsxs)("form",{className:a.actions,onSubmit:d,children:[(0,W.jsxs)("div",{children:[(0,W.jsx)("button",{disabled:!r,className:a.pagination,type:"button",onClick:r&&m(r),children:(0,W.jsx)(Go,{})}),(0,W.jsx)("button",{disabled:!s,className:a.pagination,type:"button",onClick:s&&m(s),children:(0,W.jsx)(wa,{})})]}),(0,W.jsxs)("div",{className:a.primaryButtons,children:[(0,W.jsx)(L.Button,{onClick:m(n),shortKeys:["esc"],children:c("dismiss")}),(0,W.jsx)(L.Button,{shortKeys:[8679,8629],type:"submit",children:c("add")})]})]})]})},ls=lm;var wt=require("@reduxjs/toolkit");var cm=["{amount}"," {amount}","{date}","{email}","{iban}","{name}","{postal_code}","{street}","{tarif}","{usage}","{3_digits}","{4_digits}","{5_digits}","{6_digits}","{7_digits}","{8_digits}","{9_digits}","{10_digits}"],um=new RegExp(cm.map(t=>`(?:${t.replace("{","\\{").replace("}","\\}")})`).join("|"));function pl(t,e){let n=t.split(um),o=0,s=[];for(let r=0;r<n.length;r++){let i=n[r];if(s.push(i),r===n.length-1)break;if(e.indexOf(i)===-1)return t;let a=n[r+1],l=r===n.length-2;o+=i.length;let c=o;if(l){let d=a.charAt(0),p=0;do c=d?e.indexOf(d,c+1):-1,p+=1;while(c!==-1&&a.indexOf(e.slice(c))!==0);if(c===-1&&p>2)return t}else c=a&&a!==""?e.indexOf(a,o):-1;let u=c===-1?e.slice(o):e.slice(o,c);s.push(u),o=c}return s.join("")}function dl(t,e){return typeof e=="boolean"?t:t.slice(0,e)}var gl={suggestions:[],fetchState:"idle",isInitialRequest:null},ml={default:gl},fl=t=>e=>{var n;return((n=e.textSuggestions[t])==null?void 0:n.suggestions)??[]},hl=t=>e=>{var n;return((n=e.textSuggestions[t])==null?void 0:n.suggestions)??[]},yl=t=>{let e=Object.keys(t.textSuggestions).map(n=>{var o;return(o=t.textSuggestions[n])==null?void 0:o.fetchState});return e.length===0?!0:e.every(n=>n!=="done")},Jt=t=>t.textSuggestions,Sl=t=>e=>e.text.startsWith(t),cs=(0,wt.createAction)("textSuggestions/refresh"),Fe=(0,wt.createAsyncThunk)("textSuggestions/recommendations",async(t,e)=>{var c;let{deepdeskAPI:n}=e.extra,o=e.getState(),s=(c=o.conversation.current)==null?void 0:c.id,{textSuggestionsCount:r,inlineSuggestions:i}=o.settings,a=Ht(o);if(!s)throw new Error("No current conversation to fetch text suggestions");let l=await n.getTextSuggestions(s,Dn(o),t);if(t==="default"){let u=i?l.filter(Sl(a)):l;e.dispatch(it(u.slice(0,r)))}return l}),Bn=(0,wt.createAsyncThunk)("textSuggestions/autocompletions",async(t,e)=>{var c;let{deepdeskAPI:n}=e.extra,o=e.getState(),s=(c=o.conversation.current)==null?void 0:c.id,{textSuggestionsCount:r,deanonymize:i,inlineSuggestions:a}=o.settings;if(!s)throw new Error("No current conversation to fetch text suggestions");let l=await n.getAutocompleteSuggestions(s,{...Dn(o),input:t});if(!e.getState().input.text)throw new Error("Abort");return a&&(l=l.filter(Sl(t))),i&&(l=l.map(u=>({...u,text:u.source!=="trie-with-typos"?pl(u.text,t):u.text}))),l=dl(l,r),e.dispatch(it(l)),l}),vl=(0,wt.createSlice)({name:"textSuggestions",initialState:ml,reducers:{setTextSuggestions:{reducer(t,e){let{contentType:n}=e.payload;t[n].fetchState="done",t[n].suggestions=e.payload.suggestions},prepare(t,e){return{payload:{contentType:t,suggestions:e}}}},setSuggestionState(t,e){return e.payload}},extraReducers:t=>{t.addCase(Fe.pending,(e,n)=>{let o=n.meta.arg,s=e[o]||gl;return{...e,[o]:{...s,fetchState:"loading",isInitialRequest:s.isInitialRequest===null}}}).addCase(Fe.rejected,(e,n)=>{let o=n.meta.arg;e[o].fetchState="error"}).addCase(Fe.fulfilled,(e,n)=>{let o=n.meta.arg;e[o].fetchState="done",e[o].suggestions=n.payload}).addCase(Bn.pending,e=>{e.default.fetchState="loading"}).addCase(Bn.rejected,e=>{e.default.fetchState="error"}).addCase(Bn.fulfilled,(e,n)=>{e.default.fetchState="done",e.default.suggestions=n.payload}).addCase(A,()=>ml)}}),{setTextSuggestions:xl,setSuggestionState:Cl}=vl.actions,Tl=vl.reducer;var bl=require("@reduxjs/toolkit");var wl={contentType:null,suggestion:null},El=t=>t.activeSuggestion.suggestion,_l=t=>t.activeSuggestion.contentType,Pl=(0,bl.createSlice)({name:"activeSuggestion",initialState:wl,reducers:{setActiveSuggestion(t,e){let{contentType:n,suggestion:o}=e.payload;t.contentType=n,t.suggestion=o},resetActiveSuggestion(t){t.contentType=null,t.suggestion=null}},extraReducers:t=>{t.addCase(A,()=>wl)}}),{setActiveSuggestion:Be,resetActiveSuggestion:Kr}=Pl.actions,kl=Pl.reducer;var Ur={};q(Ur,{enUS:()=>pm,nlNL:()=>dm});var pm={warning:[{type:0,value:"Are you sure you want to discard the message?"}],editContentLabel:[{type:0,value:"Edit and view suggestion"}],overlayLabel:[{type:0,value:"Close dialog"}]},dm={warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}],editContentLabel:[{type:0,value:"Bewerk en bekijk suggestie"}],overlayLabel:[{type:0,value:"Sluit"}]};var Rl=require("@reduxjs/toolkit"),mm={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var Il=({ui:t})=>t.overlayCollapsed;var Al=(0,Rl.createSlice)({name:"ui",initialState:mm,reducers:{setShowTabHint(t,e){t.showTabHint=e.payload},setInputHasFocus(t,e){t.overlayCollapsedUserOverwrite!==!0&&(e.payload===!0&&(t.overlayCollapsed=!1),t.inputHasFocus=e.payload)},setOverlayCollapsed(t,e){e.payload.collapse===!1&&(t.openOverlayWhenTyping=!1),!(e.payload.skipWhenInputFocus&&t.inputHasFocus)&&(t.overlayCollapsed=e.payload.collapse)},setOpenOverlayWhenTyping(t,e){t.openOverlayWhenTyping=e.payload},setOverlayCollapsedUserOverwrite(t,e){t.overlayCollapsedUserOverwrite=e.payload,t.overlayCollapsed=e.payload}}}),{setShowTabHint:Kn,setInputHasFocus:Yt,setOverlayCollapsed:en,setOpenOverlayWhenTyping:Ll,setOverlayCollapsedUserOverwrite:Ml}=Al.actions,Ol=Al.reducer;var Un=E(require("react")),Dl=require("react/jsx-runtime"),Nl=Un.default.createContext(null),qn=({broadcastEvents:t,children:e})=>{let n=Un.default.useMemo(()=>t,[]);return(0,Dl.jsx)(Nl.Provider,{value:n,children:e})},ge=()=>{let t=(0,Un.useContext)(Nl);if(!t)throw new Error("You should use the useBroadcastEvents within a BroadcastEventsProvider");return t};var tn=require("@reduxjs/toolkit");var gm={isLoggedIn:!0,loginFetchState:"idle",verifyFetchState:"idle",showLoginOverlay:!1},Ke=t=>t.auth.isLoggedIn,Hl=t=>t.auth.loginFetchState,Fl=t=>t.auth.verifyFetchState,Bl=t=>t.auth.showLoginOverlay,bt=(0,tn.createAsyncThunk)("auth/validate",async(t,e)=>e.extra.deepdeskAPI.isLoggedIn()),Kl=(0,tn.createAsyncThunk)("auth/requestLogin",async({email:t},e)=>{let{deepdeskAPI:n}=e.extra;return n.requestLoginByEmail(t)}),Vn=(0,tn.createAsyncThunk)("auth/verifyLoginToken",async({token:t},e)=>{let{deepdeskAPI:n}=e.extra;return n.verifyLoginToken(t)}),Ul=(0,tn.createSlice)({name:"auth",initialState:gm,reducers:{setIsLoggedIn(t,e){t.isLoggedIn=e.payload},setShowLoginOverlay(t,e){t.showLoginOverlay=e.payload}},extraReducers:t=>{t.addCase(bt.pending,e=>{e.loginFetchState="loading"}),t.addCase(bt.fulfilled,(e,{payload:n})=>{e.isLoggedIn=n,e.loginFetchState="done"}),t.addCase(bt.rejected,e=>{e.loginFetchState="error",e.isLoggedIn=!1}),t.addCase(Vn.pending,e=>{e.verifyFetchState="loading"}),t.addCase(Vn.rejected,e=>{e.verifyFetchState="error"}),t.addCase(Vn.fulfilled,(e,n)=>{n.payload.isLoggedIn?e.verifyFetchState="done":e.verifyFetchState="error"})}}),{setIsLoggedIn:us,setShowLoginOverlay:ql}=Ul.actions,Vl=Ul.reducer;var qr="SetActiveSuggestion",nn="ShowLoginOverlay",Vr="UserLoggedIn",Ue="ApplySuggestion",jr="ApplyImageSuggestion",fm="ShowCommandPalette",hm=t=>({[qr]:e=>{t.dispatch(Cl(e.state)),t.dispatch(Be({contentType:e.contentType,suggestion:e.suggestion}))},[fm]:e=>{t.dispatch(se(e.isOpen)),e.page&&t.dispatch(G(e.page))},[nn]:e=>{t.dispatch(ql(e))},[Vr]:()=>{t.dispatch(bt())},[jr]:e=>{t.dispatch(Io({suggestion:e.suggestion}))},[Ue]:e=>{t.dispatch(Ce({...e,eventMetrics:{inputType:"mouse"},replace:"selection"})),t.dispatch(at())}}),jl=hm;var zr=require("react/jsx-runtime"),ym=()=>{var g;let[t,e]=(0,zl.useState)(!1),n=(0,on.useSelector)(El),o=(0,on.useSelector)(_l),s=(0,on.useSelector)(Jt),r=(0,on.useDispatch)(),i=ge(),a=_(Ur),l=()=>{n!==null&&t?window.confirm(a("warning"))&&c():c()},c=()=>{r(Kr()),r(Yt(!0)),r(Q.actions.reset())},u=(f,x)=>{r(Kr()),r(Yt(!0)),i.send(Ue,{text:f,suggestion:x})};if(n===null||o===null)return null;let d=(g=s[o])==null?void 0:g.suggestions.indexOf(n),p=d===0||d===null?void 0:()=>r(Be({contentType:o,suggestion:s[o].suggestions[d-1]})),m=d===s[o].suggestions.length-1||d===null?void 0:()=>r(Be({contentType:o,suggestion:s[o].suggestions[d+1]}));return(0,zr.jsx)(Bt,{autoFocus:!0,isOpen:d!==null,onClose:l,onBack:l,contentAriaLabel:a("editContentLabel"),overlayAriaLabel:a("overlayLabel"),children:(0,zr.jsx)(ls,{onTouched:e,onDismiss:c,onUse:f=>u(f,n),suggestion:n,onNext:m,onPrevious:p})})},Wl=ym;var Gr=require("react-redux");var ps=E(require("classnames")),be=require("react"),ds=require("react-redux");var $l=E(require("classnames"));var Gl={root:"_root_1ukx5_1"};var Xl=require("react/jsx-runtime"),Sm=({className:t,value:e,...n})=>{let o=y("TextInput",Gl);return(0,Xl.jsx)("input",{className:(0,$l.default)(t,o.root),type:"text",value:e,...n})},jn=Sm;var Wr={};q(Wr,{enUS:()=>vm,nlNL:()=>xm});var vm={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"}]},xm={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 Ql={root:"_root_1edpl_1",anchorButton:"_anchorButton_1edpl_5",errorMessage:"_errorMessage_1edpl_19",title:"_title_1edpl_25",subtitle:"_subtitle_1edpl_31",text:"_text_1edpl_38",input:"_input_1edpl_43",actions:"_actions_1edpl_48",button:"_button_1edpl_55",primaryButton:"_primaryButton_1edpl_70"};var B=require("react/jsx-runtime");var Cm=t=>{try{let e=new URL(t);return new URLSearchParams(e.search).get("token")||void 0}catch{return t}},Tm=({agentEmail:t,isOpen:e,origin:n="",onSuccess:o,onDismiss:s})=>{let r=_(Wr),i=y("LoginTokenDialog",Ql),a=(0,ds.useSelector)(Fl),l=(0,ds.useDispatch)(),c=T("productName"),[u,d]=(0,be.useState)(t||""),[p,m]=(0,be.useState)(0),[g,f]=(0,be.useState)(""),x=(0,be.useCallback)(async C=>{C.preventDefault(),l(Kl({email:u})),m(1)},[n,u]),b=()=>{f(""),m(0)},h=(0,be.useCallback)(async C=>{C.preventDefault();let k=Cm(C.target.elements.token.value);if(!k){f(r("verifyCodeError",{login:v}));return}l(Vn({token:k}))},[n]),v=(0,be.useMemo)(()=>C=>(0,B.jsx)("button",{type:"button","data-testid":"login-token-dialog-back-button",className:i.anchorButton,onClick:b,children:C},"back-button"),[]);return(0,be.useEffect)(()=>{a==="error"&&f(r("verifyCodeError",{login:v})),a==="done"&&o()},[a]),(0,B.jsx)(Bt,{autoFocus:!0,isOpen:e,contentAriaLabel:r("promptTitle",{productName:c}),overlayAriaLabel:r("promptTitle",{productName:c}),onClose:s,onBack:s,children:(0,B.jsxs)("div",{className:i.root,children:[(0,B.jsx)("h1",{className:i.title,children:r("promptTitle",{productName:c})}),p===0&&(0,B.jsxs)("form",{onSubmit:x,children:[(0,B.jsx)("h2",{className:i.subtitle,children:r("requestCodeTitle")}),(0,B.jsx)("p",{className:i.text,children:r("requestCodeBody",{productName:c})}),(0,B.jsx)(jn,{className:i.input,name:"email",placeholder:r("requestCodeInputPlaceholder"),value:u,onChange:C=>d(C.target.value)}),(0,B.jsx)("div",{className:i.actions,children:(0,B.jsx)("button",{type:"submit",className:(0,ps.default)(i.button,i.primaryButton),children:r("requestCodeSubmitLabel")})})]}),p===1&&(0,B.jsxs)("form",{onSubmit:h,children:[(0,B.jsx)("h2",{className:i.subtitle,children:r("verifyCodeTitle")}),(0,B.jsx)("p",{className:i.text,children:r("verifyCodeBody")}),(0,B.jsx)(jn,{className:i.input,name:"token",placeholder:r("verifyCodeInputPlaceholder"),disabled:["loading","done"].includes(a)}),g&&(0,B.jsx)("div",{className:i.errorMessage,children:g}),(0,B.jsxs)("div",{className:i.actions,children:[(0,B.jsx)("button",{type:"button",className:(0,ps.default)(i.button),onClick:b,children:r("back")}),(0,B.jsx)("button",{type:"submit",className:(0,ps.default)(i.button,i.primaryButton),disabled:["loading","done"].includes(a),children:r("verifyCodeSubmitLabel")})]})]})]})})},Zl=Tm;var Yl=require("react/jsx-runtime"),wm=()=>{let t=(0,Gr.useSelector)(Bl),e=(0,Gr.useSelector)(Za),n=T("adminUrl"),o=ge(),s=()=>o.send(nn,!1),r=()=>{o.send(nn,!1),o.send(Vr)};return(0,Yl.jsx)(Zl,{isOpen:t,agentEmail:e==null?void 0:e.agentEmail,origin:n,onDismiss:s,onSuccess:r})},Jl=wm;var Tc=E(require("lodash.debounce")),re=require("react"),je=require("react-redux");var ms=require("@reduxjs/toolkit");var bm={data:null,fetchState:"idle"},ec=t=>t.contentTypes.data,zn=(0,ms.createAsyncThunk)("contentTypes/getContentTypes",async(t,e)=>e.extra.deepdeskAPI.getContentTypes()),Em=(0,ms.createSlice)({name:"contentTypes",initialState:bm,reducers:{},extraReducers:t=>{t.addCase(zn.pending,e=>{e.fetchState="loading"}).addCase(zn.rejected,e=>{e.fetchState="error"}).addCase(zn.fulfilled,(e,n)=>{e.fetchState="done",e.data=n.payload})}}),tc=Em.reducer;function Wn(t){let e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.left="-999999px",e.style.top="-999999px",document.body.appendChild(e),e.focus(),e.select(),document.execCommand("copy"),e.remove()}var nc=require("react");function oc(t,e){(0,nc.useEffect)(()=>{let n=o=>{var s;((s=navigator==null?void 0:navigator.platform)!=null&&s.toLowerCase().includes("mac")?o.metaKey:o.ctrlKey)&&o.key===t&&(o.preventDefault(),o.stopPropagation(),e())};return document.addEventListener("keydown",n),()=>{document.removeEventListener("keydown",n)}},[])}var Gn=require("react"),hs=require("react-redux");var gs=require("@reduxjs/toolkit");var sc={data:null,fetchState:"idle"},fs=t=>{var r;let e=[],{visitorName:n}=t.info.visitorInfo??{},{agentName:o,agentNickname:s}=t.info.agentInfo??{};return o&&o!==n&&e.push(o),s&&s!==n&&e.push(s),((r=t.entities.data)==null?void 0:r.filter(i=>!e.includes(i.text)))??null},Ee=(0,gs.createAsyncThunk)("entities/getEntities",async(t,e)=>{let{deepdeskAPI:n,dynamicThunkObject:o}=e.extra;if(!o.conversationQuery)return Promise.resolve([]);let s=o.conversationQuery,r=await s();return r.length===0?Promise.resolve([]):n.getEntities(r)}),_m=t=>t.filter((e,n)=>n===t.findIndex(o=>o.text===e.text)),Pm=(0,gs.createSlice)({name:"entities",initialState:sc,reducers:{},extraReducers:t=>{t.addCase(Ee.pending,e=>{e.fetchState="loading"}).addCase(Ee.rejected,e=>{e.fetchState="error"}).addCase(Ee.fulfilled,(e,n)=>{e.fetchState="done",e.data=_m(e.data?[...e.data,...n.payload]:n.payload)}).addCase(A,()=>sc)}}),rc=Pm.reducer;var $r={};q($r,{enUS:()=>km,nlNL:()=>Rm});var km={noResults:[{type:0,value:"No entities have been found"}],copy:[{type:0,value:"Copy"}],use:[{type:0,value:"Use"}]},Rm={noResults:[{type:0,value:"Er zijn geen entiteiten gevonden"}],copy:[{type:0,value:"Kopieer"}],use:[{type:0,value:"Gebruik"}]};var ic={root:"_root_17kae_1",empty:"_empty_17kae_5"};var Et=require("react/jsx-runtime"),Im=({onCopy:t,onUse:e})=>{let n=(0,Gn.useRef)(null),o=y("EntitiesList",ic),s=_($r),r=(0,hs.useSelector)(fs),i=(0,hs.useDispatch)();return(0,Gn.useEffect)(()=>{i(Ee())},[]),(0,Gn.useEffect)(()=>{n.current&&n.current.focus()},[n]),(0,Et.jsxs)("div",{className:o.root,ref:n,tabIndex:-1,children:[r&&r.length>0&&(0,Et.jsx)(L.ActionsBar,{primaryLabel:s("copy"),secondaryLabel:s("use"),onPrimary:(a,l)=>t(r[l]),onSecondary:(a,l)=>e(r[l]),list:r.map(a=>({text:a.text,type:a.label,primaryAction:"copy",secondaryAction:"use"})),children:(0,Et.jsx)(L.List,{children:r.map((a,l)=>(0,Et.jsx)(L.ListItem,{index:l,closeOnSelect:!0,onClick:()=>t(a),children:a.text},a.text))},"entities")}),r&&r.length===0&&(0,Et.jsx)("p",{className:o.empty,children:s("noResults")})]})},ac=Im;var _e=require("react"),$n=require("react-redux");var ys=require("@reduxjs/toolkit");var lc={data:null,fetchState:"idle"},cc=t=>t.summary.data,uc=t=>t.summary.fetchState==="error",qe=(0,ys.createAsyncThunk)("summary/getSummary",async(t,e)=>{let{deepdeskAPI:n,dynamicThunkObject:o}=e.extra;if(!o.conversationQuery)return Promise.reject(new Error("setConversationQuery method is not defined"));let s=o.conversationQuery,r=await s();if(r.length===0)return Promise.reject(new Error("No messages are included"));let i=await n.getSummary(r);return{original:r,summary:i}}),Am=(0,ys.createSlice)({name:"summary",initialState:lc,reducers:{},extraReducers:t=>{t.addCase(qe.pending,e=>{e.data=null,e.fetchState="loading"}).addCase(qe.rejected,e=>{e.data=null,e.fetchState="error"}).addCase(qe.fulfilled,(e,n)=>{e.fetchState="done",n.payload&&(e.data=n.payload.summary)}).addCase(A,()=>lc)}}),pc=Am.reducer;var Xr={};q(Xr,{enUS:()=>Lm,nlNL:()=>Mm});var Lm={copy:[{type:0,value:"Copy"}],error:[{type:0,value:"Could not generate a summary"}],loading:[{type:0,value:"Generating summary, this may take a few moments."}]},Mm={copy:[{type:0,value:"Kopieer"}],error:[{type:0,value:"Kon helaas geen samenvatting genereren."}],loading:[{type:0,value:"Samenvatting wordt gemaakt, dit kan even duren."}]};var dc={root:"_root_18y7z_1",actions:"_actions_18y7z_5",main:"_main_18y7z_11",textInput:"_textInput_18y7z_15",loading:"_loading_18y7z_34",error:"_error_18y7z_38"};var Ve=require("react/jsx-runtime"),Om=({onCopy:t})=>{let e=(0,_e.useRef)(null),n=y("SummaryForm",dc),[o,s]=(0,_e.useState)(""),r=_(Xr),i=(0,$n.useSelector)(cc),a=(0,$n.useSelector)(uc),l=(0,$n.useDispatch)(),c=()=>{l(Re({name:"summary copied to clipboard",data:{originalText:i,finalText:o},options:{includeConversationData:!0}})),t(o)},u=()=>{let d=document.getSelection();d&&l(Re({name:"summary copied to clipboard",data:{originalText:i,finalText:d==null?void 0:d.toString()},options:{includeConversationData:!0}}))};return(0,_e.useEffect)(()=>{l(qe())},[]),(0,_e.useEffect)(()=>{s(i||"")},[i]),(0,_e.useEffect)(()=>{e.current&&i&&e.current.focus()},[e,i]),(0,_e.useEffect)(()=>{let d=p=>{p.key==="Enter"&&p.shiftKey&&c()};return document.addEventListener("keydown",d),()=>{document.removeEventListener("keydown",d)}},[o]),(0,Ve.jsx)("div",{className:n.root,tabIndex:-1,children:a?(0,Ve.jsx)("p",{className:n.error,children:r("error")}):(0,Ve.jsxs)(_e.Fragment,{children:[(0,Ve.jsx)("div",{className:n.main,children:(0,Ve.jsx)("textarea",{placeholder:i?void 0:r("loading"),disabled:!i,className:n.textInput,ref:e,value:o,onCopy:u,onChange:d=>s(d.target.value)})}),(0,Ve.jsx)("div",{className:n.actions,children:(0,Ve.jsx)(L.Button,{shortKeys:[8679,8629],onClick:c,children:r("copy")})})]})})},mc=Om;var Qr={};q(Qr,{enUS:()=>Nm,nlNL:()=>Dm});var Nm={personalCollectionLink:[{type:0,value:"Go to Personal Collection"}],searchPlaceholder:[{type:0,value:"Start typing to search..."}],urlSuggestions:[{type:0,value:"Link suggestions"}],personalSuggestions:[{type:0,value:"Personal suggestions"}],pinnedMessages:[{type:0,value:"Pinned messages"}],imageSuggestions:[{type:0,value:"Images"}],typePlaceholder:[{type:0,value:"All types"}],navigation:[{type:0,value:"Navigation"}],entitiesClipboard:[{type:0,value:"Conversation clipper"}],entitiesTitle:[{type:0,value:"Copy to your clipboard"}],summaryClipboard:[{type:0,value:"Summarize conversation"}],summaryTitle:[{type:0,value:"Conversation summary"}],knowledgeSearch:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Commands"}],use:[{type:0,value:"Use"}],preview:[{type:0,value:"Preview"}],warning:[{type:0,value:"Are you sure you want to discard the message?"}]},Dm={personalCollectionLink:[{type:0,value:"Ga naar persoonlijke collectie"}],searchPlaceholder:[{type:0,value:"Begin met typen om te zoeken..."}],personalSuggestions:[{type:0,value:"Persoonlijke suggesties"}],urlSuggestions:[{type:0,value:"Link suggesties"}],imageSuggestions:[{type:0,value:"Afbeeldingen"}],navigation:[{type:0,value:"Navigatie"}],typePlaceholder:[{type:0,value:"Alle types"}],pinnedMessages:[{type:0,value:"Actueel"}],entitiesClipboard:[{type:0,value:"Klembord"}],entitiesTitle:[{type:0,value:"Kopieer naar klembord"}],summaryClipboard:[{type:0,value:"Vat gesprek samen"}],summaryTitle:[{type:0,value:"Gesprek samenvatting"}],knowledgeSearch:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Acties"}],use:[{type:0,value:"Gebruik"}],preview:[{type:0,value:"Bewerk"}],warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}]};var _t=E(require("react")),Zn=require("react-redux");var Zr={};q(Zr,{enUS:()=>Hm,nlNL:()=>Fm});var Hm={use:[{type:0,value:"Use"}],loading:[{type:0,value:"Loading..."}],error:[{type:0,value:"Something went wrong, please try again later."}],anotherQuestion:[{type:0,value:"Send a message..."}],reset:[{type:0,value:"Reset conversation"}]},Fm={use:[{type:0,value:"Gebruik"}],loading:[{type:0,value:"Laden..."}],error:[{type:0,value:"Er ging iets mis, probeer het later opnieuw."}],anotherQuestion:[{type:0,value:"Stuur een bericht..."}],reset:[{type:0,value:"Reset gesprek"}]};var gc={root:"_root_cnaw4_1",title:"_title_cnaw4_9",empty:"_empty_cnaw4_20",status:"_status_cnaw4_24",form:"_form_cnaw4_30",input:"_input_cnaw4_43",submit:"_submit_cnaw4_55",question:"_question_cnaw4_63",answer:"_answer_cnaw4_67",alignRight:"_alignRight_cnaw4_73"};var rn=require("@reduxjs/toolkit");var Jr={data:[],fetchState:"idle"},fc=t=>{var e;return(e=t.answer)==null?void 0:e.data},hc=t=>t.answer.fetchState,Xn=(0,rn.createAction)("answer/resetKnowledgeSearch"),sn=(0,rn.createAsyncThunk)("answer/getAnswer",async(t,e)=>{var i;let{deepdeskAPI:n}=e.extra,o=e.getState().answer.data,s=(i=e.getState().profile.data)==null?void 0:i.code;if(!s)throw new Error("Profile is not defined");let r=await n.knowledgeSearch({promptInstruction:t.promptInstruction,question:t.question},o,s);return{question:t.question,answer:r}}),Bm=(0,rn.createSlice)({name:"answer",initialState:Jr,reducers:{},extraReducers:t=>{t.addCase(sn.pending,e=>{e.fetchState="loading"}).addCase(sn.rejected,e=>{e.fetchState="error"}).addCase(sn.fulfilled,(e,n)=>{e.fetchState="done",e.data=[...e.data,n.payload]}).addCase(A,()=>Jr).addCase(Xn,()=>Jr)}}),yc=Bm.reducer;var Qn=require("react/jsx-runtime"),Sc=()=>(0,Qn.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 512 512","aria-labelledby":"paperPlaneTitle",children:[(0,Qn.jsx)("title",{id:"paperPlaneTitle",children:"PaperPlane"}),(0,Qn.jsx)("path",{d:"M498.1 5.6c10.1 7 15.4 19.1 13.5 31.2l-64 416c-1.5 9.7-7.4 18.2-16 23s-18.9 5.4-28 1.6L284 427.7l-68.5 74.1c-8.9 9.7-22.9 12.9-35.2 8.1S160 493.2 160 480V396.4c0-4 1.5-7.8 4.2-10.7L331.8 202.8c5.8-6.3 5.6-16-.4-22s-15.7-6.4-22-.7L106 360.8 17.7 316.6C7.1 311.3 .3 300.7 0 288.9s5.9-22.8 16.1-28.7l448-256c10.7-6.1 23.9-5.5 34 1.4z"})]});var Y=require("react/jsx-runtime"),Km=({onUse:t,onResetQuestion:e,question:n,promptInstruction:o})=>{let[s,r]=_t.default.useState(""),{setSelected:i}=lt(),a=(0,_t.useRef)(null),l=y("EntitiesList",gc),c=_(Zr),u=(0,Zn.useDispatch)(),d=(0,Zn.useSelector)(fc),p=(0,Zn.useSelector)(hc),m=async g=>{g.preventDefault(),g.stopPropagation(),s!==""&&u(sn({question:s,promptInstruction:o}))};return(0,_t.useEffect)(()=>{var g;n&&p==="idle"?u(sn({question:n,promptInstruction:o})):(g=a.current)==null||g.focus()},[a,p]),(0,_t.useEffect)(()=>{p==="done"&&(i(0),r(""))},[p,d]),(0,Y.jsxs)("div",{className:l.root,children:[d.length>0&&(0,Y.jsx)("div",{className:l.alignRight,children:(0,Y.jsx)(L.Button,{onClick:e,children:c("reset")})}),(0,Y.jsxs)(L.ActionsBar,{list:d.map(({answer:g})=>({text:g.answer,type:"answer"})),primaryLabel:c("use"),onPrimary:g=>t(g.text),children:[d.map(({question:g,answer:f},x)=>(0,Y.jsx)(L.List,{children:(0,Y.jsx)(L.ListItem,{"data-testid":"knowledge-search-answer",index:x,description:f.answer,closeOnSelect:!0,onClick:()=>t(f.answer),sources:f.sources,styles:{title:l.question,description:l.answer},children:g})},`${f.answer}_${x}`)),p==="loading"&&(0,Y.jsx)("p",{className:l.status,children:c("loading")}),p==="error"&&(0,Y.jsx)("p",{className:l.status,children:c("error")}),(0,Y.jsxs)("form",{className:l.form,onSubmit:m,children:[(0,Y.jsx)("input",{ref:a,placeholder:c("anotherQuestion"),className:l.input,type:"text",value:s,onFocus:()=>{i(-1)},onChange:g=>{i(-1),r(g.target.value)}}),(0,Y.jsx)("button",{type:"submit",className:l.submit,children:(0,Y.jsx)(Sc,{})})]})]})]})},vc=Km;var Ss=require("@reduxjs/toolkit");var Um={data:null,fetchState:"idle"},an=t=>t.profile.data,vs=t=>t.profile.data?t.profile.data.uiConfig.widget.types.filter(e=>e.isActive):[],Jn=(0,Ss.createAsyncThunk)("profile/getProfile",async(t,e)=>{let{deepdeskAPI:n}=e.extra,s=e.getState().conversation.current;if(!s||!s.profileCode)throw new Error("No conversation of conversation profileCode found");return n.getProfile(s.profileCode)}),qm=(0,Ss.createSlice)({name:"profile",initialState:Um,reducers:{},extraReducers:t=>{t.addCase(Jn.pending,e=>{e.fetchState="loading"}).addCase(Jn.rejected,e=>{e.fetchState="error"}).addCase(Jn.fulfilled,(e,n)=>{e.fetchState="done",e.data=n.payload})}}),xc=qm.reducer;var U=require("react/jsx-runtime"),Vm=200,jm=5,zm=4,Wm=t=>t.reduce((e,n)=>[...e,...n.list.map(o=>({...o,type:n.value}))],[]),Cc=(t,e)=>!e||t.toLowerCase().includes(e.toLowerCase()),Gm=()=>{let t=(0,je.useDispatch)(),e=ge(),n=_(Qr),[o,s]=(0,re.useState)(!1),[r,i]=(0,re.useState)(""),a=(0,je.useSelector)(nl),l=(0,je.useSelector)(an),[c,u]=(0,re.useState)(null),[d,p]=(0,re.useState)([]),[m,g]=(0,re.useState)(),f=(0,je.useSelector)(Ke),x=T("showSearch"),b=T("showEntitiesCommand"),h=T("showSummaryCommand"),v=T("showKnowledgeSearch"),C=T("showImageSearch"),k=T("searchTriggerKey"),w=(0,je.useSelector)(ec),H=(0,je.useSelector)(ol),te=(0,je.useSelector)(tl),R=S=>or(H.filter(M=>M.type===S.toUpperCase()),S),ne=[{value:"PERSONAL",label:n("personalSuggestions"),list:R("PERSONAL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"URL",label:n("urlSuggestions"),list:R("URL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"STICKYMESSAGE",label:n("pinnedMessages"),list:R("STICKYMESSAGE"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"IMAGE",label:n("imageSuggestions"),lineClamp:!1,list:R("IMAGE"),listOrientation:"horizontal",shouldShow:C}].filter(S=>S.shouldShow),Pe=[{label:n("entitiesClipboard"),onClick:()=>t(G("entities")),shouldShow:b&&Cc(n("entitiesClipboard"),r),experimental:!0},{label:n("summaryClipboard"),onClick:()=>t(G("summary")),shouldShow:h&&Cc(n("summaryClipboard"),r),experimental:!0},{label:r?`${n("knowledgeSearch")}: ${r}`:n("knowledgeSearch"),onClick:()=>t(G("knowledgeSearch")),shouldShow:v,experimental:!0}].filter(S=>S.shouldShow),Se=(w==null?void 0:w.map(S=>({value:S.code.toUpperCase(),label:`${S.name}s`,list:R(S.code.toUpperCase()),listOrientation:"vertical",lineClamp:!0})))||[],mo=(0,re.useCallback)((0,Tc.default)((S,M)=>{t(Ct({query:S,type:M,tags:["search-overlay"]}))},Vm),[]),go=Wm([...Se,...ne]),Jp=(0,re.useCallback)((S,M)=>{if(!M)return;let tt=[...ne,...Se].find(({value:Nt})=>Nt===M);tt&&(t(G("edit")),u(S),p(tt.list))},[t,c,Se]),nr=(0,re.useCallback)((S,M)=>{switch(M.type){case"IMAGE":e.send(jr,{suggestion:M});break;default:e.send(Ue,{text:S,suggestion:M})}t(se(!1))},[t]),Yp=S=>{Wn(S.text),t(Re({name:"entity copied",data:{entity:S,type:"copy"}})),t(se(!1))},ed=S=>{e.send(Ue,{text:S,suggestion:{source:"knowledge-search",text:S}}),t(Re({name:"answer used",data:{originalText:S},options:{includeConversationData:!0}})),i(""),t(G("search")),t(Xn()),t(se(!1))},td=S=>{Wn(S),t(se(!1))},nd=S=>{e.send(Ue,{text:S.text,suggestion:{source:"entity",text:S.text}}),t(se(!1))},od=c===null||d.indexOf(c)-1<0?void 0:()=>u(d[d.indexOf(c)-1]),sd=c===null||d.indexOf(c)===d.length-1?void 0:()=>u(d[d.indexOf(c)+1]);function or(S,M){return S.slice(0,m?10:M.toLowerCase()==="image"?zm:jm)}function Fi(S,M,tt){return M.reduce((Nt,fo)=>tt&&m===tt?fo.length+Nt:or(fo,tt).length+Nt,S)}function Ot(S){return M=>{o?window.confirm(n("warning"))&&(S(M),s(!1)):S(M)}}return(0,re.useEffect)(()=>{r?mo(r,m):t(ss())},[r,m]),(0,re.useEffect)(()=>{f&&t(zn())},[f]),oc(k,()=>t(se(!0))),!x||!l?null:(0,U.jsxs)(L,{placeholder:n("searchPlaceholder"),typePlaceholder:n("typePlaceholder"),onChangeSearch:i,onChangeOpen:Ot(S=>t(se(S))),onChangeType:S=>g(S),onChangePage:Ot(S=>t(G(S))),selectedType:m,search:r,page:a,isOpen:te,types:[...Se,...ne],children:[(0,U.jsx)(L.Page,{id:"search",children:(0,U.jsxs)(L.ActionsBar,{list:[...Pe.map(S=>({text:S.label,type:"command"})),...go.map(S=>({text:S.text||S.url||S.message,type:S.type}))],primaryLabel:n("use"),secondaryLabel:n("preview"),onPrimary:({text:S},M)=>nr(S,go[M]),onSecondary:(S,M)=>Jp(go[M],go[M].type),children:[Pe.length>0&&(0,U.jsx)(L.List,{heading:n("commands"),children:Pe.map((S,M)=>(0,U.jsx)(L.ListItem,{index:Fi(M,[],"commands"),closeOnSelect:!1,onClick:S.onClick,isExperimental:S.experimental,children:S.label},S.label))}),[...Se,...ne].map(({value:S,label:M,list:tt,lineClamp:Nt,listOrientation:fo},rd)=>(0,U.jsx)(L.List,{heading:M,orientation:fo==="horizontal"?"horizontal":"vertical",children:or(tt,S).map((ve,id)=>(0,U.jsx)(L.ListItem,{index:Fi(Pe.length+id,[...Se,...ne].slice(0,rd).map(({list:ad})=>ad),S),closeOnSelect:!1,lineClamp:Nt,onClick:()=>nr(ve.text,ve),description:S!=="IMAGE"?ve.title&&ve.text:void 0,children:S==="IMAGE"?(0,U.jsx)(L.Image,{title:ve.title||ve.text,src:ve.image}):ve.title||ve.text},`${ve.id}-${ve.text}`))},S))]})}),(0,U.jsx)(L.Page,{id:"edit",onDismiss:Ot(()=>{t(G("search")),u(null)}),children:c&&(0,U.jsx)(ls,{suggestion:c,onTouched:s,onDismiss:()=>{s(!1),t(G("search")),u(null),p([])},onNext:sd,onPrevious:od,onUse:S=>{t(G("search")),nr(S,c),t(se(!1)),p([]),u(null)}})}),(0,U.jsx)(L.Page,{id:"entities",title:n("entitiesTitle"),isExperimental:!0,onDismiss:Ot(()=>{t(G("search"))}),children:(0,U.jsx)(ac,{onUse:nd,onCopy:Yp})}),(0,U.jsx)(L.Page,{id:"summary",title:n("summaryTitle"),isExperimental:!0,onDismiss:Ot(()=>{t(G("search"))}),children:(0,U.jsx)(mc,{onCopy:td})}),(0,U.jsx)(L.Page,{id:"knowledgeSearch",title:n("knowledgeSearch"),isExperimental:!0,onDismiss:Ot(()=>{t(Xn()),t(G("search"))}),children:(0,U.jsx)(vc,{promptInstruction:l.knowledgeSearchPromptInstruction,question:r,onUse:ed,onResetQuestion:()=>{t(Xn()),i("")}})})]})},wc=Gm;var ln=require("react/jsx-runtime"),$m=()=>{let t=T("showSearch"),e=T("isEmbedded");return(0,ln.jsxs)(bc.Fragment,{children:[t&&(0,ln.jsx)(wc,{}),(0,ln.jsx)(Wl,{}),e&&(0,ln.jsx)(Jl,{})]})},Ec=$m;var _c=require("react-redux");var Yn=require("react/jsx-runtime"),Xm=({children:t})=>{let n=T("locale").replace("-","");return(0,Yn.jsx)(vr.Provider,{value:n,children:t})},Qm=({store:t,customStyles:e={},children:n})=>(0,Yn.jsx)(_c.Provider,{store:t,children:(0,Yn.jsx)(Xm,{children:(0,Yn.jsx)(Tn.Provider,{value:e,children:n})})}),eo=Qm;var bs=E(require("classnames")),pn=require("react"),We=require("react-redux");var Pc=require("react");function kc(t,e){let[n,o]=(0,Pc.useState)(()=>{if(typeof window>"u")return e;try{let r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return P.error(r),e}});return[n,r=>{try{let i=r instanceof Function?r(n):r;o(i),typeof window<"u"&&window.localStorage.setItem(t,JSON.stringify(i))}catch(i){P.error(i)}}]}function xs(t){let{showMidSentenceSuggestions:e,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:o}=t.settings,{text:s,selection:r}=t.input.userCommitted;return r.start!==r.end?!1:r.end>=s.length?!0:e?n&&new RegExp(n).test(s.substring(r.end))||o&&new RegExp(o).test(s.substring(0,r.end))?!0:n===!1&&o===!1:!1}var Ic=E(require("classnames")),ze=require("react");var Yr={};q(Yr,{enUS:()=>Zm,nlNL:()=>Jm});var Zm={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Sign in"}]},{type:0,value:" to enable "},{type:1,value:"productName"},{type:0,value:"."}],snooze:[{type:0,value:"Snooze for "},{type:8,value:"min",children:[{type:0,value:"10 minutes"}]},{type:0,value:", "},{type:8,value:"hour",children:[{type:0,value:"1 hour"}]},{type:0,value:" or "},{type:8,value:"day",children:[{type:0,value:"1 day"}]}]},Jm={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Log in"}]},{type:0,value:" bij "},{type:1,value:"productName"},{type:0,value:"."}],snooze:[{type:0,value:"Snooze voor "},{type:8,value:"min",children:[{type:0,value:"10 minuten"}]},{type:0,value:", "},{type:8,value:"hour",children:[{type:0,value:"1 uur"}]},{type:0,value:" of "},{type:8,value:"day",children:[{type:0,value:"1 dag"}]}]};var Rc={root:"_root_1vfca_1",anchor:"_anchor_1vfca_6",anchorButton:"_anchorButton_1vfca_11"};var pt=require("react/jsx-runtime"),ei=(t,e,n)=>o=>(0,pt.jsx)("button",{className:t.anchorButton,type:"button",value:e,onClick:n,children:o},e),Ym=({className:t,loginUrl:e,isEmbedded:n,onSnooze:o})=>{let s=_(Yr),r=ge(),i=y("Login",Rc),a=T("productName"),l=(0,ze.useCallback)(f=>{f.preventDefault(),o&&o(parseInt(f.target.value,10))},[]),c=(0,ze.useCallback)(f=>{f.preventDefault(),r.send(nn,!0)},[e]),u=(0,ze.useMemo)(()=>f=>(0,pt.jsx)("a",{href:e,className:i.anchor,target:"_blank",rel:"noreferrer",children:f},"login"),[e]),d=(0,ze.useCallback)(f=>(0,pt.jsx)("button",{type:"button",className:i.anchorButton,onClick:c,children:f},"prompt"),[c]),{min:p,hour:m,day:g}=(0,ze.useMemo)(()=>({min:ei(i,60*10,l),hour:ei(i,60*60,l),day:ei(i,60*60*12,l)}),[]);return(0,pt.jsxs)("div",{className:(0,Ic.default)(t,i.root),children:[s("loginPlease",{login:n?d:u,productName:a}),o&&(0,pt.jsxs)(ze.Fragment,{children:[(0,pt.jsx)("br",{}),s("snooze",{min:p,hour:m,day:g})]})]})},Cs=Ym;var Lc=require("react-redux");var Ac={root:"_root_1g8fi_1",text:"_text_1g8fi_19"};var to=require("react/jsx-runtime"),eg=({title:t})=>{let e=y("SearchTrigger",Ac),n=(0,Lc.useDispatch)();return(0,to.jsxs)("button",{type:"button",className:e.root,onClick:()=>n(se(!0)),children:[(0,to.jsx)(Qt,{}),(0,to.jsx)("span",{className:e.text,children:t})]})},Mc=eg;var Nc=E(require("classnames"));var Oc={root:"_root_fp74r_1",isWithDivider:"_isWithDivider_fp74r_9"};var Dc=require("react/jsx-runtime"),tg=({withDivider:t,children:e})=>{let n=y("SuggestionList",Oc);return(0,Dc.jsx)("div",{className:(0,Nc.default)(n.root,{[n.isWithDivider]:t}),children:e})},Le=tg;var jc=require("react");var qc=require("interweave"),un=require("react"),Ts=require("react-redux");var Hc=require("react");function Fc(t,e,n){(0,Hc.useEffect)(()=>{let o=t.current;return o?(o.addEventListener(e,n),()=>{o.removeEventListener(e,n)}):()=>{}},[t,e,n])}var ng=/[.*+?^${}()|[\]\\]/g,og=/[^0-9A-Za-zÀ-ÖØ-öø-ÿ](?=[0-9A-Za-zÀ-ÖØ-öø-ÿ]*$)/;function sg(t){return t.replace(ng,"\\$&")}function rg(t,e){let n=t.split("").findIndex((o,s)=>o!==e[s]);return n>-1?n:Math.min(t.length,e.length)}function ti(t){return t.search(og)}function Bc(t,e=[]){let n=t;return e.forEach(o=>{if(!o)return;let s=new RegExp(`\\b(${sg(o)})\\b`,"gi");n=n.replace(s,"<strong>$1</strong>")}),n}function Kc(t){return t.replace(Dt,'<mark data-type="placeholder">$1</mark>')}function cn(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ig(t,e){return t.split("").map((i,a)=>({char:i,index:a})).filter(({char:i,index:a})=>/\s/.test(i)&&a<=e).map(({index:i})=>i).reverse()[0]}function ni(t,e,n={}){if(e){let o=rg(e.toLowerCase(),t.toLowerCase()),s=cn(t.substring(o,t.length));if(n.stripAgentPart){let l=t.substring(0,o),c=ti(l);return`<span style="opacity: 0.5">${l.substring(c+1)}</span>${s}`}let i=e.split(Ki).length>3||e.length>30?ig(e.trim(),o):0;return`${`${i>0?"\u2026":""}${cn(t.substring(i,o))}`}<strong>${s}</strong>`}return t}var Uc={badge:"_badge_8rv7b_1",formattedText:"_formattedText_8rv7b_5"};var oi=require("react/jsx-runtime"),lg=["search","personal-collection-search","studio-search"];function cg(t,e,n,o={}){let s="";return lg.includes(e)?s=Bc(ni(t,n,{stripAgentPart:!0}),o.searchKeywords??[n]):s=ni(t,n,o),o.placeholders===!0&&(s=Kc(s)),s}var ug=()=>{},pg=({index:t,selected:e,suggestion:n})=>{let o=T("inlineSuggestions"),s=(0,Ts.useSelector)(Ht),r=(0,Ts.useDispatch)(),i=y("TextSuggestion",Uc),a=(0,un.useRef)(null);(0,un.useEffect)(()=>{let c=setTimeout(()=>{r(sa({text:n.text,suggestion:n}))},500);return()=>{clearTimeout(c)}},[n]),Fc(a,"click",()=>{r(Ao(t)),r(Ce({suggestion:n,text:n.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let l=(0,un.useMemo)(()=>cg(n.text,n.source,s,{stripAgentPart:o,placeholders:!0,searchKeywords:n.searchKeywords}),[o,n.text,n.source,s,n.searchKeywords]);return n.source==="gpt"?null:(0,oi.jsx)(N,{ref:a,as:"button",selected:e,onClick:ug,children:(0,oi.jsx)(qc.Interweave,{containerTagName:"div",noWrap:!1,tagName:"span",className:i.formattedText,content:l})})},Vc=pg;var si=require("react/jsx-runtime"),dg=({suggestions:t,selectedIndex:e})=>(0,si.jsx)(jc.Fragment,{children:t.slice().map((n,o)=>(0,si.jsx)(Vc,{index:o,selected:o===e,suggestion:n},`${n.text}-${n.source}`)).reverse()}),zc=dg;var Gc=E(require("classnames"));var Wc={root:"_root_1wpmq_1",isCollapsed:"_isCollapsed_1wpmq_17"};var ws=require("react/jsx-runtime"),mg=({className:t,isCollapsed:e,title:n,onClick:o})=>{let s=y("ToggleButton",Wc);return(0,ws.jsx)("button",{type:"button",className:(0,Gc.default)(s.root,t,{[s.isCollapsed]:e}),onClick:o,title:n,children:(0,ws.jsx)("svg",{width:"14",height:"8",viewBox:"-2.5 -5 75 60",preserveAspectRatio:"none",children:(0,ws.jsx)("path",{d:"M0,0 l35,50 l35,-50",fill:"none",stroke:"grey",strokeLinecap:"round",strokeWidth:"6"})})})},Pt=mg;var ri={};q(ri,{enUS:()=>gg,nlNL:()=>fg});var gg={arrowHint:[{type:0,value:"Tip: use arrow keys to navigate suggestions"}],searchHintWindows:[{type:0,value:"Press CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],searchHintMac:[{type:0,value:"Press CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Close"}],search:[{type:0,value:"Search"}]},fg={arrowHint:[{type:0,value:"Tip: Selecteer suggesties met pijltoetsen"}],searchHintWindows:[{type:0,value:"Druk CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],searchHintMac:[{type:0,value:"Druk CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Sluiten"}],search:[{type:0,value:"Zoeken"}]};var $c={root:"_root_4kcme_1",isInline:"_isInline_4kcme_14",toggleButton:"_toggleButton_4kcme_18",toggleButtonWrapper:"_toggleButtonWrapper_4kcme_22",toggleButtonWrapperHidden:"_toggleButtonWrapperHidden_4kcme_29",isCollapsed:"_isCollapsed_4kcme_33",collapsible:"_collapsible_4kcme_33",hints:"_hints_4kcme_41",hintsHidden:"_hintsHidden_4kcme_48",triggers:"_triggers_4kcme_53",triggersRight:"_triggersRight_4kcme_68"};var D=require("react/jsx-runtime"),hg=({inline:t=!1,textSuggestions:e,selectedIndex:n})=>{let o=y("SuggestionsOverlay",$c),s=_(ri),r=T("inlineSuggestions"),i=(0,We.useSelector)(xs),a=Yi(),l=(0,We.useDispatch)(),c=(0,pn.useRef)(null),u=T("searchTriggerKey"),d=T("productName"),p=(0,We.useSelector)(Il),m=(0,We.useSelector)(Ke),g=(0,We.useSelector)(vo),[f,x]=(0,pn.useState)(null),b=T("showSearch"),h=T("showTextSuggestions"),v=T("adminUrl"),C=T("isEmbedded"),[k,w]=kc("dd-snooze-until-ms",0),H=p||k>Date.now(),te=e.filter(Pe=>Pe.source!=="gpt").length,R=()=>{H&&w(0),l(Ml(!H))},ne=Pe=>{let Se=Date.now()+Pe*1e3;w(Se),P.info(`Snooze until: ${new Date(Se)}`),l(en({collapse:!0}))};return(0,pn.useEffect)(()=>{te===0&&x(null)},[e,te]),zt(()=>{l(en({collapse:!0,skipWhenInputFocus:!0}))}),r!==t||m===null||g===!1?null:m===!1?(0,D.jsxs)("div",{ref:c,className:(0,bs.default)(o.root,{[o.isCollapsed]:H,[o.isInline]:t}),"data-inline":t,children:[!H&&(0,D.jsxs)("div",{className:o.triggers,children:[(0,D.jsx)("div",{style:{flex:1}}),(0,D.jsx)("div",{className:o.triggersRight,children:(0,D.jsx)(Pt,{className:o.toggleButton,title:s("collapse"),onClick:R,isCollapsed:!1})})]}),(0,D.jsx)("div",{className:o.toggleButtonWrapper,children:(0,D.jsx)(Pt,{className:o.toggleButton,title:s("open",{productName:d}),onClick:R,isCollapsed:!0})}),(0,D.jsx)("div",{className:o.collapsible,children:(0,D.jsx)(Cs,{loginUrl:v,isEmbedded:C,onSnooze:ne})})]}):!a||!i?null:(0,D.jsxs)("div",{ref:c,className:(0,bs.default)(o.root,{[o.isCollapsed]:H,[o.isInline]:t}),"data-inline":t,children:[!H&&(0,D.jsxs)("div",{className:o.triggers,children:[(0,D.jsx)("div",{style:{flex:1},children:b&&(0,D.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>x(s(ts()?"searchHintMac":"searchHintWindows",{searchTriggerKey:u.toUpperCase()})),onMouseLeave:()=>x(null),children:(0,D.jsx)(Mc,{title:s("search")})})}),(0,D.jsxs)("div",{className:o.triggersRight,onFocus:()=>{},children:[(0,D.jsx)("div",{className:(0,bs.default)(!f&&o.hintsHidden,o.hints),children:f}),(0,D.jsx)(Pt,{className:o.toggleButton,title:s("collapse"),onClick:R,isCollapsed:!1})]})]}),(0,D.jsx)("div",{className:o.toggleButtonWrapper,children:(0,D.jsx)(Pt,{className:o.toggleButton,title:s("open",{productName:d}),onClick:R,isCollapsed:!0})}),te>0&&h&&(0,D.jsx)("div",{className:o.collapsible,onFocus:()=>{},children:(0,D.jsx)(Le,{children:(0,D.jsx)(zc,{suggestions:e,selectedIndex:n})})})]})},yg=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),Es=(0,We.connect)(yg)(hg);var qs=E(require("classnames")),vu=require("interweave"),Xe=require("react"),xu=require("react-redux");var Xc=require("react"),Sg=["div","span","mark","strong","b","i","u","em"];function ii(t,e,n=0){var r;let o=t[t.length-1],s=typeof o=="object"&&o!==null?(r=o.props)==null?void 0:r.tagName:void 0;if(s==="br")return t.pop(),[...t,...e,o];if(Sg.includes(s)){let i=Array.isArray(o.props.children)?o.props.children:[o.props.children];return[...t.slice(0,t.length-1),(0,Xc.cloneElement)(o,{children:ii(i,e,n+1)})]}return[...t,...e]}function Ge(t){return t.tagName.toLowerCase()==="textarea"}var Zc=E(require("classnames"));var Qc={root:"_root_1s73o_1",isArrowUp:"_isArrowUp_1s73o_22",isArrowDown:"_isArrowDown_1s73o_23",isTab:"_isTab_1s73o_39",isEsc:"_isEsc_1s73o_44",isEnter:"_isEnter_1s73o_49"};var Jc=require("react/jsx-runtime");var vg=({className:t,keyCode:e,children:n,...o})=>{let s=y("KeyboardHint",Qc);return(0,Jc.jsx)("span",{className:(0,Zc.default)(t,s.root,{[s.isArrowUp]:e==="arrow-up",[s.isArrowDown]:e==="arrow-down",[s.isTab]:e==="tab",[s.isEsc]:e==="esc",[s.isEnter]:e==="enter"}),...o,children:n})},_s=vg;var su=require("interweave"),Is=require("react");var li=E(require("classnames")),fe=require("react");var Ps=require("react"),xg=["bottom","height","left","right","top","width"],Cg=(t={},e={})=>xg.some(n=>t[n]!==e[n]),$e=new Map,Yc,eu=()=>{let t=[],e=[];$e.forEach((n,o)=>{if(o instanceof Element&&!o.isConnected){e.push(o);return}let s=o.getBoundingClientRect();Cg(s,n.rect)&&(n.rect=s,t.push(n))}),e.forEach(n=>{$e.delete(n)}),t.forEach(n=>{n.callbacks.forEach(o=>o(n.rect))}),Yc=window.requestAnimationFrame(eu)};function Tg(t,e){return{observe(){let n=$e.size===0;if($e.has(t)){let o=$e.get(t);o.callbacks.push(e),o.rect&&e(o.rect)}else $e.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});n&&eu()},unobserve(){let n=$e.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||$e.delete(t),$e.size||cancelAnimationFrame(Yc)}}}}function ai(t){let[e,n]=(0,Ps.useState)(null);return(0,Ps.useLayoutEffect)(()=>{if(!t.current)return;let o=Tg(t.current,s=>{n(s)});return o.observe(),()=>{o.unobserve()}},[t]),e}var dn=require("react"),nu=require("react-dom");var tu={root:"_root_1jq08_1"};var ou=({children:t})=>{let[e,n]=(0,dn.useState)(null),o=(0,dn.useContext)(Tn);return(0,dn.useLayoutEffect)(()=>{let s=document.createElement("div");return xt(s),s.classList.add(tu.root),o!=null&&o.rootNode&&s.classList.add(o==null?void 0:o.rootNode),document.body.appendChild(s),n(s),()=>{s.isConnected&&document.body.removeChild(s)}},[]),e?(0,nu.createPortal)(t,e):null};var Me={ref:"_ref_1rcyi_1",root:"_root_1rcyi_7",positionAbove:"_positionAbove_1rcyi_13",positionBelow:"_positionBelow_1rcyi_17",positionLeft:"_positionLeft_1rcyi_21",positionRight:"_positionRight_1rcyi_25",alignStart:"_alignStart_1rcyi_29",alignCenter:"_alignCenter_1rcyi_34",alignEnd:"_alignEnd_1rcyi_40"};var ks=require("react/jsx-runtime"),mn=(t=!1)=>{let[e,n]=(0,fe.useState)(t),o=(0,fe.useCallback)(()=>n(!0),[]),s=(0,fe.useCallback)(()=>n(!1),[]),r=(0,fe.useCallback)(()=>n(a=>!a),[]),i=(0,fe.useRef)(null);return{opened:e,open:o,close:s,toggle:r,triggerRef:i}};function ci(t,e=null,n=0){if(!t)return{display:"none"};let o=e?t.top-e.top<0||t.top<e.top-n?e.top-n:t.top+t.height>e.top+e.height+n?e.top+e.height+n-t.height:t.top:t.top,s=e?t.left<e.left-n?e.left-n:t.left+t.width>e.left+e.width+n?e.left+e.width+n-t.width:t.left:t.left;return{top:o,left:s,height:t.height,width:t.width}}var gn=({className:t,triggerRef:e,boundaryRef:n=(0,fe.createRef)(),position:o="above",align:s="center",children:r,toStyle:i=ci,...a})=>{let l=ai(e),c=ai(n),u=(0,fe.useMemo)(()=>i(l,c,0),[l,c]);return(0,ks.jsx)(ou,{children:(0,ks.jsx)("div",{className:(0,li.default)(Me.ref,{[Me.positionAbove]:o==="above",[Me.positionBelow]:o==="below",[Me.positionLeft]:o==="left",[Me.positionRight]:o==="right",[Me.alignStart]:s==="start",[Me.alignCenter]:s==="center",[Me.alignEnd]:s==="end"}),style:u,...a,role:"dialog",children:(0,ks.jsx)("div",{className:(0,li.default)(t,Me.root),children:r})})})};var dt=require("react/jsx-runtime"),wg=({inputStyle:t,inputElement:e})=>{let n=y("TabCompletion",pe),o=mn(document.activeElement===e);return zt(()=>o.close()),(0,Is.useEffect)(()=>{let s=()=>o.open();return e.addEventListener("focus",s),()=>{e.removeEventListener("focus",s)}},[]),(0,dt.jsxs)(Is.Fragment,{children:[(0,dt.jsx)("mark",{className:pe.caret,ref:o.triggerRef}),o.opened&&(0,dt.jsx)(gn,{className:n.popoverSuggestionsRoot,triggerRef:o.triggerRef,position:"above",align:"start",children:(0,dt.jsx)("div",{style:t,className:n.suggestionsOverlayInputStyles,children:(0,dt.jsx)(Es,{inline:!0})})})]})},Rs=class extends su.Matcher{charCounter=0;charLength=0;found=!1;onlyAtEnd=!1;props;onBeforeParse(e,n){var o;return this.props=n,this.charCounter=0,this.onlyAtEnd=n.inlineSuggestionsOnlyAtEnd??!1,this.charLength=(Ge(n.inputElement)?n.inputElement.value.length:(o=n.inputElement.textContent)==null?void 0:o.length)??0,this.found=!1,e}match(e){if(this.found||!this.props||this.props.selection===null)return null;let[n,o]=this.props.selection;if(n!==o||this.onlyAtEnd&&n!==this.charLength)return null;let s=n,i=s>=this.charCounter&&s<=this.charCounter+e.length?{index:ti(e.slice(0,s))+1-this.charCounter,length:0,match:"",valid:!0}:null;return i&&(this.found=!0),this.charCounter+=e.length,i??null}replaceWith(e,n){return(0,dt.jsx)(wg,{inputStyle:n.inputStyle,inputElement:n.inputElement},"caret")}asTag(){return"mark"}};var lu=E(require("classnames")),cu=require("interweave"),Ns=require("react");function ru(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function As(t){return e=>{t.forEach(n=>{typeof n=="function"?n(e):n!=null&&(n.current=e)})}}function iu(t){return t!=null}var au=E(require("classnames")),Ls=require("react");var ui=require("react/jsx-runtime"),Ms=(0,Ls.forwardRef)(({className:t,children:e,...n},o)=>{let s=(0,Ls.useRef)(null),r=y("TabCompletion",pe);return(0,ui.jsx)("div",{ref:As([s,o]),className:(0,au.default)(t,r.popoverContentContainer),...n,children:(0,ui.jsx)("div",{className:r.popoverContent,children:e})})});var mt=require("react/jsx-runtime"),bg=t=>e=>{let n=ci(e);return"top"in n&&(n.width=t.width-(e.left-t.left)-10),n},Eg=({inputElement:t,boundaryRef:e,inputStyle:n,children:o,suggestion:s})=>{let r=y("TabCompletion",pe),i=mn(),a=(0,Ns.useMemo)(()=>bg(t.getBoundingClientRect()),[t]),[l,c]=$o(t);return(0,Ns.useEffect)(()=>{c?i.open():i.close()},[c]),(0,mt.jsxs)("span",{children:[(0,mt.jsx)("mark",{ref:As([l,i.triggerRef]),className:(0,lu.default)(r.matchKeyword,{[r.hover]:c}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:o}),i.opened&&(0,mt.jsx)(gn,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:(0,mt.jsx)(Ms,{style:n,children:(0,mt.jsx)("div",{className:r.hintText,children:s})})})]})},Os=class extends cu.Matcher{keywordMatches=[];preparedKeywordMatches=[];usedKeywordMatches=new Set;onBeforeParse(e,n){return n.keywordMatches&&n.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=n.keywordMatches.map(o=>({...o,keywordRegex:new RegExp(`\\b${ru(o.keyword)}\\b`,"i")})),this.keywordMatches=n.keywordMatches),this.usedKeywordMatches.clear(),e}match(e){let n=this.preparedKeywordMatches.map(s=>{if(this.usedKeywordMatches.has(s))return null;let r=e.match(s.keywordRegex);if(!r)return null;let i=e.charAt(r.index-1),a=e.charAt(r.index+s.keyword.length);return i==="{"&&a==="}"?null:{index:r.index,length:r[0].length,match:r[0],matchString:r[0],suggestion:s.suggestion,preparedKeywordMatch:s,valid:!0}}).filter(iu);if(n.length===0)return null;let o=n.reduce((s,r)=>r.index<s.index?r:s);return this.usedKeywordMatches.add(o.preparedKeywordMatch),o}replaceWith(e,n){return(0,mt.jsx)(Eg,{inputElement:n.inputElement,suggestion:n.suggestion,inputStyle:n.inputStyle,boundaryRef:n.boundaryRef,children:e},`keyword_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var Ks=E(require("classnames")),hu=require("interweave"),X=require("react"),yu=require("react-redux");var pi=require("react/jsx-runtime"),uu=()=>(0,pi.jsx)("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:(0,pi.jsx)("path",{fill:"currentColor",d:"M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"})});var gt=require("react"),no=require("react-redux"),gu=E(require("lodash.debounce"));var Ds=E(require("classnames")),he=E(require("react"));var pu={root:"_root_vr71j_1"};var kt=require("react/jsx-runtime"),du=()=>(0,kt.jsxs)("svg",{className:pu.root,width:"185",height:"170",viewBox:"0 0 185 170",xmlns:"http://www.w3.org/2000/svg",children:[(0,kt.jsx)("defs",{children:(0,kt.jsx)("style",{children:".cls-1 { fill: #b3b3b3; }"})}),(0,kt.jsx)("title",{children:"Failed loading image"}),(0,kt.jsx)("path",{className:"cls-1",d:"M15 130.896V16.994c0-1.097.898-1.994 2.007-1.994h150.986A2 2 0 0 1 170 16.994v69.147L133.015 51 87.26 120.377l-35.863-17.758L15 130.896zM2 0C.895 0 0 .887 0 2v166c0 1.105.887 2 2 2h181c1.105 0 2-.887 2-2V2c0-1.105-.887-2-2-2H2zm49 72c11.046 0 20-9.178 20-20.5S62.046 31 51 31s-20 9.178-20 20.5S39.954 72 51 72z",fillRule:"evenodd"})]});var di={root:"_root_4e7lf_1",imageWrapper:"_imageWrapper_4e7lf_7",image:"_image_4e7lf_7",content:"_content_4e7lf_24",title:"_title_4e7lf_35",contentIsCropped:"_contentIsCropped_4e7lf_45",lineClamp:"_lineClamp_4e7lf_51"};var Rt=require("react/jsx-runtime"),Hs=(0,he.createContext)(di),_g=({title:t,src:e})=>{let n=(0,he.useContext)(Hs),[o,s]=(0,he.useState)(!1);return(0,he.useEffect)(()=>{s(!1)},[e]),(0,Rt.jsx)("div",{className:n.imageWrapper,children:e&&!o?(0,Rt.jsx)("img",{className:n.image,alt:t,src:e,onError:()=>s(!0)}):(0,Rt.jsx)(du,{})})},Pg=({className:t,lineClamp:e=!1,cropText:n=!1,children:o})=>{let s=(0,he.useContext)(Hs);return(0,Rt.jsx)("div",{className:(0,Ds.default)(s.content,t,{[s.contentIsCropped]:n,[s.lineClamp]:e}),children:o})},kg=({as:t="h1",cropText:e=!1,className:n,children:o})=>{let s=(0,he.useContext)(Hs);return he.default.createElement(t,{className:(0,Ds.default)(s.title,n,{[s.contentIsCropped]:e})},o)},Fs=({children:t})=>{let e=y("Card",di);return(0,Rt.jsx)("div",{className:(0,Ds.default)(e.root),children:(0,Rt.jsx)(Hs.Provider,{value:e,children:t})})};Fs.Image=_g;Fs.Content=Pg;Fs.Title=kg;var F=Fs;var mu={root:"_root_1muu8_1",content:"_content_1muu8_7"};function Bs(t,e,n){var s;let o=((s=t.imageSizes)==null?void 0:s[e])||t.image||n;if(!o)return null;try{return new URL(o).toString()}catch{return null}}function mi(t){return t.replace("https://www.","").replace("https://","")}var ye=require("react/jsx-runtime"),Rg=3,Ig=t=>({image:t.image||"",text:`https://${t.text}`,id:t.id,title:t.title}),Ag=({onSelectLink:t,onDismiss:e,placeholder:n,visitUrlText:o,linkCount:s=Rg})=>{let r=y("LinkSearch",mu),[i,a]=(0,gt.useState)(""),l=(0,no.useDispatch)(),c=(0,no.useSelector)(fl("url")),u=(0,no.useSelector)(sl("URL",Ig)),[d,p]=(0,gt.useState)(u.length-1),m=T("fallbackImage"),g=h=>{let v=h.target;a(v.value)},f=(h,v)=>{h.stopPropagation(),h.preventDefault(),window.open(v,"_blank")},x=h=>{var k;let v=d-1<0?u.length-1:d-1,C=d+1===u.length?0:d+1;h.code==="Escape"&&(a(""),e()),h.code==="ArrowUp"&&p(v),h.code==="ArrowDown"&&p(C),h.code==="Enter"&&t(((k=u[d])==null?void 0:k.text)||i)},b=(0,gt.useCallback)((0,gu.default)(h=>{l(Ct({query:h,type:"URL",tags:["link-search"]}))},300),[]);return(0,gt.useEffect)(()=>{i&&b(i)},[i]),(0,gt.useEffect)(()=>()=>{l(ss())},[]),(0,ye.jsxs)("div",{className:r.root,children:[(0,ye.jsx)(Le,{withDivider:!0,children:(i?u:c).slice(0,s).map((h,v)=>(0,ye.jsx)(N,{selected:d===v,onClick:()=>t(h.text),"data-testid":"linksearch-suggestion",children:(0,ye.jsxs)(F,{children:[(0,ye.jsx)(F.Image,{src:Bs(h,"small",m||void 0),title:h.title||h.text}),(0,ye.jsxs)(F.Content,{className:r.content,cropText:!0,children:[(0,ye.jsx)(F.Title,{children:h.title||mi(h.text)}),h.title&&mi(h.text)]}),(0,ye.jsx)(N.Actions,{children:(0,ye.jsx)(N.ActionButton,{label:o,onClick:C=>f(C,h.text)})})]})},h.text))}),(0,ye.jsx)(jn,{value:i,onChange:g,autoFocus:!0,placeholder:n,onKeyUp:x})]})},fu=Ag;var gi={};q(gi,{enUS:()=>Lg,nlNL:()=>Mg});var Lg={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},Mg={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var $=require("react/jsx-runtime"),Og=(0,X.forwardRef)((t,e)=>{let n=y("TabCompletion",pe);return(0,$.jsx)("mark",{ref:e,className:(0,Ks.default)(n.matchSelection)},"selection-start")}),Ng=({startRef:t,boundaryRef:e,inputStyle:n,inputElement:o,children:s})=>{let r=_(gi),i=y("TabCompletion",pe),a=(0,X.useRef)(null),l=(0,X.useRef)(null),[c,u]=(0,X.useState)(null),d=(0,yu.useDispatch)(),p=mn(document.activeElement===o),[m]=(0,X.useState)(()=>document.createRange());p.triggerRef.current=m,(0,X.useEffect)(()=>()=>m.detach(),[]),(0,X.useEffect)(()=>{let f=t.current,x=a.current;!f||!x||(m.setStart(f,0),m.setEnd(x,0))},[t.current,a.current]),zt(()=>{p.close()});let g=(0,X.useCallback)(f=>{let x=m.toString(),b=/^http(s?):\/\//.test(f)?f:`https://${f}`;d(_o({text:`[${x}](${b})`}))},[]);return(0,$.jsxs)("span",{children:[(0,$.jsx)("mark",{ref:a,className:(0,Ks.default)(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":p.opened?"true":"false",children:s}),p.opened&&(0,$.jsx)(gn,{className:i.popoverRoot,triggerRef:p.triggerRef,boundaryRef:e,position:"above",align:"start",children:(0,$.jsxs)(Ms,{style:n,ref:l,children:[(0,$.jsx)("div",{className:(0,Ks.default)(i.selectionOptions,{[i.selectionOptionsIsHidden]:c!==null}),children:(0,$.jsxs)("button",{type:"button",tabIndex:c===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>u("insertLink"),children:[(0,$.jsx)(uu,{}),(0,$.jsx)("span",{children:"\xA0"}),(0,$.jsx)("span",{children:r("insertLink")})]})}),c==="insertLink"&&(0,$.jsx)(fu,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:g,onDismiss:()=>{u(null),p.close()}})]})})]},"selection-end")},Us=class extends hu.Matcher{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(e,n){return this.props=n,this.charCount=0,this.startRef=(0,X.createRef)(),this.foundIndex=0,e}match(e){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[n,o]=this.props.selection;if(n===o)return null;let s=this.foundIndex===0?n:o,r=s>=this.charCount&&s<=this.charCount+e.length?{index:s-this.charCount,length:0,match:"",valid:!0}:null;r&&this.foundIndex++;let i=this.foundIndex===1;return r&&i?this.charCount+=s-this.charCount:this.charCount+=e.length,r?{isStart:i,...r}:null}replaceWith(e,n){return n.isStart?(0,$.jsx)(Og,{ref:this.startRef}):(0,$.jsx)(Ng,{inputElement:n.inputElement,startRef:this.startRef,boundaryRef:n.boundaryRef,inputStyle:n.inputStyle})}asTag(){return"mark"}};var Su={root:"_root_kpc8q_1",agentText:"_agentText_kpc8q_4",tabText:"_tabText_kpc8q_9",hint:"_hint_kpc8q_10",matchSelection:"_matchSelection_kpc8q_14",focus:"_focus_kpc8q_20",resetIndent:"_resetIndent_kpc8q_24",matchKeyword:"_matchKeyword_kpc8q_28",matchPlaceholder:"_matchPlaceholder_kpc8q_29",hover:"_hover_kpc8q_35",hintText:"_hintText_kpc8q_67",popover:"_popover_kpc8q_75",popoverRoot:"_popoverRoot_kpc8q_80",popoverContentContainer:"_popoverContentContainer_kpc8q_84",popoverContent:"_popoverContent_kpc8q_84",selectionOptions:"_selectionOptions_kpc8q_110",selectionOptionsIsHidden:"_selectionOptionsIsHidden_kpc8q_115",selectionOptionsButton:"_selectionOptionsButton_kpc8q_119",caret:"_caret_kpc8q_135",popoverSuggestionsRoot:"_popoverSuggestionsRoot_kpc8q_139",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_kpc8q_144"};var ft=require("react/jsx-runtime"),Dg=({enabled:t,content:e,tabText:n,showTabHint:o,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:l})=>{let c=y("TabCompletion",Su),u=T("insertLink"),d=T("showMidSentenceSuggestions"),p=T("inlineSuggestions"),m=Qo(a),g=(0,Xe.useRef)(null);(0,Xe.useEffect)(()=>{Ge(a)&&m&&Zo(a,m)},[m]);let f=(0,Xe.useCallback)(h=>{if(!s||!n)return h;let v=[(0,ft.jsx)("span",{className:c.resetIndent,children:"\u200B"},"u200B"),(0,ft.jsx)("span",{className:(0,qs.default)(c.tabText,c.resetIndent),"data-source":l,children:n},"tabText")];return o&&v.push((0,ft.jsx)(_s,{className:(0,qs.default)(c.hint,c.resetIndent),keyCode:"tab"},"tabHint")),ii(h,v)},[s,n,o]),x=(0,Xe.useMemo)(()=>{let h=[];return p&&h.push(new Rs("inline")),u&&h.push(new Us("selection")),h.push(new Vt("placeholders")),r&&h.push(new Os("keywords")),h},[p,u,r]),b=(0,Xe.useMemo)(()=>{let h=window.getComputedStyle(a);return{"--dd-color":h.color,"--dd-font-size":h.fontSize,"--dd-font-family":h.fontFamily,"--dd-font-variant":h.fontVariant}},[]);return t?(0,ft.jsxs)("div",{ref:h=>{h!=null&&h.parentElement&&(g.current=h==null?void 0:h.parentElement)},className:(0,qs.default)(c.root,c.agentText),style:b,children:[(0,ft.jsx)(vu.Interweave,{tagName:"span",noWrap:!1,containerTagName:"div",disableLineBreaks:Ge(a),content:e||"\u200B",onAfterParse:f,matchers:x,selection:m,keywordMatches:i,inputElement:a,inputStyle:b,boundaryRef:g,inlineSuggestionsOnlyAtEnd:!d}),(0,ft.jsx)("br",{})]}):null},Hg=({input:t,ui:e,settings:n,styleSuggestions:o,conversation:s})=>{var f;let{tabCompletionSuggestion:r}=t,i=(r==null?void 0:r.text)||"",a=(r==null?void 0:r.source)||"",l=t.html??cn(t.text),c=i.indexOf(t.text)===0?i.slice(t.text.length):"",{showTabHint:u}=e,{isSupported:d}=s,{showTabCompletion:p,visible:m,showStyleSuggestions:g}=n;return{showTabHint:u,showStyleSuggestions:g,showTabCompletion:p,content:l,tabText:c,source:a,keywordMatches:((f=o.list)==null?void 0:f.keywordMatches)??[],enabled:m&&d!==!1}},Cu=(0,xu.connect)(Hg)(Dg);var xp=E(require("classnames")),Cp=require("react"),V=require("react-redux");var ht=require("@reduxjs/toolkit");var Tu={list:[],fetchState:"idle",isInitialRequest:null},bu=t=>t.autoflows.list||[],wu=t=>e=>{var n;return(n=e.list)==null?void 0:n.find(o=>o.triggerPayload===t)},Qe=(0,ht.createAsyncThunk)("autoflows/getAll",async(t,e)=>{let{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getAutoflows(t)}),fi=(0,ht.createAsyncThunk)("autoflows/start",async(t,e)=>{let{dispatch:n}=e,{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.startAutoflowSession(t),await n(Qe(t.platformSessionId))}),hi=(0,ht.createAsyncThunk)("autoflows/stop",async(t,e)=>{let{dispatch:n}=e,{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.stopAutoflowSession(t.platformSessionId),await n(Qe(t.platformSessionId))}),Fg=(0,ht.createSlice)({name:"autoflows",initialState:Tu,reducers:{},extraReducers:t=>{t.addCase(fi.pending,(e,n)=>{let o=wu(n.meta.arg.triggerPayload)(e);o.state="Started",o.isBusy=!0}),t.addCase(hi.pending,(e,n)=>{let o=wu(n.meta.arg.triggerPayload)(e);o.state="Aborted",o.isBusy=!0}),t.addCase(Qe.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}),t.addCase(Qe.rejected,e=>{e.fetchState="error"}),t.addCase(Qe.fulfilled,(e,n)=>{e.list=n.payload,e.fetchState="done"}),t.addCase(A,()=>Tu)}}),Eu=(0,ht.createAsyncThunk)("autoflows/openStream",(t,e)=>{let{dispatch:n}=e,{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");let s=o.openStream(t);s.on("sessionAborted",()=>{n(Qe(t))}),s.on("sessionCompleted",()=>{n(Qe(t))})}),_u=(0,ht.createAsyncThunk)("autoflows/closeStream",(t,e)=>{let{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(t)}),Pu=Fg.reducer;var yt=require("@reduxjs/toolkit");var ku={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},Ru=t=>t.customMessages.list,Iu=t=>e=>!!e.customMessages.sentSuggestions.find(n=>n===t),Au=t=>e=>!!e.customMessages.answeredSuggestions.find(n=>n===t),Lu=t=>e=>!!e.customMessages.errorSuggestions.find(n=>n===t),oo=(0,yt.createAsyncThunk)("customMessages/getAll",async(t,e)=>{let{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getCustomMessages(t)}),Vs=(0,yt.createAsyncThunk)("customMessages/send",async(t,e)=>{let{platformSessionId:n,suggestion:o}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.sendCustomMessage(n,o)}),js=(0,yt.createAsyncThunk)("customMessages/answer",async(t,e)=>{let{platformSessionId:n,reply:o}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.answerCustomMessage(n,o)}),Mu=(0,yt.createSlice)({name:"customMessages",initialState:ku,reducers:{onCustomMessage(t,e){Array.isArray(e.payload)?t.list=e.payload:t.list=[e.payload]}},extraReducers:t=>{t.addCase(oo.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(oo.rejected,e=>{e.fetchState="error"}).addCase(oo.fulfilled,(e,n)=>{e.fetchState="done",e.list=n.payload||[]}).addCase(Vs.pending,(e,n)=>{e.sentSuggestions.push(n.meta.arg.suggestion.text),e.errorSuggestions=e.errorSuggestions.filter(o=>n.meta.arg.suggestion.text!==o)}).addCase(Vs.rejected,(e,n)=>{let o=e.sentSuggestions.indexOf(n.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(o,1))}).addCase(js.pending,(e,n)=>{e.sentSuggestions.push(n.meta.arg.suggestion.text),e.answeredSuggestions.push(n.meta.arg.suggestion.text)}).addCase(js.rejected,(e,n)=>{let o=e.answeredSuggestions.indexOf(n.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(o,1)),e.answeredSuggestions.splice(o,1)}).addCase(A,()=>ku)}}),Ou=(0,yt.createAsyncThunk)("customMessages/openStream",(t,e)=>{let{dispatch:n}=e,{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.openStream(t).on("customMessageSuggestion",r=>{n(Mu.actions.onCustomMessage(r))})}),Nu=(0,yt.createAsyncThunk)("customMessages/closeStream",(t,e)=>{let{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(t)}),Du=Mu.reducer;var so=require("@reduxjs/toolkit"),Bg={jwt:null,accountUrl:null,interval:null},Hu=t=>e=>{let{exchangeToken:{jwt:n,accountUrl:o}}=e;return n&&o?`${o}/apis/admin/session/jwt/?jwt=${n}&redirect=${t}`:null},yi=(0,so.createAsyncThunk)("exchangeToken/getTemporaryExchangeToken",async(t,e)=>{let{deepdeskAPI:n}=e.extra,o=await n.getTemporaryExchangeToken();return{accountUrl:n.client.baseUrl,jwt:o}}),Si=(0,so.createAsyncThunk)("exchangeToken/pollExchangeToken",(t={},e)=>{let{interval:n=1e3*60*30}=t,{dispatch:o}=e;return o(yi()),setInterval(()=>o(yi()),n)}),Fu=(0,so.createSlice)({name:"exchangeToken",initialState:Bg,reducers:{stopPollExchangeToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(yi.fulfilled,(e,n)=>{e.jwt=n.payload.jwt,e.accountUrl=n.payload.accountUrl}),t.addCase(Si.fulfilled,(e,n)=>{e.interval=n.payload})}}),{stopPollExchangeToken:Bu}=Fu.actions,Ku=Fu.reducer;function Uu(t){let{customMessages:e,autoflows:n}=t;return n.fetchState==="loading"&&n.isInitialRequest===!0||e.fetchState==="loading"&&e.isInitialRequest===!0}var Qu=require("react"),Zu=require("react-redux");var Gu=E(require("classnames")),$u=require("react");var Vu=E(require("classnames"));var qu={root:"_root_838fd_1"};var zu=require("react/jsx-runtime"),Kg=({className:t,children:e})=>{let n=y("Unicode",qu);return(0,zu.jsx)("span",{className:(0,Vu.default)(t,n.root),children:e})},ju=Kg;var Wu={isDisabled:"_isDisabled_1rmfm_1",buttonStart:"_buttonStart_1rmfm_5",root:"_root_1rmfm_8",buttonStop:"_buttonStop_1rmfm_8",stateBadge:"_stateBadge_1rmfm_19",isCompleted:"_isCompleted_1rmfm_26",isStarted:"_isStarted_1rmfm_30",isAborted:"_isAborted_1rmfm_34"};var vi={};q(vi,{enUS:()=>Ug,nlNL:()=>qg});var Ug={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]},qg={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]};var ie=require("react/jsx-runtime"),jg=({disabled:t,state:e,displayName:n,description:o,onStartAutoflow:s,onStopAutoflow:r})=>{let i=y("Autoflow",Wu),a=_(vi),l=e==="Started"?"stop":"start",c=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return(0,ie.jsxs)(N,{className:(0,Gu.default)(i.root,{[i.isDisabled]:t,[i.isCompleted]:e==="Completed",[i.isAborted]:e==="Aborted",[i.isStarted]:e==="Started"}),children:[(0,ie.jsx)(F,{children:(0,ie.jsxs)(F.Content,{children:[(0,ie.jsxs)(F.Title,{children:[e&&(0,ie.jsx)("span",{className:i.stateBadge,children:a(e)}),n]}),(0,ie.jsx)("span",{children:o})]})}),(0,ie.jsx)(N.Actions,{fixed:e==="Started",children:(0,ie.jsx)(N.ActionButton,{primary:!0,className:l==="start"?i.buttonStart:i.buttonStop,onClick:e==="Started"?r:s,disabled:t,label:(0,ie.jsxs)($u.Fragment,{children:[(0,ie.jsx)(ju,{children:c})," ",(0,ie.jsx)("span",{children:a(l)})]})})})]})},Xu=jg;var xi=require("react/jsx-runtime"),zg=(t,e)=>{let n=e.filter(o=>o.state==="Started");return n.length>0?n.indexOf(t)===-1:!1},Wg=({autoflows:t,onStartAutoflow:e,onStopAutoflow:n,platformSessionId:o})=>(0,xi.jsx)(Qu.Fragment,{children:t.map(s=>(0,xi.jsx)(Xu,{displayName:s.displayName,description:s.description,disabled:s.isBusy||zg(s,t),state:s.state,onStartAutoflow:()=>e({platformSessionId:o,triggerPayload:s.triggerPayload}),onStopAutoflow:()=>n({platformSessionId:o,triggerPayload:s.triggerPayload})},s.displayName))}),Gg=({autoflows:t,conversation:e})=>{var n;return{autoflows:t.list,platformSessionId:(n=e.current)==null?void 0:n.sessionId}},$g={onStartAutoflow:fi,onStopAutoflow:hi},Ju=(0,Zu.connect)(Gg,$g)(Wg);var zs=require("react"),ep=require("react-redux"),wi=E(require("classnames"));var Ci=require("react/jsx-runtime"),Ti=()=>(0,Ci.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,Ci.jsx)("path",{d:"M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"})});var Yu={root:"_root_rjdyr_1",entity:"_entity_rjdyr_10",entityText:"_entityText_rjdyr_46",iconWrapper:"_iconWrapper_rjdyr_53",icon:"_icon_rjdyr_53",iconClicked:"_iconClicked_rjdyr_67"};var Oe=require("react/jsx-runtime"),Xg=({entities:t})=>{let e=y("EntitiesWidgetList",Yu),[n,o]=(0,zs.useState)(void 0),s=(0,ep.useDispatch)(),r=()=>{o(void 0)},i=a=>{t&&(o(t.indexOf(a)),Wn(a.text),s(Re({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,zs.useEffect)(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[n]),!t||t.length===0?null:(0,Oe.jsx)("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,l)=>(0,Oe.jsxs)("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[(0,Oe.jsx)("span",{className:e.entityText,children:a.text}),(0,Oe.jsxs)("span",{className:e.iconWrapper,children:[(0,Oe.jsx)("span",{className:(0,wi.default)(e.icon),children:(0,Oe.jsx)(Ti,{})}),(0,Oe.jsx)("span",{className:(0,wi.default)(e.icon,n===l&&e.iconClicked),children:(0,Oe.jsx)(Ti,{})})]})]},a.text))})},tp=Xg;var rp=E(require("classnames")),bi=require("react"),It=require("react-redux");var op=E(require("classnames"));var np={root:"_root_4a08n_1"};var sp=require("react/jsx-runtime"),Qg=({className:t,children:e,...n})=>{let o=y("Label",np);return(0,sp.jsx)("span",{...n,className:(0,op.default)(t,o.root),children:e})},Ws=Qg;var ro={};q(ro,{enUS:()=>Zg,nlNL:()=>Jg});var Zg={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Add"}],sendSuggestion:[{type:0,value:"Send"}],suggestionSent:[{type:0,value:"Sent"}],sendingError:[{type:0,value:"Sending failed"}],tryAgain:[{type:0,value:"Try again"}],editSuggestion:[{type:0,value:"Edit"}],visitUrl:[{type:0,value:"Visit"}],answer:[{type:0,value:"Answer"}]},Jg={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Gebruik"}],sendSuggestion:[{type:0,value:"Verzenden"}],suggestionSent:[{type:0,value:"Verzonden"}],sendingError:[{type:0,value:"Verzenden mislukt"}],tryAgain:[{type:0,value:"Probeer opnieuw"}],editSuggestion:[{type:0,value:"Bewerken"}],visitUrl:[{type:0,value:"Bekijk"}],answer:[{type:0,value:"Antwoord"}]};var Ze={root:"_root_1e6ej_1",title:"_title_1e6ej_8",isUsed:"_isUsed_1e6ej_13",quickReplies:"_quickReplies_1e6ej_22",quickReply:"_quickReply_1e6ej_29",hasError:"_hasError_1e6ej_39",label:"_label_1e6ej_43",errorIcon:"_errorIcon_1e6ej_48"};var ee=require("react/jsx-runtime"),Yg=({suggestion:t})=>{let e=_(ro),n=(0,It.useDispatch)(),o=(0,It.useSelector)(Iu(t.text)),s=(0,It.useSelector)(Au(t.text)),r=(0,It.useSelector)(Lu(t.text)),i=(0,It.useSelector)(yo),{replyOptions:a}=t,l=(0,bi.useCallback)(u=>{u.preventDefault(),u.stopPropagation(),!(o||!i)&&n(Vs({platformSessionId:i,suggestion:t}))},[t,o,n,i]),c=(0,bi.useCallback)(u=>{if(u.preventDefault(),u.stopPropagation(),!i||!a)return;let d=parseInt(u.target.dataset.index,10),p=a[d];n(js({platformSessionId:i,reply:p,suggestion:t}))},[t,o,n,i]);return(0,ee.jsxs)(N,{onClick:l,className:(0,rp.default)(Ze.root,{[Ze.isUsed]:o,[Ze.hasError]:r}),children:[(0,ee.jsx)(F,{children:(0,ee.jsxs)(F.Content,{children:[(0,ee.jsxs)(F.Title,{className:Ze.title,children:[t.text," ",(0,ee.jsx)(Ws,{className:Ze.label,children:"analyse tool"})," ",r&&(0,ee.jsx)("span",{className:Ze.errorIcon,role:"img","aria-label":e("sendingError"),title:e("sendingError"),children:"!"})]}),a&&a.length>0&&(0,ee.jsx)("ul",{className:Ze.quickReplies,children:a.map(u=>(0,ee.jsx)("li",{className:Ze.quickReply,children:u.title},u.title))})]})}),(0,ee.jsxs)(N.Actions,{fixed:r||o,children:[a&&a.length>0&&(0,ee.jsx)(N.DropdownButton,{label:e("answer"),disabled:s,children:a.map((u,d)=>(0,ee.jsx)(N.DropdownItem,{index:d,label:u.title,onClick:c},u.title))}),(0,ee.jsx)(N.ActionButton,{primary:!0,disabled:o,onClick:l,label:e(o?"suggestionSent":r?"tryAgain":"sendSuggestion")})]})]})},ip=Yg;var Ei=require("react/jsx-runtime"),ap=()=>(0,Ei.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,Ei.jsx)("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});var lp={root:"_root_jlggj_1",subTitleContainer:"_subTitleContainer_jlggj_5",subtitle:"_subtitle_jlggj_9",suggestions:"_suggestions_jlggj_17"};var fn=require("react/jsx-runtime"),ef=({title:t,children:e,...n})=>{let o=y("Section",lp);return(0,fn.jsxs)("section",{...n,className:o.root,children:[t&&(0,fn.jsx)("div",{className:o.subTitleContainer,children:(0,fn.jsx)("span",{className:o.subtitle,children:t})}),(0,fn.jsx)("div",{className:o.suggestions,children:e})]})},St=ef;var up=E(require("classnames")),pp=E(require("react"));var cp={root:"_root_19wxp_1"};var dp=require("react/jsx-runtime"),tf=pp.default.forwardRef(({className:t,children:e},n)=>{let o=y("SectionList",cp);return(0,dp.jsx)("div",{ref:n,className:(0,up.default)(o.root,t),children:e})}),Gs=tf;var fp=require("react-redux");var mp=require("react");var ae=require("react/jsx-runtime"),nf=({suggestion:t,lines:e,onEdit:n,onUse:o})=>{var p;let s=t.text||t.url||t.message,r=rs(s),i=_(ro),a=T("showImages"),l=T("fallbackImage"),c=m=>{m.preventDefault(),m.stopPropagation(),o(s)},u=m=>{m.preventDefault(),m.stopPropagation(),n(t)},d=(0,mp.useCallback)(m=>{window.open(r,"_blank"),m.stopPropagation(),m.preventDefault()},[r]);return(0,ae.jsxs)(N,{onClick:c,"data-testid":"edit-suggestion",children:[(0,ae.jsxs)(F,{children:[a&&t.image&&(0,ae.jsx)(F.Image,{src:Bs(t,"small",l||void 0),title:t.title}),(0,ae.jsxs)(F.Content,{children:[t.title&&(0,ae.jsx)(F.Title,{children:t.title}),t.searchKeywords&&((p=t.searchKeywords)==null?void 0:p.length)>0&&(0,ae.jsx)(N.Labels,{labels:t.searchKeywords}),(0,ae.jsx)(F.Content,{cropText:e==="single",lineClamp:e==="multiple",children:s})]})]}),(0,ae.jsxs)(N.Actions,{children:[r&&(0,ae.jsx)(N.ActionButton,{onClick:d,label:i("visitUrl")}),(0,ae.jsx)(N.ActionButton,{primary:!0,onClick:u,label:i("preview")}),(0,ae.jsx)(N.ActionButton,{primary:!0,onClick:c,label:i("useSuggestion")})]})]})},gp=nf;var io=require("react/jsx-runtime"),of=({contentType:t,lines:e,suggestions:n})=>{let o=ge(),s=(0,fp.useSelector)(Jt),r=a=>{o.send(qr,{state:s,suggestion:a,contentType:t})},i=(a,l)=>{o.send(Ue,{text:a,suggestion:{...l,source:l.source,sourceText:l.text}})};return(0,io.jsx)(io.Fragment,{children:n.map(a=>(0,io.jsx)(gp,{suggestion:a,lines:e,onEdit:l=>r(l),onUse:l=>i(l,a)},a.text||a.url||a.message))})},hp=of;var _i={};q(_i,{enUS:()=>sf,nlNL:()=>rf});var sf={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"}],actions:[{type:0,value:"Shortcuts"}],linkPersonalcollection:[{type:0,value:"Personal Collection"}],linkSummary:[{type:0,value:"Summarize"}],linkKnowledgeSearch:[{type:0,value:"Knowledge Assist"}],linkSearch:[{type:0,value:"Search"}]},rf={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"}],actions:[{type:0,value:"Shortcuts"}],linkPersonalcollection:[{type:0,value:"Personal Collection"}],linkSummary:[{type:0,value:"Vat gesprek samen"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}]};var yp={root:"_root_oym4o_1",loginText:"_loginText_oym4o_7",stateText:"_stateText_oym4o_8",sectionList:"_sectionList_oym4o_20",links:"_links_oym4o_24",link:"_link_oym4o_24"};var Pi=require("react/jsx-runtime"),Sp=()=>(0,Pi.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Pi.jsx)("path",{d:"M543-340q16.595 0 28.798-12.202Q584-364.405 584-381t-12.202-28.798Q559.595-422 543-422t-28.798 12.202Q502-397.595 502-381t12.202 28.798Q526.405-340 543-340Zm-25-126h47q2-29 8.5-43t32.5-39q27-26 37.5-45.395Q654-612.79 654-639q0-45.882-31.5-74.941Q591-743 540-743q-38 0-68 20.5T428-665l45 19q11-25 27.5-38t39.5-13q29.778 0 48.389 17Q607-663 607-637q0 20-9 35t-32 32q-32 29-40 46.5t-8 57.5ZM260-200q-24 0-42-18t-18-42v-560q0-24 18-42t42-18h560q24 0 42 18t18 42v560q0 24-18 42t-42 18H260Zm0-60h560v-560H260v560ZM140-80q-24 0-42-18t-18-42v-620h60v620h620v60H140Zm120-740v560-560Z"})});var ki=require("react/jsx-runtime"),vp=()=>(0,ki.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,ki.jsx)("path",{d:"M319-250h322v-60H319v60Zm0-170h322v-60H319v60ZM220-80q-24 0-42-18t-18-42v-680q0-24 18-42t42-18h361l219 219v521q0 24-18 42t-42 18H220Zm331-554v-186H220v680h520v-494H551ZM220-820v186-186 680-680Z"})});var I=require("react/jsx-runtime"),$s=(t,e)=>{let n=(0,V.useSelector)(Ke);(0,Cp.useEffect)(()=>n?e.every(o=>!!o)?t():()=>{}:()=>{},[...e,n])},af=()=>{let t=_(_i),e=(0,V.useDispatch)(),n=T("isEmbedded"),o=y("Widget",yp),s=T("showAutoflows"),r=T("showCustomMessages"),i=T("showPersonalCollectionLink"),a=T("showSummaryCommand"),l=T("showKnowledgeSearch"),c=T("showSearch"),u=(0,V.useSelector)(an),d=(0,V.useSelector)(vs),p=(0,V.useSelector)(bu),m=(0,V.useSelector)(fs),g=(0,V.useSelector)(Ru),f=(0,V.useSelector)(So),x=(0,V.useSelector)(vo),b=(0,V.useSelector)(Ke),h=(0,V.useSelector)(yo),v=(0,V.useSelector)(Uu),C=(0,V.useSelector)(Jt),k=ge(),w=(0,V.useSelector)(yl),H=(0,V.useSelector)(Hu("/admin/personal-collection")),te=T("adminUrl");return $s(()=>(e(oo(h)),e(Ou(h)),()=>{e(Nu(h))}),[e,x,r,h]),$s(()=>(e(Qe(h)),e(Eu(h)),()=>{e(_u(h))}),[e,x,s,h]),$s(()=>{d.forEach(({type:R})=>{e(R==="entities"?Ee():Fe(R))})},[e,x,f,u]),$s(()=>(e(Si()),()=>{e(Bu())}),[e,x,i,f]),x===!1?(0,I.jsx)("div",{className:o.stateText,children:(0,I.jsx)("div",{children:(0,I.jsx)("p",{children:t("notSupported")})})},"supported"):b===!1?(0,I.jsx)("div",{className:o.loginText,children:(0,I.jsx)("div",{children:(0,I.jsx)(Cs,{isEmbedded:n,loginUrl:te})})},"login"):!u||!h||b===null||w||v?(0,I.jsx)("div",{className:o.stateText,children:(0,I.jsx)("div",{children:(0,I.jsx)("p",{children:t("waiting")})})},"waiting"):(0,I.jsx)("div",{className:(0,xp.default)(o.root),"data-testid":"widget",children:(0,I.jsxs)(Gs,{className:o.sectionList,children:[(0,I.jsx)(St,{title:t("actions"),children:(0,I.jsxs)("div",{className:o.links,children:[c&&(0,I.jsxs)("button",{className:o.link,onClick:()=>k.send("ShowCommandPalette",{isOpen:!0}),children:[(0,I.jsx)(Qt,{}),t("linkSearch")]}),a&&(0,I.jsxs)("button",{className:o.link,onClick:()=>k.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,I.jsx)(vp,{}),t("linkSummary")]}),l&&(0,I.jsxs)("button",{className:o.link,onClick:()=>k.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeSearch"}),children:[(0,I.jsx)(Sp,{}),t("linkKnowledgeSearch")]}),H&&(0,I.jsxs)("a",{className:o.link,target:"_blank",href:H,rel:"noreferrer",children:[(0,I.jsx)(ap,{}),t("linkPersonalcollection")]})]})}),r&&g.length>0&&(0,I.jsx)(St,{"data-testid":"custom-messages",children:(0,I.jsx)(Le,{withDivider:!0,children:g.map(R=>(0,I.jsx)(ip,{suggestion:R},R.text))})}),s&&p.length>0&&(0,I.jsx)(St,{title:t("titleAutoflows"),"data-testid":"autoflows",children:(0,I.jsx)(Le,{withDivider:!0,children:(0,I.jsx)(Ju,{})})}),d.map(({type:R,title:ne,amount:Pe,lines:Se})=>{var mo;switch(R){case"entities":return m&&m.length>0&&(0,I.jsx)(St,{title:ne,"data-testid":`type-${R}`,children:(0,I.jsx)(tp,{entities:m})},R);default:return((mo=C[R])==null?void 0:mo.fetchState)==="done"&&C[R].suggestions.length>0&&(0,I.jsx)(St,{title:ne,"data-testid":`type-${R}`,children:(0,I.jsx)(Le,{withDivider:!0,children:(0,I.jsx)(hp,{lines:Se,contentType:R,suggestions:C[R].suggestions.slice(0,Pe)||[]})})},R)}})]})})},Tp=af;function wp(t){let e=new Range;return e.selectNodeContents(t),e}var ao=/[\u200B-\u200D\uFEFF]/g;function At(t,e,n){let o=new Range;if(t.firstChild===null&&e===0&&n===0)return o.selectNodeContents(t),o;let s=0,r=!1;function i(l,c){let u=-1,d=/[\u200B-\u200D\uFEFF]/;if(!d.test(l))return c;for(let p=0;p<=l.length;p++)if(d.test(l[p])||u++,u===c)return p;throw new Error("Offset out of range")}function a(l){var c;switch(l.nodeType){case Node.TEXT_NODE:{let u=l.textContent,d=u.replace(ao,""),p=s+d.length,m=e>=s&&e<=p,g=n>=s&&n<=p;if(m){let f=i(u,e-s);f===0&&!g?o.setStartBefore(l):o.setStart(l,f)}g&&(o.setEnd(l,i(u,n-s)),r=!0),s=p;break}case Node.ELEMENT_NODE:{if(l.tagName==="BR"&&(s===e&&o.setStartBefore(l),s++,s===n)){o.setEndAfter(l),r=!0;return}for(let d=0;d<l.childNodes.length&&(a(l.childNodes[d]),!r);d++);let u=(c=l.lastChild)==null?void 0:c.tagName;l.tagName==="DIV"&&u!=="DIV"&&u!=="BR"&&s++;break}default:break}}if(a(t),o.startContainer===document)throw new Error("Offsets out of bound");return o}function Xs(t,e){if(!t.contains(e.commonAncestorContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:o,endContainer:s,endOffset:r}=e,i,a,l=0;function c(u){let d=u===n,p=u===s;switch(u.nodeType){case Node.TEXT_NODE:{let m=u.textContent;d&&(i=l+m.substring(0,o).replace(ao,"").length),p&&(a=l+m.substring(0,r).replace(ao,"").length),l+=m.replace(ao,"").length;break}case Node.ELEMENT_NODE:{let{tagName:m}=u,g=u.nextSibling===null;m==="BR"&&!g&&l++;for(let f=0;f<u.childNodes.length&&(d&&f===o&&(i=l),c(u.childNodes[f]),p&&f===r-1&&(a=l),a===void 0);f++);!p&&m==="DIV"&&!g&&l++,p&&(a=l);break}default:break}}if(c(t),a===void 0)throw new Error("Could not determine start and end");return{start:i??a,end:a}}function lo(t,e){if(!t.contains(e.commonAncestorContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:o,endContainer:s,endOffset:r}=e,i=-1,a="";function l(c){let u=c===n,d=c===s;switch(u&&i++,c.nodeType){case Node.TEXT_NODE:{if(i!==0)return;let p=u?o:0,m=d?r:void 0,g=c.textContent.replace(ao,"");p===0&&m===void 0?a+=g:a+=g.substring(p,m);break}case Node.ELEMENT_NODE:{let{tagName:p}=c,m=c.nextSibling===null;i===0&&p==="BR"&&!m&&(a+=`
|
|
4
4
|
`);for(let g=u?o:0;g<(d?Math.min(r,c.childNodes.length):c.childNodes.length)&&(l(c.childNodes[g]),i!==1);g++);!d&&i===0&&p==="DIV"&&!m&&(a+=`
|
|
5
|
-
`);break}default:break}d&&i++}return l(t),a}var Lt=class extends Ne{observer;getText(){let e=new Range;return e.selectNodeContents(this.element),lo(this.element,e)}getHTML(){return this.element.innerHTML||""}getSelection(){if(document.activeElement!==this.element)return null;let e=window.getSelection();if(!e||e.rangeCount===0)return null;let n=e.getRangeAt(0);return!n||!this.element.contains(n.commonAncestorContainer)?null:Xs(this.element,n)}getSelectedText(){if(!this.currentSelection)return"";let{start:e,end:n}=this.currentSelection;return lo(this.element,At(this.element,e,n))}applyChanges(e){var s;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),o=e(this.element);(s=this.observer)==null||s.takeRecords(),Promise.resolve(o).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let e=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==e&&(e=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>n.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var Ri=class{constructor(e){this.name=e;P.warn("BroadcastChannel is not supported")}postMessage(){}addEventListener(){}removeEventListener(){}close(){}},Ii=class{constructor(e,n){this.name=e;this.options=n;this.broadcastChannel=new this.options.broadcastChannelConstructor(e)}broadcastChannel;disposeHandlers=[];onMessage(e){this.broadcastChannel.addEventListener("message",e),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",e)})}postMessage(e){this.broadcastChannel.postMessage(e)}close(){this.disposeHandlers.forEach(e=>e()),this.broadcastChannel.close()}},Ai=class{constructor(e,n,o){this.name=e;this.targetOrigin=n;this.options=o;this.iframe=this.createIframe(),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];createIframe(){let e=`deepdesk-iframe-${this.name}`,n=document.getElementById(e);if(n)return n;let o=document.createElement("iframe"),s=`${this.targetOrigin}/v2/widget/liveengage/channel.html`,r=new URLSearchParams({channel:this.name,host:window.location.origin});return this.options.debug&&r.set("debug","1"),o.style.position="absolute",o.style.left="-999em",o.style.width="0px",o.style.height="0px",o.tabIndex=-1,o.id=e,o.title=`iframe-${this.name}`,o.src=`${s}?${r.toString()}`,o}onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var n;(n=this.iframe.contentWindow)==null||n.postMessage(e,this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(n=>n()),(e=this.iframe)==null||e.remove()}},Li=class{sessionId;deepdeskUrl;channel;broadcastChannelConstructor;eventMap;isIntegration;constructor(e){this.deepdeskUrl=e.deepdeskUrl,this.broadcastChannelConstructor=e.broadcastChannelConstructor||window.BroadcastChannel||Ri,this.isIntegration=e.deepdeskUrl!==(e.origin||window.location.origin),this.eventMap=e.eventMap,this.setSessionId("deepdesk-general")}setSessionId(e){if(this.sessionId===e)return;this.cleanup(),P.info("Set sessionId",e),this.sessionId=e,this.channel=this.isIntegration?new Ai(e,this.deepdeskUrl,{debug:!0}):new Ii(e,{broadcastChannelConstructor:this.broadcastChannelConstructor});let n=o=>{var s,r;o.origin===this.deepdeskUrl&&o.data.type==="event"&&(P.info("Received broadcast event",this.sessionId,o),(r=(s=this.eventMap)[o.data.name])==null||r.call(s,o.data.payload))};this.channel.onMessage(n)}send(e,n){var s,r,i;if(!this.sessionId)return;P.info("broadcast event",{sessionId:this.sessionId,name:e,payload:n});let o={type:"event",name:e,payload:n};(r=(s=this.eventMap)[e])==null||r.call(s,n),(i=this.channel)==null||i.postMessage(o)}cleanup(){var e;(e=this.channel)==null||e.close(),delete this.channel}},bp=Li;var hn=class extends Error{constructor(n,o){super(n);this.body=o}name="CustomError"};var Mi=t=>new Promise(e=>{setTimeout(e,t)});var yn=class extends hn{name="ClientError"},Oi=class extends hn{name="ServerError"},Je=class t{constructor(e="",n={}){this.baseUrl=e;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}async request(e,n={}){let o={isStale:!1},s=`${this.baseUrl}${e}`,r=this.fetch,{abortLatest:i=!1,attempts:a=1,retryDelay:l=500,refreshTokenOn401:c=!0,retryOnError:u=C=>C instanceof TypeError,retryOnResponse:d=C=>C.status>=500,version:p="v1",...m}=n,g={credentials:"include",...m,headers:{"Content-Type":"application/json",...m.headers}};n.method!==void 0&&n.method!=="GET"&&this.csrfToken&&(g.headers={...g.headers,"X-CSRFToken":this.csrfToken}),typeof p=="string"&&(g.headers={...g.headers,"X-Deepdesk-API-Version":p});let f=a,x=!1;if(!r)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&i&&(this.latestRequestByUrl[s].isStale=!0),this.latestRequestByUrl[s]=o;let b=async()=>(f--,r(s,g).then(async C=>d(C)&&!o.isStale&&f>0?(await Mi(l),b()):C.status===401&&c===!0&&x===!1?(x=!0,await this.refreshToken(),b()):C).catch(async C=>{if(u(C)&&!o.isStale&&f>0)return await Mi(l),b();throw C})),h=await b(),v=await h.json().catch(()=>null);if(o.isStale)throw new Error("Aborted");if(h.status>=500)throw new Oi("Server Error",v);if(h.status===401)throw new yn("Unauthorized",v);if(h.status===403)throw new yn("Forbidden",v);if(h.status===404)throw new yn("Not Found",v);if(h.status>=400)throw new yn("Bad Request",v);return delete this.latestRequestByUrl[s],v}async validateToken(){let{has_valid_access_token:e}=await this.get("/auth/validate");if(!e)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return t.refreshingToken||(t.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{t.refreshingToken=null},1e3*60)})),t.refreshingToken}get(e,n){return this.request(e,n)}post(e,n,o){return this.request(e,{method:"POST",body:JSON.stringify(n),...o})}patch(e,n,o){return this.request(e,{method:"PATCH",body:JSON.stringify(n),...o})}put(e,n,o){return this.request(e,{method:"PUT",body:JSON.stringify(n),...o})}delete(e,n){return this.request(e,{method:"DELETE",...n})}};var lf;(e=>{let t;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||={})})(lf||={});function Qs(t){return{...O(t),tags:t.tags}}var Ye=class t{constructor(e,n={}){this.options=n;this.client=new Je(e,{fetch:n.fetch}),this.client.patchFetch(o=>async(s,r)=>{let i=await o(s,r);return this.handleDeepdeskVersionHeaders(i),i})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=await this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(t.exchangeTokenPromise||(t.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),t.exchangeTokenPromise):Promise.resolve()}async createConversation(e){await this.preflight(),P.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let n=await this.client.post("/api/conversations",{...K(e),tags:e.tags},{version:"v2"});return Qs(n)}async getProfile(e){let n=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null});return O(n)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null});return O(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null});return O(e)}async checkUserExists(e){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${e}`);return n}async getConversationBySessionId(e,n={}){await this.preflight(),P.info(`Getting conversation for session ${e}`);let{attempts:o=1,retryDelay:s=1e3}=n,r=await this.client.get(`/api/conversations/by_session_id/${e}`,{attempts:o,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"});return Qs(r)}async isConversationSupported(e,n={}){P.info(`Check if conversation for session ${e} is supported`);let{attempts:o=1,retryDelay:s=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${e}/active_profile`,{attempts:o,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"})).has_active_profile}async updateConversation(e,n){let o=K(n);n.tags&&(o.tags=n.tags);let s=await this.client.put(`/api/conversations/${e}`,o,{version:"v2"});return Qs(s)}async postMessages(e,n){return(await this.client.post(`/api/conversations/${e}/messages`,n.map(s=>({...K(s),tags:s.tags})),{version:"v2"})).map(s=>Qs(s))}async sendEvent(e,n){let{data:o,...s}=n,r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((i,[a,l])=>({...i,[a]:l}),{});return this.client.post("/api/events",K({...r,...s,data:o,name:e}),{version:"v2"})}async sendEventV1(e,n){let o=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[r,i])=>({...s,[r]:i}),{});return this.client.post("/api/events",{event:e,data:K({...n,...o})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e.filter(o=>o.text)})).entities}async getSummary(e){return(await this.client.post("/api/summary",{conversation:{messages:e.filter(o=>o.text&&o.source)}})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(e){return this.client.get(`/apis/admin/session/jwt/?jwt=${e}`,{version:null}).catch(n=>{throw P.warn(`Invalid token '${e}'`),n})}async authenticateWithKey(e,n){await this.client.post("/apis/admin/session/api-key/",K(n),{version:null,refreshTokenOn401:!1,headers:{apikey:e}})}async getTextSuggestions(e,n={},o){return o==="sticky-messages"?this.getPinnedMessages(e):(await this.client.post(`/api/conversations/${e}/recommend/${o}`,K(n),{abortLatest:!0})).map(r=>({...O(r),text:r.text||r.url||r.message,source:o,type:o})).filter((r,i,a)=>i===a.findIndex(l=>l.text===r.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(e,n){return(await this.client.post(`/api/conversations/${e}/autocomplete`,K(n),{abortLatest:!0})).map(s=>({score:1,source:s.source,sourceText:s.source_text,text:s.label,trainingJobs:s.training_jobs,searchKeywords:s.search_keywords,type:s.source})).filter((s,r,i)=>r===i.findIndex(a=>a.text===s.text))}async getPinnedMessages(e){let n=await this.client.get(`/api/conversations/${e}/sticky-messages`,{abortLatest:!0});return O(n).map(o=>({...o,text:o.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(e){let n=await this.client.post("/api/style-suggestions",K(e),{abortLatest:!0});return O(n)}async search(e){let n=await this.client.post(`/api/profiles/${e.profile}/search`,K(e),{version:"v2"});return O(n)}async knowledgeSearch(e,n,o){let s=await this.client.post("/api/knowledge-search/search",K({question:e.question,promptInstruction:e.promptInstruction,profile:o,chatHistory:n.map(r=>({question:r.question,answer:r.answer.answer}))}),{version:"v2"});return O(s)}async requestLoginByEmail(e){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return O(n)}async getCsrfToken(){let{token:e}=await this.client.get("/apis/admin/session/csrf/",{version:null});return e}async verifyLoginToken(e){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:e},{version:null});return O(n)}handleDeepdeskVersionHeaders(e){e.headers.forEach((n,o)=>{let s=o.toLowerCase(),r=s.match(Ui);if(!n||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&P.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};var co=class{constructor(e,n){this.url=e;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(Nr(e),n=>{let{data:o}=n;try{let s=JSON.parse(o);this.emit(e,O(s))}catch{P.warn(`Invalid JSON for ${e}: ${o}`)}})}connect(){clearTimeout(this.timeoutTimer);let e=new EventSource(this.url,{withCredentials:!0});this.eventSource=e;let n=!1;e.onopen=()=>{n=!0},e.onerror=()=>{n&&e.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{e.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(o=>{this.proxyEvent(o)})}disconnect(){var e;clearTimeout(this.timeoutTimer),this.eventListeners={},(e=this.eventSource)==null||e.close()}emit(e,n){this.eventListeners[e]&&this.eventListeners[e].forEach(o=>o(n))}on(e,n){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n),this.proxyEvent(e),()=>{this.off(e,n)}}off(e,n){let o;this.eventListeners[e]&&(o=this.eventListeners[e].indexOf(n),o>-1&&this.eventListeners[e].splice(o,1))}};var cf;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(cf||={});var uo=class{constructor(e,n={}){this.apiUrl=e;this.client=new Je(e,n)}client;streams={};logger=P;async getCustomMessages(e){let n=await this.client.get(`/sessions/${e}/suggestions`);return O(n.suggestions)}async sendCustomMessage(e,n){let o=await this.client.post(`/sessions/${e}/messages`,K(n));return O(o)}async answerCustomMessage(e,n){await this.client.post(`/sessions/${e}/answers`,K(n))}async getAutoflows(e){let n=await this.client.get(`/sessions/${e}/autoflows`);return O(n.autoflows)}async startAutoflowSession(e){let n=await this.client.post("/autoflow-sessions",K(e));return O(n)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new co(`${this.apiUrl}/sessions/${e}/events`),this.streams[e].connect()),this.streams[e]}closeStream(e){this.streams[e]||(this.streams[e].disconnect(),delete this.streams[e])}};var Ys=require("@reduxjs/toolkit");var _p=require("@reduxjs/toolkit");var Ep={startTime:null,stopTime:null},Pp=(0,_p.createSlice)({name:"handlingTime",initialState:Ep,reducers:{handlingTimeStart(t){if(t.startTime&&!t.stopTime)throw new Error("Timing already started");t.startTime=new Date,t.stopTime=null},handlingTimeStop(t){if(!t.startTime)throw new Error("Timing not started");t.stopTime=new Date},handlingTimeReset(t){t.startTime=null,t.stopTime=null}},extraReducers:t=>{t.addCase(A,()=>Ep)}}),{handlingTimeStart:kp,handlingTimeStop:Zs,handlingTimeReset:Rp}=Pp.actions,Ip=Pp.reducer;var Ap=(t={})=>{let e={onAuthError:us(!1),...t};return n=>o=>s=>("error"in s&&s.error.message==="Unauthorized"&&n.dispatch(e.onAuthError),o(s))};var Js=require("@reduxjs/toolkit");var Ni={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var Mt=(0,Js.createAsyncThunk)("styleSuggestions/getAll",async({text:t},e)=>{var i;let{deepdeskAPI:n}=e.extra,o=e.getState(),{showStyleSuggestions:s}=o.settings,r=(i=o.conversation.current)==null?void 0:i.profileCode;if(!s)return Ni.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:r,message:t})}),uf=(0,Js.createSlice)({name:"styleSuggestions",initialState:Ni,reducers:{},extraReducers:t=>{t.addCase(Mt.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(Mt.rejected,e=>{e.fetchState="error"}).addCase(Mt.fulfilled,(e,n)=>{e.fetchState="done",st(e.list,n.payload)||(e.list=n.payload)}).addCase(A,()=>Ni)}}),Lp=uf.reducer;var Mp=(t={})=>{let e,n=!0,o={getStyleSuggestions:Mt,debounce:500,...t};return s=>r=>i=>{var m;let a=s.getState().input.text,l=r(i),c=s.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:u}=c.settings;if(!((m=c.conversation.current)==null?void 0:m.id)||!u)return l;let{text:p}=c.input;return p===a&&!n||(clearTimeout(e),p==="")||(e=setTimeout(()=>{n=!1,s.dispatch(o.getStyleSuggestions({text:p}))},t.debounce)),l}};function pf(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var Op=(t={})=>{let e={getTextSuggestions:Fe,getAutocompleteSuggestions:Bn,debounce:200,check:xs,...t},n,o=!0;return s=>r=>i=>{var x;let{input:{userCommitted:a}}=s.getState(),l=r(i),c=s.getState();if(c.auth.isLoggedIn!==!0)return l;let{recommendTextSuggestions:u,showTabCompletion:d}=c.settings,p=(x=c.conversation.current)==null?void 0:x.id,m=i.type===cs.toString();if(!p||!u&&!d)return l;let{input:{userCommitted:g}}=c;return pf(g,a)&&!o&&!m||(clearTimeout(n),!e.check(c))||(n=setTimeout(()=>{o=!1;let b=Ht(c);b===""?s.dispatch(e.getTextSuggestions("default")):s.dispatch(e.getAutocompleteSuggestions(b))},m?0:e.debounce)),l}};var Np=Mt.fulfilled.toString();function df(t,e){let n=new Set([...e.keywordMatches.map(s=>s.keyword)]),o=[];return n.forEach(s=>{let r=t.keywordMatches.filter(l=>l.keyword===s),i=e.keywordMatches.filter(l=>l.keyword===s),a=i.length-r.length;a<=0||o.push(...i.slice(0,a))}),o}var Dp=t=>e=>n=>o=>{var u;if(o.type!==Np){n(o);return}let s=e.getState().styleSuggestions.list;n(o);let r=e.getState(),i=r.styleSuggestions.list,a=(u=r.conversation)==null?void 0:u.current,{agentInfo:l}=r.info;if(s===i)return;let c=df(s,i);o.type===Np&&c.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,agentId:l.agentId??(a==null?void 0:a.agentId),agentName:l.agentName??(a==null?void 0:a.agentName),agentEmail:l.agentEmail??(a==null?void 0:a.agentEmail),data:{keywordMatches:c}})};var mf=(0,Ys.combineReducers)({activeSuggestion:kl,answer:yc,auth:Vl,autoflows:Pu,conversation:Xi,contentTypes:tc,customMessages:Du,exchangeToken:Ku,entities:rc,handlingTime:Ip,info:el,input:lr.reducer,overlayInput:Q.reducer,settings:zi,profile:xc,search:il,summary:pc,styleSuggestions:Lp,ui:Ol,textSuggestions:Tl});function Hp(t){return(0,Ys.configureStore)({reducer:mf,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),Ap(),Op({debounce:200}),Mp({debounce:500}),Dp(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var gf=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},ff=t=>e=>n=>o=>{var a;let s=e.getState(),r=sr("inlineSuggestions")(s);switch(o.type){case Be.toString():{let l=hl(o.payload.contentType)(e.getState()),c=l.indexOf(o.payload.suggestion);t.emit("edit-suggestion",{contentType:o.payload.contentType,index:c,suggestions:l});break}case Ce.toString():{let{start:l,end:c}=s.input.selection;t.emit("select-suggestion",{type:gf(o.payload.suggestion),...o.payload,replace:o.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case _o.toString():{let{start:l,end:c}=s.input.selection;t.emit("replace",{...o.payload,replace:o.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case Cn.toString():{let l=e.getState(),{text:c,selection:u}=l.input.userCommitted;t.emit("reset",{text:c,selectionAfter:u},{mayApplyChanges:!0});break}case Io.toString():t.emit("select-image",o.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:s.conversation.current.id,data:{path:o.payload.suggestion.image,title:o.payload.suggestion.title}});break;case Ee.fulfilled.toString():o.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:o.payload}});break;case qe.fulfilled.toString():t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{inputText:JSON.stringify(o.payload.original),summary:o.payload.summary}});break;case Re.toString():t.sendEvent(o.payload.name,{conversationId:((a=o.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:o.payload.data});break;case Po.toString():t.handleKeyDown(o.payload);break;case xn.toString():t.logSendMessage(o.payload);break;case ko.toString():t.logSendEditSuggestionMessage(o.payload);break;case Ro.toString():t.handleInputChanged(o.payload);break;default:break}let i=n(o);switch(o.type){case xn.toString():t.handleAfterSendMessage(o.payload);break;case Kn.toString():t.onUpdateShowTabHint(o.payload);break;case Zs.toString():t.logHandlingTime();break;case Ce.toString():{r&&(e.dispatch(it([])),e.dispatch(at()));break}default:break}return i},Fp=ff;function Di(t){return t.toISOString().replace("T"," ").replace("Z","")}function Bp(t,e){var s,r,i;let{startTime:n,stopTime:o}=t.handlingTime;if(!n||!o)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:t.conversation.current.id,clientVersion:e.version,agentId:(s=t.info.agentInfo)==null?void 0:s.agentId,agentName:(r=t.info.agentInfo)==null?void 0:r.agentName,agentEmail:(i=t.info.agentInfo)==null?void 0:i.agentEmail,timeStart:Di(n),timeStop:Di(o)}}function Hi(t,e,n){var k,w,H;let{text:o,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:c,pastes:u,cuts:d,deletions:p,textSuggestions:m,offeredTextSuggestions:g}}=e[t],f=o.length,b=m.reduce((te,{text:R,searchTerm:ne})=>te+R.length-(ne?ne.length:0),0),h=c??Date.now(),v=(Date.now()-h)/1e3,C=s/v;return{conversationId:e.conversation.current.id,source:"agent",text:o,clientVersion:n.version,pastes:u,cuts:d,deletions:p,lenTextTyped:s,lenTextTotal:f,lenTextAssisted:b,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:v,charsPerSecond:C,numPastes:l,textSuggestionsV2:m,suggestionsCounters:[{source:"gpt",countOffered:g.filter(te=>te.source==="gpt").length}],agentId:(k=e.info.agentInfo)==null?void 0:k.agentId,agentName:(w=e.info.agentInfo)==null?void 0:w.agentName,agentEmail:(H=e.info.agentInfo)==null?void 0:H.agentEmail}}function Kp(t,e){let n=t.closest(e);if(n)return n;let o=t.getRootNode().host;return o instanceof HTMLElement?Kp(o,e):null}function Up(t,e){return Kp(t,e)}function qp(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function er(t){return t instanceof HTMLElement&&(Ge(t)||Xo(t))}var Vp=(t,e)=>({value(){try{let n=sessionStorage.getItem(`dd-${t}`);if(!n)return e;try{return JSON.parse(n)}catch{return e}}catch{return e}},update(n){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(n))}catch{P.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function hf(t){return t.offsetParent!==null}function jp(t){if(!hf(t))return!1;let e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}function tr(t,e,n=100){let o=jp(t);e({isVisible:o});let s=setInterval(()=>{let r=jp(t);r!==o&&(o=r,e({isVisible:o}))},n);return()=>{clearTimeout(s)}}var le=require("react/jsx-runtime"),zp=Vp("showTabHint",!0),po=class t{static version="10.1.0";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:n,version:o=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a}){let l=e.replace(/\/api$/,"");this.deepdeskApi=new Ye(l,{token:r,fetch:i}),this.version=o,this.instanceId=t.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Fp({emit:(u,d,p)=>this.emit(u,d,p),handleAfterSendMessage:u=>this.handleAfterSendMessage(u),handleInputChanged:u=>this.handleInputChanged(u),handleKeyDown:u=>this.handleKeyDown(u),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:u=>this.logSendMessage(u),logSendEditSuggestionMessage:u=>this.logSendEditMessage(u),onUpdateShowTabHint:u=>zp.update(u),sendEvent:(u,d)=>this.deepdeskApi.sendEvent(u,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new uo(n)}),this.store=Hp(c),this.broadcastEvents=new bp({debug:!0,deepdeskUrl:l,eventMap:jl(this.store)}),this.store.dispatch(vn),this.store.dispatch(Kn(zp.value())),this.store.dispatch(vn({locale:s,adminUrl:l,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?(P.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(P.warn("Profile has not been loaded (yet)"),!0):(P.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(us(null)),this.store.dispatch(bt()),new Promise(e=>{let n=this.store.subscribe(()=>{let o=this.store.getState();Ke(o)&&Hl(o)!=="loading"&&e()});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return this.deepdeskApi.isLoggedIn()}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(n){P.warn("Failed to attach user:",n)}}async isConversationSupported(e,n){return(await this.store.dispatch(ir({sessionId:e,options:n}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(xo(e))).payload}async getConversationBySessionId(e,n){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Co({sessionId:e,options:n}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(ar(e))).payload}async postMessages(e){return(await this.store.dispatch(wo(e))).payload}async updateConversation(e){return(await this.store.dispatch(To(e))).payload}resetConversation(){this.store.dispatch(A()),this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(qe());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(vn(e))}setVisitorInfo(e){this.store.dispatch(Ya(e))}async setAgentInfo(e){await this.store.dispatch(Nn(e))}async setAgentSettings(e){await this.store.dispatch(Dr(e))}async getAgentSettings(){return(await this.store.dispatch(Hr())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();let e=[];return this.store.dispatch(cs()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Ro(e))}syncInputHtml(e){this.store.dispatch(ua(e))}notifyKeyDown(e){this.store.dispatch(Po(e))}notifyPaste(e,n){this.store.dispatch(la({text:e,selectionText:n}))}notifyCut(e){this.store.dispatch(ia(e))}notifyExternalSuggestion(e){this.store.dispatch(Ce(e)),this.store.dispatch(at())}notifyEditSuggestion(e){this.store.dispatch(xl(e.contentType,e.suggestions)),this.store.dispatch(Be({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}handleInputChanged(e){let{overlayCollapsed:n,openOverlayWhenTyping:o}=this.state.ui;n&&o&&this.store.dispatch(en({collapse:!1})),this.inputMediator&&this.store.dispatch(ea({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(it([])))}handleKeyDown(e){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=o.length>0,l=s!==-1;if(this.store.dispatch(aa(Eo(e))),!(e.key!=="Tab"&&!this.settings.showTextSuggestions))switch(e.key){case"Up":case"ArrowUp":if(n||!a||!r||e.shiftKey)return;this.store.dispatch(oa()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault();return;case"Down":case"ArrowDown":{if(n||!a||!r||e.shiftKey)return;this.store.dispatch(ra());let{selectedSuggestionIndex:c}=this.state.input;c===-1?this.store.dispatch(Cn()):i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault();return}case"Esc":case"Escape":{l?(this.store.dispatch(Ao(-1)),this.store.dispatch(Cn()),e.preventDefault()):n||(this.store.dispatch(en({collapse:!0})),this.store.dispatch(Ll(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:c}=this.state.input,u=c.text.substring(0,c.selection.end),{tabCompletionSuggestion:d}=this.state.input;this.store.dispatch(Kn(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):this.settings.showTabCompletion&&d&&d.text.startsWith(u)&&(this.store.dispatch(Ce({text:d.text,suggestion:d,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(at())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(ca()),this.store.dispatch(it([]))}handlingTimeStart(){this.state.handlingTime.startTime||(P.info("Start handling time"),this.store.dispatch(kp()))}handlingTimeStop(){this.state.handlingTime.startTime&&(P.info("Stop handling time"),this.store.dispatch(Zs()))}logSendMessage(e){let n=Hi("input",this.state,{version:this.version});e&&Object.assign(n,{text:e}),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logSendEditMessage(e){let n=Hi("overlayInput",this.state,{version:"v2"});e&&Object.assign(n,{text:e}),this.store.dispatch(na(this.state.overlayInput.metrics)),this.deepdeskApi.sendEvent("suggestion edited",{data:n})}logHandlingTime(){let e=Bp(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Rp())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(at()),this.store.dispatch(xn(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:o}=this.state.input;this.store.dispatch(Ce({text:o[n].text,suggestion:o[n],eventMetrics:e,replace:"until-selection-end"}))}emit(e,n,o={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(n)}catch(i){P.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),P.error(i)}})};this.inputMediator&&o.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,n){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n),()=>{this.off(e,n)}}off(e,n){if(!e&&!n){this.eventListeners={};return}let o;this.eventListeners[e]&&(o=this.eventListeners[e].indexOf(n),o>-1&&this.eventListeners[e].splice(o,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let n=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&n();let o=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==o&&(o=this.hasConversation(),o&&n())})}overlayContainerFactory(e,n,o,s){let[r,i]=Gt(o,s);return r.dataset.testid=e,n!=null&&n.rootNode&&r.classList.add(n.rootNode),this.unmountHandlers.push(()=>{(0,et.unmountComponentAtNode)(r),i(),r.remove()}),r}createContainer(e,n=document.body){let o=window.getComputedStyle(n),s=document.createElement("div");return xt(s),s.dataset.testid=e,s.style.color=o.color,s.style.fontSize=o.fontSize,s.style.fontFamily=o.fontFamily,s.style.fontVariant=o.fontVariant,n.appendChild(s),this.unmountHandlers.push(()=>{(0,et.unmountComponentAtNode)(s),s.remove()}),s}mount(e,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!er(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:o={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:u,isEmbedded:d,detectSubmit:p,insertLink:m,inputMediator:g,closestScrollSelector:f,appendOverlayTo:x,inlineSuggestions:b}=n;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:u,showTextSuggestions:i,insertLink:m,isEmbedded:d,inlineSuggestions:b});let h=f&&Up(e,f)||void 0,v=this.overlayContainerFactory("deepdesk-tab-completion",o,e,{appendTo:x,closestScrollElement:h,mirrorOverflow:!0,onRemove:()=>this.unmount()}),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",o,h||e,{appendTo:x});n.automaticHandlingTime&&this.setupHandlingTime(e),(0,et.render)((0,le.jsx)(eo,{store:this.store,customStyles:o,children:(0,le.jsx)(qn,{broadcastEvents:this.broadcastEvents,children:(0,le.jsx)(Cu,{inputElement:e})})}),v),(0,et.render)((0,le.jsx)(eo,{store:this.store,customStyles:o,children:(0,le.jsx)(qn,{broadcastEvents:this.broadcastEvents,children:(0,le.jsx)(Es,{})})}),C),(0,et.render)((0,le.jsx)(eo,{store:this.store,customStyles:o,children:(0,le.jsx)(qn,{broadcastEvents:this.broadcastEvents,children:(0,le.jsx)(Ec,{})})}),this.createContainer("deepdesk-overlays")),xt(e),this.inputMediator=g||(Ge(e)?new De(e):new Lt(e)),this.inputMediator.on("change",({plainText:w})=>{this.notifyInputChanged(w)}),this.inputMediator.on("updated",({rawHtml:w})=>{w!=null&&this.syncInputHtml(w)}),this.inputMediator.on("keydown",w=>{this.notifyKeyDown(w)}),this.inputMediator.on("paste",({pastedText:w,selectionText:H})=>{this.notifyPaste(w,H)}),this.inputMediator.on("cut",({selectionText:w})=>{this.notifyCut(w)});let k;this.inputMediator.on("selection",w=>{clearTimeout(k),w===null?k=setTimeout(()=>{w!==null&&this.store.dispatch(cr(w))},500):this.store.dispatch(cr(w))}),this.inputMediator.on("disabled",()=>{var w;(w=this.inputMediator)==null||w.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{p&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Yt(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Yt(!0))),this.store.dispatch(ta({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.whenConversationLoaded(()=>{var w;this.broadcastEvents.setSessionId((w=this.state.conversation.current)==null?void 0:w.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,n={}){if(this.widgetRoot&&P.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:o,showImages:s,showPersonalCollectionLink:r,isEmbedded:i}=n;this.widgetRoot=e,this.configure({showImages:s,showPersonalCollectionLink:r,isEmbedded:i}),(0,et.render)((0,le.jsx)(eo,{store:this.store,customStyles:o,children:(0,le.jsx)(qn,{broadcastEvents:this.broadcastEvents,children:(0,le.jsx)(Tp,{})})}),e),this.whenConversationLoaded(()=>{var a;this.broadcastEvents.setSessionId((a=this.state.conversation.current)==null?void 0:a.sessionId)})}unmountWidget(){this.widgetRoot&&(0,et.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let n=tr(e,({isVisible:o})=>{o?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){qp(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Jn());let e=an(this.state);e&&this.store.dispatch(vn({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:e.knowledgeSearch,recommendTextSuggestions:e.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async checkForTrialMode(e){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(P.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:o}=n;P.info(o),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let n=vs(this.state);try{n.forEach(({type:o})=>{o==="entities"?this.store.dispatch(Ee()):this.store.dispatch(Fe(o))})}catch(o){this.handleError(o)}}};async function Wp(t,e,n={}){let{value:o}=t,{start:s,end:r}=n.replace??{start:0,end:o.length},i=`${o.slice(0,s)}${e}${o.slice(r)}`,a=n.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(n.setValue)return n.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function Gp(t,e,n={}){let o=n.replace?At(t,n.replace.start,n.replace.end):wp(t),s,r=()=>{if(n.setRange)return n.setRange(o.cloneRange());o.deleteContents(),s=document.createElement("span"),o.insertNode(s),e.split(`
|
|
5
|
+
`);break}default:break}d&&i++}return l(t),a}var Lt=class extends Ne{observer;getText(){let e=new Range;return e.selectNodeContents(this.element),lo(this.element,e)}getHTML(){return this.element.innerHTML||""}getSelection(){if(document.activeElement!==this.element)return null;let e=window.getSelection();if(!e||e.rangeCount===0)return null;let n=e.getRangeAt(0);return!n||!this.element.contains(n.commonAncestorContainer)?null:Xs(this.element,n)}getSelectedText(){if(!this.currentSelection)return"";let{start:e,end:n}=this.currentSelection;return lo(this.element,At(this.element,e,n))}applyChanges(e){var s;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),o=e(this.element);(s=this.observer)==null||s.takeRecords(),Promise.resolve(o).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let e=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==e&&(e=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>n.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var Ri=class{constructor(e){this.name=e;P.warn("BroadcastChannel is not supported")}postMessage(){}addEventListener(){}removeEventListener(){}close(){}},Ii=class{constructor(e,n){this.name=e;this.options=n;this.broadcastChannel=new this.options.broadcastChannelConstructor(e)}broadcastChannel;disposeHandlers=[];onMessage(e){this.broadcastChannel.addEventListener("message",e),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",e)})}postMessage(e){this.broadcastChannel.postMessage(e)}close(){this.disposeHandlers.forEach(e=>e()),this.broadcastChannel.close()}},Ai=class{constructor(e,n,o){this.name=e;this.targetOrigin=n;this.options=o;this.iframe=this.createIframe(),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];createIframe(){let e=`deepdesk-iframe-${this.name}`,n=document.getElementById(e);if(n)return n;let o=document.createElement("iframe"),s=`${this.targetOrigin}/v2/widget/liveengage/channel.html`,r=new URLSearchParams({channel:this.name,host:window.location.origin});return this.options.debug&&r.set("debug","1"),o.style.position="absolute",o.style.left="-999em",o.style.width="0px",o.style.height="0px",o.tabIndex=-1,o.id=e,o.title=`iframe-${this.name}`,o.src=`${s}?${r.toString()}`,o}onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var n;(n=this.iframe.contentWindow)==null||n.postMessage(e,this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(n=>n()),(e=this.iframe)==null||e.remove()}},Li=class{sessionId;deepdeskUrl;channel;broadcastChannelConstructor;eventMap;isIntegration;constructor(e){this.deepdeskUrl=e.deepdeskUrl,this.broadcastChannelConstructor=e.broadcastChannelConstructor||window.BroadcastChannel||Ri,this.isIntegration=e.deepdeskUrl!==(e.origin||window.location.origin),this.eventMap=e.eventMap,this.setSessionId("deepdesk-general")}setSessionId(e){if(this.sessionId===e)return;this.cleanup(),P.info("Set sessionId",e),this.sessionId=e,this.channel=this.isIntegration?new Ai(e,this.deepdeskUrl,{debug:!0}):new Ii(e,{broadcastChannelConstructor:this.broadcastChannelConstructor});let n=o=>{var s,r;o.origin===this.deepdeskUrl&&o.data.type==="event"&&(P.info("Received broadcast event",this.sessionId,o),(r=(s=this.eventMap)[o.data.name])==null||r.call(s,o.data.payload))};this.channel.onMessage(n)}send(e,n){var s,r,i;if(!this.sessionId)return;P.info("broadcast event",{sessionId:this.sessionId,name:e,payload:n});let o={type:"event",name:e,payload:n};(r=(s=this.eventMap)[e])==null||r.call(s,n),(i=this.channel)==null||i.postMessage(o)}cleanup(){var e;(e=this.channel)==null||e.close(),delete this.channel}},bp=Li;var hn=class extends Error{constructor(n,o){super(n);this.body=o}name="CustomError"};var Mi=t=>new Promise(e=>{setTimeout(e,t)});var yn=class extends hn{name="ClientError"},Oi=class extends hn{name="ServerError"},Je=class t{constructor(e="",n={}){this.baseUrl=e;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}async request(e,n={}){let o={isStale:!1},s=`${this.baseUrl}${e}`,r=this.fetch,{abortLatest:i=!1,attempts:a=1,retryDelay:l=500,refreshTokenOn401:c=!0,retryOnError:u=C=>C instanceof TypeError,retryOnResponse:d=C=>C.status>=500,version:p="v1",...m}=n,g={credentials:"include",...m,headers:{"Content-Type":"application/json",...m.headers}};n.method!==void 0&&n.method!=="GET"&&this.csrfToken&&(g.headers={...g.headers,"X-CSRFToken":this.csrfToken}),typeof p=="string"&&(g.headers={...g.headers,"X-Deepdesk-API-Version":p});let f=a,x=!1;if(!r)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&i&&(this.latestRequestByUrl[s].isStale=!0),this.latestRequestByUrl[s]=o;let b=async()=>(f--,r(s,g).then(async C=>d(C)&&!o.isStale&&f>0?(await Mi(l),b()):C.status===401&&c===!0&&x===!1?(x=!0,await this.refreshToken(),b()):C).catch(async C=>{if(u(C)&&!o.isStale&&f>0)return await Mi(l),b();throw C})),h=await b(),v=await h.json().catch(()=>null);if(o.isStale)throw new Error("Aborted");if(h.status>=500)throw new Oi("Server Error",v);if(h.status===401)throw new yn("Unauthorized",v);if(h.status===403)throw new yn("Forbidden",v);if(h.status===404)throw new yn("Not Found",v);if(h.status>=400)throw new yn("Bad Request",v);return delete this.latestRequestByUrl[s],v}async validateToken(){let{has_valid_access_token:e}=await this.get("/auth/validate");if(!e)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return t.refreshingToken||(t.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{t.refreshingToken=null},1e3*60)})),t.refreshingToken}get(e,n){return this.request(e,n)}post(e,n,o){return this.request(e,{method:"POST",body:JSON.stringify(n),...o})}patch(e,n,o){return this.request(e,{method:"PATCH",body:JSON.stringify(n),...o})}put(e,n,o){return this.request(e,{method:"PUT",body:JSON.stringify(n),...o})}delete(e,n){return this.request(e,{method:"DELETE",...n})}};var lf;(e=>{let t;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||={})})(lf||={});function Qs(t){return{...O(t),tags:t.tags}}var Ye=class t{constructor(e,n={}){this.options=n;this.client=new Je(e,{fetch:n.fetch}),this.client.patchFetch(o=>async(s,r)=>{let i=await o(s,r);return this.handleDeepdeskVersionHeaders(i),i})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=await this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(t.exchangeTokenPromise||(t.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),t.exchangeTokenPromise):Promise.resolve()}async createConversation(e){await this.preflight(),P.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let n=await this.client.post("/api/conversations",{...K(e),tags:e.tags},{version:"v2"});return Qs(n)}async getProfile(e){let n=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null});return O(n)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null});return O(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null});return O(e)}async checkUserExists(e){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${e}`);return n}async getConversationBySessionId(e,n={}){await this.preflight(),P.info(`Getting conversation for session ${e}`);let{attempts:o=1,retryDelay:s=1e3}=n,r=await this.client.get(`/api/conversations/by_session_id/${e}`,{attempts:o,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"});return Qs(r)}async isConversationSupported(e,n={}){P.info(`Check if conversation for session ${e} is supported`);let{attempts:o=1,retryDelay:s=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${e}/active_profile`,{attempts:o,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"})).has_active_profile}async updateConversation(e,n){let o=K(n);n.tags&&(o.tags=n.tags);let s=await this.client.put(`/api/conversations/${e}`,o,{version:"v2"});return Qs(s)}async postMessages(e,n){return(await this.client.post(`/api/conversations/${e}/messages`,n.map(s=>({...K(s),tags:s.tags})),{version:"v2"})).map(s=>Qs(s))}async sendEvent(e,n){let{data:o,...s}=n,r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((i,[a,l])=>({...i,[a]:l}),{});return this.client.post("/api/events",K({...r,...s,data:o,name:e}),{version:"v2"})}async sendEventV1(e,n){let o=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[r,i])=>({...s,[r]:i}),{});return this.client.post("/api/events",{event:e,data:K({...n,...o})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e.filter(o=>o.text)})).entities}async getSummary(e){return(await this.client.post("/api/summary",{conversation:{messages:e.filter(o=>o.text&&o.source)}})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(e){return this.client.get(`/apis/admin/session/jwt/?jwt=${e}`,{version:null}).catch(n=>{throw P.warn(`Invalid token '${e}'`),n})}async authenticateWithKey(e,n){await this.client.post("/apis/admin/session/api-key/",K(n),{version:null,refreshTokenOn401:!1,headers:{apikey:e}})}async getTextSuggestions(e,n={},o){return o==="sticky-messages"?this.getPinnedMessages(e):(await this.client.post(`/api/conversations/${e}/recommend/${o}`,K(n),{abortLatest:!0})).map(r=>({...O(r),text:r.text||r.url||r.message,source:o,type:o})).filter((r,i,a)=>i===a.findIndex(l=>l.text===r.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(e,n){return(await this.client.post(`/api/conversations/${e}/autocomplete`,K(n),{abortLatest:!0})).map(s=>({score:1,source:s.source,sourceText:s.source_text,text:s.label,trainingJobs:s.training_jobs,searchKeywords:s.search_keywords,type:s.source})).filter((s,r,i)=>r===i.findIndex(a=>a.text===s.text))}async getPinnedMessages(e){let n=await this.client.get(`/api/conversations/${e}/sticky-messages`,{abortLatest:!0});return O(n).map(o=>({...o,text:o.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(e){let n=await this.client.post("/api/style-suggestions",K(e),{abortLatest:!0});return O(n)}async search(e){let n=await this.client.post(`/api/profiles/${e.profile}/search`,K(e),{version:"v2"});return O(n)}async knowledgeSearch(e,n,o){let s=await this.client.post("/api/knowledge-search/search",K({question:e.question,promptInstruction:e.promptInstruction,profile:o,chatHistory:n.map(r=>({question:r.question,answer:r.answer.answer}))}),{version:"v2"});return O(s)}async requestLoginByEmail(e){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return O(n)}async getCsrfToken(){let{token:e}=await this.client.get("/apis/admin/session/csrf/",{version:null});return e}async verifyLoginToken(e){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:e},{version:null});return O(n)}handleDeepdeskVersionHeaders(e){e.headers.forEach((n,o)=>{let s=o.toLowerCase(),r=s.match(Ui);if(!n||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&P.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};var co=class{constructor(e,n){this.url=e;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(Nr(e),n=>{let{data:o}=n;try{let s=JSON.parse(o);this.emit(e,O(s))}catch{P.warn(`Invalid JSON for ${e}: ${o}`)}})}connect(){clearTimeout(this.timeoutTimer);let e=new EventSource(this.url,{withCredentials:!0});this.eventSource=e;let n=!1;e.onopen=()=>{n=!0},e.onerror=()=>{n&&e.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{e.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(o=>{this.proxyEvent(o)})}disconnect(){var e;clearTimeout(this.timeoutTimer),this.eventListeners={},(e=this.eventSource)==null||e.close()}emit(e,n){this.eventListeners[e]&&this.eventListeners[e].forEach(o=>o(n))}on(e,n){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n),this.proxyEvent(e),()=>{this.off(e,n)}}off(e,n){let o;this.eventListeners[e]&&(o=this.eventListeners[e].indexOf(n),o>-1&&this.eventListeners[e].splice(o,1))}};var cf;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(cf||={});var uo=class{constructor(e,n={}){this.apiUrl=e;this.client=new Je(e,n)}client;streams={};logger=P;async getCustomMessages(e){let n=await this.client.get(`/sessions/${e}/suggestions`);return O(n.suggestions)}async sendCustomMessage(e,n){let o=await this.client.post(`/sessions/${e}/messages`,K(n));return O(o)}async answerCustomMessage(e,n){await this.client.post(`/sessions/${e}/answers`,K(n))}async getAutoflows(e){let n=await this.client.get(`/sessions/${e}/autoflows`);return O(n.autoflows)}async startAutoflowSession(e){let n=await this.client.post("/autoflow-sessions",K(e));return O(n)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new co(`${this.apiUrl}/sessions/${e}/events`),this.streams[e].connect()),this.streams[e]}closeStream(e){this.streams[e]||(this.streams[e].disconnect(),delete this.streams[e])}};var Ys=require("@reduxjs/toolkit");var _p=require("@reduxjs/toolkit");var Ep={startTime:null,stopTime:null},Pp=(0,_p.createSlice)({name:"handlingTime",initialState:Ep,reducers:{handlingTimeStart(t){if(t.startTime&&!t.stopTime)throw new Error("Timing already started");t.startTime=new Date,t.stopTime=null},handlingTimeStop(t){if(!t.startTime)throw new Error("Timing not started");t.stopTime=new Date},handlingTimeReset(t){t.startTime=null,t.stopTime=null}},extraReducers:t=>{t.addCase(A,()=>Ep)}}),{handlingTimeStart:kp,handlingTimeStop:Zs,handlingTimeReset:Rp}=Pp.actions,Ip=Pp.reducer;var Ap=(t={})=>{let e={onAuthError:us(!1),...t};return n=>o=>s=>("error"in s&&s.error.message==="Unauthorized"&&n.dispatch(e.onAuthError),o(s))};var Js=require("@reduxjs/toolkit");var Ni={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var Mt=(0,Js.createAsyncThunk)("styleSuggestions/getAll",async({text:t},e)=>{var i;let{deepdeskAPI:n}=e.extra,o=e.getState(),{showStyleSuggestions:s}=o.settings,r=(i=o.conversation.current)==null?void 0:i.profileCode;if(!s)return Ni.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:r,message:t})}),uf=(0,Js.createSlice)({name:"styleSuggestions",initialState:Ni,reducers:{},extraReducers:t=>{t.addCase(Mt.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(Mt.rejected,e=>{e.fetchState="error"}).addCase(Mt.fulfilled,(e,n)=>{e.fetchState="done",st(e.list,n.payload)||(e.list=n.payload)}).addCase(A,()=>Ni)}}),Lp=uf.reducer;var Mp=(t={})=>{let e,n=!0,o={getStyleSuggestions:Mt,debounce:500,...t};return s=>r=>i=>{var m;let a=s.getState().input.text,l=r(i),c=s.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:u}=c.settings;if(!((m=c.conversation.current)==null?void 0:m.id)||!u)return l;let{text:p}=c.input;return p===a&&!n||(clearTimeout(e),p==="")||(e=setTimeout(()=>{n=!1,s.dispatch(o.getStyleSuggestions({text:p}))},t.debounce)),l}};function pf(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var Op=(t={})=>{let e={getTextSuggestions:Fe,getAutocompleteSuggestions:Bn,debounce:200,check:xs,...t},n,o=!0;return s=>r=>i=>{var x;let{input:{userCommitted:a}}=s.getState(),l=r(i),c=s.getState();if(c.auth.isLoggedIn!==!0)return l;let{recommendTextSuggestions:u,showTabCompletion:d}=c.settings,p=(x=c.conversation.current)==null?void 0:x.id,m=i.type===cs.toString();if(!p||!u&&!d)return l;let{input:{userCommitted:g}}=c;return pf(g,a)&&!o&&!m||(clearTimeout(n),!e.check(c))||(n=setTimeout(()=>{o=!1;let b=Ht(c);b===""?s.dispatch(e.getTextSuggestions("default")):s.dispatch(e.getAutocompleteSuggestions(b))},m?0:e.debounce)),l}};var Np=Mt.fulfilled.toString();function df(t,e){let n=new Set([...e.keywordMatches.map(s=>s.keyword)]),o=[];return n.forEach(s=>{let r=t.keywordMatches.filter(l=>l.keyword===s),i=e.keywordMatches.filter(l=>l.keyword===s),a=i.length-r.length;a<=0||o.push(...i.slice(0,a))}),o}var Dp=t=>e=>n=>o=>{var u;if(o.type!==Np){n(o);return}let s=e.getState().styleSuggestions.list;n(o);let r=e.getState(),i=r.styleSuggestions.list,a=(u=r.conversation)==null?void 0:u.current,{agentInfo:l}=r.info;if(s===i)return;let c=df(s,i);o.type===Np&&c.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,agentId:l.agentId??(a==null?void 0:a.agentId),agentName:l.agentName??(a==null?void 0:a.agentName),agentEmail:l.agentEmail??(a==null?void 0:a.agentEmail),data:{keywordMatches:c}})};var mf=(0,Ys.combineReducers)({activeSuggestion:kl,answer:yc,auth:Vl,autoflows:Pu,conversation:Xi,contentTypes:tc,customMessages:Du,exchangeToken:Ku,entities:rc,handlingTime:Ip,info:el,input:lr.reducer,overlayInput:Q.reducer,settings:zi,profile:xc,search:il,summary:pc,styleSuggestions:Lp,ui:Ol,textSuggestions:Tl});function Hp(t){return(0,Ys.configureStore)({reducer:mf,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),Ap(),Op({debounce:200}),Mp({debounce:500}),Dp(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var gf=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},ff=t=>e=>n=>o=>{var a;let s=e.getState(),r=sr("inlineSuggestions")(s);switch(o.type){case Be.toString():{let l=hl(o.payload.contentType)(e.getState()),c=l.indexOf(o.payload.suggestion);t.emit("edit-suggestion",{contentType:o.payload.contentType,index:c,suggestions:l});break}case Ce.toString():{let{start:l,end:c}=s.input.selection;t.emit("select-suggestion",{type:gf(o.payload.suggestion),...o.payload,replace:o.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case _o.toString():{let{start:l,end:c}=s.input.selection;t.emit("replace",{...o.payload,replace:o.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case Cn.toString():{let l=e.getState(),{text:c,selection:u}=l.input.userCommitted;t.emit("reset",{text:c,selectionAfter:u},{mayApplyChanges:!0});break}case Io.toString():t.emit("select-image",o.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:s.conversation.current.id,data:{path:o.payload.suggestion.image,title:o.payload.suggestion.title}});break;case Ee.fulfilled.toString():o.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:o.payload}});break;case qe.fulfilled.toString():t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{inputText:JSON.stringify(o.payload.original),summary:o.payload.summary}});break;case Re.toString():t.sendEvent(o.payload.name,{conversationId:((a=o.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:o.payload.data});break;case Po.toString():t.handleKeyDown(o.payload);break;case xn.toString():t.logSendMessage(o.payload);break;case ko.toString():t.logSendEditSuggestionMessage(o.payload);break;case Ro.toString():t.handleInputChanged(o.payload);break;default:break}let i=n(o);switch(o.type){case xn.toString():t.handleAfterSendMessage(o.payload);break;case Kn.toString():t.onUpdateShowTabHint(o.payload);break;case Zs.toString():t.logHandlingTime();break;case Ce.toString():{r&&(e.dispatch(it([])),e.dispatch(at()));break}default:break}return i},Fp=ff;function Di(t){return t.toISOString().replace("T"," ").replace("Z","")}function Bp(t,e){var s,r,i;let{startTime:n,stopTime:o}=t.handlingTime;if(!n||!o)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:t.conversation.current.id,clientVersion:e.version,agentId:(s=t.info.agentInfo)==null?void 0:s.agentId,agentName:(r=t.info.agentInfo)==null?void 0:r.agentName,agentEmail:(i=t.info.agentInfo)==null?void 0:i.agentEmail,timeStart:Di(n),timeStop:Di(o)}}function Hi(t,e,n){var k,w,H;let{text:o,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:c,pastes:u,cuts:d,deletions:p,textSuggestions:m,offeredTextSuggestions:g}}=e[t],f=o.length,b=m.reduce((te,{text:R,searchTerm:ne})=>te+R.length-(ne?ne.length:0),0),h=c??Date.now(),v=(Date.now()-h)/1e3,C=s/v;return{conversationId:e.conversation.current.id,source:"agent",text:o,clientVersion:n.version,pastes:u,cuts:d,deletions:p,lenTextTyped:s,lenTextTotal:f,lenTextAssisted:b,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:v,charsPerSecond:C,numPastes:l,textSuggestionsV2:m,suggestionsCounters:[{source:"gpt",countOffered:g.filter(te=>te.source==="gpt").length}],agentId:(k=e.info.agentInfo)==null?void 0:k.agentId,agentName:(w=e.info.agentInfo)==null?void 0:w.agentName,agentEmail:(H=e.info.agentInfo)==null?void 0:H.agentEmail}}function Kp(t,e){let n=t.closest(e);if(n)return n;let o=t.getRootNode().host;return o instanceof HTMLElement?Kp(o,e):null}function Up(t,e){return Kp(t,e)}function qp(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function er(t){return t instanceof HTMLElement&&(Ge(t)||Xo(t))}var Vp=(t,e)=>({value(){try{let n=sessionStorage.getItem(`dd-${t}`);if(!n)return e;try{return JSON.parse(n)}catch{return e}}catch{return e}},update(n){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(n))}catch{P.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function hf(t){return t.offsetParent!==null}function jp(t){if(!hf(t))return!1;let e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}function tr(t,e,n=100){let o=jp(t);e({isVisible:o});let s=setInterval(()=>{let r=jp(t);r!==o&&(o=r,e({isVisible:o}))},n);return()=>{clearTimeout(s)}}var le=require("react/jsx-runtime"),zp=Vp("showTabHint",!0),po=class t{static version="10.1.1";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:n,version:o=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a}){let l=e.replace(/\/api$/,"");this.deepdeskApi=new Ye(l,{token:r,fetch:i}),this.version=o,this.instanceId=t.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Fp({emit:(u,d,p)=>this.emit(u,d,p),handleAfterSendMessage:u=>this.handleAfterSendMessage(u),handleInputChanged:u=>this.handleInputChanged(u),handleKeyDown:u=>this.handleKeyDown(u),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:u=>this.logSendMessage(u),logSendEditSuggestionMessage:u=>this.logSendEditMessage(u),onUpdateShowTabHint:u=>zp.update(u),sendEvent:(u,d)=>this.deepdeskApi.sendEvent(u,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new uo(n)}),this.store=Hp(c),this.broadcastEvents=new bp({debug:!0,deepdeskUrl:l,eventMap:jl(this.store)}),this.store.dispatch(vn),this.store.dispatch(Kn(zp.value())),this.store.dispatch(vn({locale:s,adminUrl:l,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?(P.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(P.warn("Profile has not been loaded (yet)"),!0):(P.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(us(null)),this.store.dispatch(bt()),new Promise(e=>{let n=this.store.subscribe(()=>{let o=this.store.getState();Ke(o)&&Hl(o)!=="loading"&&e()});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return this.deepdeskApi.isLoggedIn()}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(n){P.warn("Failed to attach user:",n)}}async isConversationSupported(e,n){return(await this.store.dispatch(ir({sessionId:e,options:n}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(xo(e))).payload}async getConversationBySessionId(e,n){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Co({sessionId:e,options:n}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(ar(e))).payload}async postMessages(e){return(await this.store.dispatch(wo(e))).payload}async updateConversation(e){return(await this.store.dispatch(To(e))).payload}resetConversation(){this.store.dispatch(A()),this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(qe());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(vn(e))}setVisitorInfo(e){this.store.dispatch(Ya(e))}async setAgentInfo(e){await this.store.dispatch(Nn(e))}async setAgentSettings(e){await this.store.dispatch(Dr(e))}async getAgentSettings(){return(await this.store.dispatch(Hr())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();let e=[];return this.store.dispatch(cs()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Ro(e))}syncInputHtml(e){this.store.dispatch(ua(e))}notifyKeyDown(e){this.store.dispatch(Po(e))}notifyPaste(e,n){this.store.dispatch(la({text:e,selectionText:n}))}notifyCut(e){this.store.dispatch(ia(e))}notifyExternalSuggestion(e){this.store.dispatch(Ce(e)),this.store.dispatch(at())}notifyEditSuggestion(e){this.store.dispatch(xl(e.contentType,e.suggestions)),this.store.dispatch(Be({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}handleInputChanged(e){let{overlayCollapsed:n,openOverlayWhenTyping:o}=this.state.ui;n&&o&&this.store.dispatch(en({collapse:!1})),this.inputMediator&&this.store.dispatch(ea({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(it([])))}handleKeyDown(e){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=o.length>0,l=s!==-1;if(this.store.dispatch(aa(Eo(e))),!(e.key!=="Tab"&&!this.settings.showTextSuggestions))switch(e.key){case"Up":case"ArrowUp":if(n||!a||!r||e.shiftKey)return;this.store.dispatch(oa()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault();return;case"Down":case"ArrowDown":{if(n||!a||!r||e.shiftKey)return;this.store.dispatch(ra());let{selectedSuggestionIndex:c}=this.state.input;c===-1?this.store.dispatch(Cn()):i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault();return}case"Esc":case"Escape":{l?(this.store.dispatch(Ao(-1)),this.store.dispatch(Cn()),e.preventDefault()):n||(this.store.dispatch(en({collapse:!0})),this.store.dispatch(Ll(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:c}=this.state.input,u=c.text.substring(0,c.selection.end),{tabCompletionSuggestion:d}=this.state.input;this.store.dispatch(Kn(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):this.settings.showTabCompletion&&d&&d.text.startsWith(u)&&(this.store.dispatch(Ce({text:d.text,suggestion:d,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(at())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(ca()),this.store.dispatch(it([]))}handlingTimeStart(){this.state.handlingTime.startTime||(P.info("Start handling time"),this.store.dispatch(kp()))}handlingTimeStop(){this.state.handlingTime.startTime&&(P.info("Stop handling time"),this.store.dispatch(Zs()))}logSendMessage(e){let n=Hi("input",this.state,{version:this.version});e&&Object.assign(n,{text:e}),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logSendEditMessage(e){let n=Hi("overlayInput",this.state,{version:"v2"});e&&Object.assign(n,{text:e}),this.store.dispatch(na(this.state.overlayInput.metrics)),this.deepdeskApi.sendEvent("suggestion edited",{data:n})}logHandlingTime(){let e=Bp(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Rp())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(at()),this.store.dispatch(xn(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:o}=this.state.input;this.store.dispatch(Ce({text:o[n].text,suggestion:o[n],eventMetrics:e,replace:"until-selection-end"}))}emit(e,n,o={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(n)}catch(i){P.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),P.error(i)}})};this.inputMediator&&o.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,n){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n),()=>{this.off(e,n)}}off(e,n){if(!e&&!n){this.eventListeners={};return}let o;this.eventListeners[e]&&(o=this.eventListeners[e].indexOf(n),o>-1&&this.eventListeners[e].splice(o,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let n=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&n();let o=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==o&&(o=this.hasConversation(),o&&n())})}overlayContainerFactory(e,n,o,s){let[r,i]=Gt(o,s);return r.dataset.testid=e,n!=null&&n.rootNode&&r.classList.add(n.rootNode),this.unmountHandlers.push(()=>{(0,et.unmountComponentAtNode)(r),i(),r.remove()}),r}createContainer(e,n=document.body){let o=window.getComputedStyle(n),s=document.createElement("div");return xt(s),s.dataset.testid=e,s.style.color=o.color,s.style.fontSize=o.fontSize,s.style.fontFamily=o.fontFamily,s.style.fontVariant=o.fontVariant,n.appendChild(s),this.unmountHandlers.push(()=>{(0,et.unmountComponentAtNode)(s),s.remove()}),s}mount(e,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!er(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:o={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:u,isEmbedded:d,detectSubmit:p,insertLink:m,inputMediator:g,closestScrollSelector:f,appendOverlayTo:x,inlineSuggestions:b}=n;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:u,showTextSuggestions:i,insertLink:m,isEmbedded:d,inlineSuggestions:b});let h=f&&Up(e,f)||void 0,v=this.overlayContainerFactory("deepdesk-tab-completion",o,e,{appendTo:x,closestScrollElement:h,mirrorOverflow:!0,onRemove:()=>this.unmount()}),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",o,h||e,{appendTo:x});n.automaticHandlingTime&&this.setupHandlingTime(e),(0,et.render)((0,le.jsx)(eo,{store:this.store,customStyles:o,children:(0,le.jsx)(qn,{broadcastEvents:this.broadcastEvents,children:(0,le.jsx)(Cu,{inputElement:e})})}),v),(0,et.render)((0,le.jsx)(eo,{store:this.store,customStyles:o,children:(0,le.jsx)(qn,{broadcastEvents:this.broadcastEvents,children:(0,le.jsx)(Es,{})})}),C),(0,et.render)((0,le.jsx)(eo,{store:this.store,customStyles:o,children:(0,le.jsx)(qn,{broadcastEvents:this.broadcastEvents,children:(0,le.jsx)(Ec,{})})}),this.createContainer("deepdesk-overlays")),xt(e),this.inputMediator=g||(Ge(e)?new De(e):new Lt(e)),this.inputMediator.on("change",({plainText:w})=>{this.notifyInputChanged(w)}),this.inputMediator.on("updated",({rawHtml:w})=>{w!=null&&this.syncInputHtml(w)}),this.inputMediator.on("keydown",w=>{this.notifyKeyDown(w)}),this.inputMediator.on("paste",({pastedText:w,selectionText:H})=>{this.notifyPaste(w,H)}),this.inputMediator.on("cut",({selectionText:w})=>{this.notifyCut(w)});let k;this.inputMediator.on("selection",w=>{clearTimeout(k),w===null?k=setTimeout(()=>{w!==null&&this.store.dispatch(cr(w))},500):this.store.dispatch(cr(w))}),this.inputMediator.on("disabled",()=>{var w;(w=this.inputMediator)==null||w.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{p&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Yt(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Yt(!0))),this.store.dispatch(ta({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.whenConversationLoaded(()=>{var w;this.broadcastEvents.setSessionId((w=this.state.conversation.current)==null?void 0:w.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,n={}){if(this.widgetRoot&&P.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:o,showImages:s,showPersonalCollectionLink:r,isEmbedded:i}=n;this.widgetRoot=e,this.configure({showImages:s,showPersonalCollectionLink:r,isEmbedded:i}),(0,et.render)((0,le.jsx)(eo,{store:this.store,customStyles:o,children:(0,le.jsx)(qn,{broadcastEvents:this.broadcastEvents,children:(0,le.jsx)(Tp,{})})}),e),this.whenConversationLoaded(()=>{var a;this.broadcastEvents.setSessionId((a=this.state.conversation.current)==null?void 0:a.sessionId)})}unmountWidget(){this.widgetRoot&&(0,et.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let n=tr(e,({isVisible:o})=>{o?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){qp(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Jn());let e=an(this.state);e&&this.store.dispatch(vn({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:e.knowledgeSearch,recommendTextSuggestions:e.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async checkForTrialMode(e){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(P.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:o}=n;P.info(o),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let n=vs(this.state);try{n.forEach(({type:o})=>{o==="entities"?this.store.dispatch(Ee()):this.store.dispatch(Fe(o))})}catch(o){this.handleError(o)}}};async function Wp(t,e,n={}){let{value:o}=t,{start:s,end:r}=n.replace??{start:0,end:o.length},i=`${o.slice(0,s)}${e}${o.slice(r)}`,a=n.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(n.setValue)return n.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function Gp(t,e,n={}){let o=n.replace?At(t,n.replace.start,n.replace.end):wp(t),s,r=()=>{if(n.setRange)return n.setRange(o.cloneRange());o.deleteContents(),s=document.createElement("span"),o.insertNode(s),e.split(`
|
|
6
6
|
`).reverse().forEach((i,a)=>{a>0&&o.insertNode(document.createElement("br")),o.insertNode(document.createTextNode(i))}),o.commonAncestorContainer===t&&o.surroundContents(document.createElement("div"))};return Promise.resolve(r()).then(()=>{try{if(n.selectionAfter!==!1){t.focus();let i=n.selectionAfter?At(t,n.selectionAfter.start,n.selectionAfter.end):(o.collapse(!1),o),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(i)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}function $p(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function Xp(t,e,n){await new Ye(t).authenticateWithKey(e,n)}async function Qp(t){let n=await new Je(t).get("/platform/config/",{version:null});return O(n)}async function yf(t){let n=await(t.fetch??window.fetch)(t.url),o=await n.blob();return new File([o],t.name,{type:t.mimeType??n.headers.get("Content-Type")??"image/jpeg"})}async function Zp(t,e){let n=await yf(e),o=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[n]}),t.dispatchEvent(o)}finally{Object.hasOwn(t,"files")&&delete t.files}}0&&(module.exports={Card,Chip,ContentEditableInput,DeepdeskAPI,DeepdeskSDK,InputMediator,InputType,KeyboardHint,Label,Locale,Section,SectionList,Sources,Suggestion,SuggestionList,TextAreaInput,ToggleButton,attachFile,authenticateWithKey,createOverlayContainer,createRangeFromOffsets,escapeHTML,fetchPlatformConfig,formatTextMarkup,getRangeOffsets,getRangeText,isSupportedInputElement,updateContentEditable,updateTextArea,useStyles,waitForElementVisibilityChange});
|