@deepdesk/deepdesk-sdk 10.4.1-beta.2 → 10.5.0

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.
@@ -18,7 +18,7 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
18
18
 
19
19
  `),o=o.replace(/\n/g,"<br/>"),o}createContainer(t){var n;let o=(typeof global<"u"&&global.INTERWEAVE_SSR_POLYFILL||iR)();if(!o)return;let i=(n=this.props.containerTagName)!==null&&n!==void 0?n:"body",s=i==="body"||i==="fragment"?o.body:o.createElement(i);return t.match(nR)||(s.innerHTML=this.convertLineBreaks(this.props.escapeHtml?(0,m_.default)(t):t)),s}extractAttributes(t){let{allowAttributes:n}=this.props,r={},o=0;return t.nodeType!==f_||!t.attributes||([...t.attributes].forEach(i=>{let{name:s,value:a}=i,l=s.toLowerCase(),u=Ac[l]||Ac[s];if(!this.isSafe(t)||!l.match(rR)&&(!n&&(!u||u===ag)||l.startsWith("on")||a.replace(/(\s|\0|&#x0([9AD]);)/,"").match(/(javascript|vbscript|livescript|xss):/i)))return;let c=l==="style"?this.extractStyleAttribute(t):a;u===vr?c=!0:u===eo?c=Number.parseFloat(String(c)):u!==Ic&&(c=String(c)),r[lg[l]||l]=this.applyAttributeFilters(l,c),o+=1}),o===0)?null:r}extractStyleAttribute(t){let n={};return Array.from(t.style).forEach(r=>{let o=t.style[r];(typeof o=="string"||typeof o=="number")&&(n[r.replace(/-([a-z])/g,(i,s)=>String(s).toUpperCase())]=o)}),n}getTagConfig(t){let n={children:[],content:0,invalid:[],parent:[],self:!0,tagName:"",type:0,void:!1};return fa[t]?{...n,...fa[t],tagName:t}:n}isSafe(t){if(typeof HTMLAnchorElement<"u"&&t instanceof HTMLAnchorElement){let n=t.getAttribute("href");if(n!=null&&n.startsWith("#"))return!0;let r=t.protocol.toLowerCase();return r===":"||r==="http:"||r==="https:"||r==="mailto:"||r==="tel:"}return!0}isTagAllowed(t){return this.banned.has(t)||this.blocked.has(t)?!1:this.props.allowElements||this.allowed.has(t)}parse(){return this.container?this.parseNode(this.container,this.getTagConfig(this.container.nodeName.toLowerCase())):[]}parseNode(t,n){let{noHtml:r,noHtmlExceptMatchers:o,allowElements:i,transform:s,transformOnlyAllowList:a}=this.props,l=[],u="";return[...t.childNodes].forEach(c=>{if(c.nodeType===f_){let d=c.nodeName.toLowerCase(),h=this.getTagConfig(d);u&&(l.push(u),u="");let v=this.applyNodeFilters(d,c);if(!v)return;let y;if(s&&!(a&&!this.isTagAllowed(d))){this.keyIndex+=1;let m=this.keyIndex;y=this.parseNode(v,h);let g=s(v,y,h);if(g===null)return;if(typeof g<"u"){l.push(no.default.cloneElement(g,{key:m}));return}this.keyIndex=m-1}if(this.banned.has(d))return;if(!(r||o&&d!=="br")&&this.isTagAllowed(d)&&(i||this.canRenderChild(n,h))){var p;this.keyIndex+=1;let m=this.extractAttributes(v),g={tagName:d};m&&(g.attributes=m),h.void&&(g.selfClose=h.void),l.push(no.default.createElement(Lc,{...g,key:this.keyIndex},(p=y)!==null&&p!==void 0?p:this.parseNode(v,h)))}else l=[...l,...this.parseNode(v,h.tagName?h:n)]}else if(c.nodeType===tR){let d=r&&!o?c.textContent:this.applyMatchers(c.textContent||"",n);Array.isArray(d)?l=[...l,...d]:u+=d}}),u&&l.push(u),l}replaceTokens(t,n){if(!t.includes("{{{"))return t;let r=[],o=t,i=null;for(;i=o.match(oR);){let[s,a]=i,l=i.index,u=s.includes("/");l>0&&(r.push(o.slice(0,l)),o=o.slice(l));let{children:c,matcher:p,props:d}=n[a],h;if(u)h=s.length,r.push(p.createElement(c,d));else{let v=o.match(new RegExp(`{{{/${a}}}}`));h=v.index+v[0].length,r.push(p.createElement(this.replaceTokens(o.slice(s.length,v.index),n),d))}o=o.slice(h)}return o.length>0&&r.push(o),r.length===0?"":r.length===1&&typeof r[0]=="string"?r[0]:r}};function sR(e){var t;let{attributes:n,className:r,containerTagName:o,content:i,emptyContent:s,parsedContent:a,tagName:l,noWrap:u}=e,c=(t=o??l)!==null&&t!==void 0?t:"span",p=c==="fragment"?!0:u,d;if(a)d=a;else{let h=new Oc(i??"",e).parse();h.length>0&&(d=h)}return d||(d=s),p?no.default.createElement(no.default.Fragment,null,d):no.default.createElement(Lc,{attributes:n,className:r,tagName:c},d)}function gi(e){let{attributes:t,className:n,content:r="",disableFilters:o=!1,disableMatchers:i=!1,emptyContent:s=null,filters:a=[],matchers:l=[],onAfterParse:u=null,onBeforeParse:c=null,tagName:p="span",noWrap:d=!1,...h}=e,v=i?[]:l,y=o?[]:a,m=c?[c]:[],g=u?[u]:[];v.forEach(b=>{b.onBeforeParse&&m.push(b.onBeforeParse.bind(b)),b.onAfterParse&&g.push(b.onAfterParse.bind(b))});let f=m.reduce((b,E)=>E(b,e),r??""),S=new Oc(f,h,v,y),_=g.reduce((b,E)=>E(b,e),S.parse());return no.default.createElement(sR,{attributes:t,className:n,containerTagName:e.containerTagName,emptyContent:s,noWrap:d,parsedContent:_.length===0?void 0:_,tagName:p})}var Sg=x($());var cg={root:"_root_kxnai_1",agentText:"_agentText_kxnai_3",textInput:"_textInput_kxnai_8",textInputWrapper:"_textInputWrapper_kxnai_27",alert:"_alert_kxnai_31",alertText:"_alertText_kxnai_50",warning:"_warning_kxnai_60",success:"_success_kxnai_69"};var h_=x($());var hi=x(O());function g_(e,t){let n;return[(...r)=>{window.cancelAnimationFrame(n);let o=t?t(...r):r;n=window.requestAnimationFrame(()=>{e(...o)})},()=>window.cancelAnimationFrame(n)]}function Nc(e){let t=(0,hi.useRef)(null),[n,r]=(0,hi.useState)(!1);return(0,hi.useEffect)(()=>{let o=!1,i=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[s,a]=g_((c,p)=>{let d=t.current;if(!d)return;let h=c/i,v=p/i,y=d.getBoundingClientRect(),m=h>y.x&&h<y.x+y.width&&v>y.y&&v<y.y+y.height;m&&!o?(o=!0,r(!0)):!m&&o&&(o=!1,r(!1))},({clientX:c,clientY:p})=>[c,p]),[l,u]=g_(()=>{o=!1,r(!1)});return e.addEventListener("mousemove",s),e.addEventListener("mouseleave",l),()=>{a(),u(),e.removeEventListener("mousemove",s),e.removeEventListener("mouseleave",l)}},[t]),[t,n]}var En={root:"_root_81non_1",container:"_container_81non_3",agentText:"_agentText_81non_5",tabText:"_tabText_81non_6",hint:"_hint_81non_6",matchSelection:"_matchSelection_81non_10",focus:"_focus_81non_16",resetIndent:"_resetIndent_81non_20",matchKeyword:"_matchKeyword_81non_24",matchPlaceholder:"_matchPlaceholder_81non_25",hover:"_hover_81non_31",hintText:"_hintText_81non_64",popover:"_popover_81non_72",popoverRoot:"_popoverRoot_81non_77",popoverContentContainer:"_popoverContentContainer_81non_81",popoverContent:"_popoverContent_81non_81",selectionOptions:"_selectionOptions_81non_107",selectionOptionsIsHidden:"_selectionOptionsIsHidden_81non_112",selectionOptionsButton:"_selectionOptionsButton_81non_116",caret:"_caret_81non_132",popoverSuggestionsRoot:"_popoverSuggestionsRoot_81non_136",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_81non_141"};var dg=x(w()),aR=({inputElement:e,children:t})=>{let n=k("TabCompletion",En),[r,o]=Nc(e);return(0,dg.jsx)("mark",{ref:r,className:(0,h_.default)(n.matchPlaceholder,{[n.hover]:o}),children:t})},yi=class extends wn{match(t){let n=t.match(/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\}(?!\}))/);return n?{index:n.index,length:n[0].length,match:n[0],matchString:n[0],valid:!0}:null}replaceWith(t,n){return(0,dg.jsx)(aR,{inputElement:n.inputElement,children:t},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var vi=x(O());function Mc(e){return e.contentEditable==="true"}function lR(e){let t=0,n=0,r=window.getSelection();if(r.rangeCount!==0){let o=r.getRangeAt(0),i=o.cloneRange();i.selectNodeContents(e),i.setEnd(o.endContainer,o.endOffset),n=i.toString().length,i.selectNodeContents(e),i.setEnd(o.startContainer,o.startOffset),t=i.toString().length}return{selectionStart:t,selectionEnd:n}}function y_(e){let{selectionStart:t,selectionEnd:n}=Mc(e)?lR(e):e;return[t,n]}function Dc(e){let[,t]=(0,vi.useState)(),n=(0,vi.useRef)(null);return n.current=y_(e),(0,vi.useEffect)(()=>{let r=()=>{let[o,i]=n.current??[],s=y_(e);(!s||o!==s[0]||i!==s[1])&&(n.current=s,t({}))};return e.addEventListener("keyup",r),e.addEventListener("click",r),e.addEventListener("focus",r),document.addEventListener("selectionchange",r),()=>{e.removeEventListener("keyup",r),e.removeEventListener("click",r),e.removeEventListener("focus",r),document.removeEventListener("selectionchange",r)}},[e]),n.current}function Fc(e,t){if(!t)return;let n=e,{value:r}=n,[o,i]=t,s=r.match(bo);if(!s||s.length===0)return;let a=0;s.find(l=>{let u=r.indexOf(l,a);return o>u&&i<u+l.length?(n.selectionStart=u,n.selectionEnd=u+l.length,!0):(a=u+l.length,!1)})}var v_=x(O());function Si(e){(0,v_.useEffect)(()=>{let t=n=>{n.isWithinRoot||e(n)};return document.body.addEventListener("mouseup",t),()=>{document.body.removeEventListener("mouseup",t)}},[e])}function ro(e){e.addEventListener("mouseup",t=>{t.isWithinRoot=!0},!0)}var S_,sn=new Map,uR=["bottom","height","left","right","top","width"],cR=(e={},t={})=>uR.some(n=>e[n]!==t[n]);function x_(e){var n,r;let t=((r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)??null;return t?[t,...x_(t)]:[]}function __(e,t){return!e||!t?null:{...e,top:e.top+t.top,left:e.left+t.left}}var pg=!1,w_=()=>{pg=!0;let e=[];sn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),sn.delete(n);return}let r=n.getBoundingClientRect();cR(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(__,t.rect):t.rect;t.callbacks.forEach(r=>r(n))}),sn.size!==0&&(S_=window.requestAnimationFrame(w_))};function fg(e,t){let n=x_(e),r=[],o=n.map((i,s)=>fg(i,a=>{r[s]=a;let l=sn.get(e);if(!l)return;let u=r.reduce(__,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),sn.has(e)){let s=sn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else sn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!pg&&w_()},unobserve(){o.forEach(s=>s.unobserve());let i=sn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||sn.delete(e),sn.size||(cancelAnimationFrame(S_),pg=!1)}}}}var b_,an=new Map,E_=()=>{an.forEach((e,t)=>{if(!t.isConnected){an.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),an.size!==0&&(b_=window.requestAnimationFrame(E_))};function C_(e,t){return{observe(){let n=an.size===0;an.has(e)?an.get(e).callbacks.push(t):an.set(e,{visible:void 0,callbacks:[t]}),n&&E_()},unobserve(){let n=an.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||an.delete(e),an.size||cancelAnimationFrame(b_)}}}}var mg=["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 gg(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function xi(e){return parseFloat(e)}function jc(e){return Math.round(e*1e6)}function T_(e){return e/1e6}function hg(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=xi(e.width),i=xi(e.borderLeftWidth),s=xi(e.borderRightWidth),a=xi(e.paddingRight),l=T_(jc(o)-jc(i)-jc(s)),u=T_(jc(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function oo(e,t={}){var l;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=t.position??"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",ro(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};gg(r,n,mg),hg(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=C_(e,()=>{gg(r,n,mg),hg(r,e,n),i(),setTimeout(i,0)}),a=fg(e,u=>{if(u===null){t.onRemove&&t.onRemove(),n.remove();return}if(u.height===0&&u.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(gg(r,n,mg),hg(r,e,n),i(),n.style.top=`${u.top}px`,n.style.left=`${u.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let c=t.closestScrollElement.getBoundingClientRect(),p=window.getComputedStyle(t.closestScrollElement),d=xi(p.borderTopWidth),h=xi(p.borderBottomWidth),v=c.top+d-u.top,y=u.top+u.height+-(c.top+c.height-h);n.style.clipPath=`inset(${v}px 0px ${y}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(l=e.parentElement)==null||l.appendChild(n),a.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),a.unobserve(),s.unobserve()}]}var yg={};Ie(yg,{enUS:()=>dR,nlNL:()=>pR});var dR={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"}]},pR={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 ma=x(w()),k_=()=>(0,ma.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 512 512","aria-labelledby":"circleCheckTitle",children:[(0,ma.jsx)("title",{id:"circleCheckTitle",children:"Check"}),(0,ma.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 vg=x(w()),P_=()=>(0,vg.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",fill:"currentColor",children:(0,vg.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"})});function fR(e){let t=e.scrollHeight>e.clientHeight,r=window.getComputedStyle(e).overflowY.indexOf("hidden")!==-1;return t&&!r}function Bc(e){return e?e instanceof ShadowRoot?Bc(e.host):e===e.ownerDocument.body?e.ownerDocument:fR(e)?e:Bc(e.parentNode):document.body}var R_=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(R_||{}),Cn=class{constructor(t){this.element=t;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}triggerChange(){let t=this.getText(),n=this.getHTML(),r=t!==this.currentText;this.isActive&&(t===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&r&&!this.isSubmitting&&this.emit("change",{plainText:t}),r&&(this.currentSelection=this.getSelection()),this.currentText=t,this.isSubmitting=!1,(this.currentHTML!==n||n===null&&r)&&(this.emit("updated",{plainText:t}),this.triggerCaretPosition(),this.currentHTML=n))}triggerSelection(){let t=this.getSelection();(t.start!==this.currentSelection.start||t.end!==this.currentSelection.end)&&(this.currentSelection=t,this.emit("selection",t),this.triggerCaretPosition())}triggerCaretPosition(){let t=this.getCaretPosition();mr(t,this.currentCaret)||(this.currentCaret=t,this.emit("caret",t))}handleKeyUp(t){let{key:n,shiftKey:r}=t;(n==="Enter"&&r===!0||n==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(R_).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",r=>this.handleKeyDown(r)),this.addEventListener("keyup",r=>this.handleKeyUp(r)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",r=>this.handlePaste(r)),this.addEventListener("click",()=>this.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()});let n=Bc(this.element);if(n){let r=()=>{this.currentCaret!==null&&(this.currentCaret=null,this.emit("caret",null))};n.addEventListener("scroll",r),this.disposeHandlers.push(()=>{n.removeEventListener("scroll",r)})}this.currentSelection=this.getSelection()}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};var Tn=class extends Cn{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:t,selectionEnd:n}=this.element;return{start:t,end:n}}getSelectedText(){let t=this.getSelection();return t?this.getText().slice(t.start,t.end):""}getCaretPosition(){return null}applyChanges(t){if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let t=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var o;return(o=t==null?void 0:t.get)==null?void 0:o.call(this.element)},set:o=>{var i;(i=t==null?void 0:t.set)==null||i.call(this.element,o),this.triggerChange()}});let n=this.element.disabled,r=new MutationObserver(()=>{this.element.disabled!==n&&(n=this.element.disabled,this.emit(n?"disabled":"enabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>r.disconnect())}};var et=x(w()),mR=({value:e,onUse:t,...n})=>{var c;let r=B(yg),o=U(),i=k("EditSuggestionTextInput",cg),[s,a]=(0,kt.useState)(null),l=(0,kt.useRef)(null),u=((c=e.match(bo))==null?void 0:c.length)||0;return(0,kt.useEffect)(()=>{let p;return l.current&&(a(l.current),p=new Tn(l.current),p.on("change",({plainText:d})=>{o(Je.actions.userInput({text:d,selection:p.getSelection()}))}),p.on("keydown",d=>{o(Je.actions.registerKeyDown(sc(d))),d.code==="Enter"&&d.shiftKey&&t(p.getText())}),p.on("paste",({pastedText:d,selectionText:h})=>{o(Je.actions.registerPaste({text:d,selectionText:h}))}),p.on("cut",({selectionText:d})=>{o(Je.actions.registerCut(d))})),()=>{o(Je.actions.reset()),p.dispose(),p.deactivate()}},[l]),(0,kt.useEffect)(()=>{e&&l.current&&(l.current.value=e)},[e,l]),(0,kt.useEffect)(()=>{l.current&&setTimeout(()=>{if(!l.current)return;let p=l.current.value.length;l.current.setSelectionRange(p,p),l.current.focus()},0)},[l]),(0,et.jsxs)("div",{className:i.textInputWrapper,children:[(0,et.jsx)("textarea",{...n,ref:l,"data-testid":"edit-suggestion-dialog-textarea",className:i.textInput,defaultValue:e,onChange:()=>{}}),s&&(0,et.jsx)(gR,{inputElement:l.current,value:e}),(0,et.jsxs)("div",{className:(0,Sg.default)(i.alert,u===0?i.success:i.warning),children:[(0,et.jsx)("div",{className:i.alertText,children:r("placeholders",{placeholderSize:u})}),u===0?(0,et.jsx)(k_,{}):(0,et.jsx)(P_,{})]})]})},gR=({inputElement:e,value:t})=>{let n=k("EditSuggestionTextInput",cg),r=(0,kt.useRef)(null),o=Dc(e);return(0,kt.useEffect)(()=>{Fc(e,o)},[o,e]),(0,et.jsx)(hR,{inputElement:e,children:(0,et.jsxs)("div",{ref:r,className:(0,Sg.default)(n.root,n.agentText),children:[(0,et.jsx)(gi,{tagName:"span",disableLineBreaks:!0,content:t,matchers:[new yi("placeholders")],inputElement:e,boundaryRef:r}),(0,et.jsx)("br",{})]})})},hR=({inputElement:e,children:t})=>{let n=(0,kt.useRef)(null);return(0,kt.useEffect)(()=>{if(!n.current)return()=>{};let[r,o]=oo(e,{overlayContainer:n.current,mirrorOverflow:!0});return r.setAttribute("translate","no"),()=>{o()}},[n.current]),(0,et.jsx)("div",{ref:n,children:t})},I_=mR;var bi=x(O());var A_=x(O()),Hc=x($());var tt={root:"_root_pc5uy_1",list:"_list_pc5uy_2",listWrapper:"_listWrapper_pc5uy_6",listHorizontal:"_listHorizontal_pc5uy_10",page:"_page_pc5uy_19",search:"_search_pc5uy_25",pageNav:"_pageNav_pc5uy_33",pageTitle:"_pageTitle_pc5uy_41",pageBackButton:"_pageBackButton_pc5uy_48",listHeading:"_listHeading_pc5uy_62",listItem:"_listItem_pc5uy_70",listItemContent:"_listItemContent_pc5uy_79",listItemText:"_listItemText_pc5uy_97",listItemDescription:"_listItemDescription_pc5uy_105",listItemActions:"_listItemActions_pc5uy_112",truncate:"_truncate_pc5uy_123",lineClamp:"_lineClamp_pc5uy_129",listItemTitle:"_listItemTitle_pc5uy_136",listItemAction:"_listItemAction_pc5uy_112",listItemPrimaryAction:"_listItemPrimaryAction_pc5uy_157",listItemSelected:"_listItemSelected_pc5uy_162",sources:"_sources_pc5uy_166",sourcesTitle:"_sourcesTitle_pc5uy_173",source:"_source_pc5uy_166",icon:"_icon_pc5uy_188",searchIcon:"_searchIcon_pc5uy_205",searchInputWrapper:"_searchInputWrapper_pc5uy_210",searchInput:"_searchInput_pc5uy_210",select:"_select_pc5uy_231",selectType:"_selectType_pc5uy_248",selectWrapper:"_selectWrapper_pc5uy_252",image:"_image_pc5uy_282",imageSrc:"_imageSrc_pc5uy_289",imageSrcHidden:"_imageSrcHidden_pc5uy_300",imageSrcStatus:"_imageSrcStatus_pc5uy_304",imageTitle:"_imageTitle_pc5uy_314",actions:"_actions_pc5uy_319",actionsWrapper:"_actionsWrapper_pc5uy_323",actionsBar:"_actionsBar_pc5uy_329",actionButton:"_actionButton_pc5uy_338",actionShortcut:"_actionShortcut_pc5uy_356",actionShortcutFixKerning:"_actionShortcutFixKerning_pc5uy_363"};var io={};Ie(io,{enUS:()=>yR,nlNL:()=>vR});var yR={visitUrl:[{type:0,value:"Visit"}],back:[{type:0,value:"Back"}],loading:[{type:0,value:"Loading..."}],imageError:[{type:0,value:"Could not load image"}]},vR={visitUrl:[{type:0,value:"Bekijk"}],back:[{type:0,value:"Terug"}],loading:[{type:0,value:"Laden..."}],imageError:[{type:0,value:"Kan afbeelding niet laden"}]};var Sr=x(w()),SR=({src:e,title:t})=>{let n=k("CommandPalette",tt),[r,o]=(0,A_.useState)("loading"),i=B(io);return(0,Sr.jsxs)("div",{className:n.image,children:[(0,Sr.jsx)("img",{src:e,alt:t,onLoad:()=>o("done"),onError:()=>o("error"),className:(0,Hc.default)(n.imageSrc,{[n.imageSrcHidden]:["loading","error"].includes(r)})}),r==="loading"&&(0,Sr.jsx)("span",{className:(0,Hc.default)(n.imageSrc,n.imageSrcStatus),children:i("loading")}),r==="error"&&(0,Sr.jsx)("span",{className:(0,Hc.default)(n.imageSrc,n.imageSrcStatus),children:(0,Sr.jsx)(Qa,{})}),t&&(0,Sr.jsx)("span",{className:n.imageTitle,children:t})]})},L_=SR;var O_=x(O()),N_=x($());var ga=x(w());function xg({children:e,heading:t,orientation:n}){let r=k("CommandPalette",tt);return O_.default.Children.count(e)===0?null:(0,ga.jsxs)("div",{"data-testid":"commandpalette-list",className:r.list,children:[t&&(0,ga.jsx)("h4",{className:r.listHeading,children:t}),(0,ga.jsx)("div",{className:(0,N_.default)(r.listWrapper,n==="horizontal"&&r.listHorizontal),children:e})]})}var ha=x($());var zc=x(O()),F_=x(w()),M_=zc.default.createContext(void 0);function xr(){let e=zc.default.useContext(M_);if(e===void 0)throw new Error("useCommandPalette must be used within the CommandPalette component");return e}var D_=({children:e,page:t,isOpen:n,onChangeOpen:r,selected:o,setSelected:i})=>{let s=zc.default.useMemo(()=>({page:t,isOpen:n,onChangeOpen:r,selected:o,setSelected:i}),[n,t,o]);return(0,F_.jsx)(M_.Provider,{value:s,children:e})};var Re=x(O()),j_=x($());var _g={root:"_root_1oh4w_1",trigger:"_trigger_1oh4w_5",content:"_content_1oh4w_19",contentOpen:"_contentOpen_1oh4w_33",contentTop:"_contentTop_1oh4w_37",contentBottom:"_contentBottom_1oh4w_41",item:"_item_1oh4w_45"};var so=x(w()),xR=0,B_=Re.default.createContext(null),_R=()=>{let e=(0,Re.useContext)(B_);if(!e)throw new Error("Invalid DropdownContext");return e},H_=({trigger:e,children:t,position:n="bottom"})=>{let r=(0,Re.useMemo)(()=>++xR,[]),o=(0,Re.useRef)(null),i=(0,Re.useRef)(null),s=k("Dropdown",_g),[a,l]=(0,Re.useState)(!1),[u,c]=(0,Re.useState)(n),p=h=>{h.preventDefault(),h.stopPropagation(),l(!a)},d=(0,Re.useCallback)(([h])=>{!h.isIntersecting&&a&&c(u==="top"?"bottom":"top")},[a]);return(0,Re.useEffect)(()=>{let h=v=>{o.current&&!o.current.contains(v.target)&&l(!1)};return document.addEventListener("click",h),()=>{document.removeEventListener("click",h)}},[]),(0,Re.useEffect)(()=>{if(!i.current&&!a)return()=>{};let h=new IntersectionObserver(d,{root:null,rootMargin:"0px",threshold:1});return i.current&&h.observe(i.current),()=>{i.current&&h.unobserve(i.current)}},[i,a]),(0,so.jsx)(B_.Provider,{value:{setIsOpen:l},children:(0,so.jsxs)("div",{ref:o,className:s.root,children:[(0,so.jsx)("button",{id:`dropdown-${r}`,"data-testid":"dropdown-trigger","aria-haspopup":"true","aria-expanded":a,"aria-label":"Dropdown trigger",type:"button",className:s.trigger,onClick:p,children:e}),(0,so.jsx)("div",{"data-testid":"dropdown-content",ref:i,"aria-hidden":!a,"aria-labelledby":`dropdown-${r}`,className:(0,j_.default)(s.content,{[s.contentOpen]:a,[s.contentTop]:u==="top",[s.contentBottom]:u==="bottom"}),children:t})]})})};function wR({as:e,children:t,onClick:n,...r}){let o=e||"button",i=k("Dropdown",_g),{setIsOpen:s}=_R(),a=l=>{s(!1),n(l),l.stopPropagation()};return(0,so.jsx)(o,{type:"button",className:i.item,onClick:a,...r,children:t})}H_.Item=wR;var wg=H_;var bg=x(w()),z_=e=>(0,bg.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"16",width:"14",viewBox:"0 0 448 512",...e,children:(0,bg.jsx)("path",{fill:"currentColor",d:"M8 256a56 56 0 1 1 112 0A56 56 0 1 1 8 256zm160 0a56 56 0 1 1 112 0 56 56 0 1 1 -112 0zm216-56a56 56 0 1 1 0 112 56 56 0 1 1 0-112z"})});var ao={};Ie(ao,{enUS:()=>bR,nlNL:()=>ER});var bR={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Add"}],sendSuggestion:[{type:0,value:"Send"}],suggestionSent:[{type:0,value:"Sent"}],sendingError:[{type:0,value:"Sending failed"}],tryAgain:[{type:0,value:"Try again"}],editSuggestion:[{type:0,value:"Edit"}],visitUrl:[{type:0,value:"Visit"}],giveFeedback:[{type:0,value:"Give feedback"}],answer:[{type:0,value:"Answer"}]},ER={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Gebruik"}],sendSuggestion:[{type:0,value:"Verzenden"}],suggestionSent:[{type:0,value:"Verzonden"}],sendingError:[{type:0,value:"Verzenden mislukt"}],tryAgain:[{type:0,value:"Probeer opnieuw"}],editSuggestion:[{type:0,value:"Bewerken"}],visitUrl:[{type:0,value:"Bekijk"}],giveFeedback:[{type:0,value:"Geef feedback"}],answer:[{type:0,value:"Antwoord"}]};var Uc=x(w()),CR="%0d%0a%0d%0a%0d%0a",TR=(e,t)=>{let n=[`Suggestie: ${encodeURIComponent(t)}`,"Beschrijf je feedback:"];return`mailto:${e.join(",")}?subject=Suggestie feedback&body=${n.join(CR)}`},kR=({suggestion:e,onFeedback:t})=>{let n=B(ao),r=M("suggestionFeedbackEmailAddresses");return!r||r.length===0?null:(0,Uc.jsx)(wg,{trigger:(0,Uc.jsx)(z_,{"data-testid":"feedback-dropdown-trigger"}),children:(0,Uc.jsx)(wg.Item,{as:"a",href:TR(r,e),onClick:t,children:n("giveFeedback")})})},Vc=kR;var ut=x(w());function Eg({closeOnSelect:e=!0,lineClamp:t,children:n,onClick:r,onFeedback:o,onSourceClick:i,index:s,description:a,sources:l,styles:u,...c}){let{selected:p,setSelected:d,onChangeOpen:h}=xr(),v=k("CommandPalette",tt);function y(m){r(m),e&&h(!1)}return(0,ut.jsxs)("div",{className:(0,ha.default)(v.listItem,p===s&&v.listItemSelected),children:[(0,ut.jsx)("button",{onMouseEnter:()=>d(s),type:"button",className:(0,ha.default)("command-palette-list-item",v.listItemAction,v.listItemPrimaryAction),"aria-disabled":c.disabled??!1,onClick:y,...c,children:(0,ut.jsxs)("div",{className:v.listItemContent,children:[typeof n=="string"?(0,ut.jsx)("p",{className:(0,ha.default)(v.listItemText,v.truncate,u==null?void 0:u.title),children:n}):n,a&&(0,ut.jsx)("p",{className:(0,ha.default)(v.listItemDescription,u==null?void 0:u.description,t?v.lineClamp:v.truncate),children:a})]})}),o&&p===s&&(0,ut.jsx)("div",{className:v.listItemActions,children:(0,ut.jsx)(Vc,{suggestion:String(n),onFeedback:o})}),l&&(0,ut.jsxs)("div",{className:v.sources,children:[(0,ut.jsx)("span",{className:v.sourcesTitle,children:"Sources"}),l.map(m=>m.url?(0,ut.jsx)("a",{className:v.source,href:m.url,target:"_blank",title:m.url,rel:"noopener noreferrer",onClick:()=>i&&i(m),children:m.name},m.url):(0,ut.jsx)("span",{className:v.source,children:m.name},m.name))]})]})}var lo=x(w());function Cg({children:e,title:t,id:n,onDismiss:r}){let o=B(io),i=k("CommandPalette",tt),{page:s}=xr();return s!==n?null:(0,lo.jsxs)("div",{className:i.page,id:`page_${n}`,tabIndex:-1,children:[r&&(0,lo.jsxs)("div",{className:i.pageNav,children:[(0,lo.jsxs)("button",{className:i.pageBackButton,type:"button",onClick:r,children:[(0,lo.jsx)(Tc,{}),o("back")]}),t&&(0,lo.jsx)("h3",{className:i.pageTitle,children:t})]}),e]})}var _r=x(O());var Kc=()=>/Mac/i.test(navigator.platform);var PR={info(...e){console.info("[Deepdesk]",...e)},warn(...e){console.warn("[Deepdesk]",...e)},error(...e){console.error("[Deepdesk]",...e)}},V=PR;function RR(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function re(e){return Array.isArray(e)?e.map(re):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>({...t,[RR(n)]:re(e[n])}),{}):e}function Tg(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function be(e){return Array.isArray(e)?e.map(be):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>({...t,[Tg(n)]:be(e[n])}),{}):e}var IR={agentInfo:void 0,agentSettings:{},visitorInfo:void 0,fetchState:"idle"},va=e=>{var t,n,r;return{timezone:((t=e.info.visitorInfo)==null?void 0:t.visitorTimeZone)||Intl.DateTimeFormat().resolvedOptions().timeZone,agentName:((n=e.info.agentInfo)==null?void 0:n.agentNickname)||"",visitorName:((r=e.info.visitorInfo)==null?void 0:r.visitorName)||""}},ya=D("info/setAgentInfo",async(e,t)=>{let{deepdeskAPI:n}=t.extra;if(!e.agentId&&!e.agentNickname)throw new Error("At least provide agentId or agentNickname");let r=await n.client.get("/apis/admin/session/me/",{version:null}),o={};return r.external_id||(o.external_id=e.agentId),r.nickname||(o.nickname=e.agentNickname),!o.external_id&&!o.nickname?re(r):(await n.client.patch("/apis/admin/session/me/",o,{version:null}),re(r))}),kg=D("info/setAgentSettings",async(e,t)=>{let{deepdeskAPI:n}=t.extra,r=await n.client.get("/apis/admin/session/me/",{version:null}),o={...typeof r.ui_config=="object"?r.ui_config:{},...e};return await n.client.patch("/apis/admin/session/me/",{ui_config:o}),o}),Pg=D("info/getAgentSettings",async(e,t)=>{let{deepdeskAPI:n}=t.extra;return(await n.client.get("/apis/admin/session/me/",{version:null})).ui_config}),U_=e=>e.info.agentInfo,V_=j({name:"info",initialState:IR,reducers:{setVisitorInfo(e,t){e.visitorInfo={...e.visitorInfo,...t.payload}}},extraReducers:e=>{e.addCase(ya.pending,(t,n)=>{t.fetchState="loading",t.agentInfo={...t.agentInfo,...n.meta.arg}}).addCase(ya.rejected,t=>{t.fetchState="error"}).addCase(ya.fulfilled,(t,n)=>{t.fetchState="done",t.agentInfo={...t.agentInfo,...n.meta.arg,agentId:n.payload.externalId||n.meta.arg.agentId||"",agentNickname:n.payload.nickname||n.meta.arg.agentNickname||""}}).addCase(kg.fulfilled,(t,n)=>{t.agentSettings=n.payload}).addCase(Pg.fulfilled,(t,n)=>{t.agentSettings=n.payload}).addCase(J,t=>{t.visitorInfo=void 0})}}),{setVisitorInfo:K_}=V_.actions,W_=V_.reducer;var Wc={list:[],fetchState:"idle",isOpen:!1,page:"search"},$_=e=>e.search.isOpen,q_=e=>e.search.page,G_=e=>e.search.list;function X_(e,t=n=>n){return n=>n.search.list.filter(r=>r.type===e).map(t)}var uo=D("search/getAll",async(e,t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=(s=r.conversation.current)==null?void 0:s.profileCode;if(!o)throw new Error("Profile should be provided in order to be able to search");let{results:i}=await n.search({profile:o,query:e.query,filters:{type:e.type},params:va(r),tags:e.tags});return i.map(a=>({...a,source:`search-${a.type.toLowerCase()}`,searchTerm:e.query}))}),Q_=j({name:"search",initialState:Wc,reducers:{setIsOpen(e,t){e.isOpen=t.payload},setPage(e,t){e.page=t.payload},resetSearch(e){e.fetchState=Wc.fetchState,e.list=Wc.list}},extraReducers:e=>{e.addCase(uo.pending,t=>{t.fetchState="loading"}).addCase(uo.rejected,(t,n)=>{t.fetchState="error",V.error(n.error)}).addCase(uo.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload}).addCase(J,()=>Wc)}}),{resetSearch:$c,setIsOpen:ct,setPage:We}=Q_.actions,Y_=Q_.reducer;var AR=/(https?:\/\/[^\s]+)/,qc=e=>e.split(" ").find(t=>AR.test(t));var Rg=x($());var Gc=x(w()),LR=({onClick:e,shortKeys:t,children:n,...r})=>{let o=k("CommandPalette",tt);return(0,Gc.jsxs)("button",{type:"button",...r,onClick:e,className:(0,Rg.default)(o.actionButton,r.className),children:[n,t&&t.map(i=>(0,Gc.jsx)("span",{className:(0,Rg.default)(o.actionShortcut,i===8629&&o.actionShortcutFixKerning),children:typeof i=="number"?String.fromCharCode(i):i},i))]})},_i=LR;var kn=x(w()),OR=({children:e,primaryLabel:t,secondaryLabel:n,onPrimary:r,onSecondary:o,list:i})=>{let s=k("CommandPalette",tt),a=B(io),{selected:l,setSelected:u}=xr(),c=i[l],p=c&&typeof c.text=="string"&&qc(c.text),d=(0,_r.useRef)(null);function h(S){if(!d.current)return;let _=d.current.querySelectorAll(".command-palette-list-item"),b=0,E=0;S==="down"?(_.forEach((R,P)=>{P===l&&(b=P)}),E=b===_.length-1?0:b+1):S==="up"?(_.forEach((R,P)=>{P===l&&(b=P)}),E=b?b-1:_.length-1):u(0);let C=_[E];C&&typeof E=="number"&&(u(E),C.scrollIntoView&&C.scrollIntoView({behavior:"smooth",block:E?"center":"end"}))}function v(){if(!d.current)return;let S=d.current.querySelectorAll(".command-palette-list-item"),_=0;S.forEach((E,C)=>{C===l&&(_=C)});let b=S[_];b&&b.click()}let y=()=>{p&&window.open(p,"_blank")},m=()=>{c&&r(c,l)},g=()=>{!c.type||["IMAGE","command"].includes(c.type)||o&&o(c,l)},f=(0,_r.useCallback)(S=>{if(S.key==="Enter"&&S.altKey&&p){y();return}if(S.key==="Enter"&&S.shiftKey){g();return}if(S.key==="ArrowDown"){S.preventDefault(),S.stopPropagation(),h("down");return}if(S.key==="ArrowUp"){S.preventDefault(),S.stopPropagation(),h("up");return}S.key==="Enter"&&l!==-1&&(S.preventDefault(),S.stopPropagation(),v())},[l]);return(0,_r.useEffect)(()=>(window.addEventListener("keyup",f),()=>{window.removeEventListener("keyup",f)}),[f]),(0,kn.jsxs)("div",{className:s.actions,children:[(0,kn.jsx)("div",{className:s.actionsWrapper,ref:d,children:e}),(0,kn.jsxs)("div",{className:s.actionsBar,children:[p&&(0,kn.jsx)(_i,{onClick:y,shortKeys:[Kc()?8997:"ALT",8629],children:a("visitUrl")}),c&&(0,kn.jsxs)(_r.Fragment,{children:[o&&c.type&&!["command","image"].includes(c.type.toLowerCase())&&(0,kn.jsx)(_i,{onClick:g,shortKeys:[8679,8629],children:n}),(0,kn.jsx)(_i,{onClick:m,shortKeys:[8629],children:t})]})]})]})},J_=OR;var ew=x(O());var Sa=x(w()),wi=()=>(0,Sa.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 24 24",width:"1em",fill:"currentColor",children:[(0,Sa.jsx)("path",{d:"M0 0h24v24H0z",fill:"none"}),(0,Sa.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 Ht=x(w());function NR({onChange:e,onChangeType:t,placeholder:n,typePlaceholder:r,types:o,value:i,selectedType:s},a){let l=k("CommandPalette",tt);return(0,Ht.jsxs)("div",{className:l.search,children:[(0,Ht.jsx)("div",{className:l.searchIcon,children:(0,Ht.jsx)(wi,{})}),(0,Ht.jsxs)("div",{className:l.searchInputWrapper,children:[(0,Ht.jsx)("input",{ref:a,spellCheck:!1,autoComplete:"off",onChange:u=>{e(u.currentTarget.value)},onFocus:u=>{u.currentTarget.select()},className:l.searchInput,placeholder:n,value:i,type:"text",id:"command-palette-search-input",autoFocus:!0}),o&&o.length>0&&(0,Ht.jsx)("div",{className:l.selectWrapper,children:(0,Ht.jsxs)("select",{"data-testid":"command-palette-type-select",className:l.select,onChange:u=>t(u.target.value===r?void 0:u.target.value),value:s||r,children:[r&&(0,Ht.jsx)("option",{children:r}),o.map(u=>(0,Ht.jsx)("option",{value:u.value,children:u.label},u.value))]})})]})]})}var tw=(0,ew.forwardRef)(NR);var xa=x(w());function co({placeholder:e="Start typing to search...",typePlaceholder:t="All types",defaultPage:n="search",page:r,onChangePage:o,onChangeSearch:i,onChangeType:s,onChangeOpen:a,selectedType:l,types:u,children:c,isOpen:p,search:d}){let[h,v]=(0,bi.useState)(0),y=(0,bi.useRef)(null),m=()=>{o&&o(n),s(void 0),i(""),a(!1)},g=()=>{var f;if(r!==n&&o){o(n);return}if(l&&s){s(void 0),(f=y.current)==null||f.focus();return}if(d.length>0){i("");return}a(!1)};return(0,bi.useEffect)(()=>{v(0)},[d,r]),(0,xa.jsx)(mi,{autoFocus:!0,contentAriaLabel:"Search Results",overlayAriaLabel:"Command Palette",isOpen:p,onBack:g,onClose:m,children:(0,xa.jsxs)(D_,{selected:h,setSelected:v,isOpen:p,onChangeOpen:a,page:r,children:[r===n&&(0,xa.jsx)(tw,{ref:y,onChange:i,onChangeType:s,placeholder:e,value:d,selectedType:l,types:u,typePlaceholder:t}),c]})})}co.Page=Cg;co.List=xg;co.Image=L_;co.ListItem=Eg;co.ActionsBar=J_;co.Button=_i;var te=co;var He=x(w()),MR=({suggestion:e,onUse:t,onDismiss:n,onTouched:r,onNext:o,onPrevious:i})=>{let s=e.text||e.url||e.message,a=k("EditSuggestionForm",Jx),l=U(),u=B(qm),c=A(v=>v.overlayInput.text);(0,Ig.useEffect)(()=>{e&&(l(Je.actions.reset()),l(Je.actions.stageSuggestion({text:s,suggestion:e,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"})),l(Je.actions.commitSuggestion()))},[e]);let p=v=>{v.preventDefault(),d(c)},d=v=>{l(uc(v)),t(v)},h=v=>y=>{c!==s?window.confirm(u("warning"))&&v(y):v(y)};return(0,Ig.useEffect)(()=>{r&&r(c!==s)},[r,e,c]),(0,He.jsxs)("div",{className:a.root,children:[(0,He.jsxs)("div",{className:a.content,children:[e.title&&(0,He.jsx)("h3",{className:a.title,children:e.title}),e.searchKeywords&&e.searchKeywords.length>0&&(0,He.jsx)(Bd,{labels:e.searchKeywords}),(0,He.jsx)(I_,{onUse:d,value:c})]}),(0,He.jsxs)("form",{className:a.actions,onSubmit:p,children:[(0,He.jsxs)("div",{children:[(0,He.jsx)("button",{disabled:!i,className:a.pagination,type:"button",onClick:i&&h(i),children:(0,He.jsx)(Tc,{})}),(0,He.jsx)("button",{disabled:!o,className:a.pagination,type:"button",onClick:o&&h(o),children:(0,He.jsx)(u_,{})})]}),(0,He.jsxs)("div",{className:a.primaryButtons,children:[(0,He.jsx)(te.Button,{onClick:h(n),shortKeys:["esc"],children:u("dismiss")}),(0,He.jsx)(te.Button,{shortKeys:[8679,8629],type:"submit",children:u("add")})]})]})]})},Xc=MR;var DR=["{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}"],FR=new RegExp(DR.map(e=>`(?:${e.replace("{","\\{").replace("}","\\}")})`).join("|"));function nw(e,t){let n=e.split(FR),r=0,o=[];for(let i=0;i<n.length;i++){let s=n[i];if(o.push(s),i===n.length-1)break;if(t.indexOf(s)===-1)return e;let a=n[i+1],l=i===n.length-2;r+=s.length;let u=r;if(l){let p=a.charAt(0),d=0;do u=p?t.indexOf(p,u+1):-1,d+=1;while(u!==-1&&a.indexOf(t.slice(u))!==0);if(u===-1&&d>2)return e}else u=a&&a!==""?t.indexOf(a,r):-1;let c=u===-1?t.slice(r):t.slice(r,u);o.push(c),r=u}return o.join("")}function rw(e,t){return typeof t=="boolean"?e:e.slice(0,t)}var iw={suggestions:[],fetchState:"idle",isInitialRequest:null},ow={default:iw},sw=e=>t=>{var n;return((n=t.textSuggestions[e])==null?void 0:n.suggestions)||[]},aw=e=>t=>{var n;return((n=t.textSuggestions[e])==null?void 0:n.suggestions)??[]},lw=e=>{let t=Object.keys(e.textSuggestions).map(n=>{var r;return(r=e.textSuggestions[n])==null?void 0:r.fetchState});return t.length===0?!0:t.every(n=>n!=="done")},Ei=e=>e.textSuggestions,uw=e=>{let t=e.toLowerCase();return n=>{let r=n.text.toLowerCase();return r.startsWith(t)&&r.length>t.length}},Qc=fe("textSuggestions/refresh"),Pn=D("textSuggestions/recommendations",async(e,t)=>{var u;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=(u=r.conversation.current)==null?void 0:u.id,{textSuggestionsCount:i,inlineSuggestions:s}=r.settings,a=pi(r);if(!o)throw new Error("No current conversation to fetch text suggestions");let l=await n.getTextSuggestions(o,va(r),e);if(e==="default"){let c=s?l.filter(uw(a)):l;t.dispatch(on(c.slice(0,i)))}return l}),_a=D("textSuggestions/autocompletions",async(e,t)=>{var u;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=(u=r.conversation.current)==null?void 0:u.id,{textSuggestionsCount:i,deanonymize:s,inlineSuggestions:a}=r.settings;if(!o)throw new Error("No current conversation to fetch text suggestions");let l=await n.getAutocompleteSuggestions(o,{...va(r),input:e});if(!t.getState().input.text)throw new Error("Abort");return a&&(l=l.filter(uw(e))),s&&(l=l.map(c=>({...c,text:c.source!=="trie-with-typos"?nw(c.text,e):c.text}))),l=rw(l,i),t.dispatch(on(l)),l}),cw=j({name:"textSuggestions",initialState:ow,reducers:{setTextSuggestions:{reducer(e,t){let{contentType:n}=t.payload;e[n].fetchState="done",e[n].suggestions=t.payload.suggestions},prepare(e,t){return{payload:{contentType:e,suggestions:t}}}},setSuggestionState(e,t){return t.payload}},extraReducers:e=>{e.addCase(Pn.pending,(t,n)=>{let r=n.meta.arg,o=t[r]||iw;return{...t,[r]:{...o,fetchState:"loading",isInitialRequest:o.isInitialRequest===null}}}).addCase(Pn.rejected,(t,n)=>{let r=n.meta.arg;t[r]&&(t[r].fetchState="error")}).addCase(Pn.fulfilled,(t,n)=>{let r=n.meta.arg;t[r]&&(t[r].fetchState="done",t[r].suggestions=n.payload)}).addCase(_a.pending,t=>{t.default.fetchState="loading"}).addCase(_a.rejected,t=>{t.default.fetchState="error"}).addCase(_a.fulfilled,(t,n)=>{t.default.fetchState="done",t.default.suggestions=n.payload}).addCase(J,()=>ow)}}),{setTextSuggestions:dw,setSuggestionState:pw}=cw.actions,fw=cw.reducer;var mw={contentType:null,suggestion:null},gw=e=>e.activeSuggestion.suggestion,hw=e=>e.activeSuggestion.contentType,yw=j({name:"activeSuggestion",initialState:mw,reducers:{setActiveSuggestion(e,t){let{contentType:n,suggestion:r}=t.payload;e.contentType=n,e.suggestion=r},resetActiveSuggestion(e){e.contentType=null,e.suggestion=null}},extraReducers:e=>{e.addCase(J,()=>mw)}}),{setActiveSuggestion:Rn,resetActiveSuggestion:Ag}=yw.actions,vw=yw.reducer;var Lg={};Ie(Lg,{enUS:()=>jR,nlNL:()=>BR});var jR={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"}]},BR={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 HR={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var Yc=({ui:e})=>e.overlayCollapsed;var Sw=j({name:"ui",initialState:HR,reducers:{setShowTabHint(e,t){e.showTabHint=t.payload},setInputHasFocus(e,t){e.overlayCollapsedUserOverwrite!==!0&&(t.payload===!0&&(e.overlayCollapsed=!1),e.inputHasFocus=t.payload)},setOverlayCollapsed(e,t){t.payload.collapse===!1&&(e.openOverlayWhenTyping=!1),!(t.payload.skipWhenInputFocus&&e.inputHasFocus)&&(e.overlayCollapsed=t.payload.collapse)},setOpenOverlayWhenTyping(e,t){e.openOverlayWhenTyping=t.payload},setOverlayCollapsedUserOverwrite(e,t){e.overlayCollapsedUserOverwrite=t.payload,e.overlayCollapsed=t.payload}}}),{setShowTabHint:wa,setInputHasFocus:Ci,setOverlayCollapsed:wr,setOpenOverlayWhenTyping:xw,setOverlayCollapsedUserOverwrite:_w}=Sw.actions,ww=Sw.reducer;var ba=x(O()),Ew=x(w()),bw=ba.default.createContext(null),Ti=({broadcastEvents:e,children:t})=>{let n=ba.default.useMemo(()=>e,[]);return(0,Ew.jsx)(bw.Provider,{value:n,children:t})},Pt=()=>{let e=(0,ba.useContext)(bw);if(!e)throw new Error("You should use the useBroadcastEvents within a BroadcastEventsProvider");return e};var zR={isLoggedIn:!0,loginFetchState:"idle",verifyFetchState:"idle",showLoginOverlay:!1},zt=e=>e.auth.isLoggedIn,Cw=e=>e.auth.loginFetchState,Tw=e=>e.auth.verifyFetchState,kw=e=>e.auth.showLoginOverlay,br=D("auth/validate",async(e,t)=>t.extra.deepdeskAPI.isLoggedIn()),Pw=D("auth/requestLogin",async({email:e},t)=>{let{deepdeskAPI:n}=t.extra;return n.requestLoginByEmail(e)}),Ea=D("auth/verifyLoginToken",async({token:e},t)=>{let{deepdeskAPI:n}=t.extra;return n.verifyLoginToken(e)}),Rw=j({name:"auth",initialState:zR,reducers:{setIsLoggedIn(e,t){e.isLoggedIn=t.payload},setShowLoginOverlay(e,t){e.showLoginOverlay=t.payload}},extraReducers:e=>{e.addCase(br.pending,t=>{t.loginFetchState="loading"}),e.addCase(br.fulfilled,(t,{payload:n})=>{t.isLoggedIn=n,t.loginFetchState="done"}),e.addCase(br.rejected,t=>{t.loginFetchState="error",t.isLoggedIn=!1}),e.addCase(Ea.pending,t=>{t.verifyFetchState="loading"}),e.addCase(Ea.rejected,t=>{t.verifyFetchState="error"}),e.addCase(Ea.fulfilled,(t,n)=>{n.payload.isLoggedIn?t.verifyFetchState="done":t.verifyFetchState="error"})}}),{setIsLoggedIn:ki,setShowLoginOverlay:Iw}=Rw.actions,Aw=Rw.reducer;var Og="SetActiveSuggestion",Pi="ShowLoginOverlay",Ng="UserLoggedIn",UR="UserLoggedOut",In="ApplySuggestion",Mg="ApplyImageSuggestion",VR="ShowCommandPalette",KR=e=>({[Og]:t=>{e.dispatch(pw(t.state)),e.dispatch(Rn({contentType:t.contentType,suggestion:t.suggestion}))},[VR]:t=>{e.dispatch(ct(t.isOpen)),t.page&&e.dispatch(We(t.page))},[Pi]:t=>{e.dispatch(Iw(t))},[Ng]:()=>{e.dispatch(br())},[UR]:()=>{e.dispatch(br())},[Mg]:t=>{e.dispatch(dc({suggestion:t.suggestion}))},[In]:t=>{e.dispatch(Ft({...t,eventMetrics:{inputType:"mouse"},replace:"selection"})),e.dispatch(yr())}}),Lw=KR;var Dg=x(w()),WR=()=>{var v;let[e,t]=(0,Ow.useState)(!1),n=A(gw),r=A(hw),o=A(Ei),i=U(),s=Pt(),a=B(Lg),l=()=>{n!==null&&e?window.confirm(a("warning"))&&u():u()},u=()=>{i(Ag()),i(Ci(!0)),i(Je.actions.reset())},c=(y,m)=>{i(Ag()),i(Ci(!0)),s.send(In,{text:y,suggestion:{...m,source:`${m.source||"text_recommendation"}-preview`}})};if(n===null||r===null)return null;let p=(v=o[r])==null?void 0:v.suggestions.indexOf(n),d=p===0||p===null?void 0:()=>i(Rn({contentType:r,suggestion:o[r].suggestions[p-1]})),h=p===o[r].suggestions.length-1||p===null?void 0:()=>i(Rn({contentType:r,suggestion:o[r].suggestions[p+1]}));return(0,Dg.jsx)(mi,{autoFocus:!0,isOpen:p!==null,onClose:l,onBack:l,contentAriaLabel:a("editContentLabel"),overlayAriaLabel:a("overlayLabel"),children:(0,Dg.jsx)(Xc,{onTouched:t,onDismiss:u,onUse:y=>c(y,n),suggestion:n,onNext:h,onPrevious:d})})},Nw=WR;var Zc=x($()),Ut=x(O());var Dw=x($());var Mw={root:"_root_1ukx5_1"};var Fw=x(w()),$R=({className:e,value:t,...n})=>{let r=k("TextInput",Mw);return(0,Fw.jsx)("input",{className:(0,Dw.default)(e,r.root),type:"text",value:t,...n})},Ca=$R;var Fg={};Ie(Fg,{enUS:()=>qR,nlNL:()=>GR});var qR={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"}]},GR={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 jw={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 ye=x(w());var XR=e=>{try{let t=new URL(e);return new URLSearchParams(t.search).get("token")||void 0}catch{return e}},QR=({agentEmail:e,isOpen:t,origin:n="",onSuccess:r,onDismiss:o})=>{let i=B(Fg),s=k("LoginTokenDialog",jw),a=A(Tw),l=U(),u=M("productName"),[c,p]=(0,Ut.useState)(e||""),[d,h]=(0,Ut.useState)(0),[v,y]=(0,Ut.useState)(""),m=(0,Ut.useCallback)(async _=>{_.preventDefault(),l(Pw({email:c})),h(1)},[n,c]),g=()=>{y(""),h(0)},f=(0,Ut.useCallback)(async _=>{_.preventDefault();let b=XR(_.target.elements.token.value);if(!b){y(i("verifyCodeError",{login:S}));return}l(Ea({token:b}))},[n]),S=(0,Ut.useMemo)(()=>_=>(0,ye.jsx)("button",{type:"button","data-testid":"login-token-dialog-back-button",className:s.anchorButton,onClick:g,children:_},"back-button"),[]);return(0,Ut.useEffect)(()=>{a==="error"&&y(i("verifyCodeError",{login:S})),a==="done"&&r()},[a]),(0,ye.jsx)(mi,{autoFocus:!0,isOpen:t,contentAriaLabel:i("promptTitle",{productName:u}),overlayAriaLabel:i("promptTitle",{productName:u}),onClose:o,onBack:o,children:(0,ye.jsxs)("div",{className:s.root,children:[(0,ye.jsx)("h1",{className:s.title,children:i("promptTitle",{productName:u})}),d===0&&(0,ye.jsxs)("form",{onSubmit:m,children:[(0,ye.jsx)("h2",{className:s.subtitle,children:i("requestCodeTitle")}),(0,ye.jsx)("p",{className:s.text,children:i("requestCodeBody",{productName:u})}),(0,ye.jsx)(Ca,{className:s.input,name:"email",placeholder:i("requestCodeInputPlaceholder"),value:c,onChange:_=>p(_.target.value)}),(0,ye.jsx)("div",{className:s.actions,children:(0,ye.jsx)("button",{type:"submit",className:(0,Zc.default)(s.button,s.primaryButton),children:i("requestCodeSubmitLabel")})})]}),d===1&&(0,ye.jsxs)("form",{onSubmit:f,children:[(0,ye.jsx)("h2",{className:s.subtitle,children:i("verifyCodeTitle")}),(0,ye.jsx)("p",{className:s.text,children:i("verifyCodeBody")}),(0,ye.jsx)(Ca,{className:s.input,name:"token",placeholder:i("verifyCodeInputPlaceholder"),disabled:["loading","done"].includes(a)}),v&&(0,ye.jsx)("div",{className:s.errorMessage,children:v}),(0,ye.jsxs)("div",{className:s.actions,children:[(0,ye.jsx)("button",{type:"button",className:(0,Zc.default)(s.button),onClick:g,children:i("back")}),(0,ye.jsx)("button",{type:"submit",className:(0,Zc.default)(s.button,s.primaryButton),disabled:["loading","done"].includes(a),children:i("verifyCodeSubmitLabel")})]})]})]})})},Bw=QR;var zw=x(w()),YR=()=>{let e=A(kw),t=A(U_),n=M("adminUrl"),r=Pt(),o=()=>r.send(Pi,!1),i=()=>{r.send(Pi,!1),r.send(Ng)};return(0,zw.jsx)(Bw,{isOpen:e,agentEmail:t==null?void 0:t.agentEmail,origin:n,onDismiss:o,onSuccess:i})},Hw=YR;var f1=x(Hg()),$e=x(O());var gI={data:null,fetchState:"idle"},Ww=e=>e.contentTypes.data,Ta=D("contentTypes/getContentTypes",async(e,t)=>t.extra.deepdeskAPI.getContentTypes()),hI=j({name:"contentTypes",initialState:gI,reducers:{},extraReducers:e=>{e.addCase(Ta.pending,t=>{t.fetchState="loading"}).addCase(Ta.rejected,t=>{t.fetchState="error"}).addCase(Ta.fulfilled,(t,n)=>{t.fetchState="done",t.data=n.payload})}}),$w=hI.reducer;function ka(e){let t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.left="-999999px",t.style.top="-999999px",document.body.appendChild(t),t.focus(),t.select(),document.execCommand("copy"),t.remove()}var qw=x(O());function Gw(e,t){(0,qw.useEffect)(()=>{let n=r=>{var o;((o=navigator==null?void 0:navigator.platform)!=null&&o.toLowerCase().includes("mac")?r.metaKey:r.ctrlKey)&&r.key===e&&(r.preventDefault(),r.stopPropagation(),t())};return document.addEventListener("keydown",n),()=>{document.removeEventListener("keydown",n)}},[])}var Pa=x(O());var Xw={data:null,fetchState:"idle"},Jc=e=>{var i;let t=[],{visitorName:n}=e.info.visitorInfo??{},{agentName:r,agentNickname:o}=e.info.agentInfo??{};return r&&r!==n&&t.push(r),o&&o!==n&&t.push(o),((i=e.entities.data)==null?void 0:i.filter(s=>!t.includes(s.text)))??null},Vt=D("entities/getEntities",async(e,t)=>{let{deepdeskAPI:n,dynamicThunkObject:r}=t.extra;if(!r.conversationQuery)return Promise.resolve([]);let o=r.conversationQuery,i=await o();return i.length===0?Promise.resolve([]):n.getEntities(i)}),yI=e=>e.filter((t,n)=>n===e.findIndex(r=>r.text===t.text)),vI=j({name:"entities",initialState:Xw,reducers:{},extraReducers:e=>{e.addCase(Vt.pending,t=>{t.fetchState="loading"}).addCase(Vt.rejected,t=>{t.fetchState="error"}).addCase(Vt.fulfilled,(t,n)=>{t.fetchState="done",t.data=yI(t.data?[...t.data,...n.payload]:n.payload)}).addCase(J,()=>Xw)}}),Qw=vI.reducer;var zg={};Ie(zg,{enUS:()=>SI,nlNL:()=>xI});var SI={noResults:[{type:0,value:"No entities have been found"}],copy:[{type:0,value:"Copy"}],use:[{type:0,value:"Use"}]},xI={noResults:[{type:0,value:"Er zijn geen entiteiten gevonden"}],copy:[{type:0,value:"Kopieer"}],use:[{type:0,value:"Gebruik"}]};var Yw={root:"_root_17kae_1",empty:"_empty_17kae_5"};var po=x(w()),_I=({onCopy:e,onUse:t})=>{let n=(0,Pa.useRef)(null),r=k("EntitiesList",Yw),o=B(zg),i=A(Jc),s=U();return(0,Pa.useEffect)(()=>{s(Vt())},[]),(0,Pa.useEffect)(()=>{n.current&&n.current.focus()},[n]),(0,po.jsxs)("div",{className:r.root,ref:n,tabIndex:-1,children:[i&&i.length>0&&(0,po.jsx)(te.ActionsBar,{primaryLabel:o("copy"),secondaryLabel:o("use"),onPrimary:(a,l)=>e(i[l]),onSecondary:(a,l)=>t(i[l]),list:i.map(a=>({text:a.text,type:a.label,primaryAction:"copy",secondaryAction:"use"})),children:(0,po.jsx)(te.List,{children:i.map((a,l)=>(0,po.jsx)(te.ListItem,{index:l,closeOnSelect:!0,onClick:()=>e(a),children:a.text},a.text))},"entities")}),i&&i.length===0&&(0,po.jsx)("p",{className:r.empty,children:o("noResults")})]})},Zw=_I;var Kt=x(O());var Jw={data:null,fetchState:"idle"},e1=e=>e.summary.data,t1=e=>e.summary.fetchState==="error",An=D("summary/getSummary",async(e,t)=>{let n=t.getState().profile.data;if(!n)throw new Error("Profile is not defined");let{deepdeskAPI:r,dynamicThunkObject:o}=t.extra;if(!o.conversationQuery)return Promise.reject(new Error("setConversationQuery method is not defined"));let i=o.conversationQuery,s=await i();return s.length===0?Promise.reject(new Error("No messages are included")):{summary:await r.getSummary(s,{promptInstruction:n.summarizerPromptInstruction,model:n.summarizerModel})}}),wI=j({name:"summary",initialState:Jw,reducers:{},extraReducers:e=>{e.addCase(An.pending,t=>{t.data=null,t.fetchState="loading"}).addCase(An.rejected,t=>{t.data=null,t.fetchState="error"}).addCase(An.fulfilled,(t,n)=>{t.fetchState="done",n.payload&&(t.data=n.payload.summary)}).addCase(J,()=>Jw)}}),n1=wI.reducer;var Ug={};Ie(Ug,{enUS:()=>bI,nlNL:()=>EI});var bI={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."}]},EI={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 r1={root:"_root_6ahh3_1",actions:"_actions_6ahh3_5",main:"_main_6ahh3_11",textInput:"_textInput_6ahh3_15",loading:"_loading_6ahh3_34",error:"_error_6ahh3_38"};var Ln=x(w()),CI=({onCopy:e})=>{let t=(0,Kt.useRef)(null),n=k("SummaryForm",r1),[r,o]=(0,Kt.useState)(""),i=B(Ug),s=A(e1),a=A(t1),l=U(),u=()=>{l(je({name:"summary copied to clipboard",data:{originalText:s,finalText:r},options:{includeConversationData:!0}})),e(r)},c=()=>{let p=document.getSelection();p&&l(je({name:"summary copied to clipboard",data:{originalText:s,finalText:p==null?void 0:p.toString()},options:{includeConversationData:!0}}))};return(0,Kt.useEffect)(()=>{l(An())},[]),(0,Kt.useEffect)(()=>{o(s||"")},[s]),(0,Kt.useEffect)(()=>{t.current&&s&&t.current.focus()},[t,s]),(0,Kt.useEffect)(()=>{let p=d=>{d.key==="Enter"&&d.shiftKey&&u()};return document.addEventListener("keydown",p),()=>{document.removeEventListener("keydown",p)}},[r]),(0,Ln.jsx)("div",{className:n.root,tabIndex:-1,children:a?(0,Ln.jsx)("p",{className:n.error,children:i("error")}):(0,Ln.jsxs)(Kt.Fragment,{children:[(0,Ln.jsx)("div",{className:n.main,children:(0,Ln.jsx)("textarea",{placeholder:s?void 0:i("loading"),disabled:!s,className:n.textInput,ref:t,value:r,onCopy:c,onChange:p=>o(p.target.value)})}),(0,Ln.jsx)("div",{className:n.actions,children:(0,Ln.jsx)(te.Button,{shortKeys:[8679,8629],onClick:u,children:i("copy")})})]})})},o1=CI;var Vg={};Ie(Vg,{enUS:()=>TI,nlNL:()=>kI});var TI={personalCollectionLink:[{type:0,value:"Go to Personal Collection"}],searchPlaceholder:[{type:0,value:"Start typing to search..."}],urlSuggestions:[{type:0,value:"Link suggestions"}],personalSuggestions:[{type:0,value:"Personal suggestions"}],pinnedMessages:[{type:0,value:"Pinned messages"}],imageSuggestions:[{type:0,value:"Images"}],typePlaceholder:[{type:0,value:"All types"}],navigation:[{type:0,value:"Navigation"}],entitiesClipboard:[{type:0,value:"Conversation clipper"}],entitiesTitle:[{type:0,value:"Copy to your clipboard"}],summaryClipboard:[{type:0,value:"Summarize conversation"}],summaryTitle:[{type:0,value:"Conversation summary"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Commands"}],use:[{type:0,value:"Use"}],preview:[{type:0,value:"Preview"}],warning:[{type:0,value:"Are you sure you want to discard the message?"}]},kI={personalCollectionLink:[{type:0,value:"Ga naar persoonlijke collectie"}],searchPlaceholder:[{type:0,value:"Begin met typen om te zoeken..."}],personalSuggestions:[{type:0,value:"Persoonlijke suggesties"}],urlSuggestions:[{type:0,value:"Link suggesties"}],imageSuggestions:[{type:0,value:"Afbeeldingen"}],navigation:[{type:0,value:"Navigatie"}],typePlaceholder:[{type:0,value:"Alle types"}],pinnedMessages:[{type:0,value:"Actueel"}],entitiesClipboard:[{type:0,value:"Klembord"}],entitiesTitle:[{type:0,value:"Kopieer naar klembord"}],summaryClipboard:[{type:0,value:"Gesprek samenvatten"}],summaryTitle:[{type:0,value:"Gesprek samenvatting"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Acties"}],use:[{type:0,value:"Gebruik"}],preview:[{type:0,value:"Bewerk"}],warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}]};var Er=x(O());var Kg={};Ie(Kg,{enUS:()=>PI,nlNL:()=>RI});var PI={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"}]},RI={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 i1={root:"_root_1g4pq_1",title:"_title_1g4pq_9",empty:"_empty_1g4pq_20",status:"_status_1g4pq_24",form:"_form_1g4pq_30",input:"_input_1g4pq_43",submit:"_submit_1g4pq_55",question:"_question_1g4pq_63",answer:"_answer_1g4pq_67",alignRight:"_alignRight_1g4pq_73"};var Wg={data:[],fetchState:"idle"},s1=e=>{var t;return(t=e.answer)==null?void 0:t.data},a1=e=>e.answer.fetchState,Ii=fe("answer/resetKnowledgeSearch"),Ri=D("answer/getAnswer",async(e,t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState().answer.data,o=(s=t.getState().conversation.current)==null?void 0:s.profileCode;if(!o)throw new Error("Profile is not defined");let i=await n.knowledgeAssist({promptInstruction:e.promptInstruction,question:e.question},r,o);return{question:e.question,answer:i}}),II=j({name:"answer",initialState:Wg,reducers:{},extraReducers:e=>{e.addCase(Ri.pending,t=>{t.fetchState="loading"}).addCase(Ri.rejected,t=>{t.fetchState="error"}).addCase(Ri.fulfilled,(t,n)=>{t.fetchState="done",t.data=[...t.data,n.payload]}).addCase(J,()=>Wg).addCase(Ii,()=>Wg)}}),l1=II.reducer;var Ra=x(w()),u1=()=>(0,Ra.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 512 512","aria-labelledby":"paperPlaneTitle",children:[(0,Ra.jsx)("title",{id:"paperPlaneTitle",children:"PaperPlane"}),(0,Ra.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 nt=x(w()),AI=({onUse:e,onResetQuestion:t,question:n,promptInstruction:r})=>{let[o,i]=Er.default.useState(""),{setSelected:s}=xr(),a=(0,Er.useRef)(null),l=k("EntitiesList",i1),u=B(Kg),c=U(),p=A(s1),d=A(a1),h=async y=>{y.preventDefault(),y.stopPropagation(),o!==""&&c(Ri({question:o,promptInstruction:r}))},v=(y,m)=>{c(je({name:"knowledge assist source viewed",data:{question:m,sourceViewed:y.url||y.name},options:{includeConversationData:!0}}))};return(0,Er.useEffect)(()=>{var y;n&&d==="idle"?c(Ri({question:n,promptInstruction:r})):(y=a.current)==null||y.focus()},[a,d]),(0,Er.useEffect)(()=>{d==="done"&&(c(je({name:"knowledge assist question answered",data:{question:o||n,sources:p[p.length-1].answer.sources,answer:p[p.length-1].answer.answer,isFollowUpQuestion:p.length>1},options:{includeConversationData:!0}})),s(p.length-1),i(""))},[d,p]),(0,Er.useEffect)(()=>{a.current&&a.current.scrollIntoView({behavior:"smooth"})},[a,p]),(0,nt.jsxs)("div",{className:l.root,children:[p.length>0&&(0,nt.jsx)("div",{className:l.alignRight,children:(0,nt.jsx)(te.Button,{onClick:t,children:u("reset")})}),(0,nt.jsxs)(te.ActionsBar,{list:p.map(({answer:y})=>({text:y.answer,type:"answer"})),primaryLabel:u("use"),onPrimary:y=>e(y.text),children:[p.map(({question:y,answer:m},g)=>(0,nt.jsx)(te.List,{children:(0,nt.jsx)(te.ListItem,{"data-testid":"knowledge-search-answer",index:g,description:m.answer,closeOnSelect:!0,onClick:()=>e(m.answer),onSourceClick:f=>v(f,y),sources:m.sources,styles:{title:l.question,description:l.answer},children:y})},`${m.answer}_${g}`)),d==="loading"&&(0,nt.jsx)("p",{className:l.status,children:u("loading")}),d==="error"&&(0,nt.jsx)("p",{className:l.status,children:u("error")}),(0,nt.jsxs)("form",{className:l.form,onSubmit:h,children:[(0,nt.jsx)("input",{ref:a,placeholder:u("anotherQuestion"),className:l.input,type:"text",value:o,onFocus:()=>{s(-1)},onChange:y=>{s(-1),i(y.target.value)}}),(0,nt.jsx)("button",{type:"submit",className:l.submit,children:(0,nt.jsx)(u1,{})})]})]})]})},c1=AI;var LI={data:null,fetchState:"idle"},Ai=e=>e.profile.data,ed=e=>e.profile.data?e.profile.data.uiConfig.widget.types.filter(t=>t.isActive):[],Ia=D("profile/getProfile",async(e,t)=>{var i;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=r.conversation.current;if(!o||!o.profileCode)throw new Error("No conversation of conversation profileCode found");return((i=r.profile.data)==null?void 0:i.code)===o.profileCode?r.profile.data:n.getProfile(o.profileCode)}),OI=j({name:"profile",initialState:LI,reducers:{},extraReducers:e=>{e.addCase(Ia.pending,t=>{t.fetchState="loading"}).addCase(Ia.rejected,t=>{t.fetchState="error"}).addCase(Ia.fulfilled,(t,n)=>{t.fetchState="done",t.data=n.payload})}}),d1=OI.reducer;var Ee=x(w()),NI=200,MI=5,DI=4,FI=e=>e.reduce((t,n)=>[...t,...n.list.map(r=>({...r,type:n.value}))],[]),p1=(e,t)=>!t||e.toLowerCase().includes(t.toLowerCase()),jI=()=>{let e=U(),t=Pt(),n=B(Vg),[r,o]=(0,$e.useState)(!1),[i,s]=(0,$e.useState)(""),a=A(q_),l=A(Ai),[u,c]=(0,$e.useState)(null),[p,d]=(0,$e.useState)([]),[h,v]=(0,$e.useState)(),y=A(zt),m=M("showSearch"),g=M("showEntitiesCommand"),f=M("showSummaryCommand"),S=M("showKnowledgeSearch"),_=M("showImageSearch"),b=M("searchTriggerKey"),E=A(Ww),C=A(G_),R=A($_),P=I=>yo(C.filter(X=>X.type===I.toUpperCase()),I),N=[{value:"PERSONAL",label:n("personalSuggestions"),list:P("PERSONAL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"URL",label:n("urlSuggestions"),list:P("URL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"STICKYMESSAGE",label:n("pinnedMessages"),list:P("STICKYMESSAGE"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"IMAGE",label:n("imageSuggestions"),lineClamp:!1,list:P("IMAGE"),listOrientation:"horizontal",shouldShow:_}].filter(I=>I.shouldShow),H=[{label:n("entitiesClipboard"),onClick:()=>e(We("entities")),shouldShow:g&&p1(n("entitiesClipboard"),i)},{label:n("summaryClipboard"),onClick:()=>e(We("summary")),shouldShow:f&&p1(n("summaryClipboard"),i)},{label:i?`${n("knowledgeAssist")}: ${i}`:n("knowledgeAssist"),onClick:()=>e(We("knowledgeAssist")),shouldShow:S}].filter(I=>I.shouldShow),z=(E==null?void 0:E.map(I=>({value:I.code.toUpperCase(),label:`${I.name}s`,list:P(I.code.toUpperCase()),listOrientation:"vertical",lineClamp:!0})))||[],Ue=(0,$e.useCallback)((0,f1.default)((I,X)=>{e(uo({query:I,type:X,tags:["search-overlay"]}))},NI),[]),cn=FI([...z,...N]),qt=(0,$e.useCallback)((I,X)=>{if(!X)return;let Xt=[...N,...z].find(({value:At})=>At===X);Xt&&(e(We("edit")),c({...I,searchTerm:void 0}),d(Xt.list))},[e,u,z]),ho=(0,$e.useCallback)((I,X)=>{switch(X.type){case"IMAGE":t.send(Mg,{suggestion:X});break;default:t.send(In,{text:I,suggestion:X})}e(ct(!1))},[e]),Ui=I=>{ka(I.text),e(je({name:"entity copied",data:{entity:I,type:"copy"}})),e(ct(!1))},Ir=(0,$e.useCallback)(I=>{e(je({name:"suggestion feedback",data:{text:I.text,source:"search",context:i},options:{includeConversationData:!0}}))},[i]),Ua=I=>{t.send(In,{text:I,suggestion:{source:"knowledge-assist",text:I}}),e(je({name:"answer used",data:{originalText:I},options:{includeConversationData:!0}})),s(""),e(We("search")),e(Ii()),e(ct(!1))},Va=I=>{ka(I),e(ct(!1))},Vi=I=>{t.send(In,{text:I.text,suggestion:{source:"entity",text:I.text}}),e(ct(!1))},Ki=u===null||p.indexOf(u)-1<0?void 0:()=>c(p[p.indexOf(u)-1]),Ar=u===null||p.indexOf(u)===p.length-1?void 0:()=>c(p[p.indexOf(u)+1]);function yo(I,X){return I.slice(0,h?10:X.toLowerCase()==="image"?DI:MI)}function Rd(I,X,Xt){return X.reduce((At,Hn)=>Xt&&h===Xt?Hn.length+At:yo(Hn,Xt).length+At,I)}function Gt(I){return X=>{r?window.confirm(n("warning"))&&(I(X),o(!1)):I(X)}}return(0,$e.useEffect)(()=>{i?Ue(i,h):e($c())},[i,h]),(0,$e.useEffect)(()=>{a==="search"&&e(Ii())},[a]),(0,$e.useEffect)(()=>{y&&e(Ta())},[y]),Gw(b,()=>e(ct(!0))),!m||!l?null:(0,Ee.jsxs)(te,{placeholder:n("searchPlaceholder"),typePlaceholder:n("typePlaceholder"),onChangeSearch:s,onChangeOpen:Gt(I=>e(ct(I))),onChangeType:I=>v(I),onChangePage:Gt(I=>e(We(I))),selectedType:h,search:i,page:a,isOpen:R,types:[...z,...N],children:[(0,Ee.jsx)(te.Page,{id:"search",children:(0,Ee.jsxs)(te.ActionsBar,{list:[...H.map(I=>({text:I.label,type:"command"})),...cn.map(I=>({text:I.text||I.url||I.message,type:I.type}))],primaryLabel:n("use"),secondaryLabel:n("preview"),onPrimary:({text:I},X)=>ho(I,cn[X]),onSecondary:(I,X)=>{qt(cn[X-H.length],cn[X-H.length].type)},children:[H.length>0&&(0,Ee.jsx)(te.List,{heading:n("commands"),children:H.map((I,X)=>(0,Ee.jsx)(te.ListItem,{index:Rd(X,[],"commands"),closeOnSelect:!1,onClick:I.onClick,children:I.label},I.label))}),[...z,...N].map(({value:I,label:X,list:Xt,lineClamp:At,listOrientation:Hn},Th)=>(0,Ee.jsx)(te.List,{heading:X,orientation:Hn==="horizontal"?"horizontal":"vertical",children:yo(Xt,I).map((ce,Lr)=>(0,Ee.jsx)(te.ListItem,{index:Rd(H.length+Lr,[...z,...N].slice(0,Th).map(({list:gE})=>gE),I),closeOnSelect:!1,lineClamp:At,onClick:()=>ho(ce.text,ce),description:I!=="IMAGE"?ce.title&&ce.text:void 0,onFeedback:I!=="IMAGE"?()=>Ir(ce):void 0,children:I==="IMAGE"?(0,Ee.jsx)(te.Image,{title:ce.title||ce.text,src:ce.image}):ce.title||ce.text},`${ce.id}-${ce.text}`))},I))]})}),(0,Ee.jsx)(te.Page,{id:"edit",onDismiss:Gt(()=>{e(We("search")),c(null)}),children:u&&(0,Ee.jsx)(Xc,{suggestion:u,onTouched:o,onDismiss:()=>{o(!1),e(We("search")),c(null),d([])},onNext:Ar,onPrevious:Ki,onUse:I=>{e(We("search")),ho(I,{...u,source:`${u.source||"text_recommendation"}-preview`}),e(ct(!1)),d([]),c(null)}})}),(0,Ee.jsx)(te.Page,{id:"entities",title:n("entitiesTitle"),onDismiss:Gt(()=>{e(We("search"))}),children:(0,Ee.jsx)(Zw,{onUse:Vi,onCopy:Ui})}),(0,Ee.jsx)(te.Page,{id:"summary",title:n("summaryTitle"),onDismiss:Gt(()=>{e(We("search"))}),children:(0,Ee.jsx)(o1,{onCopy:Va})}),(0,Ee.jsx)(te.Page,{id:"knowledgeAssist",title:n("knowledgeAssist"),onDismiss:Gt(()=>{e(Ii()),e(We("search"))}),children:(0,Ee.jsx)(c1,{promptInstruction:l.knowledgeAssistPromptInstruction,question:i,onUse:Ua,onResetQuestion:()=>{e(Ii()),s("")}})})]})},m1=jI;var Li=x(w()),BI=()=>{let e=M("showSearch"),t=M("isEmbedded");return(0,Li.jsxs)(g1.Fragment,{children:[e&&(0,Li.jsx)(m1,{}),(0,Li.jsx)(Nw,{}),t&&(0,Li.jsx)(Hw,{})]})},h1=BI;function Oi(e){let{showMidSentenceSuggestions:t,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:r}=e.settings,{text:o,selection:i}=e.input.userCommitted;return i.start!==i.end?!1:i.end>=o.length?!0:t?n&&new RegExp(n).test(o.substring(i.end))||r&&new RegExp(r).test(o.substring(0,i.end))?!0:n===!1&&r===!1:!1}var td=x(O());var Mi=x(O());var y1=x(O());function v1(e,t,n){(0,y1.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var HI=/[.*+?^${}()|[\]\\]/g,zI=/[^0-9A-Za-zÀ-ÖØ-öø-ÿ](?=[0-9A-Za-zÀ-ÖØ-öø-ÿ]*$)/;function UI(e){return e.replace(HI,"\\$&")}function VI(e,t){let n=e.split("").findIndex((r,o)=>r!==t[o]);return n>-1?n:Math.min(e.length,t.length)}function KI(e){return e.search(zI)}function S1(e,t=[]){let n=e;return t.forEach(r=>{if(!r)return;let o=new RegExp(`\\b(${UI(r)})\\b`,"gi");n=n.replace(o,"<strong>$1</strong>")}),n}function x1(e){return e.replace(bo,'<mark data-type="placeholder">$1</mark>')}function Ni(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function WI(e,t){return e.split("").map((s,a)=>({char:s,index:a})).filter(({char:s,index:a})=>/\s/.test(s)&&a<=t).map(({index:s})=>s).reverse()[0]}function $g(e,t,n={}){if(t){let r=VI(t.toLowerCase(),e.toLowerCase()),o=Ni(e.substring(r,e.length));if(n.stripAgentPart){let l=e.substring(0,r),u=KI(l);return`<span style="opacity: 0.5">${l.substring(u+1)}</span>${o}`}let s=t.split(gy).length>3||t.length>30?WI(t.trim(),r):0;return`${`${s>0?"\u2026":""}${Ni(e.substring(s,r))}`}<strong>${o}</strong>`}return e}var _1={root:"_root_4u430_1",actions:"_actions_4u430_8",badge:"_badge_4u430_15",formattedText:"_formattedText_4u430_19"};var fo=x(w()),qI=["search","personal-collection-search","search-autocomplete"];function GI(e,t,n,r={}){let o="";return qI.includes(t)?o=S1($g(e,n,{stripAgentPart:!0}),r.searchKeywords??[n]):o=$g(e,n,r),r.placeholders===!0&&(o=x1(o)),o}var XI=()=>{},QI=({index:e,selected:t,suggestion:n,onFeedback:r})=>{let o=M("inlineSuggestions"),i=A(pi),s=U(),a=k("TextSuggestion",_1),l=(0,Mi.useRef)(null);(0,Mi.useEffect)(()=>{let c=setTimeout(()=>{s(Wx({text:n.text,suggestion:n}))},500);return()=>{clearTimeout(c)}},[n]),v1(l,"click",()=>{s(hr(e)),s(Ft({suggestion:n,text:n.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let u=(0,Mi.useMemo)(()=>GI(n.text,n.source,i,{stripAgentPart:o,placeholders:!0,searchKeywords:n.searchKeywords}),[o,n.text,n.source,i,n.searchKeywords]);return n.source==="gpt"&&!o?null:(0,fo.jsxs)("div",{className:a.root,onMouseEnter:()=>s(hr(e)),children:[(0,fo.jsx)(oe,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:t,onClick:XI,children:(0,fo.jsx)(gi,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:u})}),t&&r&&(0,fo.jsx)("div",{className:a.actions,children:(0,fo.jsx)(Vc,{onFeedback:()=>r(n),suggestion:n.text})})]})},w1=QI;var qg=x(w()),YI=({onFeedback:e,suggestions:t,selectedIndex:n,reverse:r})=>{let o=(0,td.useMemo)(()=>{let i=t.map((s,a)=>(0,qg.jsx)(w1,{index:a,selected:a===n,suggestion:s,onFeedback:e},`${s.text}-${s.source}`));return r?i.reverse():i},[t,n,r]);return(0,qg.jsx)(td.Fragment,{children:o})},nd=YI;var b1={root:"_root_otdbu_1",paper:"_paper_otdbu_11"};var Aa=x(w()),ZI=({textSuggestions:e,selectedIndex:t})=>{let n=k("InlineSuggestionsOverlay",b1),r=A(Oi),o=U(),i=A(zt),s=A(di),a=A(Yc),l=M("showTextSuggestions");return Si(()=>{o(wr({collapse:!0,skipWhenInputFocus:!0}))}),a||!r||!l||e.length===0||i!==!0||s===!1?null:(0,Aa.jsx)("div",{className:n.root,"data-variant":"inline",children:(0,Aa.jsx)("div",{className:n.paper,children:(0,Aa.jsx)(yt,{children:(0,Aa.jsx)(nd,{suggestions:e,selectedIndex:t})})})})},JI=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),E1=xn(JI)(ZI);var od=x($()),Di=x(O());var C1=x(O());function T1(e,t){let[n,r]=(0,C1.useState)(()=>{if(typeof window>"u")return t;try{let i=window.localStorage.getItem(e);return i?JSON.parse(i):t}catch(i){return V.error(i),t}});return[n,i=>{try{let s=i instanceof Function?i(n):i;r(s),typeof window<"u"&&window.localStorage.setItem(e,JSON.stringify(s))}catch(s){V.error(s)}}]}var P1=x($()),On=x(O());var Gg={};Ie(Gg,{enUS:()=>eA,nlNL:()=>tA});var eA={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"}]}]},tA={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 k1={root:"_root_1vfca_1",anchor:"_anchor_1vfca_6",anchorButton:"_anchorButton_1vfca_11"};var Cr=x(w()),Xg=(e,t,n)=>r=>(0,Cr.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),nA=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r})=>{let o=B(Gg),i=Pt(),s=k("Login",k1),a=M("productName"),l=(0,On.useCallback)(y=>{y.preventDefault(),r&&r(parseInt(y.target.value,10))},[]),u=(0,On.useCallback)(y=>{y.preventDefault(),i.send(Pi,!0)},[t]),c=(0,On.useMemo)(()=>y=>(0,Cr.jsx)("a",{href:t,className:s.anchor,target:"_blank",rel:"noreferrer",children:y},"login"),[t]),p=(0,On.useCallback)(y=>(0,Cr.jsx)("button",{type:"button",className:s.anchorButton,onClick:u,children:y},"prompt"),[u]),{min:d,hour:h,day:v}=(0,On.useMemo)(()=>({min:Xg(s,60*10,l),hour:Xg(s,60*60,l),day:Xg(s,60*60*12,l)}),[]);return(0,Cr.jsxs)("div",{className:(0,P1.default)(e,s.root),children:[o("loginPlease",{login:n?p:c,productName:a}),r&&(0,Cr.jsxs)(On.Fragment,{children:[(0,Cr.jsx)("br",{}),o("snooze",{min:d,hour:h,day:v})]})]})},rd=nA;var R1={root:"_root_1g8fi_1",text:"_text_1g8fi_19"};var La=x(w()),rA=({title:e})=>{let t=k("SearchTrigger",R1),n=U();return(0,La.jsxs)("button",{type:"button",className:t.root,onClick:()=>n(ct(!0)),children:[(0,La.jsx)(wi,{}),(0,La.jsx)("span",{className:t.text,children:e})]})},I1=rA;var Qg={};Ie(Qg,{enUS:()=>oA,nlNL:()=>iA});var oA={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"}]},iA={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 A1={root:"_root_onpov_1",isInline:"_isInline_onpov_14",toggleButton:"_toggleButton_onpov_21",toggleButtonWrapper:"_toggleButtonWrapper_onpov_25",toggleButtonWrapperHidden:"_toggleButtonWrapperHidden_onpov_32",isCollapsed:"_isCollapsed_onpov_36",collapsible:"_collapsible_onpov_36",hints:"_hints_onpov_44",hintsHidden:"_hintsHidden_onpov_51",triggers:"_triggers_onpov_56",triggersRight:"_triggersRight_onpov_71"};var ue=x(w()),sA=({textSuggestions:e,selectedIndex:t})=>{let n=k("SuggestionsOverlay",A1),r=B(Qg),o=A(Oi),i=Hx(),s=U(),a=(0,Di.useRef)(null),l=M("searchTriggerKey"),u=M("productName"),c=A(Yc),p=A(zt),d=A(di),[h,v]=(0,Di.useState)(null),y=M("showSearch"),m=M("showTextSuggestions"),g=M("adminUrl"),f=M("isEmbedded"),[S,_]=T1("dd-snooze-until-ms",0),b=c||S>Date.now(),E=A(H=>H.input.text),C=e.filter(H=>H.source!=="gpt").length,R=()=>{b&&_(0),s(_w(!b))},P=H=>{s(je({name:"suggestion feedback",data:{text:H.text,source:"overlay",context:E},options:{includeConversationData:!0}}))},N=H=>{let z=Date.now()+H*1e3;_(z),V.info(`Snooze until: ${new Date(z)}`),s(wr({collapse:!0}))};return(0,Di.useEffect)(()=>{C===0&&v(null)},[e,C]),Si(()=>{s(wr({collapse:!0,skipWhenInputFocus:!0}))}),p===null||d===!1?null:p===!1?(0,ue.jsxs)("div",{ref:a,className:(0,od.default)(n.root,{[n.isCollapsed]:b}),children:[!b&&(0,ue.jsxs)("div",{className:n.triggers,children:[(0,ue.jsx)("div",{style:{flex:1}}),(0,ue.jsx)("div",{className:n.triggersRight,children:(0,ue.jsx)(Mr,{className:n.toggleButton,title:r("collapse"),onClick:R,isCollapsed:!1})})]}),(0,ue.jsx)("div",{className:n.toggleButtonWrapper,children:(0,ue.jsx)(Mr,{className:n.toggleButton,title:r("open",{productName:u}),onClick:R,isCollapsed:!0})}),(0,ue.jsx)("div",{className:n.collapsible,children:(0,ue.jsx)(rd,{loginUrl:g,isEmbedded:f,onSnooze:N})})]}):!i||!o?null:(0,ue.jsxs)("div",{ref:a,className:(0,od.default)(n.root,{[n.isCollapsed]:b}),children:[!b&&(0,ue.jsxs)("div",{className:n.triggers,children:[(0,ue.jsx)("div",{style:{flex:1},children:y&&(0,ue.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>v(r(Kc()?"searchHintMac":"searchHintWindows",{searchTriggerKey:l.toUpperCase()})),onMouseLeave:()=>v(null),children:(0,ue.jsx)(I1,{title:r("search")})})}),(0,ue.jsxs)("div",{className:n.triggersRight,onFocus:()=>{},children:[(0,ue.jsx)("div",{className:(0,od.default)(!h&&n.hintsHidden,n.hints),children:h}),(0,ue.jsx)(Mr,{className:n.toggleButton,title:r("collapse"),onClick:R,isCollapsed:!1})]})]}),(0,ue.jsx)("div",{className:n.toggleButtonWrapper,children:(0,ue.jsx)(Mr,{className:n.toggleButton,title:r("open",{productName:u}),onClick:R,isCollapsed:!0})}),C>0&&m&&(0,ue.jsx)("div",{className:n.collapsible,onFocus:()=>{},children:(0,ue.jsx)(yt,{children:(0,ue.jsx)(nd,{onFeedback:P,suggestions:e,selectedIndex:t,reverse:!0})})})]})},aA=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),L1=xn(aA)(sA);var Oa=x(w()),lA=({children:e})=>{let n=M("locale").replace("-","");return(0,Oa.jsx)(tg.Provider,{value:n,children:e})},uA=({store:e,customStyles:t={},children:n})=>(0,Oa.jsx)(Dm,{store:e,children:(0,Oa.jsx)(lA,{children:(0,Oa.jsx)($i.Provider,{value:t,children:n})})}),Fi=uA;var yd=x($());var Dn=x(O());var O1=x(O()),cA=["div","span","mark","strong","b","i","u","em"];function Yg(e,t,n=0){var i;let r=e[e.length-1],o=typeof r=="object"&&r!==null?(i=r.props)==null?void 0:i.tagName:void 0;if(o==="br")return e.pop(),[...e,...t,r];if(cA.includes(o)){let s=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,O1.cloneElement)(r,{children:Yg(s,t,n+1)})]}return[...e,...t]}function Tr(e){return e.tagName.toLowerCase()==="textarea"}var N1={root:"_root_81non_1",container:"_container_81non_3",agentText:"_agentText_81non_5",tabText:"_tabText_81non_6",hint:"_hint_81non_6",matchSelection:"_matchSelection_81non_10",focus:"_focus_81non_16",resetIndent:"_resetIndent_81non_20",matchKeyword:"_matchKeyword_81non_24",matchPlaceholder:"_matchPlaceholder_81non_25",hover:"_hover_81non_31",hintText:"_hintText_81non_64",popover:"_popover_81non_72",popoverRoot:"_popoverRoot_81non_77",popoverContentContainer:"_popoverContentContainer_81non_81",popoverContent:"_popoverContent_81non_81",selectionOptions:"_selectionOptions_81non_107",selectionOptionsIsHidden:"_selectionOptionsIsHidden_81non_112",selectionOptionsButton:"_selectionOptionsButton_81non_116",caret:"_caret_81non_132",popoverSuggestionsRoot:"_popoverSuggestionsRoot_81non_136",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_81non_141"};var V1=x($());var fd=x(O());function M1(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function id(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function D1(e){return e!=null}var Jg=x($()),Rt=x(O());var sd=x(O()),dA=["bottom","height","left","right","top","width"],pA=(e={},t={})=>dA.some(n=>e[n]!==t[n]),Nn=new Map,F1,j1=()=>{let e=[],t=[];Nn.forEach((n,r)=>{if(r instanceof Element&&!r.isConnected){t.push(r);return}let o=r.getBoundingClientRect();pA(o,n.rect)&&(n.rect=o,e.push(n))}),t.forEach(n=>{Nn.delete(n)}),e.forEach(n=>{n.callbacks.forEach(r=>r(n.rect))}),F1=window.requestAnimationFrame(j1)};function fA(e,t){return{observe(){let n=Nn.size===0;if(Nn.has(e)){let r=Nn.get(e);r.callbacks.push(t),r.rect&&t(r.rect)}else Nn.set(e,{rect:void 0,hasRectChanged:!1,callbacks:[t]});n&&j1()},unobserve(){let n=Nn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Nn.delete(e),Nn.size||cancelAnimationFrame(F1)}}}}function Zg(e){let[t,n]=(0,sd.useState)(null);return(0,sd.useLayoutEffect)(()=>{if(!e.current)return;let r=fA(e.current,o=>{n(o)});return r.observe(),()=>{r.unobserve()}},[e]),t}var ji=x(O()),H1=x(hu());var B1={root:"_root_1jq08_1"};var z1=({children:e})=>{let[t,n]=(0,ji.useState)(null),r=(0,ji.useContext)($i);return(0,ji.useLayoutEffect)(()=>{let o=document.createElement("div");return ro(o),o.classList.add(B1.root),r!=null&&r.portalRootNode&&o.classList.add(r==null?void 0:r.portalRootNode),document.body.appendChild(o),n(o),()=>{o.isConnected&&document.body.removeChild(o)}},[]),t?(0,H1.createPortal)(e,t):null};var ln={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 ad=x(w()),ld=(e=!1)=>{let[t,n]=(0,Rt.useState)(e),r=(0,Rt.useCallback)(()=>n(!0),[]),o=(0,Rt.useCallback)(()=>n(!1),[]),i=(0,Rt.useCallback)(()=>n(a=>!a),[]),s=(0,Rt.useRef)(null);return{opened:t,open:r,close:o,toggle:i,triggerRef:s}};function eh(e,t=null,n=0){if(!e)return{display:"none"};let r=t?e.top-t.top<0||e.top<t.top-n?t.top-n:e.top+e.height>t.top+t.height+n?t.top+t.height+n-e.height:e.top:e.top,o=t?e.left<t.left-n?t.left-n:e.left+e.width>t.left+t.width+n?t.left+t.width+n-e.width:e.left:e.left;return{top:r,left:o,height:e.height,width:e.width}}var ud=({className:e,triggerRef:t,boundaryRef:n=(0,Rt.createRef)(),position:r="above",align:o="center",children:i,toStyle:s=eh,...a})=>{let l=Zg(t),u=Zg(n),c=(0,Rt.useMemo)(()=>s(l,u,0),[l,u]);return(0,ad.jsx)(z1,{children:(0,ad.jsx)("div",{className:(0,Jg.default)(ln.ref,{[ln.positionAbove]:r==="above",[ln.positionBelow]:r==="below",[ln.positionLeft]:r==="left",[ln.positionRight]:r==="right",[ln.alignStart]:o==="start",[ln.alignCenter]:o==="center",[ln.alignEnd]:o==="end"}),style:c,...a,role:"dialog",children:(0,ad.jsx)("div",{className:(0,Jg.default)(e,ln.root),children:i})})})};var U1=x($()),cd=x(O());var th=x(w()),dd=(0,cd.forwardRef)(({className:e,children:t,...n},r)=>{let o=(0,cd.useRef)(null),i=k("TabCompletion",En);return(0,th.jsx)("div",{ref:id([o,r]),className:(0,U1.default)(e,i.popoverContentContainer),...n,children:(0,th.jsx)("div",{className:i.popoverContent,children:t})})});var kr=x(w()),mA=e=>t=>{let n=eh(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},gA=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let i=k("TabCompletion",En),s=ld(),a=(0,fd.useMemo)(()=>mA(e.getBoundingClientRect()),[e]),[l,u]=Nc(e);return(0,fd.useEffect)(()=>{u?s.open():s.close()},[u]),(0,kr.jsxs)("span",{children:[(0,kr.jsx)("mark",{ref:id([l,s.triggerRef]),className:(0,V1.default)(i.matchKeyword,{[i.hover]:u}),"aria-haspopup":"dialog","aria-expanded":s.opened?"true":"false",children:r}),s.opened&&(0,kr.jsx)(ud,{className:i.popover,triggerRef:s.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,kr.jsx)(dd,{style:n,children:(0,kr.jsx)("div",{className:i.hintText,children:o})})})]})},pd=class extends wn{keywordMatches=[];preparedKeywordMatches=[];usedKeywordMatches=new Set;onBeforeParse(t,n){return n.keywordMatches&&n.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=n.keywordMatches.map(r=>({...r,keywordRegex:new RegExp(`\\b${M1(r.keyword)}\\b`,"i")})),this.keywordMatches=n.keywordMatches),this.usedKeywordMatches.clear(),t}match(t){let n=this.preparedKeywordMatches.map(o=>{if(this.usedKeywordMatches.has(o))return null;let i=t.match(o.keywordRegex);if(!i)return null;let s=t.charAt(i.index-1),a=t.charAt(i.index+o.keyword.length);return s==="{"&&a==="}"?null:{index:i.index,length:i[0].length,match:i[0],matchString:i[0],suggestion:o.suggestion,preparedKeywordMatch:o,valid:!0}}).filter(D1);if(n.length===0)return null;let r=n.reduce((o,i)=>i.index<o.index?i:o);return this.usedKeywordMatches.add(r.preparedKeywordMatch),r}replaceWith(t,n){return(0,kr.jsx)(gA,{inputElement:n.inputElement,suggestion:n.suggestion,inputStyle:n.inputStyle,boundaryRef:n.boundaryRef,children:t},`keyword_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var gd=x($());var Ge=x(O());var nh=x(w()),K1=()=>(0,nh.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,nh.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 Pr=x(O());var $1=x(Hg());var W1={root:"_root_1muu8_1",content:"_content_1muu8_7"};function md(e,t,n){var o;let r=((o=e.imageSizes)==null?void 0:o[t])||e.image||n;if(!r)return null;try{return new URL(r).toString()}catch{return null}}function rh(e){return e.replace("https://www.","").replace("https://","")}var It=x(w()),hA=3,yA=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),vA=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=hA})=>{let i=k("LinkSearch",W1),[s,a]=(0,Pr.useState)(""),l=U(),u=A(sw("url")),c=A(X_("URL",yA)),[p,d]=(0,Pr.useState)(c.length-1),h=M("fallbackImage"),v=f=>{let S=f.target;a(S.value)},y=(f,S)=>{f.stopPropagation(),f.preventDefault(),window.open(S,"_blank")},m=f=>{var b;let S=p-1<0?c.length-1:p-1,_=p+1===c.length?0:p+1;f.code==="Escape"&&(a(""),t()),f.code==="ArrowUp"&&d(S),f.code==="ArrowDown"&&d(_),f.code==="Enter"&&e(((b=c[p])==null?void 0:b.text)||s)},g=(0,Pr.useCallback)((0,$1.default)(f=>{l(uo({query:f,type:"URL",tags:["link-search"]}))},300),[]);return(0,Pr.useEffect)(()=>{s&&g(s)},[s]),(0,Pr.useEffect)(()=>()=>{l($c())},[]),(0,It.jsxs)("div",{className:i.root,children:[(0,It.jsx)(yt,{withDivider:!0,children:(s?c:u).slice(0,o).map((f,S)=>(0,It.jsx)(oe,{selected:p===S,onClick:()=>e(f.text),"data-testid":"linksearch-suggestion",children:(0,It.jsxs)(ge,{children:[(0,It.jsx)(ge.Image,{src:md(f,"small",h||void 0),title:f.title||f.text}),(0,It.jsxs)(ge.Content,{className:i.content,cropText:!0,children:[(0,It.jsx)(ge.Title,{children:f.title||rh(f.text)}),f.title&&rh(f.text)]}),(0,It.jsx)(oe.Actions,{children:(0,It.jsx)(oe.ActionButton,{label:r,onClick:_=>y(_,f.text)})})]})},f.text))}),(0,It.jsx)(Ca,{value:s,onChange:v,autoFocus:!0,placeholder:n,onKeyUp:m})]})},q1=vA;var oh={};Ie(oh,{enUS:()=>SA,nlNL:()=>xA});var SA={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},xA={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var qe=x(w()),_A=(0,Ge.forwardRef)((e,t)=>{let n=k("TabCompletion",En);return(0,qe.jsx)("mark",{ref:t,className:(0,gd.default)(n.matchSelection)},"selection-start")}),wA=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let i=B(oh),s=k("TabCompletion",En),a=(0,Ge.useRef)(null),l=(0,Ge.useRef)(null),[u,c]=(0,Ge.useState)(null),p=U(),d=ld(document.activeElement===r),[h]=(0,Ge.useState)(()=>document.createRange());d.triggerRef.current=h,(0,Ge.useEffect)(()=>()=>h.detach(),[]),(0,Ge.useEffect)(()=>{let y=e.current,m=a.current;!y||!m||(h.setStart(y,0),h.setEnd(m,0))},[e.current,a.current]),Si(()=>{d.close()});let v=(0,Ge.useCallback)(y=>{let m=h.toString(),g=/^http(s?):\/\//.test(y)?y:`https://${y}`;p(ac({text:`[${m}](${g})`,replace:"selection"}))},[]);return(0,qe.jsxs)("span",{children:[(0,qe.jsx)("mark",{ref:a,className:(0,gd.default)(s.matchSelection),"aria-haspopup":"dialog","aria-expanded":d.opened?"true":"false",children:o}),d.opened&&(0,qe.jsx)(ud,{className:s.popoverRoot,triggerRef:d.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,qe.jsxs)(dd,{style:n,ref:l,children:[(0,qe.jsx)("div",{className:(0,gd.default)(s.selectionOptions,{[s.selectionOptionsIsHidden]:u!==null}),children:(0,qe.jsxs)("button",{type:"button",tabIndex:u===null?-1:void 0,className:s.selectionOptionsButton,onClick:()=>c("insertLink"),children:[(0,qe.jsx)(K1,{}),(0,qe.jsx)("span",{children:"\xA0"}),(0,qe.jsx)("span",{children:i("insertLink")})]})}),u==="insertLink"&&(0,qe.jsx)(q1,{placeholder:i("linkInputPlaceholder"),visitUrlText:i("visitUrl"),onSelectLink:v,onDismiss:()=>{c(null),d.close()}})]})})]},"selection-end")},hd=class extends wn{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(t,n){return this.props=n,this.charCount=0,this.startRef=(0,Ge.createRef)(),this.foundIndex=0,t}match(t){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[n,r]=this.props.selection;if(n===r)return null;let o=this.foundIndex===0?n:r,i=o>=this.charCount&&o<=this.charCount+t.length?{index:o-this.charCount,length:0,match:"",valid:!0}:null;i&&this.foundIndex++;let s=this.foundIndex===1;return i&&s?this.charCount+=o-this.charCount:this.charCount+=t.length,i?{isStart:s,...i}:null}replaceWith(t,n){return n.isStart?(0,qe.jsx)(_A,{ref:this.startRef}):(0,qe.jsx)(wA,{inputElement:n.inputElement,startRef:this.startRef,boundaryRef:n.boundaryRef,inputStyle:n.inputStyle})}asTag(){return"mark"}};var Mn=x(w()),bA=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:i,keywordMatches:s,inputElement:a,source:l})=>{let u=k("TabCompletion",N1),c=M("insertLink"),p=M("showMidSentenceSuggestions"),d=M("inlineSuggestions"),h=Dc(a),v=(0,Dn.useRef)(null);(0,Dn.useEffect)(()=>{Tr(a)&&h&&Fc(a,h)},[h]);let y=(0,Dn.useCallback)(f=>{if(!o||!n)return f;let S=[(0,Mn.jsx)("span",{className:u.resetIndent,children:"\u200B"},"u200B"),(0,Mn.jsx)("span",{"data-testid":"tab-completion",className:(0,yd.default)(u.tabText,u.resetIndent),"data-source":l,children:n},"tabText")];return r&&S.push((0,Mn.jsx)("span",{className:(0,yd.default)(u.hint,u.resetIndent),children:(0,Mn.jsx)(el,{keyCode:"tab"},"tabHint")})),Yg(f,S)},[o,n,r]),m=(0,Dn.useMemo)(()=>{let f=[];return c&&f.push(new hd("selection")),f.push(new yi("placeholders")),i&&f.push(new pd("keywords")),f},[d,c,i]),g=(0,Dn.useMemo)(()=>{let f=window.getComputedStyle(a);return{"--dd-color":f.color,"--dd-font-size":f.fontSize,"--dd-font-family":f.fontFamily,"--dd-font-variant":f.fontVariant}},[]);return e?(0,Mn.jsxs)("div",{ref:f=>{f!=null&&f.parentElement&&(v.current=f==null?void 0:f.parentElement)},className:u.root,style:g,children:[(0,Mn.jsx)(gi,{tagName:"span",containerTagName:"div",className:(0,yd.default)(u.container,u.agentText),disableLineBreaks:Tr(a),content:t||"\u200B",onAfterParse:y,matchers:m,selection:h,keywordMatches:s,inputElement:a,inputStyle:g,boundaryRef:v,inlineSuggestionsOnlyAtEnd:!p}),(0,Mn.jsx)("br",{})]}):null},EA=({input:e,ui:t,settings:n,styleSuggestions:r,conversation:o})=>{var y;let{tabCompletionSuggestion:i}=e,s=(i==null?void 0:i.text)||"",a=(i==null?void 0:i.source)||"",l=e.html??Ni(e.text),u=s.indexOf(e.text)===0?s.slice(e.text.length):"",{showTabHint:c}=t,{isSupported:p}=o,{showTabCompletion:d,visible:h,showStyleSuggestions:v}=n;return{showTabHint:c,showStyleSuggestions:v,showTabCompletion:d,content:l,tabText:u,source:a,keywordMatches:((y=r.list)==null?void 0:y.keywordMatches)??[],enabled:h&&p!==!1}},G1=xn(EA)(bA);var Db=x($()),Fb=x(O());var X1={list:[],fetchState:"idle",isInitialRequest:null},Y1=e=>e.autoflows.list||[],Q1=e=>t=>{var n;return(n=t.list)==null?void 0:n.find(r=>r.triggerPayload===e)},Fn=D("autoflows/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getAutoflows(e)}),ih=D("autoflows/start",async(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");await r.startAutoflowSession(e),await n(Fn(e.platformSessionId))}),sh=D("autoflows/stop",async(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");await r.stopAutoflowSession(e.platformSessionId),await n(Fn(e.platformSessionId))}),CA=j({name:"autoflows",initialState:X1,reducers:{},extraReducers:e=>{e.addCase(ih.pending,(t,n)=>{let r=Q1(n.meta.arg.triggerPayload)(t);r.state="Started",r.isBusy=!0}),e.addCase(sh.pending,(t,n)=>{let r=Q1(n.meta.arg.triggerPayload)(t);r.state="Aborted",r.isBusy=!0}),e.addCase(Fn.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}),e.addCase(Fn.rejected,t=>{t.fetchState="error"}),e.addCase(Fn.fulfilled,(t,n)=>{t.list=n.payload,t.fetchState="done"}),e.addCase(J,()=>X1)}}),Z1=D("autoflows/openStream",(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");let o=r.openStream(e);o.on("sessionAborted",()=>{n(Fn(e))}),o.on("sessionCompleted",()=>{n(Fn(e))})}),J1=D("autoflows/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),eb=CA.reducer;var tb={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},nb=e=>e.customMessages.list,rb=e=>t=>!!t.customMessages.sentSuggestions.find(n=>n===e),ob=e=>t=>!!t.customMessages.answeredSuggestions.find(n=>n===e),ib=e=>t=>!!t.customMessages.errorSuggestions.find(n=>n===e),Na=D("customMessages/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getCustomMessages(e)}),vd=D("customMessages/send",async(e,t)=>{let{platformSessionId:n,suggestion:r}=e,{deepdeskBrokerAPI:o}=t.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.sendCustomMessage(n,r)}),Sd=D("customMessages/answer",async(e,t)=>{let{platformSessionId:n,reply:r}=e,{deepdeskBrokerAPI:o}=t.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.answerCustomMessage(n,r)}),sb=j({name:"customMessages",initialState:tb,reducers:{onCustomMessage(e,t){Array.isArray(t.payload)?e.list=t.payload:e.list=[t.payload]}},extraReducers:e=>{e.addCase(Na.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(Na.rejected,t=>{t.fetchState="error"}).addCase(Na.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload||[]}).addCase(vd.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.errorSuggestions=t.errorSuggestions.filter(r=>n.meta.arg.suggestion.text!==r)}).addCase(vd.rejected,(t,n)=>{let r=t.sentSuggestions.indexOf(n.meta.arg.suggestion.text);t.errorSuggestions.push(...t.sentSuggestions.splice(r,1))}).addCase(Sd.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.answeredSuggestions.push(n.meta.arg.suggestion.text)}).addCase(Sd.rejected,(t,n)=>{let r=t.answeredSuggestions.indexOf(n.meta.arg.suggestion.text);t.errorSuggestions.push(...t.sentSuggestions.splice(r,1)),t.answeredSuggestions.splice(r,1)}).addCase(J,()=>tb)}}),ab=D("customMessages/openStream",(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");r.openStream(e).on("customMessageSuggestion",i=>{n(sb.actions.onCustomMessage(i))})}),lb=D("customMessages/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),ub=sb.reducer;var TA={jwt:null,accountUrl:null,interval:null},cb=e=>t=>{let{exchangeToken:{jwt:n,accountUrl:r}}=t;return n&&r?`${r}/apis/admin/session/jwt/?jwt=${n}&redirect=${e}`:null},ah=D("exchangeToken/getTemporaryExchangeToken",async(e,t)=>{let{deepdeskAPI:n}=t.extra,r=await n.getTemporaryExchangeToken();return{accountUrl:n.client.baseUrl,jwt:r}}),lh=D("exchangeToken/pollExchangeToken",(e={},t)=>{let{interval:n=1e3*60*30}=e,{dispatch:r}=t;return r(ah()),setInterval(()=>r(ah()),n)}),db=j({name:"exchangeToken",initialState:TA,reducers:{stopPollExchangeToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(ah.fulfilled,(t,n)=>{t.jwt=n.payload.jwt,t.accountUrl=n.payload.accountUrl}),e.addCase(lh.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollExchangeToken:pb}=db.actions,fb=db.reducer;function mb(e){let{customMessages:t,autoflows:n}=e;return n.fetchState==="loading"&&n.isInitialRequest===!0||t.fetchState==="loading"&&t.isInitialRequest===!0}var bb=x(O());var xb=x($()),_b=x(O());var hb=x($());var gb={root:"_root_838fd_1"};var vb=x(w()),kA=({className:e,children:t})=>{let n=k("Unicode",gb);return(0,vb.jsx)("span",{className:(0,hb.default)(e,n.root),children:t})},yb=kA;var Sb={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 uh={};Ie(uh,{enUS:()=>PA,nlNL:()=>RA});var PA={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"}]},RA={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 dt=x(w()),AA=({disabled:e,state:t,displayName:n,description:r,onStartAutoflow:o,onStopAutoflow:i})=>{let s=k("Autoflow",Sb),a=B(uh),l=t==="Started"?"stop":"start",u=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return(0,dt.jsxs)(oe,{className:(0,xb.default)(s.root,{[s.isDisabled]:e,[s.isCompleted]:t==="Completed",[s.isAborted]:t==="Aborted",[s.isStarted]:t==="Started"}),children:[(0,dt.jsx)(ge,{children:(0,dt.jsxs)(ge.Content,{children:[(0,dt.jsxs)(ge.Title,{children:[t&&(0,dt.jsx)("span",{className:s.stateBadge,children:a(t)}),n]}),(0,dt.jsx)("span",{children:r})]})}),(0,dt.jsx)(oe.Actions,{fixed:t==="Started",children:(0,dt.jsx)(oe.ActionButton,{primary:!0,className:l==="start"?s.buttonStart:s.buttonStop,onClick:t==="Started"?i:o,disabled:e,label:(0,dt.jsxs)(_b.Fragment,{children:[(0,dt.jsx)(yb,{children:u})," ",(0,dt.jsx)("span",{children:a(l)})]})})})]})},wb=AA;var ch=x(w()),LA=(e,t)=>{let n=t.filter(r=>r.state==="Started");return n.length>0?n.indexOf(e)===-1:!1},OA=({autoflows:e,onStartAutoflow:t,onStopAutoflow:n,platformSessionId:r})=>(0,ch.jsx)(bb.Fragment,{children:e.map(o=>(0,ch.jsx)(wb,{displayName:o.displayName,description:o.description,disabled:o.isBusy||LA(o,e),state:o.state,onStartAutoflow:()=>t({platformSessionId:r,triggerPayload:o.triggerPayload}),onStopAutoflow:()=>n({platformSessionId:r,triggerPayload:o.triggerPayload})},o.displayName))}),NA=({autoflows:e,conversation:t})=>{var n;return{autoflows:e.list,platformSessionId:(n=t.current)==null?void 0:n.sessionId}},MA={onStartAutoflow:ih,onStopAutoflow:sh},Eb=xn(NA,MA)(OA);var xd=x(O());var fh=x($());var dh=x(w()),ph=()=>(0,dh.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,dh.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 Cb={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 un=x(w()),DA=({entities:e})=>{let t=k("EntitiesWidgetList",Cb),[n,r]=(0,xd.useState)(void 0),o=U(),i=()=>{r(void 0)},s=a=>{e&&(r(e.indexOf(a)),ka(a.text),o(je({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,xd.useEffect)(()=>{let a=setTimeout(i,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,un.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,un.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>s(a),children:[(0,un.jsx)("span",{className:t.entityText,children:a.text}),(0,un.jsxs)("span",{className:t.iconWrapper,children:[(0,un.jsx)("span",{className:(0,fh.default)(t.icon),children:(0,un.jsx)(ph,{})}),(0,un.jsx)("span",{className:(0,fh.default)(t.icon,n===l&&t.iconClicked),children:(0,un.jsx)(ph,{})})]})]},a.text))})},Tb=DA;var kb=x($()),mh=x(O());var jn={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 rt=x(w()),FA=({suggestion:e})=>{let t=B(ao),n=U(),r=A(rb(e.text)),o=A(ob(e.text)),i=A(ib(e.text)),s=A(Ju),{replyOptions:a}=e,l=(0,mh.useCallback)(c=>{c.preventDefault(),c.stopPropagation(),!(r||!s)&&n(vd({platformSessionId:s,suggestion:e}))},[e,r,n,s]),u=(0,mh.useCallback)(c=>{if(c.preventDefault(),c.stopPropagation(),!s||!a)return;let p=parseInt(c.target.dataset.index,10),d=a[p];n(Sd({platformSessionId:s,reply:d,suggestion:e}))},[e,r,n,s]);return(0,rt.jsxs)(oe,{onClick:l,className:(0,kb.default)(jn.root,{[jn.isUsed]:r,[jn.hasError]:i}),children:[(0,rt.jsx)(ge,{children:(0,rt.jsxs)(ge.Content,{children:[(0,rt.jsxs)(ge.Title,{className:jn.title,children:[e.text," ",(0,rt.jsx)(tl,{className:jn.label,children:"analyse tool"})," ",i&&(0,rt.jsx)("span",{className:jn.errorIcon,role:"img","aria-label":t("sendingError"),title:t("sendingError"),children:"!"})]}),a&&a.length>0&&(0,rt.jsx)("ul",{className:jn.quickReplies,children:a.map(c=>(0,rt.jsx)("li",{className:jn.quickReply,children:c.title},c.title))})]})}),(0,rt.jsxs)(oe.Actions,{fixed:i||r,children:[a&&a.length>0&&(0,rt.jsx)(oe.DropdownButton,{label:t("answer"),disabled:o,children:a.map((c,p)=>(0,rt.jsx)(oe.DropdownItem,{index:p,label:c.title,onClick:u},c.title))}),(0,rt.jsx)(oe.ActionButton,{primary:!0,disabled:r,onClick:l,label:t(r?"suggestionSent":i?"tryAgain":"sendSuggestion")})]})]})},Pb=FA;var gh=x(w()),Rb=()=>(0,gh.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,gh.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 Ib=x(O());var pt=x(w()),jA=({suggestion:e,lines:t,onEdit:n,onUse:r})=>{var d;let o=e.text||e.url||e.message,i=qc(o),s=B(ao),a=M("showImages"),l=M("fallbackImage"),u=h=>{h.preventDefault(),h.stopPropagation(),r(o)},c=h=>{h.preventDefault(),h.stopPropagation(),n(e)},p=(0,Ib.useCallback)(h=>{window.open(i,"_blank"),h.stopPropagation(),h.preventDefault()},[i]);return(0,pt.jsxs)(oe,{onClick:u,"data-testid":"edit-suggestion",children:[(0,pt.jsxs)(ge,{children:[a&&e.image&&(0,pt.jsx)(ge.Image,{src:md(e,"small",l||void 0),title:e.title}),(0,pt.jsxs)(ge.Content,{children:[e.title&&(0,pt.jsx)(ge.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((d=e.searchKeywords)==null?void 0:d.length)>0&&(0,pt.jsx)(oe.Labels,{labels:e.searchKeywords}),(0,pt.jsx)(ge.Content,{cropText:t==="single",lineClamp:t==="multiple",children:o})]})]}),(0,pt.jsxs)(oe.Actions,{children:[i&&(0,pt.jsx)(oe.ActionButton,{onClick:p,label:s("visitUrl")}),(0,pt.jsx)(oe.ActionButton,{primary:!0,onClick:c,label:s("preview")}),(0,pt.jsx)(oe.ActionButton,{primary:!0,onClick:u,label:s("useSuggestion")})]})]})},Ab=jA;var Ma=x(w()),BA=({contentType:e,lines:t,suggestions:n})=>{let r=Pt(),o=A(Ei),i=a=>{r.send(Og,{state:o,suggestion:a,contentType:e})},s=(a,l)=>{r.send(In,{text:a,suggestion:{...l,source:l.source,sourceText:l.text}})};return(0,Ma.jsx)(Ma.Fragment,{children:n.map(a=>(0,Ma.jsx)(Ab,{suggestion:a,lines:t,onEdit:l=>i(l),onUse:l=>s(l,a)},a.text||a.url||a.message))})},Lb=BA;var hh={};Ie(hh,{enUS:()=>HA,nlNL:()=>zA});var HA={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"}]},zA={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:"Gesprek samenvatten"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}]};var Ob={root:"_root_x0pwe_1",loginText:"_loginText_x0pwe_7",stateText:"_stateText_x0pwe_8",sectionList:"_sectionList_x0pwe_20",shortcutList:"_shortcutList_x0pwe_24",shortcut:"_shortcut_x0pwe_24",link:"_link_x0pwe_52"};var yh=x(w()),Nb=()=>(0,yh.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,yh.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 vh=x(w()),Mb=()=>(0,vh.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,vh.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 K=x(w()),_d=(e,t)=>{let n=A(zt);(0,Fb.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},UA=()=>{let e=B(hh),t=U(),n=M("isEmbedded"),r=k("Widget",Ob),o=M("showAutoflows"),i=M("showCustomMessages"),s=M("showPersonalCollectionLink"),a=M("showSummaryCommand"),l=M("showKnowledgeSearch"),u=M("showSearch"),c=A(Ai),p=A(ed),d=A(Y1),h=A(Jc),v=A(nb),y=A(ec),m=A(di),g=A(zt),f=A(Ju),S=A(mb),_=A(Ei),b=Pt(),E=A(lw),C=A(cb("/admin/personal-collection")),R=M("adminUrl");if(_d(()=>(t(Na(f)),t(ab(f)),()=>{t(lb(f))}),[t,m,i,f]),_d(()=>(t(Fn(f)),t(Z1(f)),()=>{t(J1(f))}),[t,m,o,f]),_d(()=>{p.forEach(({type:N})=>{t(N==="entities"?Vt():Pn(N))})},[t,m,y,c]),_d(()=>(t(lh()),()=>{t(pb())}),[t,m,s,y]),m===!1)return(0,K.jsx)("div",{className:r.stateText,children:(0,K.jsx)("div",{children:(0,K.jsx)("p",{children:e("notSupported")})})},"supported");if(g===!1)return(0,K.jsx)("div",{className:r.loginText,children:(0,K.jsx)("div",{children:(0,K.jsx)(rd,{isEmbedded:n,loginUrl:R})})},"login");if(!c||!f||g===null||E||S)return(0,K.jsx)("div",{className:r.stateText,children:(0,K.jsx)("div",{children:(0,K.jsx)("p",{children:e("waiting")})})},"waiting");let P=u||a||l||C;return(0,K.jsx)("div",{className:(0,Db.default)(r.root),"data-testid":"widget",children:(0,K.jsxs)(nl,{className:r.sectionList,children:[P&&(0,K.jsx)(zn,{title:e("actions"),type:"shortcuts",children:(0,K.jsxs)("div",{className:r.shortcutList,children:[u&&(0,K.jsxs)("button",{className:r.shortcut,"data-testid":"shortcut-search",onClick:()=>b.send("ShowCommandPalette",{isOpen:!0}),children:[(0,K.jsx)(wi,{}),e("linkSearch")]}),a&&(0,K.jsxs)("button",{className:r.shortcut,"data-testid":"shortcut-summary",onClick:()=>b.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,K.jsx)(Mb,{}),e("linkSummary")]}),l&&(0,K.jsxs)("button",{className:r.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>b.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,K.jsx)(Nb,{}),e("linkKnowledgeSearch")]}),C&&(0,K.jsxs)("a",{className:r.shortcut,target:"_blank",href:C,"data-testid":"shortcut-personal-collection",rel:"noreferrer",children:[(0,K.jsx)(Rb,{}),e("linkPersonalcollection")]})]})}),i&&v.length>0&&(0,K.jsx)(zn,{type:"custom-messages","data-testid":"custom-messages",children:(0,K.jsx)(yt,{withDivider:!0,children:v.map(N=>(0,K.jsx)(Pb,{suggestion:N},N.text))})}),o&&d.length>0&&(0,K.jsx)(zn,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:(0,K.jsx)(yt,{withDivider:!0,children:(0,K.jsx)(Eb,{})})}),p.map(({type:N,title:H,amount:z,lines:Ue})=>{var cn;switch(N){case"entities":return h&&h.length>0&&(0,K.jsx)(zn,{type:N,title:H,"data-testid":`type-${N}`,children:(0,K.jsx)(Tb,{entities:h})},N);default:return((cn=_[N])==null?void 0:cn.fetchState)==="done"&&_[N].suggestions.length>0&&(0,K.jsx)(zn,{type:N,title:H,"data-testid":`type-${N}`,children:(0,K.jsx)(yt,{withDivider:!0,children:(0,K.jsx)(Lb,{lines:Ue,contentType:N,suggestions:_[N].suggestions.slice(0,z)||[]})})},N)}})]})})},jb=UA;function Bi(e){let t=new Range;return t.selectNodeContents(e),t}function Bb(e,t,n){try{return Rr(e,t,n),!0}catch{return!1}}function wd(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function bd(e){return"tagName"in e&&e.tagName==="BR"}var Da=/[\u200B-\u200D\uFEFF]/g;function Rr(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,i=!1;function s(l,u){let c=-1,p=/[\u200B-\u200D\uFEFF]/;if(!p.test(l))return u;for(let d=0;d<=l.length;d++)if(p.test(l[d])||c++,c===u)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let u=l.textContent,c=u.replace(Da,""),p=o+c.length,d=t>=o&&t<=p,h=n>=o&&n<=p;if(d){let v=s(u,t-o);v===0&&!h?r.setStartBefore(l):r.setStart(l,v)}h&&(r.setEnd(l,s(u,n-o)),i=!0),o=p;break}case Node.ELEMENT_NODE:{if(bd(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),i=!0;return}for(let c=0;c<l.childNodes.length&&(a(l.childNodes[c]),!i);c++);let u=l.lastChild;wd(l)&&u&&!wd(u)&&!bd(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function Fa(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a,l,u=0;function c(p){let d=p===n,h=p===o;switch(p.nodeType){case Node.TEXT_NODE:{let v=p.textContent;d&&(a=u+v.substring(0,r).replace(Da,"").length),h&&(l=u+v.substring(0,i).replace(Da,"").length),u+=v.replace(Da,"").length;break}case Node.ELEMENT_NODE:{let v=p.nextSibling===null;bd(p)&&!v&&u++;for(let y=0;y<p.childNodes.length;y++){let m=d&&y===r,g=h&&y===i;if(m&&(a=u),g&&(l=u),l!==void 0||((!m||!s)&&c(p.childNodes[y]),h&&y===i-1&&(l=u),l!==void 0))break}!h&&wd(p)&&!v&&u++,h&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a??l,end:l}}function ja(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i}=t,s=-1,a="";function l(u){let c=u===n,p=u===o;switch(c&&s++,u.nodeType){case Node.TEXT_NODE:{if(s!==0)return;let d=c?r:0,h=p?i:void 0,v=u.textContent.replace(Da,"");d===0&&h===void 0?a+=v:a+=v.substring(d,h);break}case Node.ELEMENT_NODE:{let d=u.nextSibling===null;s===0&&bd(u)&&!d&&(a+=`
20
20
  `);for(let h=c?r:0;h<(p?Math.min(i,u.childNodes.length):u.childNodes.length)&&(l(u.childNodes[h]),s!==1);h++);!p&&s===0&&wd(u)&&!d&&(a+=`
21
- `);break}default:break}p&&s++}return l(e),a}function Hb(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var mo=class extends Cn{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),ja(this.element,t)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let t=this.getRootNode();if(t.activeElement!==this.element)return null;let n="getSelection"in t?t.getSelection():window.getSelection();if(!n)return null;let r="getComposedRanges"in n&&t instanceof ShadowRoot?(i=n.getComposedRanges(t))==null?void 0:i[0]:n.rangeCount>0?n.getRangeAt(0):null;if(!r)return null;let o=this.element.ownerDocument.createRange();return o.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),o.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!o||!this.element.contains(o.startContainer)||!this.element.contains(o.endContainer)?null:o}getCaretPosition(){let t=this.getRange();if(!t||!t.collapsed||!("getBoundingClientRect"in t))return null;let n=t.getBoundingClientRect();return!Hb(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!Hb(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return Fa(this.element,t);let n=this.lastKnownSelection;if(n&&Bb(this.element,n.start,n.end))return n;let r=Bi(this.element);return r.collapse(!1),Fa(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return ja(this.element,Rr(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let t=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==t&&(t=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 Sh=class{constructor(t){this.name=t;this.broadcastChannel=new BroadcastChannel(t)}broadcastChannel;disposeHandlers=[];onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(t)}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},xh=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=this.createIframe(),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];createIframe(){let t=`deepdesk-iframe-${this.name}`,n=document.getElementById(t);if(n)return n;let r=document.createElement("iframe"),o=`${this.targetOrigin}/v2/widget/liveengage/channel.html`,i=new URLSearchParams({channel:this.name,host:window.location.origin});return this.options.debug&&i.set("debug","1"),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=t,r.title=`iframe-${this.name}`,r.src=`${o}?${i.toString()}`,r}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(t,this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},_h=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),V.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new xh(t,this.deepdeskUrl,{debug:!0}):new Sh(t),r=o=>{var i,s;o.origin===this.deepdeskUrl&&o.data.type==="event"&&o.data.channel===t&&(V.info("Received broadcast event",this.sessionId,o),(s=(i=this.eventMap)[o.data.name])==null||s.call(i,o.data.payload))};return n.onMessage(r),n}send(t,n){var o,i,s;if(!this.sessionId)return;V.info("broadcast event",{sessionId:this.sessionId,name:t,payload:n});let r={type:"event",name:t,payload:n};(i=(o=this.eventMap)[t])==null||i.call(o,n),(s=this.channel)==null||s.postMessage({...r,channel:this.sessionId})}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},zb=_h;var Hi=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var wh=e=>new Promise(t=>{setTimeout(t,e)});var zi=class extends Hi{name="ClientError"},bh=class extends Hi{name="ServerError"},Wt=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,{abortLatest:l=!1,attempts:u=1,retryDelay:c=500,refreshTokenOn401:p=!0,retryOnError:d=_=>_ instanceof TypeError,retryOnResponse:h=_=>_.status>=500,version:v="v1",...y}=n,m={credentials:"include",...y,headers:{"Content-Type":"application/json",...y.headers}};n.method!==void 0&&n.method!=="GET"&&this.csrfToken&&(m.headers={...m.headers,"X-CSRFToken":this.csrfToken}),typeof v=="string"&&(m.headers={...m.headers,"X-Deepdesk-API-Version":v});let g=u,f=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&l&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let S=async()=>(g--,a(s,m).then(async _=>h(_)&&!i.isAborted&&g>0?(await wh(c),S()):_.status===401&&p===!0&&f===!1?(f=!0,await this.refreshToken(),S()):_).catch(async _=>{if(d(_)&&!i.isAborted&&g>0)return await wh(c),S();throw _}));S().then(_=>_.json().catch(()=>null).then(b=>{_.status>=500?o(new bh("Server Error",b)):_.status===401?o(new zi("Unauthorized",b)):_.status===403?o(new zi("Forbidden",b)):_.status===404?o(new zi("Not Found",b)):_.status>=400&&o(new zi("Bad Request",b)),delete this.latestRequestByUrl[s],r(b)})).catch(_=>{o(_)})})}async validateToken(){let{has_valid_access_token:t}=await this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return e.refreshingToken||(e.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{e.refreshingToken=null},1e3*60)})),e.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,{method:"POST",body:JSON.stringify(n),...r})}patch(t,n,r){return this.request(t,{method:"PATCH",body:JSON.stringify(n),...r})}put(t,n,r){return this.request(t,{method:"PUT",body:JSON.stringify(n),...r})}delete(t,n){return this.request(t,{method:"DELETE",...n})}};var VA;(t=>{let e;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||={})})(VA||={});function Ed(e){return{...re(e),tags:e.tags}}var Bn=class e{constructor(t,n={}){this.options=n;this.client=new Wt(t,{fetch:n.fetch}),this.client.patchFetch(r=>async(o,i)=>{let s=await r(o,i);return this.handleDeepdeskVersionHeaders(s),s})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=await this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(e.exchangeTokenPromise||(e.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),e.exchangeTokenPromise):Promise.resolve()}async createConversation(t){await this.preflight(),V.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...be(t),tags:t.tags},{version:"v2"});return Ed(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null});return re(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null});return re(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null});return re(t)}async checkUserExists(t){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n}async getConversationBySessionId(t,n={}){await this.preflight(),V.info(`Getting conversation for session ${t}`);let{attempts:r=1,retryDelay:o=1e3}=n,i=await this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"});return Ed(i)}async isConversationSupported(t,n={}){V.info(`Check if conversation for session ${t} is supported`);let{attempts:r=1,retryDelay:o=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"})).has_active_profile}async updateConversation(t,n){let r=be(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Ed(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...be(o),tags:o.tags})),{version:"v2"})).map(o=>Ed(o))}async sendEvent(t,n){let{data:r,...o}=n,i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[a,l])=>({...s,[a]:l}),{});return this.client.post("/api/events",be({...i,...o,data:r,name:t}),{version:"v2"})}async sendEventV1(t,n){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>({...o,[i]:s}),{});return this.client.post("/api/events",{event:t,data:be({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){return(await this.client.post("/api/summary",{conversation:{messages:t.filter(o=>o.text&&o.source)},prompt_instruction:n.promptInstruction,model:n.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(t){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw V.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.client.post("/apis/admin/session/api-key/",be(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})}async getTextSuggestions(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(await this.client.post(`/api/conversations/${t}/recommend/${r}`,be(n),{abortLatest:!0})).map(i=>({...re(i),text:i.text||i.url||i.message,source:r,type:r})).filter((i,s,a)=>s===a.findIndex(l=>l.text===i.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(t,n){return(await this.client.post(`/api/conversations/${t}/autocomplete`,be(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))}async getPinnedMessages(t){let n=await this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return re(n).map(r=>({...r,text:r.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(t){let n=await this.client.post("/api/style-suggestions",be(t),{abortLatest:!0});return re(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,be(t),{version:"v2"});return re(n)}async knowledgeAssist(t,n,r){let o=await this.client.post("/api/knowledge-search/search",be({question:t.question,promptInstruction:t.promptInstruction,profile:r,chatHistory:n.map(i=>({question:i.question,answer:i.answer.answer}))}),{version:"v2"});return re(o)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return re(n)}async getCsrfToken(){let{token:t}=await this.client.get("/apis/admin/session/csrf/",{version:null});return t}async verifyLoginToken(t){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return re(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(hy);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&V.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var Ba=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(Tg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,re(o))}catch{V.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var KA;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(KA||={});var Ha=class{constructor(t,n={}){this.apiUrl=t;this.client=new Wt(t,n)}client;streams={};logger=V;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return re(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,be(n));return re(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,be(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return re(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",be(t));return re(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new Ba(`${this.apiUrl}/sessions/${t}/events`),this.streams[t].connect()),this.streams[t]}closeStream(t){this.streams[t]||(this.streams[t].disconnect(),delete this.streams[t])}};var Ub={startTime:null,stopTime:null},Vb=j({name:"handlingTime",initialState:Ub,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(J,()=>Ub)}}),{handlingTimeStart:Kb,handlingTimeStop:Cd,handlingTimeReset:Wb}=Vb.actions,$b=Vb.reducer;var qb=(e={})=>{let t={onAuthError:ki(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Td={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var go=D("styleSuggestions/getAll",async({text:e},t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),{showStyleSuggestions:o}=r.settings,i=(s=r.conversation.current)==null?void 0:s.profileCode;if(!o)return Td.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),WA=j({name:"styleSuggestions",initialState:Td,reducers:{},extraReducers:e=>{e.addCase(go.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(go.rejected,t=>{t.fetchState="error"}).addCase(go.fulfilled,(t,n)=>{t.fetchState="done",mr(t.list,n.payload)||(t.list=n.payload)}).addCase(Zr,t=>{t.list=Td.list}).addCase(J,()=>Td)}}),Gb=WA.reducer;var Xb=(e={})=>{let t,n=!0,r={getStyleSuggestions:go,debounce:500,...e};return o=>i=>s=>{var h;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((h=u.conversation.current)==null?void 0:h.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function $A(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var Qb=(e={})=>{let t={getTextSuggestions:Pn,getAutocompleteSuggestions:_a,debounce:200,check:Oi,...e},n;return r=>o=>i=>{var y;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,p=(y=l.conversation.current)==null?void 0:y.id,d=i.type===Qc.toString();if(!p||!u&&!c)return a;let{input:{userCommitted:h}}=l;return $A(h,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let m=pi(l);m===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(m))},d?0:t.debounce)),a}};var Yb=go.fulfilled.toString();function qA(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var Zb=e=>t=>n=>r=>{var u;if(r.type!==Yb){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=qA(o,s);r.type===Yb&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var GA=bu({activeSuggestion:vw,answer:l1,auth:Aw,autoflows:eb,conversation:jx,contentTypes:$w,customMessages:ub,exchangeToken:fb,entities:Qw,handlingTime:$b,info:W_,input:Km.reducer,overlayInput:Je.reducer,settings:Rx,profile:d1,search:Y_,summary:n1,styleSuggestions:Gb,ui:ww,textSuggestions:fw});function Jb(e){return M0({reducer:GA,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),qb(),Qb({debounce:200}),Xb({debounce:500}),Zb(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var XA=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},QA=e=>t=>n=>r=>{var a;let o=t.getState(),i=jm("inlineSuggestions")(o);switch(r.type){case Rn.toString():{let l=aw(r.payload.contentType)(t.getState()),u=l.indexOf(r.payload.suggestion);e.emit("edit-suggestion",{contentType:r.payload.contentType,index:u,suggestions:l});break}case ki.toString():{!r.payload&&e.emit("logout",void 0);break}case Ft.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",{type:XA(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case ac.toString():{let{start:l,end:u}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case ra.toString():{let l=t.getState(),{text:u,selection:c}=l.input.userCommitted;e.emit("reset",{text:u,selectionAfter:c},{mayApplyChanges:!0});break}case dc.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:o.conversation.current.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Vt.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:o.conversation.current.id,data:{entities:r.payload}});break;case An.fulfilled.toString():e.sendEvent("conversation summarized",{conversationId:o.conversation.current.id,data:{summary:r.payload.summary}});break;case je.toString():e.sendEvent(r.payload.name,{conversationId:((a=r.payload.options)==null?void 0:a.includeConversationData)&&o.conversation.current.id,data:r.payload.data});break;case lc.toString():e.handleKeyDown(r.payload);break;case Zr.toString():e.logSendMessage(r.payload);break;case uc.toString():e.logSendEditSuggestionMessage(r.payload);break;case cc.toString():e.handleInputChanged(r.payload);break;default:break}let s=n(r);switch(r.type){case Zr.toString():e.handleAfterSendMessage(r.payload);break;case wa.toString():e.onUpdateShowTabHint(r.payload);break;case Cd.toString():e.logHandlingTime();break;case Ft.toString():{i&&(t.dispatch(on([])),t.dispatch(yr()));break}case on.toString():{i&&r.payload.length>0&&t.dispatch(hr(0));break}default:break}return s},eE=QA;function Eh(e){return e.toISOString().replace("T"," ").replace("Z","")}function tE(e,t){var o,i,s;let{startTime:n,stopTime:r}=e.handlingTime;if(!n||!r)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:e.conversation.current.id,clientVersion:t.version,agentId:(o=e.info.agentInfo)==null?void 0:o.agentId,agentName:(i=e.info.agentInfo)==null?void 0:i.agentName,agentEmail:(s=e.info.agentInfo)==null?void 0:s.agentEmail,timeStart:Eh(n),timeStop:Eh(r)}}function Ch(e,t,n){var C,R,P;let{text:r,metrics:{numCharsTyped:o,numCharsPasted:i,numCharsCut:s,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:u,externalTimeTotalSeconds:c,pastes:p,cuts:d,deletions:h,textSuggestions:v,offeredTextSuggestions:y}}=t[e],m=r.length,f=v.reduce((N,{text:H,searchTerm:z})=>N+H.length-(z?z.length:0),0),S=u??Date.now(),_=(Date.now()-S)/1e3+(c||0),b=o/_,E=v.reduce((N,{searchTerm:H})=>N+(H?H.length:0),0);return{conversationId:t.conversation.current.id,source:"agent",text:r,clientVersion:n.version,pastes:p,cuts:d,deletions:h,lenTextTyped:o+E,lenTextTotal:m,lenTextAssisted:f,lenTextPasted:i,lenTextCut:s,lenTextDeleted:a,timeTotalSeconds:_,charsPerSecond:b,numPastes:l,textSuggestionsV2:v,suggestionsCounters:[{source:"gpt",countOffered:y.filter(N=>N.source==="gpt").length}],agentId:(C=t.info.agentInfo)==null?void 0:C.agentId,agentName:(R=t.info.agentInfo)==null?void 0:R.agentName,agentEmail:(P=t.info.agentInfo)==null?void 0:P.agentEmail}}function nE(e,t){let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;return r instanceof HTMLElement?nE(r,t):null}function rE(e,t){return nE(e,t)}function oE(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function YA(e){return typeof e=="object"&&e!==null&&"tagName"in e}function kd(e){return YA(e)&&(Tr(e)||Mc(e))}var iE=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch{return t}}catch{return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch{V.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function ZA(e){return e.offsetParent!==null}function sE(e){if(!ZA(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function Pd(e,t,n=100){let r=sE(e);t({isVisible:r});let o=setInterval(()=>{let i=sE(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var ze=x(w()),aE=iE("showTabHint",!0),za=class e{static version="10.4.1-beta.2";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new Bn(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[eE({emit:(p,d,h)=>this.emit(p,d,h),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),logSendEditSuggestionMessage:p=>this.logSendEditMessage(p),onUpdateShowTabHint:p=>aE.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Ha(n)}),this.store=Jb(c),this.broadcastEvents=new zb({debug:!0,deepdeskUrl:u,eventMap:Lw(this.store),createCustomChannel:l}),this.store.dispatch(ta),this.store.dispatch(wa(aE.value())),this.store.dispatch(ta({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(V.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(V.warn("Profile has not been loaded (yet)"),!0):(V.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(ki(null)),this.store.dispatch(br()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();zt(r)&&Cw(r)!=="loading"&&t()});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return this.deepdeskApi.isLoggedIn()}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){V.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Um({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(tc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(nc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Vm(t))).payload}async postMessages(t){return(await this.store.dispatch(oc(t))).payload}async updateConversation(t){return(await this.store.dispatch(rc(t))).payload}resetConversation(){this.store.dispatch(J()),this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(An());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(ta(t))}setVisitorInfo(t){this.store.dispatch(K_(t))}async setAgentInfo(t){await this.store.dispatch(ya(t))}async setAgentSettings(t){await this.store.dispatch(kg(t))}async getAgentSettings(){return(await this.store.dispatch(Pg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(Qc()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(cc(t))}notifyKeyDown(t){this.store.dispatch(lc(t))}notifyPaste(t,n){this.store.dispatch(Xx({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(qx(t))}notifyExternalSuggestion(t){this.store.dispatch(Ft(t)),this.store.dispatch(yr())}notifyEditSuggestion(t){this.store.dispatch(dw(t.contentType,t.suggestions)),this.store.dispatch(Rn({contentType:t.contentType,suggestion:typeof t.index=="number"?t.suggestions[t.index]:null}))}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(wr({collapse:!1})),this.inputMediator&&this.store.dispatch(zx({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(on([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(Gx(sc(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(Kx()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{if(n||!a||!i||t.shiftKey)return;this.store.dispatch($x());let{selectedSuggestionIndex:p}=this.state.input;t.preventDefault(),!s&&(p===-1?this.store.dispatch(ra()):this.stageSelectedSuggestion({inputType:"arrow"}))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(hr(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(hr(-1)),this.store.dispatch(ra()),t.preventDefault()):n||(this.store.dispatch(wr({collapse:!0})),this.store.dispatch(xw(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:h}=this.state.input;this.store.dispatch(wa(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&h&&h.text.startsWith(d)&&(this.store.dispatch(Ft({text:h.text,suggestion:h,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(yr())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Qx()),this.store.dispatch(on([]))}handlingTimeStart(){this.state.handlingTime.startTime||(V.info("Start handling time"),this.store.dispatch(Kb()))}handlingTimeStop(){this.state.handlingTime.startTime&&(V.info("Stop handling time"),this.store.dispatch(Cd()))}logSendMessage(t){let n=Ch("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logSendEditMessage(t){let n=Ch("overlayInput",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.store.dispatch(Vx(this.state.overlayInput.metrics))}logHandlingTime(){let t=tE(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(Wb())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(yr()),this.store.dispatch(Zr(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Ft({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){V.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),V.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=oo(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,$t.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=oo(i,{appendTo:document.body});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,$t.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return ro(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,$t.unmountComponentAtNode)(o),o.remove()}),o}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!kd(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:d,insertLink:h,inputMediator:v,closestScrollSelector:y,appendOverlayTo:m,inlineSuggestions:g}=n;if(this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:h,isEmbedded:p,inlineSuggestions:g}),n.automaticHandlingTime&&this.setupHandlingTime(t),ro(t),this.inputMediator=v||(Tr(t)?new Tn(t):new mo(t)),this.inputMediator.on("change",({plainText:S})=>{this.notifyInputChanged(S)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Yx({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",S=>{this.notifyKeyDown(S)}),this.inputMediator.on("paste",({pastedText:S,selectionText:_})=>{this.notifyPaste(S,_)}),this.inputMediator.on("cut",({selectionText:S})=>{this.notifyCut(S)}),g){if(Tr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let S=this.createInlineContainer(t,"deepdesk-caret");(0,$t.render)((0,ze.jsx)(Fi,{store:this.store,customStyles:r,children:(0,ze.jsx)(Ti,{broadcastEvents:this.broadcastEvents,children:(0,ze.jsx)(E1,{})})}),S),this.inputMediator.on("caret",_=>{this.store.dispatch(on([])),_?(S.style.display="block",S.style.top=`${_.top}px`,S.style.left=`${_.left}px`):S.style.display="none"})}else{let S=y&&rE(t,y)||void 0,_=this.overlayContainerFactory("deepdesk-tab-completion",S||t,{appendTo:m,closestScrollElement:S,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),b=this.overlayContainerFactory("deepdesk-suggestions-overlay",S||t,{appendTo:m},r==null?void 0:r.suggestionsRootNode);(0,$t.render)((0,ze.jsx)(Fi,{store:this.store,customStyles:r,children:(0,ze.jsx)(Ti,{broadcastEvents:this.broadcastEvents,children:(0,ze.jsx)(G1,{inputElement:t})})}),_),(0,$t.render)((0,ze.jsx)(Fi,{store:this.store,customStyles:r,children:(0,ze.jsx)(Ti,{broadcastEvents:this.broadcastEvents,children:(0,ze.jsx)(L1,{})})}),b)}(0,$t.render)((0,ze.jsx)(Fi,{store:this.store,customStyles:r,children:(0,ze.jsx)(Ti,{broadcastEvents:this.broadcastEvents,children:(0,ze.jsx)(h1,{})})}),this.createContainer("deepdesk-overlays"));let f;this.inputMediator.on("selection",S=>{clearTimeout(f),S===null?f=setTimeout(()=>{S!==null&&this.store.dispatch(Wm(S))},500):this.store.dispatch(Wm(S))}),this.inputMediator.on("disabled",()=>{var S;(S=this.inputMediator)==null||S.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Ci(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Ci(!0))),this.store.dispatch(Ux({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.whenConversationLoaded(()=>{var S;this.refresh(),this.broadcastEvents.setSessionId((S=this.state.conversation.current)==null?void 0:S.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&V.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,showPersonalCollectionLink:i,isEmbedded:s}=n;this.widgetRoot=t,this.configure({showImages:o,showPersonalCollectionLink:i,isEmbedded:s}),(0,$t.render)((0,ze.jsx)(Fi,{store:this.store,customStyles:r,children:(0,ze.jsx)(Ti,{broadcastEvents:this.broadcastEvents,children:(0,ze.jsx)(jb,{})})}),t),this.whenConversationLoaded(()=>{var a;this.broadcastEvents.setSessionId((a=this.state.conversation.current)==null?void 0:a.sessionId)})}unmountWidget(){this.widgetRoot&&(0,$t.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Pd(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){oE(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Ia());let t=Ai(this.state);t&&this.store.dispatch(ta({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:t.knowledgeAssistForAgents,recommendTextSuggestions:t.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(V.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;V.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=ed(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(Vt()):this.store.dispatch(Pn(r))})}catch(r){this.handleError(r)}}};async function lE(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function uE(e,t,n={}){let r=n.replace?Rr(e,n.replace.start,n.replace.end):Bi(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
21
+ `);break}default:break}p&&s++}return l(e),a}function Hb(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var mo=class extends Cn{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),ja(this.element,t)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let t=this.getRootNode();if(t.activeElement!==this.element)return null;let n="getSelection"in t?t.getSelection():window.getSelection();if(!n)return null;let r="getComposedRanges"in n&&t instanceof ShadowRoot?(i=n.getComposedRanges(t))==null?void 0:i[0]:n.rangeCount>0?n.getRangeAt(0):null;if(!r)return null;let o=this.element.ownerDocument.createRange();return o.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),o.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!o||!this.element.contains(o.startContainer)||!this.element.contains(o.endContainer)?null:o}getCaretPosition(){let t=this.getRange();if(!t||!t.collapsed||!("getBoundingClientRect"in t))return null;let n=t.getBoundingClientRect();return!Hb(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!Hb(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return Fa(this.element,t);let n=this.lastKnownSelection;if(n&&Bb(this.element,n.start,n.end))return n;let r=Bi(this.element);return r.collapse(!1),Fa(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return ja(this.element,Rr(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let t=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==t&&(t=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 Sh=class{constructor(t){this.name=t;this.broadcastChannel=new BroadcastChannel(t)}broadcastChannel;disposeHandlers=[];onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(t)}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},xh=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=this.createIframe(),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];createIframe(){let t=`deepdesk-iframe-${this.name}`,n=document.getElementById(t);if(n)return n;let r=document.createElement("iframe"),o=`${this.targetOrigin}/v2/widget/liveengage/channel.html`,i=new URLSearchParams({channel:this.name,host:window.location.origin});return this.options.debug&&i.set("debug","1"),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=t,r.title=`iframe-${this.name}`,r.src=`${o}?${i.toString()}`,r}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(t,this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},_h=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),V.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new xh(t,this.deepdeskUrl,{debug:!0}):new Sh(t),r=o=>{var i,s;o.origin===this.deepdeskUrl&&o.data.type==="event"&&o.data.channel===t&&(V.info("Received broadcast event",this.sessionId,o),(s=(i=this.eventMap)[o.data.name])==null||s.call(i,o.data.payload))};return n.onMessage(r),n}send(t,n){var o,i,s;if(!this.sessionId)return;V.info("broadcast event",{sessionId:this.sessionId,name:t,payload:n});let r={type:"event",name:t,payload:n};(i=(o=this.eventMap)[t])==null||i.call(o,n),(s=this.channel)==null||s.postMessage({...r,channel:this.sessionId})}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},zb=_h;var Hi=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var wh=e=>new Promise(t=>{setTimeout(t,e)});var zi=class extends Hi{name="ClientError"},bh=class extends Hi{name="ServerError"},Wt=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,{abortLatest:l=!1,attempts:u=1,retryDelay:c=500,refreshTokenOn401:p=!0,retryOnError:d=_=>_ instanceof TypeError,retryOnResponse:h=_=>_.status>=500,version:v="v1",...y}=n,m={credentials:"include",...y,headers:{"Content-Type":"application/json",...y.headers}};n.method!==void 0&&n.method!=="GET"&&this.csrfToken&&(m.headers={...m.headers,"X-CSRFToken":this.csrfToken}),typeof v=="string"&&(m.headers={...m.headers,"X-Deepdesk-API-Version":v});let g=u,f=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&l&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let S=async()=>(g--,a(s,m).then(async _=>h(_)&&!i.isAborted&&g>0?(await wh(c),S()):_.status===401&&p===!0&&f===!1?(f=!0,await this.refreshToken(),S()):_).catch(async _=>{if(d(_)&&!i.isAborted&&g>0)return await wh(c),S();throw _}));S().then(_=>_.json().catch(()=>null).then(b=>{_.status>=500?o(new bh("Server Error",b)):_.status===401?o(new zi("Unauthorized",b)):_.status===403?o(new zi("Forbidden",b)):_.status===404?o(new zi("Not Found",b)):_.status>=400&&o(new zi("Bad Request",b)),delete this.latestRequestByUrl[s],r(b)})).catch(_=>{o(_)})})}async validateToken(){let{has_valid_access_token:t}=await this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return e.refreshingToken||(e.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{e.refreshingToken=null},1e3*60)})),e.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,{method:"POST",body:JSON.stringify(n),...r})}patch(t,n,r){return this.request(t,{method:"PATCH",body:JSON.stringify(n),...r})}put(t,n,r){return this.request(t,{method:"PUT",body:JSON.stringify(n),...r})}delete(t,n){return this.request(t,{method:"DELETE",...n})}};var VA;(t=>{let e;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||={})})(VA||={});function Ed(e){return{...re(e),tags:e.tags}}var Bn=class e{constructor(t,n={}){this.options=n;this.client=new Wt(t,{fetch:n.fetch}),this.client.patchFetch(r=>async(o,i)=>{let s=await r(o,i);return this.handleDeepdeskVersionHeaders(s),s})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=await this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(e.exchangeTokenPromise||(e.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),e.exchangeTokenPromise):Promise.resolve()}async createConversation(t){await this.preflight(),V.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...be(t),tags:t.tags},{version:"v2"});return Ed(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null});return re(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null});return re(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null});return re(t)}async checkUserExists(t){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n}async getConversationBySessionId(t,n={}){await this.preflight(),V.info(`Getting conversation for session ${t}`);let{attempts:r=1,retryDelay:o=1e3}=n,i=await this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"});return Ed(i)}async isConversationSupported(t,n={}){V.info(`Check if conversation for session ${t} is supported`);let{attempts:r=1,retryDelay:o=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"})).has_active_profile}async updateConversation(t,n){let r=be(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Ed(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...be(o),tags:o.tags})),{version:"v2"})).map(o=>Ed(o))}async sendEvent(t,n){let{data:r,...o}=n,i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[a,l])=>({...s,[a]:l}),{});return this.client.post("/api/events",be({...i,...o,data:r,name:t}),{version:"v2"})}async sendEventV1(t,n){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>({...o,[i]:s}),{});return this.client.post("/api/events",{event:t,data:be({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){return(await this.client.post("/api/summary",{conversation:{messages:t.filter(o=>o.text&&o.source)},prompt_instruction:n.promptInstruction,model:n.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(t){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw V.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.client.post("/apis/admin/session/api-key/",be(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})}async getTextSuggestions(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(await this.client.post(`/api/conversations/${t}/recommend/${r}`,be(n),{abortLatest:!0})).map(i=>({...re(i),text:i.text||i.url||i.message,source:r,type:r})).filter((i,s,a)=>s===a.findIndex(l=>l.text===i.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(t,n){return(await this.client.post(`/api/conversations/${t}/autocomplete`,be(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))}async getPinnedMessages(t){let n=await this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return re(n).map(r=>({...r,text:r.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(t){let n=await this.client.post("/api/style-suggestions",be(t),{abortLatest:!0});return re(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,be(t),{version:"v2"});return re(n)}async knowledgeAssist(t,n,r){let o=await this.client.post("/api/knowledge-search/search",be({question:t.question,promptInstruction:t.promptInstruction,profile:r,chatHistory:n.map(i=>({question:i.question,answer:i.answer.answer}))}),{version:"v2"});return re(o)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return re(n)}async getCsrfToken(){let{token:t}=await this.client.get("/apis/admin/session/csrf/",{version:null});return t}async verifyLoginToken(t){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return re(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(hy);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&V.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var Ba=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(Tg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,re(o))}catch{V.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var KA;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(KA||={});var Ha=class{constructor(t,n={}){this.apiUrl=t;this.client=new Wt(t,n)}client;streams={};logger=V;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return re(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,be(n));return re(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,be(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return re(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",be(t));return re(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new Ba(`${this.apiUrl}/sessions/${t}/events`),this.streams[t].connect()),this.streams[t]}closeStream(t){this.streams[t]||(this.streams[t].disconnect(),delete this.streams[t])}};var Ub={startTime:null,stopTime:null},Vb=j({name:"handlingTime",initialState:Ub,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(J,()=>Ub)}}),{handlingTimeStart:Kb,handlingTimeStop:Cd,handlingTimeReset:Wb}=Vb.actions,$b=Vb.reducer;var qb=(e={})=>{let t={onAuthError:ki(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Td={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var go=D("styleSuggestions/getAll",async({text:e},t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),{showStyleSuggestions:o}=r.settings,i=(s=r.conversation.current)==null?void 0:s.profileCode;if(!o)return Td.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),WA=j({name:"styleSuggestions",initialState:Td,reducers:{},extraReducers:e=>{e.addCase(go.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(go.rejected,t=>{t.fetchState="error"}).addCase(go.fulfilled,(t,n)=>{t.fetchState="done",mr(t.list,n.payload)||(t.list=n.payload)}).addCase(Zr,t=>{t.list=Td.list}).addCase(J,()=>Td)}}),Gb=WA.reducer;var Xb=(e={})=>{let t,n=!0,r={getStyleSuggestions:go,debounce:500,...e};return o=>i=>s=>{var h;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((h=u.conversation.current)==null?void 0:h.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function $A(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var Qb=(e={})=>{let t={getTextSuggestions:Pn,getAutocompleteSuggestions:_a,debounce:200,check:Oi,...e},n;return r=>o=>i=>{var y;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,p=(y=l.conversation.current)==null?void 0:y.id,d=i.type===Qc.toString();if(!p||!u&&!c)return a;let{input:{userCommitted:h}}=l;return $A(h,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let m=pi(l);m===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(m))},d?0:t.debounce)),a}};var Yb=go.fulfilled.toString();function qA(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var Zb=e=>t=>n=>r=>{var u;if(r.type!==Yb){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=qA(o,s);r.type===Yb&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var GA=bu({activeSuggestion:vw,answer:l1,auth:Aw,autoflows:eb,conversation:jx,contentTypes:$w,customMessages:ub,exchangeToken:fb,entities:Qw,handlingTime:$b,info:W_,input:Km.reducer,overlayInput:Je.reducer,settings:Rx,profile:d1,search:Y_,summary:n1,styleSuggestions:Gb,ui:ww,textSuggestions:fw});function Jb(e){return M0({reducer:GA,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),qb(),Qb({debounce:200}),Xb({debounce:500}),Zb(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var XA=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},QA=e=>t=>n=>r=>{var a;let o=t.getState(),i=jm("inlineSuggestions")(o);switch(r.type){case Rn.toString():{let l=aw(r.payload.contentType)(t.getState()),u=l.indexOf(r.payload.suggestion);e.emit("edit-suggestion",{contentType:r.payload.contentType,index:u,suggestions:l});break}case ki.toString():{!r.payload&&e.emit("logout",void 0);break}case Ft.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",{type:XA(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case ac.toString():{let{start:l,end:u}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case ra.toString():{let l=t.getState(),{text:u,selection:c}=l.input.userCommitted;e.emit("reset",{text:u,selectionAfter:c},{mayApplyChanges:!0});break}case dc.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:o.conversation.current.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Vt.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:o.conversation.current.id,data:{entities:r.payload}});break;case An.fulfilled.toString():e.sendEvent("conversation summarized",{conversationId:o.conversation.current.id,data:{summary:r.payload.summary}});break;case je.toString():e.sendEvent(r.payload.name,{conversationId:((a=r.payload.options)==null?void 0:a.includeConversationData)&&o.conversation.current.id,data:r.payload.data});break;case lc.toString():e.handleKeyDown(r.payload);break;case Zr.toString():e.logSendMessage(r.payload);break;case uc.toString():e.logSendEditSuggestionMessage(r.payload);break;case cc.toString():e.handleInputChanged(r.payload);break;default:break}let s=n(r);switch(r.type){case Zr.toString():e.handleAfterSendMessage(r.payload);break;case wa.toString():e.onUpdateShowTabHint(r.payload);break;case Cd.toString():e.logHandlingTime();break;case Ft.toString():{i&&(t.dispatch(on([])),t.dispatch(yr()));break}case on.toString():{i&&r.payload.length>0&&t.dispatch(hr(0));break}default:break}return s},eE=QA;function Eh(e){return e.toISOString().replace("T"," ").replace("Z","")}function tE(e,t){var o,i,s;let{startTime:n,stopTime:r}=e.handlingTime;if(!n||!r)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:e.conversation.current.id,clientVersion:t.version,agentId:(o=e.info.agentInfo)==null?void 0:o.agentId,agentName:(i=e.info.agentInfo)==null?void 0:i.agentName,agentEmail:(s=e.info.agentInfo)==null?void 0:s.agentEmail,timeStart:Eh(n),timeStop:Eh(r)}}function Ch(e,t,n){var C,R,P;let{text:r,metrics:{numCharsTyped:o,numCharsPasted:i,numCharsCut:s,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:u,externalTimeTotalSeconds:c,pastes:p,cuts:d,deletions:h,textSuggestions:v,offeredTextSuggestions:y}}=t[e],m=r.length,f=v.reduce((N,{text:H,searchTerm:z})=>N+H.length-(z?z.length:0),0),S=u??Date.now(),_=(Date.now()-S)/1e3+(c||0),b=o/_,E=v.reduce((N,{searchTerm:H})=>N+(H?H.length:0),0);return{conversationId:t.conversation.current.id,source:"agent",text:r,clientVersion:n.version,pastes:p,cuts:d,deletions:h,lenTextTyped:o+E,lenTextTotal:m,lenTextAssisted:f,lenTextPasted:i,lenTextCut:s,lenTextDeleted:a,timeTotalSeconds:_,charsPerSecond:b,numPastes:l,textSuggestionsV2:v,suggestionsCounters:[{source:"gpt",countOffered:y.filter(N=>N.source==="gpt").length}],agentId:(C=t.info.agentInfo)==null?void 0:C.agentId,agentName:(R=t.info.agentInfo)==null?void 0:R.agentName,agentEmail:(P=t.info.agentInfo)==null?void 0:P.agentEmail}}function nE(e,t){let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;return r instanceof HTMLElement?nE(r,t):null}function rE(e,t){return nE(e,t)}function oE(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function YA(e){return typeof e=="object"&&e!==null&&"tagName"in e}function kd(e){return YA(e)&&(Tr(e)||Mc(e))}var iE=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch{return t}}catch{return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch{V.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function ZA(e){return e.offsetParent!==null}function sE(e){if(!ZA(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function Pd(e,t,n=100){let r=sE(e);t({isVisible:r});let o=setInterval(()=>{let i=sE(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var ze=x(w()),aE=iE("showTabHint",!0),za=class e{static version="10.5.0";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new Bn(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[eE({emit:(p,d,h)=>this.emit(p,d,h),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),logSendEditSuggestionMessage:p=>this.logSendEditMessage(p),onUpdateShowTabHint:p=>aE.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Ha(n)}),this.store=Jb(c),this.broadcastEvents=new zb({debug:!0,deepdeskUrl:u,eventMap:Lw(this.store),createCustomChannel:l}),this.store.dispatch(ta),this.store.dispatch(wa(aE.value())),this.store.dispatch(ta({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(V.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(V.warn("Profile has not been loaded (yet)"),!0):(V.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(ki(null)),this.store.dispatch(br()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();zt(r)&&Cw(r)!=="loading"&&t()});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return this.deepdeskApi.isLoggedIn()}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){V.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Um({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(tc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(nc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Vm(t))).payload}async postMessages(t){return(await this.store.dispatch(oc(t))).payload}async updateConversation(t){return(await this.store.dispatch(rc(t))).payload}resetConversation(){this.store.dispatch(J()),this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(An());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(ta(t))}setVisitorInfo(t){this.store.dispatch(K_(t))}async setAgentInfo(t){await this.store.dispatch(ya(t))}async setAgentSettings(t){await this.store.dispatch(kg(t))}async getAgentSettings(){return(await this.store.dispatch(Pg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(Qc()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(cc(t))}notifyKeyDown(t){this.store.dispatch(lc(t))}notifyPaste(t,n){this.store.dispatch(Xx({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(qx(t))}notifyExternalSuggestion(t){this.store.dispatch(Ft(t)),this.store.dispatch(yr())}notifyEditSuggestion(t){this.store.dispatch(dw(t.contentType,t.suggestions)),this.store.dispatch(Rn({contentType:t.contentType,suggestion:typeof t.index=="number"?t.suggestions[t.index]:null}))}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(wr({collapse:!1})),this.inputMediator&&this.store.dispatch(zx({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(on([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(Gx(sc(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(Kx()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{if(n||!a||!i||t.shiftKey)return;this.store.dispatch($x());let{selectedSuggestionIndex:p}=this.state.input;t.preventDefault(),!s&&(p===-1?this.store.dispatch(ra()):this.stageSelectedSuggestion({inputType:"arrow"}))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(hr(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(hr(-1)),this.store.dispatch(ra()),t.preventDefault()):n||(this.store.dispatch(wr({collapse:!0})),this.store.dispatch(xw(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:h}=this.state.input;this.store.dispatch(wa(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&h&&h.text.startsWith(d)&&(this.store.dispatch(Ft({text:h.text,suggestion:h,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(yr())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Qx()),this.store.dispatch(on([]))}handlingTimeStart(){this.state.handlingTime.startTime||(V.info("Start handling time"),this.store.dispatch(Kb()))}handlingTimeStop(){this.state.handlingTime.startTime&&(V.info("Stop handling time"),this.store.dispatch(Cd()))}logSendMessage(t){let n=Ch("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logSendEditMessage(t){let n=Ch("overlayInput",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.store.dispatch(Vx(this.state.overlayInput.metrics))}logHandlingTime(){let t=tE(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(Wb())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(yr()),this.store.dispatch(Zr(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Ft({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){V.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),V.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=oo(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,$t.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=oo(i,{appendTo:document.body});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,$t.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return ro(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,$t.unmountComponentAtNode)(o),o.remove()}),o}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!kd(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:d,insertLink:h,inputMediator:v,closestScrollSelector:y,appendOverlayTo:m,inlineSuggestions:g}=n;if(this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:h,isEmbedded:p,inlineSuggestions:g}),n.automaticHandlingTime&&this.setupHandlingTime(t),ro(t),this.inputMediator=v||(Tr(t)?new Tn(t):new mo(t)),this.inputMediator.on("change",({plainText:S})=>{this.notifyInputChanged(S)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Yx({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",S=>{this.notifyKeyDown(S)}),this.inputMediator.on("paste",({pastedText:S,selectionText:_})=>{this.notifyPaste(S,_)}),this.inputMediator.on("cut",({selectionText:S})=>{this.notifyCut(S)}),g){if(Tr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let S=this.createInlineContainer(t,"deepdesk-caret");(0,$t.render)((0,ze.jsx)(Fi,{store:this.store,customStyles:r,children:(0,ze.jsx)(Ti,{broadcastEvents:this.broadcastEvents,children:(0,ze.jsx)(E1,{})})}),S),this.inputMediator.on("caret",_=>{this.store.dispatch(on([])),_?(S.style.display="block",S.style.top=`${_.top}px`,S.style.left=`${_.left}px`):S.style.display="none"})}else{let S=y&&rE(t,y)||void 0,_=this.overlayContainerFactory("deepdesk-tab-completion",S||t,{appendTo:m,closestScrollElement:S,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),b=this.overlayContainerFactory("deepdesk-suggestions-overlay",S||t,{appendTo:m},r==null?void 0:r.suggestionsRootNode);(0,$t.render)((0,ze.jsx)(Fi,{store:this.store,customStyles:r,children:(0,ze.jsx)(Ti,{broadcastEvents:this.broadcastEvents,children:(0,ze.jsx)(G1,{inputElement:t})})}),_),(0,$t.render)((0,ze.jsx)(Fi,{store:this.store,customStyles:r,children:(0,ze.jsx)(Ti,{broadcastEvents:this.broadcastEvents,children:(0,ze.jsx)(L1,{})})}),b)}(0,$t.render)((0,ze.jsx)(Fi,{store:this.store,customStyles:r,children:(0,ze.jsx)(Ti,{broadcastEvents:this.broadcastEvents,children:(0,ze.jsx)(h1,{})})}),this.createContainer("deepdesk-overlays"));let f;this.inputMediator.on("selection",S=>{clearTimeout(f),S===null?f=setTimeout(()=>{S!==null&&this.store.dispatch(Wm(S))},500):this.store.dispatch(Wm(S))}),this.inputMediator.on("disabled",()=>{var S;(S=this.inputMediator)==null||S.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Ci(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Ci(!0))),this.store.dispatch(Ux({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.whenConversationLoaded(()=>{var S;this.refresh(),this.broadcastEvents.setSessionId((S=this.state.conversation.current)==null?void 0:S.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&V.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,showPersonalCollectionLink:i,isEmbedded:s}=n;this.widgetRoot=t,this.configure({showImages:o,showPersonalCollectionLink:i,isEmbedded:s}),(0,$t.render)((0,ze.jsx)(Fi,{store:this.store,customStyles:r,children:(0,ze.jsx)(Ti,{broadcastEvents:this.broadcastEvents,children:(0,ze.jsx)(jb,{})})}),t),this.whenConversationLoaded(()=>{var a;this.broadcastEvents.setSessionId((a=this.state.conversation.current)==null?void 0:a.sessionId)})}unmountWidget(){this.widgetRoot&&(0,$t.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Pd(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){oE(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Ia());let t=Ai(this.state);t&&this.store.dispatch(ta({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:t.knowledgeAssistForAgents,recommendTextSuggestions:t.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(V.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;V.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=ed(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(Vt()):this.store.dispatch(Pn(r))})}catch(r){this.handleError(r)}}};async function lE(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function uE(e,t,n={}){let r=n.replace?Rr(e,n.replace.start,n.replace.end):Bi(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
22
22
  `).reverse().forEach((s,a)=>{a>0&&r.insertNode(document.createElement("br")),r.insertNode(document.createTextNode(s))}):r.insertNode(document.createTextNode(t))};return Promise.resolve(i()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let s=n.selectionAfter?Rr(e,n.selectionAfter.start,n.selectionAfter.end):(r.collapse(!1),r),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(s)}if(!o)return;o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}async function cE(e,t){let n;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let r=()=>{let i=(e.ownerDocument.defaultView??window).getSelection();if(!i)return;let s=i.getRangeAt(0);s&&(s.deleteContents(),n=document.createElement("span"),s.insertNode(n),t.split(`
23
23
  `).reverse().forEach((a,l)=>{l>0&&s.insertNode(document.createElement("br")),s.insertNode(document.createTextNode(a))}),s.collapse(!1))};return Promise.resolve(r()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!n)try{n.scrollIntoView&&n.scrollIntoView({block:"nearest",inline:"nearest"})}finally{n&&n.remove()}})}function dE(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function pE(e,t,n){await new Bn(e).authenticateWithKey(t,n)}async function fE(e){let n=await new Wt(e).get("/platform/config/",{version:null});return re(n)}async function JA(e){let n=await(e.fetch??window.fetch)(e.url),r=await n.blob();return new File([r],e.name,{type:e.mimeType??n.headers.get("Content-Type")??"image/jpeg"})}async function mE(e,t){let n=await JA(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}}return _E(eL);})();
24
24
  /*! Bundled license information:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepdesk/deepdesk-sdk",
3
- "version": "10.4.1-beta.2",
3
+ "version": "10.5.0",
4
4
  "description": "Deepdesk SDK",
5
5
  "author": "Lukas Batteau",
6
6
  "license": "ISC",