@flowengage/react-chatbot 8.0.126 → 8.0.127

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,4 +1,4 @@
1
- "use client";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(e&&(t=e(e=0)),t),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,a)=>(a=n==null?{}:e(i(n)),c(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n)),u=e=>a.call(e,`module.exports`)?e[`module.exports`]:c(t({},`__esModule`,{value:!0}),e);let d=require(`react`);d=l(d);let f=require(`react/jsx-runtime`);var p=e=>{if(!e||typeof e!=`object`)throw Error(`FlowEngage config is required`);if(!e.siteId||typeof e.siteId!=`string`)throw Error(`[FlowEngage] config.siteId is required. Pass it as <FlowEngageProvider siteId="your-site-id" /> or config={{ siteId: 'your-site-id' }}.`);let t=(e.apiBaseUrl||`https://be-flowengage-stage.oslabs.app`).replace(/\/+$/,``);return{siteId:e.siteId.trim(),apiBaseUrl:t}},m=(e,t)=>{let n=Number.parseInt(String(e??``),10);return Number.isFinite(n)&&n>0?n:t},h=m(void 0,1e4),g=m(void 0,15e3),_={chatId:`flowengage.chatId`,isOpen:`flowengage.isOpen`,activeScreen:`flowengage.activeScreen`,isHumanHandled:`flowengage.isHumanHandled`,agentName:`flowengage.agentName`,agentHeadshot:`flowengage.agentHeadshot`,visitorEmail:`flowengage.visitorEmail`},v=6e4,y=480*60,b=3e4,x=typeof window<`u`,S=e=>e?`flowengage.visitorEmail.${e}`:null,C=()=>{if(!x)return null;let e=window.localStorage.getItem(_.chatId);return e&&String(e).trim()?String(e).trim():null},w=()=>{if(x)try{window.localStorage.removeItem(_.chatId)}catch{}},T=()=>x?typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`:`server-chat-id`,E=e=>e?`flowengage.entrySeen.${e}`:null,ee=e=>{if(!x||!e)return!1;try{let t=E(e);return t?window.localStorage.getItem(t)===`1`:!1}catch{return!1}},D=e=>{if(!(!x||!e))try{let t=E(e);t&&window.localStorage.setItem(t,`1`)}catch{}},O=e=>e?`flowengage.navPreference.${e}`:null,k=e=>e?`flowengage.navPreferencePromptShown.${e}`:null,te=e=>{if(!x||!e)return null;try{let t=O(e),n=t?window.localStorage.getItem(t):null;return n===`auto`||n===`ask`?n:null}catch{return null}},ne=(e,t)=>{if(!(!x||!e||t!==`auto`&&t!==`ask`))try{let n=O(e);n&&window.localStorage.setItem(n,t),ie(e)}catch{}},re=e=>{if(!x||!e)return!1;try{let t=k(e);return t?window.localStorage.getItem(t)===`1`:!1}catch{return!1}},ie=e=>{if(!(!x||!e))try{let t=k(e);t&&window.localStorage.setItem(t,`1`)}catch{}},A=e=>e?`flowengage.persistedChatId.${e}`:null,ae=e=>{if(!x||!e)return null;try{let t=A(e),n=t?window.localStorage.getItem(t):null;return n&&String(n).trim()?String(n).trim():null}catch{return null}},oe=e=>{if(!(!x||!e))try{let t=A(e);t&&window.localStorage.removeItem(t)}catch{}},se=(e,t)=>{if(!(!x||!e||!t))try{let n=A(e);n&&window.localStorage.setItem(n,String(t).trim())}catch{}},ce=()=>x?{isOpen:!1,activeScreen:window.sessionStorage.getItem(_.activeScreen)||`ai`,isHumanHandled:window.sessionStorage.getItem(_.isHumanHandled)===`true`,agentName:window.sessionStorage.getItem(_.agentName),agentHeadshot:window.sessionStorage.getItem(_.agentHeadshot),visitorEmail:``}:{isOpen:!1,activeScreen:`ai`,isHumanHandled:!1,agentName:null,agentHeadshot:null,visitorEmail:``},le=e=>{x&&Object.entries(e).forEach(([e,t])=>{let n=_[e];if(n){if(t==null||t===!1){window.sessionStorage.removeItem(n);return}window.sessionStorage.setItem(n,String(t))}})},j=e=>{if(!x||!e)return``;let t=S(e),n=window.localStorage.getItem(t);if(!n){let e=window.sessionStorage.getItem(_.visitorEmail);e&&(window.localStorage.setItem(t,e),window.sessionStorage.removeItem(_.visitorEmail),n=e)}return n||``},ue=(e,t)=>{if(!x)return;let n=S(t);if(!n)return;let r=typeof e==`string`?e.trim():``;if(!r){window.localStorage.removeItem(n),window.sessionStorage.removeItem(_.visitorEmail);return}window.localStorage.setItem(n,r),window.sessionStorage.removeItem(_.visitorEmail)},de=e=>e?`flowengage.visitorId.${e}`:null,M=()=>`v_${Date.now().toString(36)}_${typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID().replace(/-/g,``).slice(0,16):Math.random().toString(36).slice(2,18)}`,N=e=>{if(!x||!e)return null;try{let t=de(e),n=t?window.localStorage.getItem(t):null;return n&&String(n).trim()?String(n).trim():null}catch{return null}},fe=e=>{if(!x||!e)return null;try{let t=N(e);if(t)return t;let n=M(),r=de(e);return r&&window.localStorage.setItem(r,n),n}catch{return M()}},pe=`flowengage.tabId`,me=()=>{if(!x)return`default`;try{let e=window.sessionStorage.getItem(pe);return e||(e=typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID().replace(/-/g,``).slice(0,12):Math.random().toString(36).slice(2,14),window.sessionStorage.setItem(pe,e)),e}catch{return`default`}},he=e=>e?`flowengage.voice.transcript.${e}.${me()}`:null,ge=600*1e3,_e=(e,t,n={})=>{if(!x||!e)return;let r=typeof t==`string`?t.trim():``;if(!r)return;let i=Number.isFinite(n.ttlMs)?n.ttlMs:ge,a={transcript:r,expiresAt:Date.now()+i};try{let t=he(e);t&&window.localStorage.setItem(t,JSON.stringify(a))}catch{}},ve=e=>{if(!x||!e)return null;try{let t=he(e),n=t?window.localStorage.getItem(t):null;if(!n)return null;let r=JSON.parse(n);return!r||typeof r.transcript!=`string`?null:Number.isFinite(r.expiresAt)&&Date.now()>r.expiresAt?(window.localStorage.removeItem(t),null):r}catch{return null}},ye=e=>{if(!(!x||!e))try{let t=he(e);t&&window.localStorage.removeItem(t)}catch{}},be=`flowengage.voice.pendingResume`,P=()=>{if(x)try{window.sessionStorage.setItem(be,`1`)}catch{}},xe=()=>{if(!x)return!1;try{return window.sessionStorage.getItem(be)===`1`?(window.sessionStorage.removeItem(be),!0):!1}catch{return!1}},Se=`flowengage.chat.pendingReopen`,Ce=()=>{if(x)try{window.sessionStorage.setItem(Se,`1`)}catch{}},we=()=>{if(!x)return!1;try{return window.sessionStorage.getItem(Se)===`1`?(window.sessionStorage.removeItem(Se),!0):!1}catch{return!1}},Te=()=>{if(!x)return!1;try{return window.sessionStorage.getItem(be)===`1`}catch{return!1}},F=e=>e?`flowengage.voice.navState.${e}.${me()}`:null,Ee=(e,t,n,r)=>{if(!(!x||!e||!t))try{let i=F(e);i&&window.sessionStorage.setItem(i,JSON.stringify({previousPage:String(t),targetPath:n?new URL(String(n),window.location.href).pathname:null,pageName:r||null,ts:Date.now()}))}catch{}},De=e=>{if(!x||!e)return null;try{let t=F(e);if(!t)return null;let n=window.sessionStorage.getItem(t);if(!n)return null;window.sessionStorage.removeItem(t);let r=JSON.parse(n);return!r||typeof r.previousPage!=`string`||Number.isFinite(r.ts)&&Date.now()-r.ts>6e4||r.targetPath&&(window.location.pathname.replace(/\/$/,``)||`/`)!==(r.targetPath.replace(/\/$/,``)||`/`)?null:{previousPage:r.previousPage,pageName:r.pageName||null}}catch{return null}},Oe=async e=>{let t=await e.json().catch(()=>({}));if(!e.ok){let n=Error(t.message||t.error||`Request failed with status ${e.status}`);throw n.status=e.status,n}return t},I=async(e,t={})=>{try{return await fetch(e,{mode:`cors`,...t})}catch(t){let n=Error(`Network error reaching ${e}. Check: (1) backend is running, (2) CORS allows this origin, (3) siteId is correct. Original: ${t.message}`);throw n.status=0,n.cause=t,n}},ke=async({apiBaseUrl:e,userId:t,siteId:n,priorChatId:r=null,forceNew:i=!1,resumeChatId:a=null,visitorId:o=null})=>{let s=`${e}/api/visitors/resolve-session`,c={siteId:n};return r&&String(r).trim()&&(c.priorChatId=String(r).trim()),i&&(c.forceNew=!0),a&&(c.resumeChatId=a),o&&(c.visitorId=o),Oe(await I(s,{method:`POST`,mode:`cors`,headers:{"Content-Type":`application/json`,"x-user-id":t==null?``:String(t),...n?{"x-site-id":n}:{},...o?{"x-visitor-id":o}:{}},body:JSON.stringify(c)}))},Ae=async({apiBaseUrl:e,siteId:t})=>{let n=typeof window<`u`?window.location.origin:`http://localhost`;return(await Oe(await I(`${e}/api/widget/chatbot-loader?${new URLSearchParams({siteId:t,origin:n}).toString()}`,{method:`GET`}))).data},je=({apiBaseUrl:e,userId:t,siteId:n,visitorId:r=null})=>{let i=(t,n)=>{let r=`${e}${t}`,i=JSON.stringify(n);if(typeof navigator<`u`&&navigator.sendBeacon)try{let e=new Blob([i],{type:`application/json`});return navigator.sendBeacon(r,e)}catch{}return typeof fetch<`u`?(fetch(r,{method:`POST`,mode:`cors`,keepalive:!0,headers:{"Content-Type":`application/json`},body:i}).catch(()=>{}),!0):!1},a=async(i,a={})=>Oe(await I(`${e}${i}`,{...a,headers:{"Content-Type":`application/json`,"x-user-id":t,...n?{"x-site-id":n}:{},...r?{"x-visitor-id":r}:{},...a.headers||{}}})),o=async(r,i,a={})=>{let o={"x-user-id":t,...n?{"x-site-id":n}:{},...a.headers||{}};return Oe(await I(`${e}${r}`,{...a,body:i,headers:o}))};return{async loadHistory(e,t=`en`,n=``){return a(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:``,lang:t,category:n})})},async sendAiMessage(i,o,s=`en`,c=``,l=null,u={},d=null){let f={session_id:i,user_query:o,lang:s,category:c,...u||{},...l||{}};if(typeof d!=`function`)return a(`/api/ai/chat`,{method:`POST`,body:JSON.stringify(f)});let p=await I(`${e}/api/ai/chat`,{method:`POST`,headers:{"Content-Type":`application/json`,"x-user-id":t,...n?{"x-site-id":n}:{},...r?{"x-visitor-id":r}:{}},body:JSON.stringify({...f,stream:!0})});if(!(p.headers.get(`content-type`)||``).includes(`text/event-stream`))return Oe(p);let m=p.body.getReader(),h=new TextDecoder,g=``,_=null,v=e=>{let t=e.split(`
1
+ "use client";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(e&&(t=e(e=0)),t),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,a)=>(a=n==null?{}:e(i(n)),c(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n)),u=e=>a.call(e,`module.exports`)?e[`module.exports`]:c(t({},`__esModule`,{value:!0}),e);let d=require(`react`);d=l(d);let f=require(`react/jsx-runtime`);var p=e=>{if(!e||typeof e!=`object`)throw Error(`FlowEngage config is required`);if(!e.siteId||typeof e.siteId!=`string`)throw Error(`[FlowEngage] config.siteId is required. Pass it as <FlowEngageProvider siteId="your-site-id" /> or config={{ siteId: 'your-site-id' }}.`);let t=(e.apiBaseUrl||`https://be-flowengage-dev.oslabs.app`).replace(/\/+$/,``);return{siteId:e.siteId.trim(),apiBaseUrl:t}},m=(e,t)=>{let n=Number.parseInt(String(e??``),10);return Number.isFinite(n)&&n>0?n:t},h=m(void 0,1e4),g=m(void 0,15e3),_={chatId:`flowengage.chatId`,isOpen:`flowengage.isOpen`,activeScreen:`flowengage.activeScreen`,isHumanHandled:`flowengage.isHumanHandled`,agentName:`flowengage.agentName`,agentHeadshot:`flowengage.agentHeadshot`,visitorEmail:`flowengage.visitorEmail`},v=6e4,y=480*60,b=3e4,x=typeof window<`u`,S=e=>e?`flowengage.visitorEmail.${e}`:null,C=()=>{if(!x)return null;let e=window.localStorage.getItem(_.chatId);return e&&String(e).trim()?String(e).trim():null},w=()=>{if(x)try{window.localStorage.removeItem(_.chatId)}catch{}},T=()=>x?typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`:`server-chat-id`,E=e=>e?`flowengage.entrySeen.${e}`:null,ee=e=>{if(!x||!e)return!1;try{let t=E(e);return t?window.localStorage.getItem(t)===`1`:!1}catch{return!1}},D=e=>{if(!(!x||!e))try{let t=E(e);t&&window.localStorage.setItem(t,`1`)}catch{}},O=e=>e?`flowengage.navPreference.${e}`:null,k=e=>e?`flowengage.navPreferencePromptShown.${e}`:null,te=e=>{if(!x||!e)return null;try{let t=O(e),n=t?window.localStorage.getItem(t):null;return n===`auto`||n===`ask`?n:null}catch{return null}},ne=(e,t)=>{if(!(!x||!e||t!==`auto`&&t!==`ask`))try{let n=O(e);n&&window.localStorage.setItem(n,t),ie(e)}catch{}},re=e=>{if(!x||!e)return!1;try{let t=k(e);return t?window.localStorage.getItem(t)===`1`:!1}catch{return!1}},ie=e=>{if(!(!x||!e))try{let t=k(e);t&&window.localStorage.setItem(t,`1`)}catch{}},A=e=>e?`flowengage.persistedChatId.${e}`:null,ae=e=>{if(!x||!e)return null;try{let t=A(e),n=t?window.localStorage.getItem(t):null;return n&&String(n).trim()?String(n).trim():null}catch{return null}},oe=e=>{if(!(!x||!e))try{let t=A(e);t&&window.localStorage.removeItem(t)}catch{}},se=(e,t)=>{if(!(!x||!e||!t))try{let n=A(e);n&&window.localStorage.setItem(n,String(t).trim())}catch{}},ce=()=>x?{isOpen:!1,activeScreen:window.sessionStorage.getItem(_.activeScreen)||`ai`,isHumanHandled:window.sessionStorage.getItem(_.isHumanHandled)===`true`,agentName:window.sessionStorage.getItem(_.agentName),agentHeadshot:window.sessionStorage.getItem(_.agentHeadshot),visitorEmail:``}:{isOpen:!1,activeScreen:`ai`,isHumanHandled:!1,agentName:null,agentHeadshot:null,visitorEmail:``},le=e=>{x&&Object.entries(e).forEach(([e,t])=>{let n=_[e];if(n){if(t==null||t===!1){window.sessionStorage.removeItem(n);return}window.sessionStorage.setItem(n,String(t))}})},j=e=>{if(!x||!e)return``;let t=S(e),n=window.localStorage.getItem(t);if(!n){let e=window.sessionStorage.getItem(_.visitorEmail);e&&(window.localStorage.setItem(t,e),window.sessionStorage.removeItem(_.visitorEmail),n=e)}return n||``},ue=(e,t)=>{if(!x)return;let n=S(t);if(!n)return;let r=typeof e==`string`?e.trim():``;if(!r){window.localStorage.removeItem(n),window.sessionStorage.removeItem(_.visitorEmail);return}window.localStorage.setItem(n,r),window.sessionStorage.removeItem(_.visitorEmail)},de=e=>e?`flowengage.visitorId.${e}`:null,M=()=>`v_${Date.now().toString(36)}_${typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID().replace(/-/g,``).slice(0,16):Math.random().toString(36).slice(2,18)}`,N=e=>{if(!x||!e)return null;try{let t=de(e),n=t?window.localStorage.getItem(t):null;return n&&String(n).trim()?String(n).trim():null}catch{return null}},fe=e=>{if(!x||!e)return null;try{let t=N(e);if(t)return t;let n=M(),r=de(e);return r&&window.localStorage.setItem(r,n),n}catch{return M()}},pe=`flowengage.tabId`,me=()=>{if(!x)return`default`;try{let e=window.sessionStorage.getItem(pe);return e||(e=typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID().replace(/-/g,``).slice(0,12):Math.random().toString(36).slice(2,14),window.sessionStorage.setItem(pe,e)),e}catch{return`default`}},he=e=>e?`flowengage.voice.transcript.${e}.${me()}`:null,ge=600*1e3,_e=(e,t,n={})=>{if(!x||!e)return;let r=typeof t==`string`?t.trim():``;if(!r)return;let i=Number.isFinite(n.ttlMs)?n.ttlMs:ge,a={transcript:r,expiresAt:Date.now()+i};try{let t=he(e);t&&window.localStorage.setItem(t,JSON.stringify(a))}catch{}},ve=e=>{if(!x||!e)return null;try{let t=he(e),n=t?window.localStorage.getItem(t):null;if(!n)return null;let r=JSON.parse(n);return!r||typeof r.transcript!=`string`?null:Number.isFinite(r.expiresAt)&&Date.now()>r.expiresAt?(window.localStorage.removeItem(t),null):r}catch{return null}},ye=e=>{if(!(!x||!e))try{let t=he(e);t&&window.localStorage.removeItem(t)}catch{}},be=`flowengage.voice.pendingResume`,P=()=>{if(x)try{window.sessionStorage.setItem(be,`1`)}catch{}},xe=()=>{if(!x)return!1;try{return window.sessionStorage.getItem(be)===`1`?(window.sessionStorage.removeItem(be),!0):!1}catch{return!1}},Se=`flowengage.chat.pendingReopen`,Ce=()=>{if(x)try{window.sessionStorage.setItem(Se,`1`)}catch{}},we=()=>{if(!x)return!1;try{return window.sessionStorage.getItem(Se)===`1`?(window.sessionStorage.removeItem(Se),!0):!1}catch{return!1}},Te=()=>{if(!x)return!1;try{return window.sessionStorage.getItem(be)===`1`}catch{return!1}},F=e=>e?`flowengage.voice.navState.${e}.${me()}`:null,Ee=(e,t,n,r)=>{if(!(!x||!e||!t))try{let i=F(e);i&&window.sessionStorage.setItem(i,JSON.stringify({previousPage:String(t),targetPath:n?new URL(String(n),window.location.href).pathname:null,pageName:r||null,ts:Date.now()}))}catch{}},De=e=>{if(!x||!e)return null;try{let t=F(e);if(!t)return null;let n=window.sessionStorage.getItem(t);if(!n)return null;window.sessionStorage.removeItem(t);let r=JSON.parse(n);return!r||typeof r.previousPage!=`string`||Number.isFinite(r.ts)&&Date.now()-r.ts>6e4||r.targetPath&&(window.location.pathname.replace(/\/$/,``)||`/`)!==(r.targetPath.replace(/\/$/,``)||`/`)?null:{previousPage:r.previousPage,pageName:r.pageName||null}}catch{return null}},Oe=async e=>{let t=await e.json().catch(()=>({}));if(!e.ok){let n=Error(t.message||t.error||`Request failed with status ${e.status}`);throw n.status=e.status,n}return t},I=async(e,t={})=>{try{return await fetch(e,{mode:`cors`,...t})}catch(t){let n=Error(`Network error reaching ${e}. Check: (1) backend is running, (2) CORS allows this origin, (3) siteId is correct. Original: ${t.message}`);throw n.status=0,n.cause=t,n}},ke=async({apiBaseUrl:e,userId:t,siteId:n,priorChatId:r=null,forceNew:i=!1,resumeChatId:a=null,visitorId:o=null})=>{let s=`${e}/api/visitors/resolve-session`,c={siteId:n};return r&&String(r).trim()&&(c.priorChatId=String(r).trim()),i&&(c.forceNew=!0),a&&(c.resumeChatId=a),o&&(c.visitorId=o),Oe(await I(s,{method:`POST`,mode:`cors`,headers:{"Content-Type":`application/json`,"x-user-id":t==null?``:String(t),...n?{"x-site-id":n}:{},...o?{"x-visitor-id":o}:{}},body:JSON.stringify(c)}))},Ae=async({apiBaseUrl:e,siteId:t})=>{let n=typeof window<`u`?window.location.origin:`http://localhost`;return(await Oe(await I(`${e}/api/widget/chatbot-loader?${new URLSearchParams({siteId:t,origin:n}).toString()}`,{method:`GET`}))).data},je=({apiBaseUrl:e,userId:t,siteId:n,visitorId:r=null})=>{let i=(t,n)=>{let r=`${e}${t}`,i=JSON.stringify(n);if(typeof navigator<`u`&&navigator.sendBeacon)try{let e=new Blob([i],{type:`application/json`});return navigator.sendBeacon(r,e)}catch{}return typeof fetch<`u`?(fetch(r,{method:`POST`,mode:`cors`,keepalive:!0,headers:{"Content-Type":`application/json`},body:i}).catch(()=>{}),!0):!1},a=async(i,a={})=>Oe(await I(`${e}${i}`,{...a,headers:{"Content-Type":`application/json`,"x-user-id":t,...n?{"x-site-id":n}:{},...r?{"x-visitor-id":r}:{},...a.headers||{}}})),o=async(r,i,a={})=>{let o={"x-user-id":t,...n?{"x-site-id":n}:{},...a.headers||{}};return Oe(await I(`${e}${r}`,{...a,body:i,headers:o}))};return{async loadHistory(e,t=`en`,n=``){return a(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:``,lang:t,category:n})})},async sendAiMessage(i,o,s=`en`,c=``,l=null,u={},d=null){let f={session_id:i,user_query:o,lang:s,category:c,...u||{},...l||{}};if(typeof d!=`function`)return a(`/api/ai/chat`,{method:`POST`,body:JSON.stringify(f)});let p=await I(`${e}/api/ai/chat`,{method:`POST`,headers:{"Content-Type":`application/json`,"x-user-id":t,...n?{"x-site-id":n}:{},...r?{"x-visitor-id":r}:{}},body:JSON.stringify({...f,stream:!0})});if(!(p.headers.get(`content-type`)||``).includes(`text/event-stream`))return Oe(p);let m=p.body.getReader(),h=new TextDecoder,g=``,_=null,v=e=>{let t=e.split(`
2
2
  `).find(e=>e.startsWith(`data: `));if(t)try{let e=JSON.parse(t.slice(6));e.type===`delta`&&e.text?d(e.text):e.type===`done`&&(_=e.payload)}catch{}};for(;;){let{done:e,value:t}=await m.read();if(e)break;g+=h.decode(t,{stream:!0});let n;for(;(n=g.indexOf(`
3
3
 
4
4
  `))!==-1;)v(g.slice(0,n)),g=g.slice(n+2)}if(!_){let e=Error(`The response stream ended unexpectedly — please try again.`);throw e.status=0,e}return _},async uploadChatFile(e){let t=new FormData;return t.append(`file`,e),o(`/api/upload`,t,{method:`POST`})},async checkHumanHandled(e){return a(`/api/ai/check_human_handled`,{method:`POST`,body:JSON.stringify({session_id:e})})},async setChatMode(e,t){return a(`/api/ai/set_chat_mode`,{method:`POST`,body:JSON.stringify({session_id:e,mode:t})})},async toggleVoice(e){return a(`/api/ai/voice/toggle`,{method:`POST`,body:JSON.stringify({session_id:e})})},async syncVoice(e,r){return a(`/api/ai/voice/sync`,{method:`POST`,body:JSON.stringify({session_id:e,messages:r,...t?{userId:String(t)}:{},...n?{siteId:String(n)}:{}})})},async trackVisitor(e){return a(`/api/visitors/track`,{method:`POST`,body:JSON.stringify(e)})},async updateChatStatus(e,t){return a(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:t})})},async startConversation(e,t=`en`){return a(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`open`,lang:t})})},async endConversation(e){return a(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`closed`})})},async getVisitorChatHistory(){return a(`/api/visitors/my-chats`,{method:`GET`})},async getVisitorChatThread(e){return a(`/api/visitors/my-chats/${e}`,{method:`GET`})},async acceptCall(e,t){return a(`/api/calls/${e}/accept`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async rejectCall(e,t){return a(`/api/calls/${e}/reject`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async getIceServersConfig(){return Oe(await I(`${e}/api/calls/ice-config`,{method:`GET`,headers:{"x-user-id":t,...n?{"x-site-id":n}:{}}}))},async endWebRTCCall(e,t){return a(`/api/calls/${e}/end`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n,endedBy:`customer`})})},async markCustomerUnavailable(e,t){return a(`/api/calls/${e}/customer-unavailable`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async uploadRecording(e,t,n){let r=new FormData,i=`call-rec-${Date.now()}.webm`;return r.append(`audio`,t,i),r.append(`duration`,String(n)),o(`/api/calls/${e}/recording`,r,{method:`POST`})},beaconEndWebRTCCall(e,t){return i(`/api/calls/${e}/end`,{session_id:t,site_id:n,endedBy:`customer`})},beaconCustomerUnavailable(e,t){return i(`/api/calls/${e}/customer-unavailable`,{session_id:t,site_id:n})},beaconSyncVoice(r,i){if(typeof navigator>`u`||!navigator.sendBeacon)return!1;let a=new URLSearchParams;return a.append(`session_id`,r),a.append(`messages`,JSON.stringify(i)),t&&a.append(`userId`,String(t)),n&&a.append(`siteId`,String(n)),navigator.sendBeacon(`${e}/api/ai/voice/sync`,a)},beaconWidgetClosed(r){if(typeof navigator>`u`||!navigator.sendBeacon)return!1;let i=new URLSearchParams;return i.append(`chatId`,r),i.append(`type`,`widget_closed`),t&&i.append(`userId`,String(t)),n&&i.append(`siteId`,String(n)),navigator.sendBeacon(`${e}/api/chat/status`,i)}}},Me=Object.create(null);Me.open=`0`,Me.close=`1`,Me.ping=`2`,Me.pong=`3`,Me.message=`4`,Me.upgrade=`5`,Me.noop=`6`;var Ne=Object.create(null);Object.keys(Me).forEach(e=>{Ne[Me[e]]=e});var Pe={type:`error`,data:`parser error`},Fe=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,Ie=typeof ArrayBuffer==`function`,Le=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Re=({type:e,data:t},n,r)=>Fe&&t instanceof Blob?n?r(t):L(t,r):Ie&&(t instanceof ArrayBuffer||Le(t))?n?r(t):L(new Blob([t]),r):r(Me[e]+(t||``)),L=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function R(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var ze;function Be(e,t){if(Fe&&e.data instanceof Blob)return e.data.arrayBuffer().then(R).then(t);if(Ie&&(e.data instanceof ArrayBuffer||Le(e.data)))return t(R(e.data));Re(e,!1,e=>{ze||=new TextEncoder,t(ze.encode(e))})}var Ve=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,z=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)z[Ve.charCodeAt(e)]=e;var He=e=>{let t=e.length*.75,n=e.length,r,i=0,a,o,s,c;e[e.length-1]===`=`&&(t--,e[e.length-2]===`=`&&t--);let l=new ArrayBuffer(t),u=new Uint8Array(l);for(r=0;r<n;r+=4)a=z[e.charCodeAt(r)],o=z[e.charCodeAt(r+1)],s=z[e.charCodeAt(r+2)],c=z[e.charCodeAt(r+3)],u[i++]=a<<2|o>>4,u[i++]=(o&15)<<4|s>>2,u[i++]=(s&3)<<6|c&63;return l},Ue=typeof ArrayBuffer==`function`,We=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:Ke(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:Ge(e.substring(1),t)}:Ne[n]?e.length>1?{type:Ne[n],data:e.substring(1)}:{type:Ne[n]}:Pe},Ge=(e,t)=>Ue?Ke(He(e),t):{base64:!0,data:e},Ke=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},qe=``,Je=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{Re(e,!1,e=>{r[a]=e,++i===n&&t(r.join(qe))})})},Ye=(e,t)=>{let n=e.split(qe),r=[];for(let e=0;e<n.length;e++){let i=We(n[e],t);if(r.push(i),i.type===`error`)break}return r};function B(){return new TransformStream({transform(e,t){Be(e,n=>{let r=n.length,i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);let e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{i=new Uint8Array(9);let e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!=`string`&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}})}var V;function H(e){return e.reduce((e,t)=>e+t.length,0)}function U(e,t){if(e[0].length===t)return e.shift();let n=new Uint8Array(t),r=0;for(let i=0;i<t;i++)n[i]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function Xe(e,t){V||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(H(n)<1)break;let e=U(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(H(n)<2)break;let e=U(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(H(n)<8)break;let e=U(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(Pe);break}i=a*2**32+t.getUint32(4),r=3}else{if(H(n)<i)break;let e=U(n,i);s.enqueue(We(a?e:V.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(Pe);break}}}})}function W(e){if(e)return Ze(e)}function Ze(e){for(var t in W.prototype)e[t]=W.prototype[t];return e}W.prototype.on=W.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},W.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},W.prototype.off=W.prototype.removeListener=W.prototype.removeAllListeners=W.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks[`$`+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks[`$`+e],this;for(var r,i=0;i<n.length;i++)if(r=n[i],r===t||r.fn===t){n.splice(i,1);break}return n.length===0&&delete this._callbacks[`$`+e],this},W.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=Array(arguments.length-1),n=this._callbacks[`$`+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){n=n.slice(0);for(var r=0,i=n.length;r<i;++r)n[r].apply(this,t)}return this},W.prototype.emitReserved=W.prototype.emit,W.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},W.prototype.hasListeners=function(e){return!!this.listeners(e).length};var Qe=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),G=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),$e=`arraybuffer`;function et(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var tt=G.setTimeout,nt=G.clearTimeout;function rt(e,t){t.useNativeTimers?(e.setTimeoutFn=tt.bind(G),e.clearTimeoutFn=nt.bind(G)):(e.setTimeoutFn=G.setTimeout.bind(G),e.clearTimeoutFn=G.clearTimeout.bind(G))}var it=1.33;function at(e){return typeof e==`string`?ot(e):Math.ceil((e.byteLength||e.size)*it)}function ot(e){let t=0,n=0;for(let r=0,i=e.length;r<i;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}function st(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function ct(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function lt(e){let t={},n=e.split(`&`);for(let e=0,r=n.length;e<r;e++){let r=n[e].split(`=`);t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}var ut=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},dt=class extends W{constructor(e){super(),this.writable=!1,rt(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved(`error`,new ut(e,t,n)),this}open(){return this.readyState=`opening`,this.doOpen(),this}close(){return(this.readyState===`opening`||this.readyState===`open`)&&(this.doClose(),this.onClose()),this}send(e){this.readyState===`open`&&this.write(e)}onOpen(){this.readyState=`open`,this.writable=!0,super.emitReserved(`open`)}onData(e){let t=We(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved(`packet`,e)}onClose(e){this.readyState=`closed`,super.emitReserved(`close`,e)}pause(e){}createUri(e,t={}){return e+`://`+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(`:`)===-1?e:`[`+e+`]`}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?`:`+this.opts.port:``}_query(e){let t=ct(e);return t.length?`?`+t:``}},ft=class extends dt{constructor(){super(...arguments),this._polling=!1}get name(){return`polling`}doOpen(){this._poll()}pause(e){this.readyState=`pausing`;let t=()=>{this.readyState=`paused`,e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once(`pollComplete`,function(){--e||t()})),this.writable||(e++,this.once(`drain`,function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved(`poll`)}onData(e){Ye(e,this.socket.binaryType).forEach(e=>{if(this.readyState===`opening`&&e.type===`open`&&this.onOpen(),e.type===`close`)return this.onClose({description:`transport closed by the server`}),!1;this.onPacket(e)}),this.readyState!==`closed`&&(this._polling=!1,this.emitReserved(`pollComplete`),this.readyState===`open`&&this._poll())}doClose(){let e=()=>{this.write([{type:`close`}])};this.readyState===`open`?e():this.once(`open`,e)}write(e){this.writable=!1,Je(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved(`drain`)})})}uri(){let e=this.opts.secure?`https`:`http`,t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=st()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},pt=!1;try{pt=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var mt=pt;function ht(){}var gt=class extends ft{constructor(e){if(super(e),typeof location<`u`){let t=location.protocol===`https:`,n=location.port;n||=t?`443`:`80`,this.xd=typeof location<`u`&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:`POST`,data:e});n.on(`success`,t),n.on(`error`,(e,t)=>{this.onError(`xhr post error`,e,t)})}doPoll(){let e=this.request();e.on(`data`,this.onData.bind(this)),e.on(`error`,(e,t)=>{this.onError(`xhr poll error`,e,t)}),this.pollXhr=e}},_t=class e extends W{constructor(e,t,n){super(),this.createRequest=e,rt(this,n),this._opts=n,this._method=n.method||`GET`,this._uri=t,this._data=n.data===void 0?null:n.data,this._create()}_create(){var t;let n=et(this._opts,`agent`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`autoUnref`);n.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(n);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this._opts.extraHeaders[e])}}catch{}if(this._method===`POST`)try{r.setRequestHeader(`Content-type`,`text/plain;charset=UTF-8`)}catch{}try{r.setRequestHeader(`Accept`,`*/*`)}catch{}(t=this._opts.cookieJar)==null||t.addCookies(r),`withCredentials`in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var e;r.readyState===3&&((e=this._opts.cookieJar)==null||e.parseCookies(r.getResponseHeader(`set-cookie`))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status==`number`?r.status:0)},0))},r.send(this._data)}catch(e){this.setTimeoutFn(()=>{this._onError(e)},0);return}typeof document<`u`&&(this._index=e.requestsCount++,e.requests[this._index]=this)}_onError(e){this.emitReserved(`error`,e,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(this._xhr===void 0||this._xhr===null)){if(this._xhr.onreadystatechange=ht,t)try{this._xhr.abort()}catch{}typeof document<`u`&&delete e.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved(`data`,e),this.emitReserved(`success`),this._cleanup())}abort(){this._cleanup()}};if(_t.requestsCount=0,_t.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,vt);else if(typeof addEventListener==`function`){let e=`onpagehide`in G?`pagehide`:`unload`;addEventListener(e,vt,!1)}}function vt(){for(let e in _t.requests)_t.requests.hasOwnProperty(e)&&_t.requests[e].abort()}var yt=(function(){let e=xt({xdomain:!1});return e&&e.responseType!==null})(),bt=class extends gt{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=yt&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new _t(xt,this.uri(),e)}};function xt(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||mt))return new XMLHttpRequest}catch{}if(!t)try{return new G[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var St=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,Ct=class extends dt{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=St?{}:et(this.opts,`agent`,`perMessageDeflate`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`localAddress`,`protocolVersion`,`origin`,`maxPayload`,`family`,`checkServerIdentity`);this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(e){return this.emitReserved(`error`,e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:`websocket connection closed`,context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError(`websocket error`,e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;Re(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&Qe(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){this.ws!==void 0&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?`wss`:`ws`,t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=st()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},wt=G.WebSocket||G.MozWebSocket,Tt={websocket:class extends Ct{createSocket(e,t,n){return St?new wt(e,t,n):t?new wt(e,t):new wt(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends dt{get name(){return`webtransport`}doOpen(){try{this._transport=new WebTransport(this.createUri(`https`),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved(`error`,e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError(`webtransport error`,e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=Xe(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=B();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();let i=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();let a={type:`open`};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&Qe(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:bt},Et=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Dt=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function Ot(e){if(e.length>8e3)throw`URI too long`;let t=e,n=e.indexOf(`[`),r=e.indexOf(`]`);n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,`;`)+e.substring(r,e.length));let i=Et.exec(e||``),a={},o=14;for(;o--;)a[Dt[o]]=i[o]||``;return n!=-1&&r!=-1&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,`:`),a.authority=a.authority.replace(`[`,``).replace(`]`,``).replace(/;/g,`:`),a.ipv6uri=!0),a.pathNames=kt(a,a.path),a.queryKey=At(a,a.query),a}function kt(e,t){let n=t.replace(/\/{2,9}/g,`/`).split(`/`);return(t.slice(0,1)==`/`||t.length===0)&&n.splice(0,1),t.slice(-1)==`/`&&n.splice(n.length-1,1),n}function At(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var jt=typeof addEventListener==`function`&&typeof removeEventListener==`function`,Mt=[];jt&&addEventListener(`offline`,()=>{Mt.forEach(e=>e())},!1);var Nt=class e extends W{constructor(e,t){if(super(),this.binaryType=$e,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e==`object`&&(t=e,e=null),e){let n=Ot(e);t.hostname=n.host,t.secure=n.protocol===`https`||n.protocol===`wss`,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=Ot(t.host).host);rt(this,t),this.secure=t.secure==null?typeof location<`u`&&location.protocol===`https:`:t.secure,t.hostname&&!t.port&&(t.port=this.secure?`443`:`80`),this.hostname=t.hostname||(typeof location<`u`?location.hostname:`localhost`),this.port=t.port||(typeof location<`u`&&location.port?location.port:this.secure?`443`:`80`),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{let t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:`/engine.io`,agent:!1,withCredentials:!1,upgrade:!0,timestampParam:`t`,rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,``)+(this.opts.addTrailingSlash?`/`:``),typeof this.opts.query==`string`&&(this.opts.query=lt(this.opts.query)),jt&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener(`beforeunload`,this._beforeunloadEventListener,!1)),this.hostname!==`localhost`&&(this._offlineEventListener=()=>{this._onClose(`transport close`,{description:`network connection lost`})},Mt.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);let n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved(`error`,`No transports available`)},0);return}let t=this.opts.rememberUpgrade&&e.priorWebsocketSuccess&&this.transports.indexOf(`websocket`)!==-1?`websocket`:this.transports[0];this.readyState=`opening`;let n=this.createTransport(t);n.open(),this.setTransport(n)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on(`drain`,this._onDrain.bind(this)).on(`packet`,this._onPacket.bind(this)).on(`error`,this._onError.bind(this)).on(`close`,e=>this._onClose(`transport close`,e))}onOpen(){this.readyState=`open`,e.priorWebsocketSuccess=this.transport.name===`websocket`,this.emitReserved(`open`),this.flush()}_onPacket(e){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`)switch(this.emitReserved(`packet`,e),this.emitReserved(`heartbeat`),e.type){case`open`:this.onHandshake(JSON.parse(e.data));break;case`ping`:this._sendPacket(`pong`),this.emitReserved(`ping`),this.emitReserved(`pong`),this._resetPingTimeout();break;case`error`:let t=Error(`server error`);t.code=e.data,this._onError(t);break;case`message`:this.emitReserved(`data`,e.data),this.emitReserved(`message`,e.data);break}}onHandshake(e){this.emitReserved(`handshake`,e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!==`closed`&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose(`ping timeout`)},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved(`drain`):this.flush()}flush(){if(this.readyState!==`closed`&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved(`flush`)}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name===`polling`&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){let n=this.writeBuffer[t].data;if(n&&(e+=at(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,Qe(()=>{this._onClose(`ping timeout`)},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket(`message`,e,t,n),this}send(e,t,n){return this._sendPacket(`message`,e,t,n),this}_sendPacket(e,t,n,r){if(typeof t==`function`&&(r=t,t=void 0),typeof n==`function`&&(r=n,n=null),this.readyState===`closing`||this.readyState===`closed`)return;n||={},n.compress=!1!==n.compress;let i={type:e,data:t,options:n};this.emitReserved(`packetCreate`,i),this.writeBuffer.push(i),r&&this.once(`flush`,r),this.flush()}close(){let e=()=>{this._onClose(`forced close`),this.transport.close()},t=()=>{this.off(`upgrade`,t),this.off(`upgradeError`,t),e()},n=()=>{this.once(`upgrade`,t),this.once(`upgradeError`,t)};return(this.readyState===`opening`||this.readyState===`open`)&&(this.readyState=`closing`,this.writeBuffer.length?this.once(`drain`,()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(t){if(e.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState===`opening`)return this.transports.shift(),this._open();this.emitReserved(`error`,t),this._onClose(`transport error`,t)}_onClose(e,t){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners(`close`),this.transport.close(),this.transport.removeAllListeners(),jt&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=Mt.indexOf(this._offlineEventListener);e!==-1&&Mt.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};Nt.protocol=4;var Pt=class extends Nt{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState===`open`&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;Nt.priorWebsocketSuccess=!1;let r=()=>{n||(t.send([{type:`ping`,data:`probe`}]),t.once(`packet`,e=>{if(!n)if(e.type===`pong`&&e.data===`probe`){if(this.upgrading=!0,this.emitReserved(`upgrading`,t),!t)return;Nt.priorWebsocketSuccess=t.name===`websocket`,this.transport.pause(()=>{n||this.readyState!==`closed`&&(l(),this.setTransport(t),t.send([{type:`upgrade`}]),this.emitReserved(`upgrade`,t),t=null,this.upgrading=!1,this.flush())})}else{let e=Error(`probe error`);e.transport=t.name,this.emitReserved(`upgradeError`,e)}}))};function i(){n||(n=!0,l(),t.close(),t=null)}let a=e=>{let n=Error(`probe error: `+e);n.transport=t.name,i(),this.emitReserved(`upgradeError`,n)};function o(){a(`transport closed`)}function s(){a(`socket closed`)}function c(e){t&&e.name!==t.name&&i()}let l=()=>{t.removeListener(`open`,r),t.removeListener(`error`,a),t.removeListener(`close`,o),this.off(`close`,s),this.off(`upgrading`,c)};t.once(`open`,r),t.once(`error`,a),t.once(`close`,o),this.once(`close`,s),this.once(`upgrading`,c),this._upgrades.indexOf(`webtransport`)!==-1&&e!==`webtransport`?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}},Ft=class extends Pt{constructor(e,t={}){let n=typeof e==`object`?e:t;(!n.transports||n.transports&&typeof n.transports[0]==`string`)&&(n.transports=(n.transports||[`polling`,`websocket`,`webtransport`]).map(e=>Tt[e]).filter(e=>!!e)),super(e,n)}};Ft.protocol;function It(e,t=``,n){let r=e;n||=typeof location<`u`&&location,e??=n.protocol+`//`+n.host,typeof e==`string`&&(e.charAt(0)===`/`&&(e=e.charAt(1)===`/`?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=n===void 0?`https://`+e:n.protocol+`//`+e),r=Ot(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port=`80`:/^(http|ws)s$/.test(r.protocol)&&(r.port=`443`)),r.path=r.path||`/`;let i=r.host.indexOf(`:`)===-1?r.host:`[`+r.host+`]`;return r.id=r.protocol+`://`+i+`:`+r.port+t,r.href=r.protocol+`://`+i+(n&&n.port===r.port?``:`:`+r.port),r}var Lt=typeof ArrayBuffer==`function`,Rt=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,zt=Object.prototype.toString,Bt=typeof Blob==`function`||typeof Blob<`u`&&zt.call(Blob)===`[object BlobConstructor]`,Vt=typeof File==`function`||typeof File<`u`&&zt.call(File)===`[object FileConstructor]`;function Ht(e){return Lt&&(e instanceof ArrayBuffer||Rt(e))||Bt&&e instanceof Blob||Vt&&e instanceof File}function Ut(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(Ut(e[t]))return!0;return!1}if(Ht(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return Ut(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Ut(e[t]))return!0;return!1}function Wt(e){let t=[],n=e.data,r=e;return r.data=Gt(n,t),r.attachments=t.length,{packet:r,buffers:t}}function Gt(e,t){if(!e)return e;if(Ht(e)){let n={_placeholder:!0,num:t.length};return t.push(e),n}else if(Array.isArray(e)){let n=Array(e.length);for(let r=0;r<e.length;r++)n[r]=Gt(e[r],t);return n}else if(typeof e==`object`&&!(e instanceof Date)){let n={};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=Gt(e[r],t));return n}return e}function Kt(e,t){return e.data=qt(e.data,t),delete e.attachments,e}function qt(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num==`number`&&e.num>=0&&e.num<t.length)return t[e.num];throw Error(`illegal attachments`)}else if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=qt(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=qt(e[n],t));return e}var Jt=s({Decoder:()=>Zt,Encoder:()=>Xt,PacketType:()=>K,isPacketValid:()=>an,protocol:()=>5}),Yt=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],K;(function(e){e[e.CONNECT=0]=`CONNECT`,e[e.DISCONNECT=1]=`DISCONNECT`,e[e.EVENT=2]=`EVENT`,e[e.ACK=3]=`ACK`,e[e.CONNECT_ERROR=4]=`CONNECT_ERROR`,e[e.BINARY_EVENT=5]=`BINARY_EVENT`,e[e.BINARY_ACK=6]=`BINARY_ACK`})(K||={});var Xt=class{constructor(e){this.replacer=e}encode(e){return(e.type===K.EVENT||e.type===K.ACK)&&Ut(e)?this.encodeAsBinary({type:e.type===K.EVENT?K.BINARY_EVENT:K.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===K.BINARY_EVENT||e.type===K.BINARY_ACK)&&(t+=e.attachments+`-`),e.nsp&&e.nsp!==`/`&&(t+=e.nsp+`,`),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=Wt(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},Zt=class e extends W{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e==`function`?{reviver:e}:e)}add(e){let t;if(typeof e==`string`){if(this.reconstructor)throw Error(`got plaintext data when reconstructing a packet`);t=this.decodeString(e);let n=t.type===K.BINARY_EVENT;n||t.type===K.BINARY_ACK?(t.type=n?K.EVENT:K.ACK,this.reconstructor=new Qt(t),t.attachments===0&&super.emitReserved(`decoded`,t)):super.emitReserved(`decoded`,t)}else if(Ht(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved(`decoded`,t));else throw Error(`got binary data when not reconstructing a packet`);else throw Error(`Unknown type: `+e)}decodeString(t){let n=0,r={type:Number(t.charAt(0))};if(K[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===K.BINARY_EVENT||r.type===K.BINARY_ACK){let e=n+1;for(;t.charAt(++n)!==`-`&&n!=t.length;);let i=t.substring(e,n);if(i!=Number(i)||t.charAt(n)!==`-`)throw Error(`Illegal attachments`);let a=Number(i);if(!en(a)||a<0)throw Error(`Illegal attachments`);if(a>this.opts.maxAttachments)throw Error(`too many attachments`);r.attachments=a}if(t.charAt(n+1)===`/`){let e=n+1;for(;++n&&!(t.charAt(n)===`,`||n===t.length););r.nsp=t.substring(e,n)}else r.nsp=`/`;let i=t.charAt(n+1);if(i!==``&&Number(i)==i){let e=n+1;for(;++n;){let e=t.charAt(n);if(e==null||Number(e)!=e){--n;break}if(n===t.length)break}r.id=Number(t.substring(e,n+1))}if(t.charAt(++n)){let i=this.tryParse(t.substr(n));if(e.isPayloadValid(r.type,i))r.data=i;else throw Error(`invalid payload`)}return r}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case K.CONNECT:return nn(t);case K.DISCONNECT:return t===void 0;case K.CONNECT_ERROR:return typeof t==`string`||nn(t);case K.EVENT:case K.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&Yt.indexOf(t[0])===-1);case K.ACK:case K.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},Qt=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let e=Kt(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function $t(e){return typeof e==`string`}var en=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function tn(e){return e===void 0||en(e)}function nn(e){return Object.prototype.toString.call(e)===`[object Object]`}function rn(e,t){switch(e){case K.CONNECT:return t===void 0||nn(t);case K.DISCONNECT:return t===void 0;case K.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&Yt.indexOf(t[0])===-1);case K.ACK:return Array.isArray(t);case K.CONNECT_ERROR:return typeof t==`string`||nn(t);default:return!1}}function an(e){return $t(e.nsp)&&tn(e.id)&&rn(e.type,e.data)}function on(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var sn=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),cn=class extends W{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[on(e,`open`,this.onopen.bind(this)),on(e,`packet`,this.onpacket.bind(this)),on(e,`error`,this.onerror.bind(this)),on(e,`close`,this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState===`open`&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift(`message`),this.emit.apply(this,e),this}emit(e,...t){if(sn.hasOwnProperty(e))throw Error(`"`+e.toString()+`" is a reserved event name`);if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let n={type:K.EVENT,data:t};if(n.options={},n.options.compress=this.flags.compress!==!1,typeof t[t.length-1]==`function`){let e=this.ids++,r=t.pop();this._registerAckCallback(e,r),n.id=e}let r=this.io.engine?.transport?.writable,i=this.connected&&!this.io.engine?._hasPingExpired();return this.flags.volatile&&!r||(i?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){let n=this.flags.timeout??this._opts.ackTimeout;if(n===void 0){this.acks[e]=t;return}let r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,Error(`operation has timed out`))},n),i=(...e)=>{this.io.clearTimeoutFn(r),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,r)=>{let i=(e,t)=>e?r(e):n(t);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]==`function`&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>(this._queue[0],e===null?(this._queue.shift(),t&&t(null,...r)):n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth==`function`?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:K.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved(`connect_error`,e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved(`disconnect`,e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){let t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,Error(`socket has been disconnected`))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case K.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved(`connect_error`,Error(`It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)`));break;case K.EVENT:case K.BINARY_EVENT:this.onevent(e);break;case K.ACK:case K.BINARY_ACK:this.onack(e);break;case K.DISCONNECT:this.ondisconnect();break;case K.CONNECT_ERROR:this.destroy();let t=Error(e.data.message);t.data=e.data.data,this.emitReserved(`connect_error`,t);break}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]==`string`&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...r){n||(n=!0,t.packet({type:K.ACK,id:e,data:r}))}}onack(e){let t=this.acks[e.id];typeof t==`function`&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved(`connect`)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose(`io server disconnect`)}destroy(){this.subs&&=(this.subs.forEach(e=>e()),void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:K.DISCONNECT}),this.destroy(),this.connected&&this.onclose(`io client disconnect`),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let n of t)n.apply(this,e.data)}}};function ln(e){e||={},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}ln.prototype.duration=function(){var e=this.ms*this.factor**+ this.attempts++;if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0},ln.prototype.reset=function(){this.attempts=0},ln.prototype.setMin=function(e){this.ms=e},ln.prototype.setMax=function(e){this.max=e},ln.prototype.setJitter=function(e){this.jitter=e};var un=class extends W{constructor(e,t){super(),this.nsps={},this.subs=[],e&&typeof e==`object`&&(t=e,e=void 0),t||={},t.path=t.path||`/socket.io`,this.opts=t,rt(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(t.randomizationFactor??.5),this.backoff=new ln({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState=`closed`,this.uri=e;let n=t.parser||Jt;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)==null||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)==null||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)==null||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf(`open`))return this;this.engine=new Ft(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=on(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=on(t,`error`,i);if(!1!==this._timeout){let e=this._timeout,n=this.setTimeoutFn(()=>{r(),i(Error(`timeout`)),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState=`open`,this.emitReserved(`open`);let e=this.engine;this.subs.push(on(e,`ping`,this.onping.bind(this)),on(e,`data`,this.ondata.bind(this)),on(e,`error`,this.onerror.bind(this)),on(e,`close`,this.onclose.bind(this)),on(this.decoder,`decoded`,this.ondecoded.bind(this)))}onping(){this.emitReserved(`ping`)}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose(`parse error`,e)}}ondecoded(e){Qe(()=>{this.emitReserved(`packet`,e)},this.setTimeoutFn)}onerror(e){this.emitReserved(`error`,e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new cn(this,e,t),this.nsps[e]=n),n}_destroy(e){let t=Object.keys(this.nsps);for(let e of t)if(this.nsps[e].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose(`forced close`)}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),(n=this.engine)==null||n.close(),this.backoff.reset(),this._readyState=`closed`,this.emitReserved(`close`,e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved(`reconnect_failed`),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved(`reconnect_attempt`,e.backoff.attempts),!e.skipReconnect&&e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved(`reconnect_error`,t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved(`reconnect`,e)}},dn={};function fn(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=It(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=dn[i]&&a in dn[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new un(r,t):(dn[i]||(dn[i]=new un(r,t)),c=dn[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(fn,{Manager:un,Socket:cn,io:fn,connect:fn});var pn=({apiBaseUrl:e,userId:t,chatId:n,siteId:r})=>fn(e,{transports:[`polling`,`websocket`],upgrade:!0,rememberUpgrade:!1,auth:{userId:t,chatId:n,siteId:r},query:{chatId:n,siteId:r}}),mn=({socket:e,chatId:t})=>{if(!e||!t||typeof window>`u`)return()=>{};let n=window.location.pathname+window.location.search,r=Date.now(),i=null,a=null,o=()=>{console.log(`[FlowEngageTracking] visitor:session_start`,{chatId:t,path:n}),e.emit(`visitor:session_start`,{chatId:t,path:n,title:document.title,referrer:document.referrer,userAgent:navigator.userAgent,timestamp:Date.now()})},s=()=>{console.log(`[FlowEngageTracking] visitor:page_enter`,{chatId:t,path:n}),e.emit(`visitor:page_enter`,{chatId:t,path:n,title:document.title,timestamp:Date.now()})},c=(n,r)=>{console.log(`[FlowEngageTracking] visitor:page_leave`,{chatId:t,path:n,duration:Math.max(0,Math.floor((Date.now()-r)/1e3))}),e.emit(`visitor:page_leave`,{chatId:t,path:n,duration:Math.max(0,Math.floor((Date.now()-r)/1e3)),timestamp:Date.now()})},l=()=>{console.log(`[FlowEngageTracking] visitor:heartbeat`,{chatId:t,path:n}),e.emit(`visitor:heartbeat`,{chatId:t,path:n,title:document.title,timestamp:Date.now()})},u=()=>{i&&window.clearInterval(i),i=window.setInterval(l,h)},d=()=>{i&&=(window.clearInterval(i),null)},f=r=>{console.log(`[FlowEngageTracking] visitor:visibility`,{chatId:t,state:r}),e.emit(`visitor:visibility`,{chatId:t,state:r,path:n,title:document.title,timestamp:Date.now()})},p=()=>{if(document.hidden){a&&window.clearTimeout(a),a=window.setTimeout(()=>{a=null,d(),f(`hidden`)},g);return}a&&=(window.clearTimeout(a),null),f(`visible`),l(),u()},m=()=>{let e=window.location.pathname+window.location.search;if(e===n){console.log(`[FlowEngageTracking] route unchanged`,{currentPath:n});return}console.log(`[FlowEngageTracking] route changed`,{from:n,to:e}),c(n,r),n=e,r=Date.now(),s()},_=window.history.pushState.bind(window.history),v=window.history.replaceState.bind(window.history);window.history.pushState=(...e)=>{_(...e),m()},window.history.replaceState=(...e)=>{v(...e),m()};let y=()=>{c(n,r),e.emit(`visitor:session_end`,{chatId:t,timestamp:Date.now()})},b=()=>{y()},x=e=>{e.persisted||y()};return window.addEventListener(`popstate`,m),window.addEventListener(`hashchange`,m),window.addEventListener(`beforeunload`,b),window.addEventListener(`pagehide`,x),window.addEventListener(`visibilitychange`,p),o(),document.hidden?a=window.setTimeout(()=>{a=null,d(),f(`hidden`)},g):(l(),u()),{notifyRouteChange:m,cleanup:()=>{a&&=(window.clearTimeout(a),null),d(),window.history.pushState=_,window.history.replaceState=v,window.removeEventListener(`popstate`,m),window.removeEventListener(`hashchange`,m),window.removeEventListener(`beforeunload`,b),window.removeEventListener(`pagehide`,x),window.removeEventListener(`visibilitychange`,p)}}},hn=(0,d.createContext)(null),gn=()=>{let e=(0,d.useContext)(hn);if(!e)throw Error(`useFlowEngage must be used inside FlowEngageProvider`);return e};function _n(){if(typeof window>`u`)return!1;try{let e=window.localStorage?.getItem(`FE_DEBUG_VOICE`);if(e===`0`||e===`false`)return!1;if(e===`1`||e===`true`)return!0}catch{}return window.__FE_DEBUG_VOICE_TOOLS__===!1?!1:window.__FE_DEBUG_VOICE_TOOLS__===!0}var vn=80;function yn(e){requestAnimationFrame(()=>{let t=e.getBoundingClientRect(),n=t.top+t.height/2,r=vn+(window.innerHeight-vn)/2,i=window.pageYOffset+n-r;window.scrollTo({top:Math.max(0,i),behavior:`smooth`})})}function bn(e){e&&(e.hasAttribute(`data-fe-highlighted`)||(xn(),e.classList?.remove(`fe-highlight-section`,`fe-highlight-speaking`,`fe-highlight-exiting`),yn(e),e.setAttribute(`data-fe-orig-style`,e.style.cssText),e.setAttribute(`data-fe-highlighted`,`true`),e.style.outline=`3px solid #2563eb`,e.style.outlineOffset=`8px`,e.style.background=`rgba(37, 99, 235, 0.08)`,e.style.borderRadius=`8px`,e.style.padding=`12px 16px`,e.style.transition=`all 0.4s ease`))}function xn(){let e=document.querySelector(`[data-fe-highlighted]`);e&&(e.style.cssText=e.getAttribute(`data-fe-orig-style`)||``,e.removeAttribute(`data-fe-highlighted`),e.removeAttribute(`data-fe-orig-style`))}var Sn=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function Cn(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(Sn)}catch{return!1}}function wn(e){let t=e.cloneNode(!0);return t.querySelectorAll(`[aria-hidden], svg, .icon, [class*="icon"]`).forEach(e=>e.remove()),t.textContent.replace(/\s+/g,` `).trim()}function q(...e){_n()&&console.log(`[FlowEngage:shadowNavigate]`,...e)}var Tn=`fe_pending_nav_section`,En=15e3,Dn=`fe_voice_nav_state`,On=2e4,kn=!1,An=null;function jn(e=3e3){kn=!0,An&&clearTimeout(An),An=setTimeout(()=>{kn=!1,An=null},e)}function Mn(){return kn}var Nn=!1,Pn=null;function Fn(){Nn||typeof window>`u`||(Nn=!0,window.addEventListener(`popstate`,async()=>{let e=window.location.href;if(q(`popstate: body-swap to`,e),Pn){try{Wn(Pn)}catch{}try{qn(Pn)}catch{}}try{if(await cr(e,{skipPushState:!0,isBack:!0})){q(`popstate: body-swap succeeded`);return}}catch(e){console.warn(`[FlowEngage] popstate body-swap error:`,e)}q(`popstate: body-swap failed, falling back to reload`),window.location.reload()}))}var In=!1;function Ln(){In||typeof window>`u`||typeof document>`u`||(In=!0,document.addEventListener(`click`,async e=>{try{if(!window.history.state?.flowengageSpa)return}catch{return}let t=e.target.closest?.(`a[href]`);if(!t||t.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`))return;let n=t.getAttribute(`href`)||``;if(!n||n===`#`||n.startsWith(`javascript:`)||n.startsWith(`mailto:`)||n.startsWith(`tel:`)||t.hasAttribute(`download`)||t.target===`_blank`||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey)return;let r;try{if(r=new URL(n,window.location.href),r.origin!==window.location.origin)return}catch{return}if(!(r.pathname===window.location.pathname&&r.hash)&&!(r.pathname===window.location.pathname&&r.search===window.location.search)){e.preventDefault(),e.stopPropagation(),q(`link-intercept: body-swap to`,r.href),Zn();try{try{Wn()}catch{}try{qn()}catch{}if(await cr(r.href)){q(`link-intercept: body-swap succeeded`);return}}catch(e){console.warn(`[FlowEngage] link-intercept body-swap error:`,e)}q(`link-intercept: body-swap failed, falling back to normal navigation`),Qn(),window.location.href=r.href}},!0))}var Rn=null;function zn(e){Rn=e===`spa`||e===`traditional`?e:null}function Bn(){if(typeof window>`u`||Rn===`traditional`)return null;if(window.next?.router||window.__NEXT_ROUTER__)return`nextjs`;if(window.__remixRouter||window.__staticRouterHydrationData)return`react-router`;if(window.___gatsby||window.___navigate)return`gatsby`;if(window.__VUE_ROUTER__)return`vue-router`;if(window.__NUXT__||window.$nuxt)return`nuxt`;if(window.ng?.getComponent||document.querySelector(`[ng-version]`))return`angular`;if(window[Symbol.for(`wouter_v3`)])return`wouter`;if(window.__sveltekit_data||document.querySelector(`[data-sveltekit-hydrate]`))return`sveltekit`;if(document.querySelector(`[data-astro-transition]`))return`astro`;for(let e of document.body.children)if(e.tagName?.toUpperCase()===`DIV`&&e.id!==`flowengage-root`&&(e.id===`root`||e.id===`app`)&&e.children.length>0)return`generic-spa`;return Rn===`spa`?`backend-spa`:null}var Vn=`data-fe-swap-css`;function Hn(){typeof document>`u`||document.querySelectorAll(`[${Vn}]`).forEach(e=>e.remove())}var Un=`fe_form_state:`;function Wn(e){if(typeof document>`u`||typeof sessionStorage>`u`)return;let t=document.querySelectorAll(`form`);if(!t.length)return;let n=[];if(t.forEach((e,t)=>{let r={};e.querySelectorAll(`input, textarea, select`).forEach(e=>{let t=e.name||e.id;t&&(e.type===`password`||e.type===`hidden`||(e.type===`checkbox`||e.type===`radio`?r[t+`::`+e.value]=e.checked:r[t]=e.value))}),Object.keys(r).length&&n.push({formIndex:t,fields:r})}),n.length)try{let t=Un+(e||window.location.pathname);sessionStorage.setItem(t,JSON.stringify({state:n,ts:Date.now()}))}catch{}}function Gn(){if(typeof document>`u`||typeof sessionStorage>`u`)return;let e=Un+window.location.pathname,t;try{t=JSON.parse(sessionStorage.getItem(e)||`null`)}catch{return}if(!t||!t.state)return;if(Date.now()-t.ts>1800*1e3){try{sessionStorage.removeItem(e)}catch{}return}let n=document.querySelectorAll(`form`);for(let{formIndex:e,fields:r}of t.state){let t=n[e];if(t)for(let[e,n]of Object.entries(r))if(e.includes(`::`)){let[r,i]=e.split(`::`),a=t.querySelector(`input[name="${r}"][value="${i}"], input[id="${r}"][value="${i}"]`);a&&(a.checked=!!n)}else{let r=t.querySelector(`[name="${e}"], [id="${e}"]`);if(r&&r.type!==`file`){r.value=n;try{r.dispatchEvent(new Event(`input`,{bubbles:!0}))}catch{}try{r.dispatchEvent(new Event(`change`,{bubbles:!0}))}catch{}}}}try{sessionStorage.removeItem(e)}catch{}}var Kn=`fe_scroll:`;function qn(e){if(!(typeof window>`u`||typeof sessionStorage>`u`))try{let t=Kn+(e||window.location.pathname);sessionStorage.setItem(t,JSON.stringify({y:window.scrollY,ts:Date.now()}))}catch{}}function Jn(){if(typeof window>`u`||typeof sessionStorage>`u`)return;let e=Kn+window.location.pathname,t;try{t=JSON.parse(sessionStorage.getItem(e)||`null`)}catch{return}if(t){try{sessionStorage.removeItem(e)}catch{}Date.now()-t.ts>1800*1e3||setTimeout(()=>{window.scrollTo({top:t.y,behavior:`instant`})},80)}}function Yn(e){if(!(typeof window>`u`))try{window.dispatchEvent(new CustomEvent(`flowengage:pageswap`,{detail:{url:e,timestamp:Date.now()}}))}catch{}}var Xn=`fe-nav-loader`;function Zn(){if(typeof document>`u`||document.getElementById(Xn))return;let e=document.createElement(`div`);e.id=Xn,e.style.cssText=[`position:fixed`,`top:0`,`left:0`,`width:0`,`height:3px`,`background:linear-gradient(90deg,#7c3aed,#6366f1)`,`z-index:2147483647`,`transition:width 0.4s ease`,`pointer-events:none`].join(`;`),document.body.appendChild(e),requestAnimationFrame(()=>{e.style.width=`70%`})}function Qn(){if(typeof document>`u`)return;let e=document.getElementById(Xn);e&&(e.style.width=`100%`,setTimeout(()=>{e.style.opacity=`0`,e.style.transition=`opacity 0.3s ease`,setTimeout(()=>e.remove(),350)},200))}function $n(){if(typeof window>`u`||typeof document>`u`)return;try{window.history.state?.flowengageSpa&&Fn()}catch{}let e;try{e=JSON.parse(sessionStorage.getItem(Tn)||`null`)}catch{return}if(!e)return;try{sessionStorage.removeItem(Tn)}catch{}let{sectionText:t,ts:n}=e;if(!t)return;if(Date.now()-n>En){q(`initNavigationHighlight: pending section expired, skipping:`,t);return}q(`initNavigationHighlight: replaying section highlight:`,t);let r=0,i=()=>{r+=1;let e=tr(null,t);if(e){nr(e),q(`initNavigationHighlight: highlighted on attempt`,r);return}r<8?setTimeout(i,300):q(`initNavigationHighlight: could not find element after 8 attempts:`,t)};setTimeout(i,250)}var er=()=>{if(typeof document>`u`||document.getElementById(`fe-highlight-styles`))return;let e=document.createElement(`style`);e.id=`fe-highlight-styles`,e.textContent=`
@@ -18,7 +18,7 @@ var v = Object.defineProperty, y = Object.getOwnPropertyDescriptor, b = Object.g
18
18
  }, T = (e) => x.call(e, "module.exports") ? e["module.exports"] : w(v({}, "__esModule", { value: !0 }), e), E = (e) => {
19
19
  if (!e || typeof e != "object") throw Error("FlowEngage config is required");
20
20
  if (!e.siteId || typeof e.siteId != "string") throw Error("[FlowEngage] config.siteId is required. Pass it as <FlowEngageProvider siteId=\"your-site-id\" /> or config={{ siteId: 'your-site-id' }}.");
21
- let t = (e.apiBaseUrl || "https://be-flowengage-stage.oslabs.app").replace(/\/+$/, "");
21
+ let t = (e.apiBaseUrl || "https://be-flowengage-dev.oslabs.app").replace(/\/+$/, "");
22
22
  return {
23
23
  siteId: e.siteId.trim(),
24
24
  apiBaseUrl: t
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flowengage/react-chatbot",
3
- "version": "8.0.126",
3
+ "version": "8.0.127",
4
4
  "description": "Embeddable AI chat widget for React — powered by FlowEngage. Drop it in with a single siteId.",
5
5
  "keywords": [
6
6
  "chatbot",