@deepdesk/deepdesk-sdk 11.5.4-beta.2 → 11.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.iife.js +1 -1
- package/package.json +1 -1
package/dist/index.iife.js
CHANGED
|
@@ -24,7 +24,7 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
|
24
24
|
`+at),Gt&&df([W,V,Z],no=>{at=cl(at,no," ")}),w&&Ll?w.createHTML(at):at},t.setConfig=function(){let U=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};If(U),Rl=!0},t.clearConfig=function(){Jo=null,Rl=!1},t.isValidAttribute=function(U,E,A){Jo||If({});let D=Ie(U),ce=Ie(E);return qy(D,ce,A)},t.addHook=function(U,E){typeof E=="function"&&(_[U]=_[U]||[],ul(_[U],E))},t.removeHook=function(U){if(_[U])return lT(_[U])},t.removeHooks=function(U){_[U]&&(_[U]=[])},t.removeAllHooks=function(){_={}},t}var ST=vT();var Zr=S(N());var hN={"":["<em>","</em>"],_:["<strong>","</strong>"],"*":["<strong>","</strong>"],"~":["<s>","</s>"],"\n":["<br />"]," ":["<br />"],"-":["<hr />"]};function wT(e){return e.replace(RegExp("^"+(e.match(/^(\t| )+/)||"")[0],"gm"),"")}function fl(e){return(e+"").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}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||{},p=0;function d(y){var v=hN[y[1]||""],f=l[l.length-1]==y;return v?v[1]?(f?l.pop():l.push(y),v[0|f]):v[0]:y}function g(){for(var y="";l.length;)y+=d(l[l.length-1]);return y}for(e=e.replace(/^\[(.+?)\]:\s*(.+)$/gm,function(y,v,f){return c[v.toLowerCase()]=f,""}).replace(/^\n+|\n+$/g,"");o=a.exec(e);)r=e.substring(p,o.index),p=a.lastIndex,n=o[0],r.match(/[^\\](\\\\)*\\$/)||((s=o[3]||o[4])?n='<pre class="code '+(o[4]?"poetry":o[2].toLowerCase())+'"><code'+(o[2]?' class="language-'+o[2].toLowerCase()+'"':"")+">"+wT(fl(s).replace(/^\n+|\n+$/g,""))+"</code></pre>":(s=o[6])?(s.match(/\./)&&(o[5]=o[5].replace(/^\d+/gm,"")),i=pl(wT(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="'+fl(o[8])+'" alt="'+fl(o[7])+'">':o[10]?(u=u.replace("<a>",'<a href="'+fl(o[11]||c[r.toLowerCase()])+'">'),n=g()+"</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>"+fl(o[16])+"</code>":(o[17]||o[1])&&(n=d(o[17]||"--"))),u+=r,u+=n;return(u+e.substring(p)+g()).replace(/^\n+|\n+$/g,"")}var xT={root:"dd-L7b3z",popover:"dd-OQOTB",options:"dd-Y12RE",arrow:"dd-cv33T",copyIcon:"dd-6xOsH",option:"dd-9oFX4",divider:"dd-aiZf8",fadeup:"dd-Jq9pd"};var Pn=S(b());function yN(e){return`<button type="button" class=${e}><svg version="1.1" x="0px" y="0px" viewBox="0 0 115.77 122.88" width="10px" height="10px" fill="black"><g><path d="M89.62,13.96v7.73h12.19h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02v0.02 v73.27v0.01h-0.02c-0.01,3.84-1.57,7.33-4.1,9.86c-2.51,2.5-5.98,4.06-9.82,4.07v0.02h-0.02h-61.7H40.1v-0.02 c-3.84-0.01-7.34-1.57-9.86-4.1c-2.5-2.51-4.06-5.98-4.07-9.82h-0.02v-0.02V92.51H13.96h-0.01v-0.02c-3.84-0.01-7.34-1.57-9.86-4.1 c-2.5-2.51-4.06-5.98-4.07-9.82H0v-0.02V13.96v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07V0h0.02h61.7 h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02V13.96L89.62,13.96z M79.04,21.69v-7.73v-0.02h0.02 c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v64.59v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h12.19V35.65 v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07v-0.02h0.02H79.04L79.04,21.69z M105.18,108.92V35.65v-0.02 h0.02c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v73.27v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h61.7h0.02 v0.02c0.91,0,1.75-0.39,2.37-1.01c0.61-0.61,1-1.46,1-2.37h-0.02V108.92L105.18,108.92z"/></g></svg></button>`}function yy(e){let t=e.cloneNode(!0);return t.querySelectorAll("div,button").forEach(n=>n.remove()),t.textContent??""}function vN(e){return e.replace(/\r\n/g,`
|
|
25
25
|
`)}var SN=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let i=P("Markdown",xT),s=(0,Zr.useRef)(null),[a,l]=(0,Zr.useState)(null),u=(0,Zr.useMemo)(()=>{let v=pl(vN(e));return ST.sanitize(v).replace(/<\/code>/g,`${yN(i.copyIcon)}</code>`)},[e]),c=v=>{var h;let f=v.target,m=!!((h=s.current)!=null&&h.querySelector("code"));a||m&&f.tagName!=="CODE"||!m&&f!==s.current||(f.addEventListener("mouseleave",()=>l(null),{once:!0}),l(f))},p=()=>{if(!a)return;l(null);let v=a.querySelector("button");v&&(Qn(v,i.fadeup),r(yy(a)))},d=v=>{v.target.tagName.toLowerCase()==="button"&&(Qn(v.target,i.fadeup),r(yy(v.target.parentElement)))},g=()=>{a&&(l(null),o(yy(a)))},y=v=>{if(v===null)return;let f=v.getBoundingClientRect();f.left<0?v.style.transform=`translateX(${-f.left+2}px)`:f.right>window.innerWidth&&(v.style.transform=`translateX(${window.innerWidth-f.right-2}px)`)};return(0,Pn.jsxs)(Zr.Fragment,{children:[a&&(0,Pn.jsxs)(us,{triggerRef:{current:a},className:i.popover,parentNode:a,children:[(0,Pn.jsxs)("div",{className:i.options,ref:y,children:[(0,Pn.jsx)("button",{type:"button",className:i.option,onClick:p,children:n}),(0,Pn.jsx)("div",{className:i.divider}),(0,Pn.jsx)("button",{type:"button",className:i.option,onClick:g,children:t})]}),(0,Pn.jsx)("div",{className:i.arrow})]}),(0,Pn.jsx)("div",{ref:s,className:i.root,dangerouslySetInnerHTML:{__html:u},onMouseOver:c,onClick:d})]})},ET=SN;var vy={};je(vy,{enUS:()=>wN,nlNL:()=>xN});var wN={useCue:[{type:0,value:"Add to message"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},xN={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 CT={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",thumbsUp:"dd-6QwVx",thumbsDown:"dd-d3E8l"};var Pt=S(b()),EN=({cue:e,onRemove:t,onCopy:n,onUse:r,onThumbsUp:o,onThumbsDown:i})=>{let s=P("WidgetCue",CT),a=$(vy),l=ts(),[u,c]=(0,gf.useState)(null),p=f=>{n&&n(f,e)},d=f=>{r&&r(f,e)},g=f=>{f.preventDefault(),f.stopPropagation(),t(e)},y=f=>{f.preventDefault(),f.stopPropagation(),Qn(f.target,s.fadeup),c("up"),o(e)},v=f=>{f.preventDefault(),f.stopPropagation(),Qn(f.target,s.fadedown),c("down"),i(e)};return(0,gf.useEffect)(()=>{l("Assistant response displayed",{name:e.rule.name,description:e.rule.description,group:e.rule.label,cueText:e.text})},[]),(0,Pt.jsxs)(ne,{"data-testid":"cue",children:[(0,Pt.jsx)(fe,{children:(0,Pt.jsxs)(fe.Content,{children:[e.title&&(0,Pt.jsx)(fe.Title,{className:s.title,"data-testid":"widget-cue-title",children:e.title}),(0,Pt.jsx)(ET,{content:e.text,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:p,onUse:d})]})}),(0,Pt.jsx)(ne.IconButton,{title:a("thumbsUp"),onClick:y,icon:(0,Pt.jsx)(Nd,{}),className:(0,Sy.default)(s.thumbsUp,u==="up"&&s.selected),disabled:!!u}),(0,Pt.jsx)(ne.IconButton,{title:a("thumbsDown"),onClick:v,icon:(0,Pt.jsx)(Od,{}),className:(0,Sy.default)(s.thumbsDown,u==="down"&&s.selected),disabled:!!u}),(0,Pt.jsx)(ne.IconButton,{title:a("removeCue"),onClick:g,icon:(0,Pt.jsx)(sT,{})})]})},bT=EN;var ml=S(b()),CN=({cues:e})=>{let t=X(),n=jt(),r=ts(),o=u=>{t(Bb({id:u.rule.id})),r("Assistant response closed",{name:u.rule.name,group:u.rule.label,description:u.rule.description,cueText:u.text})},i=(u,c)=>{$n(u),r("Assistant response copied",{name:c.rule.name,group:c.rule.label,description:c.rule.description,copiedText:u})},s=(u,c)=>{n.send(jr,{text:u,suggestion:{source:"cue",sourceText:u}}),r("Assistant response used",{name:c.rule.name,group:c.rule.label,description:c.rule.description,usedText:u})},a=u=>{r("Assistant response feedback",{name:u.rule.name,group:u.rule.label,description:u.rule.description,thumb:"up",cueText:u.text})},l=u=>{r("Assistant response feedback",{name:u.rule.name,group:u.rule.label,description:u.rule.description,thumb:"down",cueText:u.text})};return(0,ml.jsx)(ml.Fragment,{children:e.map(u=>(0,ml.jsx)(bT,{cue:u,onRemove:o,onCopy:i,onUse:s,onThumbsDown:l,onThumbsUp:a},u.rule.id))})},TT=CN;var hf=S(N());var kT={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var dn=S(b());function bN(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var PT=({data:e,schema:t})=>{let n=P("WidgetCustomData",kT),r=o=>{$n(o)};return(0,hf.useEffect)(()=>{H.info("Custom data",e,t)},[e]),(0,dn.jsx)("dl",{className:n.root,children:t.map(o=>{let i=bN(e,o.path);return(0,dn.jsxs)(hf.Fragment,{children:[(0,dn.jsx)("dt",{className:n.label,children:o.label}),(0,dn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&i?(0,dn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!i?(0,dn.jsx)("span",{className:n.isFalse,children:o.falseValue}):i?(0,dn.jsxs)("button",{type:"button",onClick:()=>r(i),className:n.copyButton,children:[(0,dn.jsx)("span",{children:i}),(0,dn.jsx)(al,{})]}):"-"})]},o.label)})})};var AT=S(N());var TN=/(https?:\/\/[^\s]+)/,RT=e=>e.split(" ").find(t=>TN.test(t));var $t=S(b()),kN=({suggestion:e,lines:t,onUse:n})=>{var c;let r=e.text||e.url||e.message,o=RT(r),i=$(Do),s=B("showImages"),a=B("fallbackImage"),l=p=>{p.preventDefault(),p.stopPropagation(),n(r)},u=(0,AT.useCallback)(p=>{window.open(o,"_blank"),p.stopPropagation(),p.preventDefault()},[o]);return(0,$t.jsxs)(ne,{onClick:l,"data-testid":"edit-suggestion",children:[(0,$t.jsxs)(fe,{children:[s&&e.image&&(0,$t.jsx)(fe.Image,{src:rf(e,"small",a||void 0),title:e.title}),(0,$t.jsxs)(fe.Content,{children:[e.title&&(0,$t.jsx)(fe.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((c=e.searchKeywords)==null?void 0:c.length)>0&&(0,$t.jsx)(ne.Labels,{labels:e.searchKeywords}),(0,$t.jsx)(fe.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,$t.jsxs)(ne.Actions,{children:[o&&(0,$t.jsx)(ne.ActionButton,{onClick:u,label:i("visitUrl")}),(0,$t.jsx)(ne.ActionButton,{primary:!0,onClick:l,label:i("useSuggestion")})]})]})},LT=kN;var gl=S(b()),PN=({lines:e,suggestions:t})=>{let n=jt(),r=(o,i)=>{n.send(jr,{text:o,suggestion:{...i,source:i.source,sourceText:i.text}})};return(0,gl.jsx)(gl.Fragment,{children:t.map(o=>(0,gl.jsx)(LT,{suggestion:o,lines:e,onUse:i=>r(i,o)},o.text||o.url||o.message))})},IT=PN;var hl={};je(hl,{enUS:()=>RN,nlNL:()=>AN});var RN={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"}]},AN={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 yl={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",sectionList:"dd-bF9pF",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",link:"dd-DRo0x"};var K=S(b()),yf=(e,t)=>{let n=M(tt);(0,vl.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},LN=({onLogIn:e})=>{let t=P("Widget",yl),n=B("isEmbedded"),r=B("adminUrl");return(0,K.jsx)("div",{className:t.loginText,children:(0,K.jsx)("div",{children:(0,K.jsx)(Kd,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},MT=({text:e})=>{let t=P("Widget",yl);return(0,K.jsx)("div",{className:t.stateText,children:(0,K.jsx)("div",{children:(0,K.jsx)("p",{children:e})})},"notification")},IN=()=>{let e=$(hl),t=X(),n=P("Widget",yl),r=B("showSearch"),o=B("showSummaryCommand"),i=B("showKnowledgeSearch"),s=M(_b("/admin/")),a=jt(),l=B("productName"),u=r||o||i||s;return yf(()=>(t(ey()),()=>{t(Fb())}),[t]),u?(0,K.jsx)(pn,{title:e("actions"),type:"shortcuts",children:(0,K.jsxs)("div",{className:n.shortcutList,children:[r&&(0,K.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-search","aria-label":e("linkSearch"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0}),children:[(0,K.jsx)(Zi,{}),e("linkSearch")]}),o&&(0,K.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-summary","aria-label":e("linkSummary"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,K.jsx)(iT,{}),e("linkSummary")]}),i&&(0,K.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-knowledge-assist","aria-label":e("linkKnowledgeSearch"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,K.jsx)(oT,{}),e("linkKnowledgeSearch")]}),s&&(0,K.jsxs)("a",{className:n.shortcut,target:"_blank",href:s,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:l}),rel:"noreferrer",children:[(0,K.jsx)(rT,{}),e("linkStudioLogin",{productName:l})]})]})}):null},MN=()=>{let e=X(),t=B("showCustomMessages"),n=M(Pb),r=M($i);return yf(()=>(e(sl(r)),e(Mb(r)),()=>{e(Ob(r))}),[e,t,r]),!t||n.length===0?null:(0,K.jsx)(pn,{type:"custom-messages","data-testid":"custom-messages",children:(0,K.jsx)(ct,{withDivider:!0,children:n.map(o=>(0,K.jsx)(eT,{suggestion:o},o.text))})})},ON=()=>{let e=$(hl),t=X(),n=B("showAutoflows"),r=M(Eb),o=M($i);return yf(()=>(t(ir(o)),t(Cb(o)),()=>{t(bb(o))}),[t,n,o]),!n||r.length===0?null:(0,K.jsx)(pn,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:(0,K.jsx)(ct,{withDivider:!0,children:(0,K.jsx)(Zb,{})})})},NN=()=>{let e=X(),t=M(Dd),n=M(dC),r=M(Ub),o=M(_1),i=M(Md),s=M(Fd),a=M(Jn),l=M(Kc);return(0,vl.useEffect)(()=>{!!o&&!n&&H.warn("Custom data provided, but no schema.")},[o,n]),yf(()=>{t.forEach(({type:u})=>{u==="entities"?e(sn()):ql.includes(u)||e(ln(u))})},[e,l,a]),(0,K.jsx)(vl.Fragment,{children:t.map(({type:u,title:c,amount:p,lines:d,schema:g})=>{var y,v;switch(u){case"entities":return i&&i.length>0&&(0,K.jsx)(pn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,K.jsx)(nT,{entities:i})},u);case"cues":return r&&r.length>0&&(0,K.jsx)(pn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,K.jsx)(ct,{withDivider:!0,children:(0,K.jsx)(TT,{cues:r})})},u);case"custom-data":return o&&g&&(0,K.jsx)(pn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,K.jsx)(ct,{withDivider:!0,children:(0,K.jsx)(PT,{data:o,schema:g})})},u);default:return((v=(y=s[u])==null?void 0:y.suggestions)==null?void 0:v.length)>0&&(0,K.jsx)(pn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,K.jsx)(ct,{withDivider:!0,children:(0,K.jsx)(IT,{lines:d,contentType:u,suggestions:s[u].suggestions.slice(0,p)||[]})})},u)}})})},_N=({onLogIn:e})=>{let t=$(hl),n=P("Widget",yl),r=M(qi),o=M(tt),i=M($i),s=M(Jn);return r===!1?(0,K.jsx)(MT,{text:t("notSupported")}):o===!1?(0,K.jsx)(LN,{onLogIn:e}):!s||!i||o===null?(0,K.jsx)(MT,{text:t("waiting")}):(0,K.jsx)("div",{className:(0,OT.default)(n.root),"data-testid":"widget",children:(0,K.jsxs)(Kl,{className:n.sectionList,children:[(0,K.jsx)(IN,{}),(0,K.jsx)(MN,{}),(0,K.jsx)(ON,{}),(0,K.jsx)(NN,{})]})})},NT=_N;function cs(e){let t=new Range;return t.selectNodeContents(e),t}function _T(e,t,n){try{return Jr(e,t,n),!0}catch{return!1}}function vf(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function Sf(e){return"tagName"in e&&e.tagName==="BR"}var Sl=/[\u200B-\u200D\uFEFF]/g;function Jr(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,i=!1;function s(l,u){let c=-1,p=/[\u200B-\u200D\uFEFF]/;if(!p.test(l))return u;for(let d=0;d<=l.length;d++)if(p.test(l[d])||c++,c===u)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let u=l.textContent,c=u.replace(Sl,""),p=o+c.length,d=t>=o&&t<=p,g=n>=o&&n<=p;if(d){let y=s(u,t-o);y===0&&!g?r.setStartBefore(l):r.setStart(l,y)}g&&(r.setEnd(l,s(u,n-o)),i=!0),o=p;break}case Node.ELEMENT_NODE:{if(Sf(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;vf(l)&&u&&!vf(u)&&!Sf(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function wl(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a,l,u=0;function c(p){let d=p===n,g=p===o;switch(p.nodeType){case Node.TEXT_NODE:{let y=p.textContent;d&&(a=u+y.substring(0,r).replace(Sl,"").length),g&&(l=u+y.substring(0,i).replace(Sl,"").length),u+=y.replace(Sl,"").length;break}case Node.ELEMENT_NODE:{let y=p.nextSibling===null;Sf(p)&&!y&&u++;for(let v=0;v<p.childNodes.length;v++){let f=d&&v===r,m=g&&v===i;if(f&&(a=u),m&&(l=u),l!==void 0||((!f||!s)&&c(p.childNodes[v]),g&&v===i-1&&(l=u),l!==void 0))break}!g&&vf(p)&&!y&&u++,g&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a??l,end:l}}function xl(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i}=t,s=-1,a="";function l(u){let c=u===n,p=u===o;switch(c&&s++,u.nodeType){case Node.TEXT_NODE:{if(s!==0)return;let d=c?r:0,g=p?i:void 0,y=u.textContent.replace(Sl,"");d===0&&g===void 0?a+=y:a+=y.substring(d,g);break}case Node.ELEMENT_NODE:{let d=u.nextSibling===null;s===0&&Sf(u)&&!d&&(a+=`
|
|
26
26
|
`);for(let g=c?r:0;g<(p?Math.min(i,u.childNodes.length):u.childNodes.length)&&(l(u.childNodes[g]),s!==1);g++);!p&&s===0&&vf(u)&&!d&&(a+=`
|
|
27
|
-
`);break}default:break}p&&s++}return l(e),a}var DT=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(DT||{}),ar=class{constructor(t){this.element=t;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}triggerChange(){let t=this.getText(),n=this.getHTML(),r=t!==this.currentText;this.isActive&&(t===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&r&&!this.isSubmitting&&this.emit("change",{plainText:t}),r&&(this.currentSelection=this.getSelection()),this.currentText=t,this.isSubmitting=!1,(this.currentHTML!==n||n===null&&r)&&(this.emit("updated",{plainText:t}),this.triggerCaretPosition(),this.currentHTML=n))}triggerSelection(){let t=this.getSelection();(t.start!==this.currentSelection.start||t.end!==this.currentSelection.end)&&(this.currentSelection=t,this.emit("selection",t),this.triggerCaretPosition())}triggerCaretPosition(){let t=this.getCaretPosition();Ur(t,this.currentCaret)||(this.currentCaret=t,this.emit("caret",t))}handleKeyUp(t){let{key:n,shiftKey:r}=t;(n==="Enter"&&r===!0||n==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(DT).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(t={shouldObserve:!0}){this.addEventListener("keydown",r=>this.handleKeyDown(r)),this.addEventListener("keyup",r=>this.handleKeyUp(r)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",r=>this.handlePaste(r)),this.addEventListener("click",()=>this.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let n=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t!=null&&t.shouldObserve&&n.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{n.disconnect()}),this.currentSelection=this.getSelection()}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function FT(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var $o=class extends ar{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),xl(this.element,t)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let t=this.getRootNode();if(t.activeElement!==this.element)return null;let n="getSelection"in t?t.getSelection():window.getSelection();if(!n)return null;let r="getComposedRanges"in n&&t instanceof ShadowRoot?(i=n.getComposedRanges(t))==null?void 0:i[0]:n.rangeCount>0?n.getRangeAt(0):null;if(!r)return null;let o=this.element.ownerDocument.createRange();return o.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),o.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!o||!this.element.contains(o.startContainer)||!this.element.contains(o.endContainer)?null:o}getCaretPosition(){let t=this.getRange();if(!t||!t.collapsed||!("getBoundingClientRect"in t))return null;let n=t.getBoundingClientRect();return!FT(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!FT(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return wl(this.element,t);let n=this.lastKnownSelection;if(n&&_T(this.element,n.start,n.end))return n;let r=cs(this.element);return r.collapse(!1),wl(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return xl(this.element,Jr(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(t={shouldObserve:!0}){super.listen(t),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),t!=null&&t.shouldObserve&&this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let n=this.element.isContentEditable,r=new MutationObserver(()=>{this.element.isContentEditable!==n&&(n=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>r.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var qo=class extends ar{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:t,selectionEnd:n}=this.element;return{start:t,end:n}}getSelectedText(){let t=this.getSelection();return t?this.getText().slice(t.start,t.end):""}getCaretPosition(){return null}applyChanges(t){if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let t=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var o;return(o=t==null?void 0:t.get)==null?void 0:o.call(this.element)},set:o=>{var i;(i=t==null?void 0:t.set)==null||i.call(this.element,o),this.triggerChange()}});let n=this.element.disabled,r=new MutationObserver(()=>{this.element.disabled!==n&&(n=this.element.disabled,this.emit(n?"disabled":"enabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>r.disconnect())}};function HT(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function DN(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}var wy=class{constructor(t){this.name=t;this.broadcastChannel=new BroadcastChannel(t)}broadcastChannel;disposeHandlers=[];onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},xy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=HT(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},Ey=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),H.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new xy(t,this.deepdeskUrl,{debug:!0}):new wy(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=DN(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(H.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;H.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage({...o,channel:this.sessionId})}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},UT=Ey;var ds=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var Cy=e=>new Promise(t=>{setTimeout(t,e)});var fs=class extends ds{name="ClientError"},Ty=class extends ds{name="ServerError"},by=new Map;async function FN(e){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=await e.text();return n===""?null:(H.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))}var fn=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",{useCache:u=!1,abortLatest:c=!1,attempts:p=1,retryDelay:d=500,refreshTokenOn401:g=!0,retryOnError:y=C=>C instanceof TypeError,retryOnResponse:v=C=>C.status>=500,version:f="v1",...m}=n;if(u)if(l){if(by.has(s)){r(by.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h={credentials:"include",...m,headers:{"Content-Type":"application/json",...m.headers}};!l&&this.csrfToken&&(h.headers={...h.headers,"X-CSRFToken":this.csrfToken}),typeof f=="string"&&(h.headers={...h.headers,"X-Deepdesk-API-Version":f});let w=p,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=async()=>(w--,a(s,h).then(async C=>v(C)&&!i.isAborted&&w>0?(await Cy(d),T()):C.status===401&&g===!0&&x===!1?(x=!0,await this.refreshToken(),T()):C).catch(async C=>{if(y(C)&&!i.isAborted&&w>0)return await Cy(d),T();throw C}));T().then(async C=>{let k=await FN(C);if(delete this.latestRequestByUrl[s],C.status>=500){o(new Ty("Server Error",k));return}else if(C.status===401){o(new fs("Unauthorized",k));return}else if(C.status===403){o(new fs("Forbidden",k));return}else if(C.status===404){o(new fs("Not Found",k));return}else if(C.status>=400){o(new fs("Bad Request",k));return}u&&by.set(s,k),r(k)}).catch(C=>{o(C)})})}async validateToken(){let{has_valid_access_token:t}=await this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return e.refreshingToken||(e.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{e.refreshingToken=null},1e3*60)})),e.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,{method:"POST",body:JSON.stringify(n),...r})}patch(t,n,r){return this.request(t,{method:"PATCH",body:JSON.stringify(n),...r})}put(t,n,r){return this.request(t,{method:"PUT",body:JSON.stringify(n),...r})}delete(t,n){return this.request(t,{method:"DELETE",...n})}};var HN;(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||={})})(HN||={});function wf(e){return{...ee(e),tags:e.tags}}var lr=class e{constructor(t,n={}){this.options=n;this.client=new fn(t,{fetch:n.fetch}),this.client.patchFetch(r=>async(o,i)=>{let s=await r(o,i);return this.handleDeepdeskVersionHeaders(s),s})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=await this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(e.exchangeTokenPromise||(e.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),e.exchangeTokenPromise):Promise.resolve()}async createConversation(t){await this.preflight(),H.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...Re(t),tags:t.tags},{version:"v2"});return wf(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null,useCache:!0});return ee(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null,useCache:!0});return ee(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return ee(t)}async getAccount(){let t=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return ee(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null,useCache:!0});return ee(t)}async checkUserExists(t){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n}async getConversationBySessionId(t,n={}){await this.preflight(),H.info(`Getting conversation for session ${t}`);let{attempts:r=1,retryDelay:o=1e3}=n,i=await this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"});return H.info(`Successfully retrieved conversation ${i.id} for session ${t}`),wf(i)}async isConversationSupported(t,n={}){H.info(`Check if conversation for session ${t} is supported`);let{attempts:r=1,retryDelay:o=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"})).has_active_profile}async updateConversation(t,n){let r=Re(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return wf(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...Re(o),tags:o.tags})),{version:"v2"})).map(o=>wf(o))}async sendEvent(t,n){let{data:r,...o}=n,i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[a,l])=>({...s,[a]:l}),{});return this.client.post("/api/events",Re({...i,...o,data:r,name:t}),{version:"v2"})}async sendEventV1(t,n){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>({...o,[i]:s}),{});return this.client.post("/api/events",{event:t,data:Re({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){let r=await this.client.post("/api/summary",{conversation:{messages:t.filter(o=>o.text&&o.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model});return ee(r)}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(t){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw H.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.preflight(),await this.client.post("/apis/admin/session/api-key/",Re(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})}async getTextSuggestions(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(await this.client.post(`/api/conversations/${t}/recommend/${r}`,Re(n),{abortLatest:!0})).map(i=>({...ee(i),text:i.text||i.url||i.message,source:r,type:r})).filter((i,s,a)=>s===a.findIndex(l=>l.text===i.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(t,n){return(await this.client.post(`/api/conversations/${t}/autocomplete`,Re(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))}async getPinnedMessages(t){let n=await this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return ee(n).map(r=>({...r,text:r.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(t){let n=await this.client.post("/api/style-suggestions",Re(t),{abortLatest:!0});return ee(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,Re(t),{version:"v2"});return ee(n)}async knowledgeAssist(t,n,r,o={}){let i=await this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Re({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(s=>({question:s.question,answer:s.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return ee(i)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return ee(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return ee(t.token)}async getCsrfToken(){let{token:t}=await this.client.get("/apis/admin/session/csrf/",{version:null});return t}async verifyLoginToken(t){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return ee(n)}async evaluateRule(t,n,r,o={}){let i=new URLSearchParams;o.raiseForFailingConditions&&i.set("raise_for_failing_conditions","true");let s=await this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${i.toString()}`,r,{version:"v2"});return ee(s.cues)}async getRules(){let t=new URLSearchParams,n=await this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{version:null,useCache:!0});return ee(n)}async translateMessages(t){let n=await this.client.post("/api/translate",Re(t),{version:"v2"});return ee(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Vv);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&H.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var El=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(qg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,ee(o))}catch{H.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var UN;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(UN||={});var Cl=class{constructor(t,n={}){this.apiUrl=t;this.client=new fn(t,n)}client;streams={};logger=H;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return ee(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,Re(n));return ee(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,Re(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return ee(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",Re(t));return ee(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new El(`${this.apiUrl}/sessions/${t}/events`),this.streams[t].connect()),this.streams[t]}closeStream(t){this.streams[t]||(this.streams[t].disconnect(),delete this.streams[t])}};var zT={startTime:null,stopTime:null},BT=G({name:"handlingTime",initialState:zT,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(le,()=>zT)}}),{handlingTimeStart:jT,handlingTimeStop:xf,handlingTimeReset:VT}=BT.actions,KT=BT.reducer;var WT=(e={})=>{let t={onAuthError:Wi(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Ef={list:{keywordMatches:[]},fetchState:"idle"};var Go=z("styleSuggestions/getAll",async({text:e},t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),{showStyleSuggestions:o}=r.settings,i=(s=r.conversation.current)==null?void 0:s.profileCode;if(!o)return Ef.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),zN=G({name:"styleSuggestions",initialState:Ef,reducers:{},extraReducers:e=>{e.addCase(Go.pending,t=>{t.fetchState="loading"}).addCase(Go.rejected,t=>{t.fetchState="error"}).addCase(Go.fulfilled,(t,n)=>{t.fetchState="done",Ur(t.list,n.payload)||(t.list=n.payload)}).addCase(ko,t=>{t.list=Ef.list}).addCase(le,()=>Ef)}}),$T=zN.reducer;var qT=(e={})=>{let t,n=!0,r={getStyleSuggestions:Go,debounce:500,...e};return o=>i=>s=>{var g;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(!((g=u.conversation.current)==null?void 0:g.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function BN(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var GT=(e={})=>{let t={getTextSuggestions:ln,getAutocompleteSuggestions:el,debounce:200,check:rs,...e},n;return r=>o=>i=>{var v;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,p=(v=l.conversation.current)==null?void 0:v.id,d=i.type===Hd.toString();if(!p||!u&&!c)return a;let{input:{userCommitted:g}}=l;return BN(g,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let f=Gi(l);f===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(f))},d?0:t.debounce)),a}};var XT=Go.fulfilled.toString();function jN(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var YT=e=>t=>n=>r=>{var u;if(r.type!==XT){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=jN(o,s);r.type===XT&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var VN=pc({answer:lC,auth:u1,autoflows:Tb,conversation:v1,contentTypes:yE,customMessages:Nb,passwordlessToken:Hb,entities:KE,knowledgeAssistant:iC,handlingTime:KT,info:U1,input:O1,settings:n1,profile:fC,search:$1,summary:QE,styleSuggestions:$T,ui:FC,rules:jb,textSuggestions:wC});function QT(e){return lx({reducer:VN,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),WT(),GT({debounce:200}),qT({debounce:500}),YT(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var KN=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},WN=e=>t=>n=>r=>{var a,l,u,c,p;let o=t.getState(),i=zg("inlineSuggestions")(o);switch(r.type){case Wi.toString():{!r.payload&&e.emit("logout",void 0);break}case sn.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 Ye.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 Qc.toString():e.handleKeyDown(r.payload);break;case ko.toString():e.logSendMessage(r.payload);break;case Zc.toString():e.handleInputChanged(r.payload);break;case Ko.fulfilled.toString():r.isBroadcasted||e.broadcast(Yg,r,!1),e.emit("cues",r.payload);break;default:break}let s=n(r);switch(r.type){case ko.toString():e.handleAfterSendMessage(r.payload);break;case nl.toString():e.onUpdateShowTabHint(r.payload);break;case xf.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case Cn.toString():{let{start:d,end:g}=o.input.selection;e.emit("select-suggestion",{type:KN(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:d,end:g}:{start:0,end:g}},{mayApplyChanges:!0}),i&&(t.dispatch(En([])),t.dispatch(Wn()));break}case Yc.toString():{let{start:d,end:g}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:d,end:g}:{start:0,end:g}},{mayApplyChanges:!0});break}case Aa.toString():{let d=t.getState(),{text:g,selection:y}=d.input.userCommitted;e.emit("reset",{text:g,selectionAfter:y},{mayApplyChanges:!0});break}case Jc.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:(c=o.conversation.current)==null?void 0:c.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case En.toString():{i&&r.payload.length>0&&t.dispatch(Br(0));break}case Yn.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(p=o.conversation.current)==null?void 0:p.id,data:{summary:r.payload.summary,model:t.getState().summary.model}});break}default:break}return s},ZT=WN;function ky(e){return e.toISOString().replace("T"," ").replace("Z","")}function JT(e,t){var i,s,a,l;let n=(i=e.conversation.current)==null?void 0:i.id;if(!n)return H.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:o}=e.handlingTime;return!r||!o?(H.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:n,clientVersion:t.version,agentId:(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:ky(r),timeStop:ky(o)}}function ek(e,t,n){var I,L,_,W;let r=(I=t.conversation.current)==null?void 0:I.id;if(!r)return H.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:i,numCharsPasted:s,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:d,cuts:g,deletions:y,textSuggestions:v,offeredTextSuggestions:f}}=t[e],m=o.length,w=v.reduce((V,{text:Z,searchTerm:ur})=>V+Z.length-(ur?ur.length:0),0),x=c??Date.now(),T=(Date.now()-x)/1e3+(p||0),C=i/T,k=v.reduce((V,{searchTerm:Z})=>V+(Z?Z.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:g,deletions:y,lenTextTyped:i+k,lenTextTotal:m,lenTextAssisted:w,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:T,charsPerSecond:C,numPastes:u,textSuggestionsV2:v,suggestionsCounters:[{source:"gpt",countOffered:f.filter(V=>V.source==="gpt").length}],agentId:(L=t.info.agentInfo)==null?void 0:L.agentId,agentName:(_=t.info.agentInfo)==null?void 0:_.agentName,agentEmail:(W=t.info.agentInfo)==null?void 0:W.agentEmail}}function Py(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Py(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Py(o,t):null}function tk(e,t){return Py(e,t)}function nk(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function $N(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Cf(e){return $N(e)&&(Xr(e)||$d(e))}var ok,Rn=new Map,qN=["bottom","height","left","right","top","width"],rk=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:qN.some(n=>e[n]!==t[n]);function ik(e){var n,r;if(e.ownerDocument===document)return[];let t=((r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)??null;return t?[t,...ik(t)]:[]}function sk(e,t){return!e||!t?null:{...e,top:e.top+t.top,left:e.left+t.left}}var bf=!1,ak=()=>{bf=!0;let e=[];if(Rn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Rn.delete(n);return}let r=n.getBoundingClientRect();rk(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(sk,t.rect):t.rect;rk(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Rn.size===0){bf=!1;return}ok=window.requestAnimationFrame(ak)};function Ry(e,t){let n=ik(e),r=[],o=n.map((i,s)=>Ry(i,a=>{r[s]=a;let l=Rn.get(e);if(!l)return;let u=r.reduce(sk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Rn.has(e)){let s=Rn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Rn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!bf&&ak()},unobserve(){o.forEach(s=>s.unobserve());let i=Rn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Rn.delete(e),Rn.size||(cancelAnimationFrame(ok),bf=!1)}}}}var lk,An=new Map,uk=()=>{An.forEach((e,t)=>{if(!t.isConnected){An.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),An.size!==0&&(lk=window.requestAnimationFrame(uk))};function ck(e,t){return{observe(){let n=An.size===0;An.has(e)?An.get(e).callbacks.push(t):An.set(e,{visible:void 0,callbacks:[t]}),n&&uk()},unobserve(){let n=An.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||An.delete(e),An.size||cancelAnimationFrame(lk)}}}}var Ay=["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 Ly(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function ps(e){return parseFloat(e)}function Tf(e){return Math.round(e*1e6)}function dk(e){return e/1e6}function Iy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=ps(e.width),i=ps(e.borderLeftWidth),s=ps(e.borderRightWidth),a=ps(e.paddingRight),l=dk(Tf(o)-Tf(i)-Tf(s)),u=dk(Tf(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function bl(e,t={}){var c;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=t.position??"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Bo(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};Ly(r,n,Ay),Iy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=ck(e,()=>{Ly(r,n,Ay),Iy(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=Ry(e,p=>{if(p===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),p.height===0&&p.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(Ly(r,n,Ay),Iy(r,e,n),i(),n.style.top=`${p.top}px`,n.style.left=`${p.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let d=t.closestScrollElement.getBoundingClientRect(),g=window.getComputedStyle(t.closestScrollElement),y=ps(g.borderTopWidth),v=ps(g.borderBottomWidth),f=d.top+y-p.top,m=p.top+p.height+-(d.top+d.height-v);n.style.clipPath=`inset(${f}px 0px ${m}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(c=e.parentElement)==null||c.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var fk=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch{return t}}catch{return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch{H.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function GN(e){return e.offsetParent!==null}function pk(e){if(!GN(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 kf(e,t,n=100){let r=pk(e);t({isVisible:r});let o=setInterval(()=>{let i=pk(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Le=S(b());var mk=fk("showTabHint",!0),Tl=class e{static version="11.5.4-beta.2";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new lr(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[ZT({broadcast:(p,d,g)=>{this.broadcastEvents.send(p,d,g)},emit:(p,d,g)=>this.emit(p,d,g),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),onUpdateShowTabHint:p=>mk.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Cl(n)}),this.store=QT(c),this.broadcastEvents=new UT({debug:!0,deepdeskUrl:u,eventMap:q1(this.store),createCustomChannel:l}),this.store.dispatch(nl(mk.value())),this.store.dispatch(jc({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(H.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(H.warn("Profile has not been loaded (yet)"),!0):(H.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Wi(null)),this.store.dispatch(Vn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();tt(r)&&r1(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(Vn())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){H.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Kg({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Wc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch($c({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Wg(t))).payload}async postMessages(t){return(await this.store.dispatch(Gc(t))).payload}async updateConversation(t){return(await this.store.dispatch(qc(t))).payload}resetConversation(){this.store.dispatch(le()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(Yn());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(jc(t))}setVisitorInfo(t){this.store.dispatch(F1(t))}setCustomData(t){this.store.dispatch(H1(t))}async setAgentInfo(t){await this.store.dispatch(La(t))}async setAgentSettings(t){await this.store.dispatch(Gg(t))}async getAgentSettings(){return(await this.store.dispatch(Xg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(Hd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(Zc(t))}notifyKeyDown(t){this.store.dispatch(Qc(t))}notifyPaste(t,n){this.store.dispatch(A1({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(P1(t))}notifyExternalSuggestion(t){this.store.dispatch(Cn(t)),this.store.dispatch(Wn())}async evaluateRule(t,n={}){let{payload:r,error:o}=await this.store.dispatch(Ko({label:t,params:n}));if(o)throw new Error(o.message);return r}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(qr({collapse:!1})),this.inputMediator&&this.store.dispatch(E1({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(En([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(R1(S1(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(b1()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(k1()),t.preventDefault(),!s&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Aa()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(Br(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Br(-1)),this.store.dispatch(Aa()),t.preventDefault()):n||(this.store.dispatch(qr({collapse:!0})),this.store.dispatch(_C(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:g}=this.state.input;this.store.dispatch(nl(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&g&&g.text.startsWith(d)&&(this.store.dispatch(Cn({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(Wn())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(L1()),this.store.dispatch(En([]))}handlingTimeStart(){this.state.handlingTime.startTime||(H.info("Start handling time"),this.store.dispatch(jT()))}handlingTimeStop(){this.state.handlingTime.startTime&&(H.info("Stop handling time"),this.store.dispatch(xf()))}logSendMessage(t){let n=ek("input",this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n))}logHandlingTime(){let t=JT(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(VT()))}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(Wn()),this.store.dispatch(ko(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Cn({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{let i=this.eventListeners[t];i&&i.forEach(s=>{try{s(n)}catch(a){H.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),H.error(a)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=bl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,qt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=bl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,qt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Bo(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,qt.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),H.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(H.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(M1(r.metrics))):H.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Cf(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:d,insertLink:g,inputMediator:y,closestScrollSelector:v,appendOverlayTo:f,inlineSuggestions:m,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:g,isEmbedded:p,inlineSuggestions:m,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Bo(t),this.inputMediator=y||(Xr(t)?new qo(t):new $o(t)),this.inputMediator.on("change",({plainText:T})=>{this.notifyInputChanged(T)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(I1({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",T=>{this.notifyKeyDown(T)}),this.inputMediator.on("paste",({pastedText:T,selectionText:C})=>{this.notifyPaste(T,C)}),this.inputMediator.on("cut",({selectionText:T})=>{this.notifyCut(T)});let w=v&&tk(t,v)||void 0;if(m){let{customStyles:T,appendOverlayTo:C}=n;if(Xr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let k=this.createInlineContainer(t,"deepdesk-caret");(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:T,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(VC,{})})}),k),this.inputMediator.on("caret",L=>{this.store.dispatch(En([])),L?(k.style.display="block",k.style.top=`${L.top}px`,k.style.left=`${L.left}px`):k.style.display="none"});let I=this.overlayContainerFactory("floating-menu",w||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:C},T==null?void 0:T.floatingMenuRootNode);(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:T,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(MC,{onLogIn:()=>this.loginViaPopup().catch(L=>H.warn(L.message))})})}),I)}else{let T=this.overlayContainerFactory("deepdesk-tab-completion",w||t,{appendTo:f,closestScrollElement:w,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",w||t,{appendTo:f},r==null?void 0:r.suggestionsRootNode);(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:r,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(Sb,{inputElement:t})})}),T),(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:r,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(ZC,{onLogIn:()=>this.loginViaPopup().catch(k=>H.warn(k.message))})})}),C)}(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:r,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(PC,{})})}),this.createContainer("deepdesk-overlays"));let x;this.inputMediator.on("selection",T=>{clearTimeout(x),T===null?x=setTimeout(()=>{T!==null&&this.store.dispatch($g(T))},500):this.store.dispatch($g(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(Fh(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Fh(!0))),this.store.dispatch(C1({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(Wn()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var T;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((T=this.state.conversation.current)==null?void 0:T.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&H.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:r,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(NT,{onLogIn:()=>this.loginViaPopup().catch(s=>H.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,qt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=kf(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){nk(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Ja());let t=Jn(this.state);t&&(await this.store.dispatch(Ya()),this.store.dispatch(jc({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(t){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};i.onmessage=async g=>{var y,v;if((y=g.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=g.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Ma),l=!0,o.port1.close(),n()}catch(f){console.error(f),r(f)}finally{l=!0,u()}};let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let p=async g=>{var y;if(g.origin===a.origin)switch((y=g.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){H.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),g.data.message==="Timeout"&&H.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(g.data.message));break}}};window.addEventListener("message",p);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(H.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;H.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Dd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(sn()):ql.includes(r)||this.store.dispatch(ln(r))})}catch(r){this.handleError(r)}}};async function gk(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function hk(e,t,n={}){let r=n.replace?Jr(e,n.replace.start,n.replace.end):cs(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
|
|
27
|
+
`);break}default:break}p&&s++}return l(e),a}var DT=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(DT||{}),ar=class{constructor(t){this.element=t;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}triggerChange(){let t=this.getText(),n=this.getHTML(),r=t!==this.currentText;this.isActive&&(t===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&r&&!this.isSubmitting&&this.emit("change",{plainText:t}),r&&(this.currentSelection=this.getSelection()),this.currentText=t,this.isSubmitting=!1,(this.currentHTML!==n||n===null&&r)&&(this.emit("updated",{plainText:t}),this.triggerCaretPosition(),this.currentHTML=n))}triggerSelection(){let t=this.getSelection();(t.start!==this.currentSelection.start||t.end!==this.currentSelection.end)&&(this.currentSelection=t,this.emit("selection",t),this.triggerCaretPosition())}triggerCaretPosition(){let t=this.getCaretPosition();Ur(t,this.currentCaret)||(this.currentCaret=t,this.emit("caret",t))}handleKeyUp(t){let{key:n,shiftKey:r}=t;(n==="Enter"&&r===!0||n==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(DT).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(t={shouldObserve:!0}){this.addEventListener("keydown",r=>this.handleKeyDown(r)),this.addEventListener("keyup",r=>this.handleKeyUp(r)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",r=>this.handlePaste(r)),this.addEventListener("click",()=>this.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let n=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t!=null&&t.shouldObserve&&n.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{n.disconnect()}),this.currentSelection=this.getSelection()}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function FT(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var $o=class extends ar{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),xl(this.element,t)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let t=this.getRootNode();if(t.activeElement!==this.element)return null;let n="getSelection"in t?t.getSelection():window.getSelection();if(!n)return null;let r="getComposedRanges"in n&&t instanceof ShadowRoot?(i=n.getComposedRanges(t))==null?void 0:i[0]:n.rangeCount>0?n.getRangeAt(0):null;if(!r)return null;let o=this.element.ownerDocument.createRange();return o.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),o.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!o||!this.element.contains(o.startContainer)||!this.element.contains(o.endContainer)?null:o}getCaretPosition(){let t=this.getRange();if(!t||!t.collapsed||!("getBoundingClientRect"in t))return null;let n=t.getBoundingClientRect();return!FT(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!FT(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return wl(this.element,t);let n=this.lastKnownSelection;if(n&&_T(this.element,n.start,n.end))return n;let r=cs(this.element);return r.collapse(!1),wl(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return xl(this.element,Jr(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(t={shouldObserve:!0}){super.listen(t),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),t!=null&&t.shouldObserve&&this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let n=this.element.isContentEditable,r=new MutationObserver(()=>{this.element.isContentEditable!==n&&(n=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>r.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var qo=class extends ar{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:t,selectionEnd:n}=this.element;return{start:t,end:n}}getSelectedText(){let t=this.getSelection();return t?this.getText().slice(t.start,t.end):""}getCaretPosition(){return null}applyChanges(t){if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let t=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var o;return(o=t==null?void 0:t.get)==null?void 0:o.call(this.element)},set:o=>{var i;(i=t==null?void 0:t.set)==null||i.call(this.element,o),this.triggerChange()}});let n=this.element.disabled,r=new MutationObserver(()=>{this.element.disabled!==n&&(n=this.element.disabled,this.emit(n?"disabled":"enabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>r.disconnect())}};function HT(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function DN(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}var wy=class{constructor(t){this.name=t;this.broadcastChannel=new BroadcastChannel(t)}broadcastChannel;disposeHandlers=[];onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},xy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=HT(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},Ey=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),H.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new xy(t,this.deepdeskUrl,{debug:!0}):new wy(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=DN(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(H.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;H.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage({...o,channel:this.sessionId})}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},UT=Ey;var ds=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var Cy=e=>new Promise(t=>{setTimeout(t,e)});var fs=class extends ds{name="ClientError"},Ty=class extends ds{name="ServerError"},by=new Map;async function FN(e){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=await e.text();return n===""?null:(H.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))}var fn=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",{useCache:u=!1,abortLatest:c=!1,attempts:p=1,retryDelay:d=500,refreshTokenOn401:g=!0,retryOnError:y=C=>C instanceof TypeError,retryOnResponse:v=C=>C.status>=500,version:f="v1",...m}=n;if(u)if(l){if(by.has(s)){r(by.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h={credentials:"include",...m,headers:{"Content-Type":"application/json",...m.headers}};!l&&this.csrfToken&&(h.headers={...h.headers,"X-CSRFToken":this.csrfToken}),typeof f=="string"&&(h.headers={...h.headers,"X-Deepdesk-API-Version":f});let w=p,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=async()=>(w--,a(s,h).then(async C=>v(C)&&!i.isAborted&&w>0?(await Cy(d),T()):C.status===401&&g===!0&&x===!1?(x=!0,await this.refreshToken(),T()):C).catch(async C=>{if(y(C)&&!i.isAborted&&w>0)return await Cy(d),T();throw C}));T().then(async C=>{let k=await FN(C);if(delete this.latestRequestByUrl[s],C.status>=500){o(new Ty("Server Error",k));return}else if(C.status===401){o(new fs("Unauthorized",k));return}else if(C.status===403){o(new fs("Forbidden",k));return}else if(C.status===404){o(new fs("Not Found",k));return}else if(C.status>=400){o(new fs("Bad Request",k));return}u&&by.set(s,k),r(k)}).catch(C=>{o(C)})})}async validateToken(){let{has_valid_access_token:t}=await this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return e.refreshingToken||(e.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{e.refreshingToken=null},1e3*60)})),e.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,{method:"POST",body:JSON.stringify(n),...r})}patch(t,n,r){return this.request(t,{method:"PATCH",body:JSON.stringify(n),...r})}put(t,n,r){return this.request(t,{method:"PUT",body:JSON.stringify(n),...r})}delete(t,n){return this.request(t,{method:"DELETE",...n})}};var HN;(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||={})})(HN||={});function wf(e){return{...ee(e),tags:e.tags}}var lr=class e{constructor(t,n={}){this.options=n;this.client=new fn(t,{fetch:n.fetch}),this.client.patchFetch(r=>async(o,i)=>{let s=await r(o,i);return this.handleDeepdeskVersionHeaders(s),s})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=await this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(e.exchangeTokenPromise||(e.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),e.exchangeTokenPromise):Promise.resolve()}async createConversation(t){await this.preflight(),H.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...Re(t),tags:t.tags},{version:"v2"});return wf(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null,useCache:!0});return ee(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null,useCache:!0});return ee(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return ee(t)}async getAccount(){let t=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return ee(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null,useCache:!0});return ee(t)}async checkUserExists(t){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n}async getConversationBySessionId(t,n={}){await this.preflight(),H.info(`Getting conversation for session ${t}`);let{attempts:r=1,retryDelay:o=1e3}=n,i=await this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"});return H.info(`Successfully retrieved conversation ${i.id} for session ${t}`),wf(i)}async isConversationSupported(t,n={}){H.info(`Check if conversation for session ${t} is supported`);let{attempts:r=1,retryDelay:o=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"})).has_active_profile}async updateConversation(t,n){let r=Re(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return wf(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...Re(o),tags:o.tags})),{version:"v2"})).map(o=>wf(o))}async sendEvent(t,n){let{data:r,...o}=n,i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[a,l])=>({...s,[a]:l}),{});return this.client.post("/api/events",Re({...i,...o,data:r,name:t}),{version:"v2"})}async sendEventV1(t,n){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>({...o,[i]:s}),{});return this.client.post("/api/events",{event:t,data:Re({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){let r=await this.client.post("/api/summary",{conversation:{messages:t.filter(o=>o.text&&o.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model});return ee(r)}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(t){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw H.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.preflight(),await this.client.post("/apis/admin/session/api-key/",Re(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})}async getTextSuggestions(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(await this.client.post(`/api/conversations/${t}/recommend/${r}`,Re(n),{abortLatest:!0})).map(i=>({...ee(i),text:i.text||i.url||i.message,source:r,type:r})).filter((i,s,a)=>s===a.findIndex(l=>l.text===i.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(t,n){return(await this.client.post(`/api/conversations/${t}/autocomplete`,Re(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))}async getPinnedMessages(t){let n=await this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return ee(n).map(r=>({...r,text:r.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(t){let n=await this.client.post("/api/style-suggestions",Re(t),{abortLatest:!0});return ee(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,Re(t),{version:"v2"});return ee(n)}async knowledgeAssist(t,n,r,o={}){let i=await this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Re({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(s=>({question:s.question,answer:s.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return ee(i)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return ee(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return ee(t.token)}async getCsrfToken(){let{token:t}=await this.client.get("/apis/admin/session/csrf/",{version:null});return t}async verifyLoginToken(t){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return ee(n)}async evaluateRule(t,n,r,o={}){let i=new URLSearchParams;o.raiseForFailingConditions&&i.set("raise_for_failing_conditions","true");let s=await this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${i.toString()}`,r,{version:"v2"});return ee(s.cues)}async getRules(){let t=new URLSearchParams,n=await this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{version:null,useCache:!0});return ee(n)}async translateMessages(t){let n=await this.client.post("/api/translate",Re(t),{version:"v2"});return ee(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Vv);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&H.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var El=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(qg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,ee(o))}catch{H.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var UN;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(UN||={});var Cl=class{constructor(t,n={}){this.apiUrl=t;this.client=new fn(t,n)}client;streams={};logger=H;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return ee(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,Re(n));return ee(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,Re(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return ee(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",Re(t));return ee(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new El(`${this.apiUrl}/sessions/${t}/events`),this.streams[t].connect()),this.streams[t]}closeStream(t){this.streams[t]||(this.streams[t].disconnect(),delete this.streams[t])}};var zT={startTime:null,stopTime:null},BT=G({name:"handlingTime",initialState:zT,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(le,()=>zT)}}),{handlingTimeStart:jT,handlingTimeStop:xf,handlingTimeReset:VT}=BT.actions,KT=BT.reducer;var WT=(e={})=>{let t={onAuthError:Wi(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Ef={list:{keywordMatches:[]},fetchState:"idle"};var Go=z("styleSuggestions/getAll",async({text:e},t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),{showStyleSuggestions:o}=r.settings,i=(s=r.conversation.current)==null?void 0:s.profileCode;if(!o)return Ef.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),zN=G({name:"styleSuggestions",initialState:Ef,reducers:{},extraReducers:e=>{e.addCase(Go.pending,t=>{t.fetchState="loading"}).addCase(Go.rejected,t=>{t.fetchState="error"}).addCase(Go.fulfilled,(t,n)=>{t.fetchState="done",Ur(t.list,n.payload)||(t.list=n.payload)}).addCase(ko,t=>{t.list=Ef.list}).addCase(le,()=>Ef)}}),$T=zN.reducer;var qT=(e={})=>{let t,n=!0,r={getStyleSuggestions:Go,debounce:500,...e};return o=>i=>s=>{var g;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(!((g=u.conversation.current)==null?void 0:g.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function BN(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var GT=(e={})=>{let t={getTextSuggestions:ln,getAutocompleteSuggestions:el,debounce:200,check:rs,...e},n;return r=>o=>i=>{var v;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,p=(v=l.conversation.current)==null?void 0:v.id,d=i.type===Hd.toString();if(!p||!u&&!c)return a;let{input:{userCommitted:g}}=l;return BN(g,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let f=Gi(l);f===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(f))},d?0:t.debounce)),a}};var XT=Go.fulfilled.toString();function jN(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var YT=e=>t=>n=>r=>{var u;if(r.type!==XT){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=jN(o,s);r.type===XT&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var VN=pc({answer:lC,auth:u1,autoflows:Tb,conversation:v1,contentTypes:yE,customMessages:Nb,passwordlessToken:Hb,entities:KE,knowledgeAssistant:iC,handlingTime:KT,info:U1,input:O1,settings:n1,profile:fC,search:$1,summary:QE,styleSuggestions:$T,ui:FC,rules:jb,textSuggestions:wC});function QT(e){return lx({reducer:VN,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),WT(),GT({debounce:200}),qT({debounce:500}),YT(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var KN=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},WN=e=>t=>n=>r=>{var a,l,u,c,p;let o=t.getState(),i=zg("inlineSuggestions")(o);switch(r.type){case Wi.toString():{!r.payload&&e.emit("logout",void 0);break}case sn.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 Ye.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 Qc.toString():e.handleKeyDown(r.payload);break;case ko.toString():e.logSendMessage(r.payload);break;case Zc.toString():e.handleInputChanged(r.payload);break;case Ko.fulfilled.toString():r.isBroadcasted||e.broadcast(Yg,r,!1),e.emit("cues",r.payload);break;default:break}let s=n(r);switch(r.type){case ko.toString():e.handleAfterSendMessage(r.payload);break;case nl.toString():e.onUpdateShowTabHint(r.payload);break;case xf.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case Cn.toString():{let{start:d,end:g}=o.input.selection;e.emit("select-suggestion",{type:KN(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:d,end:g}:{start:0,end:g}},{mayApplyChanges:!0}),i&&(t.dispatch(En([])),t.dispatch(Wn()));break}case Yc.toString():{let{start:d,end:g}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:d,end:g}:{start:0,end:g}},{mayApplyChanges:!0});break}case Aa.toString():{let d=t.getState(),{text:g,selection:y}=d.input.userCommitted;e.emit("reset",{text:g,selectionAfter:y},{mayApplyChanges:!0});break}case Jc.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:(c=o.conversation.current)==null?void 0:c.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case En.toString():{i&&r.payload.length>0&&t.dispatch(Br(0));break}case Yn.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(p=o.conversation.current)==null?void 0:p.id,data:{summary:r.payload.summary,model:t.getState().summary.model}});break}default:break}return s},ZT=WN;function ky(e){return e.toISOString().replace("T"," ").replace("Z","")}function JT(e,t){var i,s,a,l;let n=(i=e.conversation.current)==null?void 0:i.id;if(!n)return H.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:o}=e.handlingTime;return!r||!o?(H.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:n,clientVersion:t.version,agentId:(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:ky(r),timeStop:ky(o)}}function ek(e,t,n){var I,L,_,W;let r=(I=t.conversation.current)==null?void 0:I.id;if(!r)return H.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:i,numCharsPasted:s,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:d,cuts:g,deletions:y,textSuggestions:v,offeredTextSuggestions:f}}=t[e],m=o.length,w=v.reduce((V,{text:Z,searchTerm:ur})=>V+Z.length-(ur?ur.length:0),0),x=c??Date.now(),T=(Date.now()-x)/1e3+(p||0),C=i/T,k=v.reduce((V,{searchTerm:Z})=>V+(Z?Z.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:g,deletions:y,lenTextTyped:i+k,lenTextTotal:m,lenTextAssisted:w,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:T,charsPerSecond:C,numPastes:u,textSuggestionsV2:v,suggestionsCounters:[{source:"gpt",countOffered:f.filter(V=>V.source==="gpt").length}],agentId:(L=t.info.agentInfo)==null?void 0:L.agentId,agentName:(_=t.info.agentInfo)==null?void 0:_.agentName,agentEmail:(W=t.info.agentInfo)==null?void 0:W.agentEmail}}function Py(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Py(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Py(o,t):null}function tk(e,t){return Py(e,t)}function nk(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function $N(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Cf(e){return $N(e)&&(Xr(e)||$d(e))}var ok,Rn=new Map,qN=["bottom","height","left","right","top","width"],rk=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:qN.some(n=>e[n]!==t[n]);function ik(e){var n,r;if(e.ownerDocument===document)return[];let t=((r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)??null;return t?[t,...ik(t)]:[]}function sk(e,t){return!e||!t?null:{...e,top:e.top+t.top,left:e.left+t.left}}var bf=!1,ak=()=>{bf=!0;let e=[];if(Rn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Rn.delete(n);return}let r=n.getBoundingClientRect();rk(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(sk,t.rect):t.rect;rk(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Rn.size===0){bf=!1;return}ok=window.requestAnimationFrame(ak)};function Ry(e,t){let n=ik(e),r=[],o=n.map((i,s)=>Ry(i,a=>{r[s]=a;let l=Rn.get(e);if(!l)return;let u=r.reduce(sk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Rn.has(e)){let s=Rn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Rn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!bf&&ak()},unobserve(){o.forEach(s=>s.unobserve());let i=Rn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Rn.delete(e),Rn.size||(cancelAnimationFrame(ok),bf=!1)}}}}var lk,An=new Map,uk=()=>{An.forEach((e,t)=>{if(!t.isConnected){An.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),An.size!==0&&(lk=window.requestAnimationFrame(uk))};function ck(e,t){return{observe(){let n=An.size===0;An.has(e)?An.get(e).callbacks.push(t):An.set(e,{visible:void 0,callbacks:[t]}),n&&uk()},unobserve(){let n=An.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||An.delete(e),An.size||cancelAnimationFrame(lk)}}}}var Ay=["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 Ly(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function ps(e){return parseFloat(e)}function Tf(e){return Math.round(e*1e6)}function dk(e){return e/1e6}function Iy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=ps(e.width),i=ps(e.borderLeftWidth),s=ps(e.borderRightWidth),a=ps(e.paddingRight),l=dk(Tf(o)-Tf(i)-Tf(s)),u=dk(Tf(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function bl(e,t={}){var c;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=t.position??"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Bo(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};Ly(r,n,Ay),Iy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=ck(e,()=>{Ly(r,n,Ay),Iy(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=Ry(e,p=>{if(p===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),p.height===0&&p.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(Ly(r,n,Ay),Iy(r,e,n),i(),n.style.top=`${p.top}px`,n.style.left=`${p.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let d=t.closestScrollElement.getBoundingClientRect(),g=window.getComputedStyle(t.closestScrollElement),y=ps(g.borderTopWidth),v=ps(g.borderBottomWidth),f=d.top+y-p.top,m=p.top+p.height+-(d.top+d.height-v);n.style.clipPath=`inset(${f}px 0px ${m}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(c=e.parentElement)==null||c.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var fk=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch{return t}}catch{return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch{H.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function GN(e){return e.offsetParent!==null}function pk(e){if(!GN(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 kf(e,t,n=100){let r=pk(e);t({isVisible:r});let o=setInterval(()=>{let i=pk(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Le=S(b());var mk=fk("showTabHint",!0),Tl=class e{static version="11.5.4";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new lr(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[ZT({broadcast:(p,d,g)=>{this.broadcastEvents.send(p,d,g)},emit:(p,d,g)=>this.emit(p,d,g),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),onUpdateShowTabHint:p=>mk.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Cl(n)}),this.store=QT(c),this.broadcastEvents=new UT({debug:!0,deepdeskUrl:u,eventMap:q1(this.store),createCustomChannel:l}),this.store.dispatch(nl(mk.value())),this.store.dispatch(jc({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(H.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(H.warn("Profile has not been loaded (yet)"),!0):(H.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Wi(null)),this.store.dispatch(Vn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();tt(r)&&r1(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(Vn())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){H.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Kg({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Wc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch($c({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Wg(t))).payload}async postMessages(t){return(await this.store.dispatch(Gc(t))).payload}async updateConversation(t){return(await this.store.dispatch(qc(t))).payload}resetConversation(){this.store.dispatch(le()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(Yn());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(jc(t))}setVisitorInfo(t){this.store.dispatch(F1(t))}setCustomData(t){this.store.dispatch(H1(t))}async setAgentInfo(t){await this.store.dispatch(La(t))}async setAgentSettings(t){await this.store.dispatch(Gg(t))}async getAgentSettings(){return(await this.store.dispatch(Xg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(Hd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(Zc(t))}notifyKeyDown(t){this.store.dispatch(Qc(t))}notifyPaste(t,n){this.store.dispatch(A1({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(P1(t))}notifyExternalSuggestion(t){this.store.dispatch(Cn(t)),this.store.dispatch(Wn())}async evaluateRule(t,n={}){let{payload:r,error:o}=await this.store.dispatch(Ko({label:t,params:n}));if(o)throw new Error(o.message);return r}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(qr({collapse:!1})),this.inputMediator&&this.store.dispatch(E1({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(En([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(R1(S1(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(b1()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(k1()),t.preventDefault(),!s&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Aa()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(Br(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Br(-1)),this.store.dispatch(Aa()),t.preventDefault()):n||(this.store.dispatch(qr({collapse:!0})),this.store.dispatch(_C(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:g}=this.state.input;this.store.dispatch(nl(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&g&&g.text.startsWith(d)&&(this.store.dispatch(Cn({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(Wn())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(L1()),this.store.dispatch(En([]))}handlingTimeStart(){this.state.handlingTime.startTime||(H.info("Start handling time"),this.store.dispatch(jT()))}handlingTimeStop(){this.state.handlingTime.startTime&&(H.info("Stop handling time"),this.store.dispatch(xf()))}logSendMessage(t){let n=ek("input",this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n))}logHandlingTime(){let t=JT(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(VT()))}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(Wn()),this.store.dispatch(ko(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Cn({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{let i=this.eventListeners[t];i&&i.forEach(s=>{try{s(n)}catch(a){H.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),H.error(a)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=bl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,qt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=bl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,qt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Bo(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,qt.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),H.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(H.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(M1(r.metrics))):H.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Cf(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:d,insertLink:g,inputMediator:y,closestScrollSelector:v,appendOverlayTo:f,inlineSuggestions:m,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:g,isEmbedded:p,inlineSuggestions:m,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Bo(t),this.inputMediator=y||(Xr(t)?new qo(t):new $o(t)),this.inputMediator.on("change",({plainText:T})=>{this.notifyInputChanged(T)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(I1({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",T=>{this.notifyKeyDown(T)}),this.inputMediator.on("paste",({pastedText:T,selectionText:C})=>{this.notifyPaste(T,C)}),this.inputMediator.on("cut",({selectionText:T})=>{this.notifyCut(T)});let w=v&&tk(t,v)||void 0;if(m){let{customStyles:T,appendOverlayTo:C}=n;if(Xr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let k=this.createInlineContainer(t,"deepdesk-caret");(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:T,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(VC,{})})}),k),this.inputMediator.on("caret",L=>{this.store.dispatch(En([])),L?(k.style.display="block",k.style.top=`${L.top}px`,k.style.left=`${L.left}px`):k.style.display="none"});let I=this.overlayContainerFactory("floating-menu",w||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:C},T==null?void 0:T.floatingMenuRootNode);(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:T,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(MC,{onLogIn:()=>this.loginViaPopup().catch(L=>H.warn(L.message))})})}),I)}else{let T=this.overlayContainerFactory("deepdesk-tab-completion",w||t,{appendTo:f,closestScrollElement:w,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",w||t,{appendTo:f},r==null?void 0:r.suggestionsRootNode);(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:r,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(Sb,{inputElement:t})})}),T),(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:r,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(ZC,{onLogIn:()=>this.loginViaPopup().catch(k=>H.warn(k.message))})})}),C)}(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:r,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(PC,{})})}),this.createContainer("deepdesk-overlays"));let x;this.inputMediator.on("selection",T=>{clearTimeout(x),T===null?x=setTimeout(()=>{T!==null&&this.store.dispatch($g(T))},500):this.store.dispatch($g(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(Fh(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Fh(!0))),this.store.dispatch(C1({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(Wn()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var T;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((T=this.state.conversation.current)==null?void 0:T.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&H.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:r,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(NT,{onLogIn:()=>this.loginViaPopup().catch(s=>H.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,qt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=kf(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){nk(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Ja());let t=Jn(this.state);t&&(await this.store.dispatch(Ya()),this.store.dispatch(jc({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(t){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};i.onmessage=async g=>{var y,v;if((y=g.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=g.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Ma),l=!0,o.port1.close(),n()}catch(f){console.error(f),r(f)}finally{l=!0,u()}};let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let p=async g=>{var y;if(g.origin===a.origin)switch((y=g.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){H.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),g.data.message==="Timeout"&&H.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(g.data.message));break}}};window.addEventListener("message",p);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(H.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;H.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Dd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(sn()):ql.includes(r)||this.store.dispatch(ln(r))})}catch(r){this.handleError(r)}}};async function gk(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function hk(e,t,n={}){let r=n.replace?Jr(e,n.replace.start,n.replace.end):cs(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
|
|
28
28
|
`).reverse().forEach((s,a)=>{a>0&&r.insertNode(document.createElement("br")),r.insertNode(document.createTextNode(s))}):r.insertNode(document.createTextNode(t))};return Promise.resolve(i()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let s=n.selectionAfter?Jr(e,n.selectionAfter.start,n.selectionAfter.end):(r.collapse(!1),r),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(s)}if(!o)return;o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function XN(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 YN(e){let t=document.createDocumentFragment();return e.split(`
|
|
29
29
|
`).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},i=0;for(;o=n.slice(i).match(/(\[([^\]]+)])\(([^)]+)\)/);){let s=document.createElement("a");s.href=o[3],s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer"),s.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(i,i+o.index))),t.appendChild(s),i=i+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(i)))}),t}function yk(e,t){let n=e.parentElement;if(!n){console.warn("No insert point found");return}let{display:r}=window.getComputedStyle(n);r.includes("block")||r==="table-cell"?n==null||n.insertBefore(t,e.nextSibling):yk(n,t)}async function vk(e,t,{isBlock:n,isHTML:r}={}){let o;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let i=()=>{let s=e.ownerDocument.defaultView??window,a=s.getSelection();if((!a||a.rangeCount===0)&&(e.focus(),a=s.getSelection()),!a||a.rangeCount===0)return;let l=a.getRangeAt(0);if(!l)return;o=document.createElement("span"),l.insertNode(o);let u=r?XN(t):YN(t);n?yk(l.startContainer,u):(l.insertNode(u),l.collapse(!1))};return Promise.resolve(i()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!o)try{o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function Sk(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function wk(e,t,n){await new lr(e).authenticateWithKey(t,n)}async function xk(e){let n=await new fn(e).get("/platform/config/",{version:null,useCache:!0});return ee(n)}async function QN(e){let n=await(e.fetch??window.fetch)(e.url),r=await n.blob();return new File([r],e.name,{type:e.mimeType??n.headers.get("Content-Type")??"image/jpeg"})}async function Ek(e,t){let n=await QN(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}}return Fk(ZN);})();
|
|
30
30
|
/*! Bundled license information:
|