@botpress/webchat 4.4.2 → 4.4.3

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.
@@ -1,5 +1,5 @@
1
1
 
2
- > @botpress/webchat@4.4.2 build /home/runner/work/genisys/genisys/packages/webchat-components
2
+ > @botpress/webchat@4.4.3 build /home/runner/work/genisys/genisys/packages/webchat-components
3
3
  > vite build
4
4
 
5
5
  vite v5.4.8 building for production...
@@ -10,12 +10,12 @@ rendering chunks...
10
10
  [vite:dts] Start generate declaration files...
11
11
  computing gzip size...
12
12
  dist/style.css  57.11 kB │ gzip: 9.49 kB
13
- dist/index.js 876.91 kB │ gzip: 231.53 kB
13
+ dist/index.js 876.92 kB │ gzip: 231.53 kB
14
14
  [vite:dts] Start rollup declaration files...
15
15
  Analysis will use the bundled TypeScript version 5.8.2
16
16
  *** The target project appears to use TypeScript 5.9.3 which is newer than the bundled compiler engine; consider upgrading API Extractor.
17
- [vite:dts] Declaration files built in 19758ms.
17
+ [vite:dts] Declaration files built in 19466ms.
18
18
 
19
19
  dist/style.css  57.11 kB │ gzip: 9.49 kB
20
20
  dist/index.umd.cjs 537.53 kB │ gzip: 176.30 kB
21
- ✓ built in 24.88s
21
+ ✓ built in 24.60s
package/dist/index.js CHANGED
@@ -24526,7 +24526,7 @@ function Sy({
24526
24526
  }, [a.conversationId, a.userToken, t, e]);
24527
24527
  const A = async ({ conversationId: O, userToken: z }) => {
24528
24528
  var H;
24529
- (H = R.current) == null || H.call(R), I(void 0), m(!1), w("connecting");
24529
+ (H = R.current) == null || H.call(R), I(void 0), m(!1), g(!1), w("connecting");
24530
24530
  const { on: L, conversation: P, messages: _, participants: D, user: U, client: B, onCleanup: V } = await WN({
24531
24531
  apiUrl: e,
24532
24532
  clientId: t,
@@ -320,7 +320,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
320
320
  `;break;case"id":a=g.includes("\0")?void 0:g;break;case"retry":/^\d+$/.test(g)?r(parseInt(g,10)):n(new ey(`Invalid \`retry\` value: "${g}"`,{type:"invalid-retry",value:g,line:y}));break;default:n(new ey(`Unknown field "${p.length>20?`${p.slice(0,20)}…`:p}"`,{type:"unknown-field",field:p,value:g,line:y}));break}}function d(){l.length>0&&t({id:a,event:u||void 0,data:l.endsWith(`
321
321
  `)?l.slice(0,-1):l}),a=void 0,l="",u=""}function m(p={}){o&&p.consume&&c(o),s=!0,a=void 0,l="",u="",o=""}return{feed:f,reset:m}}function RN(e){const t=[];let n="",r=0;for(;r<e.length;){const i=e.indexOf("\r",r),o=e.indexOf(`
322
322
  `,r);let s=-1;if(i!==-1&&o!==-1?s=Math.min(i,o):i!==-1?i===e.length-1?s=-1:s=i:o!==-1&&(s=o),s===-1){n=e.slice(r);break}else{const a=e.slice(r,s);t.push(a),r=s+1,e[r-1]==="\r"&&e[r]===`
323
- `&&r++}}return[t,n]}class ty extends Event{constructor(t,n){var r,i;super(t),this.code=(r=n==null?void 0:n.code)!=null?r:void 0,this.message=(i=n==null?void 0:n.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,n,r){return r(ny(this),n)}[Symbol.for("Deno.customInspect")](t,n){return t(ny(this),n)}}function $N(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function Vl(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(Vl).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${Vl(e.cause)}`:e.message:`${e}`}function ny(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var ry=e=>{throw TypeError(e)},Wl=(e,t,n)=>t.has(e)||ry("Cannot "+n),be=(e,t,n)=>(Wl(e,t,"read from private field"),n?n.call(e):t.get(e)),Ke=(e,t,n)=>t.has(e)?ry("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Le=(e,t,n,r)=>(Wl(e,t,"write to private field"),t.set(e,n),n),Qt=(e,t,n)=>(Wl(e,t,"access private method"),n),dt,_n,lr,Po,Lo,fi,ur,di,pn,cr,fr,dr,hi,Lt,ql,Yl,Kl,iy,Gl,Ql,pi,Zl,Jl;class Fo extends EventTarget{constructor(t,n){var r,i;super(),Ke(this,Lt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Ke(this,dt),Ke(this,_n),Ke(this,lr),Ke(this,Po),Ke(this,Lo),Ke(this,fi),Ke(this,ur),Ke(this,di,null),Ke(this,pn),Ke(this,cr),Ke(this,fr,null),Ke(this,dr,null),Ke(this,hi,null),Ke(this,Yl,async o=>{var s;be(this,cr).reset();const{body:a,redirected:l,status:u,headers:f}=o;if(u===204){Qt(this,Lt,pi).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?Le(this,lr,new URL(o.url)):Le(this,lr,void 0),u!==200){Qt(this,Lt,pi).call(this,`Non-200 status code (${u})`,u);return}if(!(f.get("content-type")||"").startsWith("text/event-stream")){Qt(this,Lt,pi).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(be(this,dt)===this.CLOSED)return;Le(this,dt,this.OPEN);const c=new Event("open");if((s=be(this,hi))==null||s.call(this,c),this.dispatchEvent(c),typeof a!="object"||!a||!("getReader"in a)){Qt(this,Lt,pi).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}const h=new TextDecoder,d=a.getReader();let m=!0;do{const{done:p,value:g}=await d.read();g&&be(this,cr).feed(h.decode(g,{stream:!p})),p&&(m=!1,be(this,cr).reset(),Qt(this,Lt,Zl).call(this))}while(m)}),Ke(this,Kl,o=>{Le(this,pn,void 0),!(o.name==="AbortError"||o.type==="aborted")&&Qt(this,Lt,Zl).call(this,Vl(o))}),Ke(this,Gl,o=>{typeof o.id=="string"&&Le(this,di,o.id);const s=new MessageEvent(o.event||"message",{data:o.data,origin:be(this,lr)?be(this,lr).origin:be(this,_n).origin,lastEventId:o.id||""});be(this,dr)&&(!o.event||o.event==="message")&&be(this,dr).call(this,s),this.dispatchEvent(s)}),Ke(this,Ql,o=>{Le(this,fi,o)}),Ke(this,Jl,()=>{Le(this,ur,void 0),be(this,dt)===this.CONNECTING&&Qt(this,Lt,ql).call(this)});try{if(t instanceof URL)Le(this,_n,t);else if(typeof t=="string")Le(this,_n,new URL(t,BN()));else throw new Error("Invalid URL")}catch{throw $N("An invalid or illegal string was specified")}Le(this,cr,FN({onEvent:be(this,Gl),onRetry:be(this,Ql)})),Le(this,dt,this.CONNECTING),Le(this,fi,3e3),Le(this,Lo,(r=n==null?void 0:n.fetch)!=null?r:globalThis.fetch),Le(this,Po,(i=n==null?void 0:n.withCredentials)!=null?i:!1),Qt(this,Lt,ql).call(this)}get readyState(){return be(this,dt)}get url(){return be(this,_n).href}get withCredentials(){return be(this,Po)}get onerror(){return be(this,fr)}set onerror(t){Le(this,fr,t)}get onmessage(){return be(this,dr)}set onmessage(t){Le(this,dr,t)}get onopen(){return be(this,hi)}set onopen(t){Le(this,hi,t)}addEventListener(t,n,r){const i=n;super.addEventListener(t,i,r)}removeEventListener(t,n,r){const i=n;super.removeEventListener(t,i,r)}close(){be(this,ur)&&clearTimeout(be(this,ur)),be(this,dt)!==this.CLOSED&&(be(this,pn)&&be(this,pn).abort(),Le(this,dt,this.CLOSED),Le(this,pn,void 0))}}dt=new WeakMap,_n=new WeakMap,lr=new WeakMap,Po=new WeakMap,Lo=new WeakMap,fi=new WeakMap,ur=new WeakMap,di=new WeakMap,pn=new WeakMap,cr=new WeakMap,fr=new WeakMap,dr=new WeakMap,hi=new WeakMap,Lt=new WeakSet,ql=function(){Le(this,dt,this.CONNECTING),Le(this,pn,new AbortController),be(this,Lo)(be(this,_n),Qt(this,Lt,iy).call(this)).then(be(this,Yl)).catch(be(this,Kl))},Yl=new WeakMap,Kl=new WeakMap,iy=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...be(this,di)?{"Last-Event-ID":be(this,di)}:void 0},cache:"no-store",signal:(e=be(this,pn))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Gl=new WeakMap,Ql=new WeakMap,pi=function(e,t){var n;be(this,dt)!==this.CLOSED&&Le(this,dt,this.CLOSED);const r=new ty("error",{code:t,message:e});(n=be(this,fr))==null||n.call(this,r),this.dispatchEvent(r)},Zl=function(e,t){var n;if(be(this,dt)===this.CLOSED)return;Le(this,dt,this.CONNECTING);const r=new ty("error",{code:t,message:e});(n=be(this,fr))==null||n.call(this,r),this.dispatchEvent(r),Le(this,ur,setTimeout(be(this,Jl),be(this,fi)))},Jl=new WeakMap,Fo.CONNECTING=0,Fo.OPEN=1,Fo.CLOSED=2;function BN(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}async function zN(e){var t;const n=await e.clone().json();if((t=n==null?void 0:n.id)!=null&&t.startsWith("err_")){const r=new Error(n.message);throw r.id=n.id,r.code=n.code,r.type=n.type,r}return e}const oy=()=>{const e={};return{on:(t,n)=>{var r;return e[t]||(e[t]=new Set),(r=e[t])==null||r.add(n),()=>{var i;return(i=e[t])==null?void 0:i.delete(n)}},emit:(t,n)=>{var r,i;(r=e[t])==null||r.forEach(o=>o(n)),(i=e["*"])==null||i.forEach(o=>o({type:t,payload:n}))}}},Ue=e=>e.data,sy=10,ay=3e3,UN="60000",jN={throwOnError:!0},HN=({conversationId:e,userToken:t,clientId:n,apiUrl:r,adminSecret:i})=>{let o=0,s=null;const a=oy(),l=()=>{s&&s.close();const u=`${`${r||Pe.getConfig().baseUrl}/${n}`}/initialize${e?`?conversationId=${e}`:""}`,f={...i?{"x-admin-secret":i}:{},...t?{"x-user-key":t}:{}};s=uy(u,f),s.addEventListener("open",()=>a.emit("open")),s.addEventListener("error",c=>{o<sy?(o++,setTimeout(()=>l(),ay)):a.emit("error",c)}),s.addEventListener("message",c=>{const h=ly(c.data);a.emit(h.type,h.data)})};return l(),a.on},VN=({userKey:e,clientId:t,apiUrl:n,customHeaders:r,advancedOptions:i})=>{const o={"x-user-key":e,...r},s=`${n||Pe.getConfig().baseUrl}/${t}`,a={...jN,baseUrl:s};return Pe.interceptors.response._fns.length===0&&Pe.interceptors.response.use(zN),{createConversation:()=>yN({...a,headers:o,body:{}}).then(Ue),getConversation:({conversationId:l})=>mN({...a,headers:o,path:{id:l}}).then(Ue),deleteConversation:({conversationId:l})=>pN({...a,headers:o,path:{id:l}}).then(Ue),listConversations:({nextToken:l})=>gN({...a,headers:o,query:{nextToken:l}}).then(Ue),listConversationMessages:({conversationId:l,nextToken:u})=>vN({...a,headers:o,path:{id:l},query:{nextToken:u}}).then(Ue),addParticipant:({conversationId:l,userId:u})=>wN({...a,headers:o,path:{id:l},body:{userId:u}}).then(Ue),removeParticipant:({conversationId:l,userId:u})=>SN({...a,headers:o,path:{id:l,userId:u}}).then(Ue),getParticipant:({conversationId:l,userId:u})=>xN({...a,headers:o,path:{id:l,userId:u}}).then(Ue),listParticipants:({conversationId:l,nextToken:u})=>bN({...a,headers:o,path:{id:l},query:{nextToken:u}}).then(Ue),createMessage:l=>AN({...a,headers:o,body:l}).then(Ue),updateMessage:({messageId:l,...u})=>CN({...a,headers:o,path:{id:l},body:u}).then(Ue),getMessage:({messageId:l})=>EN({...a,headers:o,path:{id:l}}).then(Ue),deleteMessage:({messageId:l})=>kN({...a,headers:o,path:{id:l}}).then(Ue),createFile:l=>LN({...a,headers:o,body:l}).then(Ue),getUser:()=>MN({...a,headers:o}).then(Ue),updateUser:l=>DN({...a,headers:o,body:l}).then(Ue),deleteUser:()=>ON({...a,headers:o}).then(Ue),createEvent:l=>PN({...a,headers:o,body:l}).then(Ue),getEvent:({eventId:l})=>_N({...a,headers:o,path:{id:l}}).then(Ue),addMessageFeedback:({messageId:l,...u})=>IN({...a,headers:o,path:{id:l},body:u}).then(Ue),removeMessageFeedback:({messageId:l})=>TN({...a,headers:o,path:{id:l}}).then(Ue),generateUserKey:({adminSecret:l,...u})=>NN({...a,headers:{"x-admin-secret":l},body:u}).then(Ue),listenConversation:({conversationId:l})=>{let u=0,f=null;const c=oy(),h=()=>{f&&f.close();const d=`${s}/conversations/${l}/listen`,m=i==null?void 0:i.eventSource;f=m?m({url:d,headers:o}):uy(d,o),f.addEventListener("open",()=>c.emit("open")),f.addEventListener("error",p=>{u<sy?(u++,setTimeout(()=>h(),ay)):c.emit("error",p)}),f.addEventListener("message",p=>{const g=ly(p.data);c.emit(g.type,g.data)})};return h(),c.on}}},ly=e=>{try{return JSON.parse(e)}catch{return e}},uy=(e,t)=>new Fo(e,{fetch:(n,r)=>fetch(n,{...r,headers:{...r==null?void 0:r.headers,...t,timeout:UN}})}),WN=async({apiUrl:e,clientId:t,adminSecret:n,clientHeaders:r,emitter:i,conversationId:o,userToken:s})=>new Promise(a=>{const l=HN({apiUrl:e,clientId:t,userToken:s,conversationId:o,adminSecret:n}),u=l("init",({conversation:f,messages:c,participants:h,user:d})=>{const m=VN({clientId:t,apiUrl:e,userKey:d.userKey,customHeaders:r});m.createEvent({conversationId:f.id,payload:{type:"conversation_started",data:{}}}).then(({event:p})=>{var g,y;(y=(g=p.payload.data)==null?void 0:g.status)!=null&&y.isInitial&&i.emit("conversation",f.id)}),a({on:l,conversation:f,messages:c,participants:h,user:d,client:m,onCleanup:()=>{u()}})})}),qN={webchat:"#9C27B0",client:"#2196F3",store:"#4CAF50",events:"#00BCD4"},YN={debug:"#9E9E9E",info:"#2196F3",warn:"#FF9800",error:"#F44336"};let cy=!1,Xl=null,fy=Date.now();const KN=e=>{cy=e,fy=Date.now()},GN=e=>{Xl=e},QN=()=>{const e=Date.now()-fy,t=Math.floor(e/1e3),n=e%1e3;return`+${t}.${n.toString().padStart(3,"0")}s`},ZN=e=>e===void 0?"undefined":e===null?"null":e instanceof Error?{error:e.message,stack:e.stack}:e,Ro=e=>{const t=qN[e]||"#666",n=(r,...i)=>{if(!cy&&r!=="warn"&&r!=="error")return;const o=QN(),s=`%c[bp:${e}]%c ${o} %c${r.toUpperCase()}%c`,a=[`color: ${t}; font-weight: bold;`,"color: #999; font-size: 10px;",`color: ${YN[r]}; font-weight: bold;`,"color: inherit;"],l=i.map(ZN);if(console[r](s,...a,...l),Xl){const[u,f]=i;Xl(`debug:${e}:${r}`,{message:typeof u=="string"?u:void 0,...typeof f=="object"&&f!==null?f:{}})}};return{debug:(...r)=>n("debug",...r),info:(...r)=>n("info",...r),warn:(...r)=>n("warn",...r),error:(...r)=>n("error",...r)}},dy={webchat:Ro("webchat"),client:Ro("client"),store:Ro("store"),events:Ro("events")};function hy(){const[e,t]=D.useState(!1),n=D.useRef(null);return{state:e,setState:(r,i)=>{if(t(r),!r)return()=>{};if(n.current=new Date,!i)return()=>{};const o=setTimeout(()=>{const s=n.current;s&&new Date().getTime()-s.getTime()>i&&t(!1)},i+100);return()=>clearTimeout(o)}}}const mi=dy.webchat;function py({apiUrl:e="https://webchat.botpress.cloud",clientId:t,storageKey:n,storageLocation:r,adminSecret:i,clientHeaders:o,playNotificationSound:s,...a}){const l=Cp(n,r),u=l(O=>O.conversationId),f=l(O=>O.user),c=l(O=>O.setConversationId),h=l(O=>O.setUser),{state:d,setState:m}=hy(),{state:p,setState:g}=hy(),y=D.useMemo(()=>sc(),[]),[v,w]=D.useState("connecting"),[E,S]=D.useState(void 0),[C,I]=D.useState(void 0),M=D.useRef(null),P=e1(a.conversationId,a.userToken,u,f==null?void 0:f.userToken);D.useEffect(()=>{let O=!1;mi.info("starting initialization",{clientId:t,apiUrl:e,storageKey:n});const U=async()=>{var L;await T(P),O&&(mi.debug("initialization completed but effect was cleaned up, tearing down"),(L=M.current)==null||L.call(M),M.current=null)},F=Jw(t,e);if(F){mi.error("configuration error",F),I(F),w("error");return}return U(),()=>{O=!0,M.current&&(M.current(),M.current=null)}},[a.conversationId,a.userToken,t,e]);const T=async({conversationId:O,userToken:U})=>{var V;(V=M.current)==null||V.call(M),I(void 0),m(!1),w("connecting");const{on:F,conversation:L,messages:R,participants:N,user:j,client:B,onCleanup:W}=await WN({apiUrl:e,clientId:t,clientHeaders:o,emitter:y,adminSecret:i,conversationId:O,userToken:U});S(B),c(L.id),h({userId:j.id,userToken:j.userKey});const b=Ep(L.id),_=R.reverse().map(ui).filter(Boolean);b.getState().setMessages(_);const H=Tp(L.id);H.getState().setParticipants(N);const x=[W,F("open",()=>{I(void 0),w("connected")}),F("error",Y=>{mi.error("connection error",{error:Y,conversationId:L.id}),I(q=>q||_r(Y)),w("error"),y.emit("error",new Error(`Connection to conversation lost: ${Y==null?void 0:Y.message}`))}),F("message_created",Y=>{const q=ui(Y);b.getState().saveMessage(q),j.id!==q.authorId&&(s==null||s(),m(!1),g(!1),y.emit("isTyping",{isTyping:!1,timeout:0})),y.emit("message",q)}),F("message_status_changed",Y=>{var q;Y.newStatus==="processing"&&b.getState().updateMessage((q=Y.message.metadata)==null?void 0:q.clientMessageId,{status:Y.newStatus})}),F("typing_stopped",()=>{m(!1),g(!1)}),F("typing_started",()=>{m(!0,5e3),g(!0,5e3),y.emit("isTyping",{isTyping:!0,timeout:5e3})}),F("participant_added",Y=>{H.getState().addParticipant(Y.participant),y.emit("participantAdded",Y.participant)}),F("participant_removed",Y=>{H.getState().removeParticipant(Y.participantId),y.emit("participantRemoved",Y.participantId)}),F("webchat_visibility",Y=>y.emit("webchatVisibility",Y.visibility)),F("webchat_config",Y=>y.emit("webchatConfig",Y.config)),F("custom",Y=>y.emit("customEvent",Y.event))];w("connected"),mi.info("client fully connected with event handlers ready",{conversationId:L.id}),M.current=()=>{x.forEach(Y=>Y())}};return{clientState:v,httpClient:E,error:C,activeConversationId:u,userCredentials:f,isTyping:d,isAwaitingResponse:p,openConversation:T,setAwaitingResponse:g,emitter:y,setError:I,setClientState:w}}const my=D.createContext(null);function $o(){const e=D.useContext(my);if(!e)throw new Error("useWebchatContext must be used inside <WebchatProvider>");return e}function gy({clientId:e,apiUrl:t,storageKey:n,storageLocation:r,adminSecret:i,clientHeaders:o,children:s,...a}){var S;const{clientState:l,httpClient:u,error:f,activeConversationId:c,userCredentials:h,isTyping:d,isAwaitingResponse:m,openConversation:p,setClientState:g,setError:y,setAwaitingResponse:v,emitter:w}=py({apiUrl:t,clientId:e,storageKey:n,storageLocation:r,adminSecret:i,clientHeaders:o,conversationId:a.conversationId,userToken:(S=a.userCredentials)==null?void 0:S.userToken}),E={client:u,clientState:l,setClientState:g,conversationId:c,userCredentials:h,error:f,setError:y,isTyping:d,isAwaitingResponse:m,openConversation:p,setAwaitingResponse:v,emitter:w};return k.jsx(my.Provider,{value:E,children:s})}const eu=({children:e,className:t,uploadFile:n,allowFileUpload:r,storageKey:i,conversationId:o,...s})=>{const{container:a}=me,l=Qn(g=>g.setMessageContainerRef),f=Ap(o||"default",i)(g=>g.uploadFile),[c,h]=D.useState(0),d=D.useRef(null);D.useEffect(()=>{l(d)},[d,l]);const m=D.useCallback(g=>{n&&(g.forEach(y=>f(y,n)),h(0))},[f,n]),{getRootProps:p}=_g({noClick:!0,noKeyboard:!0,onDrop:m,disabled:!(r&&n),onDragEnter:()=>h(g=>g+1),onDragLeave:()=>h(g=>g-1)});return k.jsxs("div",{...s,className:ar(a.className,t),...p(),ref:d,children:[k.jsxs("div",{"data-hover":c>0,...a.dropzone.overlay,children:["Drop files to upload",k.jsx(HA,{style:{width:"50px"}})]}),k.jsx(Lg,{children:e})]})};eu.displayName="Container";const yy=D.forwardRef(({onClick:e,imgUrl:t,...n},r)=>{const{fab:i}=me,{container:o,icon:s,image:a}=i??{};return t?k.jsx("img",{src:t,role:"button",tabIndex:0,...a,draggable:"false",onClick:e}):k.jsx("div",{...n,...o,ref:r,onClick:e,children:k.jsx("div",{...s})})});yy.displayName="Fab";function Zt(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e==null||e(i),n===!1||!i.defaultPrevented)return t==null?void 0:t(i)}}function JN(e,t){const n=A.createContext(t),r=o=>{const{children:s,...a}=o,l=A.useMemo(()=>a,Object.values(a));return k.jsx(n.Provider,{value:l,children:s})};r.displayName=e+"Provider";function i(o){const s=A.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${o}\` must be used within \`${e}\``)}return[r,i]}function vy(e,t=[]){let n=[];function r(o,s){const a=A.createContext(s),l=n.length;n=[...n,s];const u=c=>{var y;const{scope:h,children:d,...m}=c,p=((y=h==null?void 0:h[e])==null?void 0:y[l])||a,g=A.useMemo(()=>m,Object.values(m));return k.jsx(p.Provider,{value:g,children:d})};u.displayName=o+"Provider";function f(c,h){var p;const d=((p=h==null?void 0:h[e])==null?void 0:p[l])||a,m=A.useContext(d);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${c}\` must be used within \`${o}\``)}return[u,f]}const i=()=>{const o=n.map(s=>A.createContext(s));return function(a){const l=(a==null?void 0:a[e])||o;return A.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return i.scopeName=e,[r,XN(i,...t)]}function XN(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(o){const s=r.reduce((a,{useScope:l,scopeName:u})=>{const c=l(o)[`__scope${u}`];return{...a,...c}},{});return A.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}var e2=A[" useInsertionEffect ".trim().toString()]||en;function by({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,o,s]=t2({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:i;{const f=A.useRef(e!==void 0);A.useEffect(()=>{const c=f.current;c!==a&&console.warn(`${r} is changing from ${c?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),f.current=a},[a,r])}const u=A.useCallback(f=>{var c;if(a){const h=n2(f)?f(e):f;h!==e&&((c=s.current)==null||c.call(s,h))}else o(f)},[a,e,o,s]);return[l,u]}function t2({defaultProp:e,onChange:t}){const[n,r]=A.useState(e),i=A.useRef(n),o=A.useRef(t);return e2(()=>{o.current=t},[t]),A.useEffect(()=>{var s;i.current!==n&&((s=o.current)==null||s.call(o,n),i.current=n)},[n,i]),[n,r,o]}function n2(e){return typeof e=="function"}function wy(e){const t=r2(e),n=A.forwardRef((r,i)=>{const{children:o,...s}=r,a=A.Children.toArray(o),l=a.find(o2);if(l){const u=l.props.children,f=a.map(c=>c===l?A.Children.count(u)>1?A.Children.only(null):A.isValidElement(u)?u.props.children:null:c);return k.jsx(t,{...s,ref:i,children:A.isValidElement(u)?A.cloneElement(u,void 0,f):null})}return k.jsx(t,{...s,ref:i,children:o})});return n.displayName=`${e}.Slot`,n}function r2(e){const t=A.forwardRef((n,r)=>{const{children:i,...o}=n;if(A.isValidElement(i)){const s=a2(i),a=s2(o,i.props);return i.type!==A.Fragment&&(a.ref=r?is(r,s):s),A.cloneElement(i,a)}return A.Children.count(i)>1?A.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var i2=Symbol("radix.slottable");function o2(e){return A.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===i2}function s2(e,t){const n={...t};for(const r in t){const i=e[r],o=t[r];/^on[A-Z]/.test(r)?i&&o?n[r]=(...a)=>{const l=o(...a);return i(...a),l}:i&&(n[r]=i):r==="style"?n[r]={...i,...o}:r==="className"&&(n[r]=[i,o].filter(Boolean).join(" "))}return{...e,...n}}function a2(e){var r,i;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(i=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:i.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var l2=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ft=l2.reduce((e,t)=>{const n=wy(`Primitive.${t}`),r=A.forwardRef((i,o)=>{const{asChild:s,...a}=i,l=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),k.jsx(l,{...a,ref:o})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function u2(e,t){e&&ju.flushSync(()=>e.dispatchEvent(t))}function c2(e,t){return A.useReducer((n,r)=>t[n][r]??n,e)}var Bo=e=>{const{present:t,children:n}=e,r=f2(t),i=typeof n=="function"?n({present:r.isPresent}):A.Children.only(n),o=tn(r.ref,d2(i));return typeof n=="function"||r.isPresent?A.cloneElement(i,{ref:o}):null};Bo.displayName="Presence";function f2(e){const[t,n]=A.useState(),r=A.useRef(null),i=A.useRef(e),o=A.useRef("none"),s=e?"mounted":"unmounted",[a,l]=c2(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return A.useEffect(()=>{const u=zo(r.current);o.current=a==="mounted"?u:"none"},[a]),en(()=>{const u=r.current,f=i.current;if(f!==e){const h=o.current,d=zo(u);e?l("MOUNT"):d==="none"||(u==null?void 0:u.display)==="none"?l("UNMOUNT"):l(f&&h!==d?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,l]),en(()=>{if(t){let u;const f=t.ownerDocument.defaultView??window,c=d=>{const p=zo(r.current).includes(CSS.escape(d.animationName));if(d.target===t&&p&&(l("ANIMATION_END"),!i.current)){const g=t.style.animationFillMode;t.style.animationFillMode="forwards",u=f.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=g)})}},h=d=>{d.target===t&&(o.current=zo(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",c),t.addEventListener("animationend",c),()=>{f.clearTimeout(u),t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",c),t.removeEventListener("animationend",c)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:A.useCallback(u=>{r.current=u?getComputedStyle(u):null,n(u)},[])}}function zo(e){return(e==null?void 0:e.animationName)||"none"}function d2(e){var r,i;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(i=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:i.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var h2=A[" useId ".trim().toString()]||(()=>{}),p2=0;function Uo(e){const[t,n]=A.useState(h2());return en(()=>{n(r=>r??String(p2++))},[e]),e||(t?`radix-${t}`:"")}var jo="Collapsible",[m2]=vy(jo),[g2,tu]=m2(jo),Sy=A.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:i,disabled:o,onOpenChange:s,...a}=e,[l,u]=by({prop:r,defaultProp:i??!1,onChange:s,caller:jo});return k.jsx(g2,{scope:n,disabled:o,contentId:Uo(),open:l,onOpenToggle:A.useCallback(()=>u(f=>!f),[u]),children:k.jsx(Ft.div,{"data-state":ru(l),"data-disabled":o?"":void 0,...a,ref:t})})});Sy.displayName=jo;var xy="CollapsibleTrigger",ky=A.forwardRef((e,t)=>{const{__scopeCollapsible:n,...r}=e,i=tu(xy,n);return k.jsx(Ft.button,{type:"button","aria-controls":i.contentId,"aria-expanded":i.open||!1,"data-state":ru(i.open),"data-disabled":i.disabled?"":void 0,disabled:i.disabled,...r,ref:t,onClick:Zt(e.onClick,i.onOpenToggle)})});ky.displayName=xy;var nu="CollapsibleContent",Ey=A.forwardRef((e,t)=>{const{forceMount:n,...r}=e,i=tu(nu,e.__scopeCollapsible);return k.jsx(Bo,{present:n||i.open,children:({present:o})=>k.jsx(y2,{...r,ref:t,present:o})})});Ey.displayName=nu;var y2=A.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:r,children:i,...o}=e,s=tu(nu,n),[a,l]=A.useState(r),u=A.useRef(null),f=tn(t,u),c=A.useRef(0),h=c.current,d=A.useRef(0),m=d.current,p=s.open||a,g=A.useRef(p),y=A.useRef(void 0);return A.useEffect(()=>{const v=requestAnimationFrame(()=>g.current=!1);return()=>cancelAnimationFrame(v)},[]),en(()=>{const v=u.current;if(v){y.current=y.current||{transitionDuration:v.style.transitionDuration,animationName:v.style.animationName},v.style.transitionDuration="0s",v.style.animationName="none";const w=v.getBoundingClientRect();c.current=w.height,d.current=w.width,g.current||(v.style.transitionDuration=y.current.transitionDuration,v.style.animationName=y.current.animationName),l(r)}},[s.open,r]),k.jsx(Ft.div,{"data-state":ru(s.open),"data-disabled":s.disabled?"":void 0,id:s.contentId,hidden:!p,...o,ref:f,style:{"--radix-collapsible-content-height":h?`${h}px`:void 0,"--radix-collapsible-content-width":m?`${m}px`:void 0,...e.style},children:p&&i})});function ru(e){return e?"open":"closed"}var v2=Sy,b2=Ey;const iu=({restartConversation:e,...t})=>{var o,s;const{header:n}=me,{showInputModal:r}=Ka(),i=async a=>{a.stopPropagation(),r?r({title:"Create New Conversation",description:"This will clear the current conversation and start a new one.",confirmButtonText:"New conversation",cancelButtonText:"Cancel"}).then(()=>e()):e()};return k.jsx(rT,{...t,...(s=(o=n==null?void 0:n.content)==null?void 0:o.actions)==null?void 0:s.icons,"aria-label":"Restart Conversation Button",tabIndex:0,role:"button",onClick:i})},ou=({onClick:e,...t})=>{const{header:n}=me,r=i=>{i.stopPropagation(),e==null||e()};return k.jsx(hp,{...t,...n.content.actions.icons,role:"button",tabIndex:0,"aria-label":"Close Chatbot Button",onClick:r,onKeyDown:i=>{i.key==="Enter"&&r(i)}})},w2=({onClick:e,...t})=>{const{header:n}=me,r=i=>{i.stopPropagation(),e==null||e()};return k.jsx(ap,{...t,...n.content.actions.icons,role:"button",tabIndex:0,"aria-label":"Show Recent Conversations Button",onClick:r,onKeyDown:i=>{i.key==="Enter"&&r(i)}})},gi=({icon:e,title:t,link:n,...r})=>{var s,a,l,u,f,c,h,d,m,p,g,y;const{header:i}=me,o=e??VA;return t?n?k.jsxs("a",{...r,...(a=(s=i.expandedContent)==null?void 0:s.descriptionItems)==null?void 0:a.container,href:n,target:"_blank",rel:"noreferrer noopener",children:[k.jsx(o,{...(u=(l=i.expandedContent)==null?void 0:l.descriptionItems)==null?void 0:u.icon}),k.jsx("p",{...(c=(f=i.expandedContent)==null?void 0:f.descriptionItems)==null?void 0:c.link,children:t})]}):k.jsxs("div",{...r,...(d=(h=i.expandedContent)==null?void 0:h.descriptionItems)==null?void 0:d.container,children:[k.jsx(o,{...(p=(m=i.expandedContent)==null?void 0:m.descriptionItems)==null?void 0:p.icon}),k.jsx("p",{...(y=(g=i.expandedContent)==null?void 0:g.descriptionItems)==null?void 0:y.text,children:t})]}):null},S2=({soundOn:e,toggleSound:t})=>{const n=o=>{o.stopPropagation(),t==null||t()},{header:r}=me,i=e?dp:cT;return k.jsx("div",{role:"button",tabIndex:0,onClick:n,onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),n(o))},title:e?"Disable chat sounds":"Enable chat sounds",...r.content.actions.icons,children:k.jsx(i,{size:16})})},Cy=({defaultOpen:e,closeWindow:t,configuration:n,restartConversation:r,showConversationHistory:i,disabled:o,soundOn:s,toggleSound:a,clientId:l,...u})=>{var p,g,y,v,w,E,S,C,I,M,P,T,O,U,F,L,R,N,j,B,W,b,_,H;const{header:f}=me,[c,h]=D.useState(e),d=!!((p=n.email)!=null&&p.title)||!!((g=n.phone)!=null&&g.title)||!!((y=n.website)!=null&&y.title)||!!((v=n.termsOfService)!=null&&v.link)||!!((w=n.privacyPolicy)!=null&&w.link),m=d&&!o;return k.jsxs(v2,{open:m?c:!1,onOpenChange:m?h:void 0,"data-disabled":m?void 0:"",...f.container,...u,children:[k.jsxs(ky,{"aria-label":"Expand Header Button",...f.content.container,children:[k.jsx("div",{...f.content.conversationHistory,children:i&&!c&&k.jsx(w2,{onClick:i})}),k.jsx(En,{userId:l,src:n.botAvatar,...f.content.avatar,children:n.botName||"Bot"}),k.jsx("h2",{...f.content.title,children:n.botName||"Bot"}),n.botDescription&&k.jsx("p",{...f.content.description,children:n.botDescription}),k.jsxs("div",{...f.content.actions.container,children:[n.soundEnabled&&s!==void 0&&a&&k.jsx(S2,{soundOn:s,toggleSound:a}),r&&k.jsx(iu,{restartConversation:r}),t&&k.jsx(ou,{onClick:t})]})]}),d&&k.jsxs(b2,{...f.expandedContent.container,children:[k.jsxs("div",{"data-links":"",...f.expandedContent.group,children:[k.jsx(gi,{"data-email":"",icon:ZA,title:(E=n.email)==null?void 0:E.title,link:(C=(S=n.email)==null?void 0:S.link)!=null&&C.startsWith("mailto:")?(I=n.email)==null?void 0:I.link:`mailto:${(M=n.email)==null?void 0:M.link}`}),k.jsx(gi,{"data-phone":"",icon:tT,title:(P=n.phone)==null?void 0:P.title,link:(O=(T=n.phone)==null?void 0:T.link)!=null&&O.startsWith("tel:")?(U=n.phone)==null?void 0:U.link:`tel:${(F=n.phone)==null?void 0:F.link}`}),k.jsx(gi,{"data-website":"",link:(L=n.website)==null?void 0:L.link,icon:YA,title:(R=n.website)==null?void 0:R.title})]}),k.jsxs("div",{"data-legal":"",...(N=f.expandedContent)==null?void 0:N.group,children:[((j=n.termsOfService)==null?void 0:j.link)&&k.jsx(gi,{"data-terms":"",link:(B=n.termsOfService)==null?void 0:B.link,icon:cp,title:(W=n.termsOfService)==null?void 0:W.title}),((b=n.privacyPolicy)==null?void 0:b.link)&&k.jsx(gi,{"data-privacy":"",link:(_=n.privacyPolicy)==null?void 0:_.link,icon:QA,title:(H=n.privacyPolicy)==null?void 0:H.title})]})]})]})},su=D.memo(({...e})=>{const{typingIndicator:t}=me;return k.jsx("div",{...e,...t==null?void 0:t.container,children:k.jsx("div",{...t==null?void 0:t.loader})})});su.displayName="TypingIndicator";const au=D.memo(D.forwardRef(({direction:e,block:t,disableInput:n,children:r,sender:i,id:o,authorId:s,status:a,renderers:l,isReadOnly:u,isLastDeliveredMessage:f,feedback:c,timestamp:h,metadata:d,sendMessage:m,addMessageFeedback:p,showAvatar:g},y)=>{const[v,w]=D.useState([]),{message:{container:E,deliveryStatus:S}}=me;return g=g??e==="incoming",k.jsx(qa.Provider,{value:{isLoading:v,setIsLoading:w},children:k.jsxs("div",{...E,className:ar(E==null?void 0:E.className,f&&(S==null?void 0:S.className)),"data-loaded":v.length===0,"data-disable-input":!!n,"data-direction":e,dir:"auto",ref:y,children:[e==="incoming"&&g&&k.jsx(Ay,{authorId:s,sender:i}),t&&k.jsx(Dn,{block:{...t,isReadOnly:u,direction:e,timestamp:h,sender:i,feedback:c,messageId:o,status:a,metadata:d,sendMessage:m,addMessageFeedback:p},renderers:l}),e==="outgoing"&&g&&k.jsx(Ay,{authorId:s,sender:i}),r]})})})),Ay=({authorId:e,sender:t})=>{const{message:{avatar:n}}=me,[r,i]=D.useState("idle"),o=Ju(e??"",15);return k.jsxs(fs,{"data-color":o,"data-loading-status":r,...n==null?void 0:n.container,children:[k.jsx(ds,{...n==null?void 0:n.image,onLoadingStatusChange:i,src:t==null?void 0:t.avatar}),k.jsxs(hs,{...n==null?void 0:n.fallback,children:[t==null?void 0:t.name[0]," "]})]})};function x2({botAvatar:e,botDescription:t,botName:n}){const{messageList:{marquee:r}}=me;return k.jsxs("li",{...r.container,children:[k.jsx(En,{src:e,...r.avatar,children:(n||"Bot").slice(0,1)}),k.jsxs("div",{...r.content,children:[k.jsx("h1",{...r.title,children:n||"Bot"}),k.jsx("p",{...r.description,children:t})]})]})}let lu=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,n)=>(n&=63,n<36?t+=n.toString(36):n<62?t+=(n-26).toString(36).toUpperCase():n>62?t+="-":t+="_",t),"");/*!---------------------------------------------------------------------------------------------
323
+ `&&r++}}return[t,n]}class ty extends Event{constructor(t,n){var r,i;super(t),this.code=(r=n==null?void 0:n.code)!=null?r:void 0,this.message=(i=n==null?void 0:n.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,n,r){return r(ny(this),n)}[Symbol.for("Deno.customInspect")](t,n){return t(ny(this),n)}}function $N(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function Vl(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(Vl).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${Vl(e.cause)}`:e.message:`${e}`}function ny(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var ry=e=>{throw TypeError(e)},Wl=(e,t,n)=>t.has(e)||ry("Cannot "+n),be=(e,t,n)=>(Wl(e,t,"read from private field"),n?n.call(e):t.get(e)),Ke=(e,t,n)=>t.has(e)?ry("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Le=(e,t,n,r)=>(Wl(e,t,"write to private field"),t.set(e,n),n),Qt=(e,t,n)=>(Wl(e,t,"access private method"),n),dt,_n,lr,Po,Lo,fi,ur,di,pn,cr,fr,dr,hi,Lt,ql,Yl,Kl,iy,Gl,Ql,pi,Zl,Jl;class Fo extends EventTarget{constructor(t,n){var r,i;super(),Ke(this,Lt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Ke(this,dt),Ke(this,_n),Ke(this,lr),Ke(this,Po),Ke(this,Lo),Ke(this,fi),Ke(this,ur),Ke(this,di,null),Ke(this,pn),Ke(this,cr),Ke(this,fr,null),Ke(this,dr,null),Ke(this,hi,null),Ke(this,Yl,async o=>{var s;be(this,cr).reset();const{body:a,redirected:l,status:u,headers:f}=o;if(u===204){Qt(this,Lt,pi).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?Le(this,lr,new URL(o.url)):Le(this,lr,void 0),u!==200){Qt(this,Lt,pi).call(this,`Non-200 status code (${u})`,u);return}if(!(f.get("content-type")||"").startsWith("text/event-stream")){Qt(this,Lt,pi).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(be(this,dt)===this.CLOSED)return;Le(this,dt,this.OPEN);const c=new Event("open");if((s=be(this,hi))==null||s.call(this,c),this.dispatchEvent(c),typeof a!="object"||!a||!("getReader"in a)){Qt(this,Lt,pi).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}const h=new TextDecoder,d=a.getReader();let m=!0;do{const{done:p,value:g}=await d.read();g&&be(this,cr).feed(h.decode(g,{stream:!p})),p&&(m=!1,be(this,cr).reset(),Qt(this,Lt,Zl).call(this))}while(m)}),Ke(this,Kl,o=>{Le(this,pn,void 0),!(o.name==="AbortError"||o.type==="aborted")&&Qt(this,Lt,Zl).call(this,Vl(o))}),Ke(this,Gl,o=>{typeof o.id=="string"&&Le(this,di,o.id);const s=new MessageEvent(o.event||"message",{data:o.data,origin:be(this,lr)?be(this,lr).origin:be(this,_n).origin,lastEventId:o.id||""});be(this,dr)&&(!o.event||o.event==="message")&&be(this,dr).call(this,s),this.dispatchEvent(s)}),Ke(this,Ql,o=>{Le(this,fi,o)}),Ke(this,Jl,()=>{Le(this,ur,void 0),be(this,dt)===this.CONNECTING&&Qt(this,Lt,ql).call(this)});try{if(t instanceof URL)Le(this,_n,t);else if(typeof t=="string")Le(this,_n,new URL(t,BN()));else throw new Error("Invalid URL")}catch{throw $N("An invalid or illegal string was specified")}Le(this,cr,FN({onEvent:be(this,Gl),onRetry:be(this,Ql)})),Le(this,dt,this.CONNECTING),Le(this,fi,3e3),Le(this,Lo,(r=n==null?void 0:n.fetch)!=null?r:globalThis.fetch),Le(this,Po,(i=n==null?void 0:n.withCredentials)!=null?i:!1),Qt(this,Lt,ql).call(this)}get readyState(){return be(this,dt)}get url(){return be(this,_n).href}get withCredentials(){return be(this,Po)}get onerror(){return be(this,fr)}set onerror(t){Le(this,fr,t)}get onmessage(){return be(this,dr)}set onmessage(t){Le(this,dr,t)}get onopen(){return be(this,hi)}set onopen(t){Le(this,hi,t)}addEventListener(t,n,r){const i=n;super.addEventListener(t,i,r)}removeEventListener(t,n,r){const i=n;super.removeEventListener(t,i,r)}close(){be(this,ur)&&clearTimeout(be(this,ur)),be(this,dt)!==this.CLOSED&&(be(this,pn)&&be(this,pn).abort(),Le(this,dt,this.CLOSED),Le(this,pn,void 0))}}dt=new WeakMap,_n=new WeakMap,lr=new WeakMap,Po=new WeakMap,Lo=new WeakMap,fi=new WeakMap,ur=new WeakMap,di=new WeakMap,pn=new WeakMap,cr=new WeakMap,fr=new WeakMap,dr=new WeakMap,hi=new WeakMap,Lt=new WeakSet,ql=function(){Le(this,dt,this.CONNECTING),Le(this,pn,new AbortController),be(this,Lo)(be(this,_n),Qt(this,Lt,iy).call(this)).then(be(this,Yl)).catch(be(this,Kl))},Yl=new WeakMap,Kl=new WeakMap,iy=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...be(this,di)?{"Last-Event-ID":be(this,di)}:void 0},cache:"no-store",signal:(e=be(this,pn))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Gl=new WeakMap,Ql=new WeakMap,pi=function(e,t){var n;be(this,dt)!==this.CLOSED&&Le(this,dt,this.CLOSED);const r=new ty("error",{code:t,message:e});(n=be(this,fr))==null||n.call(this,r),this.dispatchEvent(r)},Zl=function(e,t){var n;if(be(this,dt)===this.CLOSED)return;Le(this,dt,this.CONNECTING);const r=new ty("error",{code:t,message:e});(n=be(this,fr))==null||n.call(this,r),this.dispatchEvent(r),Le(this,ur,setTimeout(be(this,Jl),be(this,fi)))},Jl=new WeakMap,Fo.CONNECTING=0,Fo.OPEN=1,Fo.CLOSED=2;function BN(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}async function zN(e){var t;const n=await e.clone().json();if((t=n==null?void 0:n.id)!=null&&t.startsWith("err_")){const r=new Error(n.message);throw r.id=n.id,r.code=n.code,r.type=n.type,r}return e}const oy=()=>{const e={};return{on:(t,n)=>{var r;return e[t]||(e[t]=new Set),(r=e[t])==null||r.add(n),()=>{var i;return(i=e[t])==null?void 0:i.delete(n)}},emit:(t,n)=>{var r,i;(r=e[t])==null||r.forEach(o=>o(n)),(i=e["*"])==null||i.forEach(o=>o({type:t,payload:n}))}}},Ue=e=>e.data,sy=10,ay=3e3,UN="60000",jN={throwOnError:!0},HN=({conversationId:e,userToken:t,clientId:n,apiUrl:r,adminSecret:i})=>{let o=0,s=null;const a=oy(),l=()=>{s&&s.close();const u=`${`${r||Pe.getConfig().baseUrl}/${n}`}/initialize${e?`?conversationId=${e}`:""}`,f={...i?{"x-admin-secret":i}:{},...t?{"x-user-key":t}:{}};s=uy(u,f),s.addEventListener("open",()=>a.emit("open")),s.addEventListener("error",c=>{o<sy?(o++,setTimeout(()=>l(),ay)):a.emit("error",c)}),s.addEventListener("message",c=>{const h=ly(c.data);a.emit(h.type,h.data)})};return l(),a.on},VN=({userKey:e,clientId:t,apiUrl:n,customHeaders:r,advancedOptions:i})=>{const o={"x-user-key":e,...r},s=`${n||Pe.getConfig().baseUrl}/${t}`,a={...jN,baseUrl:s};return Pe.interceptors.response._fns.length===0&&Pe.interceptors.response.use(zN),{createConversation:()=>yN({...a,headers:o,body:{}}).then(Ue),getConversation:({conversationId:l})=>mN({...a,headers:o,path:{id:l}}).then(Ue),deleteConversation:({conversationId:l})=>pN({...a,headers:o,path:{id:l}}).then(Ue),listConversations:({nextToken:l})=>gN({...a,headers:o,query:{nextToken:l}}).then(Ue),listConversationMessages:({conversationId:l,nextToken:u})=>vN({...a,headers:o,path:{id:l},query:{nextToken:u}}).then(Ue),addParticipant:({conversationId:l,userId:u})=>wN({...a,headers:o,path:{id:l},body:{userId:u}}).then(Ue),removeParticipant:({conversationId:l,userId:u})=>SN({...a,headers:o,path:{id:l,userId:u}}).then(Ue),getParticipant:({conversationId:l,userId:u})=>xN({...a,headers:o,path:{id:l,userId:u}}).then(Ue),listParticipants:({conversationId:l,nextToken:u})=>bN({...a,headers:o,path:{id:l},query:{nextToken:u}}).then(Ue),createMessage:l=>AN({...a,headers:o,body:l}).then(Ue),updateMessage:({messageId:l,...u})=>CN({...a,headers:o,path:{id:l},body:u}).then(Ue),getMessage:({messageId:l})=>EN({...a,headers:o,path:{id:l}}).then(Ue),deleteMessage:({messageId:l})=>kN({...a,headers:o,path:{id:l}}).then(Ue),createFile:l=>LN({...a,headers:o,body:l}).then(Ue),getUser:()=>MN({...a,headers:o}).then(Ue),updateUser:l=>DN({...a,headers:o,body:l}).then(Ue),deleteUser:()=>ON({...a,headers:o}).then(Ue),createEvent:l=>PN({...a,headers:o,body:l}).then(Ue),getEvent:({eventId:l})=>_N({...a,headers:o,path:{id:l}}).then(Ue),addMessageFeedback:({messageId:l,...u})=>IN({...a,headers:o,path:{id:l},body:u}).then(Ue),removeMessageFeedback:({messageId:l})=>TN({...a,headers:o,path:{id:l}}).then(Ue),generateUserKey:({adminSecret:l,...u})=>NN({...a,headers:{"x-admin-secret":l},body:u}).then(Ue),listenConversation:({conversationId:l})=>{let u=0,f=null;const c=oy(),h=()=>{f&&f.close();const d=`${s}/conversations/${l}/listen`,m=i==null?void 0:i.eventSource;f=m?m({url:d,headers:o}):uy(d,o),f.addEventListener("open",()=>c.emit("open")),f.addEventListener("error",p=>{u<sy?(u++,setTimeout(()=>h(),ay)):c.emit("error",p)}),f.addEventListener("message",p=>{const g=ly(p.data);c.emit(g.type,g.data)})};return h(),c.on}}},ly=e=>{try{return JSON.parse(e)}catch{return e}},uy=(e,t)=>new Fo(e,{fetch:(n,r)=>fetch(n,{...r,headers:{...r==null?void 0:r.headers,...t,timeout:UN}})}),WN=async({apiUrl:e,clientId:t,adminSecret:n,clientHeaders:r,emitter:i,conversationId:o,userToken:s})=>new Promise(a=>{const l=HN({apiUrl:e,clientId:t,userToken:s,conversationId:o,adminSecret:n}),u=l("init",({conversation:f,messages:c,participants:h,user:d})=>{const m=VN({clientId:t,apiUrl:e,userKey:d.userKey,customHeaders:r});m.createEvent({conversationId:f.id,payload:{type:"conversation_started",data:{}}}).then(({event:p})=>{var g,y;(y=(g=p.payload.data)==null?void 0:g.status)!=null&&y.isInitial&&i.emit("conversation",f.id)}),a({on:l,conversation:f,messages:c,participants:h,user:d,client:m,onCleanup:()=>{u()}})})}),qN={webchat:"#9C27B0",client:"#2196F3",store:"#4CAF50",events:"#00BCD4"},YN={debug:"#9E9E9E",info:"#2196F3",warn:"#FF9800",error:"#F44336"};let cy=!1,Xl=null,fy=Date.now();const KN=e=>{cy=e,fy=Date.now()},GN=e=>{Xl=e},QN=()=>{const e=Date.now()-fy,t=Math.floor(e/1e3),n=e%1e3;return`+${t}.${n.toString().padStart(3,"0")}s`},ZN=e=>e===void 0?"undefined":e===null?"null":e instanceof Error?{error:e.message,stack:e.stack}:e,Ro=e=>{const t=qN[e]||"#666",n=(r,...i)=>{if(!cy&&r!=="warn"&&r!=="error")return;const o=QN(),s=`%c[bp:${e}]%c ${o} %c${r.toUpperCase()}%c`,a=[`color: ${t}; font-weight: bold;`,"color: #999; font-size: 10px;",`color: ${YN[r]}; font-weight: bold;`,"color: inherit;"],l=i.map(ZN);if(console[r](s,...a,...l),Xl){const[u,f]=i;Xl(`debug:${e}:${r}`,{message:typeof u=="string"?u:void 0,...typeof f=="object"&&f!==null?f:{}})}};return{debug:(...r)=>n("debug",...r),info:(...r)=>n("info",...r),warn:(...r)=>n("warn",...r),error:(...r)=>n("error",...r)}},dy={webchat:Ro("webchat"),client:Ro("client"),store:Ro("store"),events:Ro("events")};function hy(){const[e,t]=D.useState(!1),n=D.useRef(null);return{state:e,setState:(r,i)=>{if(t(r),!r)return()=>{};if(n.current=new Date,!i)return()=>{};const o=setTimeout(()=>{const s=n.current;s&&new Date().getTime()-s.getTime()>i&&t(!1)},i+100);return()=>clearTimeout(o)}}}const mi=dy.webchat;function py({apiUrl:e="https://webchat.botpress.cloud",clientId:t,storageKey:n,storageLocation:r,adminSecret:i,clientHeaders:o,playNotificationSound:s,...a}){const l=Cp(n,r),u=l(O=>O.conversationId),f=l(O=>O.user),c=l(O=>O.setConversationId),h=l(O=>O.setUser),{state:d,setState:m}=hy(),{state:p,setState:g}=hy(),y=D.useMemo(()=>sc(),[]),[v,w]=D.useState("connecting"),[E,S]=D.useState(void 0),[C,I]=D.useState(void 0),M=D.useRef(null),P=e1(a.conversationId,a.userToken,u,f==null?void 0:f.userToken);D.useEffect(()=>{let O=!1;mi.info("starting initialization",{clientId:t,apiUrl:e,storageKey:n});const U=async()=>{var L;await T(P),O&&(mi.debug("initialization completed but effect was cleaned up, tearing down"),(L=M.current)==null||L.call(M),M.current=null)},F=Jw(t,e);if(F){mi.error("configuration error",F),I(F),w("error");return}return U(),()=>{O=!0,M.current&&(M.current(),M.current=null)}},[a.conversationId,a.userToken,t,e]);const T=async({conversationId:O,userToken:U})=>{var V;(V=M.current)==null||V.call(M),I(void 0),m(!1),g(!1),w("connecting");const{on:F,conversation:L,messages:R,participants:N,user:j,client:B,onCleanup:W}=await WN({apiUrl:e,clientId:t,clientHeaders:o,emitter:y,adminSecret:i,conversationId:O,userToken:U});S(B),c(L.id),h({userId:j.id,userToken:j.userKey});const b=Ep(L.id),_=R.reverse().map(ui).filter(Boolean);b.getState().setMessages(_);const H=Tp(L.id);H.getState().setParticipants(N);const x=[W,F("open",()=>{I(void 0),w("connected")}),F("error",Y=>{mi.error("connection error",{error:Y,conversationId:L.id}),I(q=>q||_r(Y)),w("error"),y.emit("error",new Error(`Connection to conversation lost: ${Y==null?void 0:Y.message}`))}),F("message_created",Y=>{const q=ui(Y);b.getState().saveMessage(q),j.id!==q.authorId&&(s==null||s(),m(!1),g(!1),y.emit("isTyping",{isTyping:!1,timeout:0})),y.emit("message",q)}),F("message_status_changed",Y=>{var q;Y.newStatus==="processing"&&b.getState().updateMessage((q=Y.message.metadata)==null?void 0:q.clientMessageId,{status:Y.newStatus})}),F("typing_stopped",()=>{m(!1),g(!1)}),F("typing_started",()=>{m(!0,5e3),g(!0,5e3),y.emit("isTyping",{isTyping:!0,timeout:5e3})}),F("participant_added",Y=>{H.getState().addParticipant(Y.participant),y.emit("participantAdded",Y.participant)}),F("participant_removed",Y=>{H.getState().removeParticipant(Y.participantId),y.emit("participantRemoved",Y.participantId)}),F("webchat_visibility",Y=>y.emit("webchatVisibility",Y.visibility)),F("webchat_config",Y=>y.emit("webchatConfig",Y.config)),F("custom",Y=>y.emit("customEvent",Y.event))];w("connected"),mi.info("client fully connected with event handlers ready",{conversationId:L.id}),M.current=()=>{x.forEach(Y=>Y())}};return{clientState:v,httpClient:E,error:C,activeConversationId:u,userCredentials:f,isTyping:d,isAwaitingResponse:p,openConversation:T,setAwaitingResponse:g,emitter:y,setError:I,setClientState:w}}const my=D.createContext(null);function $o(){const e=D.useContext(my);if(!e)throw new Error("useWebchatContext must be used inside <WebchatProvider>");return e}function gy({clientId:e,apiUrl:t,storageKey:n,storageLocation:r,adminSecret:i,clientHeaders:o,children:s,...a}){var S;const{clientState:l,httpClient:u,error:f,activeConversationId:c,userCredentials:h,isTyping:d,isAwaitingResponse:m,openConversation:p,setClientState:g,setError:y,setAwaitingResponse:v,emitter:w}=py({apiUrl:t,clientId:e,storageKey:n,storageLocation:r,adminSecret:i,clientHeaders:o,conversationId:a.conversationId,userToken:(S=a.userCredentials)==null?void 0:S.userToken}),E={client:u,clientState:l,setClientState:g,conversationId:c,userCredentials:h,error:f,setError:y,isTyping:d,isAwaitingResponse:m,openConversation:p,setAwaitingResponse:v,emitter:w};return k.jsx(my.Provider,{value:E,children:s})}const eu=({children:e,className:t,uploadFile:n,allowFileUpload:r,storageKey:i,conversationId:o,...s})=>{const{container:a}=me,l=Qn(g=>g.setMessageContainerRef),f=Ap(o||"default",i)(g=>g.uploadFile),[c,h]=D.useState(0),d=D.useRef(null);D.useEffect(()=>{l(d)},[d,l]);const m=D.useCallback(g=>{n&&(g.forEach(y=>f(y,n)),h(0))},[f,n]),{getRootProps:p}=_g({noClick:!0,noKeyboard:!0,onDrop:m,disabled:!(r&&n),onDragEnter:()=>h(g=>g+1),onDragLeave:()=>h(g=>g-1)});return k.jsxs("div",{...s,className:ar(a.className,t),...p(),ref:d,children:[k.jsxs("div",{"data-hover":c>0,...a.dropzone.overlay,children:["Drop files to upload",k.jsx(HA,{style:{width:"50px"}})]}),k.jsx(Lg,{children:e})]})};eu.displayName="Container";const yy=D.forwardRef(({onClick:e,imgUrl:t,...n},r)=>{const{fab:i}=me,{container:o,icon:s,image:a}=i??{};return t?k.jsx("img",{src:t,role:"button",tabIndex:0,...a,draggable:"false",onClick:e}):k.jsx("div",{...n,...o,ref:r,onClick:e,children:k.jsx("div",{...s})})});yy.displayName="Fab";function Zt(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e==null||e(i),n===!1||!i.defaultPrevented)return t==null?void 0:t(i)}}function JN(e,t){const n=A.createContext(t),r=o=>{const{children:s,...a}=o,l=A.useMemo(()=>a,Object.values(a));return k.jsx(n.Provider,{value:l,children:s})};r.displayName=e+"Provider";function i(o){const s=A.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${o}\` must be used within \`${e}\``)}return[r,i]}function vy(e,t=[]){let n=[];function r(o,s){const a=A.createContext(s),l=n.length;n=[...n,s];const u=c=>{var y;const{scope:h,children:d,...m}=c,p=((y=h==null?void 0:h[e])==null?void 0:y[l])||a,g=A.useMemo(()=>m,Object.values(m));return k.jsx(p.Provider,{value:g,children:d})};u.displayName=o+"Provider";function f(c,h){var p;const d=((p=h==null?void 0:h[e])==null?void 0:p[l])||a,m=A.useContext(d);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${c}\` must be used within \`${o}\``)}return[u,f]}const i=()=>{const o=n.map(s=>A.createContext(s));return function(a){const l=(a==null?void 0:a[e])||o;return A.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return i.scopeName=e,[r,XN(i,...t)]}function XN(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(o){const s=r.reduce((a,{useScope:l,scopeName:u})=>{const c=l(o)[`__scope${u}`];return{...a,...c}},{});return A.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}var e2=A[" useInsertionEffect ".trim().toString()]||en;function by({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,o,s]=t2({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:i;{const f=A.useRef(e!==void 0);A.useEffect(()=>{const c=f.current;c!==a&&console.warn(`${r} is changing from ${c?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),f.current=a},[a,r])}const u=A.useCallback(f=>{var c;if(a){const h=n2(f)?f(e):f;h!==e&&((c=s.current)==null||c.call(s,h))}else o(f)},[a,e,o,s]);return[l,u]}function t2({defaultProp:e,onChange:t}){const[n,r]=A.useState(e),i=A.useRef(n),o=A.useRef(t);return e2(()=>{o.current=t},[t]),A.useEffect(()=>{var s;i.current!==n&&((s=o.current)==null||s.call(o,n),i.current=n)},[n,i]),[n,r,o]}function n2(e){return typeof e=="function"}function wy(e){const t=r2(e),n=A.forwardRef((r,i)=>{const{children:o,...s}=r,a=A.Children.toArray(o),l=a.find(o2);if(l){const u=l.props.children,f=a.map(c=>c===l?A.Children.count(u)>1?A.Children.only(null):A.isValidElement(u)?u.props.children:null:c);return k.jsx(t,{...s,ref:i,children:A.isValidElement(u)?A.cloneElement(u,void 0,f):null})}return k.jsx(t,{...s,ref:i,children:o})});return n.displayName=`${e}.Slot`,n}function r2(e){const t=A.forwardRef((n,r)=>{const{children:i,...o}=n;if(A.isValidElement(i)){const s=a2(i),a=s2(o,i.props);return i.type!==A.Fragment&&(a.ref=r?is(r,s):s),A.cloneElement(i,a)}return A.Children.count(i)>1?A.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var i2=Symbol("radix.slottable");function o2(e){return A.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===i2}function s2(e,t){const n={...t};for(const r in t){const i=e[r],o=t[r];/^on[A-Z]/.test(r)?i&&o?n[r]=(...a)=>{const l=o(...a);return i(...a),l}:i&&(n[r]=i):r==="style"?n[r]={...i,...o}:r==="className"&&(n[r]=[i,o].filter(Boolean).join(" "))}return{...e,...n}}function a2(e){var r,i;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(i=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:i.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var l2=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ft=l2.reduce((e,t)=>{const n=wy(`Primitive.${t}`),r=A.forwardRef((i,o)=>{const{asChild:s,...a}=i,l=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),k.jsx(l,{...a,ref:o})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function u2(e,t){e&&ju.flushSync(()=>e.dispatchEvent(t))}function c2(e,t){return A.useReducer((n,r)=>t[n][r]??n,e)}var Bo=e=>{const{present:t,children:n}=e,r=f2(t),i=typeof n=="function"?n({present:r.isPresent}):A.Children.only(n),o=tn(r.ref,d2(i));return typeof n=="function"||r.isPresent?A.cloneElement(i,{ref:o}):null};Bo.displayName="Presence";function f2(e){const[t,n]=A.useState(),r=A.useRef(null),i=A.useRef(e),o=A.useRef("none"),s=e?"mounted":"unmounted",[a,l]=c2(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return A.useEffect(()=>{const u=zo(r.current);o.current=a==="mounted"?u:"none"},[a]),en(()=>{const u=r.current,f=i.current;if(f!==e){const h=o.current,d=zo(u);e?l("MOUNT"):d==="none"||(u==null?void 0:u.display)==="none"?l("UNMOUNT"):l(f&&h!==d?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,l]),en(()=>{if(t){let u;const f=t.ownerDocument.defaultView??window,c=d=>{const p=zo(r.current).includes(CSS.escape(d.animationName));if(d.target===t&&p&&(l("ANIMATION_END"),!i.current)){const g=t.style.animationFillMode;t.style.animationFillMode="forwards",u=f.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=g)})}},h=d=>{d.target===t&&(o.current=zo(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",c),t.addEventListener("animationend",c),()=>{f.clearTimeout(u),t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",c),t.removeEventListener("animationend",c)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:A.useCallback(u=>{r.current=u?getComputedStyle(u):null,n(u)},[])}}function zo(e){return(e==null?void 0:e.animationName)||"none"}function d2(e){var r,i;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(i=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:i.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var h2=A[" useId ".trim().toString()]||(()=>{}),p2=0;function Uo(e){const[t,n]=A.useState(h2());return en(()=>{n(r=>r??String(p2++))},[e]),e||(t?`radix-${t}`:"")}var jo="Collapsible",[m2]=vy(jo),[g2,tu]=m2(jo),Sy=A.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:i,disabled:o,onOpenChange:s,...a}=e,[l,u]=by({prop:r,defaultProp:i??!1,onChange:s,caller:jo});return k.jsx(g2,{scope:n,disabled:o,contentId:Uo(),open:l,onOpenToggle:A.useCallback(()=>u(f=>!f),[u]),children:k.jsx(Ft.div,{"data-state":ru(l),"data-disabled":o?"":void 0,...a,ref:t})})});Sy.displayName=jo;var xy="CollapsibleTrigger",ky=A.forwardRef((e,t)=>{const{__scopeCollapsible:n,...r}=e,i=tu(xy,n);return k.jsx(Ft.button,{type:"button","aria-controls":i.contentId,"aria-expanded":i.open||!1,"data-state":ru(i.open),"data-disabled":i.disabled?"":void 0,disabled:i.disabled,...r,ref:t,onClick:Zt(e.onClick,i.onOpenToggle)})});ky.displayName=xy;var nu="CollapsibleContent",Ey=A.forwardRef((e,t)=>{const{forceMount:n,...r}=e,i=tu(nu,e.__scopeCollapsible);return k.jsx(Bo,{present:n||i.open,children:({present:o})=>k.jsx(y2,{...r,ref:t,present:o})})});Ey.displayName=nu;var y2=A.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:r,children:i,...o}=e,s=tu(nu,n),[a,l]=A.useState(r),u=A.useRef(null),f=tn(t,u),c=A.useRef(0),h=c.current,d=A.useRef(0),m=d.current,p=s.open||a,g=A.useRef(p),y=A.useRef(void 0);return A.useEffect(()=>{const v=requestAnimationFrame(()=>g.current=!1);return()=>cancelAnimationFrame(v)},[]),en(()=>{const v=u.current;if(v){y.current=y.current||{transitionDuration:v.style.transitionDuration,animationName:v.style.animationName},v.style.transitionDuration="0s",v.style.animationName="none";const w=v.getBoundingClientRect();c.current=w.height,d.current=w.width,g.current||(v.style.transitionDuration=y.current.transitionDuration,v.style.animationName=y.current.animationName),l(r)}},[s.open,r]),k.jsx(Ft.div,{"data-state":ru(s.open),"data-disabled":s.disabled?"":void 0,id:s.contentId,hidden:!p,...o,ref:f,style:{"--radix-collapsible-content-height":h?`${h}px`:void 0,"--radix-collapsible-content-width":m?`${m}px`:void 0,...e.style},children:p&&i})});function ru(e){return e?"open":"closed"}var v2=Sy,b2=Ey;const iu=({restartConversation:e,...t})=>{var o,s;const{header:n}=me,{showInputModal:r}=Ka(),i=async a=>{a.stopPropagation(),r?r({title:"Create New Conversation",description:"This will clear the current conversation and start a new one.",confirmButtonText:"New conversation",cancelButtonText:"Cancel"}).then(()=>e()):e()};return k.jsx(rT,{...t,...(s=(o=n==null?void 0:n.content)==null?void 0:o.actions)==null?void 0:s.icons,"aria-label":"Restart Conversation Button",tabIndex:0,role:"button",onClick:i})},ou=({onClick:e,...t})=>{const{header:n}=me,r=i=>{i.stopPropagation(),e==null||e()};return k.jsx(hp,{...t,...n.content.actions.icons,role:"button",tabIndex:0,"aria-label":"Close Chatbot Button",onClick:r,onKeyDown:i=>{i.key==="Enter"&&r(i)}})},w2=({onClick:e,...t})=>{const{header:n}=me,r=i=>{i.stopPropagation(),e==null||e()};return k.jsx(ap,{...t,...n.content.actions.icons,role:"button",tabIndex:0,"aria-label":"Show Recent Conversations Button",onClick:r,onKeyDown:i=>{i.key==="Enter"&&r(i)}})},gi=({icon:e,title:t,link:n,...r})=>{var s,a,l,u,f,c,h,d,m,p,g,y;const{header:i}=me,o=e??VA;return t?n?k.jsxs("a",{...r,...(a=(s=i.expandedContent)==null?void 0:s.descriptionItems)==null?void 0:a.container,href:n,target:"_blank",rel:"noreferrer noopener",children:[k.jsx(o,{...(u=(l=i.expandedContent)==null?void 0:l.descriptionItems)==null?void 0:u.icon}),k.jsx("p",{...(c=(f=i.expandedContent)==null?void 0:f.descriptionItems)==null?void 0:c.link,children:t})]}):k.jsxs("div",{...r,...(d=(h=i.expandedContent)==null?void 0:h.descriptionItems)==null?void 0:d.container,children:[k.jsx(o,{...(p=(m=i.expandedContent)==null?void 0:m.descriptionItems)==null?void 0:p.icon}),k.jsx("p",{...(y=(g=i.expandedContent)==null?void 0:g.descriptionItems)==null?void 0:y.text,children:t})]}):null},S2=({soundOn:e,toggleSound:t})=>{const n=o=>{o.stopPropagation(),t==null||t()},{header:r}=me,i=e?dp:cT;return k.jsx("div",{role:"button",tabIndex:0,onClick:n,onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),n(o))},title:e?"Disable chat sounds":"Enable chat sounds",...r.content.actions.icons,children:k.jsx(i,{size:16})})},Cy=({defaultOpen:e,closeWindow:t,configuration:n,restartConversation:r,showConversationHistory:i,disabled:o,soundOn:s,toggleSound:a,clientId:l,...u})=>{var p,g,y,v,w,E,S,C,I,M,P,T,O,U,F,L,R,N,j,B,W,b,_,H;const{header:f}=me,[c,h]=D.useState(e),d=!!((p=n.email)!=null&&p.title)||!!((g=n.phone)!=null&&g.title)||!!((y=n.website)!=null&&y.title)||!!((v=n.termsOfService)!=null&&v.link)||!!((w=n.privacyPolicy)!=null&&w.link),m=d&&!o;return k.jsxs(v2,{open:m?c:!1,onOpenChange:m?h:void 0,"data-disabled":m?void 0:"",...f.container,...u,children:[k.jsxs(ky,{"aria-label":"Expand Header Button",...f.content.container,children:[k.jsx("div",{...f.content.conversationHistory,children:i&&!c&&k.jsx(w2,{onClick:i})}),k.jsx(En,{userId:l,src:n.botAvatar,...f.content.avatar,children:n.botName||"Bot"}),k.jsx("h2",{...f.content.title,children:n.botName||"Bot"}),n.botDescription&&k.jsx("p",{...f.content.description,children:n.botDescription}),k.jsxs("div",{...f.content.actions.container,children:[n.soundEnabled&&s!==void 0&&a&&k.jsx(S2,{soundOn:s,toggleSound:a}),r&&k.jsx(iu,{restartConversation:r}),t&&k.jsx(ou,{onClick:t})]})]}),d&&k.jsxs(b2,{...f.expandedContent.container,children:[k.jsxs("div",{"data-links":"",...f.expandedContent.group,children:[k.jsx(gi,{"data-email":"",icon:ZA,title:(E=n.email)==null?void 0:E.title,link:(C=(S=n.email)==null?void 0:S.link)!=null&&C.startsWith("mailto:")?(I=n.email)==null?void 0:I.link:`mailto:${(M=n.email)==null?void 0:M.link}`}),k.jsx(gi,{"data-phone":"",icon:tT,title:(P=n.phone)==null?void 0:P.title,link:(O=(T=n.phone)==null?void 0:T.link)!=null&&O.startsWith("tel:")?(U=n.phone)==null?void 0:U.link:`tel:${(F=n.phone)==null?void 0:F.link}`}),k.jsx(gi,{"data-website":"",link:(L=n.website)==null?void 0:L.link,icon:YA,title:(R=n.website)==null?void 0:R.title})]}),k.jsxs("div",{"data-legal":"",...(N=f.expandedContent)==null?void 0:N.group,children:[((j=n.termsOfService)==null?void 0:j.link)&&k.jsx(gi,{"data-terms":"",link:(B=n.termsOfService)==null?void 0:B.link,icon:cp,title:(W=n.termsOfService)==null?void 0:W.title}),((b=n.privacyPolicy)==null?void 0:b.link)&&k.jsx(gi,{"data-privacy":"",link:(_=n.privacyPolicy)==null?void 0:_.link,icon:QA,title:(H=n.privacyPolicy)==null?void 0:H.title})]})]})]})},su=D.memo(({...e})=>{const{typingIndicator:t}=me;return k.jsx("div",{...e,...t==null?void 0:t.container,children:k.jsx("div",{...t==null?void 0:t.loader})})});su.displayName="TypingIndicator";const au=D.memo(D.forwardRef(({direction:e,block:t,disableInput:n,children:r,sender:i,id:o,authorId:s,status:a,renderers:l,isReadOnly:u,isLastDeliveredMessage:f,feedback:c,timestamp:h,metadata:d,sendMessage:m,addMessageFeedback:p,showAvatar:g},y)=>{const[v,w]=D.useState([]),{message:{container:E,deliveryStatus:S}}=me;return g=g??e==="incoming",k.jsx(qa.Provider,{value:{isLoading:v,setIsLoading:w},children:k.jsxs("div",{...E,className:ar(E==null?void 0:E.className,f&&(S==null?void 0:S.className)),"data-loaded":v.length===0,"data-disable-input":!!n,"data-direction":e,dir:"auto",ref:y,children:[e==="incoming"&&g&&k.jsx(Ay,{authorId:s,sender:i}),t&&k.jsx(Dn,{block:{...t,isReadOnly:u,direction:e,timestamp:h,sender:i,feedback:c,messageId:o,status:a,metadata:d,sendMessage:m,addMessageFeedback:p},renderers:l}),e==="outgoing"&&g&&k.jsx(Ay,{authorId:s,sender:i}),r]})})})),Ay=({authorId:e,sender:t})=>{const{message:{avatar:n}}=me,[r,i]=D.useState("idle"),o=Ju(e??"",15);return k.jsxs(fs,{"data-color":o,"data-loading-status":r,...n==null?void 0:n.container,children:[k.jsx(ds,{...n==null?void 0:n.image,onLoadingStatusChange:i,src:t==null?void 0:t.avatar}),k.jsxs(hs,{...n==null?void 0:n.fallback,children:[t==null?void 0:t.name[0]," "]})]})};function x2({botAvatar:e,botDescription:t,botName:n}){const{messageList:{marquee:r}}=me;return k.jsxs("li",{...r.container,children:[k.jsx(En,{src:e,...r.avatar,children:(n||"Bot").slice(0,1)}),k.jsxs("div",{...r.content,children:[k.jsx("h1",{...r.title,children:n||"Bot"}),k.jsx("p",{...r.description,children:t})]})]})}let lu=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,n)=>(n&=63,n<36?t+=n.toString(36):n<62?t+=(n-26).toString(36).toUpperCase():n>62?t+="-":t+="_",t),"");/*!---------------------------------------------------------------------------------------------
324
324
  * Copyright (c) StackBlitz. All rights reserved.
325
325
  * Licensed under the MIT License. See License.txt in the project root for license information.
326
326
  *--------------------------------------------------------------------------------------------*/const k2={damping:.7,stiffness:.05,mass:1.25},E2=70,C2=1e3/60,A2=350;let Ho=!1;(Vv=globalThis.document)==null||Vv.addEventListener("mousedown",()=>{Ho=!0}),(Wv=globalThis.document)==null||Wv.addEventListener("mouseup",()=>{Ho=!1}),(qv=globalThis.document)==null||qv.addEventListener("click",()=>{Ho=!1});const T2=(e={})=>{const[t,n]=D.useState(!1),[r,i]=D.useState(e.initial!==!1),[o,s]=D.useState(!1),a=D.useRef(null);a.current=e;const l=D.useCallback(()=>{var E;if(!Ho)return!1;const v=window.getSelection();if(!v||!v.rangeCount)return!1;const w=v.getRangeAt(0);return w.commonAncestorContainer.contains(g.current)||((E=g.current)==null?void 0:E.contains(w.commonAncestorContainer))},[]),u=D.useCallback(v=>{c.isAtBottom=v,i(v)},[]),f=D.useCallback(v=>{c.escapedFromLock=v,n(v)},[]),c=D.useMemo(()=>{let v;return{escapedFromLock:t,isAtBottom:r,resizeDifference:0,accumulated:0,velocity:0,listeners:new Set,get scrollTop(){var w;return((w=g.current)==null?void 0:w.scrollTop)??0},set scrollTop(w){g.current&&(g.current.scrollTop=w,c.ignoreScrollToTop=g.current.scrollTop)},get targetScrollTop(){return!g.current||!y.current?0:g.current.scrollHeight-1-g.current.clientHeight},get calculatedTargetScrollTop(){if(!g.current||!y.current)return 0;const{targetScrollTop:w}=this;if(!e.targetScrollTop)return w;if((v==null?void 0:v.targetScrollTop)===w)return v.calculatedScrollTop;const E=Math.max(Math.min(e.targetScrollTop(w,{scrollElement:g.current,contentElement:y.current}),w),0);return v={targetScrollTop:w,calculatedScrollTop:E},requestAnimationFrame(()=>{v=void 0}),E},get scrollDifference(){return this.calculatedTargetScrollTop-this.scrollTop},get isNearBottom(){return this.scrollDifference<=E2}}},[]),h=D.useCallback((v={})=>{var P;typeof v=="string"&&(v={animation:v}),v.preserveScrollPosition||u(!0);const w=Date.now()+(Number(v.wait)||0),E=cu(a.current,v.animation),{ignoreEscapes:S=!1}=v;let C,I=c.calculatedTargetScrollTop;v.duration instanceof Promise?v.duration.finally(()=>{C=Date.now()}):C=w+(v.duration??0);const M=async()=>{const T=new Promise(requestAnimationFrame).then(()=>{var L;if(!c.isAtBottom)return c.animation=void 0,!1;const{scrollTop:O}=c,U=performance.now(),F=(U-(c.lastTick??U))/C2;if(c.animation||(c.animation={behavior:E,promise:T,ignoreEscapes:S}),c.animation.behavior===E&&(c.lastTick=U),l()||w>Date.now())return M();if(O<Math.min(I,c.calculatedTargetScrollTop)){if(((L=c.animation)==null?void 0:L.behavior)===E){if(E==="instant")return c.scrollTop=c.calculatedTargetScrollTop,M();c.velocity=(E.damping*c.velocity+E.stiffness*c.scrollDifference)/E.mass,c.accumulated+=c.velocity*F,c.scrollTop+=c.accumulated,c.scrollTop!==O&&(c.accumulated=0)}return M()}return C>Date.now()?(I=c.calculatedTargetScrollTop,M()):(c.animation=void 0,c.scrollTop<c.calculatedTargetScrollTop?h({animation:cu(a.current,a.current.resize),ignoreEscapes:S,duration:Math.max(0,C-Date.now())||void 0}):c.isAtBottom)});return T.then(O=>(requestAnimationFrame(()=>{c.animation||(c.lastTick=void 0,c.velocity=0)}),O))};return v.wait!==!0&&(c.animation=void 0),((P=c.animation)==null?void 0:P.behavior)===E?c.animation.promise:M()},[u,l,c]),d=D.useCallback(()=>{f(!0),u(!1)},[f,u]),m=D.useCallback(({target:v})=>{if(v!==g.current)return;const{scrollTop:w,ignoreScrollToTop:E}=c;let{lastScrollTop:S=w}=c;c.lastScrollTop=w,c.ignoreScrollToTop=void 0,E&&E>w&&(S=E),s(c.isNearBottom),setTimeout(()=>{var M;if(c.resizeDifference||w===E)return;if(l()){f(!0),u(!1);return}const C=w>S,I=w<S;if((M=c.animation)!=null&&M.ignoreEscapes){c.scrollTop=S;return}I&&(f(!0),u(!1)),C&&f(!1),!c.escapedFromLock&&c.isNearBottom&&u(!0)},1)},[f,u,l,c]),p=D.useCallback(({target:v,deltaY:w})=>{var S;let E=v;for(;!["scroll","auto"].includes(getComputedStyle(E).overflow);){if(!E.parentElement)return;E=E.parentElement}E===g.current&&w<0&&g.current.scrollHeight>g.current.clientHeight&&!((S=c.animation)!=null&&S.ignoreEscapes)&&(f(!0),u(!1))},[f,u,c]),g=Ty(v=>{var w,E;(w=g.current)==null||w.removeEventListener("scroll",m),(E=g.current)==null||E.removeEventListener("wheel",p),v==null||v.addEventListener("scroll",m,{passive:!0}),v==null||v.addEventListener("wheel",p,{passive:!0})},[]),y=Ty(v=>{var E,S;if((E=c.resizeObserver)==null||E.disconnect(),!v)return;let w;c.resizeObserver=new ResizeObserver(([C])=>{const{height:I}=C.contentRect,M=I-(w??I);if(c.resizeDifference=M,c.scrollTop>c.targetScrollTop&&(c.scrollTop=c.targetScrollTop),s(c.isNearBottom),M>=0){const P=cu(a.current,w?a.current.resize:a.current.initial);h({animation:P,wait:!0,preserveScrollPosition:!0,duration:P==="instant"?void 0:A2})}else c.isNearBottom&&(f(!1),u(!0));w=I,requestAnimationFrame(()=>{setTimeout(()=>{c.resizeDifference===M&&(c.resizeDifference=0)},1)})}),(S=c.resizeObserver)==null||S.observe(v)},[]);return{contentRef:y,scrollRef:g,scrollToBottom:h,stopScroll:d,isAtBottom:r||o,isNearBottom:o,escapedFromLock:t,state:c}};function Ty(e,t){const n=D.useCallback(r=>(n.current=r,e(r)),t);return n}const uu=new Map;function cu(...e){const t={...k2};let n=!1;for(const i of e){if(i==="instant"){n=!0;continue}typeof i=="object"&&(n=!1,t.damping=i.damping??t.damping,t.stiffness=i.stiffness??t.stiffness,t.mass=i.mass??t.mass)}const r=JSON.stringify(t);return uu.has(r)||uu.set(r,Object.freeze(t)),n?"instant":uu.get(r)}const Iy=D.createContext(null),I2=typeof window<"u"?D.useLayoutEffect:D.useEffect;function Vo({instance:e,children:t,resize:n,initial:r,mass:i,damping:o,stiffness:s,targetScrollTop:a,contextRef:l,...u}){const f=D.useRef(null),c=A.useCallback((S,C)=>{const I=(E==null?void 0:E.targetScrollTop)??a;return(I==null?void 0:I(S,C))??S},[a]),h=T2({mass:i,damping:o,stiffness:s,resize:n,initial:r,targetScrollTop:c}),{scrollRef:d,contentRef:m,scrollToBottom:p,stopScroll:g,isAtBottom:y,escapedFromLock:v,state:w}=e??h,E=D.useMemo(()=>({scrollToBottom:p,stopScroll:g,scrollRef:d,isAtBottom:y,escapedFromLock:v,contentRef:m,state:w,get targetScrollTop(){return f.current},set targetScrollTop(S){f.current=S}}),[p,y,m,d,g,v,w]);return D.useImperativeHandle(l,()=>E,[E]),I2(()=>{d.current&&getComputedStyle(d.current).overflow==="visible"&&(d.current.style.overflow="auto")},[]),k.jsx(Iy.Provider,{value:E,children:k.jsx("div",{...u,children:typeof t=="function"?t(E):t})})}(function(e){function t({children:n,...r}){const i=Oy();return k.jsx("div",{ref:i.scrollRef,style:{height:"100%",width:"100%"},children:k.jsx("div",{...r,ref:i.contentRef,children:typeof n=="function"?n(i):n})})}e.Content=t})(Vo||(Vo={}));function Oy(){const e=D.useContext(Iy);if(!e)throw new Error("use-stick-to-bottom component context must be used within a StickToBottom component");return e}const fu=D.memo(({className:e,messages:t=[],isTyping:n,headerMessage:r,renderers:i,botAvatar:o,botDescription:s,botName:a,sendMessage:l,addMessageFeedback:u,showMarquee:f=!0,showDateSystemMessage:c=!0,showMessageStatus:h=!0,showIncomingMessageAvatar:d=!0,showOutgoingMessageAvatar:m=!1,...p})=>{var E;const{messageList:g}=me,y=D.useMemo(()=>c?xb(t):t,[t]),v=D.useMemo(()=>{var C;const S=y.filter(I=>I.direction==="outgoing"&&I.status!=="pending");return(C=S[S.length-1])==null?void 0:C.id},[y]),w=S=>{if(S.direction==="incoming")return d;if(S.direction==="outgoing")return m};return k.jsxs(Vo,{...p,resize:"smooth",initial:"instant",className:ar(g.container.className,e),children:[k.jsxs(Vo.Content,{className:g.viewPort.className,children:[r&&k.jsx("span",{...g.headerMessage,children:r}),f&&k.jsx(x2,{botAvatar:o,botDescription:s,botName:a}),y.map(S=>{var C;return k.jsx(au,{renderers:i,sendMessage:l,addMessageFeedback:u,isLastDeliveredMessage:h&&S.id===v,showAvatar:w(S),...S},((C=S.metadata)==null?void 0:C.clientMessageId)||S.id)}),n&&k.jsx(au,{id:lu(),renderers:i,sendMessage:l,direction:"incoming",timestamp:new Date,showAvatar:d,block:void 0,sender:((E=t.filter(S=>S.direction==="incoming").at(-1))==null?void 0:E.sender)??{name:a||"Bot",avatar:o},children:k.jsx(su,{})})]}),k.jsx(O2,{})]})}),O2=()=>{const{isAtBottom:e,scrollToBottom:t}=Oy(),{messageList:n}=me;return e?null:k.jsx("button",{className:n.scrollDownButton.className,onClick:()=>t()})};fu.displayName="MessageList";const My=({className:e,...t})=>{const{className:n}=me.loader;return k.jsx("div",{...t,className:ar(e,n)})};function Dy({error:e,restartConversation:t,closeWindow:n}){let r,i;const{error:o}=me;return e.type==="configuration"?(r="Configuration error",i=k.jsx(eT,{...o.icon})):e.type==="bot"?(r="Bot error",i=k.jsx(sp,{...o.icon})):e.type==="network"?(r="Network error",i=k.jsx(fT,{...o.icon})):e.type==="disconnected"?(r="Disconnected",i=k.jsx(aT,{...o.icon})):(r="Unexpected error",i=k.jsx(sp,{...o.icon})),k.jsx(M2,{error:e,title:r,icon:i,restartConversation:t,closeWindow:n})}function M2({error:e,title:t,icon:n,restartConversation:r,closeWindow:i}){const{error:o}=me;return k.jsxs("div",{...o.container,children:[k.jsxs("div",{...o.header.container,children:[`Webchat ${e.type} error`,k.jsxs("div",{...o.header.actions,children:[r&&k.jsx(iu,{restartConversation:r,style:{color:"white",backgroundColor:"transparent"}}),i&&k.jsx(ou,{onClick:i,style:{color:"white",backgroundColor:"transparent"}})]})]}),k.jsxs("div",{...o.content,children:[n,k.jsx("div",{...o.errorTitle,children:t}),k.jsx("div",{...o.errorMessage,children:e.message}),e.id&&k.jsx("div",{...o.id,children:e.id})]})]})}const yi=dy.webchat;async function D2(e,t){const{userId:n,conversationId:r,userToken:i,openConversation:o,setClientState:s,setError:a,emitter:l}=t;yi.warn("handleWebchatError",{userId:n,conversationId:r,type:e.type,message:e.message});const f=[{name:"startNewConversation",predicate:c=>c.message===$s||c.type==="ResourceNotFound",recover:async()=>o({userToken:i})},{name:"reopenConversation",predicate:c=>c.type==="network",recover:async()=>o({userToken:i,conversationId:r})}].find(c=>c.predicate(e));if(!f){yi.error("no recovery strategy found, setting error state",{userId:n,conversationId:r}),s("error"),a(e);return}yi.info("attempting recovery",{userId:n,conversationId:r,strategy:f.name});try{await Jf(f.recover,3,5e3),yi.info("recovery successful",{userId:n,conversationId:r}),a(void 0),s("connected")}catch(c){yi.error("recovery failed",{error:c,userId:n,conversationId:r}),a(_r(c)),s("error"),l.emit("error",c)}}function N2(e,t){return async(...n)=>{try{return await e(...n)}catch(r){await D2(_r(r),t)}}}function Ny(e,t){const n={};for(const[r,i]of Object.entries(e))n[r]=N2(i,t);return n}function _y({client:e,conversationId:t}){return{sendEvent:async(r,i)=>{if(!e||!t)throw new Error("Cannot send event: client or conversationId not available");await e.createEvent({conversationId:t,payload:{type:"custom",data:r},bindConversation:(i==null?void 0:i.bindConversation)??!0,bindUser:(i==null?void 0:i.bindUser)??!0})}}}function Py({client:e,conversationId:t,user:n}){return{uploadFile:async i=>{if(!e)throw new Error("Client not initialized");if(!t)throw new Error("No active conversation");if(!n)throw new Error("User not authenticated");const{size:o,name:s}=i,a=await Xw(i),l=new Date;l.setDate(l.getDate()+30);const{file:{uploadUrl:u,contentType:f,url:c,id:h}}=await e.createFile({size:o,key:`${lu(6)}-${i.name}`,accessPolicies:["public_content"],index:!1,tags:{source:"integration",integrationName:"webchat",conversation:t,user:n.userId},expiresAt:l.toISOString()});await fetch(u,{method:"PUT",headers:{"x-amz-tagging":"public=true","content-type":f},body:a});const d=f.split("/").shift()??"",m=Bf(d)?d:"file";return{fileUrl:c,name:s,type:m,fileId:h}}}}function Ly({client:e,conversationId:t,userId:n,setAwaitingResponse:r}){const i=Ep(t||"default"),o=i(d=>d.messages),s=i(d=>d.saveMessage),a=i(d=>d.updateMessage),l=i(d=>d.setMessages),u=i(d=>d.clearMessages);return{messages:o,sendMessage:async d=>{if(!e||!t||!n)throw console.log("Cannot send message: client, conversationId, or userId not available",e,t,n),new Error("Cannot send message: client, conversationId, or userId not available");r==null||r(!0);const m=lu(),p={id:m,createdAt:new Date().toISOString(),userId:n,conversationId:t,payload:d,metadata:{clientMessageId:m,delivered:!1}},g=ui(p);g.status="pending",s(g),await e.createMessage({conversationId:t,payload:d,metadata:{clientMessageId:m}})},setMessages:d=>{const m=d.map(p=>ui(p)).filter(Boolean);l(m)},clearMessages:u,saveMessageFeedback:async(d,m)=>{if(!e)throw new Error("Cannot update feedback: client not available");a(d,{feedback:m.value}),await e.addMessageFeedback({messageId:d,...m})}}}function Fy({client:e,conversationId:t}){const n=Tp(t||"default"),r=n(u=>u.participants),i=n(u=>u.setParticipants),o=n(u=>u.addParticipant),s=n(u=>u.removeParticipant),a=n(u=>u.clearParticipants);return{participants:r,setParticipants:i,fetchParticipants:async()=>{if(!e||!t)return;const{participants:u}=await e.listParticipants({conversationId:t});i(u)},clearParticipants:a,addParticipant:o,removeParticipant:s}}const Ry={chatMessageNotification:new URL("data:audio/ogg;base64,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",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:rs&&rs.tagName.toUpperCase()==="SCRIPT"&&rs.src||new URL("index.umd.cjs",document.baseURI).href).href};function $y({storageKey:e,soundEnabled:t}){const n=Ip(e||"bp-webchat"),r=n(u=>u.soundOn),i=n(u=>u.toggleSound),o=D.useRef(null),s=D.useRef(t??!1),a=D.useRef(r);D.useEffect(()=>{try{o.current=new Audio,o.current.preload="auto",o.current.src=Ry.chatMessageNotification,o.current.volume=.9}catch(u){console.error("Error loading sound effect:",u),o.current=null}},[]),D.useEffect(()=>{s.current=t??!1},[t]),D.useEffect(()=>{a.current=r},[r]);const l=D.useCallback(()=>{s.current&&a.current&&o.current&&o.current.play().catch(()=>{})},[]);return{soundOn:r,toggleSound:i,playNotificationSound:l}}function _2({apiUrl:e="https://webchat.botpress.cloud",clientId:t,storageKey:n,storageLocation:r,adminSecret:i,soundEnabled:o,clientHeaders:s,...a}){var N;const{soundOn:l,toggleSound:u,playNotificationSound:f}=$y({storageKey:n,soundEnabled:o}),{clientState:c,httpClient:h,error:d,activeConversationId:m,userCredentials:p,isTyping:g,isAwaitingResponse:y,openConversation:v,setAwaitingResponse:w,emitter:E,setError:S,setClientState:C}=py({apiUrl:e,clientId:t,storageKey:n,storageLocation:r,adminSecret:i,clientHeaders:s,conversationId:a.conversationId,userToken:(N=a.user)==null?void 0:N.userToken,playNotificationSound:f}),{messages:I,sendMessage:M,saveMessageFeedback:P}=Ly({client:h,conversationId:m,userId:p==null?void 0:p.userId,setAwaitingResponse:w}),{participants:T}=Fy({client:h,conversationId:m}),{uploadFile:O}=Py({client:h,conversationId:m,user:p}),{sendEvent:U}=_y({client:h,conversationId:m});if(c!=="connected"||!p||!m||!h)return{clientState:c,on:E.on,client:void 0,messages:[],conversationId:void 0,newConversation:j=>{v({conversationId:j,userToken:p==null?void 0:p.userToken}).catch(B=>{E.emit("error",B)})},user:void 0,isTyping:void 0,participants:[],toggleSound:u,soundOn:l,error:d,disableSendButton:y};const F={userId:p==null?void 0:p.userId,conversationId:m,userToken:p==null?void 0:p.userToken,openConversation:v,setClientState:C,setError:S,emitter:E},R={...Ny({sendMessage:async j=>M(j),sendEvent:U,uploadFile:O,addMessageFeedback:P},F),getUser:async()=>{const{user:j}=await h.getUser();return j},updateUser:async j=>{const{user:B}=await h.updateUser({name:j.name,pictureUrl:j.pictureUrl,userData:j.data});return B},listConversations:async()=>h.listConversations({})};return{clientState:"connected",on:E.on,client:R,messages:I,conversationId:m,newConversation:j=>{v({conversationId:j,userToken:p.userToken}).catch(B=>{E.emit("error",B)})},user:p,isTyping:g,participants:T,error:d,soundOn:l,toggleSound:u,disableSendButton:y}}const By=()=>{const{client:e,userCredentials:t}=$o();return e?{userCredentials:t,getUser:async()=>(await e.getUser()).user,updateUser:async i=>(await e.updateUser(i)).user}:{userCredentials:t,getUser:void 0,updateUser:void 0}};function zy(){const{client:e,conversationId:t,userCredentials:n,setAwaitingResponse:r,emitter:i,clientState:o,setClientState:s,setError:a,openConversation:l,error:u,isAwaitingResponse:f,isTyping:c}=$o(),{messages:h,sendMessage:d,saveMessageFeedback:m}=Ly({client:e,conversationId:t,userId:n==null?void 0:n.userId,setAwaitingResponse:r}),{participants:p}=Fy({client:e,conversationId:t}),{sendEvent:g}=_y({client:e,conversationId:t}),{uploadFile:y}=Py({client:e,conversationId:t,user:n}),v={userId:n==null?void 0:n.userId,userToken:n==null?void 0:n.userToken,conversationId:t,openConversation:l,setClientState:s,setError:a,emitter:i},w=Ny({sendMessage:d,saveMessageFeedback:m,sendEvent:g,uploadFile:y},v);return{conversationId:t,messages:h,participants:p,sendMessage:w.sendMessage,saveMessageFeedback:w.saveMessageFeedback,sendEvent:w.sendEvent,uploadFile:w.uploadFile,on:i.on,status:o,error:u,isAwaitingResponse:f,isTyping:c}}function Uy(){const{client:e,openConversation:t,userCredentials:n}=$o();return e?{listConversations:async()=>e.listConversations({}),openConversation:i=>t({conversationId:i,userToken:n==null?void 0:n.userToken})}:{listConversations:void 0,openConversation:i=>t({conversationId:i,userToken:n==null?void 0:n.userToken})}}const jy=0,Hy=1,Vy=2,Wy=3;var qy=Object.prototype.hasOwnProperty;function du(e,t){var n,r;if(e===t)return!0;if(e&&t&&(n=e.constructor)===t.constructor){if(n===Date)return e.getTime()===t.getTime();if(n===RegExp)return e.toString()===t.toString();if(n===Array){if((r=e.length)===t.length)for(;r--&&du(e[r],t[r]););return r===-1}if(!n||typeof e=="object"){r=0;for(n in e)if(qy.call(e,n)&&++r&&!qy.call(t,n)||!(n in t)||!du(e[n],t[n]))return!1;return Object.keys(t).length===r}}return e!==e&&t!==t}const Jt=new WeakMap,Xt=()=>{},rt=Xt(),hu=Object,we=e=>e===rt,Vt=e=>typeof e=="function",mn=(e,t)=>({...e,...t}),Yy=e=>Vt(e.then),pu={},Wo={},mu="undefined",vi=typeof window!=mu,gu=typeof document!=mu,P2=vi&&"Deno"in window,L2=()=>vi&&typeof window.requestAnimationFrame!=mu,Ky=(e,t)=>{const n=Jt.get(e);return[()=>!we(t)&&e.get(t)||pu,r=>{if(!we(t)){const i=e.get(t);t in Wo||(Wo[t]=i),n[5](t,mn(i,r),i||pu)}},n[6],()=>!we(t)&&t in Wo?Wo[t]:!we(t)&&e.get(t)||pu]};let yu=!0;const F2=()=>yu,[vu,bu]=vi&&window.addEventListener?[window.addEventListener.bind(window),window.removeEventListener.bind(window)]:[Xt,Xt],R2=()=>{const e=gu&&document.visibilityState;return we(e)||e!=="hidden"},$2=e=>(gu&&document.addEventListener("visibilitychange",e),vu("focus",e),()=>{gu&&document.removeEventListener("visibilitychange",e),bu("focus",e)}),B2=e=>{const t=()=>{yu=!0,e()},n=()=>{yu=!1};return vu("online",t),vu("offline",n),()=>{bu("online",t),bu("offline",n)}},z2={isOnline:F2,isVisible:R2},U2={initFocus:$2,initReconnect:B2},Gy=!D.useId,hr=!vi||P2,j2=e=>L2()?window.requestAnimationFrame(e):setTimeout(e,1),wu=hr?D.useEffect:D.useLayoutEffect,Su=typeof navigator<"u"&&navigator.connection,Qy=!hr&&Su&&(["slow-2g","2g"].includes(Su.effectiveType)||Su.saveData),qo=new WeakMap,H2=e=>hu.prototype.toString.call(e),xu=(e,t)=>e===`[object ${t}]`;let V2=0;const ku=e=>{const t=typeof e,n=H2(e),r=xu(n,"Date"),i=xu(n,"RegExp"),o=xu(n,"Object");let s,a;if(hu(e)===e&&!r&&!i){if(s=qo.get(e),s)return s;if(s=++V2+"~",qo.set(e,s),Array.isArray(e)){for(s="@",a=0;a<e.length;a++)s+=ku(e[a])+",";qo.set(e,s)}if(o){s="#";const l=hu.keys(e).sort();for(;!we(a=l.pop());)we(e[a])||(s+=a+":"+ku(e[a])+",");qo.set(e,s)}}else s=r?e.toJSON():t=="symbol"?e.toString():t=="string"?JSON.stringify(e):""+e;return s},Eu=e=>{if(Vt(e))try{e=e()}catch{e=""}const t=e;return e=typeof e=="string"?e:(Array.isArray(e)?e.length:e)?ku(e):"",[e,t]};let W2=0;const Cu=()=>++W2;async function Zy(...e){const[t,n,r,i]=e,o=mn({populateCache:!0,throwOnError:!0},typeof i=="boolean"?{revalidate:i}:i||{});let s=o.populateCache;const a=o.rollbackOnError;let l=o.optimisticData;const u=h=>typeof a=="function"?a(h):a!==!1,f=o.throwOnError;if(Vt(n)){const h=n,d=[],m=t.keys();for(const p of m)!/^\$(inf|sub)\$/.test(p)&&h(t.get(p)._k)&&d.push(p);return Promise.all(d.map(c))}return c(n);async function c(h){const[d]=Eu(h);if(!d)return;const[m,p]=Ky(t,d),[g,y,v,w]=Jt.get(t),E=()=>{const L=g[d];return(Vt(o.revalidate)?o.revalidate(m().data,h):o.revalidate!==!1)&&(delete v[d],delete w[d],L&&L[0])?L[0](Vy).then(()=>m().data):m().data};if(e.length<3)return E();let S=r,C,I=!1;const M=Cu();y[d]=[M,0];const P=!we(l),T=m(),O=T.data,U=T._c,F=we(U)?O:U;if(P&&(l=Vt(l)?l(F,O):l,p({data:l,_c:F})),Vt(S))try{S=S(F)}catch(L){C=L,I=!0}if(S&&Yy(S))if(S=await S.catch(L=>{C=L,I=!0}),M!==y[d][0]){if(I)throw C;return S}else I&&P&&u(C)&&(s=!0,p({data:F,_c:rt}));if(s&&!I)if(Vt(s)){const L=s(S,F);p({data:L,error:rt,_c:rt})}else p({data:S,error:rt,_c:rt});if(y[d][1]=Cu(),Promise.resolve(E()).then(()=>{p({_c:rt})}),I){if(f)throw C;return}return S}}const Jy=(e,t)=>{for(const n in e)e[n][0]&&e[n][0](t)},q2=(e,t)=>{if(!Jt.has(e)){const n=mn(U2,t),r=Object.create(null),i=Zy.bind(rt,e);let o=Xt;const s=Object.create(null),a=(f,c)=>{const h=s[f]||[];return s[f]=h,h.push(c),()=>h.splice(h.indexOf(c),1)},l=(f,c,h)=>{e.set(f,c);const d=s[f];if(d)for(const m of d)m(c,h)},u=()=>{if(!Jt.has(e)&&(Jt.set(e,[r,Object.create(null),Object.create(null),Object.create(null),i,l,a]),!hr)){const f=n.initFocus(setTimeout.bind(rt,Jy.bind(rt,r,jy))),c=n.initReconnect(setTimeout.bind(rt,Jy.bind(rt,r,Hy)));o=()=>{f&&f(),c&&c(),Jt.delete(e)}}};return u(),[e,i,u,o]}return[e,Jt.get(e)[4]]},Y2=(e,t,n,r,i)=>{const o=n.errorRetryCount,s=i.retryCount,a=~~((Math.random()+.5)*(1<<(s<8?s:8)))*n.errorRetryInterval;!we(o)&&s>o||setTimeout(r,a,i)},K2=du,[Xy,G2]=q2(new Map),Q2=mn({onLoadingSlow:Xt,onSuccess:Xt,onError:Xt,onErrorRetry:Y2,onDiscarded:Xt,revalidateOnFocus:!0,revalidateOnReconnect:!0,revalidateIfStale:!0,shouldRetryOnError:!0,errorRetryInterval:Qy?1e4:5e3,focusThrottleInterval:5*1e3,dedupingInterval:2*1e3,loadingTimeout:Qy?5e3:3e3,compare:K2,isPaused:()=>!1,cache:Xy,mutate:G2,fallback:{}},z2),Z2=(e,t)=>{const n=mn(e,t);if(t){const{use:r,fallback:i}=e,{use:o,fallback:s}=t;r&&o&&(n.use=r.concat(o)),i&&s&&(n.fallback=mn(i,s))}return n},J2=D.createContext({}),X2="$inf$",ev=vi&&window.__SWR_DEVTOOLS_USE__,e_=ev?window.__SWR_DEVTOOLS_USE__:[],t_=()=>{ev&&(window.__SWR_DEVTOOLS_REACT__=D)},n_=e=>Vt(e[1])?[e[0],e[1],e[2]||{}]:[e[0],null,(e[1]===null?e[2]:e[1])||{}],r_=()=>{const e=D.useContext(J2);return D.useMemo(()=>mn(Q2,e),[e])},i_=e=>(t,n,r)=>e(t,n&&((...o)=>{const[s]=Eu(t),[,,,a]=Jt.get(Xy);if(s.startsWith(X2))return n(...o);const l=a[s];return we(l)?n(...o):(delete a[s],l)}),r),o_=e_.concat(i_),s_=e=>function(...n){const r=r_(),[i,o,s]=n_(n),a=Z2(r,s);let l=e;const{use:u}=a,f=(u||[]).concat(o_);for(let c=f.length;c--;)l=f[c](l);return l(i,o||a.fetcher||null,a)},a_=(e,t,n)=>{const r=t[e]||(t[e]=[]);return r.push(n),()=>{const i=r.indexOf(n);i>=0&&(r[i]=r[r.length-1],r.pop())}};t_();const Au=D.use||(e=>{switch(e.status){case"pending":throw e;case"fulfilled":return e.value;case"rejected":throw e.reason;default:throw e.status="pending",e.then(t=>{e.status="fulfilled",e.value=t},t=>{e.status="rejected",e.reason=t}),e}}),Tu={dedupe:!0},tv=Promise.resolve(rt),l_=()=>Xt,u_=s_((e,t,n)=>{const{cache:r,compare:i,suspense:o,fallbackData:s,revalidateOnMount:a,revalidateIfStale:l,refreshInterval:u,refreshWhenHidden:f,refreshWhenOffline:c,keepPreviousData:h,strictServerPrefetchWarning:d}=n,[m,p,g,y]=Jt.get(r),[v,w]=Eu(e),E=D.useRef(!1),S=D.useRef(!1),C=D.useRef(v),I=D.useRef(t),M=D.useRef(n),P=()=>M.current,T=()=>P().isVisible()&&P().isOnline(),[O,U,F,L]=Ky(r,v),R=D.useRef({}).current,N=we(s)?we(n.fallback)?rt:n.fallback[v]:s,j=(J,ue)=>{for(const de in R){const fe=de;if(fe==="data"){if(!i(J[fe],ue[fe])&&(!we(J[fe])||!i(q,ue[fe])))return!1}else if(ue[fe]!==J[fe])return!1}return!0},B=!E.current,W=D.useMemo(()=>{const J=O(),ue=L(),de=Me=>{const je=mn(Me);return delete je._k,(()=>{if(!v||!t||P().isPaused())return!1;if(B&&!we(a))return a;const ae=we(N)?je.data:N;return we(ae)||l})()?{isValidating:!0,isLoading:!0,...je}:je},fe=de(J),Ae=J===ue?fe:de(ue);let Fe=fe;return[()=>{const Me=de(O());return j(Me,Fe)?(Fe.data=Me.data,Fe.isLoading=Me.isLoading,Fe.isValidating=Me.isValidating,Fe.error=Me.error,Fe):(Fe=Me,Me)},()=>Ae]},[r,v]),b=us.useSyncExternalStore(D.useCallback(J=>F(v,(ue,de)=>{j(de,ue)||J()}),[r,v]),W[0],W[1]),_=m[v]&&m[v].length>0,H=b.data,x=we(H)?N&&Yy(N)?Au(N):N:H,V=b.error,Y=D.useRef(x),q=h?we(H)?we(Y.current)?x:Y.current:H:x,Q=v&&we(x),X=D.useRef(null);!hr&&us.useSyncExternalStore(l_,()=>(X.current=!1,X),()=>(X.current=!0,X));const se=X.current;d&&se&&!o&&Q&&console.warn(`Missing pre-initiated data for serialized key "${v}" during server-side rendering. Data fetching should be initiated on the server and provided to SWR via fallback data. You can set "strictServerPrefetchWarning: false" to disable this warning.`);const G=!v||!t||P().isPaused()||_&&!we(V)?!1:B&&!we(a)?a:o?we(x)?!1:l:we(x)||l,te=we(b.isValidating)?G:b.isValidating,$=we(b.isLoading)?G:b.isLoading,ne=D.useCallback(async J=>{const ue=I.current;if(!v||!ue||S.current||P().isPaused())return!1;let de,fe,Ae=!0;const Fe=J||{},Me=!g[v]||!Fe.dedupe,je=()=>Gy?!S.current&&v===C.current&&E.current:v===C.current,ee={isValidating:!1,isLoading:!1},ae=()=>{U(ee)},z=()=>{const oe=g[v];oe&&oe[1]===fe&&delete g[v]},K={isValidating:!0};we(O().data)&&(K.isLoading=!0);try{if(Me&&(U(K),n.loadingTimeout&&we(O().data)&&setTimeout(()=>{Ae&&je()&&P().onLoadingSlow(v,n)},n.loadingTimeout),g[v]=[ue(w),Cu()]),[de,fe]=g[v],de=await de,Me&&setTimeout(z,n.dedupingInterval),!g[v]||g[v][1]!==fe)return Me&&je()&&P().onDiscarded(v),!1;ee.error=rt;const oe=p[v];if(!we(oe)&&(fe<=oe[0]||fe<=oe[1]||oe[1]===0))return ae(),Me&&je()&&P().onDiscarded(v),!1;const le=O().data;ee.data=i(le,de)?le:de,Me&&je()&&P().onSuccess(de,v,n)}catch(oe){z();const le=P(),{shouldRetryOnError:he}=le;le.isPaused()||(ee.error=oe,Me&&je()&&(le.onError(oe,v,le),(he===!0||Vt(he)&&he(oe))&&(!P().revalidateOnFocus||!P().revalidateOnReconnect||T())&&le.onErrorRetry(oe,v,le,He=>{const Ge=m[v];Ge&&Ge[0]&&Ge[0](Wy,He)},{retryCount:(Fe.retryCount||0)+1,dedupe:!0})))}return Ae=!1,ae(),!0},[v,r]),ge=D.useCallback((...J)=>Zy(r,C.current,...J),[]);if(wu(()=>{I.current=t,M.current=n,we(H)||(Y.current=H)}),wu(()=>{if(!v)return;const J=ne.bind(rt,Tu);let ue=0;P().revalidateOnFocus&&(ue=Date.now()+P().focusThrottleInterval);const fe=a_(v,m,(Ae,Fe={})=>{if(Ae==jy){const Me=Date.now();P().revalidateOnFocus&&Me>ue&&T()&&(ue=Me+P().focusThrottleInterval,J())}else if(Ae==Hy)P().revalidateOnReconnect&&T()&&J();else{if(Ae==Vy)return ne();if(Ae==Wy)return ne(Fe)}});return S.current=!1,C.current=v,E.current=!0,U({_k:w}),G&&(g[v]||(we(x)||hr?J():j2(J))),()=>{S.current=!0,fe()}},[v]),wu(()=>{let J;function ue(){const fe=Vt(u)?u(O().data):u;fe&&J!==-1&&(J=setTimeout(de,fe))}function de(){!O().error&&(f||P().isVisible())&&(c||P().isOnline())?ne(Tu).then(ue):ue()}return ue(),()=>{J&&(clearTimeout(J),J=-1)}},[u,f,c,v]),D.useDebugValue(q),o){if(!Gy&&hr&&Q)throw new Error("Fallback data is required when using Suspense in SSR.");Q&&(I.current=t,M.current=n,S.current=!1);const J=y[v],ue=!we(J)&&Q?ge(J):tv;if(Au(ue),!we(V)&&Q)throw V;const de=Q?ne(Tu):tv;!we(q)&&Q&&(de.status="fulfilled",de.value=!0),Au(de)}return{mutate:ge,get data(){return R.data=!0,q},get error(){return R.error=!0,V},get isValidating(){return R.isValidating=!0,te},get isLoading(){return R.isLoading=!0,$}}});function nv({userCredentials:e,listConversations:t,clientId:n}){const r=!!e&&n&&t,{data:i,error:o,isValidating:s,mutate:a}=u_(r?[n,"conversations",e==null?void 0:e.userId]:null,async()=>(await t({})).conversations.filter(c_).sort((u,f)=>new Date(f.updatedAt).getTime()-new Date(u.updatedAt).getTime()).map(u=>({...u,lastMessage:{...u.lastMessage,author:{type:u.lastMessage.userId===(e==null?void 0:e.userId)?"user":"bot"}}})),{revalidateOnFocus:!1,revalidateOnReconnect:!0,dedupingInterval:2e3});return{conversations:i??[],isLoading:s,error:o&&_r(o),refresh:async()=>await a()}}const c_=e=>!!e.lastMessage,f_=e=>e==null||e.length===0?"":e.charAt(0).toUpperCase()+e.slice(1),Iu=({className:e,onConversationClick:t,onNewConversation:n,onClose:r,currentConversationId:i,isLoading:o,conversations:s,botAvatar:a,botName:l,...u})=>{const{conversationHistory:f}=me;return k.jsxs("div",{...u,...f.container,className:ar(f.container.className,e),children:[k.jsxs("div",{...f.header,children:["Conversations",r&&k.jsx("div",{...f.closeButton,children:k.jsx(ou,{onClick:r})})]}),o?k.jsx("div",{...f.loaderContainer,children:k.jsx(My,{})}):k.jsx("div",{...f.scrollContainer,children:s.length===0?k.jsx("div",{...f.loaderContainer,children:"No conversation started yet"}):s.map(({id:c,lastMessage:h})=>{let d="";if(h.payload.type==="text")d=h.payload.text;else if(h.payload.type==="bloc"&&h.payload.items.some(m=>m.type==="text")){const m=h.payload.items.find(p=>p.type==="text");d=(m==null?void 0:m.payload.text)??""}else d="Sent an attachment";return k.jsxs("button",{...f.conversation.container,onClick:()=>t==null?void 0:t(c),"data-active":i===c?"":void 0,children:[h.author.type==="bot"?k.jsx(En,{userId:h.userId,src:a,...f.conversation.avatar,children:l??"Bot"}):k.jsx(En,{userId:h.userId,...f.conversation.avatar,fallback:f.conversation.userAvatar.className,children:k.jsx(lT,{strokeWidth:1.5})}),k.jsxs("div",{...f.conversation.content,children:[k.jsx("span",{...f.conversation.name,children:d}),k.jsx("span",{...f.conversation.timestamp,children:f_(Aw(h.createdAt))})]}),k.jsx(lp,{strokeWidth:1.5,...f.conversation.chevron})]},c)})}),k.jsxs("button",{...f.newConversation.button,onClick:n,children:[k.jsx(iT,{...f.newConversation.icon}),"New conversation"]})]})};Iu.displayName="ConversationHistory";const rv=({connected:e,configuration:t,isTyping:n,messages:r,user:i,isLoading:o,renderers:s,isReadOnly:a,disableComposer:l,error:u,participants:f,closeWindow:c,sendMessage:h,uploadFile:d,addMessageFeedback:m,listConversations:p,restartConversation:g,clientId:y,storageKey:v,soundOn:w,toggleSound:E,disableSendButton:S,conversationId:C,...I})=>{const{color:M,fontFamily:P,radius:T,themeMode:O,variant:U,headerVariant:F,botAvatar:L,botDescription:R,botName:N,composerPlaceholder:j,footer:B,feedbackEnabled:W,additionalStylesheetUrl:b,allowFileUpload:_,conversationHistory:H}=t,x={color:M,fontFamily:P,radius:T,themeMode:O,variant:U,headerVariant:F,additionalStylesheetUrl:b},[V,Y]=D.useState("chat"),q=nv({clientId:y,listConversations:p,userCredentials:i});D.useEffect(()=>{V==="conversations"&&q.refresh()},[V]),W||(m=void 0);const Q=D.useMemo(()=>i?nc(r,f,i.userId,N,L):[],[L,N,r,i,f]),X=D.useMemo(()=>{var te,$;return(($=(te=r.at(-1))==null?void 0:te.metadata)==null?void 0:$.conversationStatus)==="closed"},[r]),se=D.useRef(null),G=Qn(te=>te.setPortalContainer);return D.useEffect(()=>(G(se.current),()=>{G(null)}),[G]),k.jsxs(k.Fragment,{children:[k.jsx(Fg,{...x}),k.jsx("div",{ref:se,style:{position:"fixed",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:10}}),k.jsx(eu,{connected:e,allowFileUpload:_,uploadFile:d,storageKey:v,conversationId:C,...I,children:u||q.error?k.jsx(Dy,{error:u||q.error,restartConversation:g,closeWindow:c}):V==="conversations"?k.jsx(Iu,{onClose:c,conversations:q.conversations,isLoading:q.isLoading,onNewConversation:()=>{g==null||g(),Y("chat")},onConversationClick:te=>{g==null||g(te),Y("chat")},botAvatar:L,botName:N}):k.jsxs(k.Fragment,{children:[k.jsx(Cy,{showConversationHistory:H?()=>Y("conversations"):void 0,closeWindow:c,configuration:t,restartConversation:g,clientId:y,soundOn:w,toggleSound:E}),o?k.jsx(My,{}):k.jsx(fu,{botAvatar:L,botDescription:R,botName:N,renderers:s,isTyping:n,sendMessage:h,addMessageFeedback:m,messages:Q}),!X&&k.jsx(ng,{sendMessage:h,uploadFile:d,connected:e,isReadOnly:a,disableComposer:l,footer:B,composerPlaceholder:j,allowFileUpload:_,storageKey:v,disableSendButton:S,conversationId:C})]})})]})};function d_({configuration:e,storageKey:t,clientId:n,...r}){const i=t||`bp-webchat-${n}`,{messages:o,participants:s,sendMessage:a,uploadFile:l,saveMessageFeedback:u,conversationId:f,status:c,error:h,isTyping:d,isAwaitingResponse:m}=zy(),{openConversation:p,listConversations:g}=Uy(),{userCredentials:y}=By(),{soundOn:v,toggleSound:w}=$y({storageKey:i,soundEnabled:e==null?void 0:e.soundEnabled});return k.jsx(rv,{configuration:e??{},user:y,isLoading:c==="connecting",isTyping:d,connected:c==="connected"?!0:c==="disconnected"?!1:void 0,messages:o,sendMessage:a,uploadFile:l,addMessageFeedback:u,listConversations:g,restartConversation:p,participants:s,error:h,clientId:n,soundOn:v,toggleSound:w,disableSendButton:m,conversationId:f,storageKey:i,...r})}const h_=({clientId:e,storageKey:t,configuration:n,apiUrl:r,user:i,conversationId:o,...s})=>{const a=t||`bp-webchat-${e}`;return k.jsx(gy,{clientId:e,apiUrl:r,userCredentials:i,conversationId:o,storageKey:a,storageLocation:n==null?void 0:n.storageLocation,adminSecret:n==null?void 0:n.adminSecret,children:k.jsx(d_,{configuration:n,storageKey:t,clientId:e,...s})})};function p_(e,t=globalThis==null?void 0:globalThis.document){const n=Ln(e);A.useEffect(()=>{const r=i=>{i.key==="Escape"&&n(i)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var m_="DismissableLayer",Ou="dismissableLayer.update",g_="dismissableLayer.pointerDownOutside",y_="dismissableLayer.focusOutside",iv,ov=A.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),sv=A.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:i,onFocusOutside:o,onInteractOutside:s,onDismiss:a,...l}=e,u=A.useContext(ov),[f,c]=A.useState(null),h=(f==null?void 0:f.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,d]=A.useState({}),m=tn(t,I=>c(I)),p=Array.from(u.layers),[g]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),y=p.indexOf(g),v=f?p.indexOf(f):-1,w=u.layersWithOutsidePointerEventsDisabled.size>0,E=v>=y,S=w_(I=>{const M=I.target,P=[...u.branches].some(T=>T.contains(M));!E||P||(i==null||i(I),s==null||s(I),I.defaultPrevented||a==null||a())},h),C=S_(I=>{const M=I.target;[...u.branches].some(T=>T.contains(M))||(o==null||o(I),s==null||s(I),I.defaultPrevented||a==null||a())},h);return p_(I=>{v===u.layers.size-1&&(r==null||r(I),!I.defaultPrevented&&a&&(I.preventDefault(),a()))},h),A.useEffect(()=>{if(f)return n&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(iv=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(f)),u.layers.add(f),av(),()=>{n&&u.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=iv)}},[f,h,n,u]),A.useEffect(()=>()=>{f&&(u.layers.delete(f),u.layersWithOutsidePointerEventsDisabled.delete(f),av())},[f,u]),A.useEffect(()=>{const I=()=>d({});return document.addEventListener(Ou,I),()=>document.removeEventListener(Ou,I)},[]),k.jsx(Ft.div,{...l,ref:m,style:{pointerEvents:w?E?"auto":"none":void 0,...e.style},onFocusCapture:Zt(e.onFocusCapture,C.onFocusCapture),onBlurCapture:Zt(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:Zt(e.onPointerDownCapture,S.onPointerDownCapture)})});sv.displayName=m_;var v_="DismissableLayerBranch",b_=A.forwardRef((e,t)=>{const n=A.useContext(ov),r=A.useRef(null),i=tn(t,r);return A.useEffect(()=>{const o=r.current;if(o)return n.branches.add(o),()=>{n.branches.delete(o)}},[n.branches]),k.jsx(Ft.div,{...e,ref:i})});b_.displayName=v_;function w_(e,t=globalThis==null?void 0:globalThis.document){const n=Ln(e),r=A.useRef(!1),i=A.useRef(()=>{});return A.useEffect(()=>{const o=a=>{if(a.target&&!r.current){let l=function(){lv(g_,n,u,{discrete:!0})};const u={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",i.current),i.current=l,t.addEventListener("click",i.current,{once:!0})):l()}else t.removeEventListener("click",i.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",o)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",o),t.removeEventListener("click",i.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function S_(e,t=globalThis==null?void 0:globalThis.document){const n=Ln(e),r=A.useRef(!1);return A.useEffect(()=>{const i=o=>{o.target&&!r.current&&lv(y_,n,{originalEvent:o},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function av(){const e=new CustomEvent(Ou);document.dispatchEvent(e)}function lv(e,t,n,{discrete:r}){const i=n.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?u2(i,o):i.dispatchEvent(o)}var Mu="focusScope.autoFocusOnMount",Du="focusScope.autoFocusOnUnmount",uv={bubbles:!1,cancelable:!0},x_="FocusScope",cv=A.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:o,...s}=e,[a,l]=A.useState(null),u=Ln(i),f=Ln(o),c=A.useRef(null),h=tn(t,p=>l(p)),d=A.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;A.useEffect(()=>{if(r){let p=function(w){if(d.paused||!a)return;const E=w.target;a.contains(E)?c.current=E:gn(c.current,{select:!0})},g=function(w){if(d.paused||!a)return;const E=w.relatedTarget;E!==null&&(a.contains(E)||gn(c.current,{select:!0}))},y=function(w){if(document.activeElement===document.body)for(const S of w)S.removedNodes.length>0&&gn(a)};document.addEventListener("focusin",p),document.addEventListener("focusout",g);const v=new MutationObserver(y);return a&&v.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",p),document.removeEventListener("focusout",g),v.disconnect()}}},[r,a,d.paused]),A.useEffect(()=>{if(a){hv.add(d);const p=document.activeElement;if(!a.contains(p)){const y=new CustomEvent(Mu,uv);a.addEventListener(Mu,u),a.dispatchEvent(y),y.defaultPrevented||(k_(I_(fv(a)),{select:!0}),document.activeElement===p&&gn(a))}return()=>{a.removeEventListener(Mu,u),setTimeout(()=>{const y=new CustomEvent(Du,uv);a.addEventListener(Du,f),a.dispatchEvent(y),y.defaultPrevented||gn(p??document.body,{select:!0}),a.removeEventListener(Du,f),hv.remove(d)},0)}}},[a,u,f,d]);const m=A.useCallback(p=>{if(!n&&!r||d.paused)return;const g=p.key==="Tab"&&!p.altKey&&!p.ctrlKey&&!p.metaKey,y=document.activeElement;if(g&&y){const v=p.currentTarget,[w,E]=E_(v);w&&E?!p.shiftKey&&y===E?(p.preventDefault(),n&&gn(w,{select:!0})):p.shiftKey&&y===w&&(p.preventDefault(),n&&gn(E,{select:!0})):y===v&&p.preventDefault()}},[n,r,d.paused]);return k.jsx(Ft.div,{tabIndex:-1,...s,ref:h,onKeyDown:m})});cv.displayName=x_;function k_(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(gn(r,{select:t}),document.activeElement!==n)return}function E_(e){const t=fv(e),n=dv(t,e),r=dv(t.reverse(),e);return[n,r]}function fv(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function dv(e,t){for(const n of e)if(!C_(n,{upTo:t}))return n}function C_(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function A_(e){return e instanceof HTMLInputElement&&"select"in e}function gn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&A_(e)&&t&&e.select()}}var hv=T_();function T_(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=pv(e,t),e.unshift(t)},remove(t){var n;e=pv(e,t),(n=e[0])==null||n.resume()}}}function pv(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function I_(e){return e.filter(t=>t.tagName!=="A")}var Nu=0;function O_(){A.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??mv()),document.body.insertAdjacentElement("beforeend",e[1]??mv()),Nu++,()=>{Nu===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Nu--}},[])}function mv(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Yo="right-scroll-bar-position",Ko="width-before-scroll-bar",M_="with-scroll-bars-hidden",D_="--removed-body-scroll-bar-size";function _u(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function N_(e,t){var n=D.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var i=n.value;i!==r&&(n.value=r,n.callback(r,i))}}}})[0];return n.callback=t,n.facade}var __=typeof window<"u"?A.useLayoutEffect:A.useEffect,gv=new WeakMap;function P_(e,t){var n=N_(null,function(r){return e.forEach(function(i){return _u(i,r)})});return __(function(){var r=gv.get(n);if(r){var i=new Set(r),o=new Set(e),s=n.current;i.forEach(function(a){o.has(a)||_u(a,null)}),o.forEach(function(a){i.has(a)||_u(a,s)})}gv.set(n,e)},[e]),n}function L_(e){return e}function F_(e,t){t===void 0&&(t=L_);var n=[],r=!1,i={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(o){var s=t(o,r);return n.push(s),function(){n=n.filter(function(a){return a!==s})}},assignSyncMedium:function(o){for(r=!0;n.length;){var s=n;n=[],s.forEach(o)}n={push:function(a){return o(a)},filter:function(){return n}}},assignMedium:function(o){r=!0;var s=[];if(n.length){var a=n;n=[],a.forEach(o),s=n}var l=function(){var f=s;s=[],f.forEach(o)},u=function(){return Promise.resolve().then(l)};u(),n={push:function(f){s.push(f),u()},filter:function(f){return s=s.filter(f),n}}}};return i}function R_(e){e===void 0&&(e={});var t=F_(null);return t.options=xt({async:!0,ssr:!1},e),t}var yv=function(e){var t=e.sideCar,n=Np(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return A.createElement(r,xt({},n))};yv.isSideCarExport=!0;function $_(e,t){return e.useMedium(t),yv}var vv=R_(),Pu=function(){},Go=A.forwardRef(function(e,t){var n=A.useRef(null),r=A.useState({onScrollCapture:Pu,onWheelCapture:Pu,onTouchMoveCapture:Pu}),i=r[0],o=r[1],s=e.forwardProps,a=e.children,l=e.className,u=e.removeScrollBar,f=e.enabled,c=e.shards,h=e.sideCar,d=e.noRelative,m=e.noIsolation,p=e.inert,g=e.allowPinchZoom,y=e.as,v=y===void 0?"div":y,w=e.gapMode,E=Np(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),S=h,C=P_([n,t]),I=xt(xt({},E),i);return A.createElement(A.Fragment,null,f&&A.createElement(S,{sideCar:vv,removeScrollBar:u,shards:c,noRelative:d,noIsolation:m,inert:p,setCallbacks:o,allowPinchZoom:!!g,lockRef:n,gapMode:w}),s?A.cloneElement(A.Children.only(a),xt(xt({},I),{ref:C})):A.createElement(v,xt({},I,{className:l,ref:C}),a))});Go.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},Go.classNames={fullWidth:Ko,zeroRight:Yo};var B_=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function z_(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=B_();return t&&e.setAttribute("nonce",t),e}function U_(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function j_(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var H_=function(){var e=0,t=null;return{add:function(n){e==0&&(t=z_())&&(U_(t,n),j_(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},V_=function(){var e=H_();return function(t,n){A.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},bv=function(){var e=V_(),t=function(n){var r=n.styles,i=n.dynamic;return e(r,i),null};return t},W_={left:0,top:0,right:0,gap:0},Lu=function(e){return parseInt(e||"",10)||0},q_=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],i=t[e==="padding"?"paddingRight":"marginRight"];return[Lu(n),Lu(r),Lu(i)]},Y_=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return W_;var t=q_(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},K_=bv(),pr="data-scroll-locked",G_=function(e,t,n,r){var i=e.left,o=e.top,s=e.right,a=e.gap;return n===void 0&&(n="margin"),`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botpress/webchat",
3
- "version": "4.4.2",
3
+ "version": "4.4.3",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "main": "./dist/index.umd.cjs",
@@ -52,7 +52,7 @@
52
52
  "use-stick-to-bottom": "^1.1.1",
53
53
  "uuid": "^9.0.1",
54
54
  "zustand": "^4.4.1",
55
- "@botpress/webchat-client": "0.6.1",
55
+ "@botpress/webchat-client": "0.7.0",
56
56
  "@bpinternal/shared": "1.1.5"
57
57
  },
58
58
  "peerDependencies": {