@deepdesk/deepdesk-sdk 12.0.1 → 12.0.2-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +5 -5
- package/dist/index.esm.js +5 -5
- 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
|
`+ct),Qt&&vf([G,Z,se],uo=>{ct=Sl(ct,uo," ")}),S&&Ul?S.createHTML(ct):ct},t.setConfig=function(){let j=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ff(j),Fl=!0},t.clearConfig=function(){oi=null,Fl=!1},t.isValidAttribute=function(j,E,I){oi||Ff({});let U=De(j),me=De(E);return Qy(U,me,I)},t.addHook=function(j,E){typeof E=="function"&&(D[j]=D[j]||[],vl(D[j],E))},t.removeHook=function(j){if(D[j])return pT(D[j])},t.removeHooks=function(j){D[j]&&(D[j]=[])},t.removeAllHooks=function(){D={}},t}var CT=bT();var oo=w(H());var kM={"":["<em>","</em>"],_:["<strong>","</strong>"],"*":["<strong>","</strong>"],"~":["<s>","</s>"],"\n":["<br />"]," ":["<br />"],"-":["<hr />"]};function TT(e){return e.replace(RegExp("^"+(e.match(/^(\t| )+/)||"")[0],"gm"),"")}function xl(e){return(e+"").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function El(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||{},m=0;function d(v){var y=kM[v[1]||""],g=l[l.length-1]==v;return y?y[1]?(g?l.pop():l.push(v),y[0|g]):y[0]:v}function f(){for(var v="";l.length;)v+=d(l[l.length-1]);return v}for(e=e.replace(/^\[(.+?)\]:\s*(.+)$/gm,function(v,y,g){return c[y.toLowerCase()]=g,""}).replace(/^\n+|\n+$/g,"");o=a.exec(e);)r=e.substring(m,o.index),m=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()+'"':"")+">"+TT(xl(s).replace(/^\n+|\n+$/g,""))+"</code></pre>":(s=o[6])?(s.match(/\./)&&(o[5]=o[5].replace(/^\d+/gm,"")),i=El(TT(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="'+xl(o[8])+'" alt="'+xl(o[7])+'">':o[10]?(u=u.replace("<a>",'<a href="'+xl(o[11]||c[r.toLowerCase()])+'">'),n=f()+"</a>"):o[9]?n="<a>":o[12]||o[14]?n="<"+(s="h"+(o[14]?o[14].length:o[13]>"="?1:2))+">"+El(o[12]||o[15],c)+"</"+s+">":o[16]?n="<code>"+xl(o[16])+"</code>":(o[17]||o[1])&&(n=d(o[17]||"--"))),u+=r,u+=n;return(u+e.substring(m)+f()).replace(/^\n+|\n+$/g,"")}var kT={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 In=w(b());function PM(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 Ey(e){var n;let t=e.cloneNode(!0);return t.querySelectorAll("div,button").forEach(r=>r.remove()),(n=t.textContent)!=null?n:""}function RM(e){return e.replace(/\r\n/g,`
|
|
25
25
|
`)}var AM=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let i=A("Markdown",kT),s=(0,oo.useRef)(null),[a,l]=(0,oo.useState)(null),u=(0,oo.useMemo)(()=>{let y=El(RM(e));return CT.sanitize(y).replace(/<\/code>/g,`${PM(i.copyIcon)}</code>`)},[e]),c=y=>{var h;let g=y.target,p=!!((h=s.current)!=null&&h.querySelector("code"));a||p&&g.tagName!=="CODE"||!p&&g!==s.current||(g.addEventListener("mouseleave",()=>l(null),{once:!0}),l(g))},m=()=>{if(!a)return;l(null);let y=a.querySelector("button");y&&(ls(y,i.fadeup),r(Ey(a)))},d=y=>{y.target.tagName.toLowerCase()==="button"&&(ls(y.target,i.fadeup),r(Ey(y.target.parentElement)))},f=()=>{a&&(l(null),o(Ey(a)))},v=y=>{if(y===null)return;let g=y.getBoundingClientRect();g.left<0?y.style.transform=`translateX(${-g.left+2}px)`:g.right>window.innerWidth&&(y.style.transform=`translateX(${window.innerWidth-g.right-2}px)`)};return(0,In.jsxs)(oo.Fragment,{children:[a&&(0,In.jsxs)(vs,{triggerRef:{current:a},className:i.popover,parentNode:a,children:[(0,In.jsxs)("div",{className:i.options,ref:v,children:[(0,In.jsx)("button",{type:"button",className:i.option,onClick:m,children:n}),(0,In.jsx)("div",{className:i.divider}),(0,In.jsx)("button",{type:"button",className:i.option,onClick:f,children:t})]}),(0,In.jsx)("div",{className:i.arrow})]}),(0,In.jsx)("div",{ref:s,className:i.root,dangerouslySetInnerHTML:{__html:u},onMouseOver:c,onClick:d})]})},PT=AM;var by={};$e(by,{enUS:()=>LM,nlNL:()=>IM});var LM={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"}]},IM={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 RT={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",thumbsUp:"dd-6QwVx",thumbsDown:"dd-d3E8l"};var gn=w(b()),NM=({cue:e,onRemove:t,onCopy:n,onUse:r})=>{let o=A("WidgetCue",RT),i=q(by),s=us(),a=c=>{n&&n(c,e)},l=c=>{r&&r(c,e)},u=c=>{c.preventDefault(),c.stopPropagation(),t(e)};return(0,AT.useEffect)(()=>{s("Assistant response displayed",{name:e.rule.name,description:e.rule.description,group:e.rule.label,cueText:e.text})},[]),(0,gn.jsxs)(oe,{"data-testid":"cue",children:[(0,gn.jsx)(ye,{children:(0,gn.jsxs)(ye.Content,{children:[e.title&&(0,gn.jsx)(ye.Title,{className:o.title,"data-testid":"widget-cue-title",children:e.title}),(0,gn.jsx)(PT,{content:e.text,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:a,onUse:l})]})}),(0,gn.jsxs)(oe.IconButtonContainer,{children:[(0,gn.jsx)(ds,{eventName:"Assistant response feedback",eventData:{name:e.rule.name,group:e.rule.label,description:e.rule.description,cueText:e.text},feedbackText:e.text,feedbackType:"assistant"}),(0,gn.jsx)(oe.IconButton,{title:i("removeCue"),onClick:u,icon:(0,gn.jsx)(dT,{})})]})]})},LT=NM;var bl=w(b()),OM=({cues:e})=>{let t=X(),n=Wt(),r=us(),o=a=>{t($C({id:a.rule.id})),r("Assistant response closed",{name:a.rule.name,group:a.rule.label,description:a.rule.description,cueText:a.text})},i=(a,l)=>{Yn(a),r("Assistant response copied",{name:l.rule.name,group:l.rule.label,description:l.rule.description,copiedText:a})},s=(a,l)=>{n.send(Gr,{text:a,suggestion:{source:"cue",sourceText:a}}),r("Assistant response used",{name:l.rule.name,group:l.rule.label,description:l.rule.description,usedText:a})};return(0,bl.jsx)(bl.Fragment,{children:e.map(a=>(0,bl.jsx)(LT,{cue:a,onRemove:o,onCopy:i,onUse:s},a.rule.id))})},IT=OM;var Ef=w(H());var NT={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var hn=w(b());function MM(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var OT=({data:e,schema:t})=>{let n=A("WidgetCustomData",NT),r=o=>{Yn(o)};return(0,Ef.useEffect)(()=>{z.info("Custom data",e,t)},[e]),(0,hn.jsx)("dl",{className:n.root,children:t.map(o=>{let i=MM(e,o.path);return(0,hn.jsxs)(Ef.Fragment,{children:[(0,hn.jsx)("dt",{className:n.label,children:o.label}),(0,hn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&i?(0,hn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!i?(0,hn.jsx)("span",{className:n.isFalse,children:o.falseValue}):i?(0,hn.jsxs)("button",{type:"button",onClick:()=>r(i),className:n.copyButton,children:[(0,hn.jsx)("span",{children:i}),(0,hn.jsx)(hl,{})]}):"-"})]},o.label)})})};var _T=w(H());var _M=/(https?:\/\/[^\s]+)/,MT=e=>e.split(" ").find(t=>_M.test(t));var Xt=w(b()),DM=({suggestion:e,lines:t,onUse:n})=>{var c;let r=e.text||e.url||e.message,o=MT(r),i=q(Vo),s=V("showImages"),a=V("fallbackImage"),l=m=>{m.preventDefault(),m.stopPropagation(),n(r)},u=(0,_T.useCallback)(m=>{window.open(o,"_blank"),m.stopPropagation(),m.preventDefault()},[o]);return(0,Xt.jsxs)(oe,{onClick:l,"data-testid":"edit-suggestion",children:[(0,Xt.jsxs)(ye,{children:[s&&e.image&&(0,Xt.jsx)(ye.Image,{src:df(e,"small",a||void 0),title:e.title}),(0,Xt.jsxs)(ye.Content,{children:[e.title&&(0,Xt.jsx)(ye.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((c=e.searchKeywords)==null?void 0:c.length)>0&&(0,Xt.jsx)(oe.Labels,{labels:e.searchKeywords}),(0,Xt.jsx)(ye.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,Xt.jsxs)(oe.Actions,{children:[o&&(0,Xt.jsx)(oe.ActionButton,{onClick:u,label:i("visitUrl")}),(0,Xt.jsx)(oe.ActionButton,{primary:!0,onClick:l,label:i("useSuggestion")})]})]})},DT=DM;var Cl=w(b()),FM=({lines:e,suggestions:t})=>{let n=Wt(),r=(o,i)=>{n.send(Gr,{text:o,suggestion:O(P({},i),{source:i.source,sourceText:i.text})})};return(0,Cl.jsx)(Cl.Fragment,{children:t.map(o=>(0,Cl.jsx)(DT,{suggestion:o,lines:e,onUse:i=>r(i,o)},o.text||o.url||o.message))})},FT=FM;var Tl={};$e(Tl,{enUS:()=>HM,nlNL:()=>UM});var HM={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"}]},UM={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 kl={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",sectionList:"dd-bF9pF",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",link:"dd-DRo0x"};var $=w(b()),bf=(e,t)=>{let n=M(rt);(0,Pl.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},zM=({onLogIn:e})=>{let t=A("Widget",kl),n=V("isEmbedded"),r=V("adminUrl");return(0,$.jsx)("div",{className:t.loginText,children:(0,$.jsx)("div",{children:(0,$.jsx)(Qd,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},HT=({text:e})=>{let t=A("Widget",kl);return(0,$.jsx)("div",{className:t.stateText,children:(0,$.jsx)("div",{children:(0,$.jsx)("p",{children:e})})},"notification")},BM=()=>{let e=q(Tl),t=X(),n=A("Widget",kl),r=V("showSearch"),o=V("showSummaryCommand"),i=V("showKnowledgeSearch"),s=M(cs("/admin/")),a=Wt(),l=V("productName"),u=r||o||i||s;return bf(()=>(t(iy()),()=>{t(BC())}),[t]),u?(0,$.jsx)(vn,{title:e("actions"),type:"shortcuts",children:(0,$.jsxs)("div",{className:n.shortcutList,children:[r&&(0,$.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-search","aria-label":e("linkSearch"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0}),children:[(0,$.jsx)(ss,{}),e("linkSearch")]}),o&&(0,$.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,$.jsx)(cT,{}),e("linkSummary")]}),i&&(0,$.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,$.jsx)(uT,{}),e("linkKnowledgeSearch")]}),s&&(0,$.jsxs)("a",{className:n.shortcut,target:"_blank",href:s,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:l}),rel:"noreferrer",children:[(0,$.jsx)(lT,{}),e("linkStudioLogin",{productName:l})]})]})}):null},jM=()=>{let e=X(),t=V("showCustomMessages"),n=M(NC),r=M(Zi);return bf(()=>(e(gl(r)),e(FC(r)),()=>{e(HC(r))}),[e,t,r]),!t||n.length===0?null:(0,$.jsx)(vn,{type:"custom-messages","data-testid":"custom-messages",children:(0,$.jsx)(mt,{withDivider:!0,children:n.map(o=>(0,$.jsx)(iT,{suggestion:o},o.text))})})},VM=()=>{let e=q(Tl),t=X(),n=V("showAutoflows"),r=M(PC),o=M(Zi);return bf(()=>(t(cr(o)),t(RC(o)),()=>{t(AC(o))}),[t,n,o]),!n||r.length===0?null:(0,$.jsx)(vn,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:(0,$.jsx)(mt,{withDivider:!0,children:(0,$.jsx)(rT,{})})})},KM=()=>{let e=X(),t=M(zd),n=M(fb),r=M(KC),o=M(F1),i=M(Hd),s=M(Bd),a=M(or),l=M(qr);return(0,Pl.useEffect)(()=>{!!o&&!n&&z.warn("Custom data provided, but no schema.")},[o,n]),bf(()=>{t.forEach(({type:u})=>{u==="entities"?e(cn()):nu.includes(u)||e(fn(u))})},[e,l,a]),(0,$.jsx)(Pl.Fragment,{children:t.map(({type:u,title:c,amount:m,lines:d,schema:f})=>{var v,y;switch(u){case"entities":return i&&i.length>0&&(0,$.jsx)(vn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,$.jsx)(aT,{entities:i})},u);case"cues":return r&&r.length>0&&(0,$.jsx)(vn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,$.jsx)(mt,{withDivider:!0,children:(0,$.jsx)(IT,{cues:r})})},u);case"custom-data":return o&&f&&(0,$.jsx)(vn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,$.jsx)(mt,{withDivider:!0,children:(0,$.jsx)(OT,{data:o,schema:f})})},u);default:return((y=(v=s[u])==null?void 0:v.suggestions)==null?void 0:y.length)>0&&(0,$.jsx)(vn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,$.jsx)(mt,{withDivider:!0,children:(0,$.jsx)(FT,{lines:d,contentType:u,suggestions:s[u].suggestions.slice(0,m)||[]})})},u)}})})},WM=({onLogIn:e})=>{let t=q(Tl),n=A("Widget",kl),r=M(Ji),o=M(rt),i=M(Zi),s=M(or);return r===!1?(0,$.jsx)(HT,{text:t("notSupported")}):o===!1?(0,$.jsx)(zM,{onLogIn:e}):!s||!i||o===null?(0,$.jsx)(HT,{text:t("waiting")}):(0,$.jsx)("div",{className:(0,UT.default)(n.root),"data-testid":"widget",children:(0,$.jsxs)(Jl,{className:n.sectionList,children:[(0,$.jsx)(BM,{}),(0,$.jsx)(jM,{}),(0,$.jsx)(VM,{}),(0,$.jsx)(KM,{})]})})},zT=WM;function Ss(e){let t=new Range;return t.selectNodeContents(e),t}function BT(e,t,n){try{return io(e,t,n),!0}catch(r){return!1}}function Cf(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function Tf(e){return"tagName"in e&&e.tagName==="BR"}var Rl=/[\u200B-\u200D\uFEFF]/g;function io(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,i=!1;function s(l,u){let c=-1,m=/[\u200B-\u200D\uFEFF]/;if(!m.test(l))return u;for(let d=0;d<=l.length;d++)if(m.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(Rl,""),m=o+c.length,d=t>=o&&t<=m,f=n>=o&&n<=m;if(d){let v=s(u,t-o);v===0&&!f?r.setStartBefore(l):r.setStart(l,v)}f&&(r.setEnd(l,s(u,n-o)),i=!0),o=m;break}case Node.ELEMENT_NODE:{if(Tf(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;Cf(l)&&u&&!Cf(u)&&!Tf(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function Al(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(m){let d=m===n,f=m===o;switch(m.nodeType){case Node.TEXT_NODE:{let v=m.textContent;d&&(a=u+v.substring(0,r).replace(Rl,"").length),f&&(l=u+v.substring(0,i).replace(Rl,"").length),u+=v.replace(Rl,"").length;break}case Node.ELEMENT_NODE:{let v=m.nextSibling===null;Tf(m)&&!v&&u++;for(let y=0;y<m.childNodes.length;y++){let g=d&&y===r,p=f&&y===i;if(g&&(a=u),p&&(l=u),l!==void 0||((!g||!s)&&c(m.childNodes[y]),f&&y===i-1&&(l=u),l!==void 0))break}!f&&Cf(m)&&!v&&u++,f&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:l,end:l}}function Ll(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,m=u===o;switch(c&&s++,u.nodeType){case Node.TEXT_NODE:{if(s!==0)return;let d=c?r:0,f=m?i:void 0,v=u.textContent.replace(Rl,"");d===0&&f===void 0?a+=v:a+=v.substring(d,f);break}case Node.ELEMENT_NODE:{let d=u.nextSibling===null;s===0&&Tf(u)&&!d&&(a+=`
|
|
26
26
|
`);for(let f=c?r:0;f<(m?Math.min(i,u.childNodes.length):u.childNodes.length)&&(l(u.childNodes[f]),s!==1);f++);!m&&s===0&&Cf(u)&&!d&&(a+=`
|
|
27
|
-
`);break}default:break}m&&s++}return l(e),a}var jT=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(jT||{}),fr=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.getCaretPosition();this.isActive&&(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText&&(this.cachedText=t,this.cachedHTML=n,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,this.emit("selection",r)),$r(o,this.cachedCaretPosition)||(this.cachedCaretPosition=o,this.emit("caretposition",o)))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(jT).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function VT(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Yo=class extends fr{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Ll(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var s;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(s=r.getComposedRanges(n))==null?void 0:s[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!VT(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!VT(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return Al(this.element,n);let r=this.lastKnownSelection;if(r&&BT(this.element,r.start,r.end))return r;let o=Ss(this.element);return o.collapse(!1),Al(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Ll(this.element,io(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(()=>{setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var Qo=class extends fr{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return null}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var i;return(i=n==null?void 0:n.get)==null?void 0:i.call(this.element)},set:i=>{var s;(s=n==null?void 0:n.set)==null||s.call(this.element,i),this.handleInteraction()}});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function KT(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 $M(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var Cy=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Ty=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=KT(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},ky=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),z.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 Ty(t,this.deepdeskUrl,{debug:!0}):new Cy(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=$M(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(z.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;z.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(P({},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)}},WT=ky;var ws=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var Py=e=>new Promise(t=>{setTimeout(t,e)});var xs=class extends ws{constructor(){super(...arguments);this.name="ClientError"}},Ay=class extends ws{constructor(){super(...arguments);this.name="ServerError"}},Ry=new Map;function qM(e){return k(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(z.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var so=class so{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",C=n,{useCache:u=!1,abortLatest:c=!1,attempts:m=1,retryDelay:d=500,refreshTokenOn401:f=!0,retryOnError:v=R=>R instanceof TypeError,retryOnResponse:y=R=>R.status>=500,version:g="v1"}=C,p=te(C,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(Ry.has(s)){r(Ry.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h=O(P({credentials:"include"},p),{headers:P({"Content-Type":"application/json"},p.headers)});!l&&this.csrfToken&&(h.headers=O(P({},h.headers),{"X-CSRFToken":this.csrfToken})),typeof g=="string"&&(h.headers=O(P({},h.headers),{"X-Deepdesk-API-Version":g}));let S=m,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=()=>k(this,null,function*(){return S--,a(s,h).then(R=>k(this,null,function*(){return y(R)&&!i.isAborted&&S>0?(yield Py(d),T()):R.status===401&&f===!0&&x===!1?(x=!0,yield this.refreshToken(),T()):R})).catch(R=>k(this,null,function*(){if(v(R)&&!i.isAborted&&S>0)return yield Py(d),T();throw R}))});T().then(R=>k(this,null,function*(){let N=yield qM(R);if(delete this.latestRequestByUrl[s],R.status>=500){o(new Ay("Server Error",N));return}else if(R.status===401){o(new xs("Unauthorized",N));return}else if(R.status===403){o(new xs("Forbidden",N));return}else if(R.status===404){o(new xs("Not Found",N));return}else if(R.status>=400){o(new xs("Bad Request",N));return}u&&Ry.set(s,N),r(N)})).catch(R=>{o(R)})})}validateToken(){return k(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/",{version:null});return!!n})}refreshToken(){return so.refreshingToken||(so.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{so.refreshingToken=null},1e3*60)})),so.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,P({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,P({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,P({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,P({method:"DELETE"},n))}};so.refreshingToken=null;var yn=so;var $T;(t=>{let e;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||(t.EventType={}))})($T||($T={}));function kf(e){return O(P({},re(e)),{tags:e.tags})}var Zo=class Zo{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new yn(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>k(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return k(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(Zo.exchangeTokenPromise||(Zo.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),Zo.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return k(this,null,function*(){yield this.preflight(),z.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",O(P({},Ne(t)),{tags:t.tags}),{version:"v2"});return kf(n)})}getProfile(t){return k(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{version:null,useCache:!0});return re(n)})}getKnowledgeAssistant(t){return k(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null,useCache:!0});return re(n)})}getContentTypes(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return re(t)})}getAccount(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{version:null,useCache:!0});return re(t)})}getPlatformConfig(){return k(this,null,function*(){let{config:t}=yield this.client.get("/platform/config/",{version:null,useCache:!0});return re(t)})}checkUserExists(t){return k(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n})}getConversationBySessionId(r){return k(this,arguments,function*(t,n={}){yield this.preflight(),z.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return z.info(`Successfully retrieved conversation ${s.id} for session ${t}`),kf(s)})}isConversationSupported(r){return k(this,arguments,function*(t,n={}){z.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return k(this,null,function*(){let r=Ne(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return kf(o)})}postMessages(t,n){return k(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>O(P({},Ne(o)),{tags:o.tags})),{version:"v2"})).map(o=>kf(o))})}sendEvent(t,n){return k(this,null,function*(){let s=n,{data:r}=s,o=te(s,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>O(P({},a),{[l]:u}),{});return this.client.post("/api/events",Ne(O(P(P({},i),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return k(this,null,function*(){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>O(P({},o),{[i]:s}),{});return this.client.post("/api/events",{event:t,data:Ne(P(P({},n),r))})})}getEntities(t){return k(this,null,function*(){return(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities})}getSummary(r){return k(this,arguments,function*(t,n={}){let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(i=>i.text&&i.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model});return re(o)})}getTemporaryExchangeToken(){return k(this,null,function*(){return(yield this.client.get("/auth/exchange-token",{version:null})).jwt})}exchangeTokenForAccessCookie(t){return k(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw z.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return k(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Ne(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return k(this,arguments,function*(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(yield this.client.post(`/api/conversations/${t}/recommend/${r}`,Ne(n),{abortLatest:!0})).map(s=>O(P({},re(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,l)=>a===l.findIndex(u=>u.text===s.text))})}isLoggedIn(){return k(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return k(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/autocomplete`,Ne(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))})}getPinnedMessages(t){return k(this,null,function*(){let n=yield this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return re(n).map(r=>O(P({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return k(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",Ne(t),{abortLatest:!0});return re(n)})}search(t){return k(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,Ne(t),{version:"v2"});return re(n)})}knowledgeAssist(i,s,a){return k(this,arguments,function*(t,n,r,o={}){let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Ne({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(u=>({question:u.question,answer:u.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return re(l)})}requestLoginByEmail(t){return k(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return re(n)})}requestPasswordlessToken(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/",{version:null});return re(t.token)})}getCsrfToken(){return k(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/",{version:null});return t})}verifyLoginToken(t){return k(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return re(n)})}evaluateRule(i,s,a){return k(this,arguments,function*(t,n,r,o={}){let l=new URLSearchParams;o.raiseForFailingConditions&&l.set("raise_for_failing_conditions","true");let u=yield this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${l.toString()}`,r,{version:"v2"});return u?re(u.cues):[]})}getRules(){return k(this,null,function*(){let t=new URLSearchParams,n=yield this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{version:null,useCache:!0});return re(n)})}translateMessages(t){return k(this,null,function*(){let n=yield this.client.post("/api/translate",Ne(t),{version:"v2"});return re(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(qv);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&z.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};Zo.exchangeTokenPromise=null;var pr=Zo;var Il=class{constructor(t,n){this.url=t;this.eventListeners={};this.options=P({timeout:25e3},n)}proxyEvent(t){this.eventSource.addEventListener(Jg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,re(o))}catch(o){z.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 qT;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||(t.AutoflowSessionState={}))})(qT||(qT={}));var Nl=class{constructor(t,n={}){this.apiUrl=t;this.streams={};this.logger=z;this.client=new yn(t,n)}getCustomMessages(t){return k(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/suggestions`);return re(n.suggestions)})}sendCustomMessage(t,n){return k(this,null,function*(){let r=yield this.client.post(`/sessions/${t}/messages`,Ne(n));return re(r)})}answerCustomMessage(t,n){return k(this,null,function*(){yield this.client.post(`/sessions/${t}/answers`,Ne(n))})}getAutoflows(t){return k(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/autoflows`);return re(n.autoflows)})}startAutoflowSession(t){return k(this,null,function*(){let n=yield this.client.post("/autoflow-sessions",Ne(t));return re(n)})}stopAutoflowSession(t){return k(this,null,function*(){yield this.client.delete(`/autoflow-sessions/${t}`)})}openStream(t){return this.streams[t]||(this.streams[t]=new Il(`${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 GT={startTime:null,stopTime:null},XT=Q({name:"handlingTime",initialState:GT,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(fe,()=>GT)}}),{handlingTimeStart:YT,handlingTimeStop:Pf,handlingTimeReset:QT}=XT.actions,ZT=XT.reducer;var JT=(e={})=>{let t=P({onAuthError:Qi(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Rf={list:{keywordMatches:[]},fetchState:"idle"};var Jo=K("styleSuggestions/getAll",(n,r)=>k(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(l=i.conversation.current)==null?void 0:l.profileCode;if(!s)return Rf.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),GM=Q({name:"styleSuggestions",initialState:Rf,reducers:{},extraReducers:e=>{e.addCase(Jo.pending,t=>{t.fetchState="loading"}).addCase(Jo.rejected,t=>{t.fetchState="error"}).addCase(Jo.fulfilled,(t,n)=>{t.fetchState="done",$r(t.list,n.payload)||(t.list=n.payload)}).addCase(Io,t=>{t.list=Rf.list}).addCase(fe,()=>Rf)}}),ek=GM.reducer;var tk=(e={})=>{let t,n=!0,r=P({getStyleSuggestions:Jo,debounce:500},e);return o=>i=>s=>{var f;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(!((f=u.conversation.current)==null?void 0:f.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 XM(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var nk=(e={})=>{let t=P({getTextSuggestions:fn,getAutocompleteSuggestions:ul,debounce:200,check:Rn},e),n;return r=>o=>i=>{var y;let{input:s}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,m=(y=l.conversation.current)==null?void 0:y.id,d=i.type===jd.toString();if(!m||!u&&!c)return a;let{input:f}=l;return XM(f,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let g=es(l);g===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(g))},d?0:t.debounce)),a}};var rk=Jo.fulfilled.toString();function YM(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 ok=e=>t=>n=>r=>{var u;if(r.type!==rk){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=YM(o,s);r.type===rk&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var QM=Ec({answer:ub,auth:p1,autoflows:LC,conversation:b1,contentTypes:SE,customMessages:UC,passwordlessToken:jC,entities:KE,knowledgeAssistant:sb,handlingTime:ZT,info:B1,input:_1,settings:s1,profile:pb,search:G1,summary:QE,styleSuggestions:ek,ui:jb,rules:qC,textSuggestions:xb});function ik(e){return fx({reducer:QM,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),JT(),nk({debounce:200}),tk({debounce:500}),ok(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var ZM=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},JM=e=>t=>n=>r=>{var a,l,u,c,m,d;let o=t.getState(),i=qg("inlineSuggestions")(o);switch(r.type){case Qi.toString():{!r.payload&&e.emit("logout",void 0);break}case cn.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 ot.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Io.toString():e.logSendMessage(r.payload);break;case Go.fulfilled.toString():r.isBroadcasted||e.broadcast(nh,r,!1),(c=r.payload.options)!=null&&c.shouldEmit&&e.emit("cues",r.payload.cues);break;default:break}let s=n(r);switch(r.type){case Io.toString():e.handleAfterSendMessage(r.payload);break;case dl.toString():e.onUpdateShowTabHint(r.payload);break;case Pf.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case rd.toString():{let{start:f,end:v}=o.input.selection;e.emit("replace",O(P({},r.payload),{replace:r.payload.replace==="selection"?{start:f,end:v}:{start:0,end:v}}));break}case rn.toString():{let{start:f,end:v}=o.input.selection;e.emit("select-suggestion",O(P({type:ZM(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:f,end:v}:{start:0,end:v}})),i&&t.dispatch(Xn([]));break}case od.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(m=o.conversation.current)==null?void 0:m.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Xn.toString():{i&&r.payload.length>0&&t.dispatch(id(0));break}case tr.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(d=o.conversation.current)==null?void 0:d.id,data:{summary:r.payload.summary,model:t.getState().summary.model}});break}default:break}return s},sk=JM;function Ly(e){return e.toISOString().replace("T"," ").replace("Z","")}function ak(e,t){var i,s,a,l;let n=(i=e.conversation.current)==null?void 0:i.id;if(!n)return z.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:o}=e.handlingTime;return!r||!o?(z.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:Ly(r),timeStop:Ly(o)}}function lk(e,t,n){var N,_,D,G;let r=(N=t.conversation.current)==null?void 0:N.id;if(!r)return z.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:m,pastes:d,cuts:f,deletions:v,textSuggestions:y,offeredTextSuggestions:g}}=t[e],p=o.length,S=y.reduce((Z,{text:se,searchTerm:mr})=>Z+se.length-(mr?mr.length:0),0),x=c!=null?c:Date.now(),T=(Date.now()-x)/1e3+(m||0),C=i/T,R=y.reduce((Z,{searchTerm:se})=>Z+(se?se.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:f,deletions:v,lenTextTyped:i+R,lenTextTotal:p,lenTextAssisted:S,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:T,charsPerSecond:C,numPastes:u,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:g.filter(Z=>Z.source==="gpt").length}],agentId:(_=t.info.agentInfo)==null?void 0:_.agentId,agentName:(D=t.info.agentInfo)==null?void 0:D.agentName,agentEmail:(G=t.info.agentInfo)==null?void 0:G.agentEmail}}function Iy(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Iy(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Iy(o,t):null}function uk(e,t){return Iy(e,t)}function ck(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function e2(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Af(e){return e2(e)&&(to(e)||Jd(e))}var fk,Nn=new Map,t2=["bottom","height","left","right","top","width"],dk=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:t2.some(n=>e[n]!==t[n]);function pk(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...pk(t)]:[]}function mk(e,t){return!e||!t?null:O(P({},e),{top:e.top+t.top,left:e.left+t.left})}var Lf=!1,gk=()=>{Lf=!0;let e=[];if(Nn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Nn.delete(n);return}let r=n.getBoundingClientRect();dk(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(mk,t.rect):t.rect;dk(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Nn.size===0){Lf=!1;return}fk=window.requestAnimationFrame(gk)};function Ny(e,t){let n=pk(e),r=[],o=n.map((i,s)=>Ny(i,a=>{r[s]=a;let l=Nn.get(e);if(!l)return;let u=r.reduce(mk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Nn.has(e)){let s=Nn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Nn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!Lf&&gk()},unobserve(){o.forEach(s=>s.unobserve());let i=Nn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Nn.delete(e),Nn.size||(cancelAnimationFrame(fk),Lf=!1)}}}}var hk,On=new Map,yk=()=>{On.forEach((e,t)=>{if(!t.isConnected){On.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)))}),On.size!==0&&(hk=window.requestAnimationFrame(yk))};function vk(e,t){return{observe(){let n=On.size===0;On.has(e)?On.get(e).callbacks.push(t):On.set(e,{visible:void 0,callbacks:[t]}),n&&yk()},unobserve(){let n=On.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||On.delete(e),On.size||cancelAnimationFrame(hk)}}}}var Oy=["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 My(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Es(e){return parseFloat(e)}function If(e){return Math.round(e*1e6)}function Sk(e){return e/1e6}function _y(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Es(e.width),i=Es(e.borderLeftWidth),s=Es(e.borderRightWidth),a=Es(e.paddingRight),l=Sk(If(o)-If(i)-If(s)),u=Sk(If(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function Ol(e,t={}){var c,m;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Wo(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};My(r,n,Oy),_y(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=vk(e,()=>{My(r,n,Oy),_y(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=Ny(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(My(r,n,Oy),_y(r,e,n),i(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let f=t.closestScrollElement.getBoundingClientRect(),v=window.getComputedStyle(t.closestScrollElement),y=Es(v.borderTopWidth),g=Es(v.borderBottomWidth),p=f.top+y-d.top,h=d.top+d.height+-(f.top+f.height-g);n.style.clipPath=`inset(${p}px 0px ${h}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(m=e.parentElement)==null||m.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var wk=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){z.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function n2(e){return e.offsetParent!==null}function xk(e){if(!n2(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 Nf(e,t,n=100){let r=xk(e);t({isVisible:r});let o=setInterval(()=>{let i=xk(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var _e=w(b());var Ek=wk("showTabHint",!0),bs=class bs{constructor({deepdeskUrl:t,brokerUrl:n,version:r=bs.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let u=t.replace(/\/api$/,"");this.deepdeskApi=new pr(u,{token:i,fetch:s}),this.version=r,this.instanceId=bs.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[sk({broadcast:(m,d,f)=>{this.broadcastEvents.send(m,d,f)},emit:(m,d)=>this.emit(m,d),handleAfterSendMessage:m=>this.handleAfterSendMessage(m),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:m=>this.logSendMessage(m),onUpdateShowTabHint:m=>Ek.update(m),sendEvent:(m,d)=>this.deepdeskApi.sendEvent(m,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Nl(n)}),this.store=ik(c),this.broadcastEvents=new WT({debug:!0,deepdeskUrl:u,eventMap:X1(this.store),createCustomChannel:l}),this.store.dispatch(dl(Ek.value())),this.store.dispatch(Qc({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(z.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(z.warn("Profile has not been loaded (yet)"),!0):(z.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Qi(null)),this.store.dispatch(qn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();rt(r)&&a1(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return k(this,null,function*(){return(yield this.store.dispatch(qn())).payload})}setPlatformAgentId(t){return k(this,null,function*(){try{if((yield this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;yield this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){z.warn("Failed to attach user:",n)}})}isConversationSupported(t,n){return k(this,null,function*(){return(yield this.store.dispatch(Yg({sessionId:t,options:n}))).payload})}createConversation(t){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(Jc(t))).payload})}getConversationBySessionId(t,n){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(ed({sessionId:t,options:n}))).payload})}upsertConversation(t){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(Qg(t))).payload})}postMessages(t){return k(this,null,function*(){return(yield this.store.dispatch(nd(t))).payload})}updateConversation(t){return k(this,null,function*(){return(yield this.store.dispatch(td(t))).payload})}resetConversation(){this.store.dispatch(fe()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}getSummary(){return k(this,null,function*(){let t=yield this.store.dispatch(tr());if(t.error)throw new Error(t.error.message);return t.payload.summary})}configure(t){this.store.dispatch(Qc(t))}setVisitorInfo(t){this.store.dispatch(U1(t))}setCustomData(t){this.store.dispatch(z1(t))}setAgentInfo(t){return k(this,null,function*(){yield this.store.dispatch(za(t))})}setAgentSettings(t){return k(this,null,function*(){yield this.store.dispatch(eh(t))})}getAgentSettings(){return k(this,null,function*(){return(yield this.store.dispatch(th())).payload})}refresh(){return k(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(sd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(jd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(rn(t))}evaluateRule(o){return k(this,arguments,function*(t,n={},r=VC){return(yield this.store.dispatch(Go({label:t,params:n,options:r}))).payload.cues})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.state.settings,u=a?"below":"above",c=o.length>0;if(!Rn(this.state)||(this.store.dispatch(R1(Zg(t))),t.key!=="Tab"&&!l))return;let m=()=>{n||!c||s&&(t.shiftKey||(this.store.dispatch(I1()),t.preventDefault()))},d=()=>{n||!c||a&&i<=0||s&&(t.shiftKey||(this.store.dispatch(N1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():m();break;case"ArrowDown":{u==="below"?m():d();break}case"Escape":{n||(this.store.dispatch(id(-1)),this.store.dispatch(Jr({collapse:!0})),this.store.dispatch(zb(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let f=ts(this.state);if(!f)return;this.store.dispatch(dl(!1)),this.store.dispatch(rn({text:f.text,suggestion:f,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.state.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let f=ts(this.state);if(!f)return;this.store.dispatch(rn({text:f.text,suggestion:f,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.state.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let f=ts(this.state);if(!f)return;this.store.dispatch(rn({text:f.text,suggestion:f,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(Jr({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Xn([]))}handlingTimeStart(){this.state.handlingTime.startTime||(z.info("Start handling time"),this.store.dispatch(YT()))}handlingTimeStop(){this.state.handlingTime.startTime&&(z.info("Stop handling time"),this.store.dispatch(Pf()))}logSendMessage(t){let n=lk("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=ak(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(QT()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Io((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(M1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){z.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),z.error(i)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}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]=Ol(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Yt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,s=i.ownerDocument.defaultView;if(i&&(s===window||(s==null?void 0:s.parent)===window)){let[l,u]=Ol(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{(0,Yt.unmountComponentAtNode)(o),u()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Wo(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,Yt.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),z.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(z.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(O1(r.metrics))):z.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Af(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:m,detectSubmit:d,insertLink:f,inputMediator:v,closestScrollSelector:y,appendOverlayTo:g,inlineSuggestions:p,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:f,isEmbedded:m,inlineSuggestions:p,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Wo(t),this.inputMediator=v||(to(t)?new Qo(t):new Yo(t)),this.inputMediator.on("change",({plainText:T,rawHTML:C})=>{this.store.dispatch(sd({text:T,html:C}))}),this.inputMediator.on("keyup",T=>{this.store.dispatch(A1(Zg(T)))}),this.inputMediator.on("keydown",T=>{this.handleKeyDown(T)}),this.inputMediator.on("paste",({pastedText:T,selectionText:C})=>{this.store.dispatch(L1({text:T,selectionText:C}))}),this.inputMediator.on("cut",({selectionText:T})=>{this.store.dispatch(P1(T))});let S;this.inputMediator.on("selection",T=>{clearTimeout(S),T===null?S=setTimeout(()=>{T!==null&&this.store.dispatch(ad(T))},500):this.store.dispatch(ad(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(qd(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(qd(!0))});let x=y&&uk(t,y)||void 0;if(p){let{customStyles:T,appendOverlayTo:C}=n;if(to(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let R=this.createInlineContainer(t,"deepdesk-caret");(0,Yt.render)((0,_e.jsx)(qo,{store:this.store,customStyles:T,children:(0,_e.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(Gb,{})})}),R),this.inputMediator.on("caretposition",_=>{this.store.dispatch(Xn([])),_?(R.style.display="block",R.style.top=`${_.top}px`,R.style.left=`${_.left}px`):R.style.display="none"});let N=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:C},T==null?void 0:T.floatingMenuRootNode);(0,Yt.render)((0,_e.jsx)(qo,{store:this.store,customStyles:T,children:(0,_e.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(Fb,{onLogIn:()=>this.loginViaPopup().catch(_=>z.warn(_.message))})})}),N)}else{let T=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:g,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:g},r==null?void 0:r.suggestionsRootNode);(0,Yt.render)((0,_e.jsx)(qo,{store:this.store,customStyles:r,children:(0,_e.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(CC,{inputElement:t})})}),T),(0,Yt.render)((0,_e.jsx)(qo,{store:this.store,customStyles:r,children:(0,_e.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(rC,{onLogIn:()=>this.loginViaPopup().catch(R=>z.warn(R.message))})})}),C)}(0,Yt.render)((0,_e.jsx)(qo,{store:this.store,customStyles:r,children:(0,_e.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(Nb,{})})}),this.createContainer("deepdesk-overlays")),this.store.dispatch(sd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(ad(this.inputMediator.getSelection())),this.store.dispatch(qd(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var T;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((T=this.state.conversation.current)==null?void 0:T.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&z.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,Yt.render)((0,_e.jsx)(qo,{store:this.store,customStyles:r,children:(0,_e.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(zT,{onLogIn:()=>this.loginViaPopup().catch(s=>z.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,Yt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Nf(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){ck(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>k(this,null,function*(){yield this.store.dispatch(ll());let t=or(this.state);t&&(yield this.store.dispatch(il()),this.store.dispatch(Qc({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)}loginViaPopup(t){return k(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",m),clearInterval(d)};i.onmessage=f=>k(this,null,function*(){var v,y;if((v=f.data)!=null&&v.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((y=f.data)==null?void 0:y.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(ja),l=!0,o.port1.close(),n()}catch(g){console.error(g),r(g)}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 m=f=>k(this,null,function*(){var v;if(f.origin===a.origin)switch((v=f.data)==null?void 0:v.type){case"deepdesk-popup-loaded":{try{let y=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(y,a.origin,[o.port2])}catch(y){z.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-error":{u(),f.data.message==="Timeout"&&z.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(f.data.message));break}}});window.addEventListener("message",m);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}checkForTrialMode(t){return k(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(z.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;z.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return k(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=zd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(cn()):nu.includes(r)||this.store.dispatch(fn(r))})}catch(r){this.handleError(r)}})}};bs.version="12.0.1",bs.count=0;var Ml=bs;function bk(r,o){return k(this,arguments,function*(e,t,n={}){var m,d;let{value:i}=e,{start:s,end:a}=(m=n.replace)!=null?m:{start:0,end:i.length},l=`${i.slice(0,s)}${t}${i.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+t.length},c=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(c()).then(()=>{e.selectionStart=u.start,e.selectionEnd=u.end,e.blur(),e.focus()})})}function Ck(r,o){return k(this,arguments,function*(e,t,n={}){let i=n.replace?io(e,n.replace.start,n.replace.end):Ss(e),s,a=()=>{if(n.setRange)return n.setRange(i.cloneRange());i.deleteContents(),s=document.createElement("span"),i.insertNode(s),n.insertBRs!==!1?t.split(`
|
|
27
|
+
`);break}default:break}m&&s++}return l(e),a}var jT=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(jT||{}),fr=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.getCaretPosition();this.isActive&&(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText&&(this.cachedText=t,this.cachedHTML=n,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,this.emit("selection",r)),$r(o,this.cachedCaretPosition)||(this.cachedCaretPosition=o,this.emit("caretposition",o)))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(jT).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function VT(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Yo=class extends fr{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Ll(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var s;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(s=r.getComposedRanges(n))==null?void 0:s[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!VT(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!VT(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return Al(this.element,n);let r=this.lastKnownSelection;if(r&&BT(this.element,r.start,r.end))return r;let o=Ss(this.element);return o.collapse(!1),Al(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Ll(this.element,io(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(()=>{setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var Qo=class extends fr{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return null}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var i;return(i=n==null?void 0:n.get)==null?void 0:i.call(this.element)},set:i=>{var s;(s=n==null?void 0:n.set)==null||s.call(this.element,i),this.handleInteraction()}});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function KT(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 $M(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var Cy=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Ty=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=KT(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},ky=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),z.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 Ty(t,this.deepdeskUrl,{debug:!0}):new Cy(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=$M(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(z.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;z.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(P({},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)}},WT=ky;var ws=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var Py=e=>new Promise(t=>{setTimeout(t,e)});var xs=class extends ws{constructor(){super(...arguments);this.name="ClientError"}},Ay=class extends ws{constructor(){super(...arguments);this.name="ServerError"}},Ry=new Map;function qM(e){return k(this,null,function*(){var r;if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=yield e.text();if(n==="")return null;z.warn("Unexpected response body:",n.slice(0,20));try{(r=window.Sentry)==null||r.captureMessage(n.slice(0,1e4))}catch(o){z.error(o)}return JSON.parse(n)})}var so=class so{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",C=n,{useCache:u=!1,abortLatest:c=!1,attempts:m=1,retryDelay:d=500,refreshTokenOn401:f=!0,retryOnError:v=R=>R instanceof TypeError,retryOnResponse:y=R=>R.status>=500,version:g="v1"}=C,p=te(C,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(Ry.has(s)){r(Ry.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h=O(P({credentials:"include"},p),{headers:P({"Content-Type":"application/json"},p.headers)});!l&&this.csrfToken&&(h.headers=O(P({},h.headers),{"X-CSRFToken":this.csrfToken})),typeof g=="string"&&(h.headers=O(P({},h.headers),{"X-Deepdesk-API-Version":g}));let S=m,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=()=>k(this,null,function*(){return S--,a(s,h).then(R=>k(this,null,function*(){return y(R)&&!i.isAborted&&S>0?(yield Py(d),T()):R.status===401&&f===!0&&x===!1?(x=!0,yield this.refreshToken(),T()):R})).catch(R=>k(this,null,function*(){if(v(R)&&!i.isAborted&&S>0)return yield Py(d),T();throw R}))});T().then(R=>k(this,null,function*(){let N=yield qM(R);if(delete this.latestRequestByUrl[s],R.status>=500){o(new Ay("Server Error",N));return}else if(R.status===401){o(new xs("Unauthorized",N));return}else if(R.status===403){o(new xs("Forbidden",N));return}else if(R.status===404){o(new xs("Not Found",N));return}else if(R.status>=400){o(new xs("Bad Request",N));return}u&&Ry.set(s,N),r(N)})).catch(R=>{o(R)})})}validateToken(){return k(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/",{version:null});return!!n})}refreshToken(){return so.refreshingToken||(so.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{so.refreshingToken=null},1e3*60)})),so.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,P({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,P({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,P({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,P({method:"DELETE"},n))}};so.refreshingToken=null;var yn=so;var $T;(t=>{let e;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||(t.EventType={}))})($T||($T={}));function kf(e){return O(P({},re(e)),{tags:e.tags})}var Zo=class Zo{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new yn(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>k(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return k(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(Zo.exchangeTokenPromise||(Zo.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),Zo.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return k(this,null,function*(){yield this.preflight(),z.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",O(P({},Ne(t)),{tags:t.tags}),{version:"v2"});return kf(n)})}getProfile(t){return k(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{version:null,useCache:!0});return re(n)})}getKnowledgeAssistant(t){return k(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null,useCache:!0});return re(n)})}getContentTypes(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return re(t)})}getAccount(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{version:null,useCache:!0});return re(t)})}getPlatformConfig(){return k(this,null,function*(){let{config:t}=yield this.client.get("/platform/config/",{version:null,useCache:!0});return re(t)})}checkUserExists(t){return k(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n})}getConversationBySessionId(r){return k(this,arguments,function*(t,n={}){yield this.preflight(),z.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return z.info(`Successfully retrieved conversation ${s.id} for session ${t}`),kf(s)})}isConversationSupported(r){return k(this,arguments,function*(t,n={}){z.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return k(this,null,function*(){let r=Ne(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return kf(o)})}postMessages(t,n){return k(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>O(P({},Ne(o)),{tags:o.tags})),{version:"v2"})).map(o=>kf(o))})}sendEvent(t,n){return k(this,null,function*(){let s=n,{data:r}=s,o=te(s,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>O(P({},a),{[l]:u}),{});return this.client.post("/api/events",Ne(O(P(P({},i),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return k(this,null,function*(){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>O(P({},o),{[i]:s}),{});return this.client.post("/api/events",{event:t,data:Ne(P(P({},n),r))})})}getEntities(t){return k(this,null,function*(){return(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities})}getSummary(r){return k(this,arguments,function*(t,n={}){let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(i=>i.text&&i.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model});return re(o)})}getTemporaryExchangeToken(){return k(this,null,function*(){return(yield this.client.get("/auth/exchange-token",{version:null})).jwt})}exchangeTokenForAccessCookie(t){return k(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw z.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return k(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Ne(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return k(this,arguments,function*(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(yield this.client.post(`/api/conversations/${t}/recommend/${r}`,Ne(n),{abortLatest:!0})).map(s=>O(P({},re(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,l)=>a===l.findIndex(u=>u.text===s.text))})}isLoggedIn(){return k(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return k(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/autocomplete`,Ne(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))})}getPinnedMessages(t){return k(this,null,function*(){let n=yield this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return re(n).map(r=>O(P({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return k(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",Ne(t),{abortLatest:!0});return re(n)})}search(t){return k(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,Ne(t),{version:"v2"});return re(n)})}knowledgeAssist(i,s,a){return k(this,arguments,function*(t,n,r,o={}){let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Ne({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(u=>({question:u.question,answer:u.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return re(l)})}requestLoginByEmail(t){return k(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return re(n)})}requestPasswordlessToken(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/",{version:null});return re(t.token)})}getCsrfToken(){return k(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/",{version:null});return t})}verifyLoginToken(t){return k(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return re(n)})}evaluateRule(i,s,a){return k(this,arguments,function*(t,n,r,o={}){let l=new URLSearchParams;o.raiseForFailingConditions&&l.set("raise_for_failing_conditions","true");let u=yield this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${l.toString()}`,r,{version:"v2"});return u?re(u.cues):[]})}getRules(){return k(this,null,function*(){let t=new URLSearchParams,n=yield this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{version:null,useCache:!0});return re(n)})}translateMessages(t){return k(this,null,function*(){let n=yield this.client.post("/api/translate",Ne(t),{version:"v2"});return re(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(qv);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&z.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};Zo.exchangeTokenPromise=null;var pr=Zo;var Il=class{constructor(t,n){this.url=t;this.eventListeners={};this.options=P({timeout:25e3},n)}proxyEvent(t){this.eventSource.addEventListener(Jg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,re(o))}catch(o){z.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 qT;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||(t.AutoflowSessionState={}))})(qT||(qT={}));var Nl=class{constructor(t,n={}){this.apiUrl=t;this.streams={};this.logger=z;this.client=new yn(t,n)}getCustomMessages(t){return k(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/suggestions`);return re(n.suggestions)})}sendCustomMessage(t,n){return k(this,null,function*(){let r=yield this.client.post(`/sessions/${t}/messages`,Ne(n));return re(r)})}answerCustomMessage(t,n){return k(this,null,function*(){yield this.client.post(`/sessions/${t}/answers`,Ne(n))})}getAutoflows(t){return k(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/autoflows`);return re(n.autoflows)})}startAutoflowSession(t){return k(this,null,function*(){let n=yield this.client.post("/autoflow-sessions",Ne(t));return re(n)})}stopAutoflowSession(t){return k(this,null,function*(){yield this.client.delete(`/autoflow-sessions/${t}`)})}openStream(t){return this.streams[t]||(this.streams[t]=new Il(`${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 GT={startTime:null,stopTime:null},XT=Q({name:"handlingTime",initialState:GT,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(fe,()=>GT)}}),{handlingTimeStart:YT,handlingTimeStop:Pf,handlingTimeReset:QT}=XT.actions,ZT=XT.reducer;var JT=(e={})=>{let t=P({onAuthError:Qi(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Rf={list:{keywordMatches:[]},fetchState:"idle"};var Jo=K("styleSuggestions/getAll",(n,r)=>k(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(l=i.conversation.current)==null?void 0:l.profileCode;if(!s)return Rf.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),GM=Q({name:"styleSuggestions",initialState:Rf,reducers:{},extraReducers:e=>{e.addCase(Jo.pending,t=>{t.fetchState="loading"}).addCase(Jo.rejected,t=>{t.fetchState="error"}).addCase(Jo.fulfilled,(t,n)=>{t.fetchState="done",$r(t.list,n.payload)||(t.list=n.payload)}).addCase(Io,t=>{t.list=Rf.list}).addCase(fe,()=>Rf)}}),ek=GM.reducer;var tk=(e={})=>{let t,n=!0,r=P({getStyleSuggestions:Jo,debounce:500},e);return o=>i=>s=>{var f;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(!((f=u.conversation.current)==null?void 0:f.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 XM(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var nk=(e={})=>{let t=P({getTextSuggestions:fn,getAutocompleteSuggestions:ul,debounce:200,check:Rn},e),n;return r=>o=>i=>{var y;let{input:s}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,m=(y=l.conversation.current)==null?void 0:y.id,d=i.type===jd.toString();if(!m||!u&&!c)return a;let{input:f}=l;return XM(f,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let g=es(l);g===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(g))},d?0:t.debounce)),a}};var rk=Jo.fulfilled.toString();function YM(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 ok=e=>t=>n=>r=>{var u;if(r.type!==rk){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=YM(o,s);r.type===rk&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var QM=Ec({answer:ub,auth:p1,autoflows:LC,conversation:b1,contentTypes:SE,customMessages:UC,passwordlessToken:jC,entities:KE,knowledgeAssistant:sb,handlingTime:ZT,info:B1,input:_1,settings:s1,profile:pb,search:G1,summary:QE,styleSuggestions:ek,ui:jb,rules:qC,textSuggestions:xb});function ik(e){return fx({reducer:QM,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),JT(),nk({debounce:200}),tk({debounce:500}),ok(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var ZM=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},JM=e=>t=>n=>r=>{var a,l,u,c,m,d;let o=t.getState(),i=qg("inlineSuggestions")(o);switch(r.type){case Qi.toString():{!r.payload&&e.emit("logout",void 0);break}case cn.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 ot.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Io.toString():e.logSendMessage(r.payload);break;case Go.fulfilled.toString():r.isBroadcasted||e.broadcast(nh,r,!1),(c=r.payload.options)!=null&&c.shouldEmit&&e.emit("cues",r.payload.cues);break;default:break}let s=n(r);switch(r.type){case Io.toString():e.handleAfterSendMessage(r.payload);break;case dl.toString():e.onUpdateShowTabHint(r.payload);break;case Pf.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case rd.toString():{let{start:f,end:v}=o.input.selection;e.emit("replace",O(P({},r.payload),{replace:r.payload.replace==="selection"?{start:f,end:v}:{start:0,end:v}}));break}case rn.toString():{let{start:f,end:v}=o.input.selection;e.emit("select-suggestion",O(P({type:ZM(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:f,end:v}:{start:0,end:v}})),i&&t.dispatch(Xn([]));break}case od.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(m=o.conversation.current)==null?void 0:m.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Xn.toString():{i&&r.payload.length>0&&t.dispatch(id(0));break}case tr.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(d=o.conversation.current)==null?void 0:d.id,data:{summary:r.payload.summary,model:t.getState().summary.model}});break}default:break}return s},sk=JM;function Ly(e){return e.toISOString().replace("T"," ").replace("Z","")}function ak(e,t){var i,s,a,l;let n=(i=e.conversation.current)==null?void 0:i.id;if(!n)return z.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:o}=e.handlingTime;return!r||!o?(z.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:Ly(r),timeStop:Ly(o)}}function lk(e,t,n){var N,_,D,G;let r=(N=t.conversation.current)==null?void 0:N.id;if(!r)return z.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:m,pastes:d,cuts:f,deletions:v,textSuggestions:y,offeredTextSuggestions:g}}=t[e],p=o.length,S=y.reduce((Z,{text:se,searchTerm:mr})=>Z+se.length-(mr?mr.length:0),0),x=c!=null?c:Date.now(),T=(Date.now()-x)/1e3+(m||0),C=i/T,R=y.reduce((Z,{searchTerm:se})=>Z+(se?se.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:f,deletions:v,lenTextTyped:i+R,lenTextTotal:p,lenTextAssisted:S,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:T,charsPerSecond:C,numPastes:u,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:g.filter(Z=>Z.source==="gpt").length}],agentId:(_=t.info.agentInfo)==null?void 0:_.agentId,agentName:(D=t.info.agentInfo)==null?void 0:D.agentName,agentEmail:(G=t.info.agentInfo)==null?void 0:G.agentEmail}}function Iy(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Iy(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Iy(o,t):null}function uk(e,t){return Iy(e,t)}function ck(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function e2(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Af(e){return e2(e)&&(to(e)||Jd(e))}var fk,Nn=new Map,t2=["bottom","height","left","right","top","width"],dk=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:t2.some(n=>e[n]!==t[n]);function pk(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...pk(t)]:[]}function mk(e,t){return!e||!t?null:O(P({},e),{top:e.top+t.top,left:e.left+t.left})}var Lf=!1,gk=()=>{Lf=!0;let e=[];if(Nn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Nn.delete(n);return}let r=n.getBoundingClientRect();dk(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(mk,t.rect):t.rect;dk(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Nn.size===0){Lf=!1;return}fk=window.requestAnimationFrame(gk)};function Ny(e,t){let n=pk(e),r=[],o=n.map((i,s)=>Ny(i,a=>{r[s]=a;let l=Nn.get(e);if(!l)return;let u=r.reduce(mk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Nn.has(e)){let s=Nn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Nn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!Lf&&gk()},unobserve(){o.forEach(s=>s.unobserve());let i=Nn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Nn.delete(e),Nn.size||(cancelAnimationFrame(fk),Lf=!1)}}}}var hk,On=new Map,yk=()=>{On.forEach((e,t)=>{if(!t.isConnected){On.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)))}),On.size!==0&&(hk=window.requestAnimationFrame(yk))};function vk(e,t){return{observe(){let n=On.size===0;On.has(e)?On.get(e).callbacks.push(t):On.set(e,{visible:void 0,callbacks:[t]}),n&&yk()},unobserve(){let n=On.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||On.delete(e),On.size||cancelAnimationFrame(hk)}}}}var Oy=["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 My(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Es(e){return parseFloat(e)}function If(e){return Math.round(e*1e6)}function Sk(e){return e/1e6}function _y(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Es(e.width),i=Es(e.borderLeftWidth),s=Es(e.borderRightWidth),a=Es(e.paddingRight),l=Sk(If(o)-If(i)-If(s)),u=Sk(If(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function Ol(e,t={}){var c,m;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Wo(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};My(r,n,Oy),_y(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=vk(e,()=>{My(r,n,Oy),_y(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=Ny(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(My(r,n,Oy),_y(r,e,n),i(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let f=t.closestScrollElement.getBoundingClientRect(),v=window.getComputedStyle(t.closestScrollElement),y=Es(v.borderTopWidth),g=Es(v.borderBottomWidth),p=f.top+y-d.top,h=d.top+d.height+-(f.top+f.height-g);n.style.clipPath=`inset(${p}px 0px ${h}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(m=e.parentElement)==null||m.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var wk=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){z.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function n2(e){return e.offsetParent!==null}function xk(e){if(!n2(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 Nf(e,t,n=100){let r=xk(e);t({isVisible:r});let o=setInterval(()=>{let i=xk(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var _e=w(b());var Ek=wk("showTabHint",!0),bs=class bs{constructor({deepdeskUrl:t,brokerUrl:n,version:r=bs.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let u=t.replace(/\/api$/,"");this.deepdeskApi=new pr(u,{token:i,fetch:s}),this.version=r,this.instanceId=bs.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[sk({broadcast:(m,d,f)=>{this.broadcastEvents.send(m,d,f)},emit:(m,d)=>this.emit(m,d),handleAfterSendMessage:m=>this.handleAfterSendMessage(m),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:m=>this.logSendMessage(m),onUpdateShowTabHint:m=>Ek.update(m),sendEvent:(m,d)=>this.deepdeskApi.sendEvent(m,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Nl(n)}),this.store=ik(c),this.broadcastEvents=new WT({debug:!0,deepdeskUrl:u,eventMap:X1(this.store),createCustomChannel:l}),this.store.dispatch(dl(Ek.value())),this.store.dispatch(Qc({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(z.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(z.warn("Profile has not been loaded (yet)"),!0):(z.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Qi(null)),this.store.dispatch(qn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();rt(r)&&a1(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return k(this,null,function*(){return(yield this.store.dispatch(qn())).payload})}setPlatformAgentId(t){return k(this,null,function*(){try{if((yield this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;yield this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){z.warn("Failed to attach user:",n)}})}isConversationSupported(t,n){return k(this,null,function*(){return(yield this.store.dispatch(Yg({sessionId:t,options:n}))).payload})}createConversation(t){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(Jc(t))).payload})}getConversationBySessionId(t,n){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(ed({sessionId:t,options:n}))).payload})}upsertConversation(t){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(Qg(t))).payload})}postMessages(t){return k(this,null,function*(){return(yield this.store.dispatch(nd(t))).payload})}updateConversation(t){return k(this,null,function*(){return(yield this.store.dispatch(td(t))).payload})}resetConversation(){this.store.dispatch(fe()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}getSummary(){return k(this,null,function*(){let t=yield this.store.dispatch(tr());if(t.error)throw new Error(t.error.message);return t.payload.summary})}configure(t){this.store.dispatch(Qc(t))}setVisitorInfo(t){this.store.dispatch(U1(t))}setCustomData(t){this.store.dispatch(z1(t))}setAgentInfo(t){return k(this,null,function*(){yield this.store.dispatch(za(t))})}setAgentSettings(t){return k(this,null,function*(){yield this.store.dispatch(eh(t))})}getAgentSettings(){return k(this,null,function*(){return(yield this.store.dispatch(th())).payload})}refresh(){return k(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(sd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(jd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(rn(t))}evaluateRule(o){return k(this,arguments,function*(t,n={},r=VC){return(yield this.store.dispatch(Go({label:t,params:n,options:r}))).payload.cues})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.state.settings,u=a?"below":"above",c=o.length>0;if(!Rn(this.state)||(this.store.dispatch(R1(Zg(t))),t.key!=="Tab"&&!l))return;let m=()=>{n||!c||s&&(t.shiftKey||(this.store.dispatch(I1()),t.preventDefault()))},d=()=>{n||!c||a&&i<=0||s&&(t.shiftKey||(this.store.dispatch(N1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():m();break;case"ArrowDown":{u==="below"?m():d();break}case"Escape":{n||(this.store.dispatch(id(-1)),this.store.dispatch(Jr({collapse:!0})),this.store.dispatch(zb(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let f=ts(this.state);if(!f)return;this.store.dispatch(dl(!1)),this.store.dispatch(rn({text:f.text,suggestion:f,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.state.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let f=ts(this.state);if(!f)return;this.store.dispatch(rn({text:f.text,suggestion:f,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.state.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let f=ts(this.state);if(!f)return;this.store.dispatch(rn({text:f.text,suggestion:f,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(Jr({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Xn([]))}handlingTimeStart(){this.state.handlingTime.startTime||(z.info("Start handling time"),this.store.dispatch(YT()))}handlingTimeStop(){this.state.handlingTime.startTime&&(z.info("Stop handling time"),this.store.dispatch(Pf()))}logSendMessage(t){let n=lk("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=ak(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(QT()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Io((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(M1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){z.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),z.error(i)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}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]=Ol(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Yt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,s=i.ownerDocument.defaultView;if(i&&(s===window||(s==null?void 0:s.parent)===window)){let[l,u]=Ol(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{(0,Yt.unmountComponentAtNode)(o),u()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Wo(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,Yt.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),z.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(z.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(O1(r.metrics))):z.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Af(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:m,detectSubmit:d,insertLink:f,inputMediator:v,closestScrollSelector:y,appendOverlayTo:g,inlineSuggestions:p,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:f,isEmbedded:m,inlineSuggestions:p,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Wo(t),this.inputMediator=v||(to(t)?new Qo(t):new Yo(t)),this.inputMediator.on("change",({plainText:T,rawHTML:C})=>{this.store.dispatch(sd({text:T,html:C}))}),this.inputMediator.on("keyup",T=>{this.store.dispatch(A1(Zg(T)))}),this.inputMediator.on("keydown",T=>{this.handleKeyDown(T)}),this.inputMediator.on("paste",({pastedText:T,selectionText:C})=>{this.store.dispatch(L1({text:T,selectionText:C}))}),this.inputMediator.on("cut",({selectionText:T})=>{this.store.dispatch(P1(T))});let S;this.inputMediator.on("selection",T=>{clearTimeout(S),T===null?S=setTimeout(()=>{T!==null&&this.store.dispatch(ad(T))},500):this.store.dispatch(ad(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(qd(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(qd(!0))});let x=y&&uk(t,y)||void 0;if(p){let{customStyles:T,appendOverlayTo:C}=n;if(to(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let R=this.createInlineContainer(t,"deepdesk-caret");(0,Yt.render)((0,_e.jsx)(qo,{store:this.store,customStyles:T,children:(0,_e.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(Gb,{})})}),R),this.inputMediator.on("caretposition",_=>{this.store.dispatch(Xn([])),_?(R.style.display="block",R.style.top=`${_.top}px`,R.style.left=`${_.left}px`):R.style.display="none"});let N=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:C},T==null?void 0:T.floatingMenuRootNode);(0,Yt.render)((0,_e.jsx)(qo,{store:this.store,customStyles:T,children:(0,_e.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(Fb,{onLogIn:()=>this.loginViaPopup().catch(_=>z.warn(_.message))})})}),N)}else{let T=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:g,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:g},r==null?void 0:r.suggestionsRootNode);(0,Yt.render)((0,_e.jsx)(qo,{store:this.store,customStyles:r,children:(0,_e.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(CC,{inputElement:t})})}),T),(0,Yt.render)((0,_e.jsx)(qo,{store:this.store,customStyles:r,children:(0,_e.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(rC,{onLogIn:()=>this.loginViaPopup().catch(R=>z.warn(R.message))})})}),C)}(0,Yt.render)((0,_e.jsx)(qo,{store:this.store,customStyles:r,children:(0,_e.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(Nb,{})})}),this.createContainer("deepdesk-overlays")),this.store.dispatch(sd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(ad(this.inputMediator.getSelection())),this.store.dispatch(qd(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var T;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((T=this.state.conversation.current)==null?void 0:T.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&z.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,Yt.render)((0,_e.jsx)(qo,{store:this.store,customStyles:r,children:(0,_e.jsx)(Oo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(zT,{onLogIn:()=>this.loginViaPopup().catch(s=>z.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,Yt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Nf(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){ck(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>k(this,null,function*(){yield this.store.dispatch(ll());let t=or(this.state);t&&(yield this.store.dispatch(il()),this.store.dispatch(Qc({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)}loginViaPopup(t){return k(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",m),clearInterval(d)};i.onmessage=f=>k(this,null,function*(){var v,y;if((v=f.data)!=null&&v.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((y=f.data)==null?void 0:y.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(ja),l=!0,o.port1.close(),n()}catch(g){console.error(g),r(g)}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 m=f=>k(this,null,function*(){var v;if(f.origin===a.origin)switch((v=f.data)==null?void 0:v.type){case"deepdesk-popup-loaded":{try{let y=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(y,a.origin,[o.port2])}catch(y){z.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-error":{u(),f.data.message==="Timeout"&&z.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(f.data.message));break}}});window.addEventListener("message",m);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}checkForTrialMode(t){return k(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(z.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;z.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return k(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=zd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(cn()):nu.includes(r)||this.store.dispatch(fn(r))})}catch(r){this.handleError(r)}})}};bs.version="12.0.2-beta.1",bs.count=0;var Ml=bs;function bk(r,o){return k(this,arguments,function*(e,t,n={}){var m,d;let{value:i}=e,{start:s,end:a}=(m=n.replace)!=null?m:{start:0,end:i.length},l=`${i.slice(0,s)}${t}${i.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+t.length},c=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(c()).then(()=>{e.selectionStart=u.start,e.selectionEnd=u.end,e.blur(),e.focus()})})}function Ck(r,o){return k(this,arguments,function*(e,t,n={}){let i=n.replace?io(e,n.replace.start,n.replace.end):Ss(e),s,a=()=>{if(n.setRange)return n.setRange(i.cloneRange());i.deleteContents(),s=document.createElement("span"),i.insertNode(s),n.insertBRs!==!1?t.split(`
|
|
28
28
|
`).reverse().forEach((l,u)=>{u>0&&i.insertNode(document.createElement("br")),i.insertNode(document.createTextNode(l))}):i.insertNode(document.createTextNode(t))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let l=n.selectionAfter?io(e,n.selectionAfter.start,n.selectionAfter.end):(i.collapse(!1),i),u=window.getSelection();u==null||u.removeAllRanges(),u==null||u.addRange(l)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}function r2(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 o2(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 Tk(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):Tk(n,t)}function kk(o,i){return k(this,arguments,function*(e,t,{isBlock:n,isHTML:r}={}){let s;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let a=()=>{var d;let l=(d=e.ownerDocument.defaultView)!=null?d:window,u=l.getSelection();if((!u||u.rangeCount===0)&&(e.focus(),u=l.getSelection()),!u||u.rangeCount===0)return;let c=u.getRangeAt(0);if(!c)return;s=document.createElement("span"),c.insertNode(s);let m=r?r2(t):o2(t);n?Tk(c.startContainer,m):(c.insertNode(m),c.collapse(!1))};return Promise.resolve(a()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!s)try{s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}function Pk(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function Rk(e,t,n){return k(this,null,function*(){yield new pr(e).authenticateWithKey(t,n)})}function Ak(e){return k(this,null,function*(){let n=yield new yn(e).get("/platform/config/",{version:null,useCache:!0});return re(n)})}function i2(e){return k(this,null,function*(){var o,i,s;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(s=(i=e.mimeType)!=null?i:n.headers.get("Content-Type"))!=null?s:"image/jpeg"})})}function Lk(e,t){return k(this,null,function*(){let n=yield i2(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 $k(s2);})();
|
|
30
30
|
/*! Bundled license information:
|