@deepdesk/deepdesk-sdk 14.2.1-beta.6 → 14.2.1-beta.7

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.
@@ -16,7 +16,7 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
16
16
  `);return o=o.replace(/\n{3,}/g,`
17
17
 
18
18
 
19
- `),o=o.replace(/\n/g,"<br/>"),o}createContainer(t){var n;let o=(typeof global!="undefined"&&global.INTERWEAVE_SSR_POLYFILL||PO)();if(!o)return;let s=(n=this.props.containerTagName)!==null&&n!==void 0?n:"body",i=s==="body"||s==="fragment"?o.body:o.createElement(s);return t.match(CO)||(i.innerHTML=this.convertLineBreaks(this.props.escapeHtml?(0,GE.default)(t):t)),i}extractAttributes(t){let{allowAttributes:n}=this.props,r={},o=0;return t.nodeType!==qE||!t.attributes||([...t.attributes].forEach(s=>{let{name:i,value:a}=s,l=i.toLowerCase(),u=Hd[l]||Hd[i];if(!this.isSafe(t)||!l.match(TO)&&(!n&&(!u||u===Ih)||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===Jr?c=!0:u===_o?c=Number.parseFloat(String(c)):u!==Fd&&(c=String(c)),r[Lh[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,(s,i)=>String(i).toUpperCase())]=o)}),n}getTagConfig(t){let n={children:[],content:0,invalid:[],parent:[],self:!0,tagName:"",type:0,void:!1};return il[t]?I(T(T({},n),il[t]),{tagName:t}):n}isSafe(t){if(typeof HTMLAnchorElement!="undefined"&&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:s,transform:i,transformOnlyAllowList:a}=this.props,l=[],u="";return[...t.childNodes].forEach(c=>{if(c.nodeType===qE){let d=c.nodeName.toLowerCase(),g=this.getTagConfig(d);u&&(l.push(u),u="");let y=this.applyNodeFilters(d,c);if(!y)return;let v;if(i&&!(a&&!this.isTagAllowed(d))){this.keyIndex+=1;let p=this.keyIndex;v=this.parseNode(y,g);let m=i(y,v,g);if(m===null)return;if(typeof m!="undefined"){l.push(Fo.default.cloneElement(m,{key:p}));return}this.keyIndex=p-1}if(this.banned.has(d))return;if(!(r||o&&d!=="br")&&this.isTagAllowed(d)&&(s||this.canRenderChild(n,g))){var f;this.keyIndex+=1;let p=this.extractAttributes(y),m={tagName:d};p&&(m.attributes=p),g.void&&(m.selfClose=g.void),l.push(Fo.default.createElement(Ud,I(T({},m),{key:this.keyIndex}),(f=v)!==null&&f!==void 0?f:this.parseNode(y,g)))}else l=[...l,...this.parseNode(y,g.tagName?g:n)]}else if(c.nodeType===bO){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,s=null;for(;s=o.match(kO);){let[i,a]=s,l=s.index,u=i.includes("/");l>0&&(r.push(o.slice(0,l)),o=o.slice(l));let{children:c,matcher:f,props:d}=n[a],g;if(u)g=i.length,r.push(f.createElement(c,d));else{let y=o.match(new RegExp(`{{{/${a}}}}`));g=y.index+y[0].length,r.push(f.createElement(this.replaceTokens(o.slice(i.length,y.index),n),d))}o=o.slice(g)}return o.length>0&&r.push(o),r.length===0?"":r.length===1&&typeof r[0]=="string"?r[0]:r}};function RO(e){var t;let{attributes:n,className:r,containerTagName:o,content:s,emptyContent:i,parsedContent:a,tagName:l,noWrap:u}=e,c=(t=o!=null?o:l)!==null&&t!==void 0?t:"span",f=c==="fragment"?!0:u,d;if(a)d=a;else{let g=new zd(s!=null?s:"",e).parse();g.length>0&&(d=g)}return d||(d=i),f?Fo.default.createElement(Fo.default.Fragment,null,d):Fo.default.createElement(Ud,{attributes:n,className:r,tagName:c},d)}function ui(e){let k=e,{attributes:t,className:n,content:r="",disableFilters:o=!1,disableMatchers:s=!1,emptyContent:i=null,filters:a=[],matchers:l=[],onAfterParse:u=null,onBeforeParse:c=null,tagName:f="span",noWrap:d=!1}=k,g=ee(k,["attributes","className","content","disableFilters","disableMatchers","emptyContent","filters","matchers","onAfterParse","onBeforeParse","tagName","noWrap"]),y=s?[]:l,v=o?[]:a,p=c?[c]:[],m=u?[u]:[];y.forEach(b=>{b.onBeforeParse&&p.push(b.onBeforeParse.bind(b)),b.onAfterParse&&m.push(b.onAfterParse.bind(b))});let h=p.reduce((b,R)=>R(b,e),r!=null?r:""),S=new zd(h,g,y,v),w=m.reduce((b,R)=>R(b,e),S.parse());return Fo.default.createElement(RO,{attributes:t,className:n,containerTagName:e.containerTagName,emptyContent:i,noWrap:d,parsedContent:w.length===0?void 0:w,tagName:f})}var tb=x(D());var AO=/[.*+?^${}()|[\]\\]/g,IO=/[^0-9A-Za-zÀ-ÖØ-öø-ÿ](?=[0-9A-Za-zÀ-ÖØ-öø-ÿ]*$)/;function LO(e){return e.replace(AO,"\\$&")}function OO(e,t){let n=e.split("").findIndex((r,o)=>r!==t[o]);return n>-1?n:Math.min(e.length,t.length)}function NO(e){return e.search(IO)}function YE(e,t=[]){let n=e;return t.forEach(r=>{if(!r)return;let o=new RegExp(`\\b(${LO(r)})\\b`,"gi");n=n.replace(o,"<strong>$1</strong>")}),n}function QE(e){return e.replace(ou,'<mark data-type="placeholder">$1</mark>')}function ci(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function MO(e,t){return e.split("").map((i,a)=>({char:i,index:a})).filter(({char:i,index:a})=>/\s/.test(i)&&a<=t).map(({index:i})=>i).reverse()[0]}function Nh(e,t,n={}){if(t){let r=OO(t.toLowerCase(),e.toLowerCase()),o=ci(e.substring(r,e.length));if(n.stripAgentPart){let l=e.substring(0,r),u=NO(l);return`<span style="opacity: 0.5">${l.substring(u+1)}</span>${o}`}let i=t.split(n0).length>3||t.length>30?MO(t.trim(),r):0;return`${`${i>0?"\u2026":""}${ci(e.substring(i,r))}`}<strong>${o}</strong>`}return e}var _O=/(<\/[a-zA-Z]+[0-9]?>|<[a-zA-Z]+\s?\/>|<br>)/i;function jd(e){return _O.test(e)}function XE(e){var n;let t=document.createElement("template");return t.innerHTML=e,(n=t.content.textContent)!=null?n:""}var Bd=x(D()),eb=x(C()),ZE=Bd.default.createContext(void 0);function eo(){let e=Bd.default.useContext(ZE);if(e===void 0)throw new Error("useCommandPalette must be used within the CommandPalette component");return e}var JE=({children:e,page:t,isOpen:n,onChangeOpen:r,selected:o,setSelected:s})=>{let i=Bd.default.useMemo(()=>({page:t,isOpen:n,onChangeOpen:r,selected:o,setSelected:s}),[n,t,o]);return(0,eb.jsx)(ZE.Provider,{value:i,children:e})};var Zt=x(C()),DO=3,nb=({children:e})=>{let t=L("CommandPalette",_t);return(0,Zt.jsx)("div",{className:t.listItemActions,children:e})};function Mh(d){var g=d,{closeOnSelect:e=!0,lineClamp:t,children:n,onClick:r,extra:o,onSourceClick:s,description:i,sources:a,id:l,styles:u,defaultSourcesAmount:c=DO}=g,f=ee(g,["closeOnSelect","lineClamp","children","onClick","extra","onSourceClick","description","sources","id","styles","defaultSourcesAmount"]);var k;let y=Y(or),[v,p]=(0,tb.useState)(!1),{selected:m,onChangeOpen:h}=eo(),S=L("CommandPalette",_t);function w(b){r(b),e&&h(!1)}return(0,Zt.jsxs)("div",{className:(0,al.default)(S.listItem,l===m&&S.listItemSelected),children:[(0,Zt.jsx)("button",I(T({type:"button",className:S.listItemAction,"aria-disabled":(k=f.disabled)!=null?k:!1,onClick:w,"data-command-palette-item":!0,"data-item-id":l},f),{children:(0,Zt.jsxs)("div",{className:S.listItemContent,children:[typeof n=="string"?(0,Zt.jsx)("p",{className:(0,al.default)(S.listItemText,S.truncate,u==null?void 0:u.title),children:n}):n,i&&(0,Zt.jsx)(ui,{tagName:"p",allowList:[],content:jd(i)?XE(i):i,className:(0,al.default)(S.listItemDescription,u==null?void 0:u.description,t?S.lineClamp:S.truncate)})]})})),o,a&&a.length>0&&(0,Zt.jsxs)("div",{className:S.sources,children:[(0,Zt.jsx)("span",{className:S.sourcesTitle,children:y("sources")}),a.slice(0,v?a.length:c).map(b=>(0,Zt.jsx)("a",{className:S.source,href:b.url,target:"_blank",title:b.url,rel:"noopener noreferrer","data-testid":"source",onClick:()=>s&&s(b),children:b.name},b.url)),!v&&a.length>c&&(0,Zt.jsx)("button",{className:(0,al.default)(S.source,S.sourceShowMore),type:"button",onClick:()=>p(!0),children:y("showMore",{amount:a.length-c})})]})]})}var ll=x(C()),rb=()=>(0,ll.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 256 512","aria-labelledby":"angleLeftTitle",children:[(0,ll.jsx)("title",{id:"angleLeftTitle",children:"AngleLeft"}),(0,ll.jsx)("path",{d:"M192 448c-8.188 0-16.38-3.125-22.62-9.375l-160-160c-12.5-12.5-12.5-32.75 0-45.25l160-160c12.5-12.5 32.75-12.5 45.25 0s12.5 32.75 0 45.25L77.25 256l137.4 137.4c12.5 12.5 12.5 32.75 0 45.25C208.4 444.9 200.2 448 192 448z"})]});var Ho=x(C());function _h({children:e,title:t,id:n,onDismiss:r}){let o=Y(or),s=L("CommandPalette",_t),{page:i}=eo();return i!==n?null:(0,Ho.jsxs)("div",{className:s.page,id:`page_${n}`,tabIndex:-1,children:[r&&(0,Ho.jsxs)("div",{className:s.pageNav,children:[(0,Ho.jsxs)("button",{className:s.pageBackButton,type:"button",onClick:r,children:[(0,Ho.jsx)(rb,{}),o("back")]}),t&&(0,Ho.jsx)("h3",{className:s.pageTitle,children:t})]}),e]})}var ob=x(D());var ul=x(C()),di=()=>(0,ul.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 24 24",width:"1em",fill:"currentColor",children:[(0,ul.jsx)("path",{d:"M0 0h24v24H0z",fill:"none"}),(0,ul.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 hn=x(C());function FO({onChange:e,onChangeType:t,placeholder:n,typePlaceholder:r,types:o,value:s,selectedType:i},a){let l=L("CommandPalette",_t);return(0,hn.jsxs)("div",{className:l.search,children:[(0,hn.jsx)("div",{className:l.searchIcon,children:(0,hn.jsx)(di,{})}),(0,hn.jsxs)("div",{className:l.searchInputWrapper,children:[(0,hn.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:s,type:"text",id:"command-palette-search-input",autoFocus:!0}),o&&o.length>0&&(0,hn.jsx)("div",{className:l.selectWrapper,children:(0,hn.jsxs)("select",{"data-testid":"command-palette-type-select",className:l.select,onChange:u=>t(u.target.value===r?void 0:u.target.value),value:i||r,children:[r&&(0,hn.jsx)("option",{children:r}),o.map(u=>(0,hn.jsx)("option",{value:u.value,children:u.label},u.value))]})})]})]})}var sb=(0,ob.forwardRef)(FO);var Dh=x(se());var Vd=x(C()),HO=o=>{var s=o,{onClick:e,shortKeys:t,children:n}=s,r=ee(s,["onClick","shortKeys","children"]);let i=L("CommandPalette",_t);return(0,Vd.jsxs)("button",I(T({type:"button"},r),{onClick:e,className:(0,Dh.default)(i.actionButton,r.className,{[i.hasShortKeys]:t&&t.length>0}),children:[n,t&&t.map(a=>(0,Vd.jsx)("span",{className:(0,Dh.default)(i.actionShortcut,a===8629&&i.actionShortcutFixKerning),children:typeof a=="number"?String.fromCharCode(a):a},a))]}))},ib=HO;var cl=x(C()),UO="[data-command-palette-item]";function Uo({placeholder:e="Start typing to search...",typePlaceholder:t="All types",defaultPage:n="search",page:r,onChangePage:o,onChangeSearch:s,onChangeType:i,onChangeOpen:a,selectedType:l,types:u,children:c,isOpen:f,search:d,updateDeps:g=[]}){let[y,v]=(0,ar.useState)(),p=(0,ar.useRef)(null),m=()=>{o&&o(n),i(void 0),s(""),a(!1)},h=()=>{var K;if(r!==n&&o){o(n);return}if(l&&i){i(void 0),(K=p.current)==null||K.focus();return}if(d.length>0){s("");return}a(!1)},S=()=>{let K=w();K.length!==0&&v(K[0].dataset.itemId)},w=()=>Array.from(document.querySelectorAll(UO)||[]),k=K=>document.querySelector(`[data-item-id=${K}]`),b=K=>{let W=k(K);W&&v(W.dataset.itemId)},R=K=>{let W=k(K);W&&W.scrollIntoView({behavior:"smooth"})},N=()=>{if(!y)return;let K=w(),W=k(y);if(!W)return;let de=K.indexOf(W),Ye=K[de+1];Ye&&Ye.dataset.itemId?b(Ye.dataset.itemId):S()},_=()=>{if(!y)return;let K=w(),W=k(y);if(!W)return;let de=K.indexOf(W),Ye=K[de-1];Ye&&Ye.dataset.itemId?b(Ye.dataset.itemId):b(K[K.length-1].dataset.itemId)},Q=(0,ar.useCallback)(K=>{switch(K.key){case"ArrowDown":{K.preventDefault(),N();break}case"ArrowUp":{K.preventDefault(),_();break}case"Enter":{if(y){let W=k(y);W==null||W.click()}break}}},[y]);return(0,ar.useEffect)(()=>{S()},[d,r,l,f,...g]),(0,ar.useEffect)(()=>{y&&R(y)},[y]),(0,cl.jsx)(Rd,{autoFocus:!0,contentAriaLabel:"Search Results",overlayAriaLabel:"Command Palette",isOpen:f,onBack:h,onClose:m,onKeyDown:Q,children:(0,cl.jsxs)(JE,{selected:y,setSelected:v,isOpen:f,onChangeOpen:a,page:r,children:[r===n&&(0,cl.jsx)(sb,{ref:p,onChange:s,onChangeType:i,placeholder:e,value:d,selectedType:l,types:u,typePlaceholder:t}),c]})})}Uo.Page=_h;Uo.List=Ch;Uo.Image=jE;Uo.ListItem=Mh;Uo.ListItemActions=nb;Uo.Button=ib;var he=Uo;var ab=x(D());function lb(e,t){(0,ab.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 dl=x(D());var ub={data:null,fetchState:"idle"},Kd=e=>{var s,i,a,l;let t=[],{visitorName:n}=(s=e.info.visitorInfo)!=null?s:{},{agentName:r,agentNickname:o}=(i=e.info.agentInfo)!=null?i:{};return r&&r!==n&&t.push(r),o&&o!==n&&t.push(o),(l=(a=e.entities.data)==null?void 0:a.filter(u=>!t.includes(u.text)))!=null?l:null},yn=V("entities/getEntities",(e,t)=>P(void 0,null,function*(){let{deepdeskAPI:n,dynamicThunkObject:r}=t.extra;if(!r.conversationQuery)return Promise.resolve([]);let o=r.conversationQuery,s=yield o();return s.length===0?Promise.resolve([]):n.getEntities(s)})),zO=e=>e.filter((t,n)=>n===e.findIndex(r=>r.text===t.text)),jO=J({name:"entities",initialState:ub,reducers:{},extraReducers:e=>{e.addCase(yn.pending,t=>{t.fetchState="loading"}).addCase(yn.rejected,t=>{t.fetchState="error"}).addCase(yn.fulfilled,(t,n)=>{t.fetchState="done",t.data=zO(t.data?[...t.data,...n.payload]:n.payload)}).addCase(xe,()=>ub)}}),cb=jO.reducer;var Fh={};Xe(Fh,{enUS:()=>BO,nlNL:()=>VO});var BO={noResults:[{type:0,value:"No entities have been found"}],copy:[{type:0,value:"Copy"}],use:[{type:0,value:"Use"}]},VO={noResults:[{type:0,value:"Er zijn geen entiteiten gevonden"}],copy:[{type:0,value:"Kopieer"}],use:[{type:0,value:"Gebruik"}]};var db={root:"dd-TYTKs",empty:"dd-AU7uT"};var fi=x(C()),KO=({onCopy:e})=>{let t=(0,dl.useRef)(null),n=L("EntitiesList",db),r=M(Kd),{setSelected:o}=eo(),s=Y(Fh),i=G();return(0,dl.useEffect)(()=>{i(yn())},[]),(0,dl.useEffect)(()=>{t.current&&(t.current.focus(),o("entity-0"))},[t]),(0,fi.jsxs)("div",{className:n.root,ref:t,tabIndex:-1,children:[r&&r.length>0&&(0,fi.jsx)(he.List,{children:r.map((a,l)=>(0,fi.jsx)(he.ListItem,{id:`entity-${l}`,closeOnSelect:!0,onClick:()=>e(a),children:a.text},a.text))},"entities"),r&&r.length===0&&(0,fi.jsx)("p",{className:n.empty,children:s("noResults")})]})},fb=KO;var zo=x(D());var pi=x(D());function pb(e,t){let n=(0,pi.useRef)(e);n.current=e;let[r,o]=(0,pi.useState)(void 0),[s,i]=(0,pi.useState)(void 0),[a,l]=(0,pi.useState)("idle"),u=G();return{error:s,state:a,data:r,call:f=>{l("loading"),u(n.current(f)).unwrap().then(d=>{o(d),l("done"),t!=null&&t.onSuccess&&(t==null||t.onSuccess(d))}).catch(d=>{i(d),l("error"),t!=null&&t.onError&&(t==null||t.onError(d))})}}}var Wd=x(se()),yb=x(D());var Hh=x(C()),Uh=e=>(0,Hh.jsx)("svg",I(T({width:"16",height:"16",fill:"#000000"},e),{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,Hh.jsx)("path",{fillRule:"evenodd",d:"M6.57086468,14.9173453 C6.38997052,14.9711236 6.19835748,15 6,15 L4,15 C2.8954305,15 2,14.1045695 2,13 L2,4 C2,2.8954305 2.8954305,2 4,2 L6,2 C6.68685475,2 7.29284112,2.34623869 7.65294381,2.87370078 C7.95642355,2.67736738 8.29504785,2.51351337 8.66312366,2.3818197 C9.50544052,2.08044754 10.3408482,1.9879107 10.9989281,1.99971266 C11.0150698,2.00005426 13.3487605,2.00015005 18,2 C20.7551411,2 22,6.05643086 22,12 C22,13.6824804 20.8695981,15 19,15 L15.9269768,15 C15.9359266,15.0245465 15.9451954,15.0497804 15.9547911,15.0757271 C16.007193,15.2174219 16.2391583,15.8256341 16.2970775,15.9810953 C16.4872151,16.4914441 16.6259612,16.9026411 16.7382242,17.3098712 C16.9079007,17.9253665 17,18.4798886 17,19 C17,20.4720069 16.091867,21.3862822 14.748281,21.777514 C14.1422801,21.9539723 13.6147967,22.0000922 13.0076976,22.0000008 L12.5204954,22 L12.2202699,21.6261158 C11.2556275,20.4248034 7.64562469,16.4822788 6.57086468,14.9173453 Z M8,13 C8,13.2401953 8.04443154,13.4528921 8.14171093,13.6800176 C8.40663864,14.2985643 11.914268,18.1371493 13.4599624,19.9848695 C13.7113931,19.9660111 13.9483736,19.9273712 14.1891338,19.8572655 C14.7621788,19.6904035 15,19.4509737 15,19 C15,18.6834183 14.9359344,18.2976852 14.8101464,17.8413935 C14.7161494,17.500423 14.5944107,17.1396301 14.4229225,16.6793379 C14.3689242,16.5344009 14.1358033,15.923159 14.0789589,15.7694517 C13.9489218,15.4178313 13.8632547,15.1589343 13.8046536,14.9236885 C13.5555377,13.9236468 13.8054549,13 15,13 L19,13 C19.6912225,13 20,12.6401099 20,12 C20,7.20925475 19.015127,4 18,4 C15.9322103,4 15.9322103,4 10.9655994,3.99940813 C10.5253746,3.99154158 9.91062406,4.05963657 9.33687634,4.2649175 C8.45196659,4.58152894 8,5.09776992 8,6 L8,13 Z M4,4 L4,13 L6,13 L6,4 L4,4 Z"})}));var zh=x(C()),mb=e=>(0,zh.jsx)("svg",I(T({width:"16",height:"16",fill:"#000000"},e),{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,zh.jsx)("path",{fillRule:"evenodd",d:"M7.65336736,21.1256786 C7.2933164,21.6534897 6.68712411,22 6,22 L4,22 C2.8954305,22 2,21.1045695 2,20 L2,11 C2,9.8954305 2.8954305,9 4,9 L6,9 C6.198171,9 6.38961023,9.02882212 6.57035446,9.08250314 C7.6444817,7.51807482 11.2554748,3.57449216 12.2202699,2.37298955 L12.5204954,1.99910538 L13,1.99910538 C13.6147967,1.99901314 14.1422801,2.04513312 14.748281,2.22159137 C16.091867,2.61282321 17,3.52709845 17,4.99910538 C17,5.51921677 16.9079007,6.07373891 16.7382242,6.68923415 C16.6259612,7.09646424 16.4872151,7.50766133 16.2970775,8.01801005 C16.2391583,8.17347129 16.007193,8.78168345 15.9547911,8.92337824 C15.9451954,8.94932503 15.9359266,8.9745589 15.9269768,8.99910538 L19,8.99910538 C20.8695981,8.99910538 22,10.316625 22,11.9991054 C22,17.9426745 20.7551411,21.9991054 18,21.9991054 L11.0344006,21.9985135 C10.3408482,22.0111947 9.50544052,21.9186578 8.66312366,21.6172857 C8.29521907,21.4856533 7.9567386,21.3218904 7.65336736,21.1256786 Z M8,17.9991054 C8,18.9013355 8.45196659,19.4175764 9.33687634,19.7341879 C9.91062406,19.9394688 10.5253746,20.0075638 10.963066,19.9997143 C10.9703499,19.9995545 10.9703499,19.9995545 11,19.9991054 L18,19.9991054 C19.015127,19.9991054 20,16.7898506 20,11.9991054 C20,11.3589955 19.6912225,10.9991054 19,10.9991054 L15,10.9991054 C13.8054549,10.9991054 13.5555377,10.0754586 13.8046536,9.07541689 C13.8632547,8.84017106 13.9489218,8.5812741 14.0789589,8.22965366 C14.1358033,8.07594642 14.3689242,7.46470447 14.4229225,7.31976744 C14.5944107,6.85947528 14.7161494,6.4986824 14.8101464,6.1577119 C14.9359344,5.70142019 15,5.31568707 15,4.99910538 C15,4.54813166 14.7621788,4.30870189 14.1891338,4.1418399 C13.9483736,4.07173418 13.7113931,4.0330943 13.4599624,4.01423587 C11.914268,5.86195611 8.40663864,9.70054105 8.14171093,10.3190878 C8.04443154,10.5462133 8,10.7589101 8,10.9991054 L8,17.9991054 Z M4,11 L4,20 L6,20 L6,11 L4,11 Z"})}));function mi(e,t){var o;let n=e.cloneNode(!0);n.style.top=`${e.offsetTop}px`,n.style.left=`${e.offsetLeft}px`,n.style.position="absolute",t.split(" ").forEach(s=>{n.classList.add(s)}),n.addEventListener("animationend",()=>n.remove()),(o=e.parentElement)==null||o.appendChild(n)}var jh={};Xe(jh,{enUS:()=>WO,nlNL:()=>$O});var WO={thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},$O={thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};function gb(e){return V("analytics/logEvent",(t,n)=>{var s,i,a;let r=(i=(s=n.getState())==null?void 0:s.conversation.current)==null?void 0:i.id,o=(a=n.getState())==null?void 0:a.info.agentInfo;return n.extra.deepdeskAPI.sendEvent(t.name,I(T({conversationId:r},o),{data:t.data}))})(e)}function gi(){let e=G();return(t,n)=>P(this,null,function*(){yield e(gb({name:t,data:n}))})}var hb={thumbs:"dd-5F1zq",fadeup:"dd-eTmY-",fadedown:"dd-sS85z",selected:"dd-rid-f",thumbsUp:"dd-4poEf",thumbsDown:"dd-3KozS"};var hi=e=>t=>{let{passwordlessToken:{token:n},settings:{isEmbedded:r,adminUrl:o}}=t,s=o||window.location.origin;return r&&!n?null:r&&n?`${s}/apis/admin/session/passwordless/login/?token=${n}&redirect=${encodeURIComponent(e)}`:`${s}${e}`};var lr=x(C()),qO=({eventName:e,eventData:t,feedbackType:n,feedbackText:r})=>{let o=L("FeedbackThumbs",hb),s=z("enableFeedbackForm"),i=M(Yr),a=M(hi(`/admin/feedback?conversationId=${i}&type=${n}&text=${r}&data=${JSON.stringify(t)}`)),l=Y(jh),u=gi(),[c,f]=(0,yb.useState)(null),d=y=>{y.stopPropagation(),mi(y.target,o.fadeup),f("up"),u(e,I(T({},t),{rating:"up"}))},g=y=>{y.stopPropagation(),mi(y.target,o.fadedown),f("down"),u(e,I(T({},t),{rating:"down"}))};return(0,lr.jsxs)("div",{className:o.thumbs,children:[(0,lr.jsx)(re.Button,{title:l("thumbsUp"),onClick:d,icon:(0,lr.jsx)(mb,{}),className:(0,Wd.default)(o.thumbsUp,c==="up"&&o.selected),disabled:!!c}),s&&a?(0,lr.jsx)(re.Button,{as:"a",title:l("thumbsDown"),href:a,target:"_blank",rel:"noreferrer",onClick:g,icon:(0,lr.jsx)(Uh,{}),className:(0,Wd.default)(o.thumbsDown,c==="down"&&o.selected),disabled:!!c}):(0,lr.jsx)(re.Button,{title:l("thumbsDown"),onClick:g,icon:(0,lr.jsx)(Uh,{}),className:(0,Wd.default)(o.thumbsDown,c==="down"&&o.selected),disabled:!!c})]})},yi=qO;var fl=x(C()),vb=()=>(0,fl.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 512 512","aria-labelledby":"paperPlaneTitle",children:[(0,fl.jsx)("title",{id:"paperPlaneTitle",children:"PaperPlane"}),(0,fl.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 Bh={};Xe(Bh,{enUS:()=>GO,nlNL:()=>YO});var GO={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"}]},YO={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 Sb={root:"dd-fxP4c",title:"dd-vDbMh",empty:"dd-sB0lz",status:"dd--oZ1C",form:"dd-t0hnD",input:"dd-i1v3W",submit:"dd-oo2Oa",question:"dd-WvK17",answer:"dd-HAHcU",alignRight:"dd-oxrX3",listItemFeedback:"dd-POUal"};var dt=x(C()),QO=({threadId:e,onNewThreadId:t,onUse:n,onResetQuestion:r,question:o})=>{var p;let[s,i]=zo.default.useState(""),{setSelected:a}=eo(),l=(0,zo.useRef)(null),u=L("KnowledgeSearchStyles",Sb),c=Y(Bh),f=G(),d=(p=M(Eh(e!=null?e:-1)))!=null?p:[],g=pb(m=>bh({input:m,threadId:e,onNewThreadId:h=>t(h)}),{onSuccess(m){f(ct({name:"knowledge assist question answered",data:{question:s||o,sources:m.answer.sources,answer:m.answer.answer,isFollowUpQuestion:d.length>=1},options:{includeConversationData:!0}})),a(`knowledge-assist-${d.length-1}`),i("")}}),y=m=>P(void 0,null,function*(){m.preventDefault(),m.stopPropagation(),s!==""&&g.call(s)}),v=(m,h)=>{f(ct({name:"knowledge assist source viewed",data:{question:h,sourceViewed:m.url||m.name},options:{includeConversationData:!0}}))};return(0,zo.useEffect)(()=>{var m;o&&g.state==="idle"?g.call(o):(m=l.current)==null||m.focus()},[l,g.state]),(0,zo.useEffect)(()=>{l.current&&l.current.scrollIntoView({behavior:"smooth"})},[l,d]),(0,dt.jsxs)("div",{className:u.root,children:[d.length>0&&(0,dt.jsx)("div",{className:u.alignRight,children:(0,dt.jsx)(he.Button,{onClick:r,children:c("reset")})}),d.map(({question:m,answer:h},S)=>(0,dt.jsx)(he.List,{children:(0,dt.jsx)(he.ListItem,{id:`knowledge-assist-${S}`,"data-testid":"knowledge-search-answer",description:h.answer,closeOnSelect:!0,onClick:()=>n(h.answer),onSourceClick:w=>v(w,m),sources:h.sources,styles:{title:u.question,description:u.answer},extra:(0,dt.jsx)("div",{className:u.listItemFeedback,children:(0,dt.jsx)(yi,{feedbackText:h.answer,feedbackType:"knowledge-assist-answer",eventName:"knowledge assist feedback",eventData:T({question:m,isAgent:o!==m,isFollowUpQuestion:d.length>1},h)})}),children:m})},`${h.answer}_${S}`)),g.state==="loading"&&(0,dt.jsx)("p",{className:u.status,children:c("loading")}),g.state==="error"&&(0,dt.jsx)("p",{className:u.status,children:c("error")}),(0,dt.jsxs)("form",{className:u.form,onSubmit:y,children:[(0,dt.jsx)("input",{ref:l,placeholder:c("anotherQuestion"),className:u.input,type:"text",value:s,onFocus:()=>{a(void 0)},onChange:m=>{a(void 0),i(m.target.value)}}),(0,dt.jsx)("button",{type:"submit",className:u.submit,disabled:g.state==="loading",children:(0,dt.jsx)(vb,{})})]})]})},xb=QO;var Ge=x(D()),wb=x(se());var Vh={root:"dd-uVyL0",trigger:"dd-KIzQa",content:"dd-Ly3zO",contentOpen:"dd-O-8fR",contentTop:"dd-q3fGa",contentBottom:"dd-SFrvc",item:"dd-HZNy-"};var jo=x(C()),XO=0,Eb=Ge.default.createContext(null),ZO=()=>{let e=(0,Ge.useContext)(Eb);if(!e)throw new Error("Invalid DropdownContext");return e},bb=({trigger:e,children:t,position:n="bottom"})=>{let r=(0,Ge.useMemo)(()=>++XO,[]),o=(0,Ge.useRef)(null),s=(0,Ge.useRef)(null),i=L("Dropdown",Vh),[a,l]=(0,Ge.useState)(!1),[u,c]=(0,Ge.useState)(n),f=g=>{g.preventDefault(),g.stopPropagation(),l(!a)},d=(0,Ge.useCallback)(([g])=>{!g.isIntersecting&&a&&c(u==="top"?"bottom":"top")},[a]);return(0,Ge.useEffect)(()=>{let g=y=>{o.current&&!o.current.contains(y.target)&&l(!1)};return document.addEventListener("click",g),()=>{document.removeEventListener("click",g)}},[]),(0,Ge.useEffect)(()=>{if(!s.current&&!a)return()=>{};let g=new IntersectionObserver(d,{root:null,rootMargin:"0px",threshold:1});return s.current&&g.observe(s.current),()=>{s.current&&g.unobserve(s.current)}},[s,a]),(0,jo.jsx)(Eb.Provider,{value:{setIsOpen:l},children:(0,jo.jsxs)("div",{ref:o,className:i.root,children:[(0,jo.jsx)("button",{id:`dropdown-${r}`,"data-testid":"dropdown-trigger","aria-haspopup":"true","aria-expanded":a,"aria-label":"Dropdown trigger",type:"button",className:i.trigger,onClick:f,children:e}),(0,jo.jsx)("div",{"data-testid":"dropdown-content",ref:s,"aria-hidden":!a,"aria-labelledby":`dropdown-${r}`,className:(0,wb.default)(i.content,{[i.contentOpen]:a,[i.contentTop]:u==="top",[i.contentBottom]:u==="bottom"}),children:t})]})})};function JO(o){var s=o,{as:e,children:t,onClick:n}=s,r=ee(s,["as","children","onClick"]);let i=e||"button",a=L("Dropdown",Vh),{setIsOpen:l}=ZO(),u=c=>{l(!1),n(c),c.stopPropagation()};return(0,jo.jsx)(i,I(T({type:"button",className:a.item,onClick:u},r),{children:t}))}bb.Item=JO;var Kh=bb;var Wh=x(C()),Cb=e=>(0,Wh.jsx)("svg",I(T({xmlns:"http://www.w3.org/2000/svg",height:"16",width:"14",viewBox:"0 0 448 512"},e),{children:(0,Wh.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 Bo={};Xe(Bo,{enUS:()=>eN,nlNL:()=>tN});var eN={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"}]},tN={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 $d=x(C()),nN=({suggestion:e,source:t,context:n})=>{let r=Y(Bo),o=M(Yr),s=G(),i=z("enableSuggestionFeedback"),a=`${e.text}`,l=M(hi(`/admin/feedback?conversationId=${o}&type=${t}&text=${a}&data=${JSON.stringify({context:n})}`)),u=()=>{s(ct({name:"suggestion feedback",data:{text:e.text,source:t,context:n},options:{includeConversationData:!0}}))};return!i||!l?null:(0,$d.jsx)(Kh,{trigger:(0,$d.jsx)(Cb,{"data-testid":"feedback-dropdown-trigger"}),children:(0,$d.jsx)(Kh.Item,{as:"a",onClick:u,target:"_blank",href:l,children:r("giveFeedback")})})},qd=nN;var Jt=x(D());var $h={};Xe($h,{enUS:()=>rN,nlNL:()=>oN});var rN={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."}]},oN={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 Tb={root:"dd-60NZr",actions:"dd-No1g3",main:"dd-l-xEF",textInput:"dd-nAaiV",loading:"dd-ciFNi",error:"dd-yNp2D"};var Nn=x(C()),sN=({onCopy:e})=>{let t=(0,Jt.useRef)(null),n=L("SummaryForm",Tb),[r,o]=(0,Jt.useState)(""),[s,i]=(0,Jt.useState)(""),[a,l]=(0,Jt.useState)(!1),u=M(nr),c=Y($h),f=G(),d=()=>{f(ct({name:"summary copied to clipboard",data:{originalText:r,finalText:s},options:{includeConversationData:!0}})),e(s)},g=()=>{let y=document.getSelection();y&&f(ct({name:"summary copied to clipboard",data:{originalText:r,finalText:y==null?void 0:y.toString(),assistant:u==null?void 0:u.summarizerAssistantNew},options:{includeConversationData:!0}}))};return(0,Jt.useEffect)(()=>{f(li({})).then(y=>{if(y.error){l(!0);return}o(y.payload||""),i(y.payload||"")})},[]),(0,Jt.useEffect)(()=>{t.current&&r&&t.current.focus()},[t,r]),(0,Jt.useEffect)(()=>{let y=v=>{v.key==="Enter"&&v.shiftKey&&d()};return document.addEventListener("keydown",y),()=>{document.removeEventListener("keydown",y)}},[s]),(0,Nn.jsx)("div",{className:n.root,tabIndex:-1,children:a?(0,Nn.jsx)("p",{className:n.error,children:c("error")}):(0,Nn.jsxs)(Jt.Fragment,{children:[(0,Nn.jsx)("div",{className:n.main,children:(0,Nn.jsx)("textarea",{placeholder:r?void 0:c("loading"),disabled:!r,className:n.textInput,ref:t,value:s,onCopy:g,onChange:y=>i(y.target.value)})}),(0,Nn.jsxs)("div",{className:n.actions,children:[(0,Nn.jsx)(yi,{feedbackText:r||"",feedbackType:"summary",eventName:"summary feedback",eventData:{summary:r}}),(0,Nn.jsx)(he.Button,{shortKeys:[8679,8629],onClick:d,children:c("copy")})]})]})})},kb=sN;var pl={};Xe(pl,{enUS:()=>iN,nlNL:()=>aN});var iN={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?"}]},aN={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 _b=x(D());var lN=["{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}"],uN=new RegExp(lN.map(e=>`(?:${e.replace("{","\\{").replace("}","\\}")})`).join("|"));function Pb(e,t){let n=e.split(uN),r=0,o=[];for(let s=0;s<n.length;s++){let i=n[s];if(o.push(i),s===n.length-1)break;if(t.indexOf(i)===-1)return e;let a=n[s+1],l=s===n.length-2;r+=i.length;let u=r;if(l){let f=a.charAt(0),d=0;do u=f?t.indexOf(f,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 Rb(e,t){return typeof t=="boolean"?e:e.slice(0,t)}var Ib={suggestions:[],fetchState:"idle"},Ab={default:Ib},Lb=e=>t=>{var n,r;return(r=(n=t.textSuggestions[e])==null?void 0:n.suggestions)!=null?r:[]},Gd=e=>e.textSuggestions,Ob=e=>{let t=e.toLowerCase();return n=>{let r=n.text.toLowerCase();return r.startsWith(t)&&r.length>t.length}},Yd=Ie("textSuggestions/refresh"),vn=V("textSuggestions/recommendations",(e,t)=>P(void 0,null,function*(){var c;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=(c=r.conversation.current)==null?void 0:c.id,{platformVariables:s}=r.info,{textSuggestionsCount:i,inlineSuggestions:a}=r.settings,l=si(r);if(!o)throw new Error("No current conversation to fetch text suggestions");let u=yield n.getTextSuggestions(o,$a(r),e);if(s&&(u=u.map(f=>T(I(T({},f),{text:qe(f.text,s)}),f.title?{title:qe(f.title,s)}:{}))),e==="default"){let f=a?u.filter(Ob(l)):u;t.dispatch(Qr(f.slice(0,i)))}return u})),ml=V("textSuggestions/autocompletions",(e,t)=>P(void 0,null,function*(){var c;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=(c=r.conversation.current)==null?void 0:c.id,{platformVariables:s}=r.info,{textSuggestionsCount:i,deanonymize:a,inlineSuggestions:l}=r.settings;if(!o)throw new Error("No current conversation to fetch text suggestions");let u=yield n.getAutocompleteSuggestions(o,I(T({},$a(r)),{input:e}));if(!t.getState().input.text)throw new Error("Abort");return l&&(u=u.filter(Ob(e))),s&&(u=u.map(f=>I(T({},f),{text:qe(f.text,s)}))),a&&(u=u.map(f=>I(T({},f),{text:f.source!=="trie-with-typos"?Pb(f.text,e):f.text}))),u=Rb(u,i),t.dispatch(Qr(u)),u})),Nb=J({name:"textSuggestions",initialState:Ab,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}}}}},extraReducers:e=>{e.addCase(vn.pending,(t,n)=>{let r=n.meta.arg,o=t[r]||Ib;return I(T({},t),{[r]:I(T({},o),{fetchState:"loading"})})}).addCase(vn.rejected,(t,n)=>{let r=n.meta.arg;t[r]&&(t[r].fetchState="error")}).addCase(vn.fulfilled,(t,n)=>{let r=n.meta.arg;t[r]&&(t[r].fetchState="done",t[r].suggestions=n.payload)}).addCase(ml.pending,t=>{t.default.fetchState="loading"}).addCase(ml.rejected,t=>{t.default.fetchState="error"}).addCase(ml.fulfilled,(t,n)=>{t.default.fetchState="done",t.default.suggestions=n.payload}).addCase(xe,()=>Ab)}}),{setTextSuggestions:V7}=Nb.actions,Mb=Nb.reducer;var Vo=x(C()),cN=({types:e,commands:t,onClick:n})=>{let r=G(),o=Y(pl),s=M(Gd);return(0,_b.useEffect)(()=>{e.forEach(({type:i})=>{(!s[i]||s[i].suggestions.length===0)&&r(vn(i))})},[]),(0,Vo.jsxs)("div",{children:[t.length>0&&(0,Vo.jsx)(he.List,{heading:o("commands"),children:t.map((i,a)=>(0,Vo.jsx)(he.ListItem,{id:`command-${a}`,closeOnSelect:!1,onClick:i.onClick,children:i.label},i.label))}),e.map(({type:i,title:a})=>{var l;return(0,Vo.jsx)(he.List,{heading:a,orientation:"vertical",children:(l=s[i])==null?void 0:l.suggestions.map((u,c)=>(0,Vo.jsx)(he.ListItem,{id:`${i}-${c}`,closeOnSelect:!1,description:u.title&&u.text,onClick:()=>n(u.text,u),"data-testid":"search-overlay-suggestion",children:u.title||u.text},`${u.id}-${u.text}`))},i)})]})},Db=cN;var De=x(C()),fN=200,pN=5,mN=4,qh=(e,t,n)=>e.slice(0,n?10:t.toLowerCase()==="image"?mN:pN),Fb=(e,t)=>!t||e.toLowerCase().includes(t.toLowerCase()),gN=()=>{var En,xr,we;let e=G(),t=Xt(),n=Y(pl),[r,o]=(0,ft.useState)(!1),[s,i]=(0,ft.useState)(""),[a,l]=(0,ft.useState)(null),u=M(eE),c=M(nr),[f,d]=(0,ft.useState)(),g=M(ut),y=z("showSearch"),v=z("enableSuggestionFeedback"),p=z("showEntitiesCommand"),m=z("showSummaryCommand"),h=z("showKnowledgeSearch"),S=z("showImageSearch"),w=z("searchTriggerKey"),k=M(DE),b=M(tE),R=M(nE),N=M(J1),_=((we=(xr=(En=c==null?void 0:c.uiConfig)==null?void 0:En.search)==null?void 0:xr.initialTypes)==null?void 0:we.filter(({isActive:B})=>B))||[],Q=(0,ft.useMemo)(()=>{let B=Pe=>qh(b.filter(fe=>fe.type===Pe.toUpperCase()),Pe,f),X=(k==null?void 0:k.map(Pe=>({value:Pe.code.toUpperCase(),label:`${Pe.name}s`,list:B(Pe.code.toUpperCase()),listOrientation:"vertical",lineClamp:!0})))||[];if(X.push({value:"PERSONAL",label:n("personalSuggestions"),list:B("PERSONAL"),lineClamp:!1,listOrientation:"vertical"},{value:"URL",label:n("urlSuggestions"),list:B("URL"),lineClamp:!1,listOrientation:"vertical"},{value:"STICKYMESSAGE",label:n("pinnedMessages"),list:B("STICKYMESSAGE"),lineClamp:!1,listOrientation:"vertical"}),S&&X.push({value:"IMAGE",label:n("imageSuggestions"),lineClamp:!1,list:B("IMAGE"),listOrientation:"horizontal"}),_.length===0)return X;let yt=_.map(Pe=>X.find(fe=>fe.value.toLowerCase()===Pe.type)).filter(Pe=>!!Pe),ce=X.filter(Pe=>!yt.find(fe=>fe.value===Pe.value));return[...yt,...ce]},[k,_,S,f]),K=[{label:n("entitiesClipboard"),onClick:()=>e(fn("entities")),shouldShow:p&&Fb(n("entitiesClipboard"),s)},{label:n("summaryClipboard"),onClick:()=>e(fn("summary")),shouldShow:m&&Fb(n("summaryClipboard"),s)},{label:s?`${n("knowledgeAssist")}: ${s}`:n("knowledgeAssist"),onClick:()=>e(fn("knowledgeAssist")),shouldShow:h}].filter(B=>B.shouldShow).filter(()=>!f),W=(0,ft.useCallback)((0,Hb.default)((B,X)=>{e(Lo({query:B,type:X,tags:["search-overlay"],size:f?50:20}))},fN),[f]),de=(0,ft.useCallback)((B,X)=>{switch(X.type){case"IMAGE":t.send(lh,{suggestion:X});break;default:t.send(Xr,{text:B,suggestion:X})}e(Nt(!1))},[e]),Ye=B=>{rr(B.text),e(ct({name:"entity copied",data:{entity:B,type:"copy"}})),e(Nt(!1))},Ft=B=>{t.send(Xr,{text:B,suggestion:{source:"knowledge-assist",text:B}}),e(ct({name:"answer used",data:{originalText:B},options:{includeConversationData:!0}})),i(""),a&&e(Ld(a)),e(fn("search")),e(Nt(!1))},ns=B=>{rr(B),e(Nt(!1))};function Ht(B){return X=>{r?window.confirm(n("warning"))&&(B(X),o(!1)):B(X)}}return(0,ft.useEffect)(()=>{s?W(s,f):e(fd())},[s,f]),(0,ft.useEffect)(()=>{g&&e(tl())},[g]),lb(w,()=>e(Nt(!0))),!y||!c?null:(0,De.jsxs)(he,{placeholder:n("searchPlaceholder"),typePlaceholder:n("typePlaceholder"),onChangeSearch:i,onChangeOpen:Ht(B=>e(Nt(B))),onChangeType:B=>d(B),onChangePage:Ht(B=>e(fn(B))),selectedType:f,search:s,page:u,isOpen:N,types:Q,updateDeps:[b],children:[(0,De.jsxs)(he.Page,{id:"search",children:[s.length===0&&(0,De.jsx)(Db,{types:_,commands:K,onClick:de}),s.length>0&&(0,De.jsxs)(ft.Fragment,{children:[K.length>0&&(0,De.jsx)(he.List,{heading:n("commands"),children:K.map((B,X)=>(0,De.jsx)(he.ListItem,{closeOnSelect:!1,onClick:B.onClick,id:`commands-${X}`,children:B.label},B.label))}),Q.map(({value:B,label:X,list:yt,lineClamp:ce,listOrientation:Pe})=>(0,De.jsx)(he.List,{heading:X,orientation:Pe==="horizontal"?"horizontal":"vertical",onShowAll:()=>d(B),hasMore:!f&&R[B.toLowerCase()]>qh(yt,B,f).length,children:qh(yt,B,f).map(fe=>(0,De.jsx)(he.ListItem,{id:`${B}-${fe.id}`,closeOnSelect:!1,lineClamp:ce,onClick:()=>de(fe.text,fe),description:B!=="IMAGE"?fe.title&&fe.text:void 0,extra:v&&(0,De.jsx)(he.ListItemActions,{children:(0,De.jsx)(qd,{context:s,source:"search",suggestion:fe})}),children:B==="IMAGE"?(0,De.jsx)(he.Image,{title:fe.title||fe.text,src:fe.image}):fe.title||fe.text},`${fe.id}-${fe.text}`))},B))]})]}),(0,De.jsx)(he.Page,{id:"entities",title:n("entitiesTitle"),onDismiss:Ht(()=>{e(fn("search"))}),children:(0,De.jsx)(fb,{onCopy:Ye})}),(0,De.jsx)(he.Page,{id:"summary",title:n("summaryTitle"),onDismiss:Ht(()=>{e(fn("search"))}),children:(0,De.jsx)(kb,{onCopy:ns})}),(0,De.jsx)(he.Page,{id:"knowledgeAssist",title:n("knowledgeAssist"),onDismiss:Ht(()=>{a&&e(Ld(a)),e(fn("search"))}),children:(0,De.jsx)(xb,{threadId:a,onNewThreadId:B=>l(B),question:s,onUse:Ft,onResetQuestion:()=>{a&&e(Ld(a)),i(""),l(null)}})})]})},Ub=gN;var gl=x(C()),hN=()=>{let e=z("showSearch"),t=z("isEmbedded");return(0,gl.jsxs)(zb.Fragment,{children:[e&&(0,gl.jsx)(Ub,{}),t&&(0,gl.jsx)(CE,{})]})},jb=hN;var Wb=x(se());var Qd=x(C()),Bb=({className:e})=>(0,Qd.jsx)("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",x:"0px",y:"0px",viewBox:"0 0 512 512",xmlSpace:"preserve",className:e,children:(0,Qd.jsx)("g",{children:(0,Qd.jsx)("path",{d:`M163.4,233h186v-70c0-25.6-9.4-47.8-27.3-65.7C304.2,79.4,282,70,256.4,70s-47.8,9.4-65.7,27.3
19
+ `),o=o.replace(/\n/g,"<br/>"),o}createContainer(t){var n;let o=(typeof global!="undefined"&&global.INTERWEAVE_SSR_POLYFILL||PO)();if(!o)return;let s=(n=this.props.containerTagName)!==null&&n!==void 0?n:"body",i=s==="body"||s==="fragment"?o.body:o.createElement(s);return t.match(CO)||(i.innerHTML=this.convertLineBreaks(this.props.escapeHtml?(0,GE.default)(t):t)),i}extractAttributes(t){let{allowAttributes:n}=this.props,r={},o=0;return t.nodeType!==qE||!t.attributes||([...t.attributes].forEach(s=>{let{name:i,value:a}=s,l=i.toLowerCase(),u=Hd[l]||Hd[i];if(!this.isSafe(t)||!l.match(TO)&&(!n&&(!u||u===Ih)||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===Jr?c=!0:u===_o?c=Number.parseFloat(String(c)):u!==Fd&&(c=String(c)),r[Lh[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,(s,i)=>String(i).toUpperCase())]=o)}),n}getTagConfig(t){let n={children:[],content:0,invalid:[],parent:[],self:!0,tagName:"",type:0,void:!1};return il[t]?I(T(T({},n),il[t]),{tagName:t}):n}isSafe(t){if(typeof HTMLAnchorElement!="undefined"&&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:s,transform:i,transformOnlyAllowList:a}=this.props,l=[],u="";return[...t.childNodes].forEach(c=>{if(c.nodeType===qE){let d=c.nodeName.toLowerCase(),g=this.getTagConfig(d);u&&(l.push(u),u="");let y=this.applyNodeFilters(d,c);if(!y)return;let v;if(i&&!(a&&!this.isTagAllowed(d))){this.keyIndex+=1;let p=this.keyIndex;v=this.parseNode(y,g);let m=i(y,v,g);if(m===null)return;if(typeof m!="undefined"){l.push(Fo.default.cloneElement(m,{key:p}));return}this.keyIndex=p-1}if(this.banned.has(d))return;if(!(r||o&&d!=="br")&&this.isTagAllowed(d)&&(s||this.canRenderChild(n,g))){var f;this.keyIndex+=1;let p=this.extractAttributes(y),m={tagName:d};p&&(m.attributes=p),g.void&&(m.selfClose=g.void),l.push(Fo.default.createElement(Ud,I(T({},m),{key:this.keyIndex}),(f=v)!==null&&f!==void 0?f:this.parseNode(y,g)))}else l=[...l,...this.parseNode(y,g.tagName?g:n)]}else if(c.nodeType===bO){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,s=null;for(;s=o.match(kO);){let[i,a]=s,l=s.index,u=i.includes("/");l>0&&(r.push(o.slice(0,l)),o=o.slice(l));let{children:c,matcher:f,props:d}=n[a],g;if(u)g=i.length,r.push(f.createElement(c,d));else{let y=o.match(new RegExp(`{{{/${a}}}}`));g=y.index+y[0].length,r.push(f.createElement(this.replaceTokens(o.slice(i.length,y.index),n),d))}o=o.slice(g)}return o.length>0&&r.push(o),r.length===0?"":r.length===1&&typeof r[0]=="string"?r[0]:r}};function RO(e){var t;let{attributes:n,className:r,containerTagName:o,content:s,emptyContent:i,parsedContent:a,tagName:l,noWrap:u}=e,c=(t=o!=null?o:l)!==null&&t!==void 0?t:"span",f=c==="fragment"?!0:u,d;if(a)d=a;else{let g=new zd(s!=null?s:"",e).parse();g.length>0&&(d=g)}return d||(d=i),f?Fo.default.createElement(Fo.default.Fragment,null,d):Fo.default.createElement(Ud,{attributes:n,className:r,tagName:c},d)}function ui(e){let k=e,{attributes:t,className:n,content:r="",disableFilters:o=!1,disableMatchers:s=!1,emptyContent:i=null,filters:a=[],matchers:l=[],onAfterParse:u=null,onBeforeParse:c=null,tagName:f="span",noWrap:d=!1}=k,g=ee(k,["attributes","className","content","disableFilters","disableMatchers","emptyContent","filters","matchers","onAfterParse","onBeforeParse","tagName","noWrap"]),y=s?[]:l,v=o?[]:a,p=c?[c]:[],m=u?[u]:[];y.forEach(b=>{b.onBeforeParse&&p.push(b.onBeforeParse.bind(b)),b.onAfterParse&&m.push(b.onAfterParse.bind(b))});let h=p.reduce((b,R)=>R(b,e),r!=null?r:""),S=new zd(h,g,y,v),w=m.reduce((b,R)=>R(b,e),S.parse());return Fo.default.createElement(RO,{attributes:t,className:n,containerTagName:e.containerTagName,emptyContent:i,noWrap:d,parsedContent:w.length===0?void 0:w,tagName:f})}var tb=x(D());var AO=/[.*+?^${}()|[\]\\]/g,IO=/[^0-9A-Za-zÀ-ÖØ-öø-ÿ](?=[0-9A-Za-zÀ-ÖØ-öø-ÿ]*$)/;function LO(e){return e.replace(AO,"\\$&")}function OO(e,t){let n=e.split("").findIndex((r,o)=>r!==t[o]);return n>-1?n:Math.min(e.length,t.length)}function NO(e){return e.search(IO)}function YE(e,t=[]){let n=e;return t.forEach(r=>{if(!r)return;let o=new RegExp(`\\b(${LO(r)})\\b`,"gi");n=n.replace(o,"<strong>$1</strong>")}),n}function QE(e){return e.replace(ou,'<mark data-type="placeholder">$1</mark>')}function ci(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function MO(e,t){return e.split("").map((i,a)=>({char:i,index:a})).filter(({char:i,index:a})=>/\s/.test(i)&&a<=t).map(({index:i})=>i).reverse()[0]}function Nh(e,t,n={}){if(t){let r=OO(t.toLowerCase(),e.toLowerCase()),o=ci(e.substring(r,e.length));if(n.stripAgentPart){let l=e.substring(0,r),u=NO(l);return`<span style="opacity: 0.5">${l.substring(u+1)}</span>${o}`}let i=t.split(n0).length>3||t.length>30?MO(t.trim(),r):0;return`${`${i>0?"\u2026":""}${ci(e.substring(i,r))}`}<strong>${o}</strong>`}return e}var _O=/(<\/[a-zA-Z]+[0-9]?>|<[a-zA-Z]+\s?\/>|<br>)/i;function jd(e){return _O.test(e)}function XE(e){var n;let t=document.createElement("template");return t.innerHTML=e,(n=t.content.textContent)!=null?n:""}var Bd=x(D()),eb=x(C()),ZE=Bd.default.createContext(void 0);function eo(){let e=Bd.default.useContext(ZE);if(e===void 0)throw new Error("useCommandPalette must be used within the CommandPalette component");return e}var JE=({children:e,page:t,isOpen:n,onChangeOpen:r,selected:o,setSelected:s})=>{let i=Bd.default.useMemo(()=>({page:t,isOpen:n,onChangeOpen:r,selected:o,setSelected:s}),[n,t,o]);return(0,eb.jsx)(ZE.Provider,{value:i,children:e})};var Zt=x(C()),DO=3,nb=({children:e})=>{let t=L("CommandPalette",_t);return(0,Zt.jsx)("div",{className:t.listItemActions,children:e})};function Mh(d){var g=d,{closeOnSelect:e=!0,lineClamp:t,children:n,onClick:r,extra:o,onSourceClick:s,description:i,sources:a,id:l,styles:u,defaultSourcesAmount:c=DO}=g,f=ee(g,["closeOnSelect","lineClamp","children","onClick","extra","onSourceClick","description","sources","id","styles","defaultSourcesAmount"]);var k;let y=Y(or),[v,p]=(0,tb.useState)(!1),{selected:m,onChangeOpen:h}=eo(),S=L("CommandPalette",_t);function w(b){r(b),e&&h(!1)}return(0,Zt.jsxs)("div",{className:(0,al.default)(S.listItem,l===m&&S.listItemSelected),children:[(0,Zt.jsx)("button",I(T({type:"button",className:S.listItemAction,"aria-disabled":(k=f.disabled)!=null?k:!1,onClick:w,"data-command-palette-item":!0,"data-item-id":l},f),{children:(0,Zt.jsxs)("div",{className:S.listItemContent,children:[typeof n=="string"?(0,Zt.jsx)("p",{className:(0,al.default)(S.listItemText,S.truncate,u==null?void 0:u.title),children:n}):n,i&&(0,Zt.jsx)(ui,{tagName:"p",allowList:[],content:jd(i)?XE(i):i,className:(0,al.default)(S.listItemDescription,u==null?void 0:u.description,t?S.lineClamp:S.truncate)})]})})),o,a&&a.length>0&&(0,Zt.jsxs)("div",{className:S.sources,children:[(0,Zt.jsx)("span",{className:S.sourcesTitle,children:y("sources")}),a.slice(0,v?a.length:c).map(b=>(0,Zt.jsx)("a",{className:S.source,href:b.url,target:"_blank",title:b.url,rel:"noopener noreferrer","data-testid":"source",onClick:()=>s&&s(b),children:b.name},b.url)),!v&&a.length>c&&(0,Zt.jsx)("button",{className:(0,al.default)(S.source,S.sourceShowMore),type:"button",onClick:()=>p(!0),children:y("showMore",{amount:a.length-c})})]})]})}var ll=x(C()),rb=()=>(0,ll.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 256 512","aria-labelledby":"angleLeftTitle",children:[(0,ll.jsx)("title",{id:"angleLeftTitle",children:"AngleLeft"}),(0,ll.jsx)("path",{d:"M192 448c-8.188 0-16.38-3.125-22.62-9.375l-160-160c-12.5-12.5-12.5-32.75 0-45.25l160-160c12.5-12.5 32.75-12.5 45.25 0s12.5 32.75 0 45.25L77.25 256l137.4 137.4c12.5 12.5 12.5 32.75 0 45.25C208.4 444.9 200.2 448 192 448z"})]});var Ho=x(C());function _h({children:e,title:t,id:n,onDismiss:r}){let o=Y(or),s=L("CommandPalette",_t),{page:i}=eo();return i!==n?null:(0,Ho.jsxs)("div",{className:s.page,id:`page_${n}`,tabIndex:-1,children:[r&&(0,Ho.jsxs)("div",{className:s.pageNav,children:[(0,Ho.jsxs)("button",{className:s.pageBackButton,type:"button",onClick:r,children:[(0,Ho.jsx)(rb,{}),o("back")]}),t&&(0,Ho.jsx)("h3",{className:s.pageTitle,children:t})]}),e]})}var ob=x(D());var ul=x(C()),di=()=>(0,ul.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 24 24",width:"1em",fill:"currentColor",children:[(0,ul.jsx)("path",{d:"M0 0h24v24H0z",fill:"none"}),(0,ul.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 hn=x(C());function FO({onChange:e,onChangeType:t,placeholder:n,typePlaceholder:r,types:o,value:s,selectedType:i},a){let l=L("CommandPalette",_t);return(0,hn.jsxs)("div",{className:l.search,children:[(0,hn.jsx)("div",{className:l.searchIcon,children:(0,hn.jsx)(di,{})}),(0,hn.jsxs)("div",{className:l.searchInputWrapper,children:[(0,hn.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:s,type:"text",id:"command-palette-search-input",autoFocus:!0}),o&&o.length>0&&(0,hn.jsx)("div",{className:l.selectWrapper,children:(0,hn.jsxs)("select",{"data-testid":"command-palette-type-select",className:l.select,onChange:u=>t(u.target.value===r?void 0:u.target.value),value:i||r,children:[r&&(0,hn.jsx)("option",{children:r}),o.map(u=>(0,hn.jsx)("option",{value:u.value,children:u.label},u.value))]})})]})]})}var sb=(0,ob.forwardRef)(FO);var Dh=x(se());var Vd=x(C()),HO=o=>{var s=o,{onClick:e,shortKeys:t,children:n}=s,r=ee(s,["onClick","shortKeys","children"]);let i=L("CommandPalette",_t);return(0,Vd.jsxs)("button",I(T({type:"button"},r),{onClick:e,className:(0,Dh.default)(i.actionButton,r.className,{[i.hasShortKeys]:t&&t.length>0}),children:[n,t&&t.map(a=>(0,Vd.jsx)("span",{className:(0,Dh.default)(i.actionShortcut,a===8629&&i.actionShortcutFixKerning),children:typeof a=="number"?String.fromCharCode(a):a},a))]}))},ib=HO;var cl=x(C()),UO="[data-command-palette-item]";function Uo({placeholder:e="Start typing to search...",typePlaceholder:t="All types",defaultPage:n="search",page:r,onChangePage:o,onChangeSearch:s,onChangeType:i,onChangeOpen:a,selectedType:l,types:u,children:c,isOpen:f,search:d,updateDeps:g=[]}){let[y,v]=(0,ar.useState)(),p=(0,ar.useRef)(null),m=()=>{o&&o(n),i(void 0),s(""),a(!1)},h=()=>{var K;if(r!==n&&o){o(n);return}if(l&&i){i(void 0),(K=p.current)==null||K.focus();return}if(d.length>0){s("");return}a(!1)},S=()=>{let K=w();K.length!==0&&v(K[0].dataset.itemId)},w=()=>Array.from(document.querySelectorAll(UO)||[]),k=K=>document.querySelector(`[data-item-id=${K}]`),b=K=>{let W=k(K);W&&v(W.dataset.itemId)},R=K=>{let W=k(K);W&&W.scrollIntoView({behavior:"smooth"})},N=()=>{if(!y)return;let K=w(),W=k(y);if(!W)return;let de=K.indexOf(W),Ye=K[de+1];Ye&&Ye.dataset.itemId?b(Ye.dataset.itemId):S()},_=()=>{if(!y)return;let K=w(),W=k(y);if(!W)return;let de=K.indexOf(W),Ye=K[de-1];Ye&&Ye.dataset.itemId?b(Ye.dataset.itemId):b(K[K.length-1].dataset.itemId)},Q=(0,ar.useCallback)(K=>{switch(K.key){case"ArrowDown":{K.preventDefault(),N();break}case"ArrowUp":{K.preventDefault(),_();break}case"Enter":{if(y){let W=k(y);W==null||W.click()}break}}},[y]);return(0,ar.useEffect)(()=>{S()},[d,r,l,f,...g]),(0,ar.useEffect)(()=>{y&&R(y)},[y]),(0,cl.jsx)(Rd,{autoFocus:!0,contentAriaLabel:"Search Results",overlayAriaLabel:"Command Palette",isOpen:f,onBack:h,onClose:m,onKeyDown:Q,children:(0,cl.jsxs)(JE,{selected:y,setSelected:v,isOpen:f,onChangeOpen:a,page:r,children:[r===n&&(0,cl.jsx)(sb,{ref:p,onChange:s,onChangeType:i,placeholder:e,value:d,selectedType:l,types:u,typePlaceholder:t}),c]})})}Uo.Page=_h;Uo.List=Ch;Uo.Image=jE;Uo.ListItem=Mh;Uo.ListItemActions=nb;Uo.Button=ib;var he=Uo;var ab=x(D());function lb(e,t){(0,ab.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 dl=x(D());var ub={data:null,fetchState:"idle"},Kd=e=>{var s,i,a,l;let t=[],{visitorName:n}=(s=e.info.visitorInfo)!=null?s:{},{agentName:r,agentNickname:o}=(i=e.info.agentInfo)!=null?i:{};return r&&r!==n&&t.push(r),o&&o!==n&&t.push(o),(l=(a=e.entities.data)==null?void 0:a.filter(u=>!t.includes(u.text)))!=null?l:null},yn=V("entities/getEntities",(e,t)=>P(void 0,null,function*(){let{deepdeskAPI:n,dynamicThunkObject:r}=t.extra;if(!r.conversationQuery)return Promise.resolve([]);let o=r.conversationQuery,s=yield o();return s.length===0?Promise.resolve([]):n.getEntities(s)})),zO=e=>e.filter((t,n)=>n===e.findIndex(r=>r.text===t.text)),jO=J({name:"entities",initialState:ub,reducers:{},extraReducers:e=>{e.addCase(yn.pending,t=>{t.fetchState="loading"}).addCase(yn.rejected,t=>{t.fetchState="error"}).addCase(yn.fulfilled,(t,n)=>{t.fetchState="done",t.data=zO(t.data?[...t.data,...n.payload]:n.payload)}).addCase(xe,()=>ub)}}),cb=jO.reducer;var Fh={};Xe(Fh,{enUS:()=>BO,nlNL:()=>VO});var BO={noResults:[{type:0,value:"No entities have been found"}],copy:[{type:0,value:"Copy"}],use:[{type:0,value:"Use"}]},VO={noResults:[{type:0,value:"Er zijn geen entiteiten gevonden"}],copy:[{type:0,value:"Kopieer"}],use:[{type:0,value:"Gebruik"}]};var db={root:"dd-TYTKs",empty:"dd-AU7uT"};var fi=x(C()),KO=({onCopy:e})=>{let t=(0,dl.useRef)(null),n=L("EntitiesList",db),r=M(Kd),{setSelected:o}=eo(),s=Y(Fh),i=G();return(0,dl.useEffect)(()=>{i(yn())},[]),(0,dl.useEffect)(()=>{t.current&&(t.current.focus(),o("entity-0"))},[t]),(0,fi.jsxs)("div",{className:n.root,ref:t,tabIndex:-1,children:[r&&r.length>0&&(0,fi.jsx)(he.List,{children:r.map((a,l)=>(0,fi.jsx)(he.ListItem,{id:`entity-${l}`,closeOnSelect:!0,onClick:()=>e(a),children:a.text},a.text))},"entities"),r&&r.length===0&&(0,fi.jsx)("p",{className:n.empty,children:s("noResults")})]})},fb=KO;var zo=x(D());var pi=x(D());function pb(e,t){let n=(0,pi.useRef)(e);n.current=e;let[r,o]=(0,pi.useState)(void 0),[s,i]=(0,pi.useState)(void 0),[a,l]=(0,pi.useState)("idle"),u=G();return{error:s,state:a,data:r,call:f=>{l("loading"),u(n.current(f)).unwrap().then(d=>{o(d),l("done"),t!=null&&t.onSuccess&&(t==null||t.onSuccess(d))}).catch(d=>{i(d),l("error"),t!=null&&t.onError&&(t==null||t.onError(d))})}}}var Wd=x(se()),yb=x(D());var Hh=x(C()),Uh=e=>(0,Hh.jsx)("svg",I(T({width:"16",height:"16",fill:"#000000"},e),{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,Hh.jsx)("path",{fillRule:"evenodd",d:"M6.57086468,14.9173453 C6.38997052,14.9711236 6.19835748,15 6,15 L4,15 C2.8954305,15 2,14.1045695 2,13 L2,4 C2,2.8954305 2.8954305,2 4,2 L6,2 C6.68685475,2 7.29284112,2.34623869 7.65294381,2.87370078 C7.95642355,2.67736738 8.29504785,2.51351337 8.66312366,2.3818197 C9.50544052,2.08044754 10.3408482,1.9879107 10.9989281,1.99971266 C11.0150698,2.00005426 13.3487605,2.00015005 18,2 C20.7551411,2 22,6.05643086 22,12 C22,13.6824804 20.8695981,15 19,15 L15.9269768,15 C15.9359266,15.0245465 15.9451954,15.0497804 15.9547911,15.0757271 C16.007193,15.2174219 16.2391583,15.8256341 16.2970775,15.9810953 C16.4872151,16.4914441 16.6259612,16.9026411 16.7382242,17.3098712 C16.9079007,17.9253665 17,18.4798886 17,19 C17,20.4720069 16.091867,21.3862822 14.748281,21.777514 C14.1422801,21.9539723 13.6147967,22.0000922 13.0076976,22.0000008 L12.5204954,22 L12.2202699,21.6261158 C11.2556275,20.4248034 7.64562469,16.4822788 6.57086468,14.9173453 Z M8,13 C8,13.2401953 8.04443154,13.4528921 8.14171093,13.6800176 C8.40663864,14.2985643 11.914268,18.1371493 13.4599624,19.9848695 C13.7113931,19.9660111 13.9483736,19.9273712 14.1891338,19.8572655 C14.7621788,19.6904035 15,19.4509737 15,19 C15,18.6834183 14.9359344,18.2976852 14.8101464,17.8413935 C14.7161494,17.500423 14.5944107,17.1396301 14.4229225,16.6793379 C14.3689242,16.5344009 14.1358033,15.923159 14.0789589,15.7694517 C13.9489218,15.4178313 13.8632547,15.1589343 13.8046536,14.9236885 C13.5555377,13.9236468 13.8054549,13 15,13 L19,13 C19.6912225,13 20,12.6401099 20,12 C20,7.20925475 19.015127,4 18,4 C15.9322103,4 15.9322103,4 10.9655994,3.99940813 C10.5253746,3.99154158 9.91062406,4.05963657 9.33687634,4.2649175 C8.45196659,4.58152894 8,5.09776992 8,6 L8,13 Z M4,4 L4,13 L6,13 L6,4 L4,4 Z"})}));var zh=x(C()),mb=e=>(0,zh.jsx)("svg",I(T({width:"16",height:"16",fill:"#000000"},e),{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,zh.jsx)("path",{fillRule:"evenodd",d:"M7.65336736,21.1256786 C7.2933164,21.6534897 6.68712411,22 6,22 L4,22 C2.8954305,22 2,21.1045695 2,20 L2,11 C2,9.8954305 2.8954305,9 4,9 L6,9 C6.198171,9 6.38961023,9.02882212 6.57035446,9.08250314 C7.6444817,7.51807482 11.2554748,3.57449216 12.2202699,2.37298955 L12.5204954,1.99910538 L13,1.99910538 C13.6147967,1.99901314 14.1422801,2.04513312 14.748281,2.22159137 C16.091867,2.61282321 17,3.52709845 17,4.99910538 C17,5.51921677 16.9079007,6.07373891 16.7382242,6.68923415 C16.6259612,7.09646424 16.4872151,7.50766133 16.2970775,8.01801005 C16.2391583,8.17347129 16.007193,8.78168345 15.9547911,8.92337824 C15.9451954,8.94932503 15.9359266,8.9745589 15.9269768,8.99910538 L19,8.99910538 C20.8695981,8.99910538 22,10.316625 22,11.9991054 C22,17.9426745 20.7551411,21.9991054 18,21.9991054 L11.0344006,21.9985135 C10.3408482,22.0111947 9.50544052,21.9186578 8.66312366,21.6172857 C8.29521907,21.4856533 7.9567386,21.3218904 7.65336736,21.1256786 Z M8,17.9991054 C8,18.9013355 8.45196659,19.4175764 9.33687634,19.7341879 C9.91062406,19.9394688 10.5253746,20.0075638 10.963066,19.9997143 C10.9703499,19.9995545 10.9703499,19.9995545 11,19.9991054 L18,19.9991054 C19.015127,19.9991054 20,16.7898506 20,11.9991054 C20,11.3589955 19.6912225,10.9991054 19,10.9991054 L15,10.9991054 C13.8054549,10.9991054 13.5555377,10.0754586 13.8046536,9.07541689 C13.8632547,8.84017106 13.9489218,8.5812741 14.0789589,8.22965366 C14.1358033,8.07594642 14.3689242,7.46470447 14.4229225,7.31976744 C14.5944107,6.85947528 14.7161494,6.4986824 14.8101464,6.1577119 C14.9359344,5.70142019 15,5.31568707 15,4.99910538 C15,4.54813166 14.7621788,4.30870189 14.1891338,4.1418399 C13.9483736,4.07173418 13.7113931,4.0330943 13.4599624,4.01423587 C11.914268,5.86195611 8.40663864,9.70054105 8.14171093,10.3190878 C8.04443154,10.5462133 8,10.7589101 8,10.9991054 L8,17.9991054 Z M4,11 L4,20 L6,20 L6,11 L4,11 Z"})}));function mi(e,t){var o;let n=e.cloneNode(!0);n.style.top=`${e.offsetTop}px`,n.style.left=`${e.offsetLeft}px`,n.style.position="absolute",t.split(" ").forEach(s=>{n.classList.add(s)}),n.addEventListener("animationend",()=>n.remove()),(o=e.parentElement)==null||o.appendChild(n)}var jh={};Xe(jh,{enUS:()=>WO,nlNL:()=>$O});var WO={thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},$O={thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};function gb(e){return V("analytics/logEvent",(t,n)=>{var s,i,a;let r=(i=(s=n.getState())==null?void 0:s.conversation.current)==null?void 0:i.id,o=(a=n.getState())==null?void 0:a.info.agentInfo;return n.extra.deepdeskAPI.sendEvent(t.name,I(T({conversationId:r},o),{data:t.data}))})(e)}function gi(){let e=G();return(t,n)=>P(this,null,function*(){yield e(gb({name:t,data:n}))})}var hb={thumbs:"dd-5F1zq",fadeup:"dd-eTmY-",fadedown:"dd-sS85z",selected:"dd-rid-f",thumbsUp:"dd-4poEf",thumbsDown:"dd-3KozS"};var hi=e=>t=>{let{passwordlessToken:{token:n},settings:{isEmbedded:r,adminUrl:o}}=t,s=o||window.location.origin;return r&&!n?null:r&&n?`${s}/apis/admin/session/passwordless/login/?token=${n}&redirect=${encodeURIComponent(e)}`:`${s}${e}`};var lr=x(C()),qO=({eventName:e,eventData:t,feedbackType:n,feedbackText:r})=>{let o=L("FeedbackThumbs",hb),s=z("enableFeedbackForm"),i=M(Yr),a=M(hi(`/admin/feedback?conversationId=${i}&type=${n}&text=${r}&data=${JSON.stringify(t)}`)),l=Y(jh),u=gi(),[c,f]=(0,yb.useState)(null),d=y=>{y.stopPropagation(),mi(y.target,o.fadeup),f("up"),u(e,I(T({},t),{rating:"up"}))},g=y=>{y.stopPropagation(),mi(y.target,o.fadedown),f("down"),u(e,I(T({},t),{rating:"down"}))};return(0,lr.jsxs)("div",{className:o.thumbs,children:[(0,lr.jsx)(re.Button,{title:l("thumbsUp"),onClick:d,icon:(0,lr.jsx)(mb,{}),className:(0,Wd.default)(o.thumbsUp,c==="up"&&o.selected),disabled:!!c}),s&&a?(0,lr.jsx)(re.Button,{as:"a",title:l("thumbsDown"),href:a,target:"_blank",rel:"noreferrer",onClick:g,icon:(0,lr.jsx)(Uh,{}),className:(0,Wd.default)(o.thumbsDown,c==="down"&&o.selected),disabled:!!c}):(0,lr.jsx)(re.Button,{title:l("thumbsDown"),onClick:g,icon:(0,lr.jsx)(Uh,{}),className:(0,Wd.default)(o.thumbsDown,c==="down"&&o.selected),disabled:!!c})]})},yi=qO;var fl=x(C()),vb=()=>(0,fl.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 512 512","aria-labelledby":"paperPlaneTitle",children:[(0,fl.jsx)("title",{id:"paperPlaneTitle",children:"PaperPlane"}),(0,fl.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 Bh={};Xe(Bh,{enUS:()=>GO,nlNL:()=>YO});var GO={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"}]},YO={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 Sb={root:"dd-fxP4c",title:"dd-vDbMh",empty:"dd-sB0lz",status:"dd--oZ1C",form:"dd-t0hnD",input:"dd-i1v3W",submit:"dd-oo2Oa",question:"dd-WvK17",answer:"dd-HAHcU",alignRight:"dd-oxrX3",listItemFeedback:"dd-POUal"};var dt=x(C()),QO=({threadId:e,onNewThreadId:t,onUse:n,onResetQuestion:r,question:o})=>{var p;let[s,i]=zo.default.useState(""),{setSelected:a}=eo(),l=(0,zo.useRef)(null),u=L("KnowledgeSearchStyles",Sb),c=Y(Bh),f=G(),d=(p=M(Eh(e!=null?e:-1)))!=null?p:[],g=pb(m=>bh({input:m,threadId:e,onNewThreadId:h=>t(h)}),{onSuccess(m){f(ct({name:"knowledge assist question answered",data:{question:s||o,sources:m.answer.sources,answer:m.answer.answer,isFollowUpQuestion:d.length>=1},options:{includeConversationData:!0}})),a(`knowledge-assist-${d.length}`),i("")}}),y=m=>P(void 0,null,function*(){m.preventDefault(),m.stopPropagation(),s!==""&&g.call(s)}),v=(m,h)=>{f(ct({name:"knowledge assist source viewed",data:{question:h,sourceViewed:m.url||m.name},options:{includeConversationData:!0}}))};return(0,zo.useEffect)(()=>{var m;o&&g.state==="idle"?g.call(o):(m=l.current)==null||m.focus()},[l,g.state]),(0,zo.useEffect)(()=>{l.current&&l.current.scrollIntoView({behavior:"smooth"})},[l,d]),(0,dt.jsxs)("div",{className:u.root,children:[d.length>0&&(0,dt.jsx)("div",{className:u.alignRight,children:(0,dt.jsx)(he.Button,{onClick:r,children:c("reset")})}),d.map(({question:m,answer:h},S)=>(0,dt.jsx)(he.List,{children:(0,dt.jsx)(he.ListItem,{id:`knowledge-assist-${S}`,"data-testid":"knowledge-search-answer",description:h.answer,closeOnSelect:!0,onClick:()=>n(h.answer),onSourceClick:w=>v(w,m),sources:h.sources,styles:{title:u.question,description:u.answer},extra:(0,dt.jsx)("div",{className:u.listItemFeedback,children:(0,dt.jsx)(yi,{feedbackText:h.answer,feedbackType:"knowledge-assist-answer",eventName:"knowledge assist feedback",eventData:T({question:m,isAgent:o!==m,isFollowUpQuestion:d.length>1},h)})}),children:m})},`${h.answer}_${S}`)),g.state==="loading"&&(0,dt.jsx)("p",{className:u.status,children:c("loading")}),g.state==="error"&&(0,dt.jsx)("p",{className:u.status,children:c("error")}),(0,dt.jsxs)("form",{className:u.form,onSubmit:y,children:[(0,dt.jsx)("input",{ref:l,placeholder:c("anotherQuestion"),className:u.input,type:"text",value:s,onFocus:()=>{a(void 0)},onChange:m=>{a(void 0),i(m.target.value)}}),(0,dt.jsx)("button",{type:"submit",className:u.submit,disabled:g.state==="loading",children:(0,dt.jsx)(vb,{})})]})]})},xb=QO;var Ge=x(D()),wb=x(se());var Vh={root:"dd-uVyL0",trigger:"dd-KIzQa",content:"dd-Ly3zO",contentOpen:"dd-O-8fR",contentTop:"dd-q3fGa",contentBottom:"dd-SFrvc",item:"dd-HZNy-"};var jo=x(C()),XO=0,Eb=Ge.default.createContext(null),ZO=()=>{let e=(0,Ge.useContext)(Eb);if(!e)throw new Error("Invalid DropdownContext");return e},bb=({trigger:e,children:t,position:n="bottom"})=>{let r=(0,Ge.useMemo)(()=>++XO,[]),o=(0,Ge.useRef)(null),s=(0,Ge.useRef)(null),i=L("Dropdown",Vh),[a,l]=(0,Ge.useState)(!1),[u,c]=(0,Ge.useState)(n),f=g=>{g.preventDefault(),g.stopPropagation(),l(!a)},d=(0,Ge.useCallback)(([g])=>{!g.isIntersecting&&a&&c(u==="top"?"bottom":"top")},[a]);return(0,Ge.useEffect)(()=>{let g=y=>{o.current&&!o.current.contains(y.target)&&l(!1)};return document.addEventListener("click",g),()=>{document.removeEventListener("click",g)}},[]),(0,Ge.useEffect)(()=>{if(!s.current&&!a)return()=>{};let g=new IntersectionObserver(d,{root:null,rootMargin:"0px",threshold:1});return s.current&&g.observe(s.current),()=>{s.current&&g.unobserve(s.current)}},[s,a]),(0,jo.jsx)(Eb.Provider,{value:{setIsOpen:l},children:(0,jo.jsxs)("div",{ref:o,className:i.root,children:[(0,jo.jsx)("button",{id:`dropdown-${r}`,"data-testid":"dropdown-trigger","aria-haspopup":"true","aria-expanded":a,"aria-label":"Dropdown trigger",type:"button",className:i.trigger,onClick:f,children:e}),(0,jo.jsx)("div",{"data-testid":"dropdown-content",ref:s,"aria-hidden":!a,"aria-labelledby":`dropdown-${r}`,className:(0,wb.default)(i.content,{[i.contentOpen]:a,[i.contentTop]:u==="top",[i.contentBottom]:u==="bottom"}),children:t})]})})};function JO(o){var s=o,{as:e,children:t,onClick:n}=s,r=ee(s,["as","children","onClick"]);let i=e||"button",a=L("Dropdown",Vh),{setIsOpen:l}=ZO(),u=c=>{l(!1),n(c),c.stopPropagation()};return(0,jo.jsx)(i,I(T({type:"button",className:a.item,onClick:u},r),{children:t}))}bb.Item=JO;var Kh=bb;var Wh=x(C()),Cb=e=>(0,Wh.jsx)("svg",I(T({xmlns:"http://www.w3.org/2000/svg",height:"16",width:"14",viewBox:"0 0 448 512"},e),{children:(0,Wh.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 Bo={};Xe(Bo,{enUS:()=>eN,nlNL:()=>tN});var eN={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"}]},tN={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 $d=x(C()),nN=({suggestion:e,source:t,context:n})=>{let r=Y(Bo),o=M(Yr),s=G(),i=z("enableSuggestionFeedback"),a=`${e.text}`,l=M(hi(`/admin/feedback?conversationId=${o}&type=${t}&text=${a}&data=${JSON.stringify({context:n})}`)),u=()=>{s(ct({name:"suggestion feedback",data:{text:e.text,source:t,context:n},options:{includeConversationData:!0}}))};return!i||!l?null:(0,$d.jsx)(Kh,{trigger:(0,$d.jsx)(Cb,{"data-testid":"feedback-dropdown-trigger"}),children:(0,$d.jsx)(Kh.Item,{as:"a",onClick:u,target:"_blank",href:l,children:r("giveFeedback")})})},qd=nN;var Jt=x(D());var $h={};Xe($h,{enUS:()=>rN,nlNL:()=>oN});var rN={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."}]},oN={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 Tb={root:"dd-60NZr",actions:"dd-No1g3",main:"dd-l-xEF",textInput:"dd-nAaiV",loading:"dd-ciFNi",error:"dd-yNp2D"};var Nn=x(C()),sN=({onCopy:e})=>{let t=(0,Jt.useRef)(null),n=L("SummaryForm",Tb),[r,o]=(0,Jt.useState)(""),[s,i]=(0,Jt.useState)(""),[a,l]=(0,Jt.useState)(!1),u=M(nr),c=Y($h),f=G(),d=()=>{f(ct({name:"summary copied to clipboard",data:{originalText:r,finalText:s},options:{includeConversationData:!0}})),e(s)},g=()=>{let y=document.getSelection();y&&f(ct({name:"summary copied to clipboard",data:{originalText:r,finalText:y==null?void 0:y.toString(),assistant:u==null?void 0:u.summarizerAssistantNew},options:{includeConversationData:!0}}))};return(0,Jt.useEffect)(()=>{f(li({})).then(y=>{if(y.error){l(!0);return}o(y.payload||""),i(y.payload||"")})},[]),(0,Jt.useEffect)(()=>{t.current&&r&&t.current.focus()},[t,r]),(0,Jt.useEffect)(()=>{let y=v=>{v.key==="Enter"&&v.shiftKey&&d()};return document.addEventListener("keydown",y),()=>{document.removeEventListener("keydown",y)}},[s]),(0,Nn.jsx)("div",{className:n.root,tabIndex:-1,children:a?(0,Nn.jsx)("p",{className:n.error,children:c("error")}):(0,Nn.jsxs)(Jt.Fragment,{children:[(0,Nn.jsx)("div",{className:n.main,children:(0,Nn.jsx)("textarea",{placeholder:r?void 0:c("loading"),disabled:!r,className:n.textInput,ref:t,value:s,onCopy:g,onChange:y=>i(y.target.value)})}),(0,Nn.jsxs)("div",{className:n.actions,children:[(0,Nn.jsx)(yi,{feedbackText:r||"",feedbackType:"summary",eventName:"summary feedback",eventData:{summary:r}}),(0,Nn.jsx)(he.Button,{shortKeys:[8679,8629],onClick:d,children:c("copy")})]})]})})},kb=sN;var pl={};Xe(pl,{enUS:()=>iN,nlNL:()=>aN});var iN={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?"}]},aN={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 _b=x(D());var lN=["{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}"],uN=new RegExp(lN.map(e=>`(?:${e.replace("{","\\{").replace("}","\\}")})`).join("|"));function Pb(e,t){let n=e.split(uN),r=0,o=[];for(let s=0;s<n.length;s++){let i=n[s];if(o.push(i),s===n.length-1)break;if(t.indexOf(i)===-1)return e;let a=n[s+1],l=s===n.length-2;r+=i.length;let u=r;if(l){let f=a.charAt(0),d=0;do u=f?t.indexOf(f,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 Rb(e,t){return typeof t=="boolean"?e:e.slice(0,t)}var Ib={suggestions:[],fetchState:"idle"},Ab={default:Ib},Lb=e=>t=>{var n,r;return(r=(n=t.textSuggestions[e])==null?void 0:n.suggestions)!=null?r:[]},Gd=e=>e.textSuggestions,Ob=e=>{let t=e.toLowerCase();return n=>{let r=n.text.toLowerCase();return r.startsWith(t)&&r.length>t.length}},Yd=Ie("textSuggestions/refresh"),vn=V("textSuggestions/recommendations",(e,t)=>P(void 0,null,function*(){var c;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=(c=r.conversation.current)==null?void 0:c.id,{platformVariables:s}=r.info,{textSuggestionsCount:i,inlineSuggestions:a}=r.settings,l=si(r);if(!o)throw new Error("No current conversation to fetch text suggestions");let u=yield n.getTextSuggestions(o,$a(r),e);if(s&&(u=u.map(f=>T(I(T({},f),{text:qe(f.text,s)}),f.title?{title:qe(f.title,s)}:{}))),e==="default"){let f=a?u.filter(Ob(l)):u;t.dispatch(Qr(f.slice(0,i)))}return u})),ml=V("textSuggestions/autocompletions",(e,t)=>P(void 0,null,function*(){var c;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=(c=r.conversation.current)==null?void 0:c.id,{platformVariables:s}=r.info,{textSuggestionsCount:i,deanonymize:a,inlineSuggestions:l}=r.settings;if(!o)throw new Error("No current conversation to fetch text suggestions");let u=yield n.getAutocompleteSuggestions(o,I(T({},$a(r)),{input:e}));if(!t.getState().input.text)throw new Error("Abort");return l&&(u=u.filter(Ob(e))),s&&(u=u.map(f=>I(T({},f),{text:qe(f.text,s)}))),a&&(u=u.map(f=>I(T({},f),{text:f.source!=="trie-with-typos"?Pb(f.text,e):f.text}))),u=Rb(u,i),t.dispatch(Qr(u)),u})),Nb=J({name:"textSuggestions",initialState:Ab,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}}}}},extraReducers:e=>{e.addCase(vn.pending,(t,n)=>{let r=n.meta.arg,o=t[r]||Ib;return I(T({},t),{[r]:I(T({},o),{fetchState:"loading"})})}).addCase(vn.rejected,(t,n)=>{let r=n.meta.arg;t[r]&&(t[r].fetchState="error")}).addCase(vn.fulfilled,(t,n)=>{let r=n.meta.arg;t[r]&&(t[r].fetchState="done",t[r].suggestions=n.payload)}).addCase(ml.pending,t=>{t.default.fetchState="loading"}).addCase(ml.rejected,t=>{t.default.fetchState="error"}).addCase(ml.fulfilled,(t,n)=>{t.default.fetchState="done",t.default.suggestions=n.payload}).addCase(xe,()=>Ab)}}),{setTextSuggestions:V7}=Nb.actions,Mb=Nb.reducer;var Vo=x(C()),cN=({types:e,commands:t,onClick:n})=>{let r=G(),o=Y(pl),s=M(Gd);return(0,_b.useEffect)(()=>{e.forEach(({type:i})=>{(!s[i]||s[i].suggestions.length===0)&&r(vn(i))})},[]),(0,Vo.jsxs)("div",{children:[t.length>0&&(0,Vo.jsx)(he.List,{heading:o("commands"),children:t.map((i,a)=>(0,Vo.jsx)(he.ListItem,{id:`command-${a}`,closeOnSelect:!1,onClick:i.onClick,children:i.label},i.label))}),e.map(({type:i,title:a})=>{var l;return(0,Vo.jsx)(he.List,{heading:a,orientation:"vertical",children:(l=s[i])==null?void 0:l.suggestions.map((u,c)=>(0,Vo.jsx)(he.ListItem,{id:`${i}-${c}`,closeOnSelect:!1,description:u.title&&u.text,onClick:()=>n(u.text,u),"data-testid":"search-overlay-suggestion",children:u.title||u.text},`${u.id}-${u.text}`))},i)})]})},Db=cN;var De=x(C()),fN=200,pN=5,mN=4,qh=(e,t,n)=>e.slice(0,n?10:t.toLowerCase()==="image"?mN:pN),Fb=(e,t)=>!t||e.toLowerCase().includes(t.toLowerCase()),gN=()=>{var En,xr,we;let e=G(),t=Xt(),n=Y(pl),[r,o]=(0,ft.useState)(!1),[s,i]=(0,ft.useState)(""),[a,l]=(0,ft.useState)(null),u=M(eE),c=M(nr),[f,d]=(0,ft.useState)(),g=M(ut),y=z("showSearch"),v=z("enableSuggestionFeedback"),p=z("showEntitiesCommand"),m=z("showSummaryCommand"),h=z("showKnowledgeSearch"),S=z("showImageSearch"),w=z("searchTriggerKey"),k=M(DE),b=M(tE),R=M(nE),N=M(J1),_=((we=(xr=(En=c==null?void 0:c.uiConfig)==null?void 0:En.search)==null?void 0:xr.initialTypes)==null?void 0:we.filter(({isActive:B})=>B))||[],Q=(0,ft.useMemo)(()=>{let B=Pe=>qh(b.filter(fe=>fe.type===Pe.toUpperCase()),Pe,f),X=(k==null?void 0:k.map(Pe=>({value:Pe.code.toUpperCase(),label:`${Pe.name}s`,list:B(Pe.code.toUpperCase()),listOrientation:"vertical",lineClamp:!0})))||[];if(X.push({value:"PERSONAL",label:n("personalSuggestions"),list:B("PERSONAL"),lineClamp:!1,listOrientation:"vertical"},{value:"URL",label:n("urlSuggestions"),list:B("URL"),lineClamp:!1,listOrientation:"vertical"},{value:"STICKYMESSAGE",label:n("pinnedMessages"),list:B("STICKYMESSAGE"),lineClamp:!1,listOrientation:"vertical"}),S&&X.push({value:"IMAGE",label:n("imageSuggestions"),lineClamp:!1,list:B("IMAGE"),listOrientation:"horizontal"}),_.length===0)return X;let yt=_.map(Pe=>X.find(fe=>fe.value.toLowerCase()===Pe.type)).filter(Pe=>!!Pe),ce=X.filter(Pe=>!yt.find(fe=>fe.value===Pe.value));return[...yt,...ce]},[k,_,S,f]),K=[{label:n("entitiesClipboard"),onClick:()=>e(fn("entities")),shouldShow:p&&Fb(n("entitiesClipboard"),s)},{label:n("summaryClipboard"),onClick:()=>e(fn("summary")),shouldShow:m&&Fb(n("summaryClipboard"),s)},{label:s?`${n("knowledgeAssist")}: ${s}`:n("knowledgeAssist"),onClick:()=>e(fn("knowledgeAssist")),shouldShow:h}].filter(B=>B.shouldShow).filter(()=>!f),W=(0,ft.useCallback)((0,Hb.default)((B,X)=>{e(Lo({query:B,type:X,tags:["search-overlay"],size:f?50:20}))},fN),[f]),de=(0,ft.useCallback)((B,X)=>{switch(X.type){case"IMAGE":t.send(lh,{suggestion:X});break;default:t.send(Xr,{text:B,suggestion:X})}e(Nt(!1))},[e]),Ye=B=>{rr(B.text),e(ct({name:"entity copied",data:{entity:B,type:"copy"}})),e(Nt(!1))},Ft=B=>{t.send(Xr,{text:B,suggestion:{source:"knowledge-assist",text:B}}),e(ct({name:"answer used",data:{originalText:B},options:{includeConversationData:!0}})),i(""),a&&e(Ld(a)),e(fn("search")),e(Nt(!1))},ns=B=>{rr(B),e(Nt(!1))};function Ht(B){return X=>{r?window.confirm(n("warning"))&&(B(X),o(!1)):B(X)}}return(0,ft.useEffect)(()=>{s?W(s,f):e(fd())},[s,f]),(0,ft.useEffect)(()=>{g&&e(tl())},[g]),lb(w,()=>e(Nt(!0))),!y||!c?null:(0,De.jsxs)(he,{placeholder:n("searchPlaceholder"),typePlaceholder:n("typePlaceholder"),onChangeSearch:i,onChangeOpen:Ht(B=>e(Nt(B))),onChangeType:B=>d(B),onChangePage:Ht(B=>e(fn(B))),selectedType:f,search:s,page:u,isOpen:N,types:Q,updateDeps:[b],children:[(0,De.jsxs)(he.Page,{id:"search",children:[s.length===0&&(0,De.jsx)(Db,{types:_,commands:K,onClick:de}),s.length>0&&(0,De.jsxs)(ft.Fragment,{children:[K.length>0&&(0,De.jsx)(he.List,{heading:n("commands"),children:K.map((B,X)=>(0,De.jsx)(he.ListItem,{closeOnSelect:!1,onClick:B.onClick,id:`commands-${X}`,children:B.label},B.label))}),Q.map(({value:B,label:X,list:yt,lineClamp:ce,listOrientation:Pe})=>(0,De.jsx)(he.List,{heading:X,orientation:Pe==="horizontal"?"horizontal":"vertical",onShowAll:()=>d(B),hasMore:!f&&R[B.toLowerCase()]>qh(yt,B,f).length,children:qh(yt,B,f).map(fe=>(0,De.jsx)(he.ListItem,{id:`${B}-${fe.id}`,closeOnSelect:!1,lineClamp:ce,onClick:()=>de(fe.text,fe),description:B!=="IMAGE"?fe.title&&fe.text:void 0,extra:v&&(0,De.jsx)(he.ListItemActions,{children:(0,De.jsx)(qd,{context:s,source:"search",suggestion:fe})}),children:B==="IMAGE"?(0,De.jsx)(he.Image,{title:fe.title||fe.text,src:fe.image}):fe.title||fe.text},`${fe.id}-${fe.text}`))},B))]})]}),(0,De.jsx)(he.Page,{id:"entities",title:n("entitiesTitle"),onDismiss:Ht(()=>{e(fn("search"))}),children:(0,De.jsx)(fb,{onCopy:Ye})}),(0,De.jsx)(he.Page,{id:"summary",title:n("summaryTitle"),onDismiss:Ht(()=>{e(fn("search"))}),children:(0,De.jsx)(kb,{onCopy:ns})}),(0,De.jsx)(he.Page,{id:"knowledgeAssist",title:n("knowledgeAssist"),onDismiss:Ht(()=>{a&&e(Ld(a)),e(fn("search"))}),children:(0,De.jsx)(xb,{threadId:a,onNewThreadId:B=>l(B),question:s,onUse:Ft,onResetQuestion:()=>{a&&e(Ld(a)),i(""),l(null)}})})]})},Ub=gN;var gl=x(C()),hN=()=>{let e=z("showSearch"),t=z("isEmbedded");return(0,gl.jsxs)(zb.Fragment,{children:[e&&(0,gl.jsx)(Ub,{}),t&&(0,gl.jsx)(CE,{})]})},jb=hN;var Wb=x(se());var Qd=x(C()),Bb=({className:e})=>(0,Qd.jsx)("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",x:"0px",y:"0px",viewBox:"0 0 512 512",xmlSpace:"preserve",className:e,children:(0,Qd.jsx)("g",{children:(0,Qd.jsx)("path",{d:`M163.4,233h186v-70c0-25.6-9.4-47.8-27.3-65.7C304.2,79.4,282,70,256.4,70s-47.8,9.4-65.7,27.3
20
20
  c-17.9,17.9-27.3,40.1-27.3,65.7C163.4,163,163.4,233,163.4,233z M465.5,267.9V477c0,9.4-3.4,17.9-10.2,24.7
21
21
  c-6.8,6.8-15.4,10.2-24.7,10.2h-349c-9.4,0-17.9-3.4-24.7-10.2c-6.8-6.8-10.2-15.4-10.2-24.7V267.9c0-9.4,3.4-17.9,10.2-24.7
22
22
  c6.8-6.8,15.4-10.2,24.7-10.2h11.9v-70c0-44.4,16.2-82.8,47.8-115.2S212.1,0,256.4,0s82.8,16.2,115.2,47.8
@@ -24,7 +24,7 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
24
24
  `+vt),bn&&bf([K,W,de],St=>{vt=bl(vt,St," ")}),S&&jl?S.createHTML(vt):vt},t.setConfig=function(){let j=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Vf(j),Un=!0},t.clearConfig=function(){us=null,Un=!1},t.isValidAttribute=function(j,E,A){us||Vf({});let U=Ue(j),Z=Ue(E);return av(U,Z,A)},t.addHook=function(j,E){typeof E=="function"&&(Q[j]=Q[j]||[],El(Q[j],E))},t.removeHook=function(j){if(Q[j])return ET(Q[j])},t.removeHooks=function(j){Q[j]&&(Q[j]=[])},t.removeAllHooks=function(){Q={}},t}var _T=MT();var hr=x(D());var DM={"":["<em>","</em>"],_:["<strong>","</strong>"],"*":["<strong>","</strong>"],"~":["<s>","</s>"],"\n":["<br />"]," ":["<br />"],"-":["<hr />"]};function DT(e){return e.replace(RegExp("^"+(e.match(/^(\t| )+/)||"")[0],"gm"),"")}function Tl(e){return(e+"").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function kl(e,t){var n,r,o,s,i,a=/((?:^|\n+)(?:\n---+|\* \*(?: \*)+)\n)|(?:^``` *(\w*)\n([\s\S]*?)\n```$)|((?:(?:^|\n+)(?:\t| {2,}).+)+\n*)|((?:(?:^|\n)([>*+-]|\d+\.)\s+.*)+)|(?:!\[([^\]]*?)\]\(([^)]+?)\))|(\[)|(\](?:\(([^)]+?)\))?)|(?:(?:^|\n+)([^\s].*)\n(-{3,}|={3,})(?:\n+|$))|(?:(?:^|\n+)(#{1,6})\s*(.+)(?:\n+|$))|(?:`([^`].*?)`)|( \n\n*|\n{2,}|__|\*\*|[_*]|~~)/gm,l=[],u="",c=t||{},f=0;function d(y){var v=DM[y[1]||""],p=l[l.length-1]==y;return v?v[1]?(p?l.pop():l.push(y),v[0|p]):v[0]:y}function g(){for(var y="";l.length;)y+=d(l[l.length-1]);return y}for(e=e.replace(/^\[(.+?)\]:\s*(.+)$/gm,function(y,v,p){return c[v.toLowerCase()]=p,""}).replace(/^\n+|\n+$/g,"");o=a.exec(e);)r=e.substring(f,o.index),f=a.lastIndex,n=o[0],r.match(/[^\\](\\\\)*\\$/)||((i=o[3]||o[4])?n='<pre class="code '+(o[4]?"poetry":o[2].toLowerCase())+'"><code'+(o[2]?' class="language-'+o[2].toLowerCase()+'"':"")+">"+DT(Tl(i).replace(/^\n+|\n+$/g,""))+"</code></pre>":(i=o[6])?(i.match(/\./)&&(o[5]=o[5].replace(/^\d+/gm,"")),s=kl(DT(o[5].replace(/^\s*[>*+.-]/gm,""))),i==">"?i="blockquote":(i=i.match(/\./)?"ol":"ul",s=s.replace(/^(.*)(\n|$)/gm,"<li>$1</li>")),n="<"+i+">"+s+"</"+i+">"):o[8]?n='<img src="'+Tl(o[8])+'" alt="'+Tl(o[7])+'">':o[10]?(u=u.replace("<a>",'<a href="'+Tl(o[11]||c[r.toLowerCase()])+'">'),n=g()+"</a>"):o[9]?n="<a>":o[12]||o[14]?n="<"+(i="h"+(o[14]?o[14].length:o[13]>"="?1:2))+">"+kl(o[12]||o[15],c)+"</"+i+">":o[16]?n="<code>"+Tl(o[16])+"</code>":(o[17]||o[1])&&(n=d(o[17]||"--"))),u+=r,u+=n;return(u+e.substring(f)+g()).replace(/^\n+|\n+$/g,"")}var FT={root:"dd-L7b3z",popover:"dd-OQOTB",options:"dd-Y12RE",arrow:"dd-cv33T",copyIcon:"dd-6xOsH",option:"dd-9oFX4",divider:"dd-aiZf8",fadeup:"dd-Jq9pd"};var xn=x(C());function FM(e){return`<button type="button" data-copy-icon class=${e}><svg version="1.1" x="0px" y="0px" viewBox="0 0 115.77 122.88" width="10px" height="10px" fill="black"><g><path d="M89.62,13.96v7.73h12.19h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02v0.02 v73.27v0.01h-0.02c-0.01,3.84-1.57,7.33-4.1,9.86c-2.51,2.5-5.98,4.06-9.82,4.07v0.02h-0.02h-61.7H40.1v-0.02 c-3.84-0.01-7.34-1.57-9.86-4.1c-2.5-2.51-4.06-5.98-4.07-9.82h-0.02v-0.02V92.51H13.96h-0.01v-0.02c-3.84-0.01-7.34-1.57-9.86-4.1 c-2.5-2.51-4.06-5.98-4.07-9.82H0v-0.02V13.96v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07V0h0.02h61.7 h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02V13.96L89.62,13.96z M79.04,21.69v-7.73v-0.02h0.02 c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v64.59v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h12.19V35.65 v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07v-0.02h0.02H79.04L79.04,21.69z M105.18,108.92V35.65v-0.02 h0.02c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v73.27v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h61.7h0.02 v0.02c0.91,0,1.75-0.39,2.37-1.01c0.61-0.61,1-1.46,1-2.37h-0.02V108.92L105.18,108.92z"/></g></svg></button>`}function Ay(e){var n;let t=e.cloneNode(!0);return t.querySelectorAll("div,button").forEach(r=>r.remove()),(n=t.textContent)!=null?n:""}function HM(e){return e.replace(/\r\n/g,`
25
25
  `)}function UM(e){return e.replace(new RegExp("(?<!\\]\\()(https?:\\/\\/[^\\s]+)","g"),"[$1]($1)")}var zM=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let s=L("Markdown",FT),i=(0,hr.useRef)(null),[a,l]=(0,hr.useState)(null),u=(0,hr.useMemo)(()=>{let v=kl(UM(HM(e)));return _T.sanitize(v).replaceAll("</code>",`${FM(s.copyIcon)}</code>`).replaceAll('<a href="','<a target="_blank" rel="noreferrer noopener" href="')},[e]),c=v=>{var h;let p=v.target,m=!!((h=i.current)!=null&&h.querySelector("code"));if(["A","BUTTON"].includes(p.tagName)){l(null);return}a||m&&p.tagName!=="CODE"||!m&&p!==i.current||(p.addEventListener("mouseleave",()=>l(null),{once:!0}),l(p))},f=()=>{if(!a)return;l(null);let v=a.querySelector("button");v&&(mi(v,s.fadeup),r(Ay(a)))},d=v=>{let p=v.target;if(p.tagName==="A"){v.stopPropagation();return}"copyIcon"in p.dataset&&(mi(p,s.fadeup),r(Ay(p.parentElement)))},g=()=>{!a||!o||(l(null),o(Ay(a)))},y=v=>{if(v===null)return;let p=v.getBoundingClientRect();p.left<0?v.style.transform=`translateX(${-p.left+2}px)`:p.right>window.innerWidth&&(v.style.transform=`translateX(${window.innerWidth-p.right-2}px)`)};return(0,xn.jsxs)(hr.Fragment,{children:[a&&(0,xn.jsxs)(bi,{triggerRef:{current:a},className:s.popover,parentNode:a,children:[(0,xn.jsxs)("div",{className:s.options,ref:y,children:[(0,xn.jsx)("button",{type:"button",className:s.option,onClick:f,children:n}),o&&(0,xn.jsxs)(hr.Fragment,{children:[(0,xn.jsx)("div",{className:s.divider}),(0,xn.jsx)("button",{type:"button",className:s.option,onClick:g,children:t})]})]}),(0,xn.jsx)("div",{className:s.arrow})]}),(0,xn.jsx)("div",{ref:i,className:s.root,dangerouslySetInnerHTML:{__html:u},onMouseOver:c,onClick:d})]})},HT=zM;var Iy={};Xe(Iy,{enUS:()=>jM,nlNL:()=>BM});var jM={useCue:[{type:0,value:"Add to message"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},BM={useCue:[{type:0,value:"Voeg toe aan bericht"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var UT={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",actions:"dd-9Iqn9",thumbsUp:"dd-6QwVx",thumbsDown:"dd-d3E8l"};var rn=x(C()),VM=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o})=>{let s=L("WidgetCue",UT),i=Y(Iy),a=gi(),l=z("hasKeyboardInput"),u=()=>{t&&t(e),n(e)},c=g=>{r&&r(g,e)},f=g=>{o&&o(g,e)},d=g=>{g.preventDefault(),g.stopPropagation(),n(e)};return(0,zT.useEffect)(()=>{a("Assistant response displayed",{name:e.rule.name,description:e.rule.description,group:e.rule.label,cueText:e.text})},[]),(0,rn.jsxs)(re,{"data-testid":"cue",children:[(0,rn.jsx)(ye,{children:(0,rn.jsxs)(ye.Content,{children:[e.title&&(0,rn.jsx)(ye.Title,{className:s.title,"data-testid":"widget-cue-title",children:e.title}),(0,rn.jsx)(HT,{content:e.text,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:c,onUse:l?f:void 0})]})}),(0,rn.jsxs)(re.ButtonsContainer,{children:[(0,rn.jsxs)("div",{className:s.actions,children:[e.callToAction&&(0,rn.jsx)(re.Button,{onClick:u,children:e.callToAction.label}),(0,rn.jsx)(re.Button,{onClick:d,children:i("removeCue")})]}),(0,rn.jsx)(yi,{eventName:"Assistant response feedback",eventData:{name:e.rule.name,group:e.rule.label,description:e.rule.description,cueText:e.text},feedbackText:e.text,feedbackType:"assistant"})]})]})},jT=VM;var Pl=x(C()),KM=({cues:e})=>{let t=G(),n=Xt(),r=gi(),o=l=>{t(tT({id:l.rule.id})),t(ME({code:l.rule.label})),r("Assistant response closed",{name:l.rule.name,group:l.rule.label,description:l.rule.description,cueText:l.text})},s=(l,u)=>{rr(l),r("Assistant response copied",{name:u.rule.name,group:u.rule.label,description:u.rule.description,copiedText:l})},i=l=>{l.callToAction&&(t(Id(l)),r("Assistant call to action",{name:l.rule.name,group:l.rule.label,description:l.rule.description,eventName:l.callToAction.event,value:l.callToAction.value}))},a=(l,u)=>{n.send(Xr,{text:l,suggestion:{source:"cue",sourceText:l}}),r("Assistant response used",{name:u.rule.name,group:u.rule.label,description:u.rule.description,usedText:l})};return(0,Pl.jsx)(Pl.Fragment,{children:e.map(l=>(0,Pl.jsx)(jT,{cue:l,onCallToAction:i,onRemove:o,onCopy:s,onUse:a},l.rule.id))})},BT=KM;var Pf=x(D());var VT={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var wn=x(C());function WM(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var KT=({data:e,schema:t})=>{let n=L("WidgetCustomData",VT),r=o=>{rr(o)};return(0,Pf.useEffect)(()=>{H.info("Custom data",e,t)},[e]),(0,wn.jsx)("dl",{className:n.root,children:t.map(o=>{let s=WM(e,o.path);return(0,wn.jsxs)(Pf.Fragment,{children:[(0,wn.jsx)("dt",{className:n.label,children:o.label}),(0,wn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&s?(0,wn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!s?(0,wn.jsx)("span",{className:n.isFalse,children:o.falseValue}):s?(0,wn.jsxs)("button",{type:"button",onClick:()=>r(s),className:n.copyButton,children:[(0,wn.jsx)("span",{className:n.copyButtonText,children:s}),(0,wn.jsx)(wl,{})]}):"-"})]},o.label)})})};var $T=x(D());var $M=/(https?:\/\/[^\s]+)/,WT=e=>e.split(" ").find(t=>$M.test(t));var on=x(C()),qM=({suggestion:e,lines:t,onUse:n})=>{var f;let r=e.text||e.url||e.message,o=WT(r),s=Y(Bo),i=z("showImages"),a=z("fallbackImage"),l=z("hasKeyboardInput"),u=d=>{d.preventDefault(),d.stopPropagation(),l&&n(r)},c=(0,$T.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,on.jsxs)(re,{onClick:l?u:void 0,"data-testid":"edit-suggestion",children:[(0,on.jsxs)(ye,{children:[i&&e.image&&(0,on.jsx)(ye.Image,{src:hf(e,"small",a||void 0),title:e.title}),(0,on.jsxs)(ye.Content,{children:[e.title&&(0,on.jsx)(ye.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((f=e.searchKeywords)==null?void 0:f.length)>0&&(0,on.jsx)(re.Labels,{labels:e.searchKeywords}),(0,on.jsx)(ye.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,on.jsxs)(re.Actions,{children:[o&&(0,on.jsx)(re.ActionButton,{onClick:c,label:s("visitUrl")}),l&&(0,on.jsx)(re.ActionButton,{primary:!0,onClick:u,label:s("useSuggestion")})]})]})},qT=qM;var Rl=x(C()),GM=({lines:e,suggestions:t})=>{let n=Xt(),r=(o,s)=>{n.send(Xr,{text:o,suggestion:I(T({},s),{source:s.source,sourceText:s.text})})};return(0,Rl.jsx)(Rl.Fragment,{children:t.map(o=>(0,Rl.jsx)(qT,{suggestion:o,lines:e,onUse:s=>r(s,o)},o.text||o.url||o.message))})},GT=GM;var Al={};Xe(Al,{enUS:()=>YM,nlNL:()=>QM});var YM={waiting:[{type:0,value:"Loading\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"My "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Summarize"}],linkKnowledgeSearch:[{type:0,value:"Knowledge Assist"}],linkSearch:[{type:0,value:"Search"}]},QM={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"Mijn "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Gesprek samenvatten"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}]};var Il={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",sectionList:"dd-bF9pF",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",link:"dd-DRo0x"};var q=x(C()),Rf=(e,t)=>{let n=M(ut);(0,Ci.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},XM=({onLogIn:e})=>{let t=L("Widget",Il),n=z("isEmbedded"),r=z("adminUrl");return(0,q.jsx)("div",{className:t.loginText,children:(0,q.jsx)("div",{children:(0,q.jsx)(nf,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},YT=({text:e})=>{let t=L("Widget",Il);return(0,q.jsx)("div",{className:t.stateText,children:(0,q.jsx)("div",{children:(0,q.jsx)("p",{children:e})})},"notification")},ZM=()=>{let e=Y(Al),t=G(),n=L("Widget",Il),r=z("showSearch"),o=z("showSummaryCommand"),s=z("showKnowledgeSearch"),i=z("isEmbedded"),a=M(hi("/admin/")),l=Xt(),u=z("productName"),c=z("hasKeyboardInput"),f=r||o||s||a;return Rf(()=>{if(i)return t(fy()),()=>{t(QC())}},[t,i]),!f||!c?null:(0,q.jsx)(Cn,{title:e("actions"),type:"shortcuts",children:(0,q.jsxs)("div",{className:n.shortcutList,children:[r&&(0,q.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-search","aria-label":e("linkSearch"),onClick:()=>l.send("ShowCommandPalette",{isOpen:!0}),children:[(0,q.jsx)(di,{}),e("linkSearch")]}),o&&(0,q.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-summary","aria-label":e("linkSummary"),onClick:()=>l.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,q.jsx)(xT,{}),e("linkSummary")]}),s&&(0,q.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-knowledge-assist","aria-label":e("linkKnowledgeSearch"),onClick:()=>l.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,q.jsx)(ST,{}),e("linkKnowledgeSearch")]}),a&&(0,q.jsxs)("a",{className:n.shortcut,target:"_blank",href:a,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:u}),rel:"noreferrer",children:[(0,q.jsx)(vT,{}),e("linkStudioLogin",{productName:u})]})]})})},JM=()=>{let e=G(),t=z("showCustomMessages"),n=M(jC),r=M(ri);return Rf(()=>(e(xl(r)),e($C(r)),()=>{e(qC(r))}),[e,t,r]),!t||n.length===0?null:(0,q.jsx)(Cn,{type:"custom-messages","data-testid":"custom-messages",children:(0,q.jsx)(Et,{withDivider:!0,children:n.map(o=>(0,q.jsx)(gT,{suggestion:o},o.text))})})},e_=()=>{let e=Y(Al),t=G(),n=z("showAutoflows"),r=M(DC),o=M(ri);return Rf(()=>(t(mr(o)),t(FC(o)),()=>{t(HC(o))}),[t,n,o]),!n||r.length===0?null:(0,q.jsx)(Cn,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:(0,q.jsx)(Et,{withDivider:!0,children:(0,q.jsx)(pT,{})})})},t_=()=>{let e=G(),t=M(Od),n=M(HE),r=M(rT),o=M(q1),s=M(Kd),i=M(Gd),a=M(nr),l=M(Yr);return(0,Ci.useEffect)(()=>{!!o&&!n&&H.warn("Custom data provided, but no schema.")},[o,n]),Rf(()=>{t.forEach(({type:u})=>{u==="entities"?e(yn()):su.includes(u)||e(vn(u))})},[e,l,a]),(0,Ci.useEffect)(()=>{r.length>0&&!t.some(u=>u.type==="cues")&&H.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,q.jsx)(Ci.Fragment,{children:t.map(({type:u,title:c,amount:f,lines:d,schema:g})=>{var y,v;switch(u){case"entities":return s&&s.length>0&&(0,q.jsx)(Cn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,q.jsx)(yT,{entities:s})},u);case"cues":return r&&r.length>0&&(0,q.jsx)(Cn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,q.jsx)(Et,{withDivider:!0,children:(0,q.jsx)(BT,{cues:r})})},u);case"custom-data":return o&&g&&(0,q.jsx)(Cn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,q.jsx)(Et,{withDivider:!0,children:(0,q.jsx)(KT,{data:o,schema:g})})},u);default:return((v=(y=i[u])==null?void 0:y.suggestions)==null?void 0:v.length)>0&&(0,q.jsx)(Cn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,q.jsx)(Et,{withDivider:!0,children:(0,q.jsx)(GT,{lines:d,contentType:u,suggestions:i[u].suggestions.slice(0,f)||[]})})},u)}})})},n_=({onLogIn:e})=>{let t=Y(Al),n=L("Widget",Il),r=M(oi),o=M(ut),s=M(ri),i=M(nr);return r===!1?(0,q.jsx)(YT,{text:t("notSupported")}):o===!1?(0,q.jsx)(XM,{onLogIn:e}):!i||!s||o===null?(0,q.jsx)(YT,{text:t("waiting")}):(0,q.jsx)("div",{className:(0,QT.default)(n.root),"data-testid":"widget",children:(0,q.jsxs)(nu,{className:n.sectionList,children:[(0,q.jsx)(ZM,{}),(0,q.jsx)(JM,{}),(0,q.jsx)(e_,{}),(0,q.jsx)(t_,{})]})})},XT=n_;function Ti(e){let t=new Range;return t.selectNodeContents(e),t}function ZT(e,t,n){try{return io(e,t,n),!0}catch(r){return!1}}function Af(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function If(e){return"tagName"in e&&e.tagName==="BR"}var Ll=/[\u200B-\u200D\uFEFF]/g;function io(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,s=!1;function i(l,u){let c=-1,f=/[\u200B-\u200D\uFEFF]/;if(!f.test(l))return u;for(let d=0;d<=l.length;d++)if(f.test(l[d])||c++,c===u)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let u=l.textContent,c=u.replace(Ll,""),f=o+c.length,d=t>=o&&t<=f,g=n>=o&&n<=f;if(d){let y=i(u,t-o);y===0&&!g?r.setStartBefore(l):r.setStart(l,y)}g&&(r.setEnd(l,i(u,n-o)),s=!0),o=f;break}case Node.ELEMENT_NODE:{if(If(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),s=!0;return}for(let c=0;c<l.childNodes.length&&(a(l.childNodes[c]),!s);c++);let u=l.lastChild;Af(l)&&u&&!Af(u)&&!If(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function Ol(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:s,collapsed:i}=t,a,l,u=0;function c(f){let d=f===e,g=f===n,y=f===o;switch(f.nodeType){case Node.TEXT_NODE:{let v=f.textContent;g&&(a=u+v.substring(0,r).replace(Ll,"").length),y&&(l=u+v.substring(0,s).replace(Ll,"").length),u+=v.replace(Ll,"").length;break}case Node.ELEMENT_NODE:{if(If(f)&&f.nextSibling){u++;break}!d&&Af(f)&&f.previousSibling&&u++;for(let v=0;v<f.childNodes.length;v++){let p=g&&v===r,m=y&&v===s;if(p&&(a=u),m&&(l=u),l!==void 0||((!p||!i)&&c(f.childNodes[v]),y&&v===s-1&&(l=u),l!==void 0))break}y&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:l,end:l}}function Nl(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:s,collapsed:i}=t,a=0,l="";function u(c){let f=c===e,d=c===n,g=c===o;switch(d&&(a=1),c.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let y=d?r:0,v=g?s:void 0;l+=c.textContent.replace(Ll,"").substring(y,v);break}case Node.ELEMENT_NODE:{if(!i&&a===1&&If(c)&&c.nextSibling){l+=`
26
26
  `;break}!f&&!i&&a===1&&Af(c)&&c.previousSibling&&(l+=`
27
- `);let y=d?r:0,v=g?Math.min(s,c.childNodes.length):c.childNodes.length;for(let p=y;p<v&&(u(c.childNodes[p]),a!==2);p++);break}default:break}g&&(a=2)}return u(e),l}var JT=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(JT||{}),yr=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let s=this.getCaretPosition();Gr(s,this.cachedCaretPosition)||(this.cachedCaretPosition=s,this.emit("caretposition",s))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(JT).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function ek(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Zo=class extends yr{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Nl(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(i=r.getComposedRanges(n))==null?void 0:i[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let s=this.element.ownerDocument.createRange();return s.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),s.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!ek(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!ek(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return Ol(this.element,n);let r=this.lastKnownSelection;if(r&&ZT(this.element,r.start,r.end))return r;let o=Ti(this.element);return o.collapse(!1),Ol(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Nl(this.element,io(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var r_=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function tk(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,s=window.getComputedStyle(e),i=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",r_.forEach(function(c){o[c]=s[c]}),n?e.scrollHeight>parseInt(s.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),i.appendChild(r);let l=e.getBoundingClientRect(),u={top:l.top-e.scrollTop+a.offsetTop+parseInt(s.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+parseInt(s.borderLeftWidth)};return i.removeChild(r),u}var Jo=class extends yr{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return tk(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function nk(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let s=document.createElement("iframe"),i=new URL(t);return Object.entries(n).forEach(([a,l])=>{i.searchParams.append(a,l)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=r,s.title=`iframe-${e}`,s.src=i.toString(),window.document.body.appendChild(s),s}function o_(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var Ly=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Oy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=nk(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},Ny=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),H.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Oy(t,this.deepdeskUrl,{debug:!0}):new Ly(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=o_(o.data);typeof s!="object"||s.type!=="event"||s.channel!==t||(H.info("Received broadcast event",this.sessionId,o),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(r),n}send(t,n,r){var i,a;H.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(i=this.eventMap)[t])==null||a.call(i,n));let s=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(I(T({},o),{channel:this.sessionId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},rk=Ny;function s_(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function oe(e){return Array.isArray(e)?e.map(oe):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(T({},t),{[s_(n)]:oe(e[n])}),{}):e}function My(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Le(e){return Array.isArray(e)?e.map(Le):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(T({},t),{[My(n)]:Le(e[n])}),{}):e}var ki=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var _y=e=>new Promise(t=>{setTimeout(t,e)});var Pi=class extends ki{constructor(){super(...arguments);this.name="ClientError"}},Fy=class extends ki{constructor(){super(...arguments);this.name="ServerError"}},Dy=new Map;function i_(e){return P(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(H.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var ao=class ao{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let s={isAborted:!1,reject:o},i=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",b=n,{useCache:u=!1,abortLatest:c=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:g=!0,retryOnError:y=R=>R instanceof TypeError,retryOnResponse:v=R=>R.status>=500,version:p=null}=b,m=ee(b,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(Dy.has(i)){r(Dy.get(i));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h=I(T({credentials:"include"},m),{headers:T({Accept:"application/json","Content-Type":"application/json"},m.headers)});!l&&this.csrfToken&&(h.headers=I(T({},h.headers),{"X-CSRFToken":this.csrfToken})),typeof p=="string"&&(h.headers=I(T({},h.headers),{"X-Deepdesk-API-Version":p}));let S=f,w=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let k=()=>P(this,null,function*(){return S--,a(i,h).then(R=>P(this,null,function*(){return v(R)&&!s.isAborted&&S>0?(yield _y(d),k()):R.status===401&&g===!0&&w===!1?(w=!0,yield this.refreshToken(),k()):R})).catch(R=>P(this,null,function*(){if(y(R)&&!s.isAborted&&S>0)return yield _y(d),k();throw R}))});k().then(R=>P(this,null,function*(){let N=yield i_(R);if(delete this.latestRequestByUrl[i],R.status>=500){o(new Fy("Server Error",N));return}else if(R.status===401){o(new Pi("Unauthorized",N));return}else if(R.status===403){o(new Pi("Forbidden",N));return}else if(R.status===404){o(new Pi("Not Found",N));return}else if(R.status>=400){o(new Pi("Bad Request",N));return}u&&Dy.set(i,N),r(N)})).catch(R=>{o(R)})})}validateToken(){return P(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)try{yield this.refreshToken()}catch(r){return!1}let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/");return!!n})}refreshToken(){return ao.refreshingToken||(ao.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{ao.refreshingToken=null},1e3*60)})),ao.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,T({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,T({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,T({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,T({method:"DELETE"},n))}};ao.refreshingToken=null;var vr=ao;var ok;(t=>{let e;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||(t.EventType={}))})(ok||(ok={}));function Lf(e){return I(T({},oe(e)),{tags:e.tags})}var es=class es{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new vr(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,s)=>P(this,null,function*(){let i=yield r(o,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return P(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(es.exchangeTokenPromise||(es.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),es.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return P(this,null,function*(){yield this.preflight(),H.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",I(T({},Le(t)),{tags:t.tags}),{version:"v2"});return Lf(n)})}getMe(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return oe(t)})}postIdentity(t){return P(this,null,function*(){yield this.client.post("/apis/admin/session/me/identities/",Le(t))})}patchMe(t){return P(this,null,function*(){let n=yield this.client.patch("/apis/admin/session/me/",Le(t));return oe(n)})}getProfile(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return oe(n)})}getKnowledgeAssistant(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return oe(n)})}getContentTypes(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return oe(t)})}getAccount(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return oe(t)})}getPlatformConfig(t){return P(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return oe(r)})}checkUserExists(t){return P(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationBySessionId(r){return P(this,arguments,function*(t,n={}){yield this.preflight(),H.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return H.info(`Successfully retrieved conversation ${i.id} for session ${t}`),Lf(i)})}isConversationSupported(r){return P(this,arguments,function*(t,n={}){H.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return P(this,null,function*(){let r=Le(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Lf(o)})}postMessages(t,n){return P(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>I(T({},Le(o)),{tags:o.tags})),{version:"v2"})).map(o=>Lf(o))})}sendEvent(t,n){return P(this,null,function*(){let i=n,{data:r}=i,o=ee(i,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>I(T({},a),{[l]:u}),{});return this.client.post("/api/events",Le(I(T(T({},s),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return P(this,null,function*(){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[s,i])=>I(T({},o),{[s]:i}),{});return this.client.post("/api/events",{event:t,data:Le(T(T({},n),r))},{version:"v1"})})}getEntities(t){return P(this,null,function*(){return(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)},{version:"v1"})).entities})}getTemporaryExchangeToken(){return P(this,null,function*(){return(yield this.client.get("/auth/exchange-token")).jwt})}exchangeTokenForAccessCookie(t){return P(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw H.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return P(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Le(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return P(this,arguments,function*(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(yield this.client.post(`/api/conversations/${t}/recommend/${r}`,Le(n),{abortLatest:!0,version:"v1"})).map(i=>I(T({},oe(i)),{text:i.text||i.url||i.message,source:r,type:r})).filter((i,a,l)=>a===l.findIndex(u=>u.text===i.text))})}isLoggedIn(){return P(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return P(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/autocomplete`,Le(n),{abortLatest:!0,version:"v1"})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,s,i)=>s===i.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return P(this,null,function*(){let n=yield this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0,version:"v1"});return oe(n).map(r=>I(T({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return P(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",Le(t),{abortLatest:!0,version:"v1"});return oe(n)})}search(t){return P(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,Le(t),{version:"v2"});return oe(n)})}knowledgeAssist(s,i,a){return P(this,arguments,function*(t,n,r,o={}){let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Le({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(u=>({question:u.question,answer:u.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return oe(l)})}requestLoginByEmail(t){return P(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return oe(n)})}requestPasswordlessToken(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return oe(t.token)})}getCsrfToken(){return P(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return P(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return oe(n)})}evaluateRule(s,i,a){return P(this,arguments,function*(t,n,r,o={}){let l=new URLSearchParams;o.raiseForFailingConditions&&l.set("raise_for_failing_conditions","true");let u=yield this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${l.toString()}`,r,{version:"v2"});return u?oe(u.cues):[]})}getSummary(r){return P(this,arguments,function*(t,n={}){let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(s=>s.text&&s.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return oe(o)})}evaluateAssistant(t,n){return P(this,null,function*(){var a;let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let l=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",l)}else r.append("expect_response_format",o);n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let s=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,i=yield this.client.post(s,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return oe(i.output)})}createAssistantThread(t){return P(this,null,function*(){let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return oe(r)})}postMessageToAssistantThread(t){return P(this,null,function*(){let{assistantCode:n,threadId:r,message:o}=t,s=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return oe(s)})}getRules(){return P(this,null,function*(){let t=new URLSearchParams,n=yield this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{useCache:!0});return oe(n)})}translateMessages(t){return P(this,null,function*(){let n=yield this.client.post("/api/translate",Le(t),{version:"v2"});return oe(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(r0);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&H.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};es.exchangeTokenPromise=null;var Sr=es;var Ml=class{constructor(t,n){this.url=t;this.eventListeners={};this.options=T({timeout:25e3},n)}proxyEvent(t){this.eventSource.addEventListener(My(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,oe(o))}catch(o){H.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var sk;(t=>{let e;(s=>(s.Started="Started",s.Aborted="Aborted",s.Completed="Completed"))(e=t.AutoflowSessionState||(t.AutoflowSessionState={}))})(sk||(sk={}));var _l=class{constructor(t,n={}){this.apiUrl=t;this.streams={};this.logger=H;this.client=new vr(t,n)}getCustomMessages(t){return P(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/suggestions`);return oe(n.suggestions)})}sendCustomMessage(t,n){return P(this,null,function*(){let r=yield this.client.post(`/sessions/${t}/messages`,Le(n));return oe(r)})}answerCustomMessage(t,n){return P(this,null,function*(){yield this.client.post(`/sessions/${t}/answers`,Le(n))})}getAutoflows(t){return P(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/autoflows`);return oe(n.autoflows)})}startAutoflowSession(t){return P(this,null,function*(){let n=yield this.client.post("/autoflow-sessions",Le(t));return oe(n)})}stopAutoflowSession(t){return P(this,null,function*(){yield this.client.delete(`/autoflow-sessions/${t}`)})}openStream(t){return this.streams[t]||(this.streams[t]=new Ml(`${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 ik={startTime:null,stopTime:null},ak=J({name:"handlingTime",initialState:ik,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(xe,()=>ik)}}),{handlingTimeStart:lk,handlingTimeStop:Of,handlingTimeReset:uk}=ak.actions,ck=ak.reducer;var dk=(e={})=>{let t=T({onAuthError:ni(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Nf={list:{keywordMatches:[]},fetchState:"idle"};var ts=V("styleSuggestions/getAll",(n,r)=>P(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,s=t.getState(),{showStyleSuggestions:i}=s.settings,a=(l=s.conversation.current)==null?void 0:l.profileCode;if(!i)return Nf.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),a_=J({name:"styleSuggestions",initialState:Nf,reducers:{},extraReducers:e=>{e.addCase(ts.pending,t=>{t.fetchState="loading"}).addCase(ts.rejected,t=>{t.fetchState="error"}).addCase(ts.fulfilled,(t,n)=>{t.fetchState="done",Gr(t.list,n.payload)||(t.list=n.payload)}).addCase(Io,t=>{t.list=Nf.list}).addCase(xe,()=>Nf)}}),fk=a_.reducer;var pk=(e={})=>{let t,n=!0,r=T({getStyleSuggestions:ts,debounce:500},e);return o=>s=>i=>{var g;let a=o.getState().input.text,l=s(i),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((g=u.conversation.current)==null?void 0:g.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 l_(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var mk=(e={})=>{let t=T({getTextSuggestions:vn,getAutocompleteSuggestions:ml,debounce:200,check:Mn},e),n;return r=>o=>s=>{var v;let{input:i}=r.getState(),a=o(s),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,f=(v=l.conversation.current)==null?void 0:v.id,d=s.type===Yd.toString();if(!f||!u&&!c)return a;let{input:g}=l;return l_(g,i)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let p=si(l);p===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(p))},d?0:t.debounce)),a}};var gk=ts.fulfilled.toString();function u_(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let s=e.keywordMatches.filter(l=>l.keyword===o),i=t.keywordMatches.filter(l=>l.keyword===o),a=i.length-s.length;a<=0||r.push(...i.slice(0,a))}),r}var hk=e=>t=>n=>r=>{var u;if(r.type!==gk){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let s=t.getState(),i=s.styleSuggestions.list,a=(u=s.conversation)==null?void 0:u.current;if(o===i)return;let l=u_(o,i);r.type===gk&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var c_=Tc({assistants:_E,auth:b1,autoflows:UC,conversation:N1,contentTypes:FE,customMessages:GC,passwordlessToken:XC,entities:cb,knowledgeAssistant:IE,handlingTime:ck,info:Z1,input:W1,settings:h1,profile:UE,search:sE,styleSuggestions:fk,ui:Xb,rules:nT,textSuggestions:Mb});function yk(e){return Ew({reducer:c_,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),dk(),mk({debounce:200}),pk({debounce:500}),hk(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var d_=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},f_=e=>t=>n=>r=>{var a,l,u,c,f,d,g;let o=t.getState(),s=Zg("inlineSuggestions")(o);switch(r.type){case ni.toString():{!r.payload&&e.emit("logout",void 0);break}case yn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case ct.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Io.toString():e.logSendMessage(r.payload);break;case Yo.fulfilled.toString():r.isBroadcasted||e.broadcast(ih,r,!1),(c=r.payload.options)!=null&&c.shouldEmit&&e.emit("cues",r.payload.cues);break;case Id.toString():e.emit("call-to-action",{cue:r.payload});break;case tr.fulfilled.toString():r.isBroadcasted||e.broadcast(ah,r,!1);break;default:break}let i=n(r);switch(r.type){case Io.toString():e.handleAfterSendMessage(r.payload);break;case hl.toString():e.onUpdateShowTabHint(r.payload);break;case Of.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case id.toString():{let{start:y,end:v}=o.input.selection;e.emit("replace",I(T({},r.payload),{replace:r.payload.replace==="selection"?{start:y,end:v}:{start:0,end:v}}));break}case dn.toString():{let{start:y,end:v}=o.input.selection;e.emit("select-suggestion",I(T({type:d_(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:y,end:v}:{start:0,end:v}})),s&&t.dispatch(Qr([]));break}case ad.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Qr.toString():{s&&r.payload.length>0&&t.dispatch(ld(0));break}case li.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(d=o.conversation.current)==null?void 0:d.id,data:{summary:r.payload,assistant:(g=t.getState().profile.data)==null?void 0:g.summarizerAssistantNew}});break}default:break}return i},vk=f_;function Hy(e){return e.toISOString().replace("T"," ").replace("Z","")}function Sk(e,t){var s,i,a,l;let n=(s=e.conversation.current)==null?void 0:s.id;if(!n)return H.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:o}=e.handlingTime;return!r||!o?(H.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:n,clientVersion:t.version,agentId:(i=e.info.agentInfo)==null?void 0:i.agentId,agentName:(a=e.info.agentInfo)==null?void 0:a.agentName,agentEmail:(l=e.info.agentInfo)==null?void 0:l.agentEmail,timeStart:Hy(r),timeStop:Hy(o)}}function xk(e,t,n){var N,_,Q,K;let r=(N=t.conversation.current)==null?void 0:N.id;if(!r)return H.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:s,numCharsPasted:i,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:f,pastes:d,cuts:g,deletions:y,textSuggestions:v,offeredTextSuggestions:p}}=t[e],m=o.length,S=v.reduce((W,{text:de,searchTerm:Ye})=>W+de.length-(Ye?Ye.length:0),0),w=c!=null?c:Date.now(),k=(Date.now()-w)/1e3+(f||0),b=s/k,R=v.reduce((W,{searchTerm:de})=>W+(de?de.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:g,deletions:y,lenTextTyped:s+R,lenTextTotal:m,lenTextAssisted:S,lenTextPasted:i,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:k,charsPerSecond:b,numPastes:u,textSuggestionsV2:v,suggestionsCounters:[{source:"gpt",countOffered:p.filter(W=>W.source==="gpt").length}],agentId:(_=t.info.agentInfo)==null?void 0:_.agentId,agentName:(Q=t.info.agentInfo)==null?void 0:Q.agentName,agentEmail:(K=t.info.agentInfo)==null?void 0:K.agentEmail}}function Uy(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Uy(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?Uy(o,t):null}function wk(e,t){return Uy(e,t)}function Ek(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function p_(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Mf(e){return p_(e)&&(Go(e)||of(e))}var Ck,Fn=new Map,m_=["bottom","height","left","right","top","width"],bk=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:m_.some(n=>e[n]!==t[n]);function Tk(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...Tk(t)]:[]}function kk(e,t){return!e||!t?null:I(T({},e),{top:e.top+t.top,left:e.left+t.left})}var _f=!1,Pk=()=>{_f=!0;let e=[];if(Fn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Fn.delete(n);return}let r=n.getBoundingClientRect();bk(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(kk,t.rect):t.rect;bk(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Fn.size===0){_f=!1;return}Ck=window.requestAnimationFrame(Pk)};function zy(e,t){let n=Tk(e),r=[],o=n.map((s,i)=>zy(s,a=>{r[i]=a;let l=Fn.get(e);if(!l)return;let u=r.reduce(kk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),Fn.has(e)){let i=Fn.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else Fn.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!_f&&Pk()},unobserve(){o.forEach(i=>i.unobserve());let s=Fn.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||Fn.delete(e),Fn.size||(cancelAnimationFrame(Ck),_f=!1)}}}}var Rk,Hn=new Map,Ak=()=>{Hn.forEach((e,t)=>{if(!t.isConnected){Hn.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(s=>s(e.visible)))}),Hn.size!==0&&(Rk=window.requestAnimationFrame(Ak))};function Ik(e,t){return{observe(){let n=Hn.size===0;Hn.has(e)?Hn.get(e).callbacks.push(t):Hn.set(e,{visible:void 0,callbacks:[t]}),n&&Ak()},unobserve(){let n=Hn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Hn.delete(e),Hn.size||cancelAnimationFrame(Rk)}}}}var jy=["borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth","borderStyle","boxSizing","color","overflowWrap","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontWeight","fontKerning","lineHeight","letterSpacing","paddingLeft","paddingTop","paddingRight","paddingBottom","width","height","textIndent","whiteSpace","wordBreak","wordSpacing","wordWrap"];function By(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Ri(e){return parseFloat(e)}function Df(e){return Math.round(e*1e6)}function Lk(e){return e/1e6}function Vy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Ri(e.width),s=Ri(e.borderLeftWidth),i=Ri(e.borderRightWidth),a=Ri(e.paddingRight),l=Lk(Df(o)-Df(s)-Df(i)),u=Lk(Df(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function Dl(e,t={}){var c,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Wo(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};By(r,n,jy),Vy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=Ik(e,()=>{By(r,n,jy),Vy(r,e,n),s(),setTimeout(s,0)}),a,l=!0,u=zy(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(By(r,n,jy),Vy(r,e,n),s(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let g=t.closestScrollElement.getBoundingClientRect(),y=window.getComputedStyle(t.closestScrollElement),v=Ri(y.borderTopWidth),p=Ri(y.borderBottomWidth),m=g.top+v-d.top,h=d.top+d.height+-(g.top+g.height-p);n.style.clipPath=`inset(${m}px 0px ${h}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),u.observe(),i.observe(),[n,()=>{e.removeEventListener("scroll",s),u.unobserve(),i.unobserve()}]}var Ok=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){H.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function g_(e){return e.offsetParent!==null}function Nk(e){if(!g_(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function Ff(e,t,n=100){let r=Nk(e);t({isVisible:r});let o=setInterval(()=>{let s=Nk(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Fe=x(C());var Mk=Ok("showTabHint",!0),Ai=class Ai{constructor({deepdeskUrl:t,brokerUrl:n,version:r=Ai.version||"unknown",locale:o="en-US",token:s,fetch:i,productName:a,createCustomChannel:l}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let u=t.replace(/\/api$/,"");this.deepdeskApi=new Sr(u,{token:s,fetch:i}),this.version=r,this.instanceId=Ai.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[vk({broadcast:(f,d,g)=>{this.broadcastEvents.send(f,d,g)},emit:(f,d)=>this.emit(f,d),handleAfterSendMessage:f=>this.handleAfterSendMessage(f),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:f=>this.logSendMessage(f),onUpdateShowTabHint:f=>Mk.update(f),sendEvent:(f,d)=>this.deepdeskApi.sendEvent(f,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new _l(n)}),this.store=yk(c),this.broadcastEvents=new rk({debug:!0,deepdeskUrl:u,eventMap:iE(this.store),createCustomChannel:l}),this.store.dispatch(hl(Mk.value())),this.store.dispatch(ed({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(H.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(H.warn("Profile has not been loaded (yet)"),!0):(H.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(ni(null)),this.store.dispatch(Jn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();ut(r)&&y1(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return P(this,null,function*(){return(yield this.store.dispatch(Jn())).payload})}isConversationSupported(t,n){return P(this,null,function*(){return(yield this.store.dispatch(th({sessionId:t,options:n}))).payload})}createConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(nd(t))).payload})}getConversationBySessionId(t,n){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(rd({sessionId:t,options:n}))).payload})}upsertConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(nh(t))).payload})}postMessages(t){return P(this,null,function*(){return(yield this.store.dispatch(sd(t))).payload})}updateConversation(t){return P(this,null,function*(){return(yield this.store.dispatch(od(t))).payload})}resetConversation(){this.store.dispatch(xe()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(ed(t))}setVisitorInfo(t){this.store.dispatch(Y1(t))}setCustomData(t){this.store.dispatch(Q1(t))}setAgentInfo(t,n){return P(this,null,function*(){yield this.store.dispatch(Wa(T(T({},t),n)))})}setAgentSettings(t){return P(this,null,function*(){yield this.store.dispatch(oh(t))})}getAgentSettings(){return P(this,null,function*(){return(yield this.store.dispatch(sh())).payload})}refresh(){return P(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(ud({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(Yd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(dn(t))}evaluateRule(o){return P(this,arguments,function*(t,n={},r=ZC){return(yield this.store.dispatch(Yo({label:t,params:n,options:r}))).payload.cues})}evaluateAssistant(t,n){return P(this,null,function*(){let c=n||{},{input:r={},transcript:o,showCuesInWidget:s=!0,includeTags:i,expectFormat:a}=c,l=ee(c,["input","transcript","showCuesInWidget","includeTags","expectFormat"]);Object.assign(r,l);let u=yield this.store.dispatch(tr({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeTags:i,input:r,skipState:!s}));if(u.error)throw new Error(u.error.message);return u.payload})}evaluateConversationAssistant(t,n){return P(this,null,function*(){yield this.loadProfileConfig();let r={accepted:"conversationAcceptedAssistant","new-message":"conversationNewMessageAssistant",ended:"conversationEndedAssistant"},o=this.state.profile.data[r[t]];if(!o){H.warn(`No assistant set in profile for conversation event "${t}"`);return}yield this.evaluateAssistant(o,T({transcript:"stored-transcript",includeTags:!0},n))})}getSummary(){return P(this,null,function*(){var n;if(!this.hasConversation())return H.warn("No conversation to create summary for."),null;(n=this.state.profile.data)!=null&&n.summarizerAssistantNew||H.warn("No profile loaded yet, or no summarizer assistant set in profile");let t=yield this.store.dispatch(li({}));if(t.error)throw new Error(t.error.message);return t.payload})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.state.settings,u=a?"below":"above",c=o.length>0;if(!Mn(this.state)||(this.store.dispatch(H1(rh(t))),t.key!=="Tab"&&!l))return;let f=()=>{n||!c||i&&(t.shiftKey||(this.store.dispatch(j1()),t.preventDefault()))},d=()=>{n||!c||a&&s<=0||i&&(t.shiftKey||(this.store.dispatch(B1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():f();break;case"ArrowDown":{u==="below"?f():d();break}case"Escape":{n||(this.store.dispatch(ld(-1)),this.store.dispatch(no({collapse:!0})),this.store.dispatch(Yb(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let g=ii(this.state);if(!g)return;this.store.dispatch(hl(!1)),this.store.dispatch(dn({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.state.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let g=ii(this.state);if(!g)return;this.store.dispatch(dn({text:g.text,suggestion:g,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.state.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let g=ii(this.state);if(!g)return;this.store.dispatch(dn({text:g.text,suggestion:g,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(no({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Qr([]))}handlingTimeStart(){this.state.handlingTime.startTime||(H.info("Start handling time"),this.store.dispatch(lk()))}handlingTimeStop(){this.state.handlingTime.startTime&&(H.info("Stop handling time"),this.store.dispatch(Of()))}logSendMessage(t){let n=xk("input",this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n))}logHandlingTime(){let t=Sk(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(uk()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Io((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(K1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(s){H.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),H.error(s)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}setPlatformVariables(t){this.store.dispatch(X1(t))}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[s,i]=Dl(n,r);return s.setAttribute("translate","no"),s.dataset.testid=t,o&&s.classList.add(o),this.unmountHandlers.push(()=>{(0,sn.unmountComponentAtNode)(s),i(),s.remove()}),s}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let s=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[l,u]=Dl(s,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{(0,sn.unmountComponentAtNode)(o),u()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Wo(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,sn.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),H.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(H.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(V1(r.metrics))):H.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Mf(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:s,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:f,detectSubmit:d,insertLink:g,inputMediator:y,closestScrollSelector:v,appendOverlayTo:p,inlineSuggestions:m,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:i,insertLink:g,isEmbedded:f,inlineSuggestions:m,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Wo(t),this.inputMediator=y||(Go(t)?new Jo(t):new Zo(t)),this.inputMediator.on("change",({plainText:k,rawHTML:b})=>{this.store.dispatch(ud({text:k,html:b}))}),this.inputMediator.on("keyup",k=>{this.store.dispatch(U1(rh(k)))}),this.inputMediator.on("keydown",k=>{this.handleKeyDown(k)}),this.inputMediator.on("paste",({pastedText:k,selectionText:b})=>{this.store.dispatch(z1({text:k,selectionText:b}))}),this.inputMediator.on("cut",({selectionText:k})=>{this.store.dispatch(F1(k))});let S;this.inputMediator.on("selection",k=>{clearTimeout(S),k===null?S=setTimeout(()=>{k!==null&&this.store.dispatch(cd(k))},500):this.store.dispatch(cd(k))}),this.inputMediator.on("disabled",()=>{var k;(k=this.inputMediator)==null||k.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(Zd(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Zd(!0))});let w=v&&wk(t,v)||void 0;if(m){let{customStyles:k,appendOverlayTo:b}=n,R=this.createInlineContainer(t,"deepdesk-caret");(0,sn.render)((0,Fe.jsx)(qo,{store:this.store,customStyles:k,children:(0,Fe.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,Fe.jsx)(rC,{})})}),R),this.inputMediator.on("caretposition",_=>{_?(R.style.display="block",R.style.top=`${_.top}px`,R.style.left=`${_.left}px`):R.style.display="none"});let N=this.overlayContainerFactory("floating-menu",w||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:b},k==null?void 0:k.floatingMenuRootNode);(0,sn.render)((0,Fe.jsx)(qo,{store:this.store,customStyles:k,children:(0,Fe.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,Fe.jsx)($b,{onLogIn:()=>this.loginViaPopup().catch(_=>H.warn(_.message))})})}),N)}else{let k=this.overlayContainerFactory("deepdesk-tab-completion",w||t,{appendTo:p,closestScrollElement:w,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),b=this.overlayContainerFactory("deepdesk-suggestions-overlay",w||t,{appendTo:p},r==null?void 0:r.suggestionsRootNode);(0,sn.render)((0,Fe.jsx)(qo,{store:this.store,customStyles:r,children:(0,Fe.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,Fe.jsx)(NC,{inputElement:t})})}),k),(0,sn.render)((0,Fe.jsx)(qo,{store:this.store,customStyles:r,children:(0,Fe.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,Fe.jsx)(fC,{onLogIn:()=>this.loginViaPopup().catch(R=>H.warn(R.message))})})}),b)}(0,sn.render)((0,Fe.jsx)(qo,{store:this.store,customStyles:r,children:(0,Fe.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,Fe.jsx)(jb,{})})}),this.createContainer("deepdesk-overlays")),this.store.dispatch(ud({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(cd(this.inputMediator.getSelection())),this.store.dispatch(Zd(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var k;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((k=this.state.conversation.current)==null?void 0:k.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&H.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:s}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:s}),(0,sn.render)((0,Fe.jsx)(qo,{store:this.store,customStyles:r,children:(0,Fe.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,Fe.jsx)(XT,{onLogIn:()=>this.loginViaPopup().catch(i=>H.warn(i.message))})})}),t),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&(0,sn.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Ff(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){Ek(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>P(this,null,function*(){yield this.store.dispatch(nl());let t=nr(this.state);t&&(yield this.store.dispatch(el()),this.store.dispatch(ed({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew||t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))})),this.loadProfileConfigPromise)}loginViaPopup(t){return P(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,s=o.port1,i=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",f),clearInterval(d)};s.onmessage=g=>P(this,null,function*(){var y,v;if((y=g.data)!=null&&y.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((v=g.data)==null?void 0:v.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(qa),l=!0,o.port1.close(),n()}catch(p){console.error(p),r(p)}finally{l=!0,u()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let f=g=>P(this,null,function*(){var y;if(g.origin===a.origin)switch((y=g.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){H.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),g.data.message==="Timeout"&&H.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(g.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}checkForTrialMode(t){return P(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(H.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;H.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return P(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Od(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(yn()):su.includes(r)||this.store.dispatch(vn(r))})}catch(r){this.handleError(r)}})}};Ai.version="14.2.1-beta.6",Ai.count=0;var Fl=Ai;function h_(e){return P(this,null,function*(){var o,s,i;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(i=(s=e.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function _k(e,t){return P(this,null,function*(){let n=yield h_(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}})}function Dk(e,t,n){return P(this,null,function*(){yield new Sr(e).authenticateWithKey(t,n)})}function Fk(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function Hk(r,o){return P(this,arguments,function*(e,t,n={}){var f,d;let{value:s}=e,{start:i,end:a}=(f=n.replace)!=null?f:{start:0,end:s.length},l=`${s.slice(0,i)}${t}${s.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:i+t.length,end:i+t.length},c=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(c()).then(()=>{e.selectionStart=u.start,e.selectionEnd=u.end,e.blur(),e.focus()})})}function Uk(r,o){return P(this,arguments,function*(e,t,n={}){let s=n.replace?io(e,n.replace.start,n.replace.end):Ti(e),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?t.split(`
27
+ `);let y=d?r:0,v=g?Math.min(s,c.childNodes.length):c.childNodes.length;for(let p=y;p<v&&(u(c.childNodes[p]),a!==2);p++);break}default:break}g&&(a=2)}return u(e),l}var JT=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(JT||{}),yr=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let s=this.getCaretPosition();Gr(s,this.cachedCaretPosition)||(this.cachedCaretPosition=s,this.emit("caretposition",s))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(JT).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function ek(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Zo=class extends yr{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Nl(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(i=r.getComposedRanges(n))==null?void 0:i[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let s=this.element.ownerDocument.createRange();return s.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),s.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!ek(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!ek(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return Ol(this.element,n);let r=this.lastKnownSelection;if(r&&ZT(this.element,r.start,r.end))return r;let o=Ti(this.element);return o.collapse(!1),Ol(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Nl(this.element,io(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var r_=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function tk(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,s=window.getComputedStyle(e),i=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",r_.forEach(function(c){o[c]=s[c]}),n?e.scrollHeight>parseInt(s.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),i.appendChild(r);let l=e.getBoundingClientRect(),u={top:l.top-e.scrollTop+a.offsetTop+parseInt(s.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+parseInt(s.borderLeftWidth)};return i.removeChild(r),u}var Jo=class extends yr{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return tk(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function nk(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let s=document.createElement("iframe"),i=new URL(t);return Object.entries(n).forEach(([a,l])=>{i.searchParams.append(a,l)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=r,s.title=`iframe-${e}`,s.src=i.toString(),window.document.body.appendChild(s),s}function o_(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var Ly=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Oy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=nk(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},Ny=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),H.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Oy(t,this.deepdeskUrl,{debug:!0}):new Ly(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=o_(o.data);typeof s!="object"||s.type!=="event"||s.channel!==t||(H.info("Received broadcast event",this.sessionId,o),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(r),n}send(t,n,r){var i,a;H.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(i=this.eventMap)[t])==null||a.call(i,n));let s=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(I(T({},o),{channel:this.sessionId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},rk=Ny;function s_(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function oe(e){return Array.isArray(e)?e.map(oe):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(T({},t),{[s_(n)]:oe(e[n])}),{}):e}function My(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Le(e){return Array.isArray(e)?e.map(Le):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(T({},t),{[My(n)]:Le(e[n])}),{}):e}var ki=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var _y=e=>new Promise(t=>{setTimeout(t,e)});var Pi=class extends ki{constructor(){super(...arguments);this.name="ClientError"}},Fy=class extends ki{constructor(){super(...arguments);this.name="ServerError"}},Dy=new Map;function i_(e){return P(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(H.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var ao=class ao{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let s={isAborted:!1,reject:o},i=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",b=n,{useCache:u=!1,abortLatest:c=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:g=!0,retryOnError:y=R=>R instanceof TypeError,retryOnResponse:v=R=>R.status>=500,version:p=null}=b,m=ee(b,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(Dy.has(i)){r(Dy.get(i));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h=I(T({credentials:"include"},m),{headers:T({Accept:"application/json","Content-Type":"application/json"},m.headers)});!l&&this.csrfToken&&(h.headers=I(T({},h.headers),{"X-CSRFToken":this.csrfToken})),typeof p=="string"&&(h.headers=I(T({},h.headers),{"X-Deepdesk-API-Version":p}));let S=f,w=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let k=()=>P(this,null,function*(){return S--,a(i,h).then(R=>P(this,null,function*(){return v(R)&&!s.isAborted&&S>0?(yield _y(d),k()):R.status===401&&g===!0&&w===!1?(w=!0,yield this.refreshToken(),k()):R})).catch(R=>P(this,null,function*(){if(y(R)&&!s.isAborted&&S>0)return yield _y(d),k();throw R}))});k().then(R=>P(this,null,function*(){let N=yield i_(R);if(delete this.latestRequestByUrl[i],R.status>=500){o(new Fy("Server Error",N));return}else if(R.status===401){o(new Pi("Unauthorized",N));return}else if(R.status===403){o(new Pi("Forbidden",N));return}else if(R.status===404){o(new Pi("Not Found",N));return}else if(R.status>=400){o(new Pi("Bad Request",N));return}u&&Dy.set(i,N),r(N)})).catch(R=>{o(R)})})}validateToken(){return P(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)try{yield this.refreshToken()}catch(r){return!1}let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/");return!!n})}refreshToken(){return ao.refreshingToken||(ao.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{ao.refreshingToken=null},1e3*60)})),ao.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,T({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,T({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,T({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,T({method:"DELETE"},n))}};ao.refreshingToken=null;var vr=ao;var ok;(t=>{let e;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||(t.EventType={}))})(ok||(ok={}));function Lf(e){return I(T({},oe(e)),{tags:e.tags})}var es=class es{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new vr(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,s)=>P(this,null,function*(){let i=yield r(o,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return P(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(es.exchangeTokenPromise||(es.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),es.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return P(this,null,function*(){yield this.preflight(),H.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",I(T({},Le(t)),{tags:t.tags}),{version:"v2"});return Lf(n)})}getMe(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return oe(t)})}postIdentity(t){return P(this,null,function*(){yield this.client.post("/apis/admin/session/me/identities/",Le(t))})}patchMe(t){return P(this,null,function*(){let n=yield this.client.patch("/apis/admin/session/me/",Le(t));return oe(n)})}getProfile(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return oe(n)})}getKnowledgeAssistant(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return oe(n)})}getContentTypes(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return oe(t)})}getAccount(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return oe(t)})}getPlatformConfig(t){return P(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return oe(r)})}checkUserExists(t){return P(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationBySessionId(r){return P(this,arguments,function*(t,n={}){yield this.preflight(),H.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return H.info(`Successfully retrieved conversation ${i.id} for session ${t}`),Lf(i)})}isConversationSupported(r){return P(this,arguments,function*(t,n={}){H.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return P(this,null,function*(){let r=Le(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Lf(o)})}postMessages(t,n){return P(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>I(T({},Le(o)),{tags:o.tags})),{version:"v2"})).map(o=>Lf(o))})}sendEvent(t,n){return P(this,null,function*(){let i=n,{data:r}=i,o=ee(i,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>I(T({},a),{[l]:u}),{});return this.client.post("/api/events",Le(I(T(T({},s),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return P(this,null,function*(){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[s,i])=>I(T({},o),{[s]:i}),{});return this.client.post("/api/events",{event:t,data:Le(T(T({},n),r))},{version:"v1"})})}getEntities(t){return P(this,null,function*(){return(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)},{version:"v1"})).entities})}getTemporaryExchangeToken(){return P(this,null,function*(){return(yield this.client.get("/auth/exchange-token")).jwt})}exchangeTokenForAccessCookie(t){return P(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw H.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return P(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Le(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return P(this,arguments,function*(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(yield this.client.post(`/api/conversations/${t}/recommend/${r}`,Le(n),{abortLatest:!0,version:"v1"})).map(i=>I(T({},oe(i)),{text:i.text||i.url||i.message,source:r,type:r})).filter((i,a,l)=>a===l.findIndex(u=>u.text===i.text))})}isLoggedIn(){return P(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return P(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/autocomplete`,Le(n),{abortLatest:!0,version:"v1"})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,s,i)=>s===i.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return P(this,null,function*(){let n=yield this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0,version:"v1"});return oe(n).map(r=>I(T({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return P(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",Le(t),{abortLatest:!0,version:"v1"});return oe(n)})}search(t){return P(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,Le(t),{version:"v2"});return oe(n)})}knowledgeAssist(s,i,a){return P(this,arguments,function*(t,n,r,o={}){let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Le({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(u=>({question:u.question,answer:u.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return oe(l)})}requestLoginByEmail(t){return P(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return oe(n)})}requestPasswordlessToken(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return oe(t.token)})}getCsrfToken(){return P(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return P(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return oe(n)})}evaluateRule(s,i,a){return P(this,arguments,function*(t,n,r,o={}){let l=new URLSearchParams;o.raiseForFailingConditions&&l.set("raise_for_failing_conditions","true");let u=yield this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${l.toString()}`,r,{version:"v2"});return u?oe(u.cues):[]})}getSummary(r){return P(this,arguments,function*(t,n={}){let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(s=>s.text&&s.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return oe(o)})}evaluateAssistant(t,n){return P(this,null,function*(){var a;let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let l=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",l)}else r.append("expect_response_format",o);n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let s=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,i=yield this.client.post(s,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return oe(i.output)})}createAssistantThread(t){return P(this,null,function*(){let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return oe(r)})}postMessageToAssistantThread(t){return P(this,null,function*(){let{assistantCode:n,threadId:r,message:o}=t,s=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return oe(s)})}getRules(){return P(this,null,function*(){let t=new URLSearchParams,n=yield this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{useCache:!0});return oe(n)})}translateMessages(t){return P(this,null,function*(){let n=yield this.client.post("/api/translate",Le(t),{version:"v2"});return oe(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(r0);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&H.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};es.exchangeTokenPromise=null;var Sr=es;var Ml=class{constructor(t,n){this.url=t;this.eventListeners={};this.options=T({timeout:25e3},n)}proxyEvent(t){this.eventSource.addEventListener(My(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,oe(o))}catch(o){H.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var sk;(t=>{let e;(s=>(s.Started="Started",s.Aborted="Aborted",s.Completed="Completed"))(e=t.AutoflowSessionState||(t.AutoflowSessionState={}))})(sk||(sk={}));var _l=class{constructor(t,n={}){this.apiUrl=t;this.streams={};this.logger=H;this.client=new vr(t,n)}getCustomMessages(t){return P(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/suggestions`);return oe(n.suggestions)})}sendCustomMessage(t,n){return P(this,null,function*(){let r=yield this.client.post(`/sessions/${t}/messages`,Le(n));return oe(r)})}answerCustomMessage(t,n){return P(this,null,function*(){yield this.client.post(`/sessions/${t}/answers`,Le(n))})}getAutoflows(t){return P(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/autoflows`);return oe(n.autoflows)})}startAutoflowSession(t){return P(this,null,function*(){let n=yield this.client.post("/autoflow-sessions",Le(t));return oe(n)})}stopAutoflowSession(t){return P(this,null,function*(){yield this.client.delete(`/autoflow-sessions/${t}`)})}openStream(t){return this.streams[t]||(this.streams[t]=new Ml(`${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 ik={startTime:null,stopTime:null},ak=J({name:"handlingTime",initialState:ik,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(xe,()=>ik)}}),{handlingTimeStart:lk,handlingTimeStop:Of,handlingTimeReset:uk}=ak.actions,ck=ak.reducer;var dk=(e={})=>{let t=T({onAuthError:ni(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Nf={list:{keywordMatches:[]},fetchState:"idle"};var ts=V("styleSuggestions/getAll",(n,r)=>P(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,s=t.getState(),{showStyleSuggestions:i}=s.settings,a=(l=s.conversation.current)==null?void 0:l.profileCode;if(!i)return Nf.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),a_=J({name:"styleSuggestions",initialState:Nf,reducers:{},extraReducers:e=>{e.addCase(ts.pending,t=>{t.fetchState="loading"}).addCase(ts.rejected,t=>{t.fetchState="error"}).addCase(ts.fulfilled,(t,n)=>{t.fetchState="done",Gr(t.list,n.payload)||(t.list=n.payload)}).addCase(Io,t=>{t.list=Nf.list}).addCase(xe,()=>Nf)}}),fk=a_.reducer;var pk=(e={})=>{let t,n=!0,r=T({getStyleSuggestions:ts,debounce:500},e);return o=>s=>i=>{var g;let a=o.getState().input.text,l=s(i),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((g=u.conversation.current)==null?void 0:g.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 l_(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var mk=(e={})=>{let t=T({getTextSuggestions:vn,getAutocompleteSuggestions:ml,debounce:200,check:Mn},e),n;return r=>o=>s=>{var v;let{input:i}=r.getState(),a=o(s),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,f=(v=l.conversation.current)==null?void 0:v.id,d=s.type===Yd.toString();if(!f||!u&&!c)return a;let{input:g}=l;return l_(g,i)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let p=si(l);p===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(p))},d?0:t.debounce)),a}};var gk=ts.fulfilled.toString();function u_(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let s=e.keywordMatches.filter(l=>l.keyword===o),i=t.keywordMatches.filter(l=>l.keyword===o),a=i.length-s.length;a<=0||r.push(...i.slice(0,a))}),r}var hk=e=>t=>n=>r=>{var u;if(r.type!==gk){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let s=t.getState(),i=s.styleSuggestions.list,a=(u=s.conversation)==null?void 0:u.current;if(o===i)return;let l=u_(o,i);r.type===gk&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var c_=Tc({assistants:_E,auth:b1,autoflows:UC,conversation:N1,contentTypes:FE,customMessages:GC,passwordlessToken:XC,entities:cb,knowledgeAssistant:IE,handlingTime:ck,info:Z1,input:W1,settings:h1,profile:UE,search:sE,styleSuggestions:fk,ui:Xb,rules:nT,textSuggestions:Mb});function yk(e){return Ew({reducer:c_,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),dk(),mk({debounce:200}),pk({debounce:500}),hk(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var d_=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},f_=e=>t=>n=>r=>{var a,l,u,c,f,d,g;let o=t.getState(),s=Zg("inlineSuggestions")(o);switch(r.type){case ni.toString():{!r.payload&&e.emit("logout",void 0);break}case yn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case ct.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Io.toString():e.logSendMessage(r.payload);break;case Yo.fulfilled.toString():r.isBroadcasted||e.broadcast(ih,r,!1),(c=r.payload.options)!=null&&c.shouldEmit&&e.emit("cues",r.payload.cues);break;case Id.toString():e.emit("call-to-action",{cue:r.payload});break;case tr.fulfilled.toString():r.isBroadcasted||e.broadcast(ah,r,!1);break;default:break}let i=n(r);switch(r.type){case Io.toString():e.handleAfterSendMessage(r.payload);break;case hl.toString():e.onUpdateShowTabHint(r.payload);break;case Of.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case id.toString():{let{start:y,end:v}=o.input.selection;e.emit("replace",I(T({},r.payload),{replace:r.payload.replace==="selection"?{start:y,end:v}:{start:0,end:v}}));break}case dn.toString():{let{start:y,end:v}=o.input.selection;e.emit("select-suggestion",I(T({type:d_(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:y,end:v}:{start:0,end:v}})),s&&t.dispatch(Qr([]));break}case ad.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Qr.toString():{s&&r.payload.length>0&&t.dispatch(ld(0));break}case li.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(d=o.conversation.current)==null?void 0:d.id,data:{summary:r.payload,assistant:(g=t.getState().profile.data)==null?void 0:g.summarizerAssistantNew}});break}default:break}return i},vk=f_;function Hy(e){return e.toISOString().replace("T"," ").replace("Z","")}function Sk(e,t){var s,i,a,l;let n=(s=e.conversation.current)==null?void 0:s.id;if(!n)return H.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:o}=e.handlingTime;return!r||!o?(H.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:n,clientVersion:t.version,agentId:(i=e.info.agentInfo)==null?void 0:i.agentId,agentName:(a=e.info.agentInfo)==null?void 0:a.agentName,agentEmail:(l=e.info.agentInfo)==null?void 0:l.agentEmail,timeStart:Hy(r),timeStop:Hy(o)}}function xk(e,t,n){var N,_,Q,K;let r=(N=t.conversation.current)==null?void 0:N.id;if(!r)return H.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:s,numCharsPasted:i,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:f,pastes:d,cuts:g,deletions:y,textSuggestions:v,offeredTextSuggestions:p}}=t[e],m=o.length,S=v.reduce((W,{text:de,searchTerm:Ye})=>W+de.length-(Ye?Ye.length:0),0),w=c!=null?c:Date.now(),k=(Date.now()-w)/1e3+(f||0),b=s/k,R=v.reduce((W,{searchTerm:de})=>W+(de?de.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:g,deletions:y,lenTextTyped:s+R,lenTextTotal:m,lenTextAssisted:S,lenTextPasted:i,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:k,charsPerSecond:b,numPastes:u,textSuggestionsV2:v,suggestionsCounters:[{source:"gpt",countOffered:p.filter(W=>W.source==="gpt").length}],agentId:(_=t.info.agentInfo)==null?void 0:_.agentId,agentName:(Q=t.info.agentInfo)==null?void 0:Q.agentName,agentEmail:(K=t.info.agentInfo)==null?void 0:K.agentEmail}}function Uy(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Uy(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?Uy(o,t):null}function wk(e,t){return Uy(e,t)}function Ek(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function p_(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Mf(e){return p_(e)&&(Go(e)||of(e))}var Ck,Fn=new Map,m_=["bottom","height","left","right","top","width"],bk=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:m_.some(n=>e[n]!==t[n]);function Tk(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...Tk(t)]:[]}function kk(e,t){return!e||!t?null:I(T({},e),{top:e.top+t.top,left:e.left+t.left})}var _f=!1,Pk=()=>{_f=!0;let e=[];if(Fn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Fn.delete(n);return}let r=n.getBoundingClientRect();bk(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(kk,t.rect):t.rect;bk(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Fn.size===0){_f=!1;return}Ck=window.requestAnimationFrame(Pk)};function zy(e,t){let n=Tk(e),r=[],o=n.map((s,i)=>zy(s,a=>{r[i]=a;let l=Fn.get(e);if(!l)return;let u=r.reduce(kk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),Fn.has(e)){let i=Fn.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else Fn.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!_f&&Pk()},unobserve(){o.forEach(i=>i.unobserve());let s=Fn.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||Fn.delete(e),Fn.size||(cancelAnimationFrame(Ck),_f=!1)}}}}var Rk,Hn=new Map,Ak=()=>{Hn.forEach((e,t)=>{if(!t.isConnected){Hn.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(s=>s(e.visible)))}),Hn.size!==0&&(Rk=window.requestAnimationFrame(Ak))};function Ik(e,t){return{observe(){let n=Hn.size===0;Hn.has(e)?Hn.get(e).callbacks.push(t):Hn.set(e,{visible:void 0,callbacks:[t]}),n&&Ak()},unobserve(){let n=Hn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Hn.delete(e),Hn.size||cancelAnimationFrame(Rk)}}}}var jy=["borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth","borderStyle","boxSizing","color","overflowWrap","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontWeight","fontKerning","lineHeight","letterSpacing","paddingLeft","paddingTop","paddingRight","paddingBottom","width","height","textIndent","whiteSpace","wordBreak","wordSpacing","wordWrap"];function By(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Ri(e){return parseFloat(e)}function Df(e){return Math.round(e*1e6)}function Lk(e){return e/1e6}function Vy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Ri(e.width),s=Ri(e.borderLeftWidth),i=Ri(e.borderRightWidth),a=Ri(e.paddingRight),l=Lk(Df(o)-Df(s)-Df(i)),u=Lk(Df(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function Dl(e,t={}){var c,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Wo(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};By(r,n,jy),Vy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=Ik(e,()=>{By(r,n,jy),Vy(r,e,n),s(),setTimeout(s,0)}),a,l=!0,u=zy(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(By(r,n,jy),Vy(r,e,n),s(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let g=t.closestScrollElement.getBoundingClientRect(),y=window.getComputedStyle(t.closestScrollElement),v=Ri(y.borderTopWidth),p=Ri(y.borderBottomWidth),m=g.top+v-d.top,h=d.top+d.height+-(g.top+g.height-p);n.style.clipPath=`inset(${m}px 0px ${h}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),u.observe(),i.observe(),[n,()=>{e.removeEventListener("scroll",s),u.unobserve(),i.unobserve()}]}var Ok=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){H.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function g_(e){return e.offsetParent!==null}function Nk(e){if(!g_(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function Ff(e,t,n=100){let r=Nk(e);t({isVisible:r});let o=setInterval(()=>{let s=Nk(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Fe=x(C());var Mk=Ok("showTabHint",!0),Ai=class Ai{constructor({deepdeskUrl:t,brokerUrl:n,version:r=Ai.version||"unknown",locale:o="en-US",token:s,fetch:i,productName:a,createCustomChannel:l}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let u=t.replace(/\/api$/,"");this.deepdeskApi=new Sr(u,{token:s,fetch:i}),this.version=r,this.instanceId=Ai.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[vk({broadcast:(f,d,g)=>{this.broadcastEvents.send(f,d,g)},emit:(f,d)=>this.emit(f,d),handleAfterSendMessage:f=>this.handleAfterSendMessage(f),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:f=>this.logSendMessage(f),onUpdateShowTabHint:f=>Mk.update(f),sendEvent:(f,d)=>this.deepdeskApi.sendEvent(f,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new _l(n)}),this.store=yk(c),this.broadcastEvents=new rk({debug:!0,deepdeskUrl:u,eventMap:iE(this.store),createCustomChannel:l}),this.store.dispatch(hl(Mk.value())),this.store.dispatch(ed({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(H.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(H.warn("Profile has not been loaded (yet)"),!0):(H.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(ni(null)),this.store.dispatch(Jn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();ut(r)&&y1(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return P(this,null,function*(){return(yield this.store.dispatch(Jn())).payload})}isConversationSupported(t,n){return P(this,null,function*(){return(yield this.store.dispatch(th({sessionId:t,options:n}))).payload})}createConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(nd(t))).payload})}getConversationBySessionId(t,n){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(rd({sessionId:t,options:n}))).payload})}upsertConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(nh(t))).payload})}postMessages(t){return P(this,null,function*(){return(yield this.store.dispatch(sd(t))).payload})}updateConversation(t){return P(this,null,function*(){return(yield this.store.dispatch(od(t))).payload})}resetConversation(){this.store.dispatch(xe()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(ed(t))}setVisitorInfo(t){this.store.dispatch(Y1(t))}setCustomData(t){this.store.dispatch(Q1(t))}setAgentInfo(t,n){return P(this,null,function*(){yield this.store.dispatch(Wa(T(T({},t),n)))})}setAgentSettings(t){return P(this,null,function*(){yield this.store.dispatch(oh(t))})}getAgentSettings(){return P(this,null,function*(){return(yield this.store.dispatch(sh())).payload})}refresh(){return P(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(ud({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(Yd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(dn(t))}evaluateRule(o){return P(this,arguments,function*(t,n={},r=ZC){return(yield this.store.dispatch(Yo({label:t,params:n,options:r}))).payload.cues})}evaluateAssistant(t,n){return P(this,null,function*(){let c=n||{},{input:r={},transcript:o,showCuesInWidget:s=!0,includeTags:i,expectFormat:a}=c,l=ee(c,["input","transcript","showCuesInWidget","includeTags","expectFormat"]);Object.assign(r,l);let u=yield this.store.dispatch(tr({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeTags:i,input:r,skipState:!s}));if(u.error)throw new Error(u.error.message);return u.payload})}evaluateConversationAssistant(t,n){return P(this,null,function*(){yield this.loadProfileConfig();let r={accepted:"conversationAcceptedAssistant","new-message":"conversationNewMessageAssistant",ended:"conversationEndedAssistant"},o=this.state.profile.data[r[t]];if(!o){H.warn(`No assistant set in profile for conversation event "${t}"`);return}yield this.evaluateAssistant(o,T({transcript:"stored-transcript",includeTags:!0},n))})}getSummary(){return P(this,null,function*(){var n;if(!this.hasConversation())return H.warn("No conversation to create summary for."),null;(n=this.state.profile.data)!=null&&n.summarizerAssistantNew||H.warn("No profile loaded yet, or no summarizer assistant set in profile");let t=yield this.store.dispatch(li({}));if(t.error)throw new Error(t.error.message);return t.payload})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.state.settings,u=a?"below":"above",c=o.length>0;if(!Mn(this.state)||(this.store.dispatch(H1(rh(t))),t.key!=="Tab"&&!l))return;let f=()=>{n||!c||i&&(t.shiftKey||(this.store.dispatch(j1()),t.preventDefault()))},d=()=>{n||!c||a&&s<=0||i&&(t.shiftKey||(this.store.dispatch(B1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():f();break;case"ArrowDown":{u==="below"?f():d();break}case"Escape":{n||(this.store.dispatch(ld(-1)),this.store.dispatch(no({collapse:!0})),this.store.dispatch(Yb(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let g=ii(this.state);if(!g)return;this.store.dispatch(hl(!1)),this.store.dispatch(dn({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.state.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let g=ii(this.state);if(!g)return;this.store.dispatch(dn({text:g.text,suggestion:g,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.state.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let g=ii(this.state);if(!g)return;this.store.dispatch(dn({text:g.text,suggestion:g,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(no({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Qr([]))}handlingTimeStart(){this.state.handlingTime.startTime||(H.info("Start handling time"),this.store.dispatch(lk()))}handlingTimeStop(){this.state.handlingTime.startTime&&(H.info("Stop handling time"),this.store.dispatch(Of()))}logSendMessage(t){let n=xk("input",this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n))}logHandlingTime(){let t=Sk(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(uk()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Io((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(K1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(s){H.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),H.error(s)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}setPlatformVariables(t){this.store.dispatch(X1(t))}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[s,i]=Dl(n,r);return s.setAttribute("translate","no"),s.dataset.testid=t,o&&s.classList.add(o),this.unmountHandlers.push(()=>{(0,sn.unmountComponentAtNode)(s),i(),s.remove()}),s}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let s=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[l,u]=Dl(s,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{(0,sn.unmountComponentAtNode)(o),u()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Wo(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,sn.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),H.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(H.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(V1(r.metrics))):H.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Mf(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:s,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:f,detectSubmit:d,insertLink:g,inputMediator:y,closestScrollSelector:v,appendOverlayTo:p,inlineSuggestions:m,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:i,insertLink:g,isEmbedded:f,inlineSuggestions:m,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Wo(t),this.inputMediator=y||(Go(t)?new Jo(t):new Zo(t)),this.inputMediator.on("change",({plainText:k,rawHTML:b})=>{this.store.dispatch(ud({text:k,html:b}))}),this.inputMediator.on("keyup",k=>{this.store.dispatch(U1(rh(k)))}),this.inputMediator.on("keydown",k=>{this.handleKeyDown(k)}),this.inputMediator.on("paste",({pastedText:k,selectionText:b})=>{this.store.dispatch(z1({text:k,selectionText:b}))}),this.inputMediator.on("cut",({selectionText:k})=>{this.store.dispatch(F1(k))});let S;this.inputMediator.on("selection",k=>{clearTimeout(S),k===null?S=setTimeout(()=>{k!==null&&this.store.dispatch(cd(k))},500):this.store.dispatch(cd(k))}),this.inputMediator.on("disabled",()=>{var k;(k=this.inputMediator)==null||k.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(Zd(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Zd(!0))});let w=v&&wk(t,v)||void 0;if(m){let{customStyles:k,appendOverlayTo:b}=n,R=this.createInlineContainer(t,"deepdesk-caret");(0,sn.render)((0,Fe.jsx)(qo,{store:this.store,customStyles:k,children:(0,Fe.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,Fe.jsx)(rC,{})})}),R),this.inputMediator.on("caretposition",_=>{_?(R.style.display="block",R.style.top=`${_.top}px`,R.style.left=`${_.left}px`):R.style.display="none"});let N=this.overlayContainerFactory("floating-menu",w||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:b},k==null?void 0:k.floatingMenuRootNode);(0,sn.render)((0,Fe.jsx)(qo,{store:this.store,customStyles:k,children:(0,Fe.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,Fe.jsx)($b,{onLogIn:()=>this.loginViaPopup().catch(_=>H.warn(_.message))})})}),N)}else{let k=this.overlayContainerFactory("deepdesk-tab-completion",w||t,{appendTo:p,closestScrollElement:w,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),b=this.overlayContainerFactory("deepdesk-suggestions-overlay",w||t,{appendTo:p},r==null?void 0:r.suggestionsRootNode);(0,sn.render)((0,Fe.jsx)(qo,{store:this.store,customStyles:r,children:(0,Fe.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,Fe.jsx)(NC,{inputElement:t})})}),k),(0,sn.render)((0,Fe.jsx)(qo,{store:this.store,customStyles:r,children:(0,Fe.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,Fe.jsx)(fC,{onLogIn:()=>this.loginViaPopup().catch(R=>H.warn(R.message))})})}),b)}(0,sn.render)((0,Fe.jsx)(qo,{store:this.store,customStyles:r,children:(0,Fe.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,Fe.jsx)(jb,{})})}),this.createContainer("deepdesk-overlays")),this.store.dispatch(ud({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(cd(this.inputMediator.getSelection())),this.store.dispatch(Zd(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var k;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((k=this.state.conversation.current)==null?void 0:k.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&H.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:s}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:s}),(0,sn.render)((0,Fe.jsx)(qo,{store:this.store,customStyles:r,children:(0,Fe.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,Fe.jsx)(XT,{onLogIn:()=>this.loginViaPopup().catch(i=>H.warn(i.message))})})}),t),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&(0,sn.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Ff(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){Ek(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>P(this,null,function*(){yield this.store.dispatch(nl());let t=nr(this.state);t&&(yield this.store.dispatch(el()),this.store.dispatch(ed({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew||t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))})),this.loadProfileConfigPromise)}loginViaPopup(t){return P(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,s=o.port1,i=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",f),clearInterval(d)};s.onmessage=g=>P(this,null,function*(){var y,v;if((y=g.data)!=null&&y.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((v=g.data)==null?void 0:v.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(qa),l=!0,o.port1.close(),n()}catch(p){console.error(p),r(p)}finally{l=!0,u()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let f=g=>P(this,null,function*(){var y;if(g.origin===a.origin)switch((y=g.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){H.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),g.data.message==="Timeout"&&H.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(g.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}checkForTrialMode(t){return P(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(H.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;H.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return P(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Od(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(yn()):su.includes(r)||this.store.dispatch(vn(r))})}catch(r){this.handleError(r)}})}};Ai.version="14.2.1-beta.7",Ai.count=0;var Fl=Ai;function h_(e){return P(this,null,function*(){var o,s,i;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(i=(s=e.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function _k(e,t){return P(this,null,function*(){let n=yield h_(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}})}function Dk(e,t,n){return P(this,null,function*(){yield new Sr(e).authenticateWithKey(t,n)})}function Fk(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function Hk(r,o){return P(this,arguments,function*(e,t,n={}){var f,d;let{value:s}=e,{start:i,end:a}=(f=n.replace)!=null?f:{start:0,end:s.length},l=`${s.slice(0,i)}${t}${s.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:i+t.length,end:i+t.length},c=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(c()).then(()=>{e.selectionStart=u.start,e.selectionEnd=u.end,e.blur(),e.focus()})})}function Uk(r,o){return P(this,arguments,function*(e,t,n={}){let s=n.replace?io(e,n.replace.start,n.replace.end):Ti(e),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?t.split(`
28
28
  `).reverse().forEach((l,u)=>{u>0&&s.insertNode(document.createElement("br")),s.insertNode(document.createTextNode(l))}):s.insertNode(document.createTextNode(t))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let l=n.selectionAfter?io(e,n.selectionAfter.start,n.selectionAfter.end):(s.collapse(!1),s),u=window.getSelection();u==null||u.removeAllRanges(),u==null||u.addRange(l)}if(!i)return;i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}function y_(e){let t=document.createElement("template");return t.innerHTML=e.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),t.content}function v_(e){let t=document.createDocumentFragment();return e.split(`
29
29
  `).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},s=0;for(;o=n.slice(s).match(/(\[([^\]]+)])\(([^)]+)\)/);){let i=document.createElement("a");i.href=o[3],i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),i.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(s,s+o.index))),t.appendChild(i),s=s+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(s)))}),t}function zk(e,t){let n=e.parentElement;if(!n){console.warn("No insert point found");return}let{display:r}=window.getComputedStyle(n);r.includes("block")||r==="table-cell"?n==null||n.insertBefore(t,e.nextSibling):zk(n,t)}function jk(o,s){return P(this,arguments,function*(e,t,{isBlock:n,isHTML:r}={}){let i;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let a=()=>{var d;let l=(d=e.ownerDocument.defaultView)!=null?d:window,u=l.getSelection();if((!u||u.rangeCount===0)&&(e.focus(),u=l.getSelection()),!u||u.rangeCount===0)return;let c=u.getRangeAt(0);if(!c)return;i=document.createElement("span"),c.insertNode(i);let f=r?y_(t):v_(t);n?zk(c.startContainer,f):(c.insertNode(f),c.collapse(!1))};return Promise.resolve(a()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!i)try{i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}return nP(S_);})();
30
30
  /*! Bundled license information: