@deepdesk/deepdesk-sdk 19.0.2-beta.5 → 19.0.2-beta.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.iife.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -13,6 +13,6 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
|
13
13
|
`)}var th=({content:t,useLabel:e,copyLabel:n,onCopy:o,onUse:r})=>{let s=x("Markdown",Hp),i=(0,ft.useRef)(null),[a,d]=(0,ft.useState)(null),l=(0,ft.useMemo)(()=>{let m=Up.marked.parse(eh(t));return Bp.default.sanitize(m.toString()).replaceAll("</code>",`${Yf(s.copyIcon)}</code>`).replaceAll('<a href="','<a target="_blank" rel="noreferrer noopener" href="')},[t]),c=m=>{var T;let h=m.target,C=!!((T=i.current)!=null&&T.querySelector("code"));if(["A","BUTTON"].includes(h.tagName)){d(null);return}a||C&&h.tagName!=="CODE"||!C&&h!==i.current||(h.addEventListener("mouseleave",()=>d(null),{once:!0}),d(h))},u=()=>{if(!a)return;d(null);let m=a.querySelector("button");m&&(Nt(m,s.fadeup),o==null||o(oa(a)))},p=m=>{let h=m.target;if(h.tagName==="A"){let C=h.getAttribute("href")||"";if(h.getAttribute("target")==="_blank"&&/^https?:\/\//.test(C))return;m.stopPropagation();return}"copyIcon"in h.dataset&&(Nt(h,s.fadeup),o==null||o(oa(h.parentElement)))},g=()=>{!a||!r||(d(null),r(oa(a)))},f=m=>{if(m===null)return;let h=m.getBoundingClientRect();h.left<0?m.style.transform=`translateX(${-h.left+2}px)`:h.right>window.innerWidth&&(m.style.transform=`translateX(${window.innerWidth-h.right-2}px)`)};return(0,Ue.jsxs)(ft.Fragment,{children:[a&&(o||r)&&(0,Ue.jsxs)(Un,{triggerRef:{current:a},className:s.popover,parentNode:a,children:[(0,Ue.jsxs)("div",{className:s.options,ref:f,children:[o&&(a==null?void 0:a.tagName)==="CODE"&&(0,Ue.jsx)("button",{type:"button",className:s.option,onClick:u,children:n}),r&&(0,Ue.jsxs)(ft.Fragment,{children:[(0,Ue.jsx)("div",{className:s.divider}),(0,Ue.jsx)("button",{type:"button",className:s.option,onClick:g,children:e})]})]}),(0,Ue.jsx)("div",{className:s.arrow})]}),(0,Ue.jsx)("div",{ref:i,"data-testid":"widget-markdown-content",className:s.root,dangerouslySetInnerHTML:{__html:l},onMouseOver:c,onClick:p})]})},ln=th;var ra={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",actions:"dd-9Iqn9",thumbsUp:"dd-6QwVx",thumbsDown:"dd-d3E8l",form:"dd-sPNU2",formInput:"dd-F3E4I",formSubmit:"dd-vw5S0",actionButton:"dd-cCWyJ",editableCue:"dd-nWSD-",inputSpace:"dd-DGYB1"};var ce=require("react/jsx-runtime"),nh=500,oh=100,rh=({content:t,onChange:e,onCopy:n})=>{let o=(0,dn.useRef)(null),r=x("WidgetCue",ra);return(0,dn.useEffect)(()=>{let s=o.current;if(!s)return;s.style.setProperty("height","0px");let i=Math.min(Math.max(s.scrollHeight,oh),nh);s.style.setProperty("height",`${i}px`)},[t]),(0,ce.jsx)("textarea",{ref:o,className:r.editableCue,onCopy:n,onChange:e,value:t})},sh=({cue:t,onCallToAction:e,onRemove:n,onCopy:o,onUse:r})=>{let s=x("WidgetCue",ra),i=R(zo),a=V(),d=E("hasKeyboardInput"),[l,c]=(0,dn.useState)(t.text),u=t.editable?l:fs(t.text,"reply").join(`
|
|
14
14
|
`)||t.text,p=()=>{e&&e(l,t),n(t)},g=(h,C)=>{o&&o(h,t),C&&Nt(C,s.fadeup)},f=h=>{r&&r(h,t)},m=h=>{h.preventDefault(),h.stopPropagation(),n(t)};return(0,dn.useEffect)(()=>{a("Assistant response displayed",{evaluationId:t.evaluationId,assistantCode:t.rule.label,assistantOutput:t.text})},[]),(0,ce.jsxs)(L,{"data-testid":"cue",children:[(0,ce.jsx)(F,{children:(0,ce.jsxs)(F.Content,{children:[t.title&&(0,ce.jsx)(F.Title,{className:s.title,"data-testid":"widget-cue-title",children:t.rule.label.startsWith("__")?i(t.rule.label):t.title}),t.editable?(0,ce.jsx)(rh,{content:l,onCopy:()=>{let h=document.getSelection();h&&g(h.toString())},onChange:h=>{var C;return c((C=h.target.value)!=null?C:"")}}):(0,ce.jsx)(ln,{content:t.text,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:g,onUse:d?f:void 0})]})}),(0,ce.jsxs)(L.ButtonsContainer,{children:[(0,ce.jsxs)("div",{className:s.actions,children:[(0,ce.jsx)(L.Button,{onClick:h=>g(u,h.target),variant:"primary",children:i("copyCue")}),t.callToAction&&(0,ce.jsx)(L.Button,{onClick:p,variant:"primary",children:t.callToAction.label}),(0,ce.jsx)(L.Button,{onClick:m,variant:"secondary",children:i("removeCue")})]}),(0,ce.jsx)(Ts,{evaluationId:t.evaluationId,assistantCode:t.rule.label,assistantOutput:t.text,feedbackText:t.text,feedbackType:"assistant"})]})]})},Kp=sh;var Wn=require("react/jsx-runtime"),ih=({cues:t})=>{let e=(0,zp.useDispatch)(),n=ge(),o=R(zo),r=V(),s=l=>{e(ys({code:l.rule.label})),r("Assistant response closed",{evaluationId:l.evaluationId,assistantCode:l.rule.label,assistantOutput:l.text})},i=(l,c)=>{We(l),r("Assistant response copied",{evaluationId:c.evaluationId,assistantCode:c.rule.label,assistantOutput:c.text,copiedText:l})},a=(l,c)=>{var u;c.callToAction&&(e(hs(c)),r("Assistant call to action",{evaluationId:c.evaluationId,assistantCode:c.rule.label,assistantOutput:c.text,eventName:c.callToAction.event,value:(u=c.callToAction.value)!=null?u:l}))},d=(l,c)=>{var u;n.send(nt,{text:l,suggestion:{source:"assistant",assistantCode:(u=c.rule)==null?void 0:u.label,sourceText:l}}),r("Assistant response used",{evaluationId:c.evaluationId,assistantCode:c.rule.label,assistantOutput:c.text,usedText:l})};return(0,Wn.jsx)(Wn.Fragment,{children:t.map(l=>l.isLoading?(0,Wn.jsx)(bs,{title:l.rule.label.startsWith("__")?o(l.rule.label):l.title},l.rule.id):(0,Wn.jsx)(Kp,{cue:l,onCallToAction:a,onRemove:s,onCopy:i,onUse:d},l.evaluationId))})},Wp=ih;var ws=require("react");var Vp={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var he=require("react/jsx-runtime");function ah(t,e){return e.split(".").reduce((n,o)=>!n||typeof n!="object"||!(o in n)?null:n[o],t)}var jp=({data:t,schema:e})=>{let n=x("WidgetCustomData",Vp),o=r=>{We(r)};return(0,ws.useEffect)(()=>{k.info("Custom data",t,e)},[t]),(0,he.jsx)("dl",{className:n.root,children:e.map(r=>{let s=ah(t,r.path);return(0,he.jsxs)(ws.Fragment,{children:[(0,he.jsx)("dt",{className:n.label,children:r.label}),(0,he.jsx)("dd",{className:n.value,children:r.type==="boolean"&&s?(0,he.jsx)("span",{className:n.isTrue,children:r.trueValue}):r.type==="boolean"&&!s?(0,he.jsx)("span",{className:n.isFalse,children:r.falseValue}):r.type==="array"&&Array.isArray(s)&&s.length>0?(0,he.jsxs)("button",{type:"button",onClick:()=>o(s.join(", ")),className:n.copyButton,children:[(0,he.jsx)("span",{className:n.copyButtonText,children:s.join(", ")}),(0,he.jsx)(Kn,{})]}):typeof s=="string"||typeof s=="number"?(0,he.jsxs)("button",{type:"button",onClick:()=>o(`${s}`),className:n.copyButton,children:[(0,he.jsx)("span",{className:n.copyButtonText,children:s}),(0,he.jsx)(Kn,{})]}):"-"})]},r.label)})})};var j=require("react"),ks=require("react-redux");var Vn={};Y(Vn,{enUS:()=>lh,nlNL:()=>dh});var lh={inputPlaceholder:[{type:0,value:"What is your question?"}],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"}],submitLabel:[{type:0,value:"Submit"}],resetLabel:[{type:0,value:"Reset"}],showMore:[{type:0,value:"Show "},{type:1,value:"amount"},{type:0,value:" more"}]},dh={inputPlaceholder:[{type:0,value:"Wat is je vraag?"}],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"}],submitLabel:[{type:0,value:"Verzend"}],resetLabel:[{type:0,value:"Gesprek wissen"}],showMore:[{type:0,value:"Toon "},{type:1,value:"amount"},{type:0,value:" meer"}]};var Es={form:"dd-pleCH",formInput:"dd-pGJMY",formSubmit:"dd--gkRg",actionButton:"dd-I2NEH",resetContainer:"dd-qKIDX",sources:"dd-xf9c6",source:"dd-a-vyX",tooltip:"dd-EsgcZ",linkContent:"dd-gARDA",showMoreSources:"dd-uDGi-"};var Gp=require("react");var $p={error:"dd-CoAuB"};var sa={};Y(sa,{enUS:()=>ch,nlNL:()=>ph});var ch={errorPrefix:[{type:0,value:"Error:"}]},ph={errorPrefix:[{type:0,value:"Foutmelding:"}]};var Wo=require("react/jsx-runtime"),qp=({message:t})=>{let e=(0,Gp.useRef)(null),n=x("WidgetCardError",$p),o=R(sa);return rr(e),(0,Wo.jsx)(L,{ref:e,children:(0,Wo.jsx)(F,{children:(0,Wo.jsxs)(F.Content,{className:n.error,children:[o("errorPrefix")," ",t]})})})};var D=require("react/jsx-runtime"),uh=3,mh=({sources:t,onClick:e})=>{let n=R(Vn),o=x("WidgetKnowledgeAssistant",Es),[r,s]=(0,j.useState)(!1),i=r?t:t.slice(0,uh);return i.length===0?null:(0,D.jsxs)("ul",{className:o.sources,children:[i.map(a=>(0,D.jsx)("li",{className:o.source,"data-testid":"knowledge-assist-source",children:(0,D.jsxs)(ee,{tooltip:!0,placement:"top-start",children:[(0,D.jsx)(ee.Trigger,{as:"a",rel:"noreferrer",target:"_blank",href:a.url,onClick:()=>e(a),children:(0,D.jsx)("span",{className:o.linkContent,children:a.name})}),a.url&&(0,D.jsx)(ee.Content,{className:o.tooltip,children:decodeURIComponent(a.url)})]})},a.name)),i<t&&(0,D.jsx)("button",{type:"button",className:o.showMoreSources,onClick:()=>s(!0),children:n("showMore",{amount:t.length-i.length})})]})},gh=({title:t,description:e})=>(0,D.jsx)(L,{"data-testid":"knowledge-assist-empty-state",children:(0,D.jsx)(F,{children:(0,D.jsxs)(F.Content,{children:[(0,D.jsx)(F.Title,{children:t}),(0,D.jsx)(ln,{content:e})]})})}),fh=({innerRef:t,item:e,hasKeyboardInput:n,onCopy:o,onUse:r,onSourceClick:s})=>{var d;let i=R(Vn),a=(0,j.useContext)(Rs);return(0,D.jsxs)(L,{"data-testid":"knowledge-assist-answer",ref:t,children:[(0,D.jsx)(F,{children:(0,D.jsxs)(F.Content,{children:[(0,D.jsx)(F.Title,{children:e.question}),(0,D.jsx)(ln,{content:e.answer.answer,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:o,onUse:n?r:void 0}),(0,D.jsx)(mh,{sources:(d=e.answer.sources)!=null?d:[],onClick:s})]})}),a.assistantCode&&(0,D.jsxs)(L.ButtonsContainer,{children:[(0,D.jsx)("div",{}),(0,D.jsx)(Ts,{evaluationId:e.evaluationId,feedbackType:"assistant",assistantCode:a.assistantCode,assistantOutput:e.answer.answer,feedbackText:e.answer.answer})]})]})},Rs=(0,j.createContext)(null),Ps=({assistantCode:t,evaluateKnowledgeAssistFn:e,initialQuestion:n,children:o})=>{let[r,s]=(0,j.useState)(null),[i,a]=(0,j.useState)(!1),[d,l]=(0,j.useState)(null),[c,u]=(0,j.useState)(!!n),[p,g]=(0,j.useState)(null),f=(0,ks.useDispatch)(),m=V(),h=xs(b=>{if(!t)throw new Error("No knowledge assistant was defined");return l(null),e({assistantCode:t,input:b,threadId:r,onNewThreadId(w){s(w)}})},{onSuccess(b){var w;m("Assistant response displayed",{evaluationId:b.evaluationId,assistantCode:t,assistantOutput:b.answer.answer,input:b.question,sources:(w=b.answer.sources)!=null?w:[]}),u(!1)},onError(b){var w;l((w=b.message)!=null?w:"Unknown error")}}),C=b=>v(null,null,function*(){a(!0),g(b),yield h.call(b),a(!1),g(null)}),T={isEnabled:!!t,assistantCode:t,isSubmitting:i,threadId:r,pendingInput:p,errorMessage:d,onSubmit:C,onReset(){r&&f(cp(r)),l(null),s(null),t&&m("Assistant thread reset",{threadId:r!=null?r:void 0,assistantCode:t})}};return(0,j.useEffect)(()=>{n&&T.isEnabled&&C(n)},[n]),(0,D.jsx)(Rs.Provider,{value:T,children:o})},Is=()=>{let t=R(Vn),e=x("WidgetKnowledgeAssistant",Es),n=(0,j.useContext)(Rs),o=(0,j.useRef)(null),[r,s]=(0,j.useState)(""),i=d=>{s(d.target.value)},a=d=>{d.preventDefault(),n.onSubmit(r).then(()=>{var l;o.current&&((l=o.current)==null||l.focus(),s(""))})};return n.isEnabled?(0,D.jsxs)("form",{className:e.form,onSubmit:a,children:[(0,D.jsx)("input",{ref:o,className:e.formInput,placeholder:t("inputPlaceholder"),type:"text",disabled:n.isSubmitting,value:r,onChange:i}),(0,D.jsx)("button",{type:"submit",disabled:n.isSubmitting||r==="",className:e.formSubmit,children:t("submitLabel")})]}):null},Ls=({title:t,emptyState:e})=>{var f,m;let n=R(Vn),o=V(),r=x("WidgetKnowledgeAssistant",Es),s=(0,j.useRef)(null),i=(0,j.useContext)(Rs),a=(m=(0,ks.useSelector)(lp((f=i.threadId)!=null?f:-1)))!=null?m:[],d=E("hasKeyboardInput"),l=ge(),c=(h,C)=>{We(h),i.assistantCode&&o("Assistant response copied",{assistantCode:i.assistantCode,assistantOutput:h,copiedText:h,evaluationId:C.evaluationId})},u=(h,C)=>{i.assistantCode&&o("Assistant source clicked",{evaluationId:C.evaluationId,assistantCode:i.assistantCode,source:h})},p=h=>{h.preventDefault(),i.onReset()},g=(h,C)=>{l.send(nt,{text:h,suggestion:{source:"assistant",sourceText:h}}),i.assistantCode&&o("Assistant response used",{assistantCode:i.assistantCode,evaluationId:C.evaluationId,assistantOutput:C.answer.answer,usedText:h})};return!i.isEnabled||(a==null?void 0:a.length)===0&&!i.isSubmitting&&!e&&!i.errorMessage?null:(0,D.jsxs)(j.Fragment,{children:[(0,D.jsx)(Ke,{type:"knowledge",title:t,"data-testid":"knowledge",children:(0,D.jsxs)(ie,{withDivider:!0,children:[e&&a.length===0&&!i.pendingInput&&(0,D.jsx)(gh,y({},e)),a.map((h,C)=>(0,D.jsx)(fh,{innerRef:C===a.length-1?s:void 0,item:h,hasKeyboardInput:d,onCopy:T=>c(T,h),onUse:T=>g(T,h),onSourceClick:T=>u(T,h)},`${h.question}_${h.answer}_${C}`)),i.pendingInput&&(0,D.jsx)(bs,{title:i.pendingInput}),i.errorMessage&&(0,D.jsx)(qp,{message:i.errorMessage})]})}),a.length>0&&(0,D.jsx)("div",{className:r.resetContainer,children:(0,D.jsx)(L.Button,{disabled:i.threadId===null||i.isSubmitting,onClick:p,children:n("resetLabel")})})]})};var Qp=require("react");var hh=/(https?:\/\/[^\s]+)/,Jp=t=>t.split(" ").find(e=>hh.test(e));var Ie=require("react/jsx-runtime"),yh=({suggestion:t,lines:e,onUse:n})=>{var u;let o=t.text||t.url||t.message,r=Jp(o),s=R(Po),i=E("showImages"),a=E("fallbackImage"),d=E("hasKeyboardInput"),l=p=>{p.preventDefault(),p.stopPropagation(),d&&n(o)},c=(0,Qp.useCallback)(p=>{window.open(r,"_blank"),p.stopPropagation(),p.preventDefault()},[r]);return(0,Ie.jsxs)(L,{onClick:d?l:void 0,"data-testid":"edit-suggestion",children:[(0,Ie.jsxs)(F,{children:[i&&t.image&&(0,Ie.jsx)(F.Image,{src:cs(t,"small",a||void 0),title:t.title}),(0,Ie.jsxs)(F.Content,{children:[t.title&&(0,Ie.jsx)(F.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((u=t.searchKeywords)==null?void 0:u.length)>0&&(0,Ie.jsx)(L.Labels,{labels:t.searchKeywords}),(0,Ie.jsx)(F.Content,{cropText:e==="single",lineClamp:e==="multiple",children:o})]})]}),(0,Ie.jsxs)(L.Actions,{children:[r&&(0,Ie.jsx)(L.ActionButton,{onClick:c,label:s("visitUrl")}),d&&(0,Ie.jsx)(L.ActionButton,{primary:!0,onClick:l,label:s("useSuggestion")})]})]})},Zp=yh;var Vo=require("react/jsx-runtime"),vh=({lines:t,suggestions:e})=>{let n=ge(),o=(r,s)=>{n.send(nt,{text:r,suggestion:S(y({},s),{source:s.source,sourceText:s.text})})};return(0,Vo.jsx)(Vo.Fragment,{children:e.map(r=>(0,Vo.jsx)(Zp,{suggestion:r,lines:t,onUse:s=>o(s,r)},r.text||r.url||r.message))})},Yp=vh;var jo={};Y(jo,{enUS:()=>xh,nlNL:()=>Sh});var xh={waiting:[{type:0,value:"Loading\u2026"}],waitingForConversation:[{type:0,value:"Waiting for conversation\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],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"}],close:[{type:0,value:"Close"}]},Sh={waiting:[{type:0,value:"Laden\u2026"}],waitingForConversation:[{type:0,value:"Wachten op gesprek\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],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"}],close:[{type:0,value:"Sluiten"}]};var jn={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",footer:"dd-tvofr",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",footerShortcut:"dd-dH7XJ",link:"dd-DRo0x"};var P=require("react/jsx-runtime"),eu=(t,e)=>{let n=(0,q.useSelector)(ne);(0,Ot.useEffect)(()=>n?e.every(o=>!!o)?t():()=>{}:()=>{},[...e,n])},bh=({onLogIn:t})=>{let e=x("Widget",jn),n=E("isEmbedded"),o=E("adminUrl");return(0,P.jsx)("div",{className:e.loginText,children:(0,P.jsx)("div",{children:(0,P.jsx)(Qr,{isEmbedded:n,loginUrl:o,onLogIn:t})})},"login")},ia=({text:t})=>{let e=x("Widget",jn);return(0,P.jsx)("div",{className:e.stateText,children:(0,P.jsx)("div",{children:(0,P.jsx)("p",{children:t})})},"notification")},Ch=()=>{let t=R(jo),e=(0,q.useDispatch)(),n=x("Widget",jn),o=E("showSearch"),r=E("isEmbedded"),s=(0,q.useSelector)(kt("/admin/")),i=ge(),a=E("productName"),d=V();return eu(()=>{if(r)return e($i()),()=>{e(fp())}},[e,r]),!o&&!s?null:(0,P.jsxs)("div",{className:n.shortcutList,children:[o&&(0,P.jsx)(L.Button,{"data-testid":"shortcut-search","aria-label":t("linkSearch"),className:n.shortcut,icon:(0,P.jsx)(Nn,{}),onClick:()=>{i.send("ShowCommandPalette",{isOpen:!0}),d("open search",{via:"widget-shortcut"})},children:t("linkSearch")}),s&&(0,P.jsx)(L.Button,{as:"a",target:"_blank",icon:(0,P.jsx)(bp,{}),href:s,"data-testid":"shortcut-studio-login","aria-label":t("linkStudioLogin",{productName:a}),className:n.shortcut,rel:"noreferrer",onClick:()=>{d("open my deepdesk",{via:"widget-shortcut"})},children:t("linkStudioLogin",{productName:a})})]})},Th=({title:t,content:e})=>{let n=R(jo),[o,r]=(0,Ot.useState)(!0);return o?(0,P.jsx)(Ke,{"data-testid":"custom-data-banner",type:"custom-data-banner",title:t,children:(0,P.jsx)(ie,{withDivider:!0,children:(0,P.jsxs)(L,{children:[(0,P.jsx)(F,{children:(0,P.jsx)(F.Content,{children:(0,P.jsx)(ln,{content:e})})}),(0,P.jsx)(L.ButtonsContainer,{children:(0,P.jsx)(L.Button,{onClick:()=>r(!1),children:n("close")})})]})})}):null},wh=()=>{let t=(0,q.useDispatch)(),e=(0,q.useSelector)(bo),n=(0,q.useSelector)(ud),o=(0,q.useSelector)(vp),r=(0,q.useSelector)(Ll),s=(0,q.useSelector)(Fr),i=(0,q.useSelector)(Wr),a=(0,q.useSelector)(Jt),d=(0,q.useSelector)(ze);return(0,Ot.useEffect)(()=>{!!r&&!n&&k.warn("Custom data provided, but no schema.")},[r,n]),eu(()=>{e.forEach(({type:l})=>{l==="entities"?t(Fe()):ar.includes(l)||t(He(l))})},[t,d,a]),(0,Ot.useEffect)(()=>{o.length>0&&!e.some(l=>l.type==="cues")&&k.warn("Received cues, but cues are not configured in widget.")},[e,o]),(0,P.jsx)(Ot.Fragment,{children:e.map(({type:l,title:c,amount:u,lines:p,schema:g,property:f})=>{var m,h;switch(l){case"entities":return s&&s.length>0&&(0,P.jsx)(Ke,{type:l,title:c,"data-testid":`type-${l}`,children:(0,P.jsx)(Sp,{entities:s})},l);case"cues":return o&&o.length>0&&(0,P.jsx)(Ke,{type:l,title:c,"data-testid":`type-${l}`,children:(0,P.jsx)(ie,{withDivider:!0,children:(0,P.jsx)(Wp,{cues:o})})},l);case"custom-data-banner":return r&&f&&r[f]&&(0,P.jsx)(Th,{title:c,content:String(r[f])},l);case"custom-data":return r&&g&&(0,P.jsx)(Ke,{type:l,title:c,"data-testid":`type-${l}`,children:(0,P.jsx)(ie,{withDivider:!0,children:(0,P.jsx)(jp,{data:r,schema:g})})},l);default:return((h=(m=i[l])==null?void 0:m.suggestions)==null?void 0:h.length)>0&&(0,P.jsx)(Ke,{type:l,title:c,"data-testid":`type-${l}`,children:(0,P.jsx)(ie,{withDivider:!0,children:(0,P.jsx)(Yp,{lines:p,contentType:l,suggestions:i[l].suggestions.slice(0,u)||[]})})},l)}})})},aa=({children:t})=>{let e=x("Widget",jn);return(0,P.jsx)("div",{className:e.footer,children:t})},la=({children:t})=>{let e=x("Widget",jn);return(0,P.jsx)("div",{className:e.root,"data-testid":"widget",children:t})},Eh=({onLogIn:t,knowledgeAssistOptions:e={},assistantOptions:n={transcript:"in-memory-transcript"}})=>{let o=R(jo),r=(0,q.useSelector)(bn),s=(0,q.useSelector)(ne),i=(0,q.useSelector)(ml),a=(0,q.useSelector)(Jt),d=(0,q.useSelector)(pd("knowledge-assist")),l=(0,q.useSelector)(md);return r===!1?(0,P.jsx)(ia,{text:o("notSupported")}):s===!1?(0,P.jsx)(bh,{onLogIn:t}):s===null?(0,P.jsx)(ia,{text:o("waiting")}):!i||!a?(0,P.jsx)(ia,{text:o("waitingForConversation")}):(0,P.jsx)(la,{children:(0,P.jsxs)(Ps,{initialQuestion:e.initialQuestion,assistantCode:l!=null?l:void 0,evaluateKnowledgeAssistFn:Bo,children:[(0,P.jsxs)(hn,{children:[(0,P.jsx)(Ch,{}),(0,P.jsx)(wh,{}),d&&(0,P.jsx)(Ls,{title:d.title,emptyState:e.emptyState})]}),(0,P.jsxs)(aa,{children:[d&&(0,P.jsx)(Is,{}),(0,P.jsx)(Ap,{assistantOptions:n})]})]})})},tu=Eh;function $n(t){let e=new Range;return e.selectNodeContents(t),e}function nu(t,e,n){try{return Dt(t,e,n),!0}catch(o){return!1}}function As(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function Ms(t){return"tagName"in t&&t.tagName==="BR"}var $o=/[\u200B-\u200D\uFEFF]/g;function Dt(t,e,n){let o=new Range;if(t.firstChild===null&&e===0&&n===0)return o.selectNodeContents(t),o;let r=0,s=!1;function i(d,l){let c=-1,u=/[\u200B-\u200D\uFEFF]/;if(!u.test(d))return l;for(let p=0;p<=d.length;p++)if(u.test(d[p])||c++,c===l)return p;throw new Error("Offset out of range")}function a(d){switch(d.nodeType){case Node.TEXT_NODE:{let l=d.textContent,c=l.replace($o,""),u=r+c.length,p=e>=r&&e<=u,g=n>=r&&n<=u;if(p){let f=i(l,e-r);f===0&&!g?o.setStartBefore(d):o.setStart(d,f)}g&&(o.setEnd(d,i(l,n-r)),s=!0),r=u;break}case Node.ELEMENT_NODE:{if(Ms(d)&&(r===e&&o.setStartBefore(d),r++,r===n)){o.setEndAfter(d),s=!0;return}for(let c=0;c<d.childNodes.length&&(a(d.childNodes[c]),!s);c++);let l=d.lastChild;As(d)&&l&&!As(l)&&!Ms(l)&&r++;break}default:break}}if(a(t),o.startContainer===document)throw new Error("Offsets out of bound");return o}function Go(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:o,endContainer:r,endOffset:s,collapsed:i}=e,a,d,l=0;function c(u){let p=u===t,g=u===n,f=u===r;switch(u.nodeType){case Node.TEXT_NODE:{let m=u.textContent;g&&(a=l+m.substring(0,o).replace($o,"").length),f&&(d=l+m.substring(0,s).replace($o,"").length),l+=m.replace($o,"").length;break}case Node.ELEMENT_NODE:{if(Ms(u)&&u.nextSibling){l++;break}!p&&As(u)&&u.previousSibling&&l++;for(let m=0;m<u.childNodes.length;m++){let h=g&&m===o,C=f&&m===s;if(h&&(a=l),C&&(d=l),d!==void 0||((!h||!i)&&c(u.childNodes[m]),f&&m===s-1&&(d=l),d!==void 0))break}f&&(d=l);break}default:break}}if(c(t),d===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:d,end:d}}function qo(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:o,endContainer:r,endOffset:s,collapsed:i}=e,a=0,d="";function l(c){let u=c===t,p=c===n,g=c===r;switch(p&&(a=1),c.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let f=p?o:0,m=g?s:void 0;d+=c.textContent.replace($o,"").substring(f,m);break}case Node.ELEMENT_NODE:{if(!i&&a===1&&Ms(c)&&c.nextSibling){d+=`
|
|
15
15
|
`;break}!u&&!i&&a===1&&As(c)&&c.previousSibling&&(d+=`
|
|
16
|
-
`);let f=p?o:0,m=g?Math.min(s,c.childNodes.length):c.childNodes.length;for(let h=f;h<m&&(l(c.childNodes[h]),a!==2);h++);break}default:break}g&&(a=2)}return l(t),d}var ou=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(ou||{}),ht=class{constructor(e){this.element=e;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(e,n){let o=r=>{n(r)};this.element.addEventListener(e,o),this.disposeHandlers.push(()=>{this.element.removeEventListener(e,o)})}removeEventListener(e,n){this.element.removeEventListener(e,n)}handleInteraction(){let e=this.getText(),n=this.getHTML(),o=this.getSelection(),r=this.cachedCaretPosition===null;if(!this.isActive||(e===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),e!==this.cachedText?(this.cachedText=e,this.cachedHTML=n,r=!0,this.emit("change",{plainText:e,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,r=!0,this.emit("change",{plainText:e,rawHTML:n})),(o.start!==this.cachedSelection.start||o.end!==this.cachedSelection.end)&&(this.cachedSelection=o,r=!0,this.emit("selection",o)),!r))return;let s=this.getCaretPosition();Ct(s,this.cachedCaretPosition)||(this.cachedCaretPosition=s,this.emit("caretposition",s))}handleClick(){this.handleInteraction()}handleFocus(){let e=!this.isFocused;this.isFocused=!0,e&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let e=this.isFocused;this.isFocused=!1,e&&this.emit("blur")}handleKeyDown(e){let{key:n,ctrlKey:o,metaKey:r}=e;this.isPossibleClearInputAction=Object.values(ou).includes(n)||n.toLowerCase()==="z"&&(o||r),this.emit("keydown",e)}handleKeyUp(e){this.handleInteraction(),this.emit("keyup",e)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){var o,r;let n=((o=e.clipboardData)==null?void 0:o.getData("text"))||((r=e.clipboardData)==null?void 0:r.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 e=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});e.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{e.disconnect()})}focus(){this.element.focus()}emit(e,...n){this.isDisposed||this.eventListeners[e]&&this.eventListeners[e].forEach(o=>{o(...n)})}on(e,n){this.isDisposed||(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n))}off(e,n){if(!this.eventListeners[e])return;let o=this.eventListeners[e].indexOf(n);o!==-1&&this.eventListeners[e].splice(o,1)}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};function ru(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var cn=class extends ht{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),qo(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){let n=this.getRootNode();if(n.activeElement!==this.element)return null;let o="getSelection"in n?n.getSelection():window.getSelection();if(!o)return null;let r=o.rangeCount>0?o.getRangeAt(0):null;if(!r)return null;let s=this.element.ownerDocument.createRange();return s.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),s.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let o=n.getBoundingClientRect();return!ru(o)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=n.getBoundingClientRect(),n.deleteContents(),!ru(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let n=this.getRange();if(n)return Go(this.element,n);let o=this.lastKnownSelection;if(o&&nu(this.element,o.start,o.end))return o;let r=$n(this.element);return r.collapse(!1),Go(this.element,r)}getSelectedText(){let{start:n,end:o}=this.getSelection();return qo(this.element,Dt(this.element,n,o))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let o=this.element.isContentEditable,r=new MutationObserver(()=>{this.element.isContentEditable!==o&&(o=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>r.disconnect())}};var kh=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function su(t,e){let n="mozInnerScreenX"in window,o=document.createElement("div");o.id="input-textarea-caret-position-mirror-div";let r=o.style,s=window.getComputedStyle(t),i=t.ownerDocument.body;r.whiteSpace="pre-wrap",r.wordWrap="break-word",r.position="absolute",r.visibility="hidden",kh.forEach(c=>{r[c]=s[c]}),n?t.scrollHeight>Number.parseInt(s.height)&&(r.overflowY="scroll"):r.overflow="hidden",o.textContent=t.value.substring(0,e);let a=document.createElement("span");a.textContent=t.value.substring(e)||".",o.appendChild(a),i.appendChild(o);let d=t.getBoundingClientRect(),l={top:d.top-t.scrollTop+a.offsetTop+Number.parseInt(s.borderTopWidth)+a.offsetHeight,left:d.left-t.scrollLeft+a.offsetLeft+Number.parseInt(s.borderLeftWidth)};return i.removeChild(o),l}var pn=class extends ht{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:o}=this.element;return{start:n,end:o}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return su(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let o=this.element.disabled,r=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>r.disconnect())}};function iu(t,e,n){let o=`deepdesk-iframe-${t}`,r=document.getElementById(o);if(r)return r;let s=document.createElement("iframe"),i=new URL(e);return Object.entries(n).forEach(([a,d])=>{i.searchParams.append(a,d)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=o,s.title=`iframe-${t}`,s.src=i.toString(),window.document.body.appendChild(s),s}function Rh(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch(e){return t}}var da=class{constructor(e){this.name=e;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(e)}onMessage(e){this.broadcastChannel.addEventListener("message",e),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",e)})}postMessage(e){this.broadcastChannel.postMessage(JSON.stringify(e))}close(){this.disposeHandlers.forEach(e=>e()),this.broadcastChannel.close()}},ca=class{constructor(e,n,o){this.name=e;this.targetOrigin=n;this.options=o;this.disposeHandlers=[];this.iframe=iu(e,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(e),this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(n=>n()),(e=this.iframe)==null||e.remove()}},pa=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.externalId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setExternalId(e){this.externalId!==e&&(this.cleanup(),k.info("Set externalId",e),this.externalId=e,this.channel=this.createChannel(e))}createChannel(e){let n=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new ca(e,this.deepdeskUrl,{debug:!0}):new da(e),o=r=>{var i,a;if(r.origin!==this.deepdeskUrl)return;let s=Rh(r.data);typeof s!="object"||s.type!=="event"||s.channel!==e||(k.info("Received broadcast event",this.externalId,r),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(o),n}send(e,n,o){var i,a;k.info("Broadcast event",{externalId:this.externalId,name:e,payload:n});let r={type:"event",name:e,payload:n};o!==!1&&((a=(i=this.eventMap)[e])==null||a.call(i,n));let s=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(S(y({},r),{channel:this.externalId}))}cleanup(e=!1){var n,o;(n=this.channel)==null||n.close(),this.channel=void 0,e&&((o=this.defaultChannel)==null||o.close(),this.defaultChannel=void 0)}},au=pa;function Ph(t){return t.replace(/(_\w)/g,e=>e[1].toUpperCase())}function z(t){return Array.isArray(t)?t.map(z):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>S(y({},e),{[Ph(n)]:z(t[n])}),{}):t}function Ih(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function pe(t){return Array.isArray(t)?t.map(pe):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>S(y({},e),{[Ih(n)]:pe(t[n])}),{}):t}var Gn=class extends Error{constructor(n,o){super(n);this.body=o;this.name="CustomError"}};var ua=t=>new Promise(e=>{setTimeout(e,t)});var qn=class extends Gn{constructor(){super(...arguments);this.name="ClientError"}},ga=class extends Gn{constructor(){super(...arguments);this.name="ServerError"}},ma=new Map;function Lh(t){return v(this,null,function*(){if(t.status===204)return t.text().catch(()=>{}),null;let e=t.headers.get("content-type");if(e!=null&&e.includes("application/json"))return t.json();let n=yield t.text();return n===""?null:(k.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var _t=class _t{constructor(e="",n={}){this.baseUrl=e;this.options=n;this.latestRequestByUrl={};var o;this.fetch=(o=n.fetch)!=null?o:window.fetch.bind(window)}patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,n={}){return new Promise((o,r)=>{let s={isAborted:!1,reject:r},i=`${this.baseUrl}${e}`,a=this.fetch,d=n.method===void 0||n.method.toLowerCase()==="get",N=n,{useCache:l=!1,abortLatest:c=!1,attempts:u=1,retryDelay:p=500,refreshTokenOn401:g=!0,retryOnError:f=B=>B instanceof TypeError,retryOnResponse:m=B=>B.status>=500,version:h=null}=N,C=M(N,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(l){if(!d)throw new Error(`Can't use 'useCache' for ${n.method}`);if(ma.has(i)){o(ma.get(i));return}}let T=S(y({credentials:"include"},C),{headers:y({Accept:"application/json","Content-Type":"application/json"},C.headers)});!d&&this.csrfToken&&(T.headers=S(y({},T.headers),{"X-CSRFToken":this.csrfToken})),typeof h=="string"&&(T.headers=S(y({},T.headers),{"X-Deepdesk-API-Version":h}));let b=u,w=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let I=()=>v(this,null,function*(){return b--,a(i,T).then(B=>v(this,null,function*(){return m(B)&&!s.isAborted&&b>0?(yield ua(p),I()):B.status===401&&g===!0&&w===!1?(w=!0,yield this.refreshToken(),I()):B})).catch(B=>v(this,null,function*(){if(f(B)&&!s.isAborted&&b>0)return yield ua(p),I();throw B}))});I().then(B=>v(this,null,function*(){let X=yield Lh(B);if(delete this.latestRequestByUrl[i],B.status>=500){r(new ga("Server Error",X));return}if(B.status===401){r(new qn("Unauthorized",X));return}if(B.status===403){r(new qn("Forbidden",X));return}if(B.status===404){r(new qn("Not Found",X));return}if(B.status>=400){r(new qn("Bad Request",X));return}l&&ma.set(i,X),o(X)})).catch(B=>{r(B)})})}validateToken(){return v(this,null,function*(){let{has_valid_access_token:e,is_logged_in:n}=yield this.get("/apis/admin/session/validate/");if(!e)try{yield this.refreshToken();let{is_logged_in:o}=yield this.get("/apis/admin/session/validate/");return o}catch(o){return!1}return n})}refreshToken(){return _t.refreshingToken||(_t.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{_t.refreshingToken=null},1e3*60)})),_t.refreshingToken}get(e,n){return this.request(e,n)}post(e,n,o){return this.request(e,y({method:"POST",body:JSON.stringify(n)},o))}patch(e,n,o){return this.request(e,y({method:"PATCH",body:JSON.stringify(n)},o))}put(e,n,o){return this.request(e,y({method:"PUT",body:JSON.stringify(n)},o))}delete(e,n){return this.request(e,y({method:"DELETE"},n))}};_t.refreshingToken=null;var un=_t;var lu;(e=>{let t;(a=>(a.SUCCESS="success",a.FAILURE="failure",a.CONDITIONS_NOT_MET="conditions_not_met",a.MAX_RECURSION_LEVEL="max_recursion_level",a.NO_ACCESS_TO_ASSISTANT="no_access_to_assistant"))(t=e.EvaluationStatus||(e.EvaluationStatus={}))})(lu||(lu={}));function fa(t){return S(y({},z(t)),{metadata:t.metadata})}var mn=class mn{constructor(e,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new un(e,{fetch:n.fetch}),this.client.patchFetch(o=>(r,s)=>v(this,null,function*(){let i=yield o(r,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return v(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=yield this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(mn.exchangeTokenPromise||(mn.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),mn.exchangeTokenPromise):Promise.resolve()})}createConversation(e){return v(this,null,function*(){var o;yield this.preflight(),k.info(`Creating conversation for session ${e.externalId} and agent ${e.agentId}`);let n=yield this.client.post("/api/v2/conversations",S(y({chat_start_time:new Date().toISOString()},pe(e)),{metadata:(o=e.metadata)!=null?o:{}}));return fa(n)})}getMe(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/session/me/");return z(e)})}postIdentity(e){return v(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",pe(e))})}patchMe(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",pe(e));return z(n)})}getProfile(e){return v(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${e}/`,{useCache:!0});return z(n)})}getKnowledgeAssistant(e){return v(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{useCache:!0});return z(n)})}getContentTypes(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return z(e)})}getAccount(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/account/",{useCache:!0});return z(e)})}getPlatformConfig(e){return v(this,null,function*(){let n=e!==void 0?`/platform/config/${e}/`:"/platform/config/",{config:o}=yield this.client.get(n,{useCache:!0});return z(o)})}checkUserExists(e){return v(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${e}`,{version:"v1"});return n})}getConversationByExternalId(o){return v(this,arguments,function*(e,n={}){yield this.preflight(),k.info(`Getting conversation for session ${e}`);let{attempts:r=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/v2/conversations/by_external_id/${e}`,{attempts:r,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return k.info(`Successfully retrieved conversation ${i.id} for session ${e}`),fa(i)})}isConversationSupported(o){return v(this,arguments,function*(e,n={}){k.info(`Check if conversation for session ${e} is supported`);let{attempts:r=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${e}/has_active_profile`,{attempts:r,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(e,n){return v(this,null,function*(){var s;yield this.preflight();let o=pe(n);n.metadata&&(o.metadata=(s=n.metadata)!=null?s:{});let r=yield this.client.put(`/api/v2/conversations/${e}`,o);return fa(r)})}postMessages(e,n){return v(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${e}/messages`,n.map(o=>S(y({},pe(o)),{metadata:o.metadata})))})}sendEvent(e,n){return v(this,null,function*(){yield this.preflight();let a=n,{data:o}=a,r=M(a,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((d,[l,c])=>S(y({},d),{[l]:c}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((d,l)=>(r[l]&&(d[l]=r[l]),d),{});return this.client.post("/api/v2/events",pe(S(y(y({},s),i),{data:o,name:e})),{version:"v2"})})}getEntities(e){return v(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:e.filter(o=>o.text)})})}getTemporaryExchangeToken(){return v(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(e){return v(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:e}).catch(n=>{throw k.warn(`Invalid token '${e}'`),n})})}authenticateWithKey(e,n){return v(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",pe(n),{refreshTokenOn401:!1,headers:{apikey:e}})})}getTextSuggestions(r){return v(this,arguments,function*(e,n={},o){if(yield this.preflight(),o==="sticky-messages")throw new Error("Use getPinnedMessages instead");return(yield this.client.post(`/api/v2/conversations/${e}/recommend/${o}`,pe(n),{abortLatest:!0})).map(i=>S(y({},z(i)),{text:i.text||i.url||i.message,source:o,type:o})).filter((i,a,d)=>a===d.findIndex(l=>l.text===i.text))})}isLoggedIn(){return v(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(e,n){return v(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${e}/autocomplete`,pe(n),{abortLatest:!0})).map(r=>({score:1,source:r.source,sourceText:r.source_text,text:r.label,trainingJobs:r.training_jobs,searchKeywords:r.search_keywords,type:r.source})).filter((r,s,i)=>s===i.findIndex(a=>a.text===r.text))})}getPinnedMessages(e){return v(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${e}/pinned-messages`,{abortLatest:!0});return z(n).map(o=>S(y({},o),{text:o.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(e){return v(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",pe(e),{abortLatest:!0,version:"v2"});return z(n)})}search(e){return v(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${e.profile}/search`,pe(e));return z(n)})}requestLoginByEmail(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:e});return z(n)})}requestPasswordlessToken(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/session/passwordless/request/");return z(e.token)})}getCsrfToken(){return v(this,null,function*(){let{token:e}=yield this.client.get("/apis/admin/session/csrf/");return e})}verifyLoginToken(e){return v(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:e});return z(n)})}evaluateAssistant(e,n){return v(this,null,function*(){var i;yield this.preflight();let o=new URLSearchParams;n!=null&&n.externalConversationId&&o.append("external_conversation_id",n.externalConversationId);let r=n!=null&&n.threadId?`/api/v2/assistants/${e}/threads/${n==null?void 0:n.threadId}/evaluate?${o.toString()}`:`/api/v2/assistants/${e}/evaluate?${o.toString()}`,s=yield this.client.post(r,{input:(i=n==null?void 0:n.input)!=null?i:{},conversation:n==null?void 0:n.transcript});return z(s)})}createAssistantThread(e){return v(this,null,function*(){yield this.preflight();let{assistantCode:n}=e,o=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return z(o)})}postMessageToAssistantThread(e){return v(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:o,message:r}=e,s=yield this.client.post(`/apis/admin/assistants/${n}/threads/${o}/messages/`,{content:r,role:"user"});return z(s)})}translateMessages(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",pe(e));return z(n)})}handleDeepdeskVersionHeaders(e){e.headers.forEach((n,o)=>{let r=o.toLowerCase(),s=r.match(Ja);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&k.warn(`Overwritten Version header ${r}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};mn.exchangeTokenPromise=null;var yt=mn;var _s=require("@reduxjs/toolkit");var cu=require("@reduxjs/toolkit");var du={startTime:null,stopTime:null},pu=t=>t.handlingTime,uu=(0,cu.createSlice)({name:"handlingTime",initialState:du,reducers:{handlingTimeStart(t){if(t.startTime&&!t.stopTime)throw new Error("Timing already started");t.startTime=new Date,t.stopTime=null},handlingTimeStop(t){if(!t.startTime)throw new Error("Timing not started");t.stopTime=new Date},handlingTimeReset(t){t.startTime=null,t.stopTime=null}},extraReducers:t=>{t.addCase(J,()=>du)}}),{handlingTimeStart:mu,handlingTimeStop:Ns,handlingTimeReset:gu}=uu.actions,fu=uu.reducer;var hu=(t={})=>{let e=y({onAuthError:Sn(!1)},t);return n=>o=>r=>("error"in r&&r.error.message==="Unauthorized"&&n.dispatch(e.onAuthError),o(r))};var Ds=require("@reduxjs/toolkit");var Os={list:{keywordMatches:[]},fetchState:"idle"};var gn=(0,Ds.createAsyncThunk)("styleSuggestions/getAll",(n,o)=>v(null,[n,o],function*({text:t},e){var d;let{deepdeskAPI:r}=e.extra,s=e.getState(),{showStyleSuggestions:i}=s.settings,a=(d=s.conversation.current)==null?void 0:d.profileCode;if(!i)return Os.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return r.getStyleSuggestions({profileCode:a,message:t})})),Ah=(0,Ds.createSlice)({name:"styleSuggestions",initialState:Os,reducers:{},extraReducers:t=>{t.addCase(gn.pending,e=>{e.fetchState="loading"}).addCase(gn.rejected,e=>{e.fetchState="error"}).addCase(gn.fulfilled,(e,n)=>{e.fetchState="done",Ct(e.list,n.payload)||(e.list=n.payload)}).addCase($t,e=>{e.list=Os.list}).addCase(J,()=>Os)}}),yu=Ah.reducer;var vu=(t={})=>{let e,n=!0,o=y({getStyleSuggestions:gn,debounce:500},t);return r=>s=>i=>{var g;let a=r.getState().input.text,d=s(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return d;let{showStyleSuggestions:c}=l.settings;if(!((g=l.conversation.current)==null?void 0:g.id)||!c)return d;let{text:p}=l.input;return p===a&&!n||(clearTimeout(e),p==="")||(e=setTimeout(()=>{n=!1,r.dispatch(o.getStyleSuggestions({text:p}))},t.debounce)),d}};function Mh(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var xu=(t={})=>{let e=y({getTextSuggestions:He,getAutocompleteSuggestions:Lo,debounce:200,check:$e},t),n;return o=>r=>s=>{var m;let{input:i}=o.getState(),a=r(s),d=o.getState();if(d.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:l,showTabCompletion:c}=d.settings,u=(m=d.conversation.current)==null?void 0:m.id,p=s.type===Vr.toString();if(!u||!l&&!c)return a;let{input:g}=d;return Mh(g,i)&&!p||(clearTimeout(n),!e.check(d))||(n=setTimeout(()=>{let h=Cn(d);h===""?o.dispatch(e.getTextSuggestions("default")):o.dispatch(e.getAutocompleteSuggestions(h))},p?0:e.debounce)),a}};var Su=gn.fulfilled.toString();function Nh(t,e){let n=new Set([...e.keywordMatches.map(r=>r.keyword)]),o=[];return n.forEach(r=>{let s=t.keywordMatches.filter(d=>d.keyword===r),i=e.keywordMatches.filter(d=>d.keyword===r),a=i.length-s.length;a<=0||o.push(...i.slice(0,a))}),o}var bu=t=>e=>n=>o=>{var l;if(o.type!==Su){n(o);return}let r=e.getState().styleSuggestions.list;n(o);let s=e.getState(),i=s.styleSuggestions.list,a=(l=s.conversation)==null?void 0:l.current;if(r===i)return;let d=Nh(r,i);o.type===Su&&d.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:d}})};var Oh=(0,_s.combineReducers)({assistants:mp,auth:ll,conversation:gl,contentTypes:dd,passwordlessToken:hp,entities:Od,handlingTime:fu,info:Fl,input:Rl,settings:tl,profile:gd,search:Wl,styleSuggestions:yu,ui:pc,textSuggestions:$d});function Cu(t){return(0,_s.configureStore)({reducer:Oh,middleware:e=>{var o;let n=e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI}},serializableCheck:!1}).concat(hu()).concat(xu({debounce:200})).concat(vu({debounce:500})).concat(bu(t.deepdeskAPI));return((o=t.middleware)!=null?o:[]).reduce((r,s)=>r.concat(s),n)},preloadedState:t.preloadedState})}var Dh=t=>{var e,n;return(n=(e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())!=null?n:"unknown"},_h=t=>e=>n=>o=>{var a,d;let r=e.getState(),s=vn("inlineSuggestions")(r);switch(o.type){case Sn.toString():{!o.payload&&t.emit("logout",void 0);break}case Fe.fulfilled.toString():o.payload.length>0&&t.sendEvent("entities found",{conversationId:(a=r.conversation.current)==null?void 0:a.id,data:{entities:o.payload}});break;case $t.toString():t.logSendMessage(o.payload);break;case hs.toString():t.emit("call-to-action",{cue:o.payload});break;case Xe.fulfilled.toString():o.isBroadcasted||t.broadcast(oi,o,!1);break;default:break}let i=n(o);switch(o.type){case $t.toString():t.handleAfterSendMessage(o.payload);break;case Mo.toString():t.onUpdateShowTabHint(o.payload);break;case Ns.toString():t.logHandlingTime();break;case wn.toString():t.broadcast(Sr,o);break;case jt.toString():t.broadcast(Sr,o);break;case ys.toString():e.dispatch(jt({source:"assistant",assistantCode:o.payload.code}));break;case"analytics/logEvent/fulfilled":{let l=r.assistants.cues.find(c=>c.code===o.meta.arg.data.assistantCode);t.emit("event",S(y({},o.meta.arg),{cue:l}));break}case ye.toString():{let{start:l,end:c}=r.input.selection;t.emit("select-suggestion",S(y({type:Dh(o.payload.suggestion)},o.payload),{replace:o.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}})),s&&e.dispatch(Tt([]));break}case mr.toString():t.emit("select-image",o.payload),t.sendEvent("Image attached",{conversationId:(d=r.conversation.current)==null?void 0:d.id,data:{path:o.payload.suggestion.image,title:o.payload.suggestion.title}});break;case Tt.toString():{s&&o.payload.length>0&&e.dispatch(gr(0));break}default:break}return i},Tu=_h;var wu=require("@reduxjs/toolkit");function ha(t){return t.toISOString().replace("T"," ").replace("Z","")}var Fh=(t,e)=>e.version,Eu=(0,wu.createSelector)([En,ze,pu,Fh],(t,e,n,o)=>{if(!e)return k.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:s}=n;return!r||!s?(k.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:e,clientVersion:o,agentId:t==null?void 0:t.agentId,agentName:t==null?void 0:t.agentName,agentEmail:t==null?void 0:t.agentEmail,timeStart:ha(r),timeStop:ha(s)}});function ku(t,e){let{text:n,metrics:{numPaste:o,pastes:r,textSuggestions:s}}=t.input,i=n.length;return{source:"agent",clientVersion:e.version,pastes:r,lenTextTotal:i,numPastes:o,suggestions:s}}function ya(t,e){var s;let n=t.closest(e);if(n)return n;let o=t.getRootNode().host;if(o instanceof HTMLElement)return ya(o,e);let r=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;return r?ya(r,e):null}function va(t,e){return ya(t,e)}function Ru(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function Hh(t){return typeof t=="object"&&t!==null&&"tagName"in t}function Fs(t){return Hh(t)&&(an(t)||Yr(t))}var Iu,Qe=new Map,Bh=["bottom","height","left","right","top","width"],Pu=(t,e)=>!t&&!e?!1:t&&!e||!t&&e?!0:Bh.some(n=>t[n]!==e[n]);function Lu(t){var n,o,r;if(t.ownerDocument===document)return[];let e=(r=(o=(n=t.ownerDocument)==null?void 0:n.defaultView)==null?void 0:o.frameElement)!=null?r:null;return e?[e,...Lu(e)]:[]}function Au(t,e){return!t||!e?null:S(y({},t),{top:t.top+e.top,left:t.left+e.left})}var Hs=!1,Mu=()=>{Hs=!0;let t=[];if(Qe.forEach((e,n)=>{if(!n.isConnected){e.rect=null,t.push(e),Qe.delete(n);return}let o=n.getBoundingClientRect();Pu(o,e.rect)&&(e.rect=o,t.push(e))}),t.forEach(e=>{let n=e.parentRects?e.parentRects.reduce(Au,e.rect):e.rect;Pu(n,e.totalRect)&&e.callbacks.forEach(o=>o(n)),e.totalRect=n}),Qe.size===0){Hs=!1;return}Iu=window.requestAnimationFrame(Mu)};function xa(t,e){let n=Lu(t),o=[],r=n.map((s,i)=>xa(s,a=>{o[i]=a;let d=Qe.get(t);if(!d)return;let l=o.reduce(Au,d.rect);d.callbacks.forEach(c=>c(l))}));return{observe(s=!0){if(r.forEach(i=>i.observe(!1)),Qe.has(t)){let i=Qe.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else Qe.set(t,{rect:void 0,callbacks:[e],parentRects:o});s&&!Hs&&Mu()},unobserve(){r.forEach(i=>i.unobserve());let s=Qe.get(t);if(s){let i=s.callbacks.indexOf(e);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||Qe.delete(t),Qe.size||(cancelAnimationFrame(Iu),Hs=!1)}}}}var Nu,Ze=new Map,Ou=()=>{Ze.forEach((t,e)=>{if(!e.isConnected){Ze.delete(e);return}let{clientHeight:n,scrollHeight:o}=e,r=o>n;t.visible!==r&&(t.visible=r,t.callbacks.forEach(s=>s(t.visible)))}),Ze.size!==0&&(Nu=window.requestAnimationFrame(Ou))};function Du(t,e){return{observe(){let n=Ze.size===0;Ze.has(t)?Ze.get(t).callbacks.push(e):Ze.set(t,{visible:void 0,callbacks:[e]}),n&&Ou()},unobserve(){let n=Ze.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||Ze.delete(t),Ze.size||cancelAnimationFrame(Nu)}}}}var Sa=["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 ba(t,e,n){return n.forEach(o=>{e.style[o]=t[o]})}function Xn(t){return Number.parseFloat(t)}function Bs(t){return Math.round(t*1e6)}function _u(t){return t/1e6}function Ca(t,e,n){if(t.boxSizing==="content-box")return;let{clientWidth:o}=e,r=Xn(t.width),s=Xn(t.borderLeftWidth),i=Xn(t.borderRightWidth),a=Xn(t.paddingRight),d=_u(Bs(r)-Bs(s)-Bs(i)),l=_u(Bs(o));if(d-l>2){let c=d-l;n.style.paddingRight=`${a+c}px`}}function Xo(t,e={}){var c,u;let n=e.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=e.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",sn(n);let o=window.getComputedStyle(t),r=!0,s=()=>{n.scrollTop=t.scrollTop};ba(o,n,Sa),Ca(o,t,n),e.mirrorOverflow&&(n.style.overflow="hidden",t.addEventListener("scroll",s));let i=Du(t,()=>{ba(o,n,Sa),Ca(o,t,n),s(),setTimeout(s,0)}),a,d=!0,l=xa(t,p=>{if(p===null){e.onRemove&&e.onRemove(),n.remove();return}if(!d&&e.onMoveStart&&(Promise.resolve().then(()=>e.onMoveStart()),d=!0),clearTimeout(a),a=setTimeout(()=>{e.onMoveEnd&&e.onMoveEnd(),d=!1},200),p.height===0&&p.width===0){if(r===!0)return;e.onHide&&e.onHide(),n.style.display="none",r=!0;return}if(ba(o,n,Sa),Ca(o,t,n),s(),e.placement==="below"&&n.classList.add("below"),n.style.top=`${p.top}px`,n.style.left=`${p.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let g=e.closestScrollElement.getBoundingClientRect(),f=window.getComputedStyle(e.closestScrollElement),m=Xn(f.borderTopWidth),h=Xn(f.borderBottomWidth),C=g.top+m-p.top,T=p.top+p.height+-(g.top+g.height-h);n.style.clipPath=`inset(${C}px 0px ${T}px 0px)`}r&&(n.style.display="block",e.onShow&&e.onShow(),r=!1)});return e.appendTo?e.appendTo.appendChild(n):(u=t.parentElement)==null||u.appendChild(n),l.observe(),i.observe(),[n,()=>{t.removeEventListener("scroll",s),l.unobserve(),i.unobserve(),n.remove()}]}var Fu=(t,e)=>({value(){try{let n=sessionStorage.getItem(`dd-${t}`);if(!n)return e;try{return JSON.parse(n)}catch(o){return e}}catch(n){return e}},update(n){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(n))}catch(o){k.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function Uh(t){return t.offsetParent!==null}function Hu(t){if(!Uh(t))return!1;let e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}function Us(t,e,n=100){let o=Hu(t);e({isVisible:o});let r=setInterval(()=>{let s=Hu(t);s!==o&&(o=s,e({isVisible:o}))},n);return()=>{clearTimeout(r)}}var Jo=class extends Error{};function Kh(){let t,e;return{promise:new Promise((o,r)=>{t=o,e=r}),resolve:t,reject:e}}var Ks=class{constructor(){this.queues={}}push(e,n){let o=()=>{let s=this.queues[e][1];s?(this.queues[e]=[s.promise,null],s.resolve()):delete this.queues[e]};if(!this.queues[e]){let s=n().finally(o);return this.queues[e]=[s,null],s}this.queues[e][1]&&this.queues[e][1].reject(new Jo("Queued async function is outdated"));let r=Kh();return this.queues[e][1]=r,r.promise.then(()=>n().finally(o))}};var zh={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},Bu=(t,e)=>{var r,s,i;if(!((i=(s=(r=t.uiConfig)==null?void 0:r.widget)==null?void 0:s.types.find(a=>a.type==="cues"))==null?void 0:i.isActive))return k.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let o=t[zh[e]];return o&&o.length>0?o.map(a=>a.code):(k.warn(`No assistant set in profile for conversation event "${e}"`),[])};var zs=class{constructor(e){this.options=e;this.socket=null;this.maxReconnectAttempts=5;this.reconnectInterval=25e3;this.cleanupCallbacks=[];var n,o;this.socket,this.eventListeners=new Map,this.url=e.url,this.maxReconnectAttempts=(n=e.maxReconnectAttempts)!=null?n:this.maxReconnectAttempts,this.reconnectInterval=(o=e.reconnectInterval)!=null?o:this.reconnectInterval,this.shouldReconnect=e.shouldReconnect}connect(){let e=()=>this.cleanup();window.addEventListener("beforeunload",e),this.cleanupCallbacks.push(()=>window.removeEventListener("beforeunload",e)),this.reconnect()}setupListeners(){this.socket&&(this.socket.onmessage=e=>{var n;try{let o=z(JSON.parse(e.data));o.event&&this.eventListeners.has(o.event)&&((n=this.eventListeners.get(o.event))==null||n.forEach(r=>r(o.data)))}catch(o){console.error("Error parsing WebSocket message:",o)}},this.socket.onclose=e=>{console.log("WebSocket connection closed:",e),setTimeout(()=>{this.reconnect()},this.reconnectInterval)},this.socket.onerror=e=>{console.error("WebSocket error:",e)})}reconnect(){var e,n;if(this.maxReconnectAttempts<=0){console.error("Max reconnect attempts reached, closing WebSocket connection."),(e=this.socket)==null||e.close();return}if(!this.shouldReconnect()){console.error("Should not reconnect, closing WebSocket connection."),(n=this.socket)==null||n.close();return}this.socket&&(this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close()),this.socket=new WebSocket(this.url),this.setupListeners(),this.maxReconnectAttempts--}send(e,n){if(!this.socket){console.error("WebSocket connection is not open.");return}this.socket.send(JSON.stringify({event:e,data:n}))}on(e,n){this.eventListeners.has(e)||this.eventListeners.set(e,[]);let o=this.eventListeners.get(e);o&&!o.includes(n)&&o.push(n)}close(){var e;(e=this.socket)==null||e.close()}cleanup(){this.close(),this.cleanupCallbacks.forEach(e=>e()),this.cleanupCallbacks=[]}};var Ft=O(require("react"));var Uu={root:"dd-7zvcP",dialogContent:"dd-4C0lK",continueButton:"dd-YUPQW",buttonContinueWrapper:"dd-IKpYs",nicknameInput:"dd-rxhGp",titleWrapper:"dd-nw3nD",title:"dd-5iof5",closeButtonWrapper:"dd-UUAzA",closeButton:"dd-7rjP5",buttonsWrapper:"dd-5e9Xb",errorMessage:"dd--5VgX",errorLink:"dd-u461n"};var Ku=require("react-redux");var Ta={};Y(Ta,{enUS:()=>Wh,nlNL:()=>Vh});var Wh={title:[{type:0,value:"Enter your nickname"}],close:[{type:0,value:"Close"}],nicknameDialogTitle:[{type:0,value:"Please enter the name you'd like customers to see during chat conversations. This nickname will be used across your Deepdesk environment."}],nicknameDialogInputPlaceholder:[{type:0,value:"Enter your nickname"}],nicknameDialogContinueButton:[{type:0,value:"Continue"}],nicknameDialogError:[{type:0,value:"Nickname cannot be empty or spaces only"}],nicknameDialogEmojiError:[{type:0,value:"You cannot use emojis in this field."}],nicknameDialogSaveError:[{type:0,value:"We couldn't save your details just now. Please try again, or update it at "},{type:1,value:"account"},{type:0,value:".deepdesk.com/admin/user-settings"}],nicknameDialogSaveErrorWithoutLink:[{type:0,value:"We couldn\u2019t save your details just now. Please try again later, or update them in My Deepdesk \u2192 Settings."}]},Vh={title:[{type:0,value:"Voer je bijnaam in"}],close:[{type:0,value:"Sluiten"}],nicknameDialogTitle:[{type:0,value:"Voer de naam in die je wilt dat klanten zien tijdens chatgesprekken. Deze bijnaam wordt gebruikt in je Deepdesk-omgeving."}],nicknameDialogInputPlaceholder:[{type:0,value:"Voer je bijnaam in"}],nicknameDialogContinueButton:[{type:0,value:"Doorgaan"}],nicknameDialogError:[{type:0,value:"Bijnaam mag niet leeg of alleen spaties zijn"}],nicknameDialogEmojiError:[{type:0,value:"Je kunt geen emoji's gebruiken in dit veld."}],nicknameDialogSaveError:[{type:0,value:"We konden je gegevens nu niet opslaan. Probeer het opnieuw of werk het bij op "},{type:1,value:"account"},{type:0,value:".deepdesk.com/admin/user-settings"}],nicknameDialogSaveErrorWithoutLink:[{type:0,value:"We konden je gegevens nu niet opslaan. Probeer het opnieuw later, of werk ze bij in My Deepdesk \u2192 Instellingen."}]};var Q=require("react/jsx-runtime"),zu=({onClose:t,onSave:e,id:n,error:o})=>{let[r,s]=(0,Ft.useState)(""),[i,a]=(0,Ft.useState)(!1),[d,l]=(0,Ft.useState)(!1),c=x("Nickname",Uu),u=Ft.default.useRef(null),p=(0,Ku.useSelector)(C=>C.info.showNicknameDialog),g=R(Ta),f=E("adminUrl");(0,Ft.useEffect)(()=>{o&&a(!0)},[o]);let m=()=>{if(!u.current)return;r.trim()?u.current.setCustomValidity(""):u.current.setCustomValidity(g("nicknameDialogError")),u.current.reportValidity()},h=C=>{C.preventDefault();let T=r.trim(),b=C.currentTarget.querySelector("#nickname-input");if(!T){b.setCustomValidity(g("nicknameDialogError")),b.reportValidity();return}b.setCustomValidity(""),e(T)};return(0,Q.jsxs)(In,{isOpen:p,"datatest-id":n,onClose:t||(()=>{}),onBack:t||(()=>{}),children:[(0,Q.jsx)("div",{className:c.titleWrapper,children:(0,Q.jsx)("h1",{className:c.title,children:g("title")})}),(0,Q.jsxs)("form",{className:c.dialogContent,onSubmit:h,children:[(0,Q.jsx)("p",{children:g("nicknameDialogTitle")}),i&&o&&(0,Q.jsx)("div",{className:c.errorMessage,children:f?(()=>{let C=g("nicknameDialogSaveError",{account:f}),T=`${f}.deepdesk.com/admin/user-settings`,b=C.indexOf(T);if(b!==-1){let w=C.substring(0,b),I=C.substring(b+T.length);return(0,Q.jsxs)(Q.Fragment,{children:[w,(0,Q.jsx)("a",{href:T,target:"_blank",rel:"noopener noreferrer",className:c.errorLink,children:T}),I]})}return C})():g("nicknameDialogSaveErrorWithoutLink")}),(0,Q.jsx)("input",{required:!0,minLength:1,maxLength:20,"data-testid":"nickname-input",id:"nickname-input",className:c.nicknameInput,type:"text",placeholder:g("nicknameDialogInputPlaceholder"),value:r,onChange:C=>{l(new RegExp("\\p{Extended_Pictographic}","u").test(C.target.value)),s(C.target.value)},onBlur:m,ref:u}),d&&(0,Q.jsx)("div",{className:c.errorMessage,role:"alert",children:g("nicknameDialogEmojiError")}),(0,Q.jsxs)("div",{className:c.buttonsWrapper,children:[o?(0,Q.jsx)("div",{className:c.closeButtonWrapper,children:(0,Q.jsx)("button",{type:"button",className:c.closeButton,onClick:()=>t==null?void 0:t(),children:g("close")})}):null,(0,Q.jsx)("div",{className:c.buttonContinueWrapper,children:(0,Q.jsx)("button",{type:"submit",className:c.continueButton,disabled:!r.trim()||new RegExp("\\p{Extended_Pictographic}","u").test(r),children:g("nicknameDialogContinueButton")})})]})]})]})};var H=require("react/jsx-runtime");var Wu=Fu("showTabHint",!0),Jn=class Jn{constructor({deepdeskUrl:e,version:n=Jn.version||"unknown",locale:o="en-US",token:r,fetch:s,productName:i,createCustomChannel:a,websocketClient:d=zs}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.disposeHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.belowSuggestions=null;this.floatingMenu=null;this.widgetElement=null;this.widgetRoot=null;this.nicknameDialogUnsubscribe=null;this.nicknameDialogFailed=!1;this.dynamicThunkObject={};this.queues=new Ks;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=e.replace(/\/api$/,"");this.deepdeskApi=new yt(l,{token:r,fetch:s}),this.version=n,this.instanceId=Jn.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Tu({broadcast:(f,m,h)=>{this.broadcastEvents.send(f,m,h)},emit:(f,m)=>this.emit(f,m),handleAfterSendMessage:f=>this.handleAfterSendMessage(f),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:f=>this.logSendMessage(f),onUpdateShowTabHint:f=>Wu.update(f),sendEvent:(f,m)=>this.deepdeskApi.sendEvent(f,m)})]};this.store=Cu(c),this.broadcastEvents=new au({debug:!0,deepdeskUrl:l,eventMap:Vl(this.store),createCustomChannel:a}),this.disposeHandlers.push(()=>{this.broadcastEvents.cleanup()}),this.ws=new d({url:`${l}/api/v2/me/realtime`.replace("https","wss"),reconnectInterval:25e3,shouldReconnect:()=>v(this,null,function*(){var f;return(f=ne(this.state))!=null?f:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(Mo(Wu.value())),this.store.dispatch(lr({locale:o,adminUrl:l,productName:i}));let u=[],p=f=>{if(!f.conversationId)return;let m=()=>{this.conversationId()===f.conversationId&&this.store.dispatch(up(f))};this.hasConversation()?m():u.push(m)};this.ws.on("assistants::direct_response",p),this.ws.on("assistants::user_notification",p),this.ws.on("assistants::response_chunk",f=>{if(!f.conversationId)return;let m=()=>{this.conversationId()===f.conversationId&&this.store.dispatch(pp(f))};this.hasConversation()?m():u.push(m)}),this.ws.on("assistants::suggest_as_reply",f=>{if(!f.conversationId)return;let m=()=>{this.conversationId()===f.conversationId&&this.store.dispatch(wn([{text:f.payload.message,type:"text",source:"assistant",assistantCode:f.code,sourceLabel:f.name}]))};this.hasConversation()?m():u.push(m)});let g=this.whenConversationLoaded(()=>{var f;this.broadcastEvents.setExternalId((f=this.state.conversation.current)==null?void 0:f.externalId),u.forEach(m=>m()),u.length=0});this.disposeHandlers.push(()=>{this.ws.cleanup(),u.length=0,g()})}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var e;return(e=Vt(this.state)[this.state.input.selectedSuggestionIndex])!=null?e:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}externalId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.externalId}shouldAbort(){return this.state.conversation.isSupported===!1?(k.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(k.warn("Profile has not been loaded (yet)"),!0):(k.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(e){if(ne(this.state))e();else{let n=this.subscribe(ne,o=>{o&&e()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Sn(null)),this.store.dispatch(tt()),new Promise(e=>{this.whenLoggedIn(()=>e())})}isLoggedIn(){return v(this,null,function*(){return(yield this.store.dispatch(tt())).payload})}isConversationSupported(e,n){return v(this,null,function*(){return(yield this.store.dispatch(Js({externalId:e,options:n}))).payload})}createConversation(e){return v(this,null,function*(){var o;return this.hasConversation()&&this.externalId()!==e.externalId&&this.resetConversation(),(yield this.store.dispatch(cr(S(y({},e),{metadata:(o=e.metadata)!=null?o:{}})))).payload})}getConversationByExternalId(e,n){return v(this,null,function*(){return this.hasConversation()&&this.externalId()!==e&&this.resetConversation(),(yield this.store.dispatch(pr({externalId:e,options:n}))).payload})}upsertConversation(e){return v(this,null,function*(){var o;return this.hasConversation()&&this.externalId()!==e.externalId&&this.resetConversation(),(yield this.store.dispatch(Qs(S(y({},e),{metadata:(o=e.metadata)!=null?o:{}})))).payload})}postMessages(e){return v(this,null,function*(){yield this.store.dispatch(Zs(e))})}updateConversation(e){return v(this,null,function*(){return(yield this.store.dispatch(ur(e))).payload})}resetConversation(){this.store.dispatch(J()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(e){this.store.dispatch(lr(e))}setVisitorInfo(e){this.store.dispatch(Nl(e))}setCustomData(e){this.store.dispatch(Ol(e))}setAgentInfo(e,n){return v(this,null,function*(){var r;yield this.store.dispatch(oo(y(y({},e),n))),((r=this.state.info.agentInfo)==null?void 0:r.agentNickname)||this.broadcastEvents.send(xr,{showNicknameDialog:!0})})}setAgentSettings(e){return v(this,null,function*(){yield this.store.dispatch(ei(e))})}getAgentSettings(){return v(this,null,function*(){return(yield this.store.dispatch(ti())).payload})}refresh(){return v(this,null,function*(){if(this.shouldAbort())return Promise.resolve();let e=[];return e.push(this.refreshTextSuggestions()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})})}syncInputMediator(){this.inputMediator&&this.store.dispatch(fr({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}))}notifyExternalSuggestion(e){this.store.dispatch(ye(e))}evaluateAssistant(e,n){return v(this,null,function*(){var d;let{input:o={},transcript:r,showCuesInWidget:s=!0,includeMetadata:i}=n||{},a=yield this.store.dispatch(Xe({assistantCode:e,transcript:r,includeMetadata:i,input:o,skipState:!s}));if(a.error)throw new Error(`Assistant evaluation failed: ${(d=a.payload)!=null?d:a.error.message}`);return a.payload.output})}evaluateConversationAssistant(e,n){return v(this,null,function*(){yield this.loadProfileConfig();let o=this.state.profile.data;if(!o){k.warn("Can't evaluate assistant when profile is not loaded yet.");return}let r=Bu(o,e);yield Promise.all(r.map(s=>this.queues.push(s,()=>v(this,null,function*(){yield this.evaluateAssistant(s,y({includeMetadata:!0},n))})).catch(i=>{if(i instanceof Jo){k.warn(`Queued assistant "${s}" was outdated and dropped`);return}throw i})))})}handleKeyDown(e){let{overlayCollapsed:n,openOverlayWhenTyping:o}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,showTextSuggestions:d,suggestionsPlacement:l}=this.settings,c=l==="inline"||l==="below"?"below":"above",u=r.length>0;if(this.store.dispatch(Sl(Ys(e))),!$e(this.state)||e.key!=="Tab"&&!d)return;let p=()=>{n||!u||i&&(e.shiftKey||(this.store.dispatch(Tl()),e.preventDefault()))},g=()=>{n||!u||a&&s<=0||i&&(e.shiftKey||(this.store.dispatch(wl()),e.preventDefault()))};switch(e.key){case"ArrowUp":c==="below"?g():p();break;case"ArrowDown":{c==="below"?p():g();break}case"Escape":{n||(this.store.dispatch(gr(-1)),this.store.dispatch(Pt({collapse:!0})),this.store.dispatch(dc(!0)),e.preventDefault());break}case"Tab":{e.preventDefault();let f=Tn(this.state);if(!f)return;this.store.dispatch(Mo(!1)),this.store.dispatch(ye({text:f.text,suggestion:f,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let f=Tn(this.state);if(!f)return;this.store.dispatch(ye({text:f.text,suggestion:f,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||e.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let f=Tn(this.state);if(!f)return;this.store.dispatch(ye({text:f.text,suggestion:f,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),e.preventDefault();break}default:}n&&o&&this.store.dispatch(Pt({collapse:!1}))}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Tt([]))}handlingTimeStart(){this.state.handlingTime.startTime||(k.info("Start handling time"),this.store.dispatch(mu()))}handlingTimeStop(){this.state.handlingTime.startTime&&(k.info("Stop handling time"),this.store.dispatch(Ns()))}logSendMessage(e){let n=ku(this.state,{version:this.version});n&&(e&&(Object.assign(n,{text:e}),Object.assign(n,{lenTextTotal:e.length})),this.deepdeskApi.sendEvent("Send Message",{conversationId:this.conversationId(),data:n}),this.emit("send-message-event",n))}logHandlingTime(){let e=Eu(this.state,{version:this.version});e&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:e}),this.store.dispatch(gu()))}notifySubmit(e={}){var n;this.shouldAbort()||(this.store.dispatch($t((n=e.text)!=null?n:this.state.input.text)),this.store.dispatch(kl()))}emit(e,n){let o=this.eventListeners[e];o&&o.forEach(r=>{try{r(n)}catch(s){k.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),k.error(s)}})}on(e,n){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n),()=>{this.off(e,n)}}off(e,n){if(!e&&!n){this.eventListeners={};return}let o;this.eventListeners[e]&&(o=this.eventListeners[e].indexOf(n),o>-1&&this.eventListeners[e].splice(o,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}setPlatformVariables(e){this.store.dispatch(Dl(e))}whenConversationLoaded(e){let n=s=>{var i;return(i=s.conversation.current)==null?void 0:i.id},o=()=>this.loadProfileConfig().then(()=>e());return n(this.state)&&o(),this.subscribe(n,s=>{s&&o()})}overlayContainerFactory(e,n,o,r){let[s,i]=Xo(n,o);return s.setAttribute("translate","no"),s.dataset.testid=e,r&&s.classList.add(r),[s,i]}createInlineContainer(e,n){var a;let o=document.createElement("div");o.style.position="absolute",o.style.top="0px",o.style.left="0px",o.style.height="0px",o.style.width="0px";let r=document.createElement("div");r.style.display="none",r.style.position="absolute",r.style.height="0px",r.style.width="0px",r.style.backgroundColor="red",o.appendChild(r);let s=(a=e.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[d,l]=Xo(s,{appendTo:document.body,onMoveStart:()=>{r.style.display="none"}});d.dataset.testid=n,d.style.zIndex="2",d.appendChild(o),this.unmountHandlers.push(()=>{l()})}else document.body.appendChild(o);return r}createContainer(e,n=document.body){let o=window.getComputedStyle(n),r=document.createElement("div");return sn(r),r.dataset.testid=e,r.style.color=o.color,r.style.fontSize=o.fontSize,r.style.fontFamily=o.fontFamily,r.style.fontVariant=o.fontVariant,r.setAttribute("translate","no"),n.appendChild(r),r}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,n),k.info(`Stored analytics for ${this.conversationId()}`)}catch(e){}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(e);if(!n)return;let o=JSON.parse(n);o.text.trim()===this.state.input.text.trim()?(k.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(El(o.metrics))):k.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch(e){}}mount(e,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Fs(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let p=n,{customStyles:o,closestScrollSelector:r,floatingMenuParent:s,appendOverlayTo:i,inputMediator:a}=p,d=M(p,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),l={customStyles:o,closestScrollSelector:r,floatingMenuParent:s,appendOverlayTo:i};this.configure(d),this.settings.automaticHandlingTime&&this.setupHandlingTime(e),sn(e),this.inputMediator=a||(an(e)?new pn(e):new cn(e)),this.inputMediator.on("change",({plainText:g,rawHTML:f})=>{this.store.dispatch(fr({text:g,html:f}))}),this.inputMediator.on("keyup",g=>{this.store.dispatch(bl(Ys(g)))}),this.inputMediator.on("keydown",g=>{this.handleKeyDown(g)}),this.inputMediator.on("paste",({pastedText:g,selectionText:f})=>{this.store.dispatch(Cl({text:g,selectionText:f}))}),this.inputMediator.on("cut",({selectionText:g})=>{this.store.dispatch(xl(g))});let c;this.inputMediator.on("selection",g=>{clearTimeout(c),g===null?c=setTimeout(()=>{g!==null&&this.store.dispatch(hr(g))},500):this.store.dispatch(hr(g))}),this.unmountHandlers.push(()=>{clearTimeout(c)}),this.inputMediator.on("disabled",()=>{var g;(g=this.inputMediator)==null||g.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{this.settings.detectSubmit&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(qr(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(qr(!0))}),this.renderSuggestions(e,l),this.subscribe(vn("inlineSuggestions"),()=>{this.renderSuggestions(e,l)}),this.subscribe(vn("suggestionsPlacement"),()=>{this.renderSuggestions(e,l)});let u=this.renderOverlays(n);this.unmountHandlers.push(()=>{u.unmount()}),this.store.dispatch(fr({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(hr(this.inputMediator.getSelection())),this.store.dispatch(qr(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{this.restoreMetrics(),this.syncInputMediator(),this.refreshTextSuggestions(),this.promptForNickname()}),this.isMounted=!0}promptForNickname(e){if(this.nicknameDialogUnsubscribe||this.nicknameDialogFailed)return;let n=this.createContainer("nickname-dialog",document.body);document.body.appendChild(n);let o=(0,vt.createRoot)(n),r=null,s=a=>{r=a,i()},i=()=>{o==null||o.render((0,H.jsx)(at,{store:this.store,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(zu,{id:"deepdesk-nickname-dialog",error:r,onSave:a=>v(this,null,function*(){try{yield this.store.dispatch(Al({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(xr,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(d){k.error("Error setting agent nickname",d),s("error"),this.nicknameDialogFailed=!0}})})})}))};i(),this.nicknameDialogUnsubscribe=()=>{o.unmount(),n.remove(),this.nicknameDialogUnsubscribe=null}}subscribe(e,n){let o=e(this.store.getState());return this.store.subscribe(()=>{let r=e(this.store.getState());r!==o&&(o=r,n(o))})}unmount(){var e,n,o,r,s;(e=this.inlineSuggestions)==null||e.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(o=this.belowSuggestions)==null||o.unmount(),(r=this.floatingMenu)==null||r.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(s=this.inputMediator)==null||s.dispose(),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(e=>e()),this.disposeHandlers=[],this.off()}renderSuggestions(e,n){var o,r,s,i;(o=this.floatingMenu)==null||o.unmount(),(r=this.inlineSuggestions)==null||r.unmount(),(s=this.aboveSuggestions)==null||s.unmount(),(i=this.belowSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(e,n)),this.settings.inlineSuggestions||this.settings.suggestionsPlacement==="inline"?this.inlineSuggestions=this.renderInlineSuggestions(e,n):this.settings.suggestionsPlacement==="below"?this.belowSuggestions=this.renderAboveOrBelowSuggestions(e,n,"below"):this.aboveSuggestions=this.renderAboveOrBelowSuggestions(e,n,"above")}renderInlineSuggestions(e,n){let{customStyles:o}=n,r=this.createInlineContainer(e,"deepdesk-caret"),s=(0,vt.createRoot)(r);s.render((0,H.jsx)(at,{store:this.store,customStyles:o,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(Sc,{})})}));let i=a=>{a?(r.style.display="block",r.style.top=`${a.top}px`,r.style.left=`${a.left}px`):r.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",i),s.unmount(),r.remove()}}}renderAboveOrBelowSuggestions(e,n,o){let{customStyles:r,closestScrollSelector:s,appendOverlayTo:i}=n,a=s&&va(e,s)||void 0,[d,l]=this.overlayContainerFactory("deepdesk-tab-completion",a||e,{appendTo:i,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),[c,u]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||e,{appendTo:i,placement:o},r==null?void 0:r.suggestionsRootNode),p=(0,vt.createRoot)(d);p.render((0,H.jsx)(at,{store:this.store,customStyles:r,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(rp,{inputElement:e})})}));let g=(0,vt.createRoot)(c);return g.render((0,H.jsx)(at,{store:this.store,customStyles:r,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(Ac,{onLogIn:()=>this.loginViaPopup().catch(f=>k.warn(f.message))})})})),{unmount(){p.unmount(),g.unmount(),l(),u()}}}renderFloatingMenu(e,n){let{customStyles:o,closestScrollSelector:r,appendOverlayTo:s,floatingMenuParent:i}=n,a=r&&va(e,r)||void 0,[d,l]=this.overlayContainerFactory("floating-menu",a||e,{appendTo:i!=null?i:s},o==null?void 0:o.floatingMenuParent),c=(0,vt.createRoot)(d);return c.render((0,H.jsx)(at,{store:this.store,customStyles:o,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(sc,{onLogIn:()=>this.loginViaPopup().catch(u=>k.warn(u.message))})})})),{unmount(){c.unmount(),l()}}}renderOverlays(e){let{customStyles:n}=e,o=this.createContainer("deepdesk-overlays"),r=(0,vt.createRoot)(o);return r.render((0,H.jsx)(at,{store:this.store,customStyles:n,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(Zd,{})})})),{unmount(){r.unmount(),o.remove()}}}renderWidget(e,n={}){if(this.widgetElement&&k.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:o,showImages:r,isEmbedded:s,insertLinkAsHtml:i}=n;this.widgetElement=e,this.configure({showImages:r,isEmbedded:s,insertLinkAsHtml:i}),this.widgetRoot=(0,vt.createRoot)(e),this.widgetRoot.render((0,H.jsx)(at,{store:this.store,customStyles:o,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(tu,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(a=>k.warn(a.message))})})}))}unmountWidget(){var e,n;(n=(e=this.widgetRoot)==null?void 0:e.unmount)==null||n.call(e),this.widgetRoot=null,this.widgetElement=null}renderKnowledgeAssistantWidget(e,n,o={}){let{customStyles:r,initialQuestion:s}=o,i=(0,vt.createRoot)(n);return i.render((0,H.jsx)(at,{store:this.store,customStyles:r,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(la,{children:(0,H.jsxs)(Ps,{assistantCode:e,initialQuestion:s,evaluateKnowledgeAssistFn:Bo,children:[(0,H.jsx)(hn,{children:(0,H.jsx)(Ls,{title:o.title,emptyState:o.emptyState})}),(0,H.jsx)(aa,{children:(0,H.jsx)(Is,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(e){let n=Us(e,({isVisible:o})=>{o?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Ru(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>v(this,null,function*(){yield this.store.dispatch(So());let e=Jt(this.state);e&&this.store.dispatch(lr({showSearch:e.search,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:!!e.summarizerAssistantNew,showKnowledgeSearch:!!e.knowledgeAssistantNew||!!e.knowledgeAssistant,recommendTextSuggestions:e.recommendTextSuggestions}))})),this.loadProfileConfigPromise)}loginViaPopup(e){return v(this,null,function*(){return new Promise((n,o)=>{this.store.dispatch(dr());let r=new MessageChannel,s=r.port1,i=this.settings.adminUrl,a=new URL(e!=null&&e.url?e==null?void 0:e.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let d=!1,l=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",u),clearInterval(p)};s.onmessage=g=>v(this,null,function*(){var f,m;if((f=g.data)!=null&&f.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((m=g.data)==null?void 0:m.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(so),d=!0,r.port1.close(),n()}catch(h){console.error(h),o(h)}finally{d=!0,l()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&o(new Error("Popup blocked by browser"));let u=g=>v(this,null,function*(){var f;if(g.origin===a.origin)switch((f=g.data)==null?void 0:f.type){case"deepdesk-popup-request-origin":{try{let m=JSON.stringify({type:"deepdesk-popup-parent-origin"});c==null||c.postMessage(m,a.origin)}catch(m){k.error("Error posting message to popup",m),o(m)}break}case"deepdesk-popup-loaded":{try{let m=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(m,a.origin,[r.port2])}catch(m){k.error("Error posting message to popup",m),o(m)}break}case"deepdesk-popup-error":{if(l(),g.data.message==="Platform account url mismatch"){let m=`Please contact your administrator: The platform account url (${g.data.targetOrigin}) is misconfigured as it differs from the origin of the page that opened the popup (${g.data.openerOrigin}).`;k.warn(m),this.store.dispatch(Xs(m)),o(new Error(m))}if(g.data.message==="Timeout"){let m="Please contact your administrator: Popup timed out. Check if the account's platform url is configured correctly.";k.warn(m),this.store.dispatch(Xs(m)),o(new Error(m))}o(new Error(g.data.message));break}}});window.addEventListener("message",u);let p=setInterval(()=>{c&&!c.closed||(l(),d||o(new Error("Popup closed by user")))},200);this.disposeHandlers.push(l)})})}translateMessages(e){return this.deepdeskApi.translateMessages(e)}refreshTextSuggestions(){return v(this,null,function*(){this.isMounted&&(yield this.store.dispatch(Vr()))})}refreshWidgetSuggestions(){return v(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let n=bo(this.state);try{n.forEach(({type:o})=>{switch(o){case"entities":this.store.dispatch(Fe());break;case"pinned-messages":case"sticky-messages":break;default:ar.includes(o)||this.store.dispatch(He(o))}})}catch(o){this.handleError(o)}})}};Jn.version="19.0.2-beta.5",Jn.count=0;var Qo=Jn;function jh(t){return v(this,null,function*(){var r,s,i;let n=yield((r=t.fetch)!=null?r:window.fetch)(t.url),o=yield n.blob();return new File([o],t.name,{type:(i=(s=t.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function Vu(t,e){return v(this,null,function*(){let n=yield jh(e),o=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[n]}),t.dispatchEvent(o)}finally{Object.hasOwn(t,"files")&&delete t.files}})}function ju(t,e,n){return v(this,null,function*(){yield new yt(t).authenticateWithKey(e,n)})}function $u(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function Gu(o,r){return v(this,arguments,function*(t,e,n={}){var u,p;let{value:s}=t,{start:i,end:a}=(u=n.replace)!=null?u:{start:0,end:s.length},d=`${s.slice(0,i)}${e}${s.slice(a)}`,l=(p=n.selectionAfter)!=null?p:{start:i+e.length,end:i+e.length},c=()=>{if(n.setValue)return n.setValue(d);t.value=d};return Promise.resolve(c()).then(()=>{t.selectionStart=l.start,t.selectionEnd=l.end,t.blur(),t.focus()})})}function qu(o,r){return v(this,arguments,function*(t,e,n={}){let s=n.replace?Dt(t,n.replace.start,n.replace.end):$n(t),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?e.split(`
|
|
16
|
+
`);let f=p?o:0,m=g?Math.min(s,c.childNodes.length):c.childNodes.length;for(let h=f;h<m&&(l(c.childNodes[h]),a!==2);h++);break}default:break}g&&(a=2)}return l(t),d}var ou=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(ou||{}),ht=class{constructor(e){this.element=e;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(e,n){let o=r=>{n(r)};this.element.addEventListener(e,o),this.disposeHandlers.push(()=>{this.element.removeEventListener(e,o)})}removeEventListener(e,n){this.element.removeEventListener(e,n)}handleInteraction(){let e=this.getText(),n=this.getHTML(),o=this.getSelection(),r=this.cachedCaretPosition===null;if(!this.isActive||(e===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),e!==this.cachedText?(this.cachedText=e,this.cachedHTML=n,r=!0,this.emit("change",{plainText:e,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,r=!0,this.emit("change",{plainText:e,rawHTML:n})),(o.start!==this.cachedSelection.start||o.end!==this.cachedSelection.end)&&(this.cachedSelection=o,r=!0,this.emit("selection",o)),!r))return;let s=this.getCaretPosition();Ct(s,this.cachedCaretPosition)||(this.cachedCaretPosition=s,this.emit("caretposition",s))}handleClick(){this.handleInteraction()}handleFocus(){let e=!this.isFocused;this.isFocused=!0,e&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let e=this.isFocused;this.isFocused=!1,e&&this.emit("blur")}handleKeyDown(e){let{key:n,ctrlKey:o,metaKey:r}=e;this.isPossibleClearInputAction=Object.values(ou).includes(n)||n.toLowerCase()==="z"&&(o||r),this.emit("keydown",e)}handleKeyUp(e){this.handleInteraction(),this.emit("keyup",e)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){var o,r;let n=((o=e.clipboardData)==null?void 0:o.getData("text"))||((r=e.clipboardData)==null?void 0:r.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 e=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});e.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{e.disconnect()})}focus(){this.element.focus()}emit(e,...n){this.isDisposed||this.eventListeners[e]&&this.eventListeners[e].forEach(o=>{o(...n)})}on(e,n){this.isDisposed||(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n))}off(e,n){if(!this.eventListeners[e])return;let o=this.eventListeners[e].indexOf(n);o!==-1&&this.eventListeners[e].splice(o,1)}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};function ru(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var cn=class extends ht{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),qo(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){let n=this.getRootNode();if(n.activeElement!==this.element)return null;let o="getSelection"in n?n.getSelection():window.getSelection();if(!o)return null;let r=o.rangeCount>0?o.getRangeAt(0):null;if(!r)return null;let s=this.element.ownerDocument.createRange();return s.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),s.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let o=n.getBoundingClientRect();return!ru(o)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=n.getBoundingClientRect(),n.deleteContents(),!ru(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let n=this.getRange();if(n)return Go(this.element,n);let o=this.lastKnownSelection;if(o&&nu(this.element,o.start,o.end))return o;let r=$n(this.element);return r.collapse(!1),Go(this.element,r)}getSelectedText(){let{start:n,end:o}=this.getSelection();return qo(this.element,Dt(this.element,n,o))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let o=this.element.isContentEditable,r=new MutationObserver(()=>{this.element.isContentEditable!==o&&(o=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>r.disconnect())}};var kh=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function su(t,e){let n="mozInnerScreenX"in window,o=document.createElement("div");o.id="input-textarea-caret-position-mirror-div";let r=o.style,s=window.getComputedStyle(t),i=t.ownerDocument.body;r.whiteSpace="pre-wrap",r.wordWrap="break-word",r.position="absolute",r.visibility="hidden",kh.forEach(c=>{r[c]=s[c]}),n?t.scrollHeight>Number.parseInt(s.height)&&(r.overflowY="scroll"):r.overflow="hidden",o.textContent=t.value.substring(0,e);let a=document.createElement("span");a.textContent=t.value.substring(e)||".",o.appendChild(a),i.appendChild(o);let d=t.getBoundingClientRect(),l={top:d.top-t.scrollTop+a.offsetTop+Number.parseInt(s.borderTopWidth)+a.offsetHeight,left:d.left-t.scrollLeft+a.offsetLeft+Number.parseInt(s.borderLeftWidth)};return i.removeChild(o),l}var pn=class extends ht{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:o}=this.element;return{start:n,end:o}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return su(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let o=this.element.disabled,r=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>r.disconnect())}};function iu(t,e,n){let o=`deepdesk-iframe-${t}`,r=document.getElementById(o);if(r)return r;let s=document.createElement("iframe"),i=new URL(e);return Object.entries(n).forEach(([a,d])=>{i.searchParams.append(a,d)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=o,s.title=`iframe-${t}`,s.src=i.toString(),window.document.body.appendChild(s),s}function Rh(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch(e){return t}}var da=class{constructor(e){this.name=e;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(e)}onMessage(e){this.broadcastChannel.addEventListener("message",e),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",e)})}postMessage(e){this.broadcastChannel.postMessage(JSON.stringify(e))}close(){this.disposeHandlers.forEach(e=>e()),this.broadcastChannel.close()}},ca=class{constructor(e,n,o){this.name=e;this.targetOrigin=n;this.options=o;this.disposeHandlers=[];this.iframe=iu(e,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(e),this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(n=>n()),(e=this.iframe)==null||e.remove()}},pa=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.externalId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setExternalId(e){this.externalId!==e&&(this.cleanup(),k.info("Set externalId",e),this.externalId=e,this.channel=this.createChannel(e))}createChannel(e){let n=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new ca(e,this.deepdeskUrl,{debug:!0}):new da(e),o=r=>{var i,a;if(r.origin!==this.deepdeskUrl)return;let s=Rh(r.data);typeof s!="object"||s.type!=="event"||s.channel!==e||(k.info("Received broadcast event",this.externalId,r),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(o),n}send(e,n,o){var i,a;k.info("Broadcast event",{externalId:this.externalId,name:e,payload:n});let r={type:"event",name:e,payload:n};o!==!1&&((a=(i=this.eventMap)[e])==null||a.call(i,n));let s=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(S(y({},r),{channel:this.externalId}))}cleanup(e=!1){var n,o;(n=this.channel)==null||n.close(),this.channel=void 0,e&&((o=this.defaultChannel)==null||o.close(),this.defaultChannel=void 0)}},au=pa;function Ph(t){return t.replace(/(_\w)/g,e=>e[1].toUpperCase())}function z(t){return Array.isArray(t)?t.map(z):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>S(y({},e),{[Ph(n)]:z(t[n])}),{}):t}function Ih(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function pe(t){return Array.isArray(t)?t.map(pe):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>S(y({},e),{[Ih(n)]:pe(t[n])}),{}):t}var Gn=class extends Error{constructor(n,o){super(n);this.body=o;this.name="CustomError"}};var ua=t=>new Promise(e=>{setTimeout(e,t)});var qn=class extends Gn{constructor(){super(...arguments);this.name="ClientError"}},ga=class extends Gn{constructor(){super(...arguments);this.name="ServerError"}},ma=new Map;function Lh(t){return v(this,null,function*(){if(t.status===204)return t.text().catch(()=>{}),null;let e=t.headers.get("content-type");if(e!=null&&e.includes("application/json"))return t.json();let n=yield t.text();return n===""?null:(k.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var _t=class _t{constructor(e="",n={}){this.baseUrl=e;this.options=n;this.latestRequestByUrl={};var o;this.fetch=(o=n.fetch)!=null?o:window.fetch.bind(window)}patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,n={}){return new Promise((o,r)=>{let s={isAborted:!1,reject:r},i=`${this.baseUrl}${e}`,a=this.fetch,d=n.method===void 0||n.method.toLowerCase()==="get",N=n,{useCache:l=!1,abortLatest:c=!1,attempts:u=1,retryDelay:p=500,refreshTokenOn401:g=!0,retryOnError:f=B=>B instanceof TypeError,retryOnResponse:m=B=>B.status>=500,version:h=null}=N,C=M(N,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(l){if(!d)throw new Error(`Can't use 'useCache' for ${n.method}`);if(ma.has(i)){o(ma.get(i));return}}let T=S(y({credentials:"include"},C),{headers:y({Accept:"application/json","Content-Type":"application/json"},C.headers)});!d&&this.csrfToken&&(T.headers=S(y({},T.headers),{"X-CSRFToken":this.csrfToken})),typeof h=="string"&&(T.headers=S(y({},T.headers),{"X-Deepdesk-API-Version":h}));let b=u,w=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let I=()=>v(this,null,function*(){return b--,a(i,T).then(B=>v(this,null,function*(){return m(B)&&!s.isAborted&&b>0?(yield ua(p),I()):B.status===401&&g===!0&&w===!1?(w=!0,yield this.refreshToken(),I()):B})).catch(B=>v(this,null,function*(){if(f(B)&&!s.isAborted&&b>0)return yield ua(p),I();throw B}))});I().then(B=>v(this,null,function*(){let X=yield Lh(B);if(delete this.latestRequestByUrl[i],B.status>=500){r(new ga("Server Error",X));return}if(B.status===401){r(new qn("Unauthorized",X));return}if(B.status===403){r(new qn("Forbidden",X));return}if(B.status===404){r(new qn("Not Found",X));return}if(B.status>=400){r(new qn("Bad Request",X));return}l&&ma.set(i,X),o(X)})).catch(B=>{r(B)})})}validateToken(){return v(this,null,function*(){let{has_valid_access_token:e,is_logged_in:n}=yield this.get("/apis/admin/session/validate/");if(!e)try{yield this.refreshToken();let{is_logged_in:o}=yield this.get("/apis/admin/session/validate/");return o}catch(o){return!1}return n})}refreshToken(){return _t.refreshingToken||(_t.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{_t.refreshingToken=null},1e3*60)})),_t.refreshingToken}get(e,n){return this.request(e,n)}post(e,n,o){return this.request(e,y({method:"POST",body:JSON.stringify(n)},o))}patch(e,n,o){return this.request(e,y({method:"PATCH",body:JSON.stringify(n)},o))}put(e,n,o){return this.request(e,y({method:"PUT",body:JSON.stringify(n)},o))}delete(e,n){return this.request(e,y({method:"DELETE"},n))}};_t.refreshingToken=null;var un=_t;var lu;(e=>{let t;(a=>(a.SUCCESS="success",a.FAILURE="failure",a.CONDITIONS_NOT_MET="conditions_not_met",a.MAX_RECURSION_LEVEL="max_recursion_level",a.NO_ACCESS_TO_ASSISTANT="no_access_to_assistant"))(t=e.EvaluationStatus||(e.EvaluationStatus={}))})(lu||(lu={}));function fa(t){return S(y({},z(t)),{metadata:t.metadata})}var mn=class mn{constructor(e,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new un(e,{fetch:n.fetch}),this.client.patchFetch(o=>(r,s)=>v(this,null,function*(){let i=yield o(r,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return v(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=yield this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(mn.exchangeTokenPromise||(mn.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),mn.exchangeTokenPromise):Promise.resolve()})}createConversation(e){return v(this,null,function*(){var o;yield this.preflight(),k.info(`Creating conversation for session ${e.externalId} and agent ${e.agentId}`);let n=yield this.client.post("/api/v2/conversations",S(y({chat_start_time:new Date().toISOString()},pe(e)),{metadata:(o=e.metadata)!=null?o:{}}));return fa(n)})}getMe(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/session/me/");return z(e)})}postIdentity(e){return v(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",pe(e))})}patchMe(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",pe(e));return z(n)})}getProfile(e){return v(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${e}/`,{useCache:!0});return z(n)})}getKnowledgeAssistant(e){return v(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{useCache:!0});return z(n)})}getContentTypes(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return z(e)})}getAccount(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/account/",{useCache:!0});return z(e)})}getPlatformConfig(e){return v(this,null,function*(){let n=e!==void 0?`/platform/config/${e}/`:"/platform/config/",{config:o}=yield this.client.get(n,{useCache:!0});return z(o)})}checkUserExists(e){return v(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${e}`,{version:"v1"});return n})}getConversationByExternalId(o){return v(this,arguments,function*(e,n={}){yield this.preflight(),k.info(`Getting conversation for session ${e}`);let{attempts:r=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/v2/conversations/by_external_id/${e}`,{attempts:r,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return k.info(`Successfully retrieved conversation ${i.id} for session ${e}`),fa(i)})}isConversationSupported(o){return v(this,arguments,function*(e,n={}){k.info(`Check if conversation for session ${e} is supported`);let{attempts:r=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${e}/has_active_profile`,{attempts:r,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(e,n){return v(this,null,function*(){var s;yield this.preflight();let o=pe(n);n.metadata&&(o.metadata=(s=n.metadata)!=null?s:{});let r=yield this.client.put(`/api/v2/conversations/${e}`,o);return fa(r)})}postMessages(e,n){return v(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${e}/messages`,n.map(o=>S(y({},pe(o)),{metadata:o.metadata})))})}sendEvent(e,n){return v(this,null,function*(){yield this.preflight();let a=n,{data:o}=a,r=M(a,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((d,[l,c])=>S(y({},d),{[l]:c}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((d,l)=>(r[l]&&(d[l]=r[l]),d),{});return this.client.post("/api/v2/events",pe(S(y(y({},s),i),{data:o,name:e})),{version:"v2"})})}getEntities(e){return v(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:e.filter(o=>o.text)})})}getTemporaryExchangeToken(){return v(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(e){return v(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:e}).catch(n=>{throw k.warn(`Invalid token '${e}'`),n})})}authenticateWithKey(e,n){return v(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",pe(n),{refreshTokenOn401:!1,headers:{apikey:e}})})}getTextSuggestions(r){return v(this,arguments,function*(e,n={},o){if(yield this.preflight(),o==="sticky-messages")throw new Error("Use getPinnedMessages instead");return(yield this.client.post(`/api/v2/conversations/${e}/recommend/${o}`,pe(n),{abortLatest:!0})).map(i=>S(y({},z(i)),{text:i.text||i.url||i.message,source:o,type:o})).filter((i,a,d)=>a===d.findIndex(l=>l.text===i.text))})}isLoggedIn(){return v(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(e,n){return v(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${e}/autocomplete`,pe(n),{abortLatest:!0})).map(r=>({score:1,source:r.source,sourceText:r.source_text,text:r.label,trainingJobs:r.training_jobs,searchKeywords:r.search_keywords,type:r.source})).filter((r,s,i)=>s===i.findIndex(a=>a.text===r.text))})}getPinnedMessages(e){return v(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${e}/pinned-messages`,{abortLatest:!0});return z(n).map(o=>S(y({},o),{text:o.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(e){return v(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",pe(e),{abortLatest:!0,version:"v2"});return z(n)})}search(e){return v(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${e.profile}/search`,pe(e));return z(n)})}requestLoginByEmail(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:e});return z(n)})}requestPasswordlessToken(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/session/passwordless/request/");return z(e.token)})}getCsrfToken(){return v(this,null,function*(){let{token:e}=yield this.client.get("/apis/admin/session/csrf/");return e})}verifyLoginToken(e){return v(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:e});return z(n)})}evaluateAssistant(e,n){return v(this,null,function*(){var i;yield this.preflight();let o=new URLSearchParams;n!=null&&n.externalConversationId&&o.append("external_conversation_id",n.externalConversationId);let r=n!=null&&n.threadId?`/api/v2/assistants/${e}/threads/${n==null?void 0:n.threadId}/evaluate?${o.toString()}`:`/api/v2/assistants/${e}/evaluate?${o.toString()}`,s=yield this.client.post(r,{input:(i=n==null?void 0:n.input)!=null?i:{},conversation:n==null?void 0:n.transcript});return z(s)})}createAssistantThread(e){return v(this,null,function*(){yield this.preflight();let{assistantCode:n}=e,o=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return z(o)})}postMessageToAssistantThread(e){return v(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:o,message:r}=e,s=yield this.client.post(`/apis/admin/assistants/${n}/threads/${o}/messages/`,{content:r,role:"user"});return z(s)})}translateMessages(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",pe(e));return z(n)})}handleDeepdeskVersionHeaders(e){e.headers.forEach((n,o)=>{let r=o.toLowerCase(),s=r.match(Ja);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&k.warn(`Overwritten Version header ${r}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};mn.exchangeTokenPromise=null;var yt=mn;var _s=require("@reduxjs/toolkit");var cu=require("@reduxjs/toolkit");var du={startTime:null,stopTime:null},pu=t=>t.handlingTime,uu=(0,cu.createSlice)({name:"handlingTime",initialState:du,reducers:{handlingTimeStart(t){if(t.startTime&&!t.stopTime)throw new Error("Timing already started");t.startTime=new Date,t.stopTime=null},handlingTimeStop(t){if(!t.startTime)throw new Error("Timing not started");t.stopTime=new Date},handlingTimeReset(t){t.startTime=null,t.stopTime=null}},extraReducers:t=>{t.addCase(J,()=>du)}}),{handlingTimeStart:mu,handlingTimeStop:Ns,handlingTimeReset:gu}=uu.actions,fu=uu.reducer;var hu=(t={})=>{let e=y({onAuthError:Sn(!1)},t);return n=>o=>r=>("error"in r&&r.error.message==="Unauthorized"&&n.dispatch(e.onAuthError),o(r))};var Ds=require("@reduxjs/toolkit");var Os={list:{keywordMatches:[]},fetchState:"idle"};var gn=(0,Ds.createAsyncThunk)("styleSuggestions/getAll",(n,o)=>v(null,[n,o],function*({text:t},e){var d;let{deepdeskAPI:r}=e.extra,s=e.getState(),{showStyleSuggestions:i}=s.settings,a=(d=s.conversation.current)==null?void 0:d.profileCode;if(!i)return Os.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return r.getStyleSuggestions({profileCode:a,message:t})})),Ah=(0,Ds.createSlice)({name:"styleSuggestions",initialState:Os,reducers:{},extraReducers:t=>{t.addCase(gn.pending,e=>{e.fetchState="loading"}).addCase(gn.rejected,e=>{e.fetchState="error"}).addCase(gn.fulfilled,(e,n)=>{e.fetchState="done",Ct(e.list,n.payload)||(e.list=n.payload)}).addCase($t,e=>{e.list=Os.list}).addCase(J,()=>Os)}}),yu=Ah.reducer;var vu=(t={})=>{let e,n=!0,o=y({getStyleSuggestions:gn,debounce:500},t);return r=>s=>i=>{var g;let a=r.getState().input.text,d=s(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return d;let{showStyleSuggestions:c}=l.settings;if(!((g=l.conversation.current)==null?void 0:g.id)||!c)return d;let{text:p}=l.input;return p===a&&!n||(clearTimeout(e),p==="")||(e=setTimeout(()=>{n=!1,r.dispatch(o.getStyleSuggestions({text:p}))},t.debounce)),d}};function Mh(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var xu=(t={})=>{let e=y({getTextSuggestions:He,getAutocompleteSuggestions:Lo,debounce:200,check:$e},t),n;return o=>r=>s=>{var m;let{input:i}=o.getState(),a=r(s),d=o.getState();if(d.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:l,showTabCompletion:c}=d.settings,u=(m=d.conversation.current)==null?void 0:m.id,p=s.type===Vr.toString();if(!u||!l&&!c)return a;let{input:g}=d;return Mh(g,i)&&!p||(clearTimeout(n),!e.check(d))||(n=setTimeout(()=>{let h=Cn(d);h===""?o.dispatch(e.getTextSuggestions("default")):o.dispatch(e.getAutocompleteSuggestions(h))},p?0:e.debounce)),a}};var Su=gn.fulfilled.toString();function Nh(t,e){let n=new Set([...e.keywordMatches.map(r=>r.keyword)]),o=[];return n.forEach(r=>{let s=t.keywordMatches.filter(d=>d.keyword===r),i=e.keywordMatches.filter(d=>d.keyword===r),a=i.length-s.length;a<=0||o.push(...i.slice(0,a))}),o}var bu=t=>e=>n=>o=>{var l;if(o.type!==Su){n(o);return}let r=e.getState().styleSuggestions.list;n(o);let s=e.getState(),i=s.styleSuggestions.list,a=(l=s.conversation)==null?void 0:l.current;if(r===i)return;let d=Nh(r,i);o.type===Su&&d.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:d}})};var Oh=(0,_s.combineReducers)({assistants:mp,auth:ll,conversation:gl,contentTypes:dd,passwordlessToken:hp,entities:Od,handlingTime:fu,info:Fl,input:Rl,settings:tl,profile:gd,search:Wl,styleSuggestions:yu,ui:pc,textSuggestions:$d});function Cu(t){return(0,_s.configureStore)({reducer:Oh,middleware:e=>{var o;let n=e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI}},serializableCheck:!1}).concat(hu()).concat(xu({debounce:200})).concat(vu({debounce:500})).concat(bu(t.deepdeskAPI));return((o=t.middleware)!=null?o:[]).reduce((r,s)=>r.concat(s),n)},preloadedState:t.preloadedState})}var Dh=t=>{var e,n;return(n=(e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())!=null?n:"unknown"},_h=t=>e=>n=>o=>{var a,d;let r=e.getState(),s=vn("inlineSuggestions")(r);switch(o.type){case Sn.toString():{!o.payload&&t.emit("logout",void 0);break}case Fe.fulfilled.toString():o.payload.length>0&&t.sendEvent("entities found",{conversationId:(a=r.conversation.current)==null?void 0:a.id,data:{entities:o.payload}});break;case $t.toString():t.logSendMessage(o.payload);break;case hs.toString():t.emit("call-to-action",{cue:o.payload});break;case Xe.fulfilled.toString():o.isBroadcasted||t.broadcast(oi,o,!1);break;default:break}let i=n(o);switch(o.type){case $t.toString():t.handleAfterSendMessage(o.payload);break;case Mo.toString():t.onUpdateShowTabHint(o.payload);break;case Ns.toString():t.logHandlingTime();break;case wn.toString():t.broadcast(Sr,o);break;case jt.toString():t.broadcast(Sr,o);break;case ys.toString():e.dispatch(jt({source:"assistant",assistantCode:o.payload.code}));break;case"analytics/logEvent/fulfilled":{let l=r.assistants.cues.find(c=>c.code===o.meta.arg.data.assistantCode);t.emit("event",S(y({},o.meta.arg),{cue:l}));break}case ye.toString():{let{start:l,end:c}=r.input.selection;t.emit("select-suggestion",S(y({type:Dh(o.payload.suggestion)},o.payload),{replace:o.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}})),s&&e.dispatch(Tt([]));break}case mr.toString():t.emit("select-image",o.payload),t.sendEvent("Image attached",{conversationId:(d=r.conversation.current)==null?void 0:d.id,data:{path:o.payload.suggestion.image,title:o.payload.suggestion.title}});break;case Tt.toString():{s&&o.payload.length>0&&e.dispatch(gr(0));break}default:break}return i},Tu=_h;var wu=require("@reduxjs/toolkit");function ha(t){return t.toISOString().replace("T"," ").replace("Z","")}var Fh=(t,e)=>e.version,Eu=(0,wu.createSelector)([En,ze,pu,Fh],(t,e,n,o)=>{if(!e)return k.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:s}=n;return!r||!s?(k.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:e,clientVersion:o,agentId:t==null?void 0:t.agentId,agentName:t==null?void 0:t.agentName,agentEmail:t==null?void 0:t.agentEmail,timeStart:ha(r),timeStop:ha(s)}});function ku(t,e){let{text:n,metrics:{numPaste:o,pastes:r,textSuggestions:s}}=t.input,i=n.length;return{source:"agent",clientVersion:e.version,pastes:r,lenTextTotal:i,numPastes:o,suggestions:s}}function ya(t,e){var s;let n=t.closest(e);if(n)return n;let o=t.getRootNode().host;if(o instanceof HTMLElement)return ya(o,e);let r=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;return r?ya(r,e):null}function va(t,e){return ya(t,e)}function Ru(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function Hh(t){return typeof t=="object"&&t!==null&&"tagName"in t}function Fs(t){return Hh(t)&&(an(t)||Yr(t))}var Iu,Qe=new Map,Bh=["bottom","height","left","right","top","width"],Pu=(t,e)=>!t&&!e?!1:t&&!e||!t&&e?!0:Bh.some(n=>t[n]!==e[n]);function Lu(t){var n,o,r;if(t.ownerDocument===document)return[];let e=(r=(o=(n=t.ownerDocument)==null?void 0:n.defaultView)==null?void 0:o.frameElement)!=null?r:null;return e?[e,...Lu(e)]:[]}function Au(t,e){return!t||!e?null:S(y({},t),{top:t.top+e.top,left:t.left+e.left})}var Hs=!1,Mu=()=>{Hs=!0;let t=[];if(Qe.forEach((e,n)=>{if(!n.isConnected){e.rect=null,t.push(e),Qe.delete(n);return}let o=n.getBoundingClientRect();Pu(o,e.rect)&&(e.rect=o,t.push(e))}),t.forEach(e=>{let n=e.parentRects?e.parentRects.reduce(Au,e.rect):e.rect;Pu(n,e.totalRect)&&e.callbacks.forEach(o=>o(n)),e.totalRect=n}),Qe.size===0){Hs=!1;return}Iu=window.requestAnimationFrame(Mu)};function xa(t,e){let n=Lu(t),o=[],r=n.map((s,i)=>xa(s,a=>{o[i]=a;let d=Qe.get(t);if(!d)return;let l=o.reduce(Au,d.rect);d.callbacks.forEach(c=>c(l))}));return{observe(s=!0){if(r.forEach(i=>i.observe(!1)),Qe.has(t)){let i=Qe.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else Qe.set(t,{rect:void 0,callbacks:[e],parentRects:o});s&&!Hs&&Mu()},unobserve(){r.forEach(i=>i.unobserve());let s=Qe.get(t);if(s){let i=s.callbacks.indexOf(e);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||Qe.delete(t),Qe.size||(cancelAnimationFrame(Iu),Hs=!1)}}}}var Nu,Ze=new Map,Ou=()=>{Ze.forEach((t,e)=>{if(!e.isConnected){Ze.delete(e);return}let{clientHeight:n,scrollHeight:o}=e,r=o>n;t.visible!==r&&(t.visible=r,t.callbacks.forEach(s=>s(t.visible)))}),Ze.size!==0&&(Nu=window.requestAnimationFrame(Ou))};function Du(t,e){return{observe(){let n=Ze.size===0;Ze.has(t)?Ze.get(t).callbacks.push(e):Ze.set(t,{visible:void 0,callbacks:[e]}),n&&Ou()},unobserve(){let n=Ze.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||Ze.delete(t),Ze.size||cancelAnimationFrame(Nu)}}}}var Sa=["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 ba(t,e,n){return n.forEach(o=>{e.style[o]=t[o]})}function Xn(t){return Number.parseFloat(t)}function Bs(t){return Math.round(t*1e6)}function _u(t){return t/1e6}function Ca(t,e,n){if(t.boxSizing==="content-box")return;let{clientWidth:o}=e,r=Xn(t.width),s=Xn(t.borderLeftWidth),i=Xn(t.borderRightWidth),a=Xn(t.paddingRight),d=_u(Bs(r)-Bs(s)-Bs(i)),l=_u(Bs(o));if(d-l>2){let c=d-l;n.style.paddingRight=`${a+c}px`}}function Xo(t,e={}){var c,u;let n=e.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=e.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",sn(n);let o=window.getComputedStyle(t),r=!0,s=()=>{n.scrollTop=t.scrollTop};ba(o,n,Sa),Ca(o,t,n),e.mirrorOverflow&&(n.style.overflow="hidden",t.addEventListener("scroll",s));let i=Du(t,()=>{ba(o,n,Sa),Ca(o,t,n),s(),setTimeout(s,0)}),a,d=!0,l=xa(t,p=>{if(p===null){e.onRemove&&e.onRemove(),n.remove();return}if(!d&&e.onMoveStart&&(Promise.resolve().then(()=>e.onMoveStart()),d=!0),clearTimeout(a),a=setTimeout(()=>{e.onMoveEnd&&e.onMoveEnd(),d=!1},200),p.height===0&&p.width===0){if(r===!0)return;e.onHide&&e.onHide(),n.style.display="none",r=!0;return}if(ba(o,n,Sa),Ca(o,t,n),s(),e.placement==="below"&&n.classList.add("below"),n.style.top=`${p.top}px`,n.style.left=`${p.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let g=e.closestScrollElement.getBoundingClientRect(),f=window.getComputedStyle(e.closestScrollElement),m=Xn(f.borderTopWidth),h=Xn(f.borderBottomWidth),C=g.top+m-p.top,T=p.top+p.height+-(g.top+g.height-h);n.style.clipPath=`inset(${C}px 0px ${T}px 0px)`}r&&(n.style.display="block",e.onShow&&e.onShow(),r=!1)});return e.appendTo?e.appendTo.appendChild(n):(u=t.parentElement)==null||u.appendChild(n),l.observe(),i.observe(),[n,()=>{t.removeEventListener("scroll",s),l.unobserve(),i.unobserve(),n.remove()}]}var Fu=(t,e)=>({value(){try{let n=sessionStorage.getItem(`dd-${t}`);if(!n)return e;try{return JSON.parse(n)}catch(o){return e}}catch(n){return e}},update(n){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(n))}catch(o){k.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function Uh(t){return t.offsetParent!==null}function Hu(t){if(!Uh(t))return!1;let e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}function Us(t,e,n=100){let o=Hu(t);e({isVisible:o});let r=setInterval(()=>{let s=Hu(t);s!==o&&(o=s,e({isVisible:o}))},n);return()=>{clearTimeout(r)}}var Jo=class extends Error{};function Kh(){let t,e;return{promise:new Promise((o,r)=>{t=o,e=r}),resolve:t,reject:e}}var Ks=class{constructor(){this.queues={}}push(e,n){let o=()=>{let s=this.queues[e][1];s?(this.queues[e]=[s.promise,null],s.resolve()):delete this.queues[e]};if(!this.queues[e]){let s=n().finally(o);return this.queues[e]=[s,null],s}this.queues[e][1]&&this.queues[e][1].reject(new Jo("Queued async function is outdated"));let r=Kh();return this.queues[e][1]=r,r.promise.then(()=>n().finally(o))}};var zh={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},Bu=(t,e)=>{var r,s,i;if(!((i=(s=(r=t.uiConfig)==null?void 0:r.widget)==null?void 0:s.types.find(a=>a.type==="cues"))==null?void 0:i.isActive))return k.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let o=t[zh[e]];return o&&o.length>0?o.map(a=>a.code):(k.warn(`No assistant set in profile for conversation event "${e}"`),[])};var zs=class{constructor(e){this.options=e;this.socket=null;this.maxReconnectAttempts=5;this.reconnectInterval=25e3;this.cleanupCallbacks=[];var n,o;this.socket,this.eventListeners=new Map,this.url=e.url,this.maxReconnectAttempts=(n=e.maxReconnectAttempts)!=null?n:this.maxReconnectAttempts,this.reconnectInterval=(o=e.reconnectInterval)!=null?o:this.reconnectInterval,this.shouldReconnect=e.shouldReconnect}connect(){let e=()=>this.cleanup();window.addEventListener("beforeunload",e),this.cleanupCallbacks.push(()=>window.removeEventListener("beforeunload",e)),this.reconnect()}setupListeners(){this.socket&&(this.socket.onmessage=e=>{var n;try{let o=z(JSON.parse(e.data));o.event&&this.eventListeners.has(o.event)&&((n=this.eventListeners.get(o.event))==null||n.forEach(r=>r(o.data)))}catch(o){console.error("Error parsing WebSocket message:",o)}},this.socket.onclose=e=>{console.log("WebSocket connection closed:",e),setTimeout(()=>{this.reconnect()},this.reconnectInterval)},this.socket.onerror=e=>{console.error("WebSocket error:",e)})}reconnect(){var e,n;if(this.maxReconnectAttempts<=0){console.error("Max reconnect attempts reached, closing WebSocket connection."),(e=this.socket)==null||e.close();return}if(!this.shouldReconnect()){console.error("Should not reconnect, closing WebSocket connection."),(n=this.socket)==null||n.close();return}this.socket&&(this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close()),this.socket=new WebSocket(this.url),this.setupListeners(),this.maxReconnectAttempts--}send(e,n){if(!this.socket){console.error("WebSocket connection is not open.");return}this.socket.send(JSON.stringify({event:e,data:n}))}on(e,n){this.eventListeners.has(e)||this.eventListeners.set(e,[]);let o=this.eventListeners.get(e);o&&!o.includes(n)&&o.push(n)}close(){var e;(e=this.socket)==null||e.close()}cleanup(){this.close(),this.cleanupCallbacks.forEach(e=>e()),this.cleanupCallbacks=[]}};var Ft=O(require("react"));var Uu={root:"dd-7zvcP",dialogContent:"dd-4C0lK",continueButton:"dd-YUPQW",buttonContinueWrapper:"dd-IKpYs",nicknameInput:"dd-rxhGp",titleWrapper:"dd-nw3nD",title:"dd-5iof5",closeButtonWrapper:"dd-UUAzA",closeButton:"dd-7rjP5",buttonsWrapper:"dd-5e9Xb",errorMessage:"dd--5VgX",errorLink:"dd-u461n"};var Ku=require("react-redux");var Ta={};Y(Ta,{enUS:()=>Wh,nlNL:()=>Vh});var Wh={title:[{type:0,value:"Enter your nickname"}],close:[{type:0,value:"Close"}],nicknameDialogTitle:[{type:0,value:"Please enter the name you'd like customers to see during chat conversations. This nickname will be used across your Deepdesk environment."}],nicknameDialogInputPlaceholder:[{type:0,value:"Enter your nickname"}],nicknameDialogContinueButton:[{type:0,value:"Continue"}],nicknameDialogError:[{type:0,value:"Nickname cannot be empty or spaces only"}],nicknameDialogEmojiError:[{type:0,value:"You cannot use emojis in this field."}],nicknameDialogSaveError:[{type:0,value:"We couldn't save your details just now. Please try again, or update it at "},{type:1,value:"account"},{type:0,value:".deepdesk.com/admin/user-settings"}],nicknameDialogSaveErrorWithoutLink:[{type:0,value:"We couldn\u2019t save your details just now. Please try again later, or update them in My Deepdesk \u2192 Settings."}]},Vh={title:[{type:0,value:"Voer je bijnaam in"}],close:[{type:0,value:"Sluiten"}],nicknameDialogTitle:[{type:0,value:"Voer de naam in die je wilt dat klanten zien tijdens chatgesprekken. Deze bijnaam wordt gebruikt in je Deepdesk-omgeving."}],nicknameDialogInputPlaceholder:[{type:0,value:"Voer je bijnaam in"}],nicknameDialogContinueButton:[{type:0,value:"Doorgaan"}],nicknameDialogError:[{type:0,value:"Bijnaam mag niet leeg of alleen spaties zijn"}],nicknameDialogEmojiError:[{type:0,value:"Je kunt geen emoji's gebruiken in dit veld."}],nicknameDialogSaveError:[{type:0,value:"We konden je gegevens nu niet opslaan. Probeer het opnieuw of werk het bij op "},{type:1,value:"account"},{type:0,value:".deepdesk.com/admin/user-settings"}],nicknameDialogSaveErrorWithoutLink:[{type:0,value:"We konden je gegevens nu niet opslaan. Probeer het opnieuw later, of werk ze bij in My Deepdesk \u2192 Instellingen."}]};var Q=require("react/jsx-runtime"),zu=({onClose:t,onSave:e,id:n,error:o})=>{let[r,s]=(0,Ft.useState)(""),[i,a]=(0,Ft.useState)(!1),[d,l]=(0,Ft.useState)(!1),c=x("Nickname",Uu),u=Ft.default.useRef(null),p=(0,Ku.useSelector)(C=>C.info.showNicknameDialog),g=R(Ta),f=E("adminUrl");(0,Ft.useEffect)(()=>{o&&a(!0)},[o]);let m=()=>{if(!u.current)return;r.trim()?u.current.setCustomValidity(""):u.current.setCustomValidity(g("nicknameDialogError")),u.current.reportValidity()},h=C=>{C.preventDefault();let T=r.trim(),b=C.currentTarget.querySelector("#nickname-input");if(!T){b.setCustomValidity(g("nicknameDialogError")),b.reportValidity();return}b.setCustomValidity(""),e(T)};return(0,Q.jsxs)(In,{isOpen:p,"datatest-id":n,onClose:t||(()=>{}),onBack:t||(()=>{}),children:[(0,Q.jsx)("div",{className:c.titleWrapper,children:(0,Q.jsx)("h1",{className:c.title,children:g("title")})}),(0,Q.jsxs)("form",{className:c.dialogContent,onSubmit:h,children:[(0,Q.jsx)("p",{children:g("nicknameDialogTitle")}),i&&o&&(0,Q.jsx)("div",{className:c.errorMessage,children:f?(()=>{let C=g("nicknameDialogSaveError",{account:f}),T=`${f}.deepdesk.com/admin/user-settings`,b=C.indexOf(T);if(b!==-1){let w=C.substring(0,b),I=C.substring(b+T.length);return(0,Q.jsxs)(Q.Fragment,{children:[w,(0,Q.jsx)("a",{href:T,target:"_blank",rel:"noopener noreferrer",className:c.errorLink,children:T}),I]})}return C})():g("nicknameDialogSaveErrorWithoutLink")}),(0,Q.jsx)("input",{required:!0,minLength:1,maxLength:20,"data-testid":"nickname-input",id:"nickname-input",className:c.nicknameInput,type:"text",placeholder:g("nicknameDialogInputPlaceholder"),value:r,onChange:C=>{l(new RegExp("\\p{Extended_Pictographic}","u").test(C.target.value)),s(C.target.value)},onBlur:m,ref:u}),d&&(0,Q.jsx)("div",{className:c.errorMessage,role:"alert",children:g("nicknameDialogEmojiError")}),(0,Q.jsxs)("div",{className:c.buttonsWrapper,children:[o?(0,Q.jsx)("div",{className:c.closeButtonWrapper,children:(0,Q.jsx)("button",{type:"button",className:c.closeButton,onClick:()=>t==null?void 0:t(),children:g("close")})}):null,(0,Q.jsx)("div",{className:c.buttonContinueWrapper,children:(0,Q.jsx)("button",{type:"submit",className:c.continueButton,disabled:!r.trim()||new RegExp("\\p{Extended_Pictographic}","u").test(r),children:g("nicknameDialogContinueButton")})})]})]})]})};var H=require("react/jsx-runtime");var Wu=Fu("showTabHint",!0),Jn=class Jn{constructor({deepdeskUrl:e,version:n=Jn.version||"unknown",locale:o="en-US",token:r,fetch:s,productName:i,createCustomChannel:a,websocketClient:d=zs}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.disposeHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.belowSuggestions=null;this.floatingMenu=null;this.widgetElement=null;this.widgetRoot=null;this.nicknameDialogUnsubscribe=null;this.nicknameDialogFailed=!1;this.dynamicThunkObject={};this.queues=new Ks;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=e.replace(/\/api$/,"");this.deepdeskApi=new yt(l,{token:r,fetch:s}),this.version=n,this.instanceId=Jn.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Tu({broadcast:(f,m,h)=>{this.broadcastEvents.send(f,m,h)},emit:(f,m)=>this.emit(f,m),handleAfterSendMessage:f=>this.handleAfterSendMessage(f),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:f=>this.logSendMessage(f),onUpdateShowTabHint:f=>Wu.update(f),sendEvent:(f,m)=>this.deepdeskApi.sendEvent(f,m)})]};this.store=Cu(c),this.broadcastEvents=new au({debug:!0,deepdeskUrl:l,eventMap:Vl(this.store),createCustomChannel:a}),this.disposeHandlers.push(()=>{this.broadcastEvents.cleanup()}),this.ws=new d({url:`${l}/api/v2/me/realtime`.replace("https","wss"),reconnectInterval:25e3,shouldReconnect:()=>v(this,null,function*(){var f;return(f=ne(this.state))!=null?f:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(Mo(Wu.value())),this.store.dispatch(lr({locale:o,adminUrl:l,productName:i}));let u=[],p=f=>{if(!f.conversationId)return;let m=()=>{this.conversationId()===f.conversationId&&this.store.dispatch(up(f))};this.hasConversation()?m():u.push(m)};this.ws.on("assistants::direct_response",p),this.ws.on("assistants::user_notification",p),this.ws.on("assistants::response_chunk",f=>{if(!f.conversationId)return;let m=()=>{this.conversationId()===f.conversationId&&this.store.dispatch(pp(f))};this.hasConversation()?m():u.push(m)}),this.ws.on("assistants::suggest_as_reply",f=>{if(!f.conversationId)return;let m=()=>{this.conversationId()===f.conversationId&&this.store.dispatch(wn([{text:f.payload.message,type:"text",source:"assistant",assistantCode:f.code,sourceLabel:f.name}]))};this.hasConversation()?m():u.push(m)});let g=this.whenConversationLoaded(()=>{var f;this.broadcastEvents.setExternalId((f=this.state.conversation.current)==null?void 0:f.externalId),u.forEach(m=>m()),u.length=0});this.disposeHandlers.push(()=>{this.ws.cleanup(),u.length=0,g()})}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var e;return(e=Vt(this.state)[this.state.input.selectedSuggestionIndex])!=null?e:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}externalId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.externalId}shouldAbort(){return this.state.conversation.isSupported===!1?(k.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(k.warn("Profile has not been loaded (yet)"),!0):(k.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(e){if(ne(this.state))e();else{let n=this.subscribe(ne,o=>{o&&e()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Sn(null)),this.store.dispatch(tt()),new Promise(e=>{this.whenLoggedIn(()=>e())})}isLoggedIn(){return v(this,null,function*(){return(yield this.store.dispatch(tt())).payload})}isConversationSupported(e,n){return v(this,null,function*(){return(yield this.store.dispatch(Js({externalId:e,options:n}))).payload})}createConversation(e){return v(this,null,function*(){var o;return this.hasConversation()&&this.externalId()!==e.externalId&&this.resetConversation(),(yield this.store.dispatch(cr(S(y({},e),{metadata:(o=e.metadata)!=null?o:{}})))).payload})}getConversationByExternalId(e,n){return v(this,null,function*(){return this.hasConversation()&&this.externalId()!==e&&this.resetConversation(),(yield this.store.dispatch(pr({externalId:e,options:n}))).payload})}upsertConversation(e){return v(this,null,function*(){var o;return this.hasConversation()&&this.externalId()!==e.externalId&&this.resetConversation(),(yield this.store.dispatch(Qs(S(y({},e),{metadata:(o=e.metadata)!=null?o:{}})))).payload})}postMessages(e){return v(this,null,function*(){yield this.store.dispatch(Zs(e))})}updateConversation(e){return v(this,null,function*(){return(yield this.store.dispatch(ur(e))).payload})}resetConversation(){this.store.dispatch(J()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(e){this.store.dispatch(lr(e))}setVisitorInfo(e){this.store.dispatch(Nl(e))}setCustomData(e){this.store.dispatch(Ol(e))}setAgentInfo(e,n){return v(this,null,function*(){var r;yield this.store.dispatch(oo(y(y({},e),n))),((r=this.state.info.agentInfo)==null?void 0:r.agentNickname)||this.broadcastEvents.send(xr,{showNicknameDialog:!0})})}setAgentSettings(e){return v(this,null,function*(){yield this.store.dispatch(ei(e))})}getAgentSettings(){return v(this,null,function*(){return(yield this.store.dispatch(ti())).payload})}refresh(){return v(this,null,function*(){if(this.shouldAbort())return Promise.resolve();let e=[];return e.push(this.refreshTextSuggestions()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})})}syncInputMediator(){this.inputMediator&&this.store.dispatch(fr({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}))}notifyExternalSuggestion(e){this.store.dispatch(ye(e))}evaluateAssistant(e,n){return v(this,null,function*(){var d;let{input:o={},transcript:r,showCuesInWidget:s=!0,includeMetadata:i}=n||{},a=yield this.store.dispatch(Xe({assistantCode:e,transcript:r,includeMetadata:i,input:o,skipState:!s}));if(a.error)throw new Error(`Assistant evaluation failed: ${(d=a.payload)!=null?d:a.error.message}`);return a.payload.output})}evaluateConversationAssistant(e,n){return v(this,null,function*(){yield this.loadProfileConfig();let o=this.state.profile.data;if(!o){k.warn("Can't evaluate assistant when profile is not loaded yet.");return}let r=Bu(o,e);yield Promise.all(r.map(s=>this.queues.push(s,()=>v(this,null,function*(){yield this.evaluateAssistant(s,y({includeMetadata:!0},n))})).catch(i=>{if(i instanceof Jo){k.warn(`Queued assistant "${s}" was outdated and dropped`);return}throw i})))})}handleKeyDown(e){let{overlayCollapsed:n,openOverlayWhenTyping:o}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,showTextSuggestions:d,suggestionsPlacement:l}=this.settings,c=l==="inline"||l==="below"?"below":"above",u=r.length>0;if(this.store.dispatch(Sl(Ys(e))),!$e(this.state)||e.key!=="Tab"&&!d)return;let p=()=>{n||!u||i&&(e.shiftKey||(this.store.dispatch(Tl()),e.preventDefault()))},g=()=>{n||!u||a&&s<=0||i&&(e.shiftKey||(this.store.dispatch(wl()),e.preventDefault()))};switch(e.key){case"ArrowUp":c==="below"?g():p();break;case"ArrowDown":{c==="below"?p():g();break}case"Escape":{n||(this.store.dispatch(gr(-1)),this.store.dispatch(Pt({collapse:!0})),this.store.dispatch(dc(!0)),e.preventDefault());break}case"Tab":{e.preventDefault();let f=Tn(this.state);if(!f)return;this.store.dispatch(Mo(!1)),this.store.dispatch(ye({text:f.text,suggestion:f,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let f=Tn(this.state);if(!f)return;this.store.dispatch(ye({text:f.text,suggestion:f,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||e.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let f=Tn(this.state);if(!f)return;this.store.dispatch(ye({text:f.text,suggestion:f,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),e.preventDefault();break}default:}n&&o&&this.store.dispatch(Pt({collapse:!1}))}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Tt([]))}handlingTimeStart(){this.state.handlingTime.startTime||(k.info("Start handling time"),this.store.dispatch(mu()))}handlingTimeStop(){this.state.handlingTime.startTime&&(k.info("Stop handling time"),this.store.dispatch(Ns()))}logSendMessage(e){let n=ku(this.state,{version:this.version});n&&(e&&(Object.assign(n,{text:e}),Object.assign(n,{lenTextTotal:e.length})),this.deepdeskApi.sendEvent("Send Message",{conversationId:this.conversationId(),data:n}),this.emit("send-message-event",n))}logHandlingTime(){let e=Eu(this.state,{version:this.version});e&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:e}),this.store.dispatch(gu()))}notifySubmit(e={}){var n;this.shouldAbort()||(this.store.dispatch($t((n=e.text)!=null?n:this.state.input.text)),this.store.dispatch(kl()))}emit(e,n){let o=this.eventListeners[e];o&&o.forEach(r=>{try{r(n)}catch(s){k.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),k.error(s)}})}on(e,n){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n),()=>{this.off(e,n)}}off(e,n){if(!e&&!n){this.eventListeners={};return}let o;this.eventListeners[e]&&(o=this.eventListeners[e].indexOf(n),o>-1&&this.eventListeners[e].splice(o,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}setPlatformVariables(e){this.store.dispatch(Dl(e))}whenConversationLoaded(e){let n=s=>{var i;return(i=s.conversation.current)==null?void 0:i.id},o=()=>this.loadProfileConfig().then(()=>e());return n(this.state)&&o(),this.subscribe(n,s=>{s&&o()})}overlayContainerFactory(e,n,o,r){let[s,i]=Xo(n,o);return s.setAttribute("translate","no"),s.dataset.testid=e,r&&s.classList.add(r),[s,i]}createInlineContainer(e,n){var a;let o=document.createElement("div");o.style.position="absolute",o.style.top="0px",o.style.left="0px",o.style.height="0px",o.style.width="0px";let r=document.createElement("div");r.style.display="none",r.style.position="absolute",r.style.height="0px",r.style.width="0px",r.style.backgroundColor="red",o.appendChild(r);let s=(a=e.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[d,l]=Xo(s,{appendTo:document.body,onMoveStart:()=>{r.style.display="none"}});d.dataset.testid=n,d.style.zIndex="2",d.appendChild(o),this.unmountHandlers.push(()=>{l()})}else document.body.appendChild(o);return r}createContainer(e,n=document.body){let o=window.getComputedStyle(n),r=document.createElement("div");return sn(r),r.dataset.testid=e,r.style.color=o.color,r.style.fontSize=o.fontSize,r.style.fontFamily=o.fontFamily,r.style.fontVariant=o.fontVariant,r.setAttribute("translate","no"),n.appendChild(r),r}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,n),k.info(`Stored analytics for ${this.conversationId()}`)}catch(e){}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(e);if(!n)return;let o=JSON.parse(n);o.text.trim()===this.state.input.text.trim()?(k.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(El(o.metrics))):k.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch(e){}}mount(e,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Fs(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let p=n,{customStyles:o,closestScrollSelector:r,floatingMenuParent:s,appendOverlayTo:i,inputMediator:a}=p,d=M(p,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),l={customStyles:o,closestScrollSelector:r,floatingMenuParent:s,appendOverlayTo:i};this.configure(d),this.settings.automaticHandlingTime&&this.setupHandlingTime(e),sn(e),this.inputMediator=a||(an(e)?new pn(e):new cn(e)),this.inputMediator.on("change",({plainText:g,rawHTML:f})=>{this.store.dispatch(fr({text:g,html:f}))}),this.inputMediator.on("keyup",g=>{this.store.dispatch(bl(Ys(g)))}),this.inputMediator.on("keydown",g=>{this.handleKeyDown(g)}),this.inputMediator.on("paste",({pastedText:g,selectionText:f})=>{this.store.dispatch(Cl({text:g,selectionText:f}))}),this.inputMediator.on("cut",({selectionText:g})=>{this.store.dispatch(xl(g))});let c;this.inputMediator.on("selection",g=>{clearTimeout(c),g===null?c=setTimeout(()=>{g!==null&&this.store.dispatch(hr(g))},500):this.store.dispatch(hr(g))}),this.unmountHandlers.push(()=>{clearTimeout(c)}),this.inputMediator.on("disabled",()=>{var g;(g=this.inputMediator)==null||g.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{this.settings.detectSubmit&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(qr(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(qr(!0))}),this.renderSuggestions(e,l),this.subscribe(vn("inlineSuggestions"),()=>{this.renderSuggestions(e,l)}),this.subscribe(vn("suggestionsPlacement"),()=>{this.renderSuggestions(e,l)});let u=this.renderOverlays(n);this.unmountHandlers.push(()=>{u.unmount()}),this.store.dispatch(fr({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(hr(this.inputMediator.getSelection())),this.store.dispatch(qr(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{this.restoreMetrics(),this.syncInputMediator(),this.refreshTextSuggestions(),this.promptForNickname()}),this.isMounted=!0}promptForNickname(e){if(this.nicknameDialogUnsubscribe||this.nicknameDialogFailed)return;let n=this.createContainer("nickname-dialog",document.body);document.body.appendChild(n);let o=(0,vt.createRoot)(n),r=null,s=a=>{r=a,i()},i=()=>{o==null||o.render((0,H.jsx)(at,{store:this.store,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(zu,{id:"deepdesk-nickname-dialog",error:r,onSave:a=>v(this,null,function*(){try{yield this.store.dispatch(Al({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(xr,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(d){k.error("Error setting agent nickname",d),s("error"),this.nicknameDialogFailed=!0}})})})}))};i(),this.nicknameDialogUnsubscribe=()=>{o.unmount(),n.remove(),this.nicknameDialogUnsubscribe=null}}subscribe(e,n){let o=e(this.store.getState());return this.store.subscribe(()=>{let r=e(this.store.getState());r!==o&&(o=r,n(o))})}unmount(){var e,n,o,r,s;(e=this.inlineSuggestions)==null||e.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(o=this.belowSuggestions)==null||o.unmount(),(r=this.floatingMenu)==null||r.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(s=this.inputMediator)==null||s.dispose(),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(e=>e()),this.disposeHandlers=[],this.off()}renderSuggestions(e,n){var o,r,s,i;(o=this.floatingMenu)==null||o.unmount(),(r=this.inlineSuggestions)==null||r.unmount(),(s=this.aboveSuggestions)==null||s.unmount(),(i=this.belowSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(e,n)),this.settings.inlineSuggestions||this.settings.suggestionsPlacement==="inline"?this.inlineSuggestions=this.renderInlineSuggestions(e,n):this.settings.suggestionsPlacement==="below"?this.belowSuggestions=this.renderAboveOrBelowSuggestions(e,n,"below"):this.aboveSuggestions=this.renderAboveOrBelowSuggestions(e,n,"above")}renderInlineSuggestions(e,n){let{customStyles:o}=n,r=this.createInlineContainer(e,"deepdesk-caret"),s=(0,vt.createRoot)(r);s.render((0,H.jsx)(at,{store:this.store,customStyles:o,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(Sc,{})})}));let i=a=>{a?(r.style.display="block",r.style.top=`${a.top}px`,r.style.left=`${a.left}px`):r.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",i),s.unmount(),r.remove()}}}renderAboveOrBelowSuggestions(e,n,o){let{customStyles:r,closestScrollSelector:s,appendOverlayTo:i}=n,a=s&&va(e,s)||void 0,[d,l]=this.overlayContainerFactory("deepdesk-tab-completion",a||e,{appendTo:i,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),[c,u]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||e,{appendTo:i,placement:o},r==null?void 0:r.suggestionsRootNode),p=(0,vt.createRoot)(d);p.render((0,H.jsx)(at,{store:this.store,customStyles:r,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(rp,{inputElement:e})})}));let g=(0,vt.createRoot)(c);return g.render((0,H.jsx)(at,{store:this.store,customStyles:r,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(Ac,{onLogIn:()=>this.loginViaPopup().catch(f=>k.warn(f.message))})})})),{unmount(){p.unmount(),g.unmount(),l(),u()}}}renderFloatingMenu(e,n){let{customStyles:o,closestScrollSelector:r,appendOverlayTo:s,floatingMenuParent:i}=n,a=r&&va(e,r)||void 0,[d,l]=this.overlayContainerFactory("floating-menu",a||e,{appendTo:i!=null?i:s},o==null?void 0:o.floatingMenuParent),c=(0,vt.createRoot)(d);return c.render((0,H.jsx)(at,{store:this.store,customStyles:o,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(sc,{onLogIn:()=>this.loginViaPopup().catch(u=>k.warn(u.message))})})})),{unmount(){c.unmount(),l()}}}renderOverlays(e){let{customStyles:n}=e,o=this.createContainer("deepdesk-overlays"),r=(0,vt.createRoot)(o);return r.render((0,H.jsx)(at,{store:this.store,customStyles:n,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(Zd,{})})})),{unmount(){r.unmount(),o.remove()}}}renderWidget(e,n={}){if(this.widgetElement&&k.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:o,showImages:r,isEmbedded:s,insertLinkAsHtml:i}=n;this.widgetElement=e,this.configure({showImages:r,isEmbedded:s,insertLinkAsHtml:i}),this.widgetRoot=(0,vt.createRoot)(e),this.widgetRoot.render((0,H.jsx)(at,{store:this.store,customStyles:o,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(tu,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(a=>k.warn(a.message))})})}))}unmountWidget(){var e,n;(n=(e=this.widgetRoot)==null?void 0:e.unmount)==null||n.call(e),this.widgetRoot=null,this.widgetElement=null}renderKnowledgeAssistantWidget(e,n,o={}){let{customStyles:r,initialQuestion:s}=o,i=(0,vt.createRoot)(n);return i.render((0,H.jsx)(at,{store:this.store,customStyles:r,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(la,{children:(0,H.jsxs)(Ps,{assistantCode:e,initialQuestion:s,evaluateKnowledgeAssistFn:Bo,children:[(0,H.jsx)(hn,{children:(0,H.jsx)(Ls,{title:o.title,emptyState:o.emptyState})}),(0,H.jsx)(aa,{children:(0,H.jsx)(Is,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(e){let n=Us(e,({isVisible:o})=>{o?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Ru(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>v(this,null,function*(){yield this.store.dispatch(So());let e=Jt(this.state);e&&this.store.dispatch(lr({showSearch:e.search,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:!!e.summarizerAssistantNew,showKnowledgeSearch:!!e.knowledgeAssistantNew||!!e.knowledgeAssistant,recommendTextSuggestions:e.recommendTextSuggestions}))})),this.loadProfileConfigPromise)}loginViaPopup(e){return v(this,null,function*(){return new Promise((n,o)=>{this.store.dispatch(dr());let r=new MessageChannel,s=r.port1,i=this.settings.adminUrl,a=new URL(e!=null&&e.url?e==null?void 0:e.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let d=!1,l=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",u),clearInterval(p)};s.onmessage=g=>v(this,null,function*(){var f,m;if((f=g.data)!=null&&f.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((m=g.data)==null?void 0:m.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(so),d=!0,r.port1.close(),n()}catch(h){console.error(h),o(h)}finally{d=!0,l()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&o(new Error("Popup blocked by browser"));let u=g=>v(this,null,function*(){var f;if(g.origin===a.origin)switch((f=g.data)==null?void 0:f.type){case"deepdesk-popup-request-origin":{try{let m=JSON.stringify({type:"deepdesk-popup-parent-origin"});c==null||c.postMessage(m,a.origin)}catch(m){k.error("Error posting message to popup",m),o(m)}break}case"deepdesk-popup-loaded":{try{let m=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(m,a.origin,[r.port2])}catch(m){k.error("Error posting message to popup",m),o(m)}break}case"deepdesk-popup-error":{if(l(),g.data.message==="Platform account url mismatch"){let m=`Please contact your administrator: The platform account url (${g.data.targetOrigin}) is misconfigured as it differs from the origin of the page that opened the popup (${g.data.openerOrigin}).`;k.warn(m),this.store.dispatch(Xs(m)),o(new Error(m))}if(g.data.message==="Timeout"){let m="Please contact your administrator: Popup timed out. Check if the account's platform url is configured correctly.";k.warn(m),this.store.dispatch(Xs(m)),o(new Error(m))}o(new Error(g.data.message));break}}});window.addEventListener("message",u);let p=setInterval(()=>{c&&!c.closed||(l(),d||o(new Error("Popup closed by user")))},200);this.disposeHandlers.push(l)})})}translateMessages(e){return this.deepdeskApi.translateMessages(e)}refreshTextSuggestions(){return v(this,null,function*(){this.isMounted&&(yield this.store.dispatch(Vr()))})}refreshWidgetSuggestions(){return v(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let n=bo(this.state);try{n.forEach(({type:o})=>{switch(o){case"entities":this.store.dispatch(Fe());break;case"pinned-messages":case"sticky-messages":break;default:ar.includes(o)||this.store.dispatch(He(o))}})}catch(o){this.handleError(o)}})}};Jn.version="19.0.2-beta.7",Jn.count=0;var Qo=Jn;function jh(t){return v(this,null,function*(){var r,s,i;let n=yield((r=t.fetch)!=null?r:window.fetch)(t.url),o=yield n.blob();return new File([o],t.name,{type:(i=(s=t.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function Vu(t,e){return v(this,null,function*(){let n=yield jh(e),o=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[n]}),t.dispatchEvent(o)}finally{Object.hasOwn(t,"files")&&delete t.files}})}function ju(t,e,n){return v(this,null,function*(){yield new yt(t).authenticateWithKey(e,n)})}function $u(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function Gu(o,r){return v(this,arguments,function*(t,e,n={}){var u,p;let{value:s}=t,{start:i,end:a}=(u=n.replace)!=null?u:{start:0,end:s.length},d=`${s.slice(0,i)}${e}${s.slice(a)}`,l=(p=n.selectionAfter)!=null?p:{start:i+e.length,end:i+e.length},c=()=>{if(n.setValue)return n.setValue(d);t.value=d};return Promise.resolve(c()).then(()=>{t.selectionStart=l.start,t.selectionEnd=l.end,t.blur(),t.focus()})})}function qu(o,r){return v(this,arguments,function*(t,e,n={}){let s=n.replace?Dt(t,n.replace.start,n.replace.end):$n(t),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?e.split(`
|
|
17
17
|
`).reverse().forEach((d,l)=>{l>0&&s.insertNode(document.createElement("br")),s.insertNode(document.createTextNode(d))}):s.insertNode(document.createTextNode(e))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){t.focus();let d=n.selectionAfter?Dt(t,n.selectionAfter.start,n.selectionAfter.end):(s.collapse(!1),s),l=window.getSelection();l==null||l.removeAllRanges(),l==null||l.addRange(d)}if(!i)return;i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}function $h(t){let e=document.createElement("template");return e.innerHTML=t.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),e.content}function Gh(t){let e=document.createDocumentFragment();return t.split(`
|
|
18
18
|
`).forEach((n,o)=>{o>0&&e.appendChild(document.createElement("br"));let r={index:0},s=0;for(;r=n.slice(s).match(/(\[([^\]]+)])\(([^)]+)\)/);){let i=document.createElement("a");i.href=r[3],i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),i.appendChild(document.createTextNode(r[2])),e.appendChild(document.createTextNode(n.slice(s,s+r.index))),e.appendChild(i),s=s+r.index+r[0].length}e.appendChild(document.createTextNode(n.slice(s)))}),e}function Xu(t,e){let n=t.parentElement;if(!n){console.warn("No insert point found");return}let{display:o}=window.getComputedStyle(n);o.includes("block")||o==="table-cell"?n==null||n.insertBefore(e,t.nextSibling):Xu(n,e)}function Ju(r,s){return v(this,arguments,function*(t,e,{isBlock:n,isHTML:o}={}){let i;t.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0}));let a=()=>{var p;let d=(p=t.ownerDocument.defaultView)!=null?p:window,l=d.getSelection();if((!l||l.rangeCount===0)&&(t.focus(),l=d.getSelection()),!l||l.rangeCount===0)return;let c=l.getRangeAt(0);if(!c)return;i=document.createElement("span"),c.insertNode(i);let u=o?$h(e):Gh(e);n?Xu(c.startContainer,u):(c.insertNode(u),c.collapse(!1))};return Promise.resolve(a()).then(()=>{if(t.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0})),t.focus(),!!i)try{i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}0&&(module.exports={Card,ContentEditableInput,DeepdeskAPI,DeepdeskSDK,HTTPClient,InputMediator,InputType,KeyboardHint,Label,Locale,Section,SectionList,Sources,Suggestion,SuggestionList,TextAreaInput,ToggleButton,attachFile,authenticateWithKey,createFullRange,createOverlayContainer,createRangeFromOffsets,escapeHTML,formatTextMarkup,getRangeOffsets,getRangeText,insertCKEditor,isHTML,isSupportedInputElement,logEvent,updateContentEditable,updateTextArea,useClickOutsideRoot,useStyles,waitForElementVisibilityChange});
|