@deepdesk/deepdesk-sdk 10.12.1-beta.3 → 10.12.1-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +2 -2
- package/dist/index.esm.js +2 -2
- package/dist/index.iife.js +2 -2
- package/package.json +1 -1
package/dist/index.iife.js
CHANGED
|
@@ -20,9 +20,9 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
|
20
20
|
c-17.9,17.9-27.3,40.1-27.3,65.7C163.4,163,163.4,233,163.4,233z M465.5,267.9V477c0,9.4-3.4,17.9-10.2,24.7
|
|
21
21
|
c-6.8,6.8-15.4,10.2-24.7,10.2h-349c-9.4,0-17.9-3.4-24.7-10.2c-6.8-6.8-10.2-15.4-10.2-24.7V267.9c0-9.4,3.4-17.9,10.2-24.7
|
|
22
22
|
c6.8-6.8,15.4-10.2,24.7-10.2h11.9v-70c0-44.4,16.2-82.8,47.8-115.2S212.1,0,256.4,0s82.8,16.2,115.2,47.8
|
|
23
|
-
c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});var ah=S(C()),DL={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},G1=({className:e,color:t})=>(0,ah.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,ah.jsx)("path",{d:"M172.03 0.0199966H0V86.03C47.5 86.03 86 124.54 86 172.04C86 124.54 124.51 86.03 172.01 86.03C219.51 86.03 258.03 124.54 258.03 172.04C258.03 219.54 219.52 258.05 172.01 258.05C124.5 258.05 86 219.54 86 172.04C86 219.54 47.5 258.05 0 258.05V344.06H172.03C267.04 344.06 344.06 267.04 344.06 172.03C344.06 77.02 267.04 0 172.03 0V0.0199966Z",fill:DL[t||"pink"]})});var X1={root:"_root_1tvv4_1",text:"_text_1tvv4_18",isLoggedIn:"_isLoggedIn_1tvv4_25",isLoggedOut:"_isLoggedOut_1tvv4_29",icon:"_icon_1tvv4_39",logo:"_logo_1tvv4_44",lock:"_lock_1tvv4_49"};var lh={};Ee(lh,{enUS:()=>FL,nlNL:()=>jL});var FL={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},jL={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var wo=S(C()),Y1=({onLogIn:e})=>{let t=H(lh),n=M("floatingMenu"),r=M("productName"),o=U(),i=R(Xe),s=k("FloatingMenu",X1);if(i===null||n===!1)return null;let a=()=>{i===!0?o(qe(!0)):e()};return(0,wo.jsxs)("button",{className:(0,Q1.default)(s.root,{[s.isLoggedIn]:i,[s.isLoggedOut]:!i}),onClick:a,children:[(0,wo.jsx)("div",{className:s.text,children:t(i?"search":"signin",{productName:r})}),(0,wo.jsxs)("div",{className:s.icon,children:[(0,wo.jsx)(G1,{className:s.logo,color:"pink"}),i===!1&&(0,wo.jsx)(q1,{className:s.lock})]})]})};var yd=S(O());function Bi(e){let{showMidSentenceSuggestions:t,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:r}=e.settings,{text:o,selection:i}=e.input.userCommitted;return i.start!==i.end?!1:i.end>=o.length?!0:t?n&&new RegExp(n).test(o.substring(i.end))||r&&new RegExp(r).test(o.substring(0,i.end))?!0:n===!1&&r===!1:!1}var gd=S(O());var zi=S(O());var Z1=S(O());function J1(e,t,n){(0,Z1.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var eC={root:"_root_4u430_1",actions:"_actions_4u430_8",badge:"_badge_4u430_15",formattedText:"_formattedText_4u430_19"};var Co=S(C()),BL=["search","personal-collection-search","search-autocomplete"];function zL(e,t,n,r={}){let o="";return BL.includes(t)?o=X_(Og(e,n,{stripAgentPart:!0}),r.searchKeywords??[n]):o=Og(e,n,r),r.placeholders===!0&&(o=Q_(o)),o}var UL=()=>{},KL=({index:e,selected:t,suggestion:n,onFeedback:r})=>{let o=M("inlineSuggestions"),i=R(wi),s=U(),a=k("TextSuggestion",eC),l=(0,zi.useRef)(null);(0,zi.useEffect)(()=>{let c=setTimeout(()=>{s(u_({text:n.text,suggestion:n}))},500);return()=>{clearTimeout(c)}},[n]),J1(l,"click",()=>{s(br(e)),s(zt({suggestion:n,text:n.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let u=(0,zi.useMemo)(()=>zL(n.text,n.source,i,{stripAgentPart:o,placeholders:!0,searchKeywords:n.searchKeywords}),[o,n.text,n.source,i,n.searchKeywords]);return n.source==="gpt"&&!o?null:(0,Co.jsxs)("div",{className:a.root,onMouseEnter:()=>s(br(e)),children:[(0,Co.jsx)(Q,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:t,onClick:UL,children:(0,Co.jsx)(Pn,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:u})}),t&&r&&(0,Co.jsx)("div",{className:a.actions,children:(0,Co.jsx)(ed,{onFeedback:()=>r(n),suggestion:n.text})})]})},tC=KL;var uh=S(C()),VL=({onFeedback:e,suggestions:t,selectedIndex:n,reverse:r})=>{let o=(0,gd.useMemo)(()=>{let i=t.map((s,a)=>(0,uh.jsx)(tC,{index:a,selected:a===n,suggestion:s,onFeedback:e},`${s.text}-${s.source}`));return r?i.reverse():i},[t,n,r]);return(0,uh.jsx)(gd.Fragment,{children:o})},hd=VL;var nC={root:"_root_otdbu_1",paper:"_paper_otdbu_11"};var Ka=S(C()),WL=({textSuggestions:e,selectedIndex:t})=>{let n=(0,yd.useRef)(null),r=k("InlineSuggestionsOverlay",nC),o=R(Bi),i=U(),s=R(Xe),a=R(_i),l=R(cd),u=M("showTextSuggestions");return Pi(()=>{i(Rr({collapse:!0,skipWhenInputFocus:!0}))}),(0,yd.useEffect)(()=>{let c=n.current;if(!c||!c.parentElement)return;c.parentElement.style.left="0px";let p=c.getBoundingClientRect();c.parentElement.style.left=`${Math.min(window.innerWidth-4-p.right,0)}px`}),l||!o||!u||e.length===0||s!==!0||a===!1?null:(0,Ka.jsx)("div",{className:r.root,"data-variant":"inline",children:(0,Ka.jsx)("div",{ref:n,className:r.paper,children:(0,Ka.jsx)(ut,{children:(0,Ka.jsx)(hd,{suggestions:e,selectedIndex:t})})})})},$L=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),rC=Cn($L)(WL);var Va=S(C()),qL=({children:e})=>{let n=M("locale").replace("-","");return(0,Va.jsx)(hg.Provider,{value:n,children:e})},GL=({store:e,customStyles:t={},children:n})=>(0,Va.jsx)(Ym,{store:e,children:(0,Va.jsx)(qL,{children:(0,Va.jsx)(Ji.Provider,{value:t,children:n})})}),bo=GL;var Sd=S(q()),Ui=S(O());var oC=S(O());function iC(e,t){let[n,r]=(0,oC.useState)(()=>{if(typeof window>"u")return t;try{let i=window.localStorage.getItem(e);return i?JSON.parse(i):t}catch(i){return j.error(i),t}});return[n,i=>{try{let s=i instanceof Function?i(n):i;r(s),typeof window<"u"&&window.localStorage.setItem(e,JSON.stringify(s))}catch(s){j.error(s)}}]}var aC=S(q()),Bn=S(O());var ch={};Ee(ch,{enUS:()=>XL,nlNL:()=>QL});var XL={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Sign in"}]},{type:0,value:" to enable "},{type:1,value:"productName"},{type:0,value:"."}],snooze:[{type:0,value:"Snooze for "},{type:8,value:"min",children:[{type:0,value:"10 minutes"}]},{type:0,value:", "},{type:8,value:"hour",children:[{type:0,value:"1 hour"}]},{type:0,value:" or "},{type:8,value:"day",children:[{type:0,value:"1 day"}]}]},QL={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Log in"}]},{type:0,value:" bij "},{type:1,value:"productName"},{type:0,value:"."}],snooze:[{type:0,value:"Snooze voor "},{type:8,value:"min",children:[{type:0,value:"10 minuten"}]},{type:0,value:", "},{type:8,value:"hour",children:[{type:0,value:"1 uur"}]},{type:0,value:" of "},{type:8,value:"day",children:[{type:0,value:"1 dag"}]}]};var sC={root:"_root_1vfca_1",anchor:"_anchor_1vfca_6",anchorButton:"_anchorButton_1vfca_11"};var Or=S(C()),dh=(e,t,n)=>r=>(0,Or.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),YL=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r,onLogIn:o})=>{let i=H(ch),s=At(),a=k("Login",sC),l=M("productName"),u=(0,Bn.useCallback)(m=>{m.preventDefault(),r&&r(parseInt(m.target.value,10))},[]),c=(0,Bn.useCallback)(m=>{m.preventDefault(),s.send(Di,!0)},[t]),p=(0,Bn.useMemo)(()=>m=>(0,Or.jsx)("a",{onClick:h=>{h.preventDefault(),o()},href:t,className:a.anchor,target:"_blank",rel:"noreferrer",children:m},"login"),[t]),d=(0,Bn.useCallback)(m=>(0,Or.jsx)("button",{type:"button",className:a.anchorButton,onClick:c,children:m},"prompt"),[c]),{min:f,hour:y,day:v}=(0,Bn.useMemo)(()=>({min:dh(a,60*10,u),hour:dh(a,60*60,u),day:dh(a,60*60*12,u)}),[]);return(0,Or.jsxs)("div",{className:(0,aC.default)(e,a.root),children:[i("loginPlease",{login:n?d:p,productName:l}),r&&(0,Or.jsxs)(Bn.Fragment,{children:[(0,Or.jsx)("br",{}),i("snooze",{min:f,hour:y,day:v})]})]})},vd=YL;var lC={root:"_root_1g8fi_1",text:"_text_1g8fi_19"};var Wa=S(C()),ZL=({title:e})=>{let t=k("SearchTrigger",lC),n=U();return(0,Wa.jsxs)("button",{type:"button",className:t.root,onClick:()=>n(qe(!0)),children:[(0,Wa.jsx)(Ai,{}),(0,Wa.jsx)("span",{className:t.text,children:e})]})},uC=ZL;var ph={};Ee(ph,{enUS:()=>JL,nlNL:()=>eA});var JL={arrowHint:[{type:0,value:"Tip: use arrow keys to navigate suggestions"}],searchHintWindows:[{type:0,value:"Press CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],searchHintMac:[{type:0,value:"Press CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Close"}],search:[{type:0,value:"Search"}]},eA={arrowHint:[{type:0,value:"Tip: Selecteer suggesties met pijltoetsen"}],searchHintWindows:[{type:0,value:"Druk CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],searchHintMac:[{type:0,value:"Druk CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Sluiten"}],search:[{type:0,value:"Zoeken"}]};var cC={root:"_root_onpov_1",isInline:"_isInline_onpov_14",toggleButton:"_toggleButton_onpov_21",toggleButtonWrapper:"_toggleButtonWrapper_onpov_25",toggleButtonWrapperHidden:"_toggleButtonWrapperHidden_onpov_32",isCollapsed:"_isCollapsed_onpov_36",collapsible:"_collapsible_onpov_36",hints:"_hints_onpov_44",hintsHidden:"_hintsHidden_onpov_51",triggers:"_triggers_onpov_56",triggersRight:"_triggersRight_onpov_71"};var pe=S(C()),tA=({textSuggestions:e,selectedIndex:t,onLogIn:n})=>{let r=k("SuggestionsOverlay",cC),o=H(ph),i=R(Bi),s=o_(),a=U(),l=(0,Ui.useRef)(null),u=M("searchTriggerKey"),c=M("productName"),p=R(cd),d=R(Xe),f=R(_i),[y,v]=(0,Ui.useState)(null),m=M("showSearch"),g=M("showTextSuggestions"),h=M("adminUrl"),x=M("isEmbedded"),[_,w]=iC("dd-snooze-until-ms",0),b=p||_>Date.now(),E=R(N=>N.input.text),P=e.filter(N=>N.source!=="gpt").length,I=()=>{b&&w(0),a(Kw(!b))},z=N=>{a(ze({name:"suggestion feedback",data:{text:N.text,source:"overlay",context:E},options:{includeConversationData:!0}}))},V=N=>{let le=Date.now()+N*1e3;w(le),j.info(`Snooze until: ${new Date(le)}`),a(Rr({collapse:!0}))};return(0,Ui.useEffect)(()=>{P===0&&v(null)},[e,P]),Pi(()=>{a(Rr({collapse:!0,skipWhenInputFocus:!0}))}),d===null||f===!1?null:d===!1?(0,pe.jsxs)("div",{ref:l,className:(0,Sd.default)(r.root,{[r.isCollapsed]:b}),children:[!b&&(0,pe.jsxs)("div",{className:r.triggers,children:[(0,pe.jsx)("div",{style:{flex:1}}),(0,pe.jsx)("div",{className:r.triggersRight,children:(0,pe.jsx)(zr,{className:r.toggleButton,title:o("collapse"),onClick:I,isCollapsed:!1})})]}),(0,pe.jsx)("div",{className:r.toggleButtonWrapper,children:(0,pe.jsx)(zr,{className:r.toggleButton,title:o("open",{productName:c}),onClick:I,isCollapsed:!0})}),(0,pe.jsx)("div",{className:r.collapsible,children:(0,pe.jsx)(vd,{loginUrl:h,isEmbedded:x,onLogIn:n,onSnooze:V})})]}):!s||!i?null:(0,pe.jsxs)("div",{ref:l,className:(0,Sd.default)(r.root,{[r.isCollapsed]:b}),children:[!b&&(0,pe.jsxs)("div",{className:r.triggers,children:[(0,pe.jsx)("div",{style:{flex:1},children:m&&(0,pe.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>v(o(id()?"searchHintMac":"searchHintWindows",{searchTriggerKey:u.toUpperCase()})),onMouseLeave:()=>v(null),children:(0,pe.jsx)(uC,{title:o("search")})})}),(0,pe.jsxs)("div",{className:r.triggersRight,onFocus:()=>{},children:[(0,pe.jsx)("div",{className:(0,Sd.default)(!y&&r.hintsHidden,r.hints),children:y}),(0,pe.jsx)(zr,{className:r.toggleButton,title:o("collapse"),onClick:I,isCollapsed:!1})]})]}),(0,pe.jsx)("div",{className:r.toggleButtonWrapper,children:(0,pe.jsx)(zr,{className:r.toggleButton,title:o("open",{productName:c}),onClick:I,isCollapsed:!0})}),P>0&&g&&(0,pe.jsx)("div",{className:r.collapsible,onFocus:()=>{},children:(0,pe.jsx)(ut,{children:(0,pe.jsx)(hd,{onFeedback:z,suggestions:e,selectedIndex:t,reverse:!0})})})]})},nA=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),dC=Cn(nA)(tA);var Ad=S(q());var Kn=S(O());var pC=S(O()),rA=["div","span","mark","strong","b","i","u","em"];function fh(e,t,n=0){var i;let r=e[e.length-1],o=typeof r=="object"&&r!==null?(i=r.props)==null?void 0:i.tagName:void 0;if(o==="br")return e.pop(),[...e,...t,r];if(rA.includes(o)){let s=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,pC.cloneElement)(r,{children:fh(s,t,n+1)})]}return[...e,...t]}function Nr(e){return e.tagName.toLowerCase()==="textarea"}var fC={root:"_root_81non_1",container:"_container_81non_3",agentText:"_agentText_81non_5",tabText:"_tabText_81non_6",hint:"_hint_81non_6",matchSelection:"_matchSelection_81non_10",focus:"_focus_81non_16",resetIndent:"_resetIndent_81non_20",matchKeyword:"_matchKeyword_81non_24",matchPlaceholder:"_matchPlaceholder_81non_25",hover:"_hover_81non_31",hintText:"_hintText_81non_64",popover:"_popover_81non_72",popoverRoot:"_popoverRoot_81non_77",popoverContentContainer:"_popoverContentContainer_81non_81",popoverContent:"_popoverContent_81non_81",selectionOptions:"_selectionOptions_81non_107",selectionOptionsIsHidden:"_selectionOptionsIsHidden_81non_112",selectionOptionsButton:"_selectionOptionsButton_81non_116",caret:"_caret_81non_132",popoverSuggestionsRoot:"_popoverSuggestionsRoot_81non_136",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_81non_141"};var wC=S(q());var Pd=S(O());function mC(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function xd(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function gC(e){return e!=null}var gh=S(q()),Ot=S(O());var _d=S(O()),oA=["bottom","height","left","right","top","width"],iA=(e={},t={})=>oA.some(n=>e[n]!==t[n]),zn=new Map,hC,yC=()=>{let e=[],t=[];zn.forEach((n,r)=>{if(r instanceof Element&&!r.isConnected){t.push(r);return}let o=r.getBoundingClientRect();iA(o,n.rect)&&(n.rect=o,e.push(n))}),t.forEach(n=>{zn.delete(n)}),e.forEach(n=>{n.callbacks.forEach(r=>r(n.rect))}),hC=window.requestAnimationFrame(yC)};function sA(e,t){return{observe(){let n=zn.size===0;if(zn.has(e)){let r=zn.get(e);r.callbacks.push(t),r.rect&&t(r.rect)}else zn.set(e,{rect:void 0,hasRectChanged:!1,callbacks:[t]});n&&yC()},unobserve(){let n=zn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||zn.delete(e),zn.size||cancelAnimationFrame(hC)}}}}function mh(e){let[t,n]=(0,_d.useState)(null);return(0,_d.useLayoutEffect)(()=>{if(!e.current)return;let r=sA(e.current,o=>{n(o)});return r.observe(),()=>{r.unobserve()}},[e]),t}var Ki=S(O()),SC=S(Pu());var vC={root:"_root_1jq08_1"};var xC=({children:e})=>{let[t,n]=(0,Ki.useState)(null),r=(0,Ki.useContext)(Ji);return(0,Ki.useLayoutEffect)(()=>{let o=document.createElement("div");return uo(o),o.classList.add(vC.root),r!=null&&r.portalRootNode&&o.classList.add(r==null?void 0:r.portalRootNode),document.body.appendChild(o),n(o),()=>{o.isConnected&&document.body.removeChild(o)}},[]),t?(0,SC.createPortal)(e,t):null};var cn={ref:"_ref_1rcyi_1",root:"_root_1rcyi_7",positionAbove:"_positionAbove_1rcyi_13",positionBelow:"_positionBelow_1rcyi_17",positionLeft:"_positionLeft_1rcyi_21",positionRight:"_positionRight_1rcyi_25",alignStart:"_alignStart_1rcyi_29",alignCenter:"_alignCenter_1rcyi_34",alignEnd:"_alignEnd_1rcyi_40"};var wd=S(C()),Cd=(e=!1)=>{let[t,n]=(0,Ot.useState)(e),r=(0,Ot.useCallback)(()=>n(!0),[]),o=(0,Ot.useCallback)(()=>n(!1),[]),i=(0,Ot.useCallback)(()=>n(a=>!a),[]),s=(0,Ot.useRef)(null);return{opened:t,open:r,close:o,toggle:i,triggerRef:s}};function hh(e,t=null,n=0){if(!e)return{display:"none"};let r=t?e.top-t.top<0||e.top<t.top-n?t.top-n:e.top+e.height>t.top+t.height+n?t.top+t.height+n-e.height:e.top:e.top,o=t?e.left<t.left-n?t.left-n:e.left+e.width>t.left+t.width+n?t.left+t.width+n-e.width:e.left:e.left;return{top:r,left:o,height:e.height,width:e.width}}var bd=({className:e,triggerRef:t,boundaryRef:n=(0,Ot.createRef)(),position:r="above",align:o="center",children:i,toStyle:s=hh,...a})=>{let l=mh(t),u=mh(n),c=(0,Ot.useMemo)(()=>s(l,u,0),[l,u]);return(0,wd.jsx)(xC,{children:(0,wd.jsx)("div",{className:(0,gh.default)(cn.ref,{[cn.positionAbove]:r==="above",[cn.positionBelow]:r==="below",[cn.positionLeft]:r==="left",[cn.positionRight]:r==="right",[cn.alignStart]:o==="start",[cn.alignCenter]:o==="center",[cn.alignEnd]:o==="end"}),style:c,...a,role:"dialog",children:(0,wd.jsx)("div",{className:(0,gh.default)(e,cn.root),children:i})})})};var _C=S(q()),Ed=S(O());var yh=S(C()),Td=(0,Ed.forwardRef)(({className:e,children:t,...n},r)=>{let o=(0,Ed.useRef)(null),i=k("TabCompletion",In);return(0,yh.jsx)("div",{ref:xd([o,r]),className:(0,_C.default)(e,i.popoverContentContainer),...n,children:(0,yh.jsx)("div",{className:i.popoverContent,children:t})})});var Mr=S(C()),aA=e=>t=>{let n=hh(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},lA=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let i=k("TabCompletion",In),s=Cd(),a=(0,Pd.useMemo)(()=>aA(e.getBoundingClientRect()),[e]),[l,u]=$c(e);return(0,Pd.useEffect)(()=>{u?s.open():s.close()},[u]),(0,Mr.jsxs)("span",{children:[(0,Mr.jsx)("mark",{ref:xd([l,s.triggerRef]),className:(0,wC.default)(i.matchKeyword,{[i.hover]:u}),"aria-haspopup":"dialog","aria-expanded":s.opened?"true":"false",children:r}),s.opened&&(0,Mr.jsx)(bd,{className:i.popover,triggerRef:s.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,Mr.jsx)(Td,{style:n,children:(0,Mr.jsx)("div",{className:i.hintText,children:o})})})]})},kd=class extends Tn{keywordMatches=[];preparedKeywordMatches=[];usedKeywordMatches=new Set;onBeforeParse(t,n){return n.keywordMatches&&n.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=n.keywordMatches.map(r=>({...r,keywordRegex:new RegExp(`\\b${mC(r.keyword)}\\b`,"i")})),this.keywordMatches=n.keywordMatches),this.usedKeywordMatches.clear(),t}match(t){let n=this.preparedKeywordMatches.map(o=>{if(this.usedKeywordMatches.has(o))return null;let i=t.match(o.keywordRegex);if(!i)return null;let s=t.charAt(i.index-1),a=t.charAt(i.index+o.keyword.length);return s==="{"&&a==="}"?null:{index:i.index,length:i[0].length,match:i[0],matchString:i[0],suggestion:o.suggestion,preparedKeywordMatch:o,valid:!0}}).filter(gC);if(n.length===0)return null;let r=n.reduce((o,i)=>i.index<o.index?i:o);return this.usedKeywordMatches.add(r.preparedKeywordMatch),r}replaceWith(t,n){return(0,Mr.jsx)(lA,{inputElement:n.inputElement,suggestion:n.suggestion,inputStyle:n.inputStyle,boundaryRef:n.boundaryRef,children:t},`keyword_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var Rd=S(q());var Ze=S(O());var vh=S(C()),CC=()=>(0,vh.jsx)("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:(0,vh.jsx)("path",{fill:"currentColor",d:"M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"})});var Dr=S(O());var EC=S(nh());var bC={root:"_root_1muu8_1",content:"_content_1muu8_7"};function Id(e,t,n){var o;let r=((o=e.imageSizes)==null?void 0:o[t])||e.image||n;if(!r)return null;try{return new URL(r).toString()}catch{return null}}function Sh(e){return e.replace("https://www.","").replace("https://","")}var Nt=S(C()),uA=3,cA=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),dA=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=uA})=>{let i=k("LinkSearch",bC),[s,a]=(0,Dr.useState)(""),l=U(),u=R(ld("url")),c=R(Sw("URL",cA)),[p,d]=(0,Dr.useState)(c.length-1),f=M("fallbackImage"),y=h=>{let x=h.target;a(x.value)},v=(h,x)=>{h.stopPropagation(),h.preventDefault(),window.open(x,"_blank")},m=h=>{var w;let x=p-1<0?c.length-1:p-1,_=p+1===c.length?0:p+1;h.code==="Escape"&&(a(""),t()),h.code==="ArrowUp"&&d(x),h.code==="ArrowDown"&&d(_),h.code==="Enter"&&e(((w=c[p])==null?void 0:w.text)||s)},g=(0,Dr.useCallback)((0,EC.default)(h=>{l(yo({query:h,type:"URL",tags:["link-search"]}))},300),[]);return(0,Dr.useEffect)(()=>{s&&g(s)},[s]),(0,Dr.useEffect)(()=>()=>{l(rd())},[]),(0,Nt.jsxs)("div",{className:i.root,children:[(0,Nt.jsx)(ut,{withDivider:!0,children:(s?c:u).slice(0,o).map((h,x)=>(0,Nt.jsx)(Q,{selected:p===x,onClick:()=>e(h.text),"data-testid":"linksearch-suggestion",children:(0,Nt.jsxs)(oe,{children:[(0,Nt.jsx)(oe.Image,{src:Id(h,"small",f||void 0),title:h.title||h.text}),(0,Nt.jsxs)(oe.Content,{className:i.content,cropText:!0,children:[(0,Nt.jsx)(oe.Title,{children:h.title||Sh(h.text)}),h.title&&Sh(h.text)]}),(0,Nt.jsx)(Q.Actions,{children:(0,Nt.jsx)(Q.ActionButton,{label:r,onClick:_=>v(_,h.text)})})]})},h.text))}),(0,Nt.jsx)(Ma,{value:s,onChange:y,autoFocus:!0,placeholder:n,onKeyUp:m})]})},TC=dA;var xh={};Ee(xh,{enUS:()=>pA,nlNL:()=>fA});var pA={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},fA={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var Ye=S(C()),mA=(0,Ze.forwardRef)((e,t)=>{let n=k("TabCompletion",In);return(0,Ye.jsx)("mark",{ref:t,className:(0,Rd.default)(n.matchSelection)},"selection-start")}),gA=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let i=H(xh),s=k("TabCompletion",In),a=(0,Ze.useRef)(null),l=(0,Ze.useRef)(null),[u,c]=(0,Ze.useState)(null),p=U(),d=Cd(document.activeElement===r),[f]=(0,Ze.useState)(()=>document.createRange());d.triggerRef.current=f,(0,Ze.useEffect)(()=>()=>f.detach(),[]),(0,Ze.useEffect)(()=>{let v=e.current,m=a.current;!v||!m||(f.setStart(v,0),f.setEnd(m,0))},[e.current,a.current]),Pi(()=>{d.close()});let y=(0,Ze.useCallback)(v=>{let m=f.toString(),g=/^http(s?):\/\//.test(v)?v:`https://${v}`;p(Sc({text:`[${m}](${g})`,replace:"selection"}))},[]);return(0,Ye.jsxs)("span",{children:[(0,Ye.jsx)("mark",{ref:a,className:(0,Rd.default)(s.matchSelection),"aria-haspopup":"dialog","aria-expanded":d.opened?"true":"false",children:o}),d.opened&&(0,Ye.jsx)(bd,{className:s.popoverRoot,triggerRef:d.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,Ye.jsxs)(Td,{style:n,ref:l,children:[(0,Ye.jsx)("div",{className:(0,Rd.default)(s.selectionOptions,{[s.selectionOptionsIsHidden]:u!==null}),children:(0,Ye.jsxs)("button",{type:"button",tabIndex:u===null?-1:void 0,className:s.selectionOptionsButton,onClick:()=>c("insertLink"),children:[(0,Ye.jsx)(CC,{}),(0,Ye.jsx)("span",{children:"\xA0"}),(0,Ye.jsx)("span",{children:i("insertLink")})]})}),u==="insertLink"&&(0,Ye.jsx)(TC,{placeholder:i("linkInputPlaceholder"),visitUrlText:i("visitUrl"),onSelectLink:y,onDismiss:()=>{c(null),d.close()}})]})})]},"selection-end")},Ld=class extends Tn{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(t,n){return this.props=n,this.charCount=0,this.startRef=(0,Ze.createRef)(),this.foundIndex=0,t}match(t){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[n,r]=this.props.selection;if(n===r)return null;let o=this.foundIndex===0?n:r,i=o>=this.charCount&&o<=this.charCount+t.length?{index:o-this.charCount,length:0,match:"",valid:!0}:null;i&&this.foundIndex++;let s=this.foundIndex===1;return i&&s?this.charCount+=o-this.charCount:this.charCount+=t.length,i?{isStart:s,...i}:null}replaceWith(t,n){return n.isStart?(0,Ye.jsx)(mA,{ref:this.startRef}):(0,Ye.jsx)(gA,{inputElement:n.inputElement,startRef:this.startRef,boundaryRef:n.boundaryRef,inputStyle:n.inputStyle})}asTag(){return"mark"}};var Un=S(C()),hA=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:i,keywordMatches:s,inputElement:a,source:l})=>{let u=k("TabCompletion",fC),c=M("insertLink"),p=M("showMidSentenceSuggestions"),d=M("inlineSuggestions"),f=Gc(a),y=(0,Kn.useRef)(null),v=R(Xe);(0,Kn.useEffect)(()=>{Nr(a)&&f&&Xc(a,f)},[f]);let m=(0,Kn.useCallback)(x=>{if(!o||!n)return x;let _=[(0,Un.jsx)("span",{className:u.resetIndent,children:"\u200B"},"u200B"),(0,Un.jsx)("span",{"data-testid":"tab-completion",className:(0,Ad.default)(u.tabText,u.resetIndent),"data-source":l,children:n},"tabText")];return r&&_.push((0,Un.jsx)("span",{className:(0,Ad.default)(u.hint,u.resetIndent),children:(0,Un.jsx)(pl,{keyCode:"tab"},"tabHint")})),fh(x,_)},[o,n,r]),g=(0,Kn.useMemo)(()=>{let x=[];return c&&x.push(new Ld("selection")),x.push(new Ti("placeholders")),i&&x.push(new kd("keywords")),x},[d,c,i]),h=(0,Kn.useMemo)(()=>{let x=window.getComputedStyle(a);return{"--dd-color":x.color,"--dd-font-size":x.fontSize,"--dd-font-family":x.fontFamily,"--dd-font-variant":x.fontVariant}},[]);return!e||!v?null:(0,Un.jsxs)("div",{ref:x=>{x!=null&&x.parentElement&&(y.current=x==null?void 0:x.parentElement)},className:u.root,style:h,children:[(0,Un.jsx)(Pn,{tagName:"span",containerTagName:"div",className:(0,Ad.default)(u.container,u.agentText),disableLineBreaks:Nr(a),content:t||"\u200B",onAfterParse:m,matchers:g,selection:f,keywordMatches:s,inputElement:a,inputStyle:h,boundaryRef:y,inlineSuggestionsOnlyAtEnd:!p}),(0,Un.jsx)("br",{})]})},yA=({input:e,ui:t,settings:n,styleSuggestions:r,conversation:o})=>{var v;let{tabCompletionSuggestion:i}=e,s=(i==null?void 0:i.text)||"",a=(i==null?void 0:i.source)||"",l=e.html??Ri(e.text),u=s.indexOf(e.text)===0?s.slice(e.text.length):"",{showTabHint:c}=t,{isSupported:p}=o,{showTabCompletion:d,visible:f,showStyleSuggestions:y}=n;return{showTabHint:c,showStyleSuggestions:y,showTabCompletion:d,content:l,tabText:u,source:a,keywordMatches:((v=r.list)==null?void 0:v.keywordMatches)??[],enabled:f&&p!==!1}},kC=Cn(yA)(hA);var yb=S(q()),vb=S(O());var PC={list:[],fetchState:"idle",isInitialRequest:null},RC=e=>e.autoflows.list||[],IC=e=>t=>{var n;return(n=t.list)==null?void 0:n.find(r=>r.triggerPayload===e)},Vn=D("autoflows/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getAutoflows(e)}),_h=D("autoflows/start",async(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");await r.startAutoflowSession(e),await n(Vn(e.platformSessionId))}),wh=D("autoflows/stop",async(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");await r.stopAutoflowSession(e.platformSessionId),await n(Vn(e.platformSessionId))}),vA=B({name:"autoflows",initialState:PC,reducers:{},extraReducers:e=>{e.addCase(_h.pending,(t,n)=>{let r=IC(n.meta.arg.triggerPayload)(t);r.state="Started",r.isBusy=!0}),e.addCase(wh.pending,(t,n)=>{let r=IC(n.meta.arg.triggerPayload)(t);r.state="Aborted",r.isBusy=!0}),e.addCase(Vn.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}),e.addCase(Vn.rejected,t=>{t.fetchState="error"}),e.addCase(Vn.fulfilled,(t,n)=>{t.list=n.payload,t.fetchState="done"}),e.addCase(J,()=>PC)}}),LC=D("autoflows/openStream",(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");let o=r.openStream(e);o.on("sessionAborted",()=>{n(Vn(e))}),o.on("sessionCompleted",()=>{n(Vn(e))})}),AC=D("autoflows/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),OC=vA.reducer;var NC={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},MC=e=>e.customMessages.list,DC=e=>t=>!!t.customMessages.sentSuggestions.find(n=>n===e),FC=e=>t=>!!t.customMessages.answeredSuggestions.find(n=>n===e),jC=e=>t=>!!t.customMessages.errorSuggestions.find(n=>n===e),$a=D("customMessages/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getCustomMessages(e)}),Od=D("customMessages/send",async(e,t)=>{let{platformSessionId:n,suggestion:r}=e,{deepdeskBrokerAPI:o}=t.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.sendCustomMessage(n,r)}),Nd=D("customMessages/answer",async(e,t)=>{let{platformSessionId:n,reply:r}=e,{deepdeskBrokerAPI:o}=t.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.answerCustomMessage(n,r)}),HC=B({name:"customMessages",initialState:NC,reducers:{onCustomMessage(e,t){Array.isArray(t.payload)?e.list=t.payload:e.list=[t.payload]}},extraReducers:e=>{e.addCase($a.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase($a.rejected,t=>{t.fetchState="error"}).addCase($a.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload||[]}).addCase(Od.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.errorSuggestions=t.errorSuggestions.filter(r=>n.meta.arg.suggestion.text!==r)}).addCase(Od.rejected,(t,n)=>{let r=t.sentSuggestions.indexOf(n.meta.arg.suggestion.text);t.errorSuggestions.push(...t.sentSuggestions.splice(r,1))}).addCase(Nd.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.answeredSuggestions.push(n.meta.arg.suggestion.text)}).addCase(Nd.rejected,(t,n)=>{let r=t.answeredSuggestions.indexOf(n.meta.arg.suggestion.text);t.errorSuggestions.push(...t.sentSuggestions.splice(r,1)),t.answeredSuggestions.splice(r,1)}).addCase(J,()=>NC)}}),BC=D("customMessages/openStream",(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");r.openStream(e).on("customMessageSuggestion",i=>{n(HC.actions.onCustomMessage(i))})}),zC=D("customMessages/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),UC=HC.reducer;var SA={token:null,accountUrl:null,interval:null},KC=e=>t=>{let{passwordlessToken:{token:n,accountUrl:r}}=t;return n&&r?`${r}/apis/admin/session/passwordless/login/?token=${n}&redirect=${e}`:null},Ch=D("passwordlessToken/getTemporaryPasswordlessToken",async(e,t)=>{let{deepdeskAPI:n}=t.extra,r=await n.requestPasswordlessToken();return{accountUrl:n.client.baseUrl,token:r}}),bh=D("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(Ch()),setInterval(()=>r(Ch()),n)}),VC=B({name:"passwordlessToken",initialState:SA,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(Ch.fulfilled,(t,n)=>{t.token=n.payload.token,t.accountUrl=n.payload.accountUrl}),e.addCase(bh.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:WC}=VC.actions,$C=VC.reducer;function qC(e){let{customMessages:t,autoflows:n}=e;return n.fetchState==="loading"&&n.isInitialRequest===!0||t.fetchState==="loading"&&t.isInitialRequest===!0}var nb=S(O());var JC=S(q()),eb=S(O());var XC=S(q());var GC={root:"_root_838fd_1"};var YC=S(C()),xA=({className:e,children:t})=>{let n=k("Unicode",GC);return(0,YC.jsx)("span",{className:(0,XC.default)(e,n.root),children:t})},QC=xA;var ZC={isDisabled:"_isDisabled_1rmfm_1",buttonStart:"_buttonStart_1rmfm_5",root:"_root_1rmfm_8",buttonStop:"_buttonStop_1rmfm_8",stateBadge:"_stateBadge_1rmfm_19",isCompleted:"_isCompleted_1rmfm_26",isStarted:"_isStarted_1rmfm_30",isAborted:"_isAborted_1rmfm_34"};var Eh={};Ee(Eh,{enUS:()=>_A,nlNL:()=>wA});var _A={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]},wA={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]};var ht=S(C()),bA=({disabled:e,state:t,displayName:n,description:r,onStartAutoflow:o,onStopAutoflow:i})=>{let s=k("Autoflow",ZC),a=H(Eh),l=t==="Started"?"stop":"start",u=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return(0,ht.jsxs)(Q,{className:(0,JC.default)(s.root,{[s.isDisabled]:e,[s.isCompleted]:t==="Completed",[s.isAborted]:t==="Aborted",[s.isStarted]:t==="Started"}),children:[(0,ht.jsx)(oe,{children:(0,ht.jsxs)(oe.Content,{children:[(0,ht.jsxs)(oe.Title,{children:[t&&(0,ht.jsx)("span",{className:s.stateBadge,children:a(t)}),n]}),(0,ht.jsx)("span",{children:r})]})}),(0,ht.jsx)(Q.Actions,{fixed:t==="Started",children:(0,ht.jsx)(Q.ActionButton,{primary:!0,className:l==="start"?s.buttonStart:s.buttonStop,onClick:t==="Started"?i:o,disabled:e,label:(0,ht.jsxs)(eb.Fragment,{children:[(0,ht.jsx)(QC,{children:u})," ",(0,ht.jsx)("span",{children:a(l)})]})})})]})},tb=bA;var Th=S(C()),EA=(e,t)=>{let n=t.filter(r=>r.state==="Started");return n.length>0?n.indexOf(e)===-1:!1},TA=({autoflows:e,onStartAutoflow:t,onStopAutoflow:n,platformSessionId:r})=>(0,Th.jsx)(nb.Fragment,{children:e.map(o=>(0,Th.jsx)(tb,{displayName:o.displayName,description:o.description,disabled:o.isBusy||EA(o,e),state:o.state,onStartAutoflow:()=>t({platformSessionId:r,triggerPayload:o.triggerPayload}),onStopAutoflow:()=>n({platformSessionId:r,triggerPayload:o.triggerPayload})},o.displayName))}),kA=({autoflows:e,conversation:t})=>{var n;return{autoflows:e.list,platformSessionId:(n=t.current)==null?void 0:n.sessionId}},PA={onStartAutoflow:_h,onStopAutoflow:wh},rb=Cn(kA,PA)(TA);var ob=S(q()),kh=S(O());var Wn={root:"_root_1e6ej_1",title:"_title_1e6ej_8",isUsed:"_isUsed_1e6ej_13",quickReplies:"_quickReplies_1e6ej_22",quickReply:"_quickReply_1e6ej_29",hasError:"_hasError_1e6ej_39",label:"_label_1e6ej_43",errorIcon:"_errorIcon_1e6ej_48"};var at=S(C()),IA=({suggestion:e})=>{let t=H(go),n=U(),r=R(DC(e.text)),o=R(FC(e.text)),i=R(jC(e.text)),s=R(dc),{replyOptions:a}=e,l=(0,kh.useCallback)(c=>{c.preventDefault(),c.stopPropagation(),!(r||!s)&&n(Od({platformSessionId:s,suggestion:e}))},[e,r,n,s]),u=(0,kh.useCallback)(c=>{if(c.preventDefault(),c.stopPropagation(),!s||!a)return;let p=parseInt(c.target.dataset.index,10),d=a[p];n(Nd({platformSessionId:s,reply:d,suggestion:e}))},[e,r,n,s]);return(0,at.jsxs)(Q,{onClick:l,className:(0,ob.default)(Wn.root,{[Wn.isUsed]:r,[Wn.hasError]:i}),children:[(0,at.jsx)(oe,{children:(0,at.jsxs)(oe.Content,{children:[(0,at.jsxs)(oe.Title,{className:Wn.title,children:[e.text," ",(0,at.jsx)(fl,{className:Wn.label,children:"analyse tool"})," ",i&&(0,at.jsx)("span",{className:Wn.errorIcon,role:"img","aria-label":t("sendingError"),title:t("sendingError"),children:"!"})]}),a&&a.length>0&&(0,at.jsx)("ul",{className:Wn.quickReplies,children:a.map(c=>(0,at.jsx)("li",{className:Wn.quickReply,children:c.title},c.title))})]})}),(0,at.jsxs)(Q.Actions,{fixed:i||r,children:[a&&a.length>0&&(0,at.jsx)(Q.DropdownButton,{label:t("answer"),disabled:o,children:a.map((c,p)=>(0,at.jsx)(Q.DropdownItem,{index:p,label:c.title,onClick:u},c.title))}),(0,at.jsx)(Q.ActionButton,{primary:!0,disabled:r,onClick:l,label:t(r?"suggestionSent":i?"tryAgain":"sendSuggestion")})]})]})},ib=IA;var Md=S(O());var Rh=S(q());var Ph=S(C()),Ih=()=>(0,Ph.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,Ph.jsx)("path",{d:"M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"})});var sb={root:"_root_rjdyr_1",entity:"_entity_rjdyr_10",entityText:"_entityText_rjdyr_46",iconWrapper:"_iconWrapper_rjdyr_53",icon:"_icon_rjdyr_53",iconClicked:"_iconClicked_rjdyr_67"};var dn=S(C()),RA=({entities:e})=>{let t=k("EntitiesWidgetList",sb),[n,r]=(0,Md.useState)(void 0),o=U(),i=()=>{r(void 0)},s=a=>{e&&(r(e.indexOf(a)),Fa(a.text),o(ze({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,Md.useEffect)(()=>{let a=setTimeout(i,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,dn.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,dn.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>s(a),children:[(0,dn.jsx)("span",{className:t.entityText,children:a.text}),(0,dn.jsxs)("span",{className:t.iconWrapper,children:[(0,dn.jsx)("span",{className:(0,Rh.default)(t.icon),children:(0,dn.jsx)(Ih,{})}),(0,dn.jsx)("span",{className:(0,Rh.default)(t.icon,n===l&&t.iconClicked),children:(0,dn.jsx)(Ih,{})})]})]},a.text))})},ab=RA;var Lh=S(C()),lb=()=>(0,Lh.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,Lh.jsx)("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});var Ah=S(C()),ub=()=>(0,Ah.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Ah.jsx)("path",{d:"M543-340q16.595 0 28.798-12.202Q584-364.405 584-381t-12.202-28.798Q559.595-422 543-422t-28.798 12.202Q502-397.595 502-381t12.202 28.798Q526.405-340 543-340Zm-25-126h47q2-29 8.5-43t32.5-39q27-26 37.5-45.395Q654-612.79 654-639q0-45.882-31.5-74.941Q591-743 540-743q-38 0-68 20.5T428-665l45 19q11-25 27.5-38t39.5-13q29.778 0 48.389 17Q607-663 607-637q0 20-9 35t-32 32q-32 29-40 46.5t-8 57.5ZM260-200q-24 0-42-18t-18-42v-560q0-24 18-42t42-18h560q24 0 42 18t18 42v560q0 24-18 42t-42 18H260Zm0-60h560v-560H260v560ZM140-80q-24 0-42-18t-18-42v-620h60v620h620v60H140Zm120-740v560-560Z"})});var Oh=S(C()),cb=()=>(0,Oh.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Oh.jsx)("path",{d:"M319-250h322v-60H319v60Zm0-170h322v-60H319v60ZM220-80q-24 0-42-18t-18-42v-680q0-24 18-42t42-18h361l219 219v521q0 24-18 42t-42 18H220Zm331-554v-186H220v680h520v-494H551ZM220-820v186-186 680-680Z"})});var Dd=S(O());var Nh={};Ee(Nh,{enUS:()=>LA,nlNL:()=>AA});var LA={copyCue:[{type:0,value:"Copy"}],copiedCue:[{type:0,value:"Copied!"}],removeCue:[{type:0,value:"Close"}]},AA={copyCue:[{type:0,value:"Kopieer"}],copiedCue:[{type:0,value:"Gekopieerd!"}],removeCue:[{type:0,value:"Sluiten"}]};var $n=S(C()),OA=({cue:e,onRemove:t,onCopy:n})=>{let r=H(Nh),[o,i]=(0,Dd.useState)(!1),s=l=>{l.preventDefault(),l.stopPropagation(),n&&(n(e.text),i(!0))},a=l=>{l.preventDefault(),l.stopPropagation(),t&&t(e.id)};return(0,Dd.useEffect)(()=>{if(!o)return;let l=setTimeout(()=>{i(!1)},1e3);return()=>{clearTimeout(l)}},[o]),(0,$n.jsx)(Q,{"data-testid":"cue",children:(0,$n.jsxs)(oe,{children:[(0,$n.jsxs)(oe.Content,{children:[e.title&&(0,$n.jsx)(oe.Title,{"data-testid":"widget-cue-title",children:e.title}),e.text]}),(0,$n.jsx)(Q.Actions,{children:n&&(0,$n.jsx)(Q.ActionButton,{primary:!0,onClick:s,label:r(o?"copiedCue":"copyCue")})}),(0,$n.jsx)(oe.CloseIcon,{title:r("removeCue"),onClick:a})]})})},db=OA;var qa=S(C()),NA=({cues:e,onCopyCue:t,onRemoveCue:n})=>(0,qa.jsx)(qa.Fragment,{children:e.map(r=>(0,qa.jsx)(db,{cue:r,onRemove:n,onCopy:t},`${r.id}_${r.timestamp}`))}),pb=NA;var fb=S(O());var yt=S(C()),MA=({suggestion:e,lines:t,onEdit:n,onUse:r})=>{var d;let o=e.text||e.url||e.message,i=od(o),s=H(go),a=M("showImages"),l=M("fallbackImage"),u=f=>{f.preventDefault(),f.stopPropagation(),r(o)},c=f=>{f.preventDefault(),f.stopPropagation(),n(e)},p=(0,fb.useCallback)(f=>{window.open(i,"_blank"),f.stopPropagation(),f.preventDefault()},[i]);return(0,yt.jsxs)(Q,{onClick:u,"data-testid":"edit-suggestion",children:[(0,yt.jsxs)(oe,{children:[a&&e.image&&(0,yt.jsx)(oe.Image,{src:Id(e,"small",l||void 0),title:e.title}),(0,yt.jsxs)(oe.Content,{children:[e.title&&(0,yt.jsx)(oe.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((d=e.searchKeywords)==null?void 0:d.length)>0&&(0,yt.jsx)(Q.Labels,{labels:e.searchKeywords}),(0,yt.jsx)(oe.Content,{cropText:t==="single",lineClamp:t==="multiple",children:o})]})]}),(0,yt.jsxs)(Q.Actions,{children:[i&&(0,yt.jsx)(Q.ActionButton,{onClick:p,label:s("visitUrl")}),(0,yt.jsx)(Q.ActionButton,{primary:!0,onClick:c,label:s("preview")}),(0,yt.jsx)(Q.ActionButton,{primary:!0,onClick:u,label:s("useSuggestion")})]})]})},mb=MA;var Ga=S(C()),DA=({contentType:e,lines:t,suggestions:n})=>{let r=At(),o=R(Ir),i=a=>{r.send(Xg,{state:o,suggestion:a,contentType:e})},s=(a,l)=>{r.send(Fn,{text:a,suggestion:{...l,source:l.source,sourceText:l.text}})};return(0,Ga.jsx)(Ga.Fragment,{children:n.map(a=>(0,Ga.jsx)(mb,{suggestion:a,lines:t,onEdit:l=>i(l),onUse:l=>s(l,a)},a.text||a.url||a.message))})},gb=DA;var Mh={};Ee(Mh,{enUS:()=>FA,nlNL:()=>jA});var FA={waiting:[{type:0,value:"Loading\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"My "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Summarize"}],linkKnowledgeSearch:[{type:0,value:"Knowledge Assist"}],linkSearch:[{type:0,value:"Search"}]},jA={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"Mijn "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Gesprek samenvatten"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}]};var hb={root:"_root_x0pwe_1",loginText:"_loginText_x0pwe_7",stateText:"_stateText_x0pwe_8",sectionList:"_sectionList_x0pwe_20",shortcutList:"_shortcutList_x0pwe_24",shortcut:"_shortcut_x0pwe_24",link:"_link_x0pwe_52"};var K=S(C()),Fd=(e,t)=>{let n=R(Xe);(0,vb.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},HA=({onLogIn:e})=>{let t=H(Mh),n=U(),r=M("isEmbedded"),o=k("Widget",hb),i=M("showAutoflows"),s=M("showCustomMessages"),a=M("showSummaryCommand"),l=M("showKnowledgeSearch"),u=M("showSearch"),c=R(Ar),p=R(fd),d=R(RC),f=R(e1),y=R(pd),v=R(MC),m=R(pc),g=R(_i),h=R(Xe),x=R(dc),_=R(qC),w=R(Ir),b=At(),E=R(Rw),P=R(KC("/admin/")),I=M("adminUrl"),z=M("productName");if(Fd(()=>(n($a(x)),n(BC(x)),()=>{n(zC(x))}),[n,g,s,x]),Fd(()=>(n(Vn(x)),n(LC(x)),()=>{n(AC(x))}),[n,g,i,x]),Fd(()=>{p.forEach(({type:N})=>{n(N==="entities"?qt():Wt(N))})},[n,g,m,c]),Fd(()=>(n(bh()),()=>{n(WC())}),[n]),g===!1)return(0,K.jsx)("div",{className:o.stateText,children:(0,K.jsx)("div",{children:(0,K.jsx)("p",{children:t("notSupported")})})},"supported");if(h===!1)return(0,K.jsx)("div",{className:o.loginText,children:(0,K.jsx)("div",{children:(0,K.jsx)(vd,{isEmbedded:r,loginUrl:I,onLogIn:e})})},"login");if(!c||!x||h===null||E||_)return(0,K.jsx)("div",{className:o.stateText,children:(0,K.jsx)("div",{children:(0,K.jsx)("p",{children:t("waiting")})})},"waiting");let V=u||a||l||P;return(0,K.jsx)("div",{className:(0,yb.default)(o.root),"data-testid":"widget",children:(0,K.jsxs)(ml,{className:o.sectionList,children:[V&&(0,K.jsx)(mn,{title:t("actions"),type:"shortcuts",children:(0,K.jsxs)("div",{className:o.shortcutList,children:[u&&(0,K.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-search",onClick:()=>b.send("ShowCommandPalette",{isOpen:!0}),children:[(0,K.jsx)(Ai,{}),t("linkSearch")]}),a&&(0,K.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-summary",onClick:()=>b.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,K.jsx)(cb,{}),t("linkSummary")]}),l&&(0,K.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>b.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,K.jsx)(ub,{}),t("linkKnowledgeSearch")]}),P&&(0,K.jsxs)("a",{className:o.shortcut,target:"_blank",href:P,"data-testid":"shortcut-studio-login",rel:"noreferrer",children:[(0,K.jsx)(lb,{}),t("linkStudioLogin",{productName:z})]})]})}),s&&v.length>0&&(0,K.jsx)(mn,{type:"custom-messages","data-testid":"custom-messages",children:(0,K.jsx)(ut,{withDivider:!0,children:v.map(N=>(0,K.jsx)(ib,{suggestion:N},N.text))})}),i&&d.length>0&&(0,K.jsx)(mn,{type:"autoflows",title:t("titleAutoflows"),"data-testid":"autoflows",children:(0,K.jsx)(ut,{withDivider:!0,children:(0,K.jsx)(rb,{})})}),p.map(({type:N,title:le,amount:qi,lines:Je})=>{var Gn;switch(N){case"entities":return y&&y.length>0&&(0,K.jsx)(mn,{type:N,title:le,"data-testid":`type-${N}`,children:(0,K.jsx)(ab,{entities:y})},N);case"cues":return f&&f.length>0&&(0,K.jsx)(mn,{type:N,title:le,"data-testid":`type-${N}`,children:(0,K.jsx)(ut,{withDivider:!0,children:(0,K.jsx)(pb,{cues:f,onRemoveCue:Qt=>n(n1({id:Qt}))})})},N);default:return((Gn=w[N])==null?void 0:Gn.fetchState)==="done"&&w[N].suggestions.length>0&&(0,K.jsx)(mn,{type:N,title:le,"data-testid":`type-${N}`,children:(0,K.jsx)(ut,{withDivider:!0,children:(0,K.jsx)(gb,{lines:Je,contentType:N,suggestions:w[N].suggestions.slice(0,qi)||[]})})},N)}})]})})},Sb=HA;function Vi(e){let t=new Range;return t.selectNodeContents(e),t}function xb(e,t,n){try{return Fr(e,t,n),!0}catch{return!1}}function jd(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function Hd(e){return"tagName"in e&&e.tagName==="BR"}var Xa=/[\u200B-\u200D\uFEFF]/g;function Fr(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,i=!1;function s(l,u){let c=-1,p=/[\u200B-\u200D\uFEFF]/;if(!p.test(l))return u;for(let d=0;d<=l.length;d++)if(p.test(l[d])||c++,c===u)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let u=l.textContent,c=u.replace(Xa,""),p=o+c.length,d=t>=o&&t<=p,f=n>=o&&n<=p;if(d){let y=s(u,t-o);y===0&&!f?r.setStartBefore(l):r.setStart(l,y)}f&&(r.setEnd(l,s(u,n-o)),i=!0),o=p;break}case Node.ELEMENT_NODE:{if(Hd(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),i=!0;return}for(let c=0;c<l.childNodes.length&&(a(l.childNodes[c]),!i);c++);let u=l.lastChild;jd(l)&&u&&!jd(u)&&!Hd(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function Qa(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a,l,u=0;function c(p){let d=p===n,f=p===o;switch(p.nodeType){case Node.TEXT_NODE:{let y=p.textContent;d&&(a=u+y.substring(0,r).replace(Xa,"").length),f&&(l=u+y.substring(0,i).replace(Xa,"").length),u+=y.replace(Xa,"").length;break}case Node.ELEMENT_NODE:{let y=p.nextSibling===null;Hd(p)&&!y&&u++;for(let v=0;v<p.childNodes.length;v++){let m=d&&v===r,g=f&&v===i;if(m&&(a=u),g&&(l=u),l!==void 0||((!m||!s)&&c(p.childNodes[v]),f&&v===i-1&&(l=u),l!==void 0))break}!f&&jd(p)&&!y&&u++,f&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a??l,end:l}}function Ya(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i}=t,s=-1,a="";function l(u){let c=u===n,p=u===o;switch(c&&s++,u.nodeType){case Node.TEXT_NODE:{if(s!==0)return;let d=c?r:0,f=p?i:void 0,y=u.textContent.replace(Xa,"");d===0&&f===void 0?a+=y:a+=y.substring(d,f);break}case Node.ELEMENT_NODE:{let d=u.nextSibling===null;s===0&&Hd(u)&&!d&&(a+=`
|
|
23
|
+
c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});var ah=S(C()),DL={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},G1=({className:e,color:t})=>(0,ah.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,ah.jsx)("path",{d:"M172.03 0.0199966H0V86.03C47.5 86.03 86 124.54 86 172.04C86 124.54 124.51 86.03 172.01 86.03C219.51 86.03 258.03 124.54 258.03 172.04C258.03 219.54 219.52 258.05 172.01 258.05C124.5 258.05 86 219.54 86 172.04C86 219.54 47.5 258.05 0 258.05V344.06H172.03C267.04 344.06 344.06 267.04 344.06 172.03C344.06 77.02 267.04 0 172.03 0V0.0199966Z",fill:DL[t||"pink"]})});var X1={root:"_root_1tvv4_1",text:"_text_1tvv4_18",isLoggedIn:"_isLoggedIn_1tvv4_25",isLoggedOut:"_isLoggedOut_1tvv4_29",icon:"_icon_1tvv4_39",logo:"_logo_1tvv4_44",lock:"_lock_1tvv4_49"};var lh={};Ee(lh,{enUS:()=>FL,nlNL:()=>jL});var FL={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},jL={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var wo=S(C()),Y1=({onLogIn:e})=>{let t=H(lh),n=M("floatingMenu"),r=M("productName"),o=U(),i=R(Xe),s=k("FloatingMenu",X1);if(i===null||n===!1)return null;let a=()=>{i===!0?o(qe(!0)):e()};return(0,wo.jsxs)("button",{className:(0,Q1.default)(s.root,{[s.isLoggedIn]:i,[s.isLoggedOut]:!i}),onClick:a,children:[(0,wo.jsx)("div",{className:s.text,children:t(i?"search":"signin",{productName:r})}),(0,wo.jsxs)("div",{className:s.icon,children:[(0,wo.jsx)(G1,{className:s.logo,color:"pink"}),i===!1&&(0,wo.jsx)(q1,{className:s.lock})]})]})};var yd=S(O());function Bi(e){let{showMidSentenceSuggestions:t,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:r}=e.settings,{text:o,selection:i}=e.input.userCommitted;return i.start!==i.end?!1:i.end>=o.length?!0:t?n&&new RegExp(n).test(o.substring(i.end))||r&&new RegExp(r).test(o.substring(0,i.end))?!0:n===!1&&r===!1:!1}var gd=S(O());var zi=S(O());var Z1=S(O());function J1(e,t,n){(0,Z1.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var eC={root:"_root_4u430_1",actions:"_actions_4u430_8",badge:"_badge_4u430_15",formattedText:"_formattedText_4u430_19"};var Co=S(C()),BL=["search","personal-collection-search","search-autocomplete"];function zL(e,t,n,r={}){let o="";return BL.includes(t)?o=X_(Og(e,n,{stripAgentPart:!0}),r.searchKeywords??[n]):o=Og(e,n,r),r.placeholders===!0&&(o=Q_(o)),o}var UL=()=>{},KL=({index:e,selected:t,suggestion:n,onFeedback:r})=>{let o=M("inlineSuggestions"),i=R(wi),s=U(),a=k("TextSuggestion",eC),l=(0,zi.useRef)(null);(0,zi.useEffect)(()=>{let c=setTimeout(()=>{s(u_({text:n.text,suggestion:n}))},500);return()=>{clearTimeout(c)}},[n]),J1(l,"click",()=>{s(br(e)),s(zt({suggestion:n,text:n.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let u=(0,zi.useMemo)(()=>zL(n.text,n.source,i,{stripAgentPart:o,placeholders:!0,searchKeywords:n.searchKeywords}),[o,n.text,n.source,i,n.searchKeywords]);return n.source==="gpt"&&!o?null:(0,Co.jsxs)("div",{className:a.root,onMouseEnter:()=>s(br(e)),children:[(0,Co.jsx)(Q,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:t,onClick:UL,children:(0,Co.jsx)(Pn,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:u})}),t&&r&&(0,Co.jsx)("div",{className:a.actions,children:(0,Co.jsx)(ed,{onFeedback:()=>r(n),suggestion:n.text})})]})},tC=KL;var uh=S(C()),VL=({onFeedback:e,suggestions:t,selectedIndex:n,reverse:r})=>{let o=(0,gd.useMemo)(()=>{let i=t.map((s,a)=>(0,uh.jsx)(tC,{index:a,selected:a===n,suggestion:s,onFeedback:e},`${s.text}-${s.source}`));return r?i.reverse():i},[t,n,r]);return(0,uh.jsx)(gd.Fragment,{children:o})},hd=VL;var nC={root:"_root_otdbu_1",paper:"_paper_otdbu_11"};var Ka=S(C()),WL=({textSuggestions:e,selectedIndex:t})=>{let n=(0,yd.useRef)(null),r=k("InlineSuggestionsOverlay",nC),o=R(Bi),i=U(),s=R(Xe),a=R(_i),l=R(cd),u=M("showTextSuggestions");return Pi(()=>{setTimeout(()=>{i(Rr({collapse:!0,skipWhenInputFocus:!0}))})}),(0,yd.useEffect)(()=>{let c=n.current;if(!c||!c.parentElement)return;c.parentElement.style.left="0px";let p=c.getBoundingClientRect();c.parentElement.style.left=`${Math.min(window.innerWidth-4-p.right,0)}px`}),l||!o||!u||e.length===0||s!==!0||a===!1?null:(0,Ka.jsx)("div",{className:r.root,"data-variant":"inline",children:(0,Ka.jsx)("div",{ref:n,className:r.paper,children:(0,Ka.jsx)(ut,{children:(0,Ka.jsx)(hd,{suggestions:e,selectedIndex:t})})})})},$L=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),rC=Cn($L)(WL);var Va=S(C()),qL=({children:e})=>{let n=M("locale").replace("-","");return(0,Va.jsx)(hg.Provider,{value:n,children:e})},GL=({store:e,customStyles:t={},children:n})=>(0,Va.jsx)(Ym,{store:e,children:(0,Va.jsx)(qL,{children:(0,Va.jsx)(Ji.Provider,{value:t,children:n})})}),bo=GL;var Sd=S(q()),Ui=S(O());var oC=S(O());function iC(e,t){let[n,r]=(0,oC.useState)(()=>{if(typeof window>"u")return t;try{let i=window.localStorage.getItem(e);return i?JSON.parse(i):t}catch(i){return j.error(i),t}});return[n,i=>{try{let s=i instanceof Function?i(n):i;r(s),typeof window<"u"&&window.localStorage.setItem(e,JSON.stringify(s))}catch(s){j.error(s)}}]}var aC=S(q()),Bn=S(O());var ch={};Ee(ch,{enUS:()=>XL,nlNL:()=>QL});var XL={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Sign in"}]},{type:0,value:" to enable "},{type:1,value:"productName"},{type:0,value:"."}],snooze:[{type:0,value:"Snooze for "},{type:8,value:"min",children:[{type:0,value:"10 minutes"}]},{type:0,value:", "},{type:8,value:"hour",children:[{type:0,value:"1 hour"}]},{type:0,value:" or "},{type:8,value:"day",children:[{type:0,value:"1 day"}]}]},QL={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Log in"}]},{type:0,value:" bij "},{type:1,value:"productName"},{type:0,value:"."}],snooze:[{type:0,value:"Snooze voor "},{type:8,value:"min",children:[{type:0,value:"10 minuten"}]},{type:0,value:", "},{type:8,value:"hour",children:[{type:0,value:"1 uur"}]},{type:0,value:" of "},{type:8,value:"day",children:[{type:0,value:"1 dag"}]}]};var sC={root:"_root_1vfca_1",anchor:"_anchor_1vfca_6",anchorButton:"_anchorButton_1vfca_11"};var Or=S(C()),dh=(e,t,n)=>r=>(0,Or.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),YL=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r,onLogIn:o})=>{let i=H(ch),s=At(),a=k("Login",sC),l=M("productName"),u=(0,Bn.useCallback)(m=>{m.preventDefault(),r&&r(parseInt(m.target.value,10))},[]),c=(0,Bn.useCallback)(m=>{m.preventDefault(),s.send(Di,!0)},[t]),p=(0,Bn.useMemo)(()=>m=>(0,Or.jsx)("a",{onClick:h=>{h.preventDefault(),o()},href:t,className:a.anchor,target:"_blank",rel:"noreferrer",children:m},"login"),[t]),d=(0,Bn.useCallback)(m=>(0,Or.jsx)("button",{type:"button",className:a.anchorButton,onClick:c,children:m},"prompt"),[c]),{min:f,hour:y,day:v}=(0,Bn.useMemo)(()=>({min:dh(a,60*10,u),hour:dh(a,60*60,u),day:dh(a,60*60*12,u)}),[]);return(0,Or.jsxs)("div",{className:(0,aC.default)(e,a.root),children:[i("loginPlease",{login:n?d:p,productName:l}),r&&(0,Or.jsxs)(Bn.Fragment,{children:[(0,Or.jsx)("br",{}),i("snooze",{min:f,hour:y,day:v})]})]})},vd=YL;var lC={root:"_root_1g8fi_1",text:"_text_1g8fi_19"};var Wa=S(C()),ZL=({title:e})=>{let t=k("SearchTrigger",lC),n=U();return(0,Wa.jsxs)("button",{type:"button",className:t.root,onClick:()=>n(qe(!0)),children:[(0,Wa.jsx)(Ai,{}),(0,Wa.jsx)("span",{className:t.text,children:e})]})},uC=ZL;var ph={};Ee(ph,{enUS:()=>JL,nlNL:()=>eA});var JL={arrowHint:[{type:0,value:"Tip: use arrow keys to navigate suggestions"}],searchHintWindows:[{type:0,value:"Press CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],searchHintMac:[{type:0,value:"Press CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Close"}],search:[{type:0,value:"Search"}]},eA={arrowHint:[{type:0,value:"Tip: Selecteer suggesties met pijltoetsen"}],searchHintWindows:[{type:0,value:"Druk CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],searchHintMac:[{type:0,value:"Druk CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Sluiten"}],search:[{type:0,value:"Zoeken"}]};var cC={root:"_root_onpov_1",isInline:"_isInline_onpov_14",toggleButton:"_toggleButton_onpov_21",toggleButtonWrapper:"_toggleButtonWrapper_onpov_25",toggleButtonWrapperHidden:"_toggleButtonWrapperHidden_onpov_32",isCollapsed:"_isCollapsed_onpov_36",collapsible:"_collapsible_onpov_36",hints:"_hints_onpov_44",hintsHidden:"_hintsHidden_onpov_51",triggers:"_triggers_onpov_56",triggersRight:"_triggersRight_onpov_71"};var pe=S(C()),tA=({textSuggestions:e,selectedIndex:t,onLogIn:n})=>{let r=k("SuggestionsOverlay",cC),o=H(ph),i=R(Bi),s=o_(),a=U(),l=(0,Ui.useRef)(null),u=M("searchTriggerKey"),c=M("productName"),p=R(cd),d=R(Xe),f=R(_i),[y,v]=(0,Ui.useState)(null),m=M("showSearch"),g=M("showTextSuggestions"),h=M("adminUrl"),x=M("isEmbedded"),[_,w]=iC("dd-snooze-until-ms",0),b=p||_>Date.now(),E=R(N=>N.input.text),P=e.filter(N=>N.source!=="gpt").length,I=()=>{b&&w(0),a(Kw(!b))},z=N=>{a(ze({name:"suggestion feedback",data:{text:N.text,source:"overlay",context:E},options:{includeConversationData:!0}}))},V=N=>{let le=Date.now()+N*1e3;w(le),j.info(`Snooze until: ${new Date(le)}`),a(Rr({collapse:!0}))};return(0,Ui.useEffect)(()=>{P===0&&v(null)},[e,P]),Pi(()=>{a(Rr({collapse:!0,skipWhenInputFocus:!0}))}),d===null||f===!1?null:d===!1?(0,pe.jsxs)("div",{ref:l,className:(0,Sd.default)(r.root,{[r.isCollapsed]:b}),children:[!b&&(0,pe.jsxs)("div",{className:r.triggers,children:[(0,pe.jsx)("div",{style:{flex:1}}),(0,pe.jsx)("div",{className:r.triggersRight,children:(0,pe.jsx)(zr,{className:r.toggleButton,title:o("collapse"),onClick:I,isCollapsed:!1})})]}),(0,pe.jsx)("div",{className:r.toggleButtonWrapper,children:(0,pe.jsx)(zr,{className:r.toggleButton,title:o("open",{productName:c}),onClick:I,isCollapsed:!0})}),(0,pe.jsx)("div",{className:r.collapsible,children:(0,pe.jsx)(vd,{loginUrl:h,isEmbedded:x,onLogIn:n,onSnooze:V})})]}):!s||!i?null:(0,pe.jsxs)("div",{ref:l,className:(0,Sd.default)(r.root,{[r.isCollapsed]:b}),children:[!b&&(0,pe.jsxs)("div",{className:r.triggers,children:[(0,pe.jsx)("div",{style:{flex:1},children:m&&(0,pe.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>v(o(id()?"searchHintMac":"searchHintWindows",{searchTriggerKey:u.toUpperCase()})),onMouseLeave:()=>v(null),children:(0,pe.jsx)(uC,{title:o("search")})})}),(0,pe.jsxs)("div",{className:r.triggersRight,onFocus:()=>{},children:[(0,pe.jsx)("div",{className:(0,Sd.default)(!y&&r.hintsHidden,r.hints),children:y}),(0,pe.jsx)(zr,{className:r.toggleButton,title:o("collapse"),onClick:I,isCollapsed:!1})]})]}),(0,pe.jsx)("div",{className:r.toggleButtonWrapper,children:(0,pe.jsx)(zr,{className:r.toggleButton,title:o("open",{productName:c}),onClick:I,isCollapsed:!0})}),P>0&&g&&(0,pe.jsx)("div",{className:r.collapsible,onFocus:()=>{},children:(0,pe.jsx)(ut,{children:(0,pe.jsx)(hd,{onFeedback:z,suggestions:e,selectedIndex:t,reverse:!0})})})]})},nA=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),dC=Cn(nA)(tA);var Ad=S(q());var Kn=S(O());var pC=S(O()),rA=["div","span","mark","strong","b","i","u","em"];function fh(e,t,n=0){var i;let r=e[e.length-1],o=typeof r=="object"&&r!==null?(i=r.props)==null?void 0:i.tagName:void 0;if(o==="br")return e.pop(),[...e,...t,r];if(rA.includes(o)){let s=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,pC.cloneElement)(r,{children:fh(s,t,n+1)})]}return[...e,...t]}function Nr(e){return e.tagName.toLowerCase()==="textarea"}var fC={root:"_root_81non_1",container:"_container_81non_3",agentText:"_agentText_81non_5",tabText:"_tabText_81non_6",hint:"_hint_81non_6",matchSelection:"_matchSelection_81non_10",focus:"_focus_81non_16",resetIndent:"_resetIndent_81non_20",matchKeyword:"_matchKeyword_81non_24",matchPlaceholder:"_matchPlaceholder_81non_25",hover:"_hover_81non_31",hintText:"_hintText_81non_64",popover:"_popover_81non_72",popoverRoot:"_popoverRoot_81non_77",popoverContentContainer:"_popoverContentContainer_81non_81",popoverContent:"_popoverContent_81non_81",selectionOptions:"_selectionOptions_81non_107",selectionOptionsIsHidden:"_selectionOptionsIsHidden_81non_112",selectionOptionsButton:"_selectionOptionsButton_81non_116",caret:"_caret_81non_132",popoverSuggestionsRoot:"_popoverSuggestionsRoot_81non_136",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_81non_141"};var wC=S(q());var Pd=S(O());function mC(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function xd(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function gC(e){return e!=null}var gh=S(q()),Ot=S(O());var _d=S(O()),oA=["bottom","height","left","right","top","width"],iA=(e={},t={})=>oA.some(n=>e[n]!==t[n]),zn=new Map,hC,yC=()=>{let e=[],t=[];zn.forEach((n,r)=>{if(r instanceof Element&&!r.isConnected){t.push(r);return}let o=r.getBoundingClientRect();iA(o,n.rect)&&(n.rect=o,e.push(n))}),t.forEach(n=>{zn.delete(n)}),e.forEach(n=>{n.callbacks.forEach(r=>r(n.rect))}),hC=window.requestAnimationFrame(yC)};function sA(e,t){return{observe(){let n=zn.size===0;if(zn.has(e)){let r=zn.get(e);r.callbacks.push(t),r.rect&&t(r.rect)}else zn.set(e,{rect:void 0,hasRectChanged:!1,callbacks:[t]});n&&yC()},unobserve(){let n=zn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||zn.delete(e),zn.size||cancelAnimationFrame(hC)}}}}function mh(e){let[t,n]=(0,_d.useState)(null);return(0,_d.useLayoutEffect)(()=>{if(!e.current)return;let r=sA(e.current,o=>{n(o)});return r.observe(),()=>{r.unobserve()}},[e]),t}var Ki=S(O()),SC=S(Pu());var vC={root:"_root_1jq08_1"};var xC=({children:e})=>{let[t,n]=(0,Ki.useState)(null),r=(0,Ki.useContext)(Ji);return(0,Ki.useLayoutEffect)(()=>{let o=document.createElement("div");return uo(o),o.classList.add(vC.root),r!=null&&r.portalRootNode&&o.classList.add(r==null?void 0:r.portalRootNode),document.body.appendChild(o),n(o),()=>{o.isConnected&&document.body.removeChild(o)}},[]),t?(0,SC.createPortal)(e,t):null};var cn={ref:"_ref_1rcyi_1",root:"_root_1rcyi_7",positionAbove:"_positionAbove_1rcyi_13",positionBelow:"_positionBelow_1rcyi_17",positionLeft:"_positionLeft_1rcyi_21",positionRight:"_positionRight_1rcyi_25",alignStart:"_alignStart_1rcyi_29",alignCenter:"_alignCenter_1rcyi_34",alignEnd:"_alignEnd_1rcyi_40"};var wd=S(C()),Cd=(e=!1)=>{let[t,n]=(0,Ot.useState)(e),r=(0,Ot.useCallback)(()=>n(!0),[]),o=(0,Ot.useCallback)(()=>n(!1),[]),i=(0,Ot.useCallback)(()=>n(a=>!a),[]),s=(0,Ot.useRef)(null);return{opened:t,open:r,close:o,toggle:i,triggerRef:s}};function hh(e,t=null,n=0){if(!e)return{display:"none"};let r=t?e.top-t.top<0||e.top<t.top-n?t.top-n:e.top+e.height>t.top+t.height+n?t.top+t.height+n-e.height:e.top:e.top,o=t?e.left<t.left-n?t.left-n:e.left+e.width>t.left+t.width+n?t.left+t.width+n-e.width:e.left:e.left;return{top:r,left:o,height:e.height,width:e.width}}var bd=({className:e,triggerRef:t,boundaryRef:n=(0,Ot.createRef)(),position:r="above",align:o="center",children:i,toStyle:s=hh,...a})=>{let l=mh(t),u=mh(n),c=(0,Ot.useMemo)(()=>s(l,u,0),[l,u]);return(0,wd.jsx)(xC,{children:(0,wd.jsx)("div",{className:(0,gh.default)(cn.ref,{[cn.positionAbove]:r==="above",[cn.positionBelow]:r==="below",[cn.positionLeft]:r==="left",[cn.positionRight]:r==="right",[cn.alignStart]:o==="start",[cn.alignCenter]:o==="center",[cn.alignEnd]:o==="end"}),style:c,...a,role:"dialog",children:(0,wd.jsx)("div",{className:(0,gh.default)(e,cn.root),children:i})})})};var _C=S(q()),Ed=S(O());var yh=S(C()),Td=(0,Ed.forwardRef)(({className:e,children:t,...n},r)=>{let o=(0,Ed.useRef)(null),i=k("TabCompletion",In);return(0,yh.jsx)("div",{ref:xd([o,r]),className:(0,_C.default)(e,i.popoverContentContainer),...n,children:(0,yh.jsx)("div",{className:i.popoverContent,children:t})})});var Mr=S(C()),aA=e=>t=>{let n=hh(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},lA=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let i=k("TabCompletion",In),s=Cd(),a=(0,Pd.useMemo)(()=>aA(e.getBoundingClientRect()),[e]),[l,u]=$c(e);return(0,Pd.useEffect)(()=>{u?s.open():s.close()},[u]),(0,Mr.jsxs)("span",{children:[(0,Mr.jsx)("mark",{ref:xd([l,s.triggerRef]),className:(0,wC.default)(i.matchKeyword,{[i.hover]:u}),"aria-haspopup":"dialog","aria-expanded":s.opened?"true":"false",children:r}),s.opened&&(0,Mr.jsx)(bd,{className:i.popover,triggerRef:s.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,Mr.jsx)(Td,{style:n,children:(0,Mr.jsx)("div",{className:i.hintText,children:o})})})]})},kd=class extends Tn{keywordMatches=[];preparedKeywordMatches=[];usedKeywordMatches=new Set;onBeforeParse(t,n){return n.keywordMatches&&n.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=n.keywordMatches.map(r=>({...r,keywordRegex:new RegExp(`\\b${mC(r.keyword)}\\b`,"i")})),this.keywordMatches=n.keywordMatches),this.usedKeywordMatches.clear(),t}match(t){let n=this.preparedKeywordMatches.map(o=>{if(this.usedKeywordMatches.has(o))return null;let i=t.match(o.keywordRegex);if(!i)return null;let s=t.charAt(i.index-1),a=t.charAt(i.index+o.keyword.length);return s==="{"&&a==="}"?null:{index:i.index,length:i[0].length,match:i[0],matchString:i[0],suggestion:o.suggestion,preparedKeywordMatch:o,valid:!0}}).filter(gC);if(n.length===0)return null;let r=n.reduce((o,i)=>i.index<o.index?i:o);return this.usedKeywordMatches.add(r.preparedKeywordMatch),r}replaceWith(t,n){return(0,Mr.jsx)(lA,{inputElement:n.inputElement,suggestion:n.suggestion,inputStyle:n.inputStyle,boundaryRef:n.boundaryRef,children:t},`keyword_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var Rd=S(q());var Ze=S(O());var vh=S(C()),CC=()=>(0,vh.jsx)("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:(0,vh.jsx)("path",{fill:"currentColor",d:"M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"})});var Dr=S(O());var EC=S(nh());var bC={root:"_root_1muu8_1",content:"_content_1muu8_7"};function Id(e,t,n){var o;let r=((o=e.imageSizes)==null?void 0:o[t])||e.image||n;if(!r)return null;try{return new URL(r).toString()}catch{return null}}function Sh(e){return e.replace("https://www.","").replace("https://","")}var Nt=S(C()),uA=3,cA=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),dA=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=uA})=>{let i=k("LinkSearch",bC),[s,a]=(0,Dr.useState)(""),l=U(),u=R(ld("url")),c=R(Sw("URL",cA)),[p,d]=(0,Dr.useState)(c.length-1),f=M("fallbackImage"),y=h=>{let x=h.target;a(x.value)},v=(h,x)=>{h.stopPropagation(),h.preventDefault(),window.open(x,"_blank")},m=h=>{var w;let x=p-1<0?c.length-1:p-1,_=p+1===c.length?0:p+1;h.code==="Escape"&&(a(""),t()),h.code==="ArrowUp"&&d(x),h.code==="ArrowDown"&&d(_),h.code==="Enter"&&e(((w=c[p])==null?void 0:w.text)||s)},g=(0,Dr.useCallback)((0,EC.default)(h=>{l(yo({query:h,type:"URL",tags:["link-search"]}))},300),[]);return(0,Dr.useEffect)(()=>{s&&g(s)},[s]),(0,Dr.useEffect)(()=>()=>{l(rd())},[]),(0,Nt.jsxs)("div",{className:i.root,children:[(0,Nt.jsx)(ut,{withDivider:!0,children:(s?c:u).slice(0,o).map((h,x)=>(0,Nt.jsx)(Q,{selected:p===x,onClick:()=>e(h.text),"data-testid":"linksearch-suggestion",children:(0,Nt.jsxs)(oe,{children:[(0,Nt.jsx)(oe.Image,{src:Id(h,"small",f||void 0),title:h.title||h.text}),(0,Nt.jsxs)(oe.Content,{className:i.content,cropText:!0,children:[(0,Nt.jsx)(oe.Title,{children:h.title||Sh(h.text)}),h.title&&Sh(h.text)]}),(0,Nt.jsx)(Q.Actions,{children:(0,Nt.jsx)(Q.ActionButton,{label:r,onClick:_=>v(_,h.text)})})]})},h.text))}),(0,Nt.jsx)(Ma,{value:s,onChange:y,autoFocus:!0,placeholder:n,onKeyUp:m})]})},TC=dA;var xh={};Ee(xh,{enUS:()=>pA,nlNL:()=>fA});var pA={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},fA={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var Ye=S(C()),mA=(0,Ze.forwardRef)((e,t)=>{let n=k("TabCompletion",In);return(0,Ye.jsx)("mark",{ref:t,className:(0,Rd.default)(n.matchSelection)},"selection-start")}),gA=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let i=H(xh),s=k("TabCompletion",In),a=(0,Ze.useRef)(null),l=(0,Ze.useRef)(null),[u,c]=(0,Ze.useState)(null),p=U(),d=Cd(document.activeElement===r),[f]=(0,Ze.useState)(()=>document.createRange());d.triggerRef.current=f,(0,Ze.useEffect)(()=>()=>f.detach(),[]),(0,Ze.useEffect)(()=>{let v=e.current,m=a.current;!v||!m||(f.setStart(v,0),f.setEnd(m,0))},[e.current,a.current]),Pi(()=>{d.close()});let y=(0,Ze.useCallback)(v=>{let m=f.toString(),g=/^http(s?):\/\//.test(v)?v:`https://${v}`;p(Sc({text:`[${m}](${g})`,replace:"selection"}))},[]);return(0,Ye.jsxs)("span",{children:[(0,Ye.jsx)("mark",{ref:a,className:(0,Rd.default)(s.matchSelection),"aria-haspopup":"dialog","aria-expanded":d.opened?"true":"false",children:o}),d.opened&&(0,Ye.jsx)(bd,{className:s.popoverRoot,triggerRef:d.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,Ye.jsxs)(Td,{style:n,ref:l,children:[(0,Ye.jsx)("div",{className:(0,Rd.default)(s.selectionOptions,{[s.selectionOptionsIsHidden]:u!==null}),children:(0,Ye.jsxs)("button",{type:"button",tabIndex:u===null?-1:void 0,className:s.selectionOptionsButton,onClick:()=>c("insertLink"),children:[(0,Ye.jsx)(CC,{}),(0,Ye.jsx)("span",{children:"\xA0"}),(0,Ye.jsx)("span",{children:i("insertLink")})]})}),u==="insertLink"&&(0,Ye.jsx)(TC,{placeholder:i("linkInputPlaceholder"),visitUrlText:i("visitUrl"),onSelectLink:y,onDismiss:()=>{c(null),d.close()}})]})})]},"selection-end")},Ld=class extends Tn{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(t,n){return this.props=n,this.charCount=0,this.startRef=(0,Ze.createRef)(),this.foundIndex=0,t}match(t){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[n,r]=this.props.selection;if(n===r)return null;let o=this.foundIndex===0?n:r,i=o>=this.charCount&&o<=this.charCount+t.length?{index:o-this.charCount,length:0,match:"",valid:!0}:null;i&&this.foundIndex++;let s=this.foundIndex===1;return i&&s?this.charCount+=o-this.charCount:this.charCount+=t.length,i?{isStart:s,...i}:null}replaceWith(t,n){return n.isStart?(0,Ye.jsx)(mA,{ref:this.startRef}):(0,Ye.jsx)(gA,{inputElement:n.inputElement,startRef:this.startRef,boundaryRef:n.boundaryRef,inputStyle:n.inputStyle})}asTag(){return"mark"}};var Un=S(C()),hA=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:i,keywordMatches:s,inputElement:a,source:l})=>{let u=k("TabCompletion",fC),c=M("insertLink"),p=M("showMidSentenceSuggestions"),d=M("inlineSuggestions"),f=Gc(a),y=(0,Kn.useRef)(null),v=R(Xe);(0,Kn.useEffect)(()=>{Nr(a)&&f&&Xc(a,f)},[f]);let m=(0,Kn.useCallback)(x=>{if(!o||!n)return x;let _=[(0,Un.jsx)("span",{className:u.resetIndent,children:"\u200B"},"u200B"),(0,Un.jsx)("span",{"data-testid":"tab-completion",className:(0,Ad.default)(u.tabText,u.resetIndent),"data-source":l,children:n},"tabText")];return r&&_.push((0,Un.jsx)("span",{className:(0,Ad.default)(u.hint,u.resetIndent),children:(0,Un.jsx)(pl,{keyCode:"tab"},"tabHint")})),fh(x,_)},[o,n,r]),g=(0,Kn.useMemo)(()=>{let x=[];return c&&x.push(new Ld("selection")),x.push(new Ti("placeholders")),i&&x.push(new kd("keywords")),x},[d,c,i]),h=(0,Kn.useMemo)(()=>{let x=window.getComputedStyle(a);return{"--dd-color":x.color,"--dd-font-size":x.fontSize,"--dd-font-family":x.fontFamily,"--dd-font-variant":x.fontVariant}},[]);return!e||!v?null:(0,Un.jsxs)("div",{ref:x=>{x!=null&&x.parentElement&&(y.current=x==null?void 0:x.parentElement)},className:u.root,style:h,children:[(0,Un.jsx)(Pn,{tagName:"span",containerTagName:"div",className:(0,Ad.default)(u.container,u.agentText),disableLineBreaks:Nr(a),content:t||"\u200B",onAfterParse:m,matchers:g,selection:f,keywordMatches:s,inputElement:a,inputStyle:h,boundaryRef:y,inlineSuggestionsOnlyAtEnd:!p}),(0,Un.jsx)("br",{})]})},yA=({input:e,ui:t,settings:n,styleSuggestions:r,conversation:o})=>{var v;let{tabCompletionSuggestion:i}=e,s=(i==null?void 0:i.text)||"",a=(i==null?void 0:i.source)||"",l=e.html??Ri(e.text),u=s.indexOf(e.text)===0?s.slice(e.text.length):"",{showTabHint:c}=t,{isSupported:p}=o,{showTabCompletion:d,visible:f,showStyleSuggestions:y}=n;return{showTabHint:c,showStyleSuggestions:y,showTabCompletion:d,content:l,tabText:u,source:a,keywordMatches:((v=r.list)==null?void 0:v.keywordMatches)??[],enabled:f&&p!==!1}},kC=Cn(yA)(hA);var yb=S(q()),vb=S(O());var PC={list:[],fetchState:"idle",isInitialRequest:null},RC=e=>e.autoflows.list||[],IC=e=>t=>{var n;return(n=t.list)==null?void 0:n.find(r=>r.triggerPayload===e)},Vn=D("autoflows/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getAutoflows(e)}),_h=D("autoflows/start",async(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");await r.startAutoflowSession(e),await n(Vn(e.platformSessionId))}),wh=D("autoflows/stop",async(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");await r.stopAutoflowSession(e.platformSessionId),await n(Vn(e.platformSessionId))}),vA=B({name:"autoflows",initialState:PC,reducers:{},extraReducers:e=>{e.addCase(_h.pending,(t,n)=>{let r=IC(n.meta.arg.triggerPayload)(t);r.state="Started",r.isBusy=!0}),e.addCase(wh.pending,(t,n)=>{let r=IC(n.meta.arg.triggerPayload)(t);r.state="Aborted",r.isBusy=!0}),e.addCase(Vn.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}),e.addCase(Vn.rejected,t=>{t.fetchState="error"}),e.addCase(Vn.fulfilled,(t,n)=>{t.list=n.payload,t.fetchState="done"}),e.addCase(J,()=>PC)}}),LC=D("autoflows/openStream",(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");let o=r.openStream(e);o.on("sessionAborted",()=>{n(Vn(e))}),o.on("sessionCompleted",()=>{n(Vn(e))})}),AC=D("autoflows/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),OC=vA.reducer;var NC={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},MC=e=>e.customMessages.list,DC=e=>t=>!!t.customMessages.sentSuggestions.find(n=>n===e),FC=e=>t=>!!t.customMessages.answeredSuggestions.find(n=>n===e),jC=e=>t=>!!t.customMessages.errorSuggestions.find(n=>n===e),$a=D("customMessages/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getCustomMessages(e)}),Od=D("customMessages/send",async(e,t)=>{let{platformSessionId:n,suggestion:r}=e,{deepdeskBrokerAPI:o}=t.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.sendCustomMessage(n,r)}),Nd=D("customMessages/answer",async(e,t)=>{let{platformSessionId:n,reply:r}=e,{deepdeskBrokerAPI:o}=t.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.answerCustomMessage(n,r)}),HC=B({name:"customMessages",initialState:NC,reducers:{onCustomMessage(e,t){Array.isArray(t.payload)?e.list=t.payload:e.list=[t.payload]}},extraReducers:e=>{e.addCase($a.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase($a.rejected,t=>{t.fetchState="error"}).addCase($a.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload||[]}).addCase(Od.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.errorSuggestions=t.errorSuggestions.filter(r=>n.meta.arg.suggestion.text!==r)}).addCase(Od.rejected,(t,n)=>{let r=t.sentSuggestions.indexOf(n.meta.arg.suggestion.text);t.errorSuggestions.push(...t.sentSuggestions.splice(r,1))}).addCase(Nd.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.answeredSuggestions.push(n.meta.arg.suggestion.text)}).addCase(Nd.rejected,(t,n)=>{let r=t.answeredSuggestions.indexOf(n.meta.arg.suggestion.text);t.errorSuggestions.push(...t.sentSuggestions.splice(r,1)),t.answeredSuggestions.splice(r,1)}).addCase(J,()=>NC)}}),BC=D("customMessages/openStream",(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");r.openStream(e).on("customMessageSuggestion",i=>{n(HC.actions.onCustomMessage(i))})}),zC=D("customMessages/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),UC=HC.reducer;var SA={token:null,accountUrl:null,interval:null},KC=e=>t=>{let{passwordlessToken:{token:n,accountUrl:r}}=t;return n&&r?`${r}/apis/admin/session/passwordless/login/?token=${n}&redirect=${e}`:null},Ch=D("passwordlessToken/getTemporaryPasswordlessToken",async(e,t)=>{let{deepdeskAPI:n}=t.extra,r=await n.requestPasswordlessToken();return{accountUrl:n.client.baseUrl,token:r}}),bh=D("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(Ch()),setInterval(()=>r(Ch()),n)}),VC=B({name:"passwordlessToken",initialState:SA,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(Ch.fulfilled,(t,n)=>{t.token=n.payload.token,t.accountUrl=n.payload.accountUrl}),e.addCase(bh.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:WC}=VC.actions,$C=VC.reducer;function qC(e){let{customMessages:t,autoflows:n}=e;return n.fetchState==="loading"&&n.isInitialRequest===!0||t.fetchState==="loading"&&t.isInitialRequest===!0}var nb=S(O());var JC=S(q()),eb=S(O());var XC=S(q());var GC={root:"_root_838fd_1"};var YC=S(C()),xA=({className:e,children:t})=>{let n=k("Unicode",GC);return(0,YC.jsx)("span",{className:(0,XC.default)(e,n.root),children:t})},QC=xA;var ZC={isDisabled:"_isDisabled_1rmfm_1",buttonStart:"_buttonStart_1rmfm_5",root:"_root_1rmfm_8",buttonStop:"_buttonStop_1rmfm_8",stateBadge:"_stateBadge_1rmfm_19",isCompleted:"_isCompleted_1rmfm_26",isStarted:"_isStarted_1rmfm_30",isAborted:"_isAborted_1rmfm_34"};var Eh={};Ee(Eh,{enUS:()=>_A,nlNL:()=>wA});var _A={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]},wA={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]};var ht=S(C()),bA=({disabled:e,state:t,displayName:n,description:r,onStartAutoflow:o,onStopAutoflow:i})=>{let s=k("Autoflow",ZC),a=H(Eh),l=t==="Started"?"stop":"start",u=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return(0,ht.jsxs)(Q,{className:(0,JC.default)(s.root,{[s.isDisabled]:e,[s.isCompleted]:t==="Completed",[s.isAborted]:t==="Aborted",[s.isStarted]:t==="Started"}),children:[(0,ht.jsx)(oe,{children:(0,ht.jsxs)(oe.Content,{children:[(0,ht.jsxs)(oe.Title,{children:[t&&(0,ht.jsx)("span",{className:s.stateBadge,children:a(t)}),n]}),(0,ht.jsx)("span",{children:r})]})}),(0,ht.jsx)(Q.Actions,{fixed:t==="Started",children:(0,ht.jsx)(Q.ActionButton,{primary:!0,className:l==="start"?s.buttonStart:s.buttonStop,onClick:t==="Started"?i:o,disabled:e,label:(0,ht.jsxs)(eb.Fragment,{children:[(0,ht.jsx)(QC,{children:u})," ",(0,ht.jsx)("span",{children:a(l)})]})})})]})},tb=bA;var Th=S(C()),EA=(e,t)=>{let n=t.filter(r=>r.state==="Started");return n.length>0?n.indexOf(e)===-1:!1},TA=({autoflows:e,onStartAutoflow:t,onStopAutoflow:n,platformSessionId:r})=>(0,Th.jsx)(nb.Fragment,{children:e.map(o=>(0,Th.jsx)(tb,{displayName:o.displayName,description:o.description,disabled:o.isBusy||EA(o,e),state:o.state,onStartAutoflow:()=>t({platformSessionId:r,triggerPayload:o.triggerPayload}),onStopAutoflow:()=>n({platformSessionId:r,triggerPayload:o.triggerPayload})},o.displayName))}),kA=({autoflows:e,conversation:t})=>{var n;return{autoflows:e.list,platformSessionId:(n=t.current)==null?void 0:n.sessionId}},PA={onStartAutoflow:_h,onStopAutoflow:wh},rb=Cn(kA,PA)(TA);var ob=S(q()),kh=S(O());var Wn={root:"_root_1e6ej_1",title:"_title_1e6ej_8",isUsed:"_isUsed_1e6ej_13",quickReplies:"_quickReplies_1e6ej_22",quickReply:"_quickReply_1e6ej_29",hasError:"_hasError_1e6ej_39",label:"_label_1e6ej_43",errorIcon:"_errorIcon_1e6ej_48"};var at=S(C()),IA=({suggestion:e})=>{let t=H(go),n=U(),r=R(DC(e.text)),o=R(FC(e.text)),i=R(jC(e.text)),s=R(dc),{replyOptions:a}=e,l=(0,kh.useCallback)(c=>{c.preventDefault(),c.stopPropagation(),!(r||!s)&&n(Od({platformSessionId:s,suggestion:e}))},[e,r,n,s]),u=(0,kh.useCallback)(c=>{if(c.preventDefault(),c.stopPropagation(),!s||!a)return;let p=parseInt(c.target.dataset.index,10),d=a[p];n(Nd({platformSessionId:s,reply:d,suggestion:e}))},[e,r,n,s]);return(0,at.jsxs)(Q,{onClick:l,className:(0,ob.default)(Wn.root,{[Wn.isUsed]:r,[Wn.hasError]:i}),children:[(0,at.jsx)(oe,{children:(0,at.jsxs)(oe.Content,{children:[(0,at.jsxs)(oe.Title,{className:Wn.title,children:[e.text," ",(0,at.jsx)(fl,{className:Wn.label,children:"analyse tool"})," ",i&&(0,at.jsx)("span",{className:Wn.errorIcon,role:"img","aria-label":t("sendingError"),title:t("sendingError"),children:"!"})]}),a&&a.length>0&&(0,at.jsx)("ul",{className:Wn.quickReplies,children:a.map(c=>(0,at.jsx)("li",{className:Wn.quickReply,children:c.title},c.title))})]})}),(0,at.jsxs)(Q.Actions,{fixed:i||r,children:[a&&a.length>0&&(0,at.jsx)(Q.DropdownButton,{label:t("answer"),disabled:o,children:a.map((c,p)=>(0,at.jsx)(Q.DropdownItem,{index:p,label:c.title,onClick:u},c.title))}),(0,at.jsx)(Q.ActionButton,{primary:!0,disabled:r,onClick:l,label:t(r?"suggestionSent":i?"tryAgain":"sendSuggestion")})]})]})},ib=IA;var Md=S(O());var Rh=S(q());var Ph=S(C()),Ih=()=>(0,Ph.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,Ph.jsx)("path",{d:"M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"})});var sb={root:"_root_rjdyr_1",entity:"_entity_rjdyr_10",entityText:"_entityText_rjdyr_46",iconWrapper:"_iconWrapper_rjdyr_53",icon:"_icon_rjdyr_53",iconClicked:"_iconClicked_rjdyr_67"};var dn=S(C()),RA=({entities:e})=>{let t=k("EntitiesWidgetList",sb),[n,r]=(0,Md.useState)(void 0),o=U(),i=()=>{r(void 0)},s=a=>{e&&(r(e.indexOf(a)),Fa(a.text),o(ze({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,Md.useEffect)(()=>{let a=setTimeout(i,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,dn.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,dn.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>s(a),children:[(0,dn.jsx)("span",{className:t.entityText,children:a.text}),(0,dn.jsxs)("span",{className:t.iconWrapper,children:[(0,dn.jsx)("span",{className:(0,Rh.default)(t.icon),children:(0,dn.jsx)(Ih,{})}),(0,dn.jsx)("span",{className:(0,Rh.default)(t.icon,n===l&&t.iconClicked),children:(0,dn.jsx)(Ih,{})})]})]},a.text))})},ab=RA;var Lh=S(C()),lb=()=>(0,Lh.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,Lh.jsx)("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});var Ah=S(C()),ub=()=>(0,Ah.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Ah.jsx)("path",{d:"M543-340q16.595 0 28.798-12.202Q584-364.405 584-381t-12.202-28.798Q559.595-422 543-422t-28.798 12.202Q502-397.595 502-381t12.202 28.798Q526.405-340 543-340Zm-25-126h47q2-29 8.5-43t32.5-39q27-26 37.5-45.395Q654-612.79 654-639q0-45.882-31.5-74.941Q591-743 540-743q-38 0-68 20.5T428-665l45 19q11-25 27.5-38t39.5-13q29.778 0 48.389 17Q607-663 607-637q0 20-9 35t-32 32q-32 29-40 46.5t-8 57.5ZM260-200q-24 0-42-18t-18-42v-560q0-24 18-42t42-18h560q24 0 42 18t18 42v560q0 24-18 42t-42 18H260Zm0-60h560v-560H260v560ZM140-80q-24 0-42-18t-18-42v-620h60v620h620v60H140Zm120-740v560-560Z"})});var Oh=S(C()),cb=()=>(0,Oh.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Oh.jsx)("path",{d:"M319-250h322v-60H319v60Zm0-170h322v-60H319v60ZM220-80q-24 0-42-18t-18-42v-680q0-24 18-42t42-18h361l219 219v521q0 24-18 42t-42 18H220Zm331-554v-186H220v680h520v-494H551ZM220-820v186-186 680-680Z"})});var Dd=S(O());var Nh={};Ee(Nh,{enUS:()=>LA,nlNL:()=>AA});var LA={copyCue:[{type:0,value:"Copy"}],copiedCue:[{type:0,value:"Copied!"}],removeCue:[{type:0,value:"Close"}]},AA={copyCue:[{type:0,value:"Kopieer"}],copiedCue:[{type:0,value:"Gekopieerd!"}],removeCue:[{type:0,value:"Sluiten"}]};var $n=S(C()),OA=({cue:e,onRemove:t,onCopy:n})=>{let r=H(Nh),[o,i]=(0,Dd.useState)(!1),s=l=>{l.preventDefault(),l.stopPropagation(),n&&(n(e.text),i(!0))},a=l=>{l.preventDefault(),l.stopPropagation(),t&&t(e.id)};return(0,Dd.useEffect)(()=>{if(!o)return;let l=setTimeout(()=>{i(!1)},1e3);return()=>{clearTimeout(l)}},[o]),(0,$n.jsx)(Q,{"data-testid":"cue",children:(0,$n.jsxs)(oe,{children:[(0,$n.jsxs)(oe.Content,{children:[e.title&&(0,$n.jsx)(oe.Title,{"data-testid":"widget-cue-title",children:e.title}),e.text]}),(0,$n.jsx)(Q.Actions,{children:n&&(0,$n.jsx)(Q.ActionButton,{primary:!0,onClick:s,label:r(o?"copiedCue":"copyCue")})}),(0,$n.jsx)(oe.CloseIcon,{title:r("removeCue"),onClick:a})]})})},db=OA;var qa=S(C()),NA=({cues:e,onCopyCue:t,onRemoveCue:n})=>(0,qa.jsx)(qa.Fragment,{children:e.map(r=>(0,qa.jsx)(db,{cue:r,onRemove:n,onCopy:t},`${r.id}_${r.timestamp}`))}),pb=NA;var fb=S(O());var yt=S(C()),MA=({suggestion:e,lines:t,onEdit:n,onUse:r})=>{var d;let o=e.text||e.url||e.message,i=od(o),s=H(go),a=M("showImages"),l=M("fallbackImage"),u=f=>{f.preventDefault(),f.stopPropagation(),r(o)},c=f=>{f.preventDefault(),f.stopPropagation(),n(e)},p=(0,fb.useCallback)(f=>{window.open(i,"_blank"),f.stopPropagation(),f.preventDefault()},[i]);return(0,yt.jsxs)(Q,{onClick:u,"data-testid":"edit-suggestion",children:[(0,yt.jsxs)(oe,{children:[a&&e.image&&(0,yt.jsx)(oe.Image,{src:Id(e,"small",l||void 0),title:e.title}),(0,yt.jsxs)(oe.Content,{children:[e.title&&(0,yt.jsx)(oe.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((d=e.searchKeywords)==null?void 0:d.length)>0&&(0,yt.jsx)(Q.Labels,{labels:e.searchKeywords}),(0,yt.jsx)(oe.Content,{cropText:t==="single",lineClamp:t==="multiple",children:o})]})]}),(0,yt.jsxs)(Q.Actions,{children:[i&&(0,yt.jsx)(Q.ActionButton,{onClick:p,label:s("visitUrl")}),(0,yt.jsx)(Q.ActionButton,{primary:!0,onClick:c,label:s("preview")}),(0,yt.jsx)(Q.ActionButton,{primary:!0,onClick:u,label:s("useSuggestion")})]})]})},mb=MA;var Ga=S(C()),DA=({contentType:e,lines:t,suggestions:n})=>{let r=At(),o=R(Ir),i=a=>{r.send(Xg,{state:o,suggestion:a,contentType:e})},s=(a,l)=>{r.send(Fn,{text:a,suggestion:{...l,source:l.source,sourceText:l.text}})};return(0,Ga.jsx)(Ga.Fragment,{children:n.map(a=>(0,Ga.jsx)(mb,{suggestion:a,lines:t,onEdit:l=>i(l),onUse:l=>s(l,a)},a.text||a.url||a.message))})},gb=DA;var Mh={};Ee(Mh,{enUS:()=>FA,nlNL:()=>jA});var FA={waiting:[{type:0,value:"Loading\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"My "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Summarize"}],linkKnowledgeSearch:[{type:0,value:"Knowledge Assist"}],linkSearch:[{type:0,value:"Search"}]},jA={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"Mijn "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Gesprek samenvatten"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}]};var hb={root:"_root_x0pwe_1",loginText:"_loginText_x0pwe_7",stateText:"_stateText_x0pwe_8",sectionList:"_sectionList_x0pwe_20",shortcutList:"_shortcutList_x0pwe_24",shortcut:"_shortcut_x0pwe_24",link:"_link_x0pwe_52"};var K=S(C()),Fd=(e,t)=>{let n=R(Xe);(0,vb.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},HA=({onLogIn:e})=>{let t=H(Mh),n=U(),r=M("isEmbedded"),o=k("Widget",hb),i=M("showAutoflows"),s=M("showCustomMessages"),a=M("showSummaryCommand"),l=M("showKnowledgeSearch"),u=M("showSearch"),c=R(Ar),p=R(fd),d=R(RC),f=R(e1),y=R(pd),v=R(MC),m=R(pc),g=R(_i),h=R(Xe),x=R(dc),_=R(qC),w=R(Ir),b=At(),E=R(Rw),P=R(KC("/admin/")),I=M("adminUrl"),z=M("productName");if(Fd(()=>(n($a(x)),n(BC(x)),()=>{n(zC(x))}),[n,g,s,x]),Fd(()=>(n(Vn(x)),n(LC(x)),()=>{n(AC(x))}),[n,g,i,x]),Fd(()=>{p.forEach(({type:N})=>{n(N==="entities"?qt():Wt(N))})},[n,g,m,c]),Fd(()=>(n(bh()),()=>{n(WC())}),[n]),g===!1)return(0,K.jsx)("div",{className:o.stateText,children:(0,K.jsx)("div",{children:(0,K.jsx)("p",{children:t("notSupported")})})},"supported");if(h===!1)return(0,K.jsx)("div",{className:o.loginText,children:(0,K.jsx)("div",{children:(0,K.jsx)(vd,{isEmbedded:r,loginUrl:I,onLogIn:e})})},"login");if(!c||!x||h===null||E||_)return(0,K.jsx)("div",{className:o.stateText,children:(0,K.jsx)("div",{children:(0,K.jsx)("p",{children:t("waiting")})})},"waiting");let V=u||a||l||P;return(0,K.jsx)("div",{className:(0,yb.default)(o.root),"data-testid":"widget",children:(0,K.jsxs)(ml,{className:o.sectionList,children:[V&&(0,K.jsx)(mn,{title:t("actions"),type:"shortcuts",children:(0,K.jsxs)("div",{className:o.shortcutList,children:[u&&(0,K.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-search",onClick:()=>b.send("ShowCommandPalette",{isOpen:!0}),children:[(0,K.jsx)(Ai,{}),t("linkSearch")]}),a&&(0,K.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-summary",onClick:()=>b.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,K.jsx)(cb,{}),t("linkSummary")]}),l&&(0,K.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>b.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,K.jsx)(ub,{}),t("linkKnowledgeSearch")]}),P&&(0,K.jsxs)("a",{className:o.shortcut,target:"_blank",href:P,"data-testid":"shortcut-studio-login",rel:"noreferrer",children:[(0,K.jsx)(lb,{}),t("linkStudioLogin",{productName:z})]})]})}),s&&v.length>0&&(0,K.jsx)(mn,{type:"custom-messages","data-testid":"custom-messages",children:(0,K.jsx)(ut,{withDivider:!0,children:v.map(N=>(0,K.jsx)(ib,{suggestion:N},N.text))})}),i&&d.length>0&&(0,K.jsx)(mn,{type:"autoflows",title:t("titleAutoflows"),"data-testid":"autoflows",children:(0,K.jsx)(ut,{withDivider:!0,children:(0,K.jsx)(rb,{})})}),p.map(({type:N,title:le,amount:qi,lines:Je})=>{var Gn;switch(N){case"entities":return y&&y.length>0&&(0,K.jsx)(mn,{type:N,title:le,"data-testid":`type-${N}`,children:(0,K.jsx)(ab,{entities:y})},N);case"cues":return f&&f.length>0&&(0,K.jsx)(mn,{type:N,title:le,"data-testid":`type-${N}`,children:(0,K.jsx)(ut,{withDivider:!0,children:(0,K.jsx)(pb,{cues:f,onRemoveCue:Qt=>n(n1({id:Qt}))})})},N);default:return((Gn=w[N])==null?void 0:Gn.fetchState)==="done"&&w[N].suggestions.length>0&&(0,K.jsx)(mn,{type:N,title:le,"data-testid":`type-${N}`,children:(0,K.jsx)(ut,{withDivider:!0,children:(0,K.jsx)(gb,{lines:Je,contentType:N,suggestions:w[N].suggestions.slice(0,qi)||[]})})},N)}})]})})},Sb=HA;function Vi(e){let t=new Range;return t.selectNodeContents(e),t}function xb(e,t,n){try{return Fr(e,t,n),!0}catch{return!1}}function jd(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function Hd(e){return"tagName"in e&&e.tagName==="BR"}var Xa=/[\u200B-\u200D\uFEFF]/g;function Fr(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,i=!1;function s(l,u){let c=-1,p=/[\u200B-\u200D\uFEFF]/;if(!p.test(l))return u;for(let d=0;d<=l.length;d++)if(p.test(l[d])||c++,c===u)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let u=l.textContent,c=u.replace(Xa,""),p=o+c.length,d=t>=o&&t<=p,f=n>=o&&n<=p;if(d){let y=s(u,t-o);y===0&&!f?r.setStartBefore(l):r.setStart(l,y)}f&&(r.setEnd(l,s(u,n-o)),i=!0),o=p;break}case Node.ELEMENT_NODE:{if(Hd(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),i=!0;return}for(let c=0;c<l.childNodes.length&&(a(l.childNodes[c]),!i);c++);let u=l.lastChild;jd(l)&&u&&!jd(u)&&!Hd(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function Qa(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a,l,u=0;function c(p){let d=p===n,f=p===o;switch(p.nodeType){case Node.TEXT_NODE:{let y=p.textContent;d&&(a=u+y.substring(0,r).replace(Xa,"").length),f&&(l=u+y.substring(0,i).replace(Xa,"").length),u+=y.replace(Xa,"").length;break}case Node.ELEMENT_NODE:{let y=p.nextSibling===null;Hd(p)&&!y&&u++;for(let v=0;v<p.childNodes.length;v++){let m=d&&v===r,g=f&&v===i;if(m&&(a=u),g&&(l=u),l!==void 0||((!m||!s)&&c(p.childNodes[v]),f&&v===i-1&&(l=u),l!==void 0))break}!f&&jd(p)&&!y&&u++,f&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a??l,end:l}}function Ya(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i}=t,s=-1,a="";function l(u){let c=u===n,p=u===o;switch(c&&s++,u.nodeType){case Node.TEXT_NODE:{if(s!==0)return;let d=c?r:0,f=p?i:void 0,y=u.textContent.replace(Xa,"");d===0&&f===void 0?a+=y:a+=y.substring(d,f);break}case Node.ELEMENT_NODE:{let d=u.nextSibling===null;s===0&&Hd(u)&&!d&&(a+=`
|
|
24
24
|
`);for(let f=c?r:0;f<(p?Math.min(i,u.childNodes.length):u.childNodes.length)&&(l(u.childNodes[f]),s!==1);f++);!p&&s===0&&jd(u)&&!d&&(a+=`
|
|
25
|
-
`);break}default:break}p&&s++}return l(e),a}function _b(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Eo=class extends Rn{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),Ya(this.element,t)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let t=this.getRootNode();if(t.activeElement!==this.element)return null;let n="getSelection"in t?t.getSelection():window.getSelection();if(!n)return null;let r="getComposedRanges"in n&&t instanceof ShadowRoot?(i=n.getComposedRanges(t))==null?void 0:i[0]:n.rangeCount>0?n.getRangeAt(0):null;if(!r)return null;let o=this.element.ownerDocument.createRange();return o.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),o.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!o||!this.element.contains(o.startContainer)||!this.element.contains(o.endContainer)?null:o}getCaretPosition(){let t=this.getRange();if(!t||!t.collapsed||!("getBoundingClientRect"in t))return null;let n=t.getBoundingClientRect();return!_b(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!_b(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return Qa(this.element,t);let n=this.lastKnownSelection;if(n&&xb(this.element,n.start,n.end))return n;let r=Vi(this.element);return r.collapse(!1),Qa(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return Ya(this.element,Fr(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let t=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==t&&(t=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>n.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};function wb(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}var Dh=class{constructor(t){this.name=t;this.broadcastChannel=new BroadcastChannel(t)}broadcastChannel;disposeHandlers=[];onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Fh=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=wb(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},jh=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),j.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Fh(t,this.deepdeskUrl,{debug:!0}):new Dh(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=typeof o.data=="string"?JSON.parse(o.data):o.data;i.type==="event"&&i.channel===t&&(j.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;j.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage({...o,channel:this.sessionId})}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},Cb=jh;var Wi=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var Hh=e=>new Promise(t=>{setTimeout(t,e)});var $i=class extends Wi{name="ClientError"},Bh=class extends Wi{name="ServerError"},Xt=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,{abortLatest:l=!1,attempts:u=1,retryDelay:c=500,refreshTokenOn401:p=!0,retryOnError:d=_=>_ instanceof TypeError,retryOnResponse:f=_=>_.status>=500,version:y="v1",...v}=n,m={credentials:"include",...v,headers:{"Content-Type":"application/json",...v.headers}};n.method!==void 0&&n.method!=="GET"&&this.csrfToken&&(m.headers={...m.headers,"X-CSRFToken":this.csrfToken}),typeof y=="string"&&(m.headers={...m.headers,"X-Deepdesk-API-Version":y});let g=u,h=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&l&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let x=async()=>(g--,a(s,m).then(async _=>f(_)&&!i.isAborted&&g>0?(await Hh(c),x()):_.status===401&&p===!0&&h===!1?(h=!0,await this.refreshToken(),x()):_).catch(async _=>{if(d(_)&&!i.isAborted&&g>0)return await Hh(c),x();throw _}));x().then(_=>_.json().catch(()=>null).then(w=>{_.status>=500?o(new Bh("Server Error",w)):_.status===401?o(new $i("Unauthorized",w)):_.status===403?o(new $i("Forbidden",w)):_.status===404?o(new $i("Not Found",w)):_.status>=400&&o(new $i("Bad Request",w)),delete this.latestRequestByUrl[s],r(w)})).catch(_=>{o(_)})})}async validateToken(){let{has_valid_access_token:t}=await this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return e.refreshingToken||(e.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{e.refreshingToken=null},1e3*60)})),e.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,{method:"POST",body:JSON.stringify(n),...r})}patch(t,n,r){return this.request(t,{method:"PATCH",body:JSON.stringify(n),...r})}put(t,n,r){return this.request(t,{method:"PUT",body:JSON.stringify(n),...r})}delete(t,n){return this.request(t,{method:"DELETE",...n})}};var BA;(t=>{let e;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||={})})(BA||={});function Bd(e){return{...ee(e),tags:e.tags}}var qn=class e{constructor(t,n={}){this.options=n;this.client=new Xt(t,{fetch:n.fetch}),this.client.patchFetch(r=>async(o,i)=>{let s=await r(o,i);return this.handleDeepdeskVersionHeaders(s),s})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=await this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(e.exchangeTokenPromise||(e.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),e.exchangeTokenPromise):Promise.resolve()}async createConversation(t){await this.preflight(),j.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...Pe(t),tags:t.tags},{version:"v2"});return Bd(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null});return ee(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null});return ee(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null});return ee(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null});return ee(t)}async checkUserExists(t){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n}async getConversationBySessionId(t,n={}){await this.preflight(),j.info(`Getting conversation for session ${t}`);let{attempts:r=1,retryDelay:o=1e3}=n,i=await this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"});return j.info(`Successfully retrieved conversation ${i.id} for session ${t}`),Bd(i)}async isConversationSupported(t,n={}){j.info(`Check if conversation for session ${t} is supported`);let{attempts:r=1,retryDelay:o=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"})).has_active_profile}async updateConversation(t,n){let r=Pe(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Bd(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...Pe(o),tags:o.tags})),{version:"v2"})).map(o=>Bd(o))}async sendEvent(t,n){let{data:r,...o}=n,i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[a,l])=>({...s,[a]:l}),{});return this.client.post("/api/events",Pe({...i,...o,data:r,name:t}),{version:"v2"})}async sendEventV1(t,n){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>({...o,[i]:s}),{});return this.client.post("/api/events",{event:t,data:Pe({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){return(await this.client.post("/api/summary",{conversation:{messages:t.filter(o=>o.text&&o.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(t){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw j.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.client.post("/apis/admin/session/api-key/",Pe(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})}async getTextSuggestions(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(await this.client.post(`/api/conversations/${t}/recommend/${r}`,Pe(n),{abortLatest:!0})).map(i=>({...ee(i),text:i.text||i.url||i.message,source:r,type:r})).filter((i,s,a)=>s===a.findIndex(l=>l.text===i.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(t,n){return(await this.client.post(`/api/conversations/${t}/autocomplete`,Pe(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))}async getPinnedMessages(t){let n=await this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return ee(n).map(r=>({...r,text:r.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(t){let n=await this.client.post("/api/style-suggestions",Pe(t),{abortLatest:!0});return ee(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,Pe(t),{version:"v2"});return ee(n)}async knowledgeAssist(t,n,r,o={}){let i=await this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Pe({question:t.question,promptInstruction:t.promptInstruction,chatHistory:n.map(s=>({question:s.question,answer:s.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return ee(i)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return ee(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return ee(t.token)}async getCsrfToken(){let{token:t}=await this.client.get("/apis/admin/session/csrf/",{version:null});return t}async verifyLoginToken(t){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return ee(n)}async evaluateRule(t,n,r,o={}){let i=new URLSearchParams;o.raiseForFailingConditions&&i.set("raise_for_failing_conditions","true");let s=await this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${i.toString()}`,r,{version:"v2"});return ee(s.cues)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Ny);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&j.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var Za=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(zg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,ee(o))}catch{j.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var zA;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(zA||={});var Ja=class{constructor(t,n={}){this.apiUrl=t;this.client=new Xt(t,n)}client;streams={};logger=j;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return ee(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,Pe(n));return ee(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,Pe(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return ee(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",Pe(t));return ee(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new Za(`${this.apiUrl}/sessions/${t}/events`),this.streams[t].connect()),this.streams[t]}closeStream(t){this.streams[t]||(this.streams[t].disconnect(),delete this.streams[t])}};var bb={startTime:null,stopTime:null},Eb=B({name:"handlingTime",initialState:bb,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(J,()=>bb)}}),{handlingTimeStart:Tb,handlingTimeStop:zd,handlingTimeReset:kb}=Eb.actions,Pb=Eb.reducer;var Ib=(e={})=>{let t={onAuthError:Mi(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Ud={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var To=D("styleSuggestions/getAll",async({text:e},t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),{showStyleSuggestions:o}=r.settings,i=(s=r.conversation.current)==null?void 0:s.profileCode;if(!o)return Ud.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),UA=B({name:"styleSuggestions",initialState:Ud,reducers:{},extraReducers:e=>{e.addCase(To.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(To.rejected,t=>{t.fetchState="error"}).addCase(To.fulfilled,(t,n)=>{t.fetchState="done",wr(t.list,n.payload)||(t.list=n.payload)}).addCase(oo,t=>{t.list=Ud.list}).addCase(J,()=>Ud)}}),Rb=UA.reducer;var Lb=(e={})=>{let t,n=!0,r={getStyleSuggestions:To,debounce:500,...e};return o=>i=>s=>{var f;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((f=u.conversation.current)==null?void 0:f.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function KA(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var Ab=(e={})=>{let t={getTextSuggestions:Wt,getAutocompleteSuggestions:Ra,debounce:200,check:Bi,...e},n;return r=>o=>i=>{var v;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,p=(v=l.conversation.current)==null?void 0:v.id,d=i.type===ud.toString();if(!p||!u&&!c)return a;let{input:{userCommitted:f}}=l;return KA(f,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let m=wi(l);m===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(m))},d?0:t.debounce)),a}};var Ob=To.fulfilled.toString();function VA(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var Nb=e=>t=>n=>r=>{var u;if(r.type!==Ob){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=VA(o,s);r.type===Ob&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var WA=Mu({activeSuggestion:Bw,answer:D1,auth:Jw,autoflows:OC,conversation:n_,contentTypes:v1,customMessages:UC,passwordlessToken:$C,entities:w1,knowledgeAssistant:O1,handlingTime:Pb,info:mw,input:ig.reducer,overlayInput:ot.reducer,settings:qx,profile:H1,search:_w,summary:P1,styleSuggestions:Rb,ui:Vw,rules:r1,textSuggestions:Mw});function Mb(e){return J0({reducer:WA,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),Ib(),Ab({debounce:200}),Lb({debounce:500}),Nb(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var $A=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},qA=e=>t=>n=>r=>{var a;let o=t.getState(),i=Jm("inlineSuggestions")(o);switch(r.type){case Nn.toString():{let l=ld(r.payload.contentType)(t.getState()),u=l.indexOf(r.payload.suggestion);e.emit("edit-suggestion",{contentType:r.payload.contentType,index:u,suggestions:l});break}case Mi.toString():{!r.payload&&e.emit("logout",void 0);break}case zt.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",{type:$A(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case Sc.toString():{let{start:l,end:u}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case fa.toString():{let l=t.getState(),{text:u,selection:c}=l.input.userCommitted;e.emit("reset",{text:u,selectionAfter:c},{mayApplyChanges:!0});break}case Cc.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:o.conversation.current.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case qt.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:o.conversation.current.id,data:{entities:r.payload}});break;case jn.fulfilled.toString():e.sendEvent("conversation summarized",{conversationId:o.conversation.current.id,data:{summary:r.payload.summary}});break;case ze.toString():e.sendEvent(r.payload.name,{conversationId:((a=r.payload.options)==null?void 0:a.includeConversationData)&&o.conversation.current.id,data:r.payload.data});break;case xc.toString():e.handleKeyDown(r.payload);break;case oo.toString():e.logSendMessage(r.payload);break;case _c.toString():e.logSendEditSuggestionMessage(r.payload);break;case wc.toString():e.handleInputChanged(r.payload);break;case Dn.fulfilled.toString():e.broadcast(Qg,r.payload,!1),e.emit("cues",r.payload);break;default:break}let s=n(r);switch(r.type){case oo.toString():e.handleAfterSendMessage(r.payload);break;case La.toString():e.onUpdateShowTabHint(r.payload);break;case zd.toString():e.logHandlingTime();break;case zt.toString():{i&&(t.dispatch(an([])),t.dispatch(En()));break}case an.toString():{i&&r.payload.length>0&&t.dispatch(br(0));break}default:break}return s},Db=qA;function zh(e){return e.toISOString().replace("T"," ").replace("Z","")}function Fb(e,t){var o,i,s;let{startTime:n,stopTime:r}=e.handlingTime;if(!n||!r)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:e.conversation.current.id,clientVersion:t.version,agentId:(o=e.info.agentInfo)==null?void 0:o.agentId,agentName:(i=e.info.agentInfo)==null?void 0:i.agentName,agentEmail:(s=e.info.agentInfo)==null?void 0:s.agentEmail,timeStart:zh(n),timeStop:zh(r)}}function Uh(e,t,n){var E,P,I;let{text:r,metrics:{numCharsTyped:o,numCharsPasted:i,numCharsCut:s,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:u,externalTimeTotalSeconds:c,pastes:p,cuts:d,deletions:f,textSuggestions:y,offeredTextSuggestions:v}}=t[e],m=r.length,h=y.reduce((z,{text:V,searchTerm:N})=>z+V.length-(N?N.length:0),0),x=u??Date.now(),_=(Date.now()-x)/1e3+(c||0),w=o/_,b=y.reduce((z,{searchTerm:V})=>z+(V?V.length:0),0);return{conversationId:t.conversation.current.id,source:"agent",text:r,clientVersion:n.version,pastes:p,cuts:d,deletions:f,lenTextTyped:o+b,lenTextTotal:m,lenTextAssisted:h,lenTextPasted:i,lenTextCut:s,lenTextDeleted:a,timeTotalSeconds:_,charsPerSecond:w,numPastes:l,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:v.filter(z=>z.source==="gpt").length}],agentId:(E=t.info.agentInfo)==null?void 0:E.agentId,agentName:(P=t.info.agentInfo)==null?void 0:P.agentName,agentEmail:(I=t.info.agentInfo)==null?void 0:I.agentEmail}}function Kh(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Kh(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Kh(o,t):null}function jb(e,t){return Kh(e,t)}function Hb(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function GA(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Kd(e){return GA(e)&&(Nr(e)||qc(e))}var Bb=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch{return t}}catch{return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch{j.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function XA(e){return e.offsetParent!==null}function zb(e){if(!XA(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function Vd(e,t,n=100){let r=zb(e);t({isVisible:r});let o=setInterval(()=>{let i=zb(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Ce=S(C());var Ub=Bb("showTabHint",!0),el=class e{static version="10.12.1-beta.3";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new qn(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Db({broadcast:(p,d,f)=>{this.broadcastEvents.send(p,d,f)},emit:(p,d,f)=>this.emit(p,d,f),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),logSendEditSuggestionMessage:p=>this.logSendEditMessage(p),onUpdateShowTabHint:p=>Ub.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Ja(n)}),this.store=Mb(c),this.broadcastEvents=new Cb({debug:!0,deepdeskUrl:u,eventMap:o1(this.store),createCustomChannel:l}),this.store.dispatch(da),this.store.dispatch(La(Ub.value())),this.store.dispatch(da({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(j.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(j.warn("Profile has not been loaded (yet)"),!0):(j.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Mi(null)),this.store.dispatch(Mn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();Xe(r)&&qw(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(Mn())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){j.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(rg({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(fc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(mc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(og(t))).payload}async postMessages(t){return(await this.store.dispatch(hc(t))).payload}async updateConversation(t){return(await this.store.dispatch(gc(t))).payload}resetConversation(){this.store.dispatch(J()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(jn());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(da(t))}setVisitorInfo(t){this.store.dispatch(fw(t))}async setAgentInfo(t){await this.store.dispatch(Ta(t))}async setAgentSettings(t){await this.store.dispatch(Ug(t))}async getAgentSettings(){return(await this.store.dispatch(Kg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(ud()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(wc(t))}notifyKeyDown(t){this.store.dispatch(xc(t))}notifyPaste(t,n){this.store.dispatch(f_({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(d_(t))}notifyExternalSuggestion(t){this.store.dispatch(zt(t)),this.store.dispatch(En())}notifyEditSuggestion(t){this.store.dispatch(Ow(t.contentType,t.suggestions)),this.store.dispatch(Nn({contentType:t.contentType,suggestion:typeof t.index=="number"?t.suggestions[t.index]:null}))}async evaluateRule(t,n={}){let{payload:r,error:o}=await this.store.dispatch(Dn({label:t,params:n}));if(o)throw o;return r}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(Rr({collapse:!1})),this.inputMediator&&this.store.dispatch(i_({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(an([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(p_(vc(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(l_()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(c_()),t.preventDefault(),!s&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(fa()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(br(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(br(-1)),this.store.dispatch(fa()),t.preventDefault()):n||(this.store.dispatch(Rr({collapse:!0})),this.store.dispatch(Uw(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:f}=this.state.input;this.store.dispatch(La(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&f&&f.text.startsWith(d)&&(this.store.dispatch(zt({text:f.text,suggestion:f,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(En())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(m_()),this.store.dispatch(an([]))}handlingTimeStart(){this.state.handlingTime.startTime||(j.info("Start handling time"),this.store.dispatch(Tb()))}handlingTimeStop(){this.state.handlingTime.startTime&&(j.info("Stop handling time"),this.store.dispatch(zd()))}logSendMessage(t){let n=Uh("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logSendEditMessage(t){let n=Uh("overlayInput",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.store.dispatch(a_(this.state.overlayInput.metrics))}logHandlingTime(){let t=Fb(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(kb())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(En()),this.store.dispatch(oo(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(zt({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){j.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),j.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=co(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Mt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=co(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,Mt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return uo(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,Mt.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),j.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(j.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(h_(r.metrics))):j.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Kd(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:d,insertLink:f,inputMediator:y,closestScrollSelector:v,appendOverlayTo:m,inlineSuggestions:g,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:f,isEmbedded:p,inlineSuggestions:g,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),uo(t),this.inputMediator=y||(Nr(t)?new Ln(t):new Eo(t)),this.inputMediator.on("change",({plainText:w})=>{this.notifyInputChanged(w)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(g_({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",w=>{this.notifyKeyDown(w)}),this.inputMediator.on("paste",({pastedText:w,selectionText:b})=>{this.notifyPaste(w,b)}),this.inputMediator.on("cut",({selectionText:w})=>{this.notifyCut(w)});let x=v&&jb(t,v)||void 0;if(g){let{customStyles:w,appendOverlayTo:b}=n;if(Nr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let E=this.createInlineContainer(t,"deepdesk-caret");(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:w,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)(rC,{})})}),E),this.inputMediator.on("caret",I=>{this.store.dispatch(an([])),I?(E.style.display="block",E.style.top=`${I.top}px`,E.style.left=`${I.left}px`):E.style.display="none"});let P=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:b},w==null?void 0:w.floatingMenuRootNode);(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:w,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)(Y1,{onLogIn:()=>this.loginViaPopup().catch(I=>j.warn(I.message))})})}),P)}else{let w=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:m,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),b=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:m},r==null?void 0:r.suggestionsRootNode);(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:r,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)(kC,{inputElement:t})})}),w),(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:r,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)(dC,{onLogIn:()=>this.loginViaPopup().catch(E=>j.warn(E.message))})})}),b)}(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:r,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)($1,{})})}),this.createContainer("deepdesk-overlays"));let _;this.inputMediator.on("selection",w=>{clearTimeout(_),w===null?_=setTimeout(()=>{w!==null&&this.store.dispatch(sg(w))},500):this.store.dispatch(sg(w))}),this.inputMediator.on("disabled",()=>{var w;(w=this.inputMediator)==null||w.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Ni(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Ni(!0))),this.store.dispatch(s_({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(En()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var w;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((w=this.state.conversation.current)==null?void 0:w.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&j.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:r,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)(Sb,{onLogIn:()=>this.loginViaPopup().catch(s=>j.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Mt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Vd(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){Hb(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Ua());let t=Ar(this.state);t&&(await this.store.dispatch(Ba()),this.store.dispatch(da({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(t){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};i.onmessage=async f=>{var y,v;if((y=f.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=f.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Na),l=!0,o.port1.close(),n()}catch(m){console.error(m),r(m)}finally{l=!0,u()}};let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let p=async f=>{var y;if(f.origin===a.origin)switch((y=f.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){j.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),f.data.message==="Timeout"&&j.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(f.data.message));break}}};window.addEventListener("message",p);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(j.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;j.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=fd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(qt()):this.store.dispatch(Wt(r))})}catch(r){this.handleError(r)}}};async function Kb(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function Vb(e,t,n={}){let r=n.replace?Fr(e,n.replace.start,n.replace.end):Vi(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
|
|
25
|
+
`);break}default:break}p&&s++}return l(e),a}function _b(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Eo=class extends Rn{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),Ya(this.element,t)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let t=this.getRootNode();if(t.activeElement!==this.element)return null;let n="getSelection"in t?t.getSelection():window.getSelection();if(!n)return null;let r="getComposedRanges"in n&&t instanceof ShadowRoot?(i=n.getComposedRanges(t))==null?void 0:i[0]:n.rangeCount>0?n.getRangeAt(0):null;if(!r)return null;let o=this.element.ownerDocument.createRange();return o.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),o.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!o||!this.element.contains(o.startContainer)||!this.element.contains(o.endContainer)?null:o}getCaretPosition(){let t=this.getRange();if(!t||!t.collapsed||!("getBoundingClientRect"in t))return null;let n=t.getBoundingClientRect();return!_b(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!_b(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return Qa(this.element,t);let n=this.lastKnownSelection;if(n&&xb(this.element,n.start,n.end))return n;let r=Vi(this.element);return r.collapse(!1),Qa(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return Ya(this.element,Fr(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let t=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==t&&(t=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>n.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};function wb(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}var Dh=class{constructor(t){this.name=t;this.broadcastChannel=new BroadcastChannel(t)}broadcastChannel;disposeHandlers=[];onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Fh=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=wb(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},jh=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),j.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Fh(t,this.deepdeskUrl,{debug:!0}):new Dh(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=typeof o.data=="string"?JSON.parse(o.data):o.data;i.type==="event"&&i.channel===t&&(j.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;j.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage({...o,channel:this.sessionId})}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},Cb=jh;var Wi=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var Hh=e=>new Promise(t=>{setTimeout(t,e)});var $i=class extends Wi{name="ClientError"},Bh=class extends Wi{name="ServerError"},Xt=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,{abortLatest:l=!1,attempts:u=1,retryDelay:c=500,refreshTokenOn401:p=!0,retryOnError:d=_=>_ instanceof TypeError,retryOnResponse:f=_=>_.status>=500,version:y="v1",...v}=n,m={credentials:"include",...v,headers:{"Content-Type":"application/json",...v.headers}};n.method!==void 0&&n.method!=="GET"&&this.csrfToken&&(m.headers={...m.headers,"X-CSRFToken":this.csrfToken}),typeof y=="string"&&(m.headers={...m.headers,"X-Deepdesk-API-Version":y});let g=u,h=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&l&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let x=async()=>(g--,a(s,m).then(async _=>f(_)&&!i.isAborted&&g>0?(await Hh(c),x()):_.status===401&&p===!0&&h===!1?(h=!0,await this.refreshToken(),x()):_).catch(async _=>{if(d(_)&&!i.isAborted&&g>0)return await Hh(c),x();throw _}));x().then(_=>_.json().catch(()=>null).then(w=>{_.status>=500?o(new Bh("Server Error",w)):_.status===401?o(new $i("Unauthorized",w)):_.status===403?o(new $i("Forbidden",w)):_.status===404?o(new $i("Not Found",w)):_.status>=400&&o(new $i("Bad Request",w)),delete this.latestRequestByUrl[s],r(w)})).catch(_=>{o(_)})})}async validateToken(){let{has_valid_access_token:t}=await this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return e.refreshingToken||(e.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{e.refreshingToken=null},1e3*60)})),e.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,{method:"POST",body:JSON.stringify(n),...r})}patch(t,n,r){return this.request(t,{method:"PATCH",body:JSON.stringify(n),...r})}put(t,n,r){return this.request(t,{method:"PUT",body:JSON.stringify(n),...r})}delete(t,n){return this.request(t,{method:"DELETE",...n})}};var BA;(t=>{let e;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||={})})(BA||={});function Bd(e){return{...ee(e),tags:e.tags}}var qn=class e{constructor(t,n={}){this.options=n;this.client=new Xt(t,{fetch:n.fetch}),this.client.patchFetch(r=>async(o,i)=>{let s=await r(o,i);return this.handleDeepdeskVersionHeaders(s),s})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=await this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(e.exchangeTokenPromise||(e.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),e.exchangeTokenPromise):Promise.resolve()}async createConversation(t){await this.preflight(),j.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...Pe(t),tags:t.tags},{version:"v2"});return Bd(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null});return ee(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null});return ee(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null});return ee(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null});return ee(t)}async checkUserExists(t){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n}async getConversationBySessionId(t,n={}){await this.preflight(),j.info(`Getting conversation for session ${t}`);let{attempts:r=1,retryDelay:o=1e3}=n,i=await this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"});return j.info(`Successfully retrieved conversation ${i.id} for session ${t}`),Bd(i)}async isConversationSupported(t,n={}){j.info(`Check if conversation for session ${t} is supported`);let{attempts:r=1,retryDelay:o=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"})).has_active_profile}async updateConversation(t,n){let r=Pe(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Bd(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...Pe(o),tags:o.tags})),{version:"v2"})).map(o=>Bd(o))}async sendEvent(t,n){let{data:r,...o}=n,i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[a,l])=>({...s,[a]:l}),{});return this.client.post("/api/events",Pe({...i,...o,data:r,name:t}),{version:"v2"})}async sendEventV1(t,n){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>({...o,[i]:s}),{});return this.client.post("/api/events",{event:t,data:Pe({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){return(await this.client.post("/api/summary",{conversation:{messages:t.filter(o=>o.text&&o.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(t){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw j.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.client.post("/apis/admin/session/api-key/",Pe(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})}async getTextSuggestions(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(await this.client.post(`/api/conversations/${t}/recommend/${r}`,Pe(n),{abortLatest:!0})).map(i=>({...ee(i),text:i.text||i.url||i.message,source:r,type:r})).filter((i,s,a)=>s===a.findIndex(l=>l.text===i.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(t,n){return(await this.client.post(`/api/conversations/${t}/autocomplete`,Pe(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))}async getPinnedMessages(t){let n=await this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return ee(n).map(r=>({...r,text:r.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(t){let n=await this.client.post("/api/style-suggestions",Pe(t),{abortLatest:!0});return ee(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,Pe(t),{version:"v2"});return ee(n)}async knowledgeAssist(t,n,r,o={}){let i=await this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Pe({question:t.question,promptInstruction:t.promptInstruction,chatHistory:n.map(s=>({question:s.question,answer:s.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return ee(i)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return ee(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return ee(t.token)}async getCsrfToken(){let{token:t}=await this.client.get("/apis/admin/session/csrf/",{version:null});return t}async verifyLoginToken(t){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return ee(n)}async evaluateRule(t,n,r,o={}){let i=new URLSearchParams;o.raiseForFailingConditions&&i.set("raise_for_failing_conditions","true");let s=await this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${i.toString()}`,r,{version:"v2"});return ee(s.cues)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Ny);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&j.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var Za=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(zg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,ee(o))}catch{j.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var zA;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(zA||={});var Ja=class{constructor(t,n={}){this.apiUrl=t;this.client=new Xt(t,n)}client;streams={};logger=j;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return ee(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,Pe(n));return ee(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,Pe(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return ee(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",Pe(t));return ee(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new Za(`${this.apiUrl}/sessions/${t}/events`),this.streams[t].connect()),this.streams[t]}closeStream(t){this.streams[t]||(this.streams[t].disconnect(),delete this.streams[t])}};var bb={startTime:null,stopTime:null},Eb=B({name:"handlingTime",initialState:bb,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(J,()=>bb)}}),{handlingTimeStart:Tb,handlingTimeStop:zd,handlingTimeReset:kb}=Eb.actions,Pb=Eb.reducer;var Ib=(e={})=>{let t={onAuthError:Mi(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Ud={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var To=D("styleSuggestions/getAll",async({text:e},t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),{showStyleSuggestions:o}=r.settings,i=(s=r.conversation.current)==null?void 0:s.profileCode;if(!o)return Ud.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),UA=B({name:"styleSuggestions",initialState:Ud,reducers:{},extraReducers:e=>{e.addCase(To.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(To.rejected,t=>{t.fetchState="error"}).addCase(To.fulfilled,(t,n)=>{t.fetchState="done",wr(t.list,n.payload)||(t.list=n.payload)}).addCase(oo,t=>{t.list=Ud.list}).addCase(J,()=>Ud)}}),Rb=UA.reducer;var Lb=(e={})=>{let t,n=!0,r={getStyleSuggestions:To,debounce:500,...e};return o=>i=>s=>{var f;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((f=u.conversation.current)==null?void 0:f.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function KA(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var Ab=(e={})=>{let t={getTextSuggestions:Wt,getAutocompleteSuggestions:Ra,debounce:200,check:Bi,...e},n;return r=>o=>i=>{var v;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,p=(v=l.conversation.current)==null?void 0:v.id,d=i.type===ud.toString();if(!p||!u&&!c)return a;let{input:{userCommitted:f}}=l;return KA(f,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let m=wi(l);m===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(m))},d?0:t.debounce)),a}};var Ob=To.fulfilled.toString();function VA(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var Nb=e=>t=>n=>r=>{var u;if(r.type!==Ob){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=VA(o,s);r.type===Ob&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var WA=Mu({activeSuggestion:Bw,answer:D1,auth:Jw,autoflows:OC,conversation:n_,contentTypes:v1,customMessages:UC,passwordlessToken:$C,entities:w1,knowledgeAssistant:O1,handlingTime:Pb,info:mw,input:ig.reducer,overlayInput:ot.reducer,settings:qx,profile:H1,search:_w,summary:P1,styleSuggestions:Rb,ui:Vw,rules:r1,textSuggestions:Mw});function Mb(e){return J0({reducer:WA,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),Ib(),Ab({debounce:200}),Lb({debounce:500}),Nb(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var $A=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},qA=e=>t=>n=>r=>{var a;let o=t.getState(),i=Jm("inlineSuggestions")(o);switch(r.type){case Nn.toString():{let l=ld(r.payload.contentType)(t.getState()),u=l.indexOf(r.payload.suggestion);e.emit("edit-suggestion",{contentType:r.payload.contentType,index:u,suggestions:l});break}case Mi.toString():{!r.payload&&e.emit("logout",void 0);break}case zt.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",{type:$A(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case Sc.toString():{let{start:l,end:u}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case fa.toString():{let l=t.getState(),{text:u,selection:c}=l.input.userCommitted;e.emit("reset",{text:u,selectionAfter:c},{mayApplyChanges:!0});break}case Cc.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:o.conversation.current.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case qt.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:o.conversation.current.id,data:{entities:r.payload}});break;case jn.fulfilled.toString():e.sendEvent("conversation summarized",{conversationId:o.conversation.current.id,data:{summary:r.payload.summary}});break;case ze.toString():e.sendEvent(r.payload.name,{conversationId:((a=r.payload.options)==null?void 0:a.includeConversationData)&&o.conversation.current.id,data:r.payload.data});break;case xc.toString():e.handleKeyDown(r.payload);break;case oo.toString():e.logSendMessage(r.payload);break;case _c.toString():e.logSendEditSuggestionMessage(r.payload);break;case wc.toString():e.handleInputChanged(r.payload);break;case Dn.fulfilled.toString():e.broadcast(Qg,r.payload,!1),e.emit("cues",r.payload);break;default:break}let s=n(r);switch(r.type){case oo.toString():e.handleAfterSendMessage(r.payload);break;case La.toString():e.onUpdateShowTabHint(r.payload);break;case zd.toString():e.logHandlingTime();break;case zt.toString():{i&&(t.dispatch(an([])),t.dispatch(En()));break}case an.toString():{i&&r.payload.length>0&&t.dispatch(br(0));break}default:break}return s},Db=qA;function zh(e){return e.toISOString().replace("T"," ").replace("Z","")}function Fb(e,t){var o,i,s;let{startTime:n,stopTime:r}=e.handlingTime;if(!n||!r)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:e.conversation.current.id,clientVersion:t.version,agentId:(o=e.info.agentInfo)==null?void 0:o.agentId,agentName:(i=e.info.agentInfo)==null?void 0:i.agentName,agentEmail:(s=e.info.agentInfo)==null?void 0:s.agentEmail,timeStart:zh(n),timeStop:zh(r)}}function Uh(e,t,n){var E,P,I;let{text:r,metrics:{numCharsTyped:o,numCharsPasted:i,numCharsCut:s,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:u,externalTimeTotalSeconds:c,pastes:p,cuts:d,deletions:f,textSuggestions:y,offeredTextSuggestions:v}}=t[e],m=r.length,h=y.reduce((z,{text:V,searchTerm:N})=>z+V.length-(N?N.length:0),0),x=u??Date.now(),_=(Date.now()-x)/1e3+(c||0),w=o/_,b=y.reduce((z,{searchTerm:V})=>z+(V?V.length:0),0);return{conversationId:t.conversation.current.id,source:"agent",text:r,clientVersion:n.version,pastes:p,cuts:d,deletions:f,lenTextTyped:o+b,lenTextTotal:m,lenTextAssisted:h,lenTextPasted:i,lenTextCut:s,lenTextDeleted:a,timeTotalSeconds:_,charsPerSecond:w,numPastes:l,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:v.filter(z=>z.source==="gpt").length}],agentId:(E=t.info.agentInfo)==null?void 0:E.agentId,agentName:(P=t.info.agentInfo)==null?void 0:P.agentName,agentEmail:(I=t.info.agentInfo)==null?void 0:I.agentEmail}}function Kh(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Kh(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Kh(o,t):null}function jb(e,t){return Kh(e,t)}function Hb(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function GA(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Kd(e){return GA(e)&&(Nr(e)||qc(e))}var Bb=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch{return t}}catch{return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch{j.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function XA(e){return e.offsetParent!==null}function zb(e){if(!XA(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function Vd(e,t,n=100){let r=zb(e);t({isVisible:r});let o=setInterval(()=>{let i=zb(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Ce=S(C());var Ub=Bb("showTabHint",!0),el=class e{static version="10.12.1-beta.4";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new qn(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Db({broadcast:(p,d,f)=>{this.broadcastEvents.send(p,d,f)},emit:(p,d,f)=>this.emit(p,d,f),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),logSendEditSuggestionMessage:p=>this.logSendEditMessage(p),onUpdateShowTabHint:p=>Ub.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Ja(n)}),this.store=Mb(c),this.broadcastEvents=new Cb({debug:!0,deepdeskUrl:u,eventMap:o1(this.store),createCustomChannel:l}),this.store.dispatch(da),this.store.dispatch(La(Ub.value())),this.store.dispatch(da({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(j.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(j.warn("Profile has not been loaded (yet)"),!0):(j.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Mi(null)),this.store.dispatch(Mn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();Xe(r)&&qw(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(Mn())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){j.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(rg({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(fc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(mc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(og(t))).payload}async postMessages(t){return(await this.store.dispatch(hc(t))).payload}async updateConversation(t){return(await this.store.dispatch(gc(t))).payload}resetConversation(){this.store.dispatch(J()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(jn());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(da(t))}setVisitorInfo(t){this.store.dispatch(fw(t))}async setAgentInfo(t){await this.store.dispatch(Ta(t))}async setAgentSettings(t){await this.store.dispatch(Ug(t))}async getAgentSettings(){return(await this.store.dispatch(Kg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(ud()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(wc(t))}notifyKeyDown(t){this.store.dispatch(xc(t))}notifyPaste(t,n){this.store.dispatch(f_({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(d_(t))}notifyExternalSuggestion(t){this.store.dispatch(zt(t)),this.store.dispatch(En())}notifyEditSuggestion(t){this.store.dispatch(Ow(t.contentType,t.suggestions)),this.store.dispatch(Nn({contentType:t.contentType,suggestion:typeof t.index=="number"?t.suggestions[t.index]:null}))}async evaluateRule(t,n={}){let{payload:r,error:o}=await this.store.dispatch(Dn({label:t,params:n}));if(o)throw o;return r}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(Rr({collapse:!1})),this.inputMediator&&this.store.dispatch(i_({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(an([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(p_(vc(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(l_()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(c_()),t.preventDefault(),!s&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(fa()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(br(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(br(-1)),this.store.dispatch(fa()),t.preventDefault()):n||(this.store.dispatch(Rr({collapse:!0})),this.store.dispatch(Uw(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:f}=this.state.input;this.store.dispatch(La(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&f&&f.text.startsWith(d)&&(this.store.dispatch(zt({text:f.text,suggestion:f,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(En())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(m_()),this.store.dispatch(an([]))}handlingTimeStart(){this.state.handlingTime.startTime||(j.info("Start handling time"),this.store.dispatch(Tb()))}handlingTimeStop(){this.state.handlingTime.startTime&&(j.info("Stop handling time"),this.store.dispatch(zd()))}logSendMessage(t){let n=Uh("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logSendEditMessage(t){let n=Uh("overlayInput",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.store.dispatch(a_(this.state.overlayInput.metrics))}logHandlingTime(){let t=Fb(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(kb())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(En()),this.store.dispatch(oo(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(zt({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){j.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),j.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=co(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Mt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=co(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,Mt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return uo(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,Mt.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),j.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(j.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(h_(r.metrics))):j.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Kd(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:d,insertLink:f,inputMediator:y,closestScrollSelector:v,appendOverlayTo:m,inlineSuggestions:g,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:f,isEmbedded:p,inlineSuggestions:g,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),uo(t),this.inputMediator=y||(Nr(t)?new Ln(t):new Eo(t)),this.inputMediator.on("change",({plainText:w})=>{this.notifyInputChanged(w)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(g_({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",w=>{this.notifyKeyDown(w)}),this.inputMediator.on("paste",({pastedText:w,selectionText:b})=>{this.notifyPaste(w,b)}),this.inputMediator.on("cut",({selectionText:w})=>{this.notifyCut(w)});let x=v&&jb(t,v)||void 0;if(g){let{customStyles:w,appendOverlayTo:b}=n;if(Nr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let E=this.createInlineContainer(t,"deepdesk-caret");(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:w,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)(rC,{})})}),E),this.inputMediator.on("caret",I=>{this.store.dispatch(an([])),I?(E.style.display="block",E.style.top=`${I.top}px`,E.style.left=`${I.left}px`):E.style.display="none"});let P=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:b},w==null?void 0:w.floatingMenuRootNode);(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:w,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)(Y1,{onLogIn:()=>this.loginViaPopup().catch(I=>j.warn(I.message))})})}),P)}else{let w=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:m,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),b=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:m},r==null?void 0:r.suggestionsRootNode);(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:r,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)(kC,{inputElement:t})})}),w),(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:r,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)(dC,{onLogIn:()=>this.loginViaPopup().catch(E=>j.warn(E.message))})})}),b)}(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:r,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)($1,{})})}),this.createContainer("deepdesk-overlays"));let _;this.inputMediator.on("selection",w=>{clearTimeout(_),w===null?_=setTimeout(()=>{w!==null&&this.store.dispatch(sg(w))},500):this.store.dispatch(sg(w))}),this.inputMediator.on("disabled",()=>{var w;(w=this.inputMediator)==null||w.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Ni(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Ni(!0))),this.store.dispatch(s_({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(En()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var w;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((w=this.state.conversation.current)==null?void 0:w.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&j.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,Mt.render)((0,Ce.jsx)(bo,{store:this.store,customStyles:r,children:(0,Ce.jsx)(So,{broadcastEvents:this.broadcastEvents,children:(0,Ce.jsx)(Sb,{onLogIn:()=>this.loginViaPopup().catch(s=>j.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Mt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Vd(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){Hb(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Ua());let t=Ar(this.state);t&&(await this.store.dispatch(Ba()),this.store.dispatch(da({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(t){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};i.onmessage=async f=>{var y,v;if((y=f.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=f.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Na),l=!0,o.port1.close(),n()}catch(m){console.error(m),r(m)}finally{l=!0,u()}};let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let p=async f=>{var y;if(f.origin===a.origin)switch((y=f.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){j.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),f.data.message==="Timeout"&&j.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(f.data.message));break}}};window.addEventListener("message",p);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(j.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;j.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=fd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(qt()):this.store.dispatch(Wt(r))})}catch(r){this.handleError(r)}}};async function Kb(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function Vb(e,t,n={}){let r=n.replace?Fr(e,n.replace.start,n.replace.end):Vi(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
|
|
26
26
|
`).reverse().forEach((s,a)=>{a>0&&r.insertNode(document.createElement("br")),r.insertNode(document.createTextNode(s))}):r.insertNode(document.createTextNode(t))};return Promise.resolve(i()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let s=n.selectionAfter?Fr(e,n.selectionAfter.start,n.selectionAfter.end):(r.collapse(!1),r),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(s)}if(!o)return;o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function QA(e){let t=document.createElement("template");return t.innerHTML=e.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),t.content}function YA(e){let t=document.createDocumentFragment();return e.split(`
|
|
27
27
|
`).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},i=0;for(;o=n.slice(i).match(/(\[([^\]]+)])\(([^)]+)\)/);){let s=document.createElement("a");s.href=o[3],s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer"),s.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(i,i+o.index))),t.appendChild(s),i=i+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(i)))}),t}function Wb(e,t){return!e.contains(t)||t===e?null:t.parentNode===e?t:Wb(e,t.parentNode)}async function $b(e,t,{isBlock:n,isHTML:r}={}){let o;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let i=()=>{let s=e.ownerDocument.defaultView??window,a=s.getSelection();if((!a||a.rangeCount===0)&&(e.focus(),a=s.getSelection()),!a||a.rangeCount===0)return;let l=a.getRangeAt(0);if(!l)return;o=document.createElement("span"),l.insertNode(o);let u=r?QA(t):YA(t);if(n){let c=l.startContainer===e?e.childNodes[l.startOffset]:l.startContainer,p=Wb(e,c)??e.firstChild;e.insertBefore(u,(p==null?void 0:p.nextSibling)??null)}else l.insertNode(u),l.collapse(!1)};return Promise.resolve(i()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!o)try{o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function qb(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function Gb(e,t,n){await new qn(e).authenticateWithKey(t,n)}async function Xb(e){let n=await new Xt(e).get("/platform/config/",{version:null});return ee(n)}async function ZA(e){let n=await(e.fetch??window.fetch)(e.url),r=await n.blob();return new File([r],e.name,{type:e.mimeType??n.headers.get("Content-Type")??"image/jpeg"})}async function Qb(e,t){let n=await ZA(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}}return oE(JA);})();
|
|
28
28
|
/*! Bundled license information:
|