@deepdesk/deepdesk-sdk 14.2.1-beta.0 → 14.2.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -24,7 +24,7 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
24
24
  `+yt),xn&&bf([V,W,me],vt=>{yt=Cl(yt,vt," ")}),S&&jl?S.createHTML(yt):yt},t.setConfig=function(){let B=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Vf(B),Hn=!0},t.clearConfig=function(){ui=null,Hn=!1},t.isValidAttribute=function(B,E,A){ui||Vf({});let U=He(B),Z=He(E);return av(U,Z,A)},t.addHook=function(B,E){typeof E=="function"&&(Y[B]=Y[B]||[],bl(Y[B],E))},t.removeHook=function(B){if(Y[B])return bT(Y[B])},t.removeHooks=function(B){Y[B]&&(Y[B]=[])},t.removeAllHooks=function(){Y={}},t}var DT=_T();var gr=w(H());var FM={"":["<em>","</em>"],_:["<strong>","</strong>"],"*":["<strong>","</strong>"],"~":["<s>","</s>"],"\n":["<br />"]," ":["<br />"],"-":["<hr />"]};function FT(e){return e.replace(RegExp("^"+(e.match(/^(\t| )+/)||"")[0],"gm"),"")}function kl(e){return(e+"").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Pl(e,t){var n,r,o,i,s,a=/((?:^|\n+)(?:\n---+|\* \*(?: \*)+)\n)|(?:^``` *(\w*)\n([\s\S]*?)\n```$)|((?:(?:^|\n+)(?:\t| {2,}).+)+\n*)|((?:(?:^|\n)([>*+-]|\d+\.)\s+.*)+)|(?:!\[([^\]]*?)\]\(([^)]+?)\))|(\[)|(\](?:\(([^)]+?)\))?)|(?:(?:^|\n+)([^\s].*)\n(-{3,}|={3,})(?:\n+|$))|(?:(?:^|\n+)(#{1,6})\s*(.+)(?:\n+|$))|(?:`([^`].*?)`)|( \n\n*|\n{2,}|__|\*\*|[_*]|~~)/gm,l=[],u="",c=t||{},f=0;function d(v){var y=FM[v[1]||""],p=l[l.length-1]==v;return y?y[1]?(p?l.pop():l.push(v),y[0|p]):y[0]:v}function h(){for(var v="";l.length;)v+=d(l[l.length-1]);return v}for(e=e.replace(/^\[(.+?)\]:\s*(.+)$/gm,function(v,y,p){return c[y.toLowerCase()]=p,""}).replace(/^\n+|\n+$/g,"");o=a.exec(e);)r=e.substring(f,o.index),f=a.lastIndex,n=o[0],r.match(/[^\\](\\\\)*\\$/)||((s=o[3]||o[4])?n='<pre class="code '+(o[4]?"poetry":o[2].toLowerCase())+'"><code'+(o[2]?' class="language-'+o[2].toLowerCase()+'"':"")+">"+FT(kl(s).replace(/^\n+|\n+$/g,""))+"</code></pre>":(s=o[6])?(s.match(/\./)&&(o[5]=o[5].replace(/^\d+/gm,"")),i=Pl(FT(o[5].replace(/^\s*[>*+.-]/gm,""))),s==">"?s="blockquote":(s=s.match(/\./)?"ol":"ul",i=i.replace(/^(.*)(\n|$)/gm,"<li>$1</li>")),n="<"+s+">"+i+"</"+s+">"):o[8]?n='<img src="'+kl(o[8])+'" alt="'+kl(o[7])+'">':o[10]?(u=u.replace("<a>",'<a href="'+kl(o[11]||c[r.toLowerCase()])+'">'),n=h()+"</a>"):o[9]?n="<a>":o[12]||o[14]?n="<"+(s="h"+(o[14]?o[14].length:o[13]>"="?1:2))+">"+Pl(o[12]||o[15],c)+"</"+s+">":o[16]?n="<code>"+kl(o[16])+"</code>":(o[17]||o[1])&&(n=d(o[17]||"--"))),u+=r,u+=n;return(u+e.substring(f)+h()).replace(/^\n+|\n+$/g,"")}var HT={root:"dd-L7b3z",popover:"dd-OQOTB",options:"dd-Y12RE",arrow:"dd-cv33T",copyIcon:"dd-6xOsH",option:"dd-9oFX4",divider:"dd-aiZf8",fadeup:"dd-Jq9pd"};var vn=w(C());function HM(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 UM(e){return e.replace(/\r\n/g,`
25
25
  `)}function zM(e){return e.replace(new RegExp("(?<!\\]\\()(https?:\\/\\/[^\\s]+)","g"),"[$1]($1)")}var BM=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let i=L("Markdown",HT),s=(0,gr.useRef)(null),[a,l]=(0,gr.useState)(null),u=(0,gr.useMemo)(()=>{let y=Pl(zM(UM(e)));return DT.sanitize(y).replaceAll("</code>",`${HM(i.copyIcon)}</code>`).replaceAll('<a href="','<a target="_blank" rel="noreferrer noopener" href="')},[e]),c=y=>{var g;let p=y.target,m=!!((g=s.current)!=null&&g.querySelector("code"));if(["A","BUTTON"].includes(p.tagName)){l(null);return}a||m&&p.tagName!=="CODE"||!m&&p!==s.current||(p.addEventListener("mouseleave",()=>l(null),{once:!0}),l(p))},f=()=>{if(!a)return;l(null);let y=a.querySelector("button");y&&(ps(y,i.fadeup),r(Ay(a)))},d=y=>{let p=y.target;if(p.tagName==="A"){y.stopPropagation();return}"copyIcon"in p.dataset&&(ps(p,i.fadeup),r(Ay(p.parentElement)))},h=()=>{!a||!o||(l(null),o(Ay(a)))},v=y=>{if(y===null)return;let p=y.getBoundingClientRect();p.left<0?y.style.transform=`translateX(${-p.left+2}px)`:p.right>window.innerWidth&&(y.style.transform=`translateX(${window.innerWidth-p.right-2}px)`)};return(0,vn.jsxs)(gr.Fragment,{children:[a&&(0,vn.jsxs)(bs,{triggerRef:{current:a},className:i.popover,parentNode:a,children:[(0,vn.jsxs)("div",{className:i.options,ref:v,children:[(0,vn.jsx)("button",{type:"button",className:i.option,onClick:f,children:n}),o&&(0,vn.jsxs)(gr.Fragment,{children:[(0,vn.jsx)("div",{className:i.divider}),(0,vn.jsx)("button",{type:"button",className:i.option,onClick:h,children:t})]})]}),(0,vn.jsx)("div",{className:i.arrow})]}),(0,vn.jsx)("div",{ref:s,className:i.root,dangerouslySetInnerHTML:{__html:u},onMouseOver:c,onClick:d})]})},UT=BM;var Ly={};Ye(Ly,{enUS:()=>jM,nlNL:()=>VM});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"}]},VM={useCue:[{type:0,value:"Voeg toe aan bericht"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var zT={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",actions:"dd-9Iqn9",thumbsUp:"dd-6QwVx",thumbsDown:"dd-d3E8l"};var tn=w(C()),KM=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o})=>{let i=L("WidgetCue",zT),s=Q(Ly),a=ms(),l=z("hasKeyboardInput"),u=()=>{t&&t(e),n(e)},c=h=>{r&&r(h,e)},f=h=>{o&&o(h,e)},d=h=>{h.preventDefault(),h.stopPropagation(),n(e)};return(0,BT.useEffect)(()=>{a("Assistant response displayed",{name:e.rule.name,description:e.rule.description,group:e.rule.label,cueText:e.text})},[]),(0,tn.jsxs)(oe,{"data-testid":"cue",children:[(0,tn.jsx)(ve,{children:(0,tn.jsxs)(ve.Content,{children:[e.title&&(0,tn.jsx)(ve.Title,{className:i.title,"data-testid":"widget-cue-title",children:e.title}),(0,tn.jsx)(UT,{content:e.text,useLabel:s("useCue"),copyLabel:s("copyCue"),onCopy:c,onUse:l?f:void 0})]})}),(0,tn.jsxs)(oe.ButtonsContainer,{children:[(0,tn.jsxs)("div",{className:i.actions,children:[e.callToAction&&(0,tn.jsx)(oe.Button,{onClick:u,children:e.callToAction.label}),(0,tn.jsx)(oe.Button,{onClick:d,children:s("removeCue")})]}),(0,tn.jsx)(hs,{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=KM;var Rl=w(C()),WM=({cues:e})=>{let t=X(),n=Qt(),r=ms(),o=l=>{t(nT({id:l.rule.id})),t(sb({code:l.rule.label})),r("Assistant response closed",{name:l.rule.name,group:l.rule.label,description:l.rule.description,cueText:l.text})},i=(l,u)=>{er(l),r("Assistant response copied",{name:u.rule.name,group:u.rule.label,description:u.rule.description,copiedText:l})},s=l=>{l.callToAction&&(t(Vd(l)),r("Assistant call to action",{name:l.rule.name,group:l.rule.label,description:l.rule.description,eventName:l.callToAction.event,value:l.callToAction.value}))},a=(l,u)=>{n.send(Qr,{text:l,suggestion:{source:"cue",sourceText:l}}),r("Assistant response used",{name:u.rule.name,group:u.rule.label,description:u.rule.description,usedText:l})};return(0,Rl.jsx)(Rl.Fragment,{children:e.map(l=>(0,Rl.jsx)(jT,{cue:l,onCallToAction:s,onRemove:o,onCopy:i,onUse:a},l.rule.id))})},VT=WM;var Pf=w(H());var KT={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var Sn=w(C());function $M(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var WT=({data:e,schema:t})=>{let n=L("WidgetCustomData",KT),r=o=>{er(o)};return(0,Pf.useEffect)(()=>{F.info("Custom data",e,t)},[e]),(0,Sn.jsx)("dl",{className:n.root,children:t.map(o=>{let i=$M(e,o.path);return(0,Sn.jsxs)(Pf.Fragment,{children:[(0,Sn.jsx)("dt",{className:n.label,children:o.label}),(0,Sn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&i?(0,Sn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!i?(0,Sn.jsx)("span",{className:n.isFalse,children:o.falseValue}):i?(0,Sn.jsxs)("button",{type:"button",onClick:()=>r(i),className:n.copyButton,children:[(0,Sn.jsx)("span",{className:n.copyButtonText,children:i}),(0,Sn.jsx)(El,{})]}):"-"})]},o.label)})})};var qT=w(H());var qM=/(https?:\/\/[^\s]+)/,$T=e=>e.split(" ").find(t=>qM.test(t));var nn=w(C()),GM=({suggestion:e,lines:t,onUse:n})=>{var f;let r=e.text||e.url||e.message,o=$T(r),i=Q(Ko),s=z("showImages"),a=z("fallbackImage"),l=z("hasKeyboardInput"),u=d=>{d.preventDefault(),d.stopPropagation(),l&&n(r)},c=(0,qT.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,nn.jsxs)(oe,{onClick:l?u:void 0,"data-testid":"edit-suggestion",children:[(0,nn.jsxs)(ve,{children:[s&&e.image&&(0,nn.jsx)(ve.Image,{src:hf(e,"small",a||void 0),title:e.title}),(0,nn.jsxs)(ve.Content,{children:[e.title&&(0,nn.jsx)(ve.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((f=e.searchKeywords)==null?void 0:f.length)>0&&(0,nn.jsx)(oe.Labels,{labels:e.searchKeywords}),(0,nn.jsx)(ve.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,nn.jsxs)(oe.Actions,{children:[o&&(0,nn.jsx)(oe.ActionButton,{onClick:c,label:i("visitUrl")}),l&&(0,nn.jsx)(oe.ActionButton,{primary:!0,onClick:u,label:i("useSuggestion")})]})]})},GT=GM;var Al=w(C()),QM=({lines:e,suggestions:t})=>{let n=Qt(),r=(o,i)=>{n.send(Qr,{text:o,suggestion:I(k({},i),{source:i.source,sourceText:i.text})})};return(0,Al.jsx)(Al.Fragment,{children:t.map(o=>(0,Al.jsx)(GT,{suggestion:o,lines:e,onUse:i=>r(i,o)},o.text||o.url||o.message))})},QT=QM;var Ll={};Ye(Ll,{enUS:()=>YM,nlNL:()=>XM});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"}]},XM={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"Mijn "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Gesprek samenvatten"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}]};var Il={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",sectionList:"dd-bF9pF",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",link:"dd-DRo0x"};var q=w(C()),Rf=(e,t)=>{let n=M(ut);(0,Cs.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},ZM=({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")},JM=()=>{let e=Q(Ll),t=X(),n=L("Widget",Il),r=z("showSearch"),o=z("showSummaryCommand"),i=z("showKnowledgeSearch"),s=z("isEmbedded"),a=M(gs("/admin/")),l=Qt(),u=z("productName"),c=z("hasKeyboardInput"),f=r||o||i||a;return Rf(()=>{if(s)return t(fy()),()=>{t(XC())}},[t,s]),!f||!c?null:(0,q.jsx)(En,{title:e("actions"),type:"shortcuts",children:(0,q.jsxs)("div",{className:n.shortcutList,children:[r&&(0,q.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-search","aria-label":e("linkSearch"),onClick:()=>l.send("ShowCommandPalette",{isOpen:!0}),children:[(0,q.jsx)(cs,{}),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")]}),i&&(0,q.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-knowledge-assist","aria-label":e("linkKnowledgeSearch"),onClick:()=>l.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,q.jsx)(wT,{}),e("linkKnowledgeSearch")]}),a&&(0,q.jsxs)("a",{className:n.shortcut,target:"_blank",href:a,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:u}),rel:"noreferrer",children:[(0,q.jsx)(ST,{}),e("linkStudioLogin",{productName:u})]})]})})},e_=()=>{let e=X(),t=z("showCustomMessages"),n=M(jC),r=M(rs);return Rf(()=>(e(xl(r)),e(qC(r)),()=>{e(GC(r))}),[e,t,r]),!t||n.length===0?null:(0,q.jsx)(En,{type:"custom-messages","data-testid":"custom-messages",children:(0,q.jsx)(xt,{withDivider:!0,children:n.map(o=>(0,q.jsx)(hT,{suggestion:o},o.text))})})},t_=()=>{let e=Q(Ll),t=X(),n=z("showAutoflows"),r=M(FC),o=M(rs);return Rf(()=>(t(pr(o)),t(HC(o)),()=>{t(UC(o))}),[t,n,o]),!n||r.length===0?null:(0,q.jsx)(En,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:(0,q.jsx)(xt,{withDivider:!0,children:(0,q.jsx)(mT,{})})})},n_=()=>{let e=X(),t=M(Wd),n=M(pb),r=M(oT),o=M(q1),i=M(jd),s=M($d),a=M(sr),l=M(qr);return(0,Cs.useEffect)(()=>{!!o&&!n&&F.warn("Custom data provided, but no schema.")},[o,n]),Rf(()=>{t.forEach(({type:u})=>{u==="entities"?e(gn()):su.includes(u)||e(hn(u))})},[e,l,a]),(0,Cs.useEffect)(()=>{r.length>0&&!t.some(u=>u.type==="cues")&&F.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,q.jsx)(Cs.Fragment,{children:t.map(({type:u,title:c,amount:f,lines:d,schema:h})=>{var v,y;switch(u){case"entities":return i&&i.length>0&&(0,q.jsx)(En,{type:u,title:c,"data-testid":`type-${u}`,children:(0,q.jsx)(vT,{entities:i})},u);case"cues":return r&&r.length>0&&(0,q.jsx)(En,{type:u,title:c,"data-testid":`type-${u}`,children:(0,q.jsx)(xt,{withDivider:!0,children:(0,q.jsx)(VT,{cues:r})})},u);case"custom-data":return o&&h&&(0,q.jsx)(En,{type:u,title:c,"data-testid":`type-${u}`,children:(0,q.jsx)(xt,{withDivider:!0,children:(0,q.jsx)(WT,{data:o,schema:h})})},u);default:return((y=(v=s[u])==null?void 0:v.suggestions)==null?void 0:y.length)>0&&(0,q.jsx)(En,{type:u,title:c,"data-testid":`type-${u}`,children:(0,q.jsx)(xt,{withDivider:!0,children:(0,q.jsx)(QT,{lines:d,contentType:u,suggestions:s[u].suggestions.slice(0,f)||[]})})},u)}})})},r_=({onLogIn:e})=>{let t=Q(Ll),n=L("Widget",Il),r=M(os),o=M(ut),i=M(rs),s=M(sr);return r===!1?(0,q.jsx)(YT,{text:t("notSupported")}):o===!1?(0,q.jsx)(ZM,{onLogIn:e}):!s||!i||o===null?(0,q.jsx)(YT,{text:t("waiting")}):(0,q.jsx)("div",{className:(0,XT.default)(n.root),"data-testid":"widget",children:(0,q.jsxs)(ru,{className:n.sectionList,children:[(0,q.jsx)(JM,{}),(0,q.jsx)(e_,{}),(0,q.jsx)(t_,{}),(0,q.jsx)(n_,{})]})})},ZT=r_;function Ts(e){let t=new Range;return t.selectNodeContents(e),t}function JT(e,t,n){try{return so(e,t,n),!0}catch(r){return!1}}function Af(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function Lf(e){return"tagName"in e&&e.tagName==="BR"}var Ol=/[\u200B-\u200D\uFEFF]/g;function so(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,i=!1;function s(l,u){let c=-1,f=/[\u200B-\u200D\uFEFF]/;if(!f.test(l))return u;for(let d=0;d<=l.length;d++)if(f.test(l[d])||c++,c===u)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let u=l.textContent,c=u.replace(Ol,""),f=o+c.length,d=t>=o&&t<=f,h=n>=o&&n<=f;if(d){let v=s(u,t-o);v===0&&!h?r.setStartBefore(l):r.setStart(l,v)}h&&(r.setEnd(l,s(u,n-o)),i=!0),o=f;break}case Node.ELEMENT_NODE:{if(Lf(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),i=!0;return}for(let c=0;c<l.childNodes.length&&(a(l.childNodes[c]),!i);c++);let u=l.lastChild;Af(l)&&u&&!Af(u)&&!Lf(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function Nl(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a,l,u=0;function c(f){let d=f===e,h=f===n,v=f===o;switch(f.nodeType){case Node.TEXT_NODE:{let y=f.textContent;h&&(a=u+y.substring(0,r).replace(Ol,"").length),v&&(l=u+y.substring(0,i).replace(Ol,"").length),u+=y.replace(Ol,"").length;break}case Node.ELEMENT_NODE:{if(Lf(f)&&f.nextSibling){u++;break}!d&&Af(f)&&f.previousSibling&&u++;for(let y=0;y<f.childNodes.length;y++){let p=h&&y===r,m=v&&y===i;if(p&&(a=u),m&&(l=u),l!==void 0||((!p||!s)&&c(f.childNodes[y]),v&&y===i-1&&(l=u),l!==void 0))break}v&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:l,end:l}}function Ml(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a=0,l="";function u(c){let f=c===e,d=c===n,h=c===o;switch(d&&(a=1),c.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let v=d?r:0,y=h?i:void 0;l+=c.textContent.replace(Ol,"").substring(v,y);break}case Node.ELEMENT_NODE:{if(!s&&a===1&&Lf(c)&&c.nextSibling){l+=`
26
26
  `;break}!f&&!s&&a===1&&Af(c)&&c.previousSibling&&(l+=`
27
- `);let v=d?r:0,y=h?Math.min(i,c.childNodes.length):c.childNodes.length;for(let p=v;p<y&&(u(c.childNodes[p]),a!==2);p++);break}default:break}h&&(a=2)}return u(e),l}var ek=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(ek||{}),hr=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let i=this.getCaretPosition();$r(i,this.cachedCaretPosition)||(this.cachedCaretPosition=i,this.emit("caretposition",i))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(ek).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function tk(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Zo=class extends hr{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Ml(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var s;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?(s=r.getComposedRanges(n))==null?void 0:s[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!tk(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!tk(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return Nl(this.element,n);let r=this.lastKnownSelection;if(r&&JT(this.element,r.start,r.end))return r;let o=Ts(this.element);return o.collapse(!1),Nl(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Ml(this.element,so(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(i=>{var s,a;i.length===2&&i[0].addedNodes.length===1&&((s=i[0].addedNodes[0])==null?void 0:s.textContent)==="\u2060"&&((a=i[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 Jo=class extends hr{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return null}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var i;return(i=n==null?void 0:n.get)==null?void 0:i.call(this.element)},set:i=>{var s;(s=n==null?void 0:n.set)==null||s.call(this.element,i),this.handleInteraction()}});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 i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function o_(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var Iy=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Oy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=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(),F.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Oy(t,this.deepdeskUrl,{debug:!0}):new Iy(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=o_(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(F.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;F.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage(I(k({},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 i_(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function se(e){return Array.isArray(e)?e.map(se):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(k({},t),{[i_(n)]:se(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(k({},t),{[My(n)]:Le(e[n])}),{}):e}var ks=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var _y=e=>new Promise(t=>{setTimeout(t,e)});var Ps=class extends ks{constructor(){super(...arguments);this.name="ClientError"}},Fy=class extends ks{constructor(){super(...arguments);this.name="ServerError"}},Dy=new Map;function s_(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:(F.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 i={isAborted:!1,reject:o},s=`${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:h=!0,retryOnError:v=R=>R instanceof TypeError,retryOnResponse:y=R=>R.status>=500,version:p=null}=b,m=ne(b,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(Dy.has(s)){r(Dy.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let g=I(k({credentials:"include"},m),{headers:k({Accept:"application/json","Content-Type":"application/json"},m.headers)});!l&&this.csrfToken&&(g.headers=I(k({},g.headers),{"X-CSRFToken":this.csrfToken})),typeof p=="string"&&(g.headers=I(k({},g.headers),{"X-Deepdesk-API-Version":p}));let S=f,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&c&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let T=()=>P(this,null,function*(){return S--,a(s,g).then(R=>P(this,null,function*(){return y(R)&&!i.isAborted&&S>0?(yield _y(d),T()):R.status===401&&h===!0&&x===!1?(x=!0,yield this.refreshToken(),T()):R})).catch(R=>P(this,null,function*(){if(v(R)&&!i.isAborted&&S>0)return yield _y(d),T();throw R}))});T().then(R=>P(this,null,function*(){let N=yield s_(R);if(delete this.latestRequestByUrl[s],R.status>=500){o(new Fy("Server Error",N));return}else if(R.status===401){o(new Ps("Unauthorized",N));return}else if(R.status===403){o(new Ps("Forbidden",N));return}else if(R.status===404){o(new Ps("Not Found",N));return}else if(R.status>=400){o(new Ps("Bad Request",N));return}u&&Dy.set(s,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,k({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,k({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,k({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,k({method:"DELETE"},n))}};ao.refreshingToken=null;var yr=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 If(e){return I(k({},se(e)),{tags:e.tags})}var ei=class ei{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new yr(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>P(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}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?(ei.exchangeTokenPromise||(ei.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),ei.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return P(this,null,function*(){yield this.preflight(),F.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",I(k({},Le(t)),{tags:t.tags}),{version:"v2"});return If(n)})}getMe(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return se(t)})}postIdentity(t){return P(this,null,function*(){yield this.client.post("/apis/admin/session/me/identity",Le(t))})}patchMe(t){return P(this,null,function*(){let n=yield this.client.patch("/apis/admin/session/me/",Le(t));return se(n)})}getProfile(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return se(n)})}getKnowledgeAssistant(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return se(n)})}getContentTypes(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return se(t)})}getAccount(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return se(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 se(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(),F.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return F.info(`Successfully retrieved conversation ${s.id} for session ${t}`),If(s)})}isConversationSupported(r){return P(this,arguments,function*(t,n={}){F.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return P(this,null,function*(){let r=Le(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return If(o)})}postMessages(t,n){return P(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>I(k({},Le(o)),{tags:o.tags})),{version:"v2"})).map(o=>If(o))})}sendEvent(t,n){return P(this,null,function*(){let s=n,{data:r}=s,o=ne(s,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>I(k({},a),{[l]:u}),{});return this.client.post("/api/events",Le(I(k(k({},i),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return P(this,null,function*(){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>I(k({},o),{[i]:s}),{});return this.client.post("/api/events",{event:t,data:Le(k(k({},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 F.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(s=>I(k({},se(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,l)=>a===l.findIndex(u=>u.text===s.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,i,s)=>i===s.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 se(n).map(r=>I(k({},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 se(n)})}search(t){return P(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,Le(t),{version:"v2"});return se(n)})}knowledgeAssist(i,s,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 se(l)})}requestLoginByEmail(t){return P(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return se(n)})}requestPasswordlessToken(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return se(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 se(n)})}evaluateRule(i,s,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?se(u.cues):[]})}getSummary(r){return P(this,arguments,function*(t,n={}){let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(i=>i.text&&i.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return se(o)})}evaluateAssistant(t,n){return P(this,null,function*(){var i;let r=new URLSearchParams;r.append("enforce_cues_schema","true"),n.conversationId&&r.append("conversation_id",n.conversationId);let o=yield this.client.post(`/api/v2/assistants/${t}/evaluate?${r.toString()}`,{input:(i=n.input)!=null?i:{},conversation:n.transcript});return se(o.output)})}getRules(){return P(this,null,function*(){let t=new URLSearchParams,n=yield this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{useCache:!0});return se(n)})}translateMessages(t){return P(this,null,function*(){let n=yield this.client.post("/api/translate",Le(t),{version:"v2"});return se(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(r0);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&F.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};ei.exchangeTokenPromise=null;var vr=ei;var _l=class{constructor(t,n){this.url=t;this.eventListeners={};this.options=k({timeout:25e3},n)}proxyEvent(t){this.eventSource.addEventListener(My(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,se(o))}catch(o){F.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var ik;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||(t.AutoflowSessionState={}))})(ik||(ik={}));var Dl=class{constructor(t,n={}){this.apiUrl=t;this.streams={};this.logger=F;this.client=new yr(t,n)}getCustomMessages(t){return P(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/suggestions`);return se(n.suggestions)})}sendCustomMessage(t,n){return P(this,null,function*(){let r=yield this.client.post(`/sessions/${t}/messages`,Le(n));return se(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 se(n.autoflows)})}startAutoflowSession(t){return P(this,null,function*(){let n=yield this.client.post("/autoflow-sessions",Le(t));return se(n)})}stopAutoflowSession(t){return P(this,null,function*(){yield this.client.delete(`/autoflow-sessions/${t}`)})}openStream(t){return this.streams[t]||(this.streams[t]=new _l(`${this.apiUrl}/sessions/${t}/events`),this.streams[t].connect()),this.streams[t]}closeStream(t){this.streams[t]||(this.streams[t].disconnect(),delete this.streams[t])}};var sk={startTime:null,stopTime:null},ak=ee({name:"handlingTime",initialState:sk,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(fe,()=>sk)}}),{handlingTimeStart:lk,handlingTimeStop:Of,handlingTimeReset:uk}=ak.actions,ck=ak.reducer;var dk=(e={})=>{let t=k({onAuthError:ns(!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 ti=j("styleSuggestions/getAll",(n,r)=>P(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(l=i.conversation.current)==null?void 0:l.profileCode;if(!s)return Nf.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),a_=ee({name:"styleSuggestions",initialState:Nf,reducers:{},extraReducers:e=>{e.addCase(ti.pending,t=>{t.fetchState="loading"}).addCase(ti.rejected,t=>{t.fetchState="error"}).addCase(ti.fulfilled,(t,n)=>{t.fetchState="done",$r(t.list,n.payload)||(t.list=n.payload)}).addCase(Oo,t=>{t.list=Nf.list}).addCase(fe,()=>Nf)}}),fk=a_.reducer;var pk=(e={})=>{let t,n=!0,r=k({getStyleSuggestions:ti,debounce:500},e);return o=>i=>s=>{var h;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((h=u.conversation.current)==null?void 0:h.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function 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=k({getTextSuggestions:hn,getAutocompleteSuggestions:gl,debounce:200,check:On},e),n;return r=>o=>i=>{var y;let{input:s}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,f=(y=l.conversation.current)==null?void 0:y.id,d=i.type===qd.toString();if(!f||!u&&!c)return a;let{input:h}=l;return l_(h,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let p=is(l);p===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(p))},d?0:t.debounce)),a}};var gk=ti.fulfilled.toString();function u_(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var hk=e=>t=>n=>r=>{var u;if(r.type!==gk){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=u_(o,s);r.type===gk&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var c_=kc({assistants:ab,answer:xb,auth:b1,autoflows:zC,conversation:N1,contentTypes:LE,customMessages:QC,passwordlessToken:ZC,entities:tb,knowledgeAssistant:vb,handlingTime:ck,info:Z1,input:W1,settings:h1,profile:mb,search:iE,styleSuggestions:fk,ui:Zb,rules:rT,textSuggestions:Ib});function yk(e){return Ex({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,h;let o=t.getState(),i=Zg("inlineSuggestions")(o);switch(r.type){case ns.toString():{!r.payload&&e.emit("logout",void 0);break}case gn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case ct.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Oo.toString():e.logSendMessage(r.payload);break;case Qo.fulfilled.toString():r.isBroadcasted||e.broadcast(sh,r,!1),(c=r.payload.options)!=null&&c.shouldEmit&&e.emit("cues",r.payload.cues);break;case Vd.toString():e.emit("call-to-action",{cue:r.payload});break;case Jr.fulfilled.toString():r.isBroadcasted||e.broadcast(ah,r,!1);break;default:break}let s=n(r);switch(r.type){case Oo.toString():e.handleAfterSendMessage(r.payload);break;case yl.toString():e.onUpdateShowTabHint(r.payload);break;case Of.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case ad.toString():{let{start:v,end:y}=o.input.selection;e.emit("replace",I(k({},r.payload),{replace:r.payload.replace==="selection"?{start:v,end:y}:{start:0,end:y}}));break}case un.toString():{let{start:v,end:y}=o.input.selection;e.emit("select-suggestion",I(k({type:d_(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:v,end:y}:{start:0,end:y}})),i&&t.dispatch(Gr([]));break}case ld.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Gr.toString():{i&&r.payload.length>0&&t.dispatch(ud(0));break}case fs.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(d=o.conversation.current)==null?void 0:d.id,data:{summary:r.payload,assistant:(h=t.getState().profile.data)==null?void 0:h.summarizerAssistantNew}});break}default:break}return s},vk=f_;function Hy(e){return e.toISOString().replace("T"," ").replace("Z","")}function Sk(e,t){var i,s,a,l;let n=(i=e.conversation.current)==null?void 0:i.id;if(!n)return F.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:o}=e.handlingTime;return!r||!o?(F.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:n,clientVersion:t.version,agentId:(s=e.info.agentInfo)==null?void 0:s.agentId,agentName:(a=e.info.agentInfo)==null?void 0:a.agentName,agentEmail:(l=e.info.agentInfo)==null?void 0:l.agentEmail,timeStart:Hy(r),timeStop:Hy(o)}}function wk(e,t,n){var N,_,Y,V;let r=(N=t.conversation.current)==null?void 0:N.id;if(!r)return F.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:i,numCharsPasted:s,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:f,pastes:d,cuts:h,deletions:v,textSuggestions:y,offeredTextSuggestions:p}}=t[e],m=o.length,S=y.reduce((W,{text:me,searchTerm:qe})=>W+me.length-(qe?qe.length:0),0),x=c!=null?c:Date.now(),T=(Date.now()-x)/1e3+(f||0),b=i/T,R=y.reduce((W,{searchTerm:me})=>W+(me?me.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:h,deletions:v,lenTextTyped:i+R,lenTextTotal:m,lenTextAssisted:S,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:T,charsPerSecond:b,numPastes:u,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:p.filter(W=>W.source==="gpt").length}],agentId:(_=t.info.agentInfo)==null?void 0:_.agentId,agentName:(Y=t.info.agentInfo)==null?void 0:Y.agentName,agentEmail:(V=t.info.agentInfo)==null?void 0:V.agentEmail}}function Uy(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Uy(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Uy(o,t):null}function xk(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)&&(ro(e)||of(e))}var Ck,_n=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(k({},e),{top:e.top+t.top,left:e.left+t.left})}var _f=!1,Pk=()=>{_f=!0;let e=[];if(_n.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),_n.delete(n);return}let r=n.getBoundingClientRect();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}),_n.size===0){_f=!1;return}Ck=window.requestAnimationFrame(Pk)};function zy(e,t){let n=Tk(e),r=[],o=n.map((i,s)=>zy(i,a=>{r[s]=a;let l=_n.get(e);if(!l)return;let u=r.reduce(kk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),_n.has(e)){let s=_n.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else _n.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!_f&&Pk()},unobserve(){o.forEach(s=>s.unobserve());let i=_n.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||_n.delete(e),_n.size||(cancelAnimationFrame(Ck),_f=!1)}}}}var Rk,Dn=new Map,Ak=()=>{Dn.forEach((e,t)=>{if(!t.isConnected){Dn.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),Dn.size!==0&&(Rk=window.requestAnimationFrame(Ak))};function Lk(e,t){return{observe(){let n=Dn.size===0;Dn.has(e)?Dn.get(e).callbacks.push(t):Dn.set(e,{visible:void 0,callbacks:[t]}),n&&Ak()},unobserve(){let n=Dn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Dn.delete(e),Dn.size||cancelAnimationFrame(Rk)}}}}var By=["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 jy(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Rs(e){return parseFloat(e)}function Df(e){return Math.round(e*1e6)}function Ik(e){return e/1e6}function Vy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Rs(e.width),i=Rs(e.borderLeftWidth),s=Rs(e.borderRightWidth),a=Rs(e.paddingRight),l=Ik(Df(o)-Df(i)-Df(s)),u=Ik(Df(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function Fl(e,t={}){var c,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",$o(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};jy(r,n,By),Vy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=Lk(e,()=>{jy(r,n,By),Vy(r,e,n),i(),setTimeout(i,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(jy(r,n,By),Vy(r,e,n),i(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let h=t.closestScrollElement.getBoundingClientRect(),v=window.getComputedStyle(t.closestScrollElement),y=Rs(v.borderTopWidth),p=Rs(v.borderBottomWidth),m=h.top+y-d.top,g=d.top+d.height+-(h.top+h.height-p);n.style.clipPath=`inset(${m}px 0px ${g}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(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.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){F.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 i=Nk(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var De=w(C());var Mk=Ok("showTabHint",!0),As=class As{constructor({deepdeskUrl:t,brokerUrl:n,version:r=As.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let u=t.replace(/\/api$/,"");this.deepdeskApi=new vr(u,{token:i,fetch:s}),this.version=r,this.instanceId=As.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[vk({broadcast:(f,d,h)=>{this.broadcastEvents.send(f,d,h)},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 Dl(n)}),this.store=yk(c),this.broadcastEvents=new rk({debug:!0,deepdeskUrl:u,eventMap:sE(this.store),createCustomChannel:l}),this.store.dispatch(yl(Mk.value())),this.store.dispatch(td({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(F.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(F.warn("Profile has not been loaded (yet)"),!0):(F.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(ns(null)),this.store.dispatch(Zn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();ut(r)&&y1(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return P(this,null,function*(){return(yield this.store.dispatch(Zn())).payload})}isConversationSupported(t,n){return P(this,null,function*(){return(yield this.store.dispatch(th({sessionId:t,options:n}))).payload})}createConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(rd(t))).payload})}getConversationBySessionId(t,n){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(od({sessionId:t,options:n}))).payload})}upsertConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(nh(t))).payload})}postMessages(t){return P(this,null,function*(){return(yield this.store.dispatch(sd(t))).payload})}updateConversation(t){return P(this,null,function*(){return(yield this.store.dispatch(id(t))).payload})}resetConversation(){this.store.dispatch(fe()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(td(t))}setVisitorInfo(t){this.store.dispatch(Q1(t))}setCustomData(t){this.store.dispatch(Y1(t))}setAgentInfo(t){return P(this,null,function*(){yield this.store.dispatch(Wa(t))})}setAgentSettings(t){return P(this,null,function*(){yield this.store.dispatch(oh(t))})}getAgentSettings(){return P(this,null,function*(){return(yield this.store.dispatch(ih())).payload})}refresh(){return P(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(cd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(qd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(un(t))}evaluateRule(o){return P(this,arguments,function*(t,n={},r=JC){return(yield this.store.dispatch(Qo({label:t,params:n,options:r}))).payload.cues})}evaluateAssistant(r){return P(this,arguments,function*(t,n={}){let c=n,{input:o={},transcript:i,showCuesInWidget:s=!0,includeTags:a}=c,l=ne(c,["input","transcript","showCuesInWidget","includeTags"]);Object.assign(o,l);let u=yield this.store.dispatch(Jr({assistantCode:t,transcript:i,includeTags:a,input:o,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){F.warn(`No assistant set in profile for conversation event "${t}"`);return}yield this.evaluateAssistant(o,k({transcript:"stored-transcript",includeTags:!0},n))})}getSummary(){return P(this,null,function*(){var n;if(!this.hasConversation())return F.warn("No conversation to create summary for."),null;(n=this.state.profile.data)!=null&&n.summarizerAssistantNew||F.warn("No profile loaded yet, or no summarizer assistant set in profile");let t=yield this.store.dispatch(fs({}));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:i,selection:s}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.state.settings,u=a?"below":"above",c=o.length>0;if(!On(this.state)||(this.store.dispatch(H1(rh(t))),t.key!=="Tab"&&!l))return;let f=()=>{n||!c||s&&(t.shiftKey||(this.store.dispatch(B1()),t.preventDefault()))},d=()=>{n||!c||a&&i<=0||s&&(t.shiftKey||(this.store.dispatch(j1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():f();break;case"ArrowDown":{u==="below"?f():d();break}case"Escape":{n||(this.store.dispatch(ud(-1)),this.store.dispatch(to({collapse:!0})),this.store.dispatch(Yb(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let h=ss(this.state);if(!h)return;this.store.dispatch(yl(!1)),this.store.dispatch(un({text:h.text,suggestion:h,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.state.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let h=ss(this.state);if(!h)return;this.store.dispatch(un({text:h.text,suggestion:h,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.state.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let h=ss(this.state);if(!h)return;this.store.dispatch(un({text:h.text,suggestion:h,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(to({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Gr([]))}handlingTimeStart(){this.state.handlingTime.startTime||(F.info("Start handling time"),this.store.dispatch(lk()))}handlingTimeStop(){this.state.handlingTime.startTime&&(F.info("Stop handling time"),this.store.dispatch(Of()))}logSendMessage(t){let n=wk("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(Oo((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(i){F.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),F.error(i)}})}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[i,s]=Fl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,rn.unmountComponentAtNode)(i),s(),i.remove()}),i}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 i=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,s=i?i.ownerDocument.defaultView:null;if(i&&(s===window||(s==null?void 0:s.parent)===window)){let[l,u]=Fl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{(0,rn.unmountComponentAtNode)(o),u()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return $o(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,rn.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),F.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()?(F.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(V1(r.metrics))):F.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:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:f,detectSubmit:d,insertLink:h,inputMediator:v,closestScrollSelector:y,appendOverlayTo:p,inlineSuggestions:m,floatingMenu:g}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:h,isEmbedded:f,inlineSuggestions:m,floatingMenu:!!g}),n.automaticHandlingTime&&this.setupHandlingTime(t),$o(t),this.inputMediator=v||(ro(t)?new Jo(t):new Zo(t)),this.inputMediator.on("change",({plainText:T,rawHTML:b})=>{this.store.dispatch(cd({text:T,html:b}))}),this.inputMediator.on("keyup",T=>{this.store.dispatch(U1(rh(T)))}),this.inputMediator.on("keydown",T=>{this.handleKeyDown(T)}),this.inputMediator.on("paste",({pastedText:T,selectionText:b})=>{this.store.dispatch(z1({text:T,selectionText:b}))}),this.inputMediator.on("cut",({selectionText:T})=>{this.store.dispatch(F1(T))});let S;this.inputMediator.on("selection",T=>{clearTimeout(S),T===null?S=setTimeout(()=>{T!==null&&this.store.dispatch(dd(T))},500):this.store.dispatch(dd(T))}),this.inputMediator.on("disabled",()=>{var T;(T=this.inputMediator)==null||T.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(Zd(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Zd(!0))});let x=y&&xk(t,y)||void 0;if(m){let{customStyles:T,appendOverlayTo:b}=n;if(ro(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let R=this.createInlineContainer(t,"deepdesk-caret");(0,rn.render)((0,De.jsx)(Go,{store:this.store,customStyles:T,children:(0,De.jsx)(Mo,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(oC,{})})}),R),this.inputMediator.on("caretposition",_=>{_?(R.style.display="block",R.style.top=`${_.top}px`,R.style.left=`${_.left}px`):R.style.display="none"});let N=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof g=="object"&&"appendOverlayTo"in g?g.appendOverlayTo:b},T==null?void 0:T.floatingMenuRootNode);(0,rn.render)((0,De.jsx)(Go,{store:this.store,customStyles:T,children:(0,De.jsx)(Mo,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(qb,{onLogIn:()=>this.loginViaPopup().catch(_=>F.warn(_.message))})})}),N)}else{let T=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:p,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),b=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:p},r==null?void 0:r.suggestionsRootNode);(0,rn.render)((0,De.jsx)(Go,{store:this.store,customStyles:r,children:(0,De.jsx)(Mo,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(MC,{inputElement:t})})}),T),(0,rn.render)((0,De.jsx)(Go,{store:this.store,customStyles:r,children:(0,De.jsx)(Mo,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(pC,{onLogIn:()=>this.loginViaPopup().catch(R=>F.warn(R.message))})})}),b)}(0,rn.render)((0,De.jsx)(Go,{store:this.store,customStyles:r,children:(0,De.jsx)(Mo,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(jb,{})})}),this.createContainer("deepdesk-overlays")),this.store.dispatch(cd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(dd(this.inputMediator.getSelection())),this.store.dispatch(Zd(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var T;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((T=this.state.conversation.current)==null?void 0:T.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&F.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,rn.render)((0,De.jsx)(Go,{store:this.store,customStyles:r,children:(0,De.jsx)(Mo,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(ZT,{onLogIn:()=>this.loginViaPopup().catch(s=>F.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,rn.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Ff(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){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(cl());let t=sr(this.state);t&&(yield this.store.dispatch(fl()),this.store.dispatch(td({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew||t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))})),this.loadProfileConfigPromise)}loginViaPopup(t){return P(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=h=>P(this,null,function*(){var v,y;if((v=h.data)!=null&&v.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((y=h.data)==null?void 0:y.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(qa),l=!0,o.port1.close(),n()}catch(p){console.error(p),r(p)}finally{l=!0,u()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let f=h=>P(this,null,function*(){var v;if(h.origin===a.origin)switch((v=h.data)==null?void 0:v.type){case"deepdesk-popup-loaded":{try{let y=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(y,a.origin,[o.port2])}catch(y){F.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-error":{u(),h.data.message==="Timeout"&&F.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(h.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(F.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;F.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return P(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Wd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(gn()):su.includes(r)||this.store.dispatch(hn(r))})}catch(r){this.handleError(r)}})}};As.version="14.2.1-beta.0",As.count=0;var Hl=As;function h_(e){return P(this,null,function*(){var o,i,s;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(s=(i=e.mimeType)!=null?i:n.headers.get("Content-Type"))!=null?s:"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 vr(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:i}=e,{start:s,end:a}=(f=n.replace)!=null?f:{start:0,end:i.length},l=`${i.slice(0,s)}${t}${i.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+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 i=n.replace?so(e,n.replace.start,n.replace.end):Ts(e),s,a=()=>{if(n.setRange)return n.setRange(i.cloneRange());i.deleteContents(),s=document.createElement("span"),i.insertNode(s),n.insertBRs!==!1?t.split(`
27
+ `);let v=d?r:0,y=h?Math.min(i,c.childNodes.length):c.childNodes.length;for(let p=v;p<y&&(u(c.childNodes[p]),a!==2);p++);break}default:break}h&&(a=2)}return u(e),l}var ek=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(ek||{}),hr=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let i=this.getCaretPosition();$r(i,this.cachedCaretPosition)||(this.cachedCaretPosition=i,this.emit("caretposition",i))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(ek).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function tk(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Zo=class extends hr{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Ml(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var s;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?(s=r.getComposedRanges(n))==null?void 0:s[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!tk(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!tk(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return Nl(this.element,n);let r=this.lastKnownSelection;if(r&&JT(this.element,r.start,r.end))return r;let o=Ts(this.element);return o.collapse(!1),Nl(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Ml(this.element,so(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(i=>{var s,a;i.length===2&&i[0].addedNodes.length===1&&((s=i[0].addedNodes[0])==null?void 0:s.textContent)==="\u2060"&&((a=i[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 Jo=class extends hr{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return null}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var i;return(i=n==null?void 0:n.get)==null?void 0:i.call(this.element)},set:i=>{var s;(s=n==null?void 0:n.set)==null||s.call(this.element,i),this.handleInteraction()}});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 i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function o_(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var Iy=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Oy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=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(),F.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Oy(t,this.deepdeskUrl,{debug:!0}):new Iy(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=o_(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(F.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;F.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage(I(k({},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 i_(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function se(e){return Array.isArray(e)?e.map(se):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(k({},t),{[i_(n)]:se(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(k({},t),{[My(n)]:Le(e[n])}),{}):e}var ks=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var _y=e=>new Promise(t=>{setTimeout(t,e)});var Ps=class extends ks{constructor(){super(...arguments);this.name="ClientError"}},Fy=class extends ks{constructor(){super(...arguments);this.name="ServerError"}},Dy=new Map;function s_(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:(F.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 i={isAborted:!1,reject:o},s=`${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:h=!0,retryOnError:v=R=>R instanceof TypeError,retryOnResponse:y=R=>R.status>=500,version:p=null}=b,m=ne(b,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(Dy.has(s)){r(Dy.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let g=I(k({credentials:"include"},m),{headers:k({Accept:"application/json","Content-Type":"application/json"},m.headers)});!l&&this.csrfToken&&(g.headers=I(k({},g.headers),{"X-CSRFToken":this.csrfToken})),typeof p=="string"&&(g.headers=I(k({},g.headers),{"X-Deepdesk-API-Version":p}));let S=f,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&c&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let T=()=>P(this,null,function*(){return S--,a(s,g).then(R=>P(this,null,function*(){return y(R)&&!i.isAborted&&S>0?(yield _y(d),T()):R.status===401&&h===!0&&x===!1?(x=!0,yield this.refreshToken(),T()):R})).catch(R=>P(this,null,function*(){if(v(R)&&!i.isAborted&&S>0)return yield _y(d),T();throw R}))});T().then(R=>P(this,null,function*(){let N=yield s_(R);if(delete this.latestRequestByUrl[s],R.status>=500){o(new Fy("Server Error",N));return}else if(R.status===401){o(new Ps("Unauthorized",N));return}else if(R.status===403){o(new Ps("Forbidden",N));return}else if(R.status===404){o(new Ps("Not Found",N));return}else if(R.status>=400){o(new Ps("Bad Request",N));return}u&&Dy.set(s,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,k({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,k({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,k({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,k({method:"DELETE"},n))}};ao.refreshingToken=null;var yr=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 If(e){return I(k({},se(e)),{tags:e.tags})}var ei=class ei{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new yr(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>P(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}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?(ei.exchangeTokenPromise||(ei.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),ei.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return P(this,null,function*(){yield this.preflight(),F.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",I(k({},Le(t)),{tags:t.tags}),{version:"v2"});return If(n)})}getMe(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return se(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 se(n)})}getProfile(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return se(n)})}getKnowledgeAssistant(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return se(n)})}getContentTypes(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return se(t)})}getAccount(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return se(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 se(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(),F.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return F.info(`Successfully retrieved conversation ${s.id} for session ${t}`),If(s)})}isConversationSupported(r){return P(this,arguments,function*(t,n={}){F.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return P(this,null,function*(){let r=Le(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return If(o)})}postMessages(t,n){return P(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>I(k({},Le(o)),{tags:o.tags})),{version:"v2"})).map(o=>If(o))})}sendEvent(t,n){return P(this,null,function*(){let s=n,{data:r}=s,o=ne(s,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>I(k({},a),{[l]:u}),{});return this.client.post("/api/events",Le(I(k(k({},i),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return P(this,null,function*(){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>I(k({},o),{[i]:s}),{});return this.client.post("/api/events",{event:t,data:Le(k(k({},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 F.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(s=>I(k({},se(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,l)=>a===l.findIndex(u=>u.text===s.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,i,s)=>i===s.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 se(n).map(r=>I(k({},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 se(n)})}search(t){return P(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,Le(t),{version:"v2"});return se(n)})}knowledgeAssist(i,s,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 se(l)})}requestLoginByEmail(t){return P(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return se(n)})}requestPasswordlessToken(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return se(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 se(n)})}evaluateRule(i,s,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?se(u.cues):[]})}getSummary(r){return P(this,arguments,function*(t,n={}){let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(i=>i.text&&i.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return se(o)})}evaluateAssistant(t,n){return P(this,null,function*(){var i;let r=new URLSearchParams;r.append("enforce_cues_schema","true"),n.conversationId&&r.append("conversation_id",n.conversationId);let o=yield this.client.post(`/api/v2/assistants/${t}/evaluate?${r.toString()}`,{input:(i=n.input)!=null?i:{},conversation:n.transcript});return se(o.output)})}getRules(){return P(this,null,function*(){let t=new URLSearchParams,n=yield this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{useCache:!0});return se(n)})}translateMessages(t){return P(this,null,function*(){let n=yield this.client.post("/api/translate",Le(t),{version:"v2"});return se(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(r0);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&F.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};ei.exchangeTokenPromise=null;var vr=ei;var _l=class{constructor(t,n){this.url=t;this.eventListeners={};this.options=k({timeout:25e3},n)}proxyEvent(t){this.eventSource.addEventListener(My(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,se(o))}catch(o){F.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var ik;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||(t.AutoflowSessionState={}))})(ik||(ik={}));var Dl=class{constructor(t,n={}){this.apiUrl=t;this.streams={};this.logger=F;this.client=new yr(t,n)}getCustomMessages(t){return P(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/suggestions`);return se(n.suggestions)})}sendCustomMessage(t,n){return P(this,null,function*(){let r=yield this.client.post(`/sessions/${t}/messages`,Le(n));return se(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 se(n.autoflows)})}startAutoflowSession(t){return P(this,null,function*(){let n=yield this.client.post("/autoflow-sessions",Le(t));return se(n)})}stopAutoflowSession(t){return P(this,null,function*(){yield this.client.delete(`/autoflow-sessions/${t}`)})}openStream(t){return this.streams[t]||(this.streams[t]=new _l(`${this.apiUrl}/sessions/${t}/events`),this.streams[t].connect()),this.streams[t]}closeStream(t){this.streams[t]||(this.streams[t].disconnect(),delete this.streams[t])}};var sk={startTime:null,stopTime:null},ak=ee({name:"handlingTime",initialState:sk,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(fe,()=>sk)}}),{handlingTimeStart:lk,handlingTimeStop:Of,handlingTimeReset:uk}=ak.actions,ck=ak.reducer;var dk=(e={})=>{let t=k({onAuthError:ns(!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 ti=j("styleSuggestions/getAll",(n,r)=>P(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(l=i.conversation.current)==null?void 0:l.profileCode;if(!s)return Nf.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),a_=ee({name:"styleSuggestions",initialState:Nf,reducers:{},extraReducers:e=>{e.addCase(ti.pending,t=>{t.fetchState="loading"}).addCase(ti.rejected,t=>{t.fetchState="error"}).addCase(ti.fulfilled,(t,n)=>{t.fetchState="done",$r(t.list,n.payload)||(t.list=n.payload)}).addCase(Oo,t=>{t.list=Nf.list}).addCase(fe,()=>Nf)}}),fk=a_.reducer;var pk=(e={})=>{let t,n=!0,r=k({getStyleSuggestions:ti,debounce:500},e);return o=>i=>s=>{var h;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((h=u.conversation.current)==null?void 0:h.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function 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=k({getTextSuggestions:hn,getAutocompleteSuggestions:gl,debounce:200,check:On},e),n;return r=>o=>i=>{var y;let{input:s}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,f=(y=l.conversation.current)==null?void 0:y.id,d=i.type===qd.toString();if(!f||!u&&!c)return a;let{input:h}=l;return l_(h,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let p=is(l);p===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(p))},d?0:t.debounce)),a}};var gk=ti.fulfilled.toString();function u_(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var hk=e=>t=>n=>r=>{var u;if(r.type!==gk){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=u_(o,s);r.type===gk&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var c_=kc({assistants:ab,answer:xb,auth:b1,autoflows:zC,conversation:N1,contentTypes:LE,customMessages:QC,passwordlessToken:ZC,entities:tb,knowledgeAssistant:vb,handlingTime:ck,info:Z1,input:W1,settings:h1,profile:mb,search:iE,styleSuggestions:fk,ui:Zb,rules:rT,textSuggestions:Ib});function yk(e){return Ex({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,h;let o=t.getState(),i=Zg("inlineSuggestions")(o);switch(r.type){case ns.toString():{!r.payload&&e.emit("logout",void 0);break}case gn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case ct.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Oo.toString():e.logSendMessage(r.payload);break;case Qo.fulfilled.toString():r.isBroadcasted||e.broadcast(sh,r,!1),(c=r.payload.options)!=null&&c.shouldEmit&&e.emit("cues",r.payload.cues);break;case Vd.toString():e.emit("call-to-action",{cue:r.payload});break;case Jr.fulfilled.toString():r.isBroadcasted||e.broadcast(ah,r,!1);break;default:break}let s=n(r);switch(r.type){case Oo.toString():e.handleAfterSendMessage(r.payload);break;case yl.toString():e.onUpdateShowTabHint(r.payload);break;case Of.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case ad.toString():{let{start:v,end:y}=o.input.selection;e.emit("replace",I(k({},r.payload),{replace:r.payload.replace==="selection"?{start:v,end:y}:{start:0,end:y}}));break}case un.toString():{let{start:v,end:y}=o.input.selection;e.emit("select-suggestion",I(k({type:d_(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:v,end:y}:{start:0,end:y}})),i&&t.dispatch(Gr([]));break}case ld.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Gr.toString():{i&&r.payload.length>0&&t.dispatch(ud(0));break}case fs.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(d=o.conversation.current)==null?void 0:d.id,data:{summary:r.payload,assistant:(h=t.getState().profile.data)==null?void 0:h.summarizerAssistantNew}});break}default:break}return s},vk=f_;function Hy(e){return e.toISOString().replace("T"," ").replace("Z","")}function Sk(e,t){var i,s,a,l;let n=(i=e.conversation.current)==null?void 0:i.id;if(!n)return F.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:o}=e.handlingTime;return!r||!o?(F.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:n,clientVersion:t.version,agentId:(s=e.info.agentInfo)==null?void 0:s.agentId,agentName:(a=e.info.agentInfo)==null?void 0:a.agentName,agentEmail:(l=e.info.agentInfo)==null?void 0:l.agentEmail,timeStart:Hy(r),timeStop:Hy(o)}}function wk(e,t,n){var N,_,Y,V;let r=(N=t.conversation.current)==null?void 0:N.id;if(!r)return F.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:i,numCharsPasted:s,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:f,pastes:d,cuts:h,deletions:v,textSuggestions:y,offeredTextSuggestions:p}}=t[e],m=o.length,S=y.reduce((W,{text:me,searchTerm:qe})=>W+me.length-(qe?qe.length:0),0),x=c!=null?c:Date.now(),T=(Date.now()-x)/1e3+(f||0),b=i/T,R=y.reduce((W,{searchTerm:me})=>W+(me?me.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:h,deletions:v,lenTextTyped:i+R,lenTextTotal:m,lenTextAssisted:S,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:T,charsPerSecond:b,numPastes:u,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:p.filter(W=>W.source==="gpt").length}],agentId:(_=t.info.agentInfo)==null?void 0:_.agentId,agentName:(Y=t.info.agentInfo)==null?void 0:Y.agentName,agentEmail:(V=t.info.agentInfo)==null?void 0:V.agentEmail}}function Uy(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Uy(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Uy(o,t):null}function xk(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)&&(ro(e)||of(e))}var Ck,_n=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(k({},e),{top:e.top+t.top,left:e.left+t.left})}var _f=!1,Pk=()=>{_f=!0;let e=[];if(_n.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),_n.delete(n);return}let r=n.getBoundingClientRect();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}),_n.size===0){_f=!1;return}Ck=window.requestAnimationFrame(Pk)};function zy(e,t){let n=Tk(e),r=[],o=n.map((i,s)=>zy(i,a=>{r[s]=a;let l=_n.get(e);if(!l)return;let u=r.reduce(kk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),_n.has(e)){let s=_n.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else _n.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!_f&&Pk()},unobserve(){o.forEach(s=>s.unobserve());let i=_n.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||_n.delete(e),_n.size||(cancelAnimationFrame(Ck),_f=!1)}}}}var Rk,Dn=new Map,Ak=()=>{Dn.forEach((e,t)=>{if(!t.isConnected){Dn.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),Dn.size!==0&&(Rk=window.requestAnimationFrame(Ak))};function Lk(e,t){return{observe(){let n=Dn.size===0;Dn.has(e)?Dn.get(e).callbacks.push(t):Dn.set(e,{visible:void 0,callbacks:[t]}),n&&Ak()},unobserve(){let n=Dn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Dn.delete(e),Dn.size||cancelAnimationFrame(Rk)}}}}var By=["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 jy(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Rs(e){return parseFloat(e)}function Df(e){return Math.round(e*1e6)}function Ik(e){return e/1e6}function Vy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Rs(e.width),i=Rs(e.borderLeftWidth),s=Rs(e.borderRightWidth),a=Rs(e.paddingRight),l=Ik(Df(o)-Df(i)-Df(s)),u=Ik(Df(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function Fl(e,t={}){var c,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",$o(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};jy(r,n,By),Vy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=Lk(e,()=>{jy(r,n,By),Vy(r,e,n),i(),setTimeout(i,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(jy(r,n,By),Vy(r,e,n),i(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let h=t.closestScrollElement.getBoundingClientRect(),v=window.getComputedStyle(t.closestScrollElement),y=Rs(v.borderTopWidth),p=Rs(v.borderBottomWidth),m=h.top+y-d.top,g=d.top+d.height+-(h.top+h.height-p);n.style.clipPath=`inset(${m}px 0px ${g}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(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.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){F.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 i=Nk(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var De=w(C());var Mk=Ok("showTabHint",!0),As=class As{constructor({deepdeskUrl:t,brokerUrl:n,version:r=As.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let u=t.replace(/\/api$/,"");this.deepdeskApi=new vr(u,{token:i,fetch:s}),this.version=r,this.instanceId=As.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[vk({broadcast:(f,d,h)=>{this.broadcastEvents.send(f,d,h)},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 Dl(n)}),this.store=yk(c),this.broadcastEvents=new rk({debug:!0,deepdeskUrl:u,eventMap:sE(this.store),createCustomChannel:l}),this.store.dispatch(yl(Mk.value())),this.store.dispatch(td({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(F.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(F.warn("Profile has not been loaded (yet)"),!0):(F.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(ns(null)),this.store.dispatch(Zn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();ut(r)&&y1(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return P(this,null,function*(){return(yield this.store.dispatch(Zn())).payload})}isConversationSupported(t,n){return P(this,null,function*(){return(yield this.store.dispatch(th({sessionId:t,options:n}))).payload})}createConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(rd(t))).payload})}getConversationBySessionId(t,n){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(od({sessionId:t,options:n}))).payload})}upsertConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(nh(t))).payload})}postMessages(t){return P(this,null,function*(){return(yield this.store.dispatch(sd(t))).payload})}updateConversation(t){return P(this,null,function*(){return(yield this.store.dispatch(id(t))).payload})}resetConversation(){this.store.dispatch(fe()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(td(t))}setVisitorInfo(t){this.store.dispatch(Q1(t))}setCustomData(t){this.store.dispatch(Y1(t))}setAgentInfo(t){return P(this,null,function*(){yield this.store.dispatch(Wa(t))})}setAgentSettings(t){return P(this,null,function*(){yield this.store.dispatch(oh(t))})}getAgentSettings(){return P(this,null,function*(){return(yield this.store.dispatch(ih())).payload})}refresh(){return P(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(cd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(qd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(un(t))}evaluateRule(o){return P(this,arguments,function*(t,n={},r=JC){return(yield this.store.dispatch(Qo({label:t,params:n,options:r}))).payload.cues})}evaluateAssistant(r){return P(this,arguments,function*(t,n={}){let c=n,{input:o={},transcript:i,showCuesInWidget:s=!0,includeTags:a}=c,l=ne(c,["input","transcript","showCuesInWidget","includeTags"]);Object.assign(o,l);let u=yield this.store.dispatch(Jr({assistantCode:t,transcript:i,includeTags:a,input:o,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){F.warn(`No assistant set in profile for conversation event "${t}"`);return}yield this.evaluateAssistant(o,k({transcript:"stored-transcript",includeTags:!0},n))})}getSummary(){return P(this,null,function*(){var n;if(!this.hasConversation())return F.warn("No conversation to create summary for."),null;(n=this.state.profile.data)!=null&&n.summarizerAssistantNew||F.warn("No profile loaded yet, or no summarizer assistant set in profile");let t=yield this.store.dispatch(fs({}));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:i,selection:s}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.state.settings,u=a?"below":"above",c=o.length>0;if(!On(this.state)||(this.store.dispatch(H1(rh(t))),t.key!=="Tab"&&!l))return;let f=()=>{n||!c||s&&(t.shiftKey||(this.store.dispatch(B1()),t.preventDefault()))},d=()=>{n||!c||a&&i<=0||s&&(t.shiftKey||(this.store.dispatch(j1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():f();break;case"ArrowDown":{u==="below"?f():d();break}case"Escape":{n||(this.store.dispatch(ud(-1)),this.store.dispatch(to({collapse:!0})),this.store.dispatch(Yb(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let h=ss(this.state);if(!h)return;this.store.dispatch(yl(!1)),this.store.dispatch(un({text:h.text,suggestion:h,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.state.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let h=ss(this.state);if(!h)return;this.store.dispatch(un({text:h.text,suggestion:h,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.state.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let h=ss(this.state);if(!h)return;this.store.dispatch(un({text:h.text,suggestion:h,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(to({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Gr([]))}handlingTimeStart(){this.state.handlingTime.startTime||(F.info("Start handling time"),this.store.dispatch(lk()))}handlingTimeStop(){this.state.handlingTime.startTime&&(F.info("Stop handling time"),this.store.dispatch(Of()))}logSendMessage(t){let n=wk("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(Oo((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(i){F.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),F.error(i)}})}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[i,s]=Fl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,rn.unmountComponentAtNode)(i),s(),i.remove()}),i}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 i=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,s=i?i.ownerDocument.defaultView:null;if(i&&(s===window||(s==null?void 0:s.parent)===window)){let[l,u]=Fl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{(0,rn.unmountComponentAtNode)(o),u()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return $o(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,rn.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),F.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()?(F.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(V1(r.metrics))):F.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:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:f,detectSubmit:d,insertLink:h,inputMediator:v,closestScrollSelector:y,appendOverlayTo:p,inlineSuggestions:m,floatingMenu:g}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:h,isEmbedded:f,inlineSuggestions:m,floatingMenu:!!g}),n.automaticHandlingTime&&this.setupHandlingTime(t),$o(t),this.inputMediator=v||(ro(t)?new Jo(t):new Zo(t)),this.inputMediator.on("change",({plainText:T,rawHTML:b})=>{this.store.dispatch(cd({text:T,html:b}))}),this.inputMediator.on("keyup",T=>{this.store.dispatch(U1(rh(T)))}),this.inputMediator.on("keydown",T=>{this.handleKeyDown(T)}),this.inputMediator.on("paste",({pastedText:T,selectionText:b})=>{this.store.dispatch(z1({text:T,selectionText:b}))}),this.inputMediator.on("cut",({selectionText:T})=>{this.store.dispatch(F1(T))});let S;this.inputMediator.on("selection",T=>{clearTimeout(S),T===null?S=setTimeout(()=>{T!==null&&this.store.dispatch(dd(T))},500):this.store.dispatch(dd(T))}),this.inputMediator.on("disabled",()=>{var T;(T=this.inputMediator)==null||T.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(Zd(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Zd(!0))});let x=y&&xk(t,y)||void 0;if(m){let{customStyles:T,appendOverlayTo:b}=n;if(ro(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let R=this.createInlineContainer(t,"deepdesk-caret");(0,rn.render)((0,De.jsx)(Go,{store:this.store,customStyles:T,children:(0,De.jsx)(Mo,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(oC,{})})}),R),this.inputMediator.on("caretposition",_=>{_?(R.style.display="block",R.style.top=`${_.top}px`,R.style.left=`${_.left}px`):R.style.display="none"});let N=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof g=="object"&&"appendOverlayTo"in g?g.appendOverlayTo:b},T==null?void 0:T.floatingMenuRootNode);(0,rn.render)((0,De.jsx)(Go,{store:this.store,customStyles:T,children:(0,De.jsx)(Mo,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(qb,{onLogIn:()=>this.loginViaPopup().catch(_=>F.warn(_.message))})})}),N)}else{let T=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:p,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),b=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:p},r==null?void 0:r.suggestionsRootNode);(0,rn.render)((0,De.jsx)(Go,{store:this.store,customStyles:r,children:(0,De.jsx)(Mo,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(MC,{inputElement:t})})}),T),(0,rn.render)((0,De.jsx)(Go,{store:this.store,customStyles:r,children:(0,De.jsx)(Mo,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(pC,{onLogIn:()=>this.loginViaPopup().catch(R=>F.warn(R.message))})})}),b)}(0,rn.render)((0,De.jsx)(Go,{store:this.store,customStyles:r,children:(0,De.jsx)(Mo,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(jb,{})})}),this.createContainer("deepdesk-overlays")),this.store.dispatch(cd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(dd(this.inputMediator.getSelection())),this.store.dispatch(Zd(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var T;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((T=this.state.conversation.current)==null?void 0:T.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&F.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,rn.render)((0,De.jsx)(Go,{store:this.store,customStyles:r,children:(0,De.jsx)(Mo,{broadcastEvents:this.broadcastEvents,children:(0,De.jsx)(ZT,{onLogIn:()=>this.loginViaPopup().catch(s=>F.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,rn.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Ff(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){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(cl());let t=sr(this.state);t&&(yield this.store.dispatch(fl()),this.store.dispatch(td({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew||t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))})),this.loadProfileConfigPromise)}loginViaPopup(t){return P(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=h=>P(this,null,function*(){var v,y;if((v=h.data)!=null&&v.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((y=h.data)==null?void 0:y.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(qa),l=!0,o.port1.close(),n()}catch(p){console.error(p),r(p)}finally{l=!0,u()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let f=h=>P(this,null,function*(){var v;if(h.origin===a.origin)switch((v=h.data)==null?void 0:v.type){case"deepdesk-popup-loaded":{try{let y=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(y,a.origin,[o.port2])}catch(y){F.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-error":{u(),h.data.message==="Timeout"&&F.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(h.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(F.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;F.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return P(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Wd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(gn()):su.includes(r)||this.store.dispatch(hn(r))})}catch(r){this.handleError(r)}})}};As.version="14.2.1-beta.1",As.count=0;var Hl=As;function h_(e){return P(this,null,function*(){var o,i,s;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(s=(i=e.mimeType)!=null?i:n.headers.get("Content-Type"))!=null?s:"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 vr(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:i}=e,{start:s,end:a}=(f=n.replace)!=null?f:{start:0,end:i.length},l=`${i.slice(0,s)}${t}${i.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+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 i=n.replace?so(e,n.replace.start,n.replace.end):Ts(e),s,a=()=>{if(n.setRange)return n.setRange(i.cloneRange());i.deleteContents(),s=document.createElement("span"),i.insertNode(s),n.insertBRs!==!1?t.split(`
28
28
  `).reverse().forEach((l,u)=>{u>0&&i.insertNode(document.createElement("br")),i.insertNode(document.createTextNode(l))}):i.insertNode(document.createTextNode(t))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let l=n.selectionAfter?so(e,n.selectionAfter.start,n.selectionAfter.end):(i.collapse(!1),i),u=window.getSelection();u==null||u.removeAllRanges(),u==null||u.addRange(l)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.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},i=0;for(;o=n.slice(i).match(/(\[([^\]]+)])\(([^)]+)\)/);){let s=document.createElement("a");s.href=o[3],s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer"),s.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(i,i+o.index))),t.appendChild(s),i=i+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(i)))}),t}function 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 Bk(o,i){return P(this,arguments,function*(e,t,{isBlock:n,isHTML:r}={}){let s;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;s=document.createElement("span"),c.insertNode(s);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(),!!s)try{s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}return nP(S_);})();
30
30
  /*! Bundled license information:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepdesk/deepdesk-sdk",
3
- "version": "14.2.1-beta.0",
3
+ "version": "14.2.1-beta.1",
4
4
  "description": "Deepdesk SDK",
5
5
  "author": "Lukas Batteau",
6
6
  "license": "ISC",