@flowengage/react-chatbot 1.5.4 → 1.5.5
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
|
-
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.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,ee=()=>{if(!x)return null;let e=window.localStorage.getItem(_.chatId);return e&&String(e).trim()?String(e).trim():null},te=()=>{if(x)try{window.localStorage.removeItem(_.chatId)}catch{}},C=()=>x?typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`:`server-chat-id`,ne=e=>e?`flowengage.persistedChatId.${e}`:null,re=e=>{if(!x||!e)return null;try{let t=ne(e),n=t?window.localStorage.getItem(t):null;return n&&String(n).trim()?String(n).trim():null}catch{return null}},ie=(e,t)=>{if(!(!x||!e||!t))try{let n=ne(e);n&&window.localStorage.setItem(n,String(t).trim())}catch{}},ae=()=>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:``},oe=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))}})},se=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||``},ce=(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)},le=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},ue=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}},de=async({apiBaseUrl:e,userId:t,siteId:n,priorChatId:r=null})=>{let i=`${e}/api/visitors/resolve-session`,a={siteId:n};return r&&String(r).trim()&&(a.priorChatId=String(r).trim()),le(await ue(i,{method:`POST`,mode:`cors`,headers:{"Content-Type":`application/json`,"x-user-id":t==null?``:String(t),...n?{"x-site-id":n}:{}},body:JSON.stringify(a)}))},fe=async({apiBaseUrl:e,siteId:t})=>{let n=typeof window<`u`?window.location.origin:`http://localhost`,r=`${e}/api/widget/chatbot-loader?${new URLSearchParams({siteId:t,origin:n}).toString()}`;console.log(`[FlowEngageAPI] bootstrap request`,{apiBaseUrl:e,siteId:t,origin:n,url:r});let i=await le(await ue(r,{method:`GET`}));return console.log(`[FlowEngageAPI] bootstrap success`,i),i.data},pe=({apiBaseUrl:e,userId:t,siteId:n})=>{let r=(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},i=async(r,i={})=>le(await ue(`${e}${r}`,{...i,headers:{"Content-Type":`application/json`,"x-user-id":t,...n?{"x-site-id":n}:{},...i.headers||{}}})),a=async(r,i,a={})=>{let o={"x-user-id":t,...n?{"x-site-id":n}:{},...a.headers||{}};return le(await ue(`${e}${r}`,{...a,body:i,headers:o}))};return{async loadHistory(e,t=`en`,n=``){return i(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:``,lang:t,category:n})})},async sendAiMessage(e,t,n=`en`,r=``,a=null,o={}){return i(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:t,lang:n,category:r,...o||{},...a||{}})})},async uploadChatFile(e){let t=new FormData;return t.append(`file`,e),a(`/api/upload`,t,{method:`POST`})},async checkHumanHandled(e){return i(`/api/ai/check_human_handled`,{method:`POST`,body:JSON.stringify({session_id:e})})},async setChatMode(e,t){return i(`/api/ai/set_chat_mode`,{method:`POST`,body:JSON.stringify({session_id:e,mode:t})})},async toggleVoice(e){return i(`/api/ai/voice/toggle`,{method:`POST`,body:JSON.stringify({session_id:e})})},async syncVoice(e,r){return i(`/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 i(`/api/visitors/track`,{method:`POST`,body:JSON.stringify(e)})},async updateChatStatus(e,t){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:t})})},async startConversation(e,t=`en`){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`open`,lang:t})})},async endConversation(e){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`closed`})})},async acceptCall(e,t){return i(`/api/calls/${e}/accept`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async rejectCall(e,t){return i(`/api/calls/${e}/reject`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async getIceServersConfig(){return le(await ue(`${e}/api/calls/ice-config`,{method:`GET`,headers:{"x-user-id":t,...n?{"x-site-id":n}:{}}}))},async endWebRTCCall(e,t){return i(`/api/calls/${e}/end`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n,endedBy:`customer`})})},async markCustomerUnavailable(e,t){return i(`/api/calls/${e}/customer-unavailable`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},beaconEndWebRTCCall(e,t){return r(`/api/calls/${e}/end`,{session_id:t,site_id:n,endedBy:`customer`})},beaconCustomerUnavailable(e,t){return r(`/api/calls/${e}/customer-unavailable`,{session_id:t,site_id:n})},beaconSyncVoice(r,i){if(typeof navigator>`u`||!navigator.sendBeacon)return!1;let a={session_id:r,messages:i,...t?{userId:String(t)}:{},...n?{siteId:String(n)}:{}},o=new Blob([JSON.stringify(a)],{type:`application/json`});return navigator.sendBeacon(`${e}/api/ai/voice/sync`,o)}}},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 he=Object.create(null);Object.keys(me).forEach(e=>{he[me[e]]=e});var ge={type:`error`,data:`parser error`},_e=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,ve=typeof ArrayBuffer==`function`,w=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,ye=({type:e,data:t},n,r)=>_e&&t instanceof Blob?n?r(t):be(t,r):ve&&(t instanceof ArrayBuffer||w(t))?n?r(t):be(new Blob([t]),r):r(me[e]+(t||``)),be=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function xe(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var Se;function Ce(e,t){if(_e&&e.data instanceof Blob)return e.data.arrayBuffer().then(xe).then(t);if(ve&&(e.data instanceof ArrayBuffer||w(e.data)))return t(xe(e.data));ye(e,!1,e=>{Se||=new TextEncoder,t(Se.encode(e))})}var we=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Te=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)Te[we.charCodeAt(e)]=e;var Ee=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=Te[e.charCodeAt(r)],o=Te[e.charCodeAt(r+1)],s=Te[e.charCodeAt(r+2)],c=Te[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},De=typeof ArrayBuffer==`function`,Oe=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:Ae(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:ke(e.substring(1),t)}:he[n]?e.length>1?{type:he[n],data:e.substring(1)}:{type:he[n]}:ge},ke=(e,t)=>De?Ae(Ee(e),t):{base64:!0,data:e},Ae=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},je=``,Me=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{ye(e,!1,e=>{r[a]=e,++i===n&&t(r.join(je))})})},Ne=(e,t)=>{let n=e.split(je),r=[];for(let e=0;e<n.length;e++){let i=Oe(n[e],t);if(r.push(i),i.type===`error`)break}return r};function Pe(){return new TransformStream({transform(e,t){Ce(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 Fe;function T(e){return e.reduce((e,t)=>e+t.length,0)}function Ie(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 Le(e,t){Fe||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(T(n)<1)break;let e=Ie(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(T(n)<2)break;let e=Ie(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(T(n)<8)break;let e=Ie(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(ge);break}i=a*2**32+t.getUint32(4),r=3}else{if(T(n)<i)break;let e=Ie(n,i);s.enqueue(Oe(a?e:Fe.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(ge);break}}}})}function E(e){if(e)return Re(e)}function Re(e){for(var t in E.prototype)e[t]=E.prototype[t];return e}E.prototype.on=E.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},E.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},E.prototype.off=E.prototype.removeListener=E.prototype.removeAllListeners=E.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},E.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},E.prototype.emitReserved=E.prototype.emit,E.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},E.prototype.hasListeners=function(e){return!!this.listeners(e).length};var ze=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Be=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),Ve=`arraybuffer`;function He(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var Ue=Be.setTimeout,We=Be.clearTimeout;function Ge(e,t){t.useNativeTimers?(e.setTimeoutFn=Ue.bind(Be),e.clearTimeoutFn=We.bind(Be)):(e.setTimeoutFn=Be.setTimeout.bind(Be),e.clearTimeoutFn=Be.clearTimeout.bind(Be))}var Ke=1.33;function D(e){return typeof e==`string`?O(e):Math.ceil((e.byteLength||e.size)*Ke)}function O(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 qe(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Je(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function Ye(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 Xe=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},Ze=class extends E{constructor(e){super(),this.writable=!1,Ge(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 Xe(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=Oe(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=Je(e);return t.length?`?`+t:``}},Qe=class extends Ze{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){Ne(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,Me(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]=qe()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},k=!1;try{k=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var $e=k;function et(){}var tt=class extends Qe{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}},nt=class e extends E{constructor(e,t,n){super(),this.createRequest=e,Ge(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=He(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=et,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(nt.requestsCount=0,nt.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,rt);else if(typeof addEventListener==`function`){let e=`onpagehide`in Be?`pagehide`:`unload`;addEventListener(e,rt,!1)}}function rt(){for(let e in nt.requests)nt.requests.hasOwnProperty(e)&&nt.requests[e].abort()}var it=(function(){let e=ot({xdomain:!1});return e&&e.responseType!==null})(),at=class extends tt{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=it&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new nt(ot,this.uri(),e)}};function ot(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||$e))return new XMLHttpRequest}catch{}if(!t)try{return new Be[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var st=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,ct=class extends Ze{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=st?{}:He(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;ye(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&ze(()=>{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]=qe()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},lt=Be.WebSocket||Be.MozWebSocket,ut={websocket:class extends ct{createSocket(e,t,n){return st?new lt(e,t,n):t?new lt(e,t):new lt(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends Ze{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=Le(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=Pe();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&&ze(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:at},dt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ft=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function pt(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=dt.exec(e||``),a={},o=14;for(;o--;)a[ft[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=mt(a,a.path),a.queryKey=ht(a,a.query),a}function mt(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 ht(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var gt=typeof addEventListener==`function`&&typeof removeEventListener==`function`,_t=[];gt&&addEventListener(`offline`,()=>{_t.forEach(e=>e())},!1);var vt=class e extends E{constructor(e,t){if(super(),this.binaryType=Ve,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=pt(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=pt(t.host).host);Ge(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=Ye(this.opts.query)),gt&&(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`})},_t.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+=D(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,ze(()=>{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(),gt&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=_t.indexOf(this._offlineEventListener);e!==-1&&_t.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};vt.protocol=4;var yt=class extends vt{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;vt.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;vt.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}},bt=class extends yt{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=>ut[e]).filter(e=>!!e)),super(e,n)}};bt.protocol;function xt(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=pt(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 St=typeof ArrayBuffer==`function`,Ct=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,wt=Object.prototype.toString,Tt=typeof Blob==`function`||typeof Blob<`u`&&wt.call(Blob)===`[object BlobConstructor]`,Et=typeof File==`function`||typeof File<`u`&&wt.call(File)===`[object FileConstructor]`;function Dt(e){return St&&(e instanceof ArrayBuffer||Ct(e))||Tt&&e instanceof Blob||Et&&e instanceof File}function Ot(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(Ot(e[t]))return!0;return!1}if(Dt(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return Ot(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Ot(e[t]))return!0;return!1}function kt(e){let t=[],n=e.data,r=e;return r.data=At(n,t),r.attachments=t.length,{packet:r,buffers:t}}function At(e,t){if(!e)return e;if(Dt(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]=At(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]=At(e[r],t));return n}return e}function jt(e,t){return e.data=Mt(e.data,t),delete e.attachments,e}function Mt(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]=Mt(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=Mt(e[n],t));return e}var Nt=s({Decoder:()=>It,Encoder:()=>Ft,PacketType:()=>A,isPacketValid:()=>Ut,protocol:()=>5}),Pt=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],A;(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`})(A||={});var Ft=class{constructor(e){this.replacer=e}encode(e){return(e.type===A.EVENT||e.type===A.ACK)&&Ot(e)?this.encodeAsBinary({type:e.type===A.EVENT?A.BINARY_EVENT:A.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===A.BINARY_EVENT||e.type===A.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=kt(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},It=class e extends E{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===A.BINARY_EVENT;n||t.type===A.BINARY_ACK?(t.type=n?A.EVENT:A.ACK,this.reconstructor=new Lt(t),t.attachments===0&&super.emitReserved(`decoded`,t)):super.emitReserved(`decoded`,t)}else if(Dt(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(A[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===A.BINARY_EVENT||r.type===A.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(!zt(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 A.CONNECT:return Vt(t);case A.DISCONNECT:return t===void 0;case A.CONNECT_ERROR:return typeof t==`string`||Vt(t);case A.EVENT:case A.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&Pt.indexOf(t[0])===-1);case A.ACK:case A.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},Lt=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=jt(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function Rt(e){return typeof e==`string`}var zt=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function Bt(e){return e===void 0||zt(e)}function Vt(e){return Object.prototype.toString.call(e)===`[object Object]`}function Ht(e,t){switch(e){case A.CONNECT:return t===void 0||Vt(t);case A.DISCONNECT:return t===void 0;case A.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&Pt.indexOf(t[0])===-1);case A.ACK:return Array.isArray(t);case A.CONNECT_ERROR:return typeof t==`string`||Vt(t);default:return!1}}function Ut(e){return Rt(e.nsp)&&Bt(e.id)&&Ht(e.type,e.data)}function Wt(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var Gt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Kt=class extends E{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=[Wt(e,`open`,this.onopen.bind(this)),Wt(e,`packet`,this.onpacket.bind(this)),Wt(e,`error`,this.onerror.bind(this)),Wt(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(Gt.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:A.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:A.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 A.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 A.EVENT:case A.BINARY_EVENT:this.onevent(e);break;case A.ACK:case A.BINARY_ACK:this.onack(e);break;case A.DISCONNECT:this.ondisconnect();break;case A.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:A.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:A.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 qt(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}qt.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},qt.prototype.reset=function(){this.attempts=0},qt.prototype.setMin=function(e){this.ms=e},qt.prototype.setMax=function(e){this.max=e},qt.prototype.setJitter=function(e){this.jitter=e};var Jt=class extends E{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,Ge(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 qt({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||Nt;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 bt(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=Wt(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=Wt(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(Wt(e,`ping`,this.onping.bind(this)),Wt(e,`data`,this.ondata.bind(this)),Wt(e,`error`,this.onerror.bind(this)),Wt(e,`close`,this.onclose.bind(this)),Wt(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){ze(()=>{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 Kt(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)}},Yt={};function Xt(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=xt(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=Yt[i]&&a in Yt[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new Jt(r,t):(Yt[i]||(Yt[i]=new Jt(r,t)),c=Yt[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(Xt,{Manager:Jt,Socket:Kt,io:Xt,connect:Xt});var Zt=({apiBaseUrl:e,userId:t,chatId:n,siteId:r})=>Xt(e,{transports:[`polling`,`websocket`],upgrade:!0,rememberUpgrade:!1,auth:{userId:t,chatId:n,siteId:r},query:{chatId:n,siteId:r}}),Qt=({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()})};return window.addEventListener(`popstate`,m),window.addEventListener(`hashchange`,m),window.addEventListener(`beforeunload`,y),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`,y),window.removeEventListener(`visibilitychange`,p)}}},$t=(0,d.createContext)(null),en=()=>{let e=(0,d.useContext)($t);if(!e)throw Error(`useFlowEngage must be used inside FlowEngageProvider`);return e};function tn(){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}function nn(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)}catch{return!1}}function rn(...e){tn()&&console.log(`[FlowEngage:shadowNavigate]`,...e)}var an=`fe_pending_nav_section`,on=15e3;function sn(){if(typeof window>`u`||typeof document>`u`)return;let e;try{e=JSON.parse(sessionStorage.getItem(an)||`null`)}catch{return}if(!e)return;try{sessionStorage.removeItem(an)}catch{}let{sectionText:t,ts:n}=e;if(!t)return;if(Date.now()-n>on){rn(`initNavigationHighlight: pending section expired, skipping:`,t);return}rn(`initNavigationHighlight: replaying section highlight:`,t);let r=0,i=()=>{r+=1;let e=ln(null,t);if(e){un(e),rn(`initNavigationHighlight: highlighted on attempt`,r);return}r<8?setTimeout(i,300):rn(`initNavigationHighlight: could not find element after 8 attempts:`,t)};setTimeout(i,250)}var cn=()=>{if(typeof document>`u`||document.getElementById(`fe-highlight-styles`))return;let e=document.createElement(`style`);e.id=`fe-highlight-styles`,e.textContent=`
|
|
1
|
+
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.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,ee=()=>{if(!x)return null;let e=window.localStorage.getItem(_.chatId);return e&&String(e).trim()?String(e).trim():null},te=()=>{if(x)try{window.localStorage.removeItem(_.chatId)}catch{}},C=()=>x?typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`:`server-chat-id`,ne=e=>e?`flowengage.persistedChatId.${e}`:null,re=e=>{if(!x||!e)return null;try{let t=ne(e),n=t?window.localStorage.getItem(t):null;return n&&String(n).trim()?String(n).trim():null}catch{return null}},ie=(e,t)=>{if(!(!x||!e||!t))try{let n=ne(e);n&&window.localStorage.setItem(n,String(t).trim())}catch{}},ae=()=>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:``},oe=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))}})},se=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||``},ce=(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)},le=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},ue=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}},de=async({apiBaseUrl:e,userId:t,siteId:n,priorChatId:r=null})=>{let i=`${e}/api/visitors/resolve-session`,a={siteId:n};return r&&String(r).trim()&&(a.priorChatId=String(r).trim()),le(await ue(i,{method:`POST`,mode:`cors`,headers:{"Content-Type":`application/json`,"x-user-id":t==null?``:String(t),...n?{"x-site-id":n}:{}},body:JSON.stringify(a)}))},fe=async({apiBaseUrl:e,siteId:t})=>{let n=typeof window<`u`?window.location.origin:`http://localhost`,r=`${e}/api/widget/chatbot-loader?${new URLSearchParams({siteId:t,origin:n}).toString()}`;console.log(`[FlowEngageAPI] bootstrap request`,{apiBaseUrl:e,siteId:t,origin:n,url:r});let i=await le(await ue(r,{method:`GET`}));return console.log(`[FlowEngageAPI] bootstrap success`,i),i.data},pe=({apiBaseUrl:e,userId:t,siteId:n})=>{let r=(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},i=async(r,i={})=>le(await ue(`${e}${r}`,{...i,headers:{"Content-Type":`application/json`,"x-user-id":t,...n?{"x-site-id":n}:{},...i.headers||{}}})),a=async(r,i,a={})=>{let o={"x-user-id":t,...n?{"x-site-id":n}:{},...a.headers||{}};return le(await ue(`${e}${r}`,{...a,body:i,headers:o}))};return{async loadHistory(e,t=`en`,n=``){return i(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:``,lang:t,category:n})})},async sendAiMessage(e,t,n=`en`,r=``,a=null,o={}){return i(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:t,lang:n,category:r,...o||{},...a||{}})})},async uploadChatFile(e){let t=new FormData;return t.append(`file`,e),a(`/api/upload`,t,{method:`POST`})},async checkHumanHandled(e){return i(`/api/ai/check_human_handled`,{method:`POST`,body:JSON.stringify({session_id:e})})},async setChatMode(e,t){return i(`/api/ai/set_chat_mode`,{method:`POST`,body:JSON.stringify({session_id:e,mode:t})})},async toggleVoice(e){return i(`/api/ai/voice/toggle`,{method:`POST`,body:JSON.stringify({session_id:e})})},async syncVoice(e,r){return i(`/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 i(`/api/visitors/track`,{method:`POST`,body:JSON.stringify(e)})},async updateChatStatus(e,t){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:t})})},async startConversation(e,t=`en`){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`open`,lang:t})})},async endConversation(e){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`closed`})})},async acceptCall(e,t){return i(`/api/calls/${e}/accept`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async rejectCall(e,t){return i(`/api/calls/${e}/reject`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async getIceServersConfig(){return le(await ue(`${e}/api/calls/ice-config`,{method:`GET`,headers:{"x-user-id":t,...n?{"x-site-id":n}:{}}}))},async endWebRTCCall(e,t){return i(`/api/calls/${e}/end`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n,endedBy:`customer`})})},async markCustomerUnavailable(e,t){return i(`/api/calls/${e}/customer-unavailable`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},beaconEndWebRTCCall(e,t){return r(`/api/calls/${e}/end`,{session_id:t,site_id:n,endedBy:`customer`})},beaconCustomerUnavailable(e,t){return r(`/api/calls/${e}/customer-unavailable`,{session_id:t,site_id:n})},beaconSyncVoice(r,i){if(typeof navigator>`u`||!navigator.sendBeacon)return!1;let a={session_id:r,messages:i,...t?{userId:String(t)}:{},...n?{siteId:String(n)}:{}},o=new Blob([JSON.stringify(a)],{type:`application/json`});return navigator.sendBeacon(`${e}/api/ai/voice/sync`,o)}}},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 he=Object.create(null);Object.keys(me).forEach(e=>{he[me[e]]=e});var ge={type:`error`,data:`parser error`},_e=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,ve=typeof ArrayBuffer==`function`,w=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,ye=({type:e,data:t},n,r)=>_e&&t instanceof Blob?n?r(t):be(t,r):ve&&(t instanceof ArrayBuffer||w(t))?n?r(t):be(new Blob([t]),r):r(me[e]+(t||``)),be=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function xe(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var Se;function Ce(e,t){if(_e&&e.data instanceof Blob)return e.data.arrayBuffer().then(xe).then(t);if(ve&&(e.data instanceof ArrayBuffer||w(e.data)))return t(xe(e.data));ye(e,!1,e=>{Se||=new TextEncoder,t(Se.encode(e))})}var we=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Te=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)Te[we.charCodeAt(e)]=e;var Ee=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=Te[e.charCodeAt(r)],o=Te[e.charCodeAt(r+1)],s=Te[e.charCodeAt(r+2)],c=Te[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},De=typeof ArrayBuffer==`function`,Oe=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:Ae(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:ke(e.substring(1),t)}:he[n]?e.length>1?{type:he[n],data:e.substring(1)}:{type:he[n]}:ge},ke=(e,t)=>De?Ae(Ee(e),t):{base64:!0,data:e},Ae=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},je=``,Me=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{ye(e,!1,e=>{r[a]=e,++i===n&&t(r.join(je))})})},Ne=(e,t)=>{let n=e.split(je),r=[];for(let e=0;e<n.length;e++){let i=Oe(n[e],t);if(r.push(i),i.type===`error`)break}return r};function Pe(){return new TransformStream({transform(e,t){Ce(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 Fe;function T(e){return e.reduce((e,t)=>e+t.length,0)}function Ie(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 Le(e,t){Fe||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(T(n)<1)break;let e=Ie(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(T(n)<2)break;let e=Ie(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(T(n)<8)break;let e=Ie(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(ge);break}i=a*2**32+t.getUint32(4),r=3}else{if(T(n)<i)break;let e=Ie(n,i);s.enqueue(Oe(a?e:Fe.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(ge);break}}}})}function E(e){if(e)return Re(e)}function Re(e){for(var t in E.prototype)e[t]=E.prototype[t];return e}E.prototype.on=E.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},E.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},E.prototype.off=E.prototype.removeListener=E.prototype.removeAllListeners=E.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},E.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},E.prototype.emitReserved=E.prototype.emit,E.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},E.prototype.hasListeners=function(e){return!!this.listeners(e).length};var ze=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Be=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),Ve=`arraybuffer`;function He(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var Ue=Be.setTimeout,We=Be.clearTimeout;function Ge(e,t){t.useNativeTimers?(e.setTimeoutFn=Ue.bind(Be),e.clearTimeoutFn=We.bind(Be)):(e.setTimeoutFn=Be.setTimeout.bind(Be),e.clearTimeoutFn=Be.clearTimeout.bind(Be))}var Ke=1.33;function D(e){return typeof e==`string`?O(e):Math.ceil((e.byteLength||e.size)*Ke)}function O(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 qe(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Je(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function Ye(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 Xe=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},Ze=class extends E{constructor(e){super(),this.writable=!1,Ge(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 Xe(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=Oe(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=Je(e);return t.length?`?`+t:``}},Qe=class extends Ze{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){Ne(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,Me(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]=qe()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},k=!1;try{k=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var $e=k;function et(){}var tt=class extends Qe{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}},nt=class e extends E{constructor(e,t,n){super(),this.createRequest=e,Ge(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=He(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=et,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(nt.requestsCount=0,nt.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,rt);else if(typeof addEventListener==`function`){let e=`onpagehide`in Be?`pagehide`:`unload`;addEventListener(e,rt,!1)}}function rt(){for(let e in nt.requests)nt.requests.hasOwnProperty(e)&&nt.requests[e].abort()}var it=(function(){let e=ot({xdomain:!1});return e&&e.responseType!==null})(),at=class extends tt{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=it&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new nt(ot,this.uri(),e)}};function ot(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||$e))return new XMLHttpRequest}catch{}if(!t)try{return new Be[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var st=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,ct=class extends Ze{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=st?{}:He(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;ye(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&ze(()=>{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]=qe()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},lt=Be.WebSocket||Be.MozWebSocket,ut={websocket:class extends ct{createSocket(e,t,n){return st?new lt(e,t,n):t?new lt(e,t):new lt(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends Ze{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=Le(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=Pe();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&&ze(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:at},dt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ft=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function pt(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=dt.exec(e||``),a={},o=14;for(;o--;)a[ft[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=mt(a,a.path),a.queryKey=ht(a,a.query),a}function mt(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 ht(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var gt=typeof addEventListener==`function`&&typeof removeEventListener==`function`,_t=[];gt&&addEventListener(`offline`,()=>{_t.forEach(e=>e())},!1);var vt=class e extends E{constructor(e,t){if(super(),this.binaryType=Ve,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=pt(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=pt(t.host).host);Ge(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=Ye(this.opts.query)),gt&&(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`})},_t.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+=D(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,ze(()=>{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(),gt&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=_t.indexOf(this._offlineEventListener);e!==-1&&_t.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};vt.protocol=4;var yt=class extends vt{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;vt.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;vt.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}},bt=class extends yt{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=>ut[e]).filter(e=>!!e)),super(e,n)}};bt.protocol;function xt(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=pt(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 St=typeof ArrayBuffer==`function`,Ct=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,wt=Object.prototype.toString,Tt=typeof Blob==`function`||typeof Blob<`u`&&wt.call(Blob)===`[object BlobConstructor]`,Et=typeof File==`function`||typeof File<`u`&&wt.call(File)===`[object FileConstructor]`;function Dt(e){return St&&(e instanceof ArrayBuffer||Ct(e))||Tt&&e instanceof Blob||Et&&e instanceof File}function Ot(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(Ot(e[t]))return!0;return!1}if(Dt(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return Ot(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Ot(e[t]))return!0;return!1}function kt(e){let t=[],n=e.data,r=e;return r.data=At(n,t),r.attachments=t.length,{packet:r,buffers:t}}function At(e,t){if(!e)return e;if(Dt(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]=At(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]=At(e[r],t));return n}return e}function jt(e,t){return e.data=Mt(e.data,t),delete e.attachments,e}function Mt(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]=Mt(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=Mt(e[n],t));return e}var Nt=s({Decoder:()=>It,Encoder:()=>Ft,PacketType:()=>A,isPacketValid:()=>Ut,protocol:()=>5}),Pt=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],A;(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`})(A||={});var Ft=class{constructor(e){this.replacer=e}encode(e){return(e.type===A.EVENT||e.type===A.ACK)&&Ot(e)?this.encodeAsBinary({type:e.type===A.EVENT?A.BINARY_EVENT:A.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===A.BINARY_EVENT||e.type===A.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=kt(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},It=class e extends E{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===A.BINARY_EVENT;n||t.type===A.BINARY_ACK?(t.type=n?A.EVENT:A.ACK,this.reconstructor=new Lt(t),t.attachments===0&&super.emitReserved(`decoded`,t)):super.emitReserved(`decoded`,t)}else if(Dt(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(A[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===A.BINARY_EVENT||r.type===A.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(!zt(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 A.CONNECT:return Vt(t);case A.DISCONNECT:return t===void 0;case A.CONNECT_ERROR:return typeof t==`string`||Vt(t);case A.EVENT:case A.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&Pt.indexOf(t[0])===-1);case A.ACK:case A.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},Lt=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=jt(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function Rt(e){return typeof e==`string`}var zt=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function Bt(e){return e===void 0||zt(e)}function Vt(e){return Object.prototype.toString.call(e)===`[object Object]`}function Ht(e,t){switch(e){case A.CONNECT:return t===void 0||Vt(t);case A.DISCONNECT:return t===void 0;case A.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&Pt.indexOf(t[0])===-1);case A.ACK:return Array.isArray(t);case A.CONNECT_ERROR:return typeof t==`string`||Vt(t);default:return!1}}function Ut(e){return Rt(e.nsp)&&Bt(e.id)&&Ht(e.type,e.data)}function Wt(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var Gt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Kt=class extends E{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=[Wt(e,`open`,this.onopen.bind(this)),Wt(e,`packet`,this.onpacket.bind(this)),Wt(e,`error`,this.onerror.bind(this)),Wt(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(Gt.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:A.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:A.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 A.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 A.EVENT:case A.BINARY_EVENT:this.onevent(e);break;case A.ACK:case A.BINARY_ACK:this.onack(e);break;case A.DISCONNECT:this.ondisconnect();break;case A.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:A.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:A.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 qt(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}qt.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},qt.prototype.reset=function(){this.attempts=0},qt.prototype.setMin=function(e){this.ms=e},qt.prototype.setMax=function(e){this.max=e},qt.prototype.setJitter=function(e){this.jitter=e};var Jt=class extends E{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,Ge(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 qt({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||Nt;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 bt(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=Wt(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=Wt(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(Wt(e,`ping`,this.onping.bind(this)),Wt(e,`data`,this.ondata.bind(this)),Wt(e,`error`,this.onerror.bind(this)),Wt(e,`close`,this.onclose.bind(this)),Wt(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){ze(()=>{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 Kt(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)}},Yt={};function Xt(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=xt(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=Yt[i]&&a in Yt[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new Jt(r,t):(Yt[i]||(Yt[i]=new Jt(r,t)),c=Yt[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(Xt,{Manager:Jt,Socket:Kt,io:Xt,connect:Xt});var Zt=({apiBaseUrl:e,userId:t,chatId:n,siteId:r})=>Xt(e,{transports:[`polling`,`websocket`],upgrade:!0,rememberUpgrade:!1,auth:{userId:t,chatId:n,siteId:r},query:{chatId:n,siteId:r}}),Qt=({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)}}},$t=(0,d.createContext)(null),en=()=>{let e=(0,d.useContext)($t);if(!e)throw Error(`useFlowEngage must be used inside FlowEngageProvider`);return e};function tn(){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}function nn(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)}catch{return!1}}function rn(...e){tn()&&console.log(`[FlowEngage:shadowNavigate]`,...e)}var an=`fe_pending_nav_section`,on=15e3;function sn(){if(typeof window>`u`||typeof document>`u`)return;let e;try{e=JSON.parse(sessionStorage.getItem(an)||`null`)}catch{return}if(!e)return;try{sessionStorage.removeItem(an)}catch{}let{sectionText:t,ts:n}=e;if(!t)return;if(Date.now()-n>on){rn(`initNavigationHighlight: pending section expired, skipping:`,t);return}rn(`initNavigationHighlight: replaying section highlight:`,t);let r=0,i=()=>{r+=1;let e=ln(null,t);if(e){un(e),rn(`initNavigationHighlight: highlighted on attempt`,r);return}r<8?setTimeout(i,300):rn(`initNavigationHighlight: could not find element after 8 attempts:`,t)};setTimeout(i,250)}var cn=()=>{if(typeof document>`u`||document.getElementById(`fe-highlight-styles`))return;let e=document.createElement(`style`);e.id=`fe-highlight-styles`,e.textContent=`
|
|
2
2
|
.fe-highlight-section {
|
|
3
3
|
outline: 3px solid #7c3aed !important;
|
|
4
4
|
box-shadow: 0 0 15px rgba(124, 58, 237, 0.6) !important;
|
|
@@ -602,7 +602,7 @@ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
|
|
|
602
602
|
fill="white" stroke="#1e1b4b" stroke-width="1.6" stroke-linejoin="round"
|
|
603
603
|
filter="url(#${Q}-csh)"/>
|
|
604
604
|
</svg>`,fD=null,pD=!1;function mD(){return(!fD||!fD.isConnected)&&(fD=document.createElement(`div`),fD.id=`${Q}-cursor`,fD.innerHTML=dD,document.body.appendChild(fD),pD=!1),fD}async function hD(e){if(typeof document>`u`||!e)return;ZE();let t;try{t=e.getBoundingClientRect()}catch{return}let n=t.left+Math.min(16,t.width*.2),r=t.top+Math.min(12,t.height*.25),i=mD();pD||=(i.style.transition=`none`,i.style.left=`${window.innerWidth/2}px`,i.style.top=`${window.innerHeight*.4}px`,i.classList.add(`${Q}-cursor-visible`),i.offsetHeight,i.style.transition=`left 0.32s cubic-bezier(0.25,0.46,0.45,0.94), top 0.32s cubic-bezier(0.25,0.46,0.45,0.94), opacity 0.2s ease`,!0),i.style.left=`${n}px`,i.style.top=`${r}px`,await yD(360)}function gD(e=!1){fD&&(e?(fD.classList.remove(`${Q}-cursor-visible`),pD=!1):(fD.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{pD=!1},250)))}async function _D(e){fD&&(fD.classList.add(`${Q}-cursor-click`),await yD(280),fD.classList.remove(`${Q}-cursor-click`))}function vD(e){if(!e||typeof document>`u`)return;ZE();let t;try{t=e.getBoundingClientRect()}catch{return}let n=e.style.position,r=e.style.overflow,i=window.getComputedStyle(e).position;[`relative`,`absolute`,`fixed`,`sticky`].includes(i)||(e.style.position=`relative`),e.style.overflow=`hidden`;let a=document.createElement(`span`);a.className=`${Q}-ripple`;let o=Math.max(t.width,t.height)*1.2;Object.assign(a.style,{width:`${o}px`,height:`${o}px`,left:`${t.width/2-o/2}px`,top:`${t.height/2-o/2}px`}),e.appendChild(a),setTimeout(()=>{a.remove(),e.style.position=n,e.style.overflow=r},650)}function yD(e){return new Promise(t=>setTimeout(t,e))}function $(...e){tn()&&console.log(`[FlowEngage:voice-tools]`,...e)}function bD(e){return new Promise(t=>setTimeout(t,e))}var xD=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function SD(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(xD)}catch{return!1}}function CD(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function wD(e){let t=new Set;function n(r){if(!r||t.has(r))return;t.add(r),e(r);let i=r.querySelectorAll(`iframe`);for(let e of i)if(!SD(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function TD(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function ED(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return TD(r.join(` `))}if(e.labels&&e.labels.length)return TD(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return TD(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return TD(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return TD(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=TD(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return TD(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return TD(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?TD(o):null}function DD(){let e=[];return wD(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(SD(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=CD(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function OD(){return DD().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:ED(e),placeholder:e.placeholder||null}))}function kD(){let e=[];return wD(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(SD(e)||e.disabled)return!1;try{let t=CD(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e.slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function AD(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function jD(e){let t=AD(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function MD(e,t){let n=jD(t);if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|site|audit/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|site|audit/.test(n))return 100;let a=[e.name,e.id,e.placeholder,ED(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>AD(e)),o=0;for(let e of a){if(!e)continue;if(e.includes(n)||n.includes(e)){o=Math.max(o,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);o=Math.max(o,r/t.length*88)}return o}var ND=28;function PD(e,t){let n=null,r=0;for(let i of e){let e=MD(i,t);e>r&&(r=e,n=i)}return!n||r<ND?null:n}function FD(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,ED(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function ID(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function LD(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function RD(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function zD(e){if(!RD(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,ED(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function BD(e,t,n){let r=String(t??``),i=String(n??``),a=UD(e,r)||PD(e,r)||FD(e,r,i);if(!a)return[];let o=new Set([a]);if(ID(i)&&LD(r))for(let t of e)t!==a&&zD(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function VD(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function HD(e){if(!e||typeof e!=`string`)return null;let t=null;return wD(n=>{try{let r=n.getElementById(e);r&&!SD(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function UD(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=HD(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=HD(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function WD(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r.includes(n))return 100;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function GD(e,t){let n=[];wD(e=>{n.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(SD(e)||e.disabled)return!1;try{let t=CD(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:WD(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<36)return null;let a=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(a.length===1)return a[0];let o=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(o.length){let e=a[0],t=1/0;for(let n of a)for(let r of o){let i=VD(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function KD(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function qD(e){let t=KD(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function JD(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t||/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i.test(t))return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function YD(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=/\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i,a=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},o=t.match(/^\s*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\s*$/i);if(o)return a(`Email Address`,o[1]),n;let s=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),s&&a(`Full Name`,s[1]),s=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),s){let e=s[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&a(`Full Name`,e)}if(s=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),s){let e=s[1].trim();e.length>0&&a(`Message`,e)}if(!n.some(e=>/email/i.test(String(e.field_key)))){let e=t.match(i);if(e){let r=t.replace(e[0],``).trim().replace(/^(please|it's|it is|use|is|my email is|e-?mail is)\s*/i,``).replace(/[.,;:!?]+$/,``).trim();if(t.length<=96&&r.length<=36)return a(`Email Address`,e[1]),n}}if(n.length===0){let e=t.split(/\s+/).filter(Boolean).length,n=/[.!?]/.test(t)||e>=6||t.length>=24&&e>=5||t.length>=42,r=/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(t.trim());n&&t.length>=16&&!i.test(t)&&!r&&a(`Message`,t)}return n}function XD(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function ZD(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function QD(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase();if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(i===`checkbox`||i===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let a=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=e.ownerDocument?.defaultView||window,n=r===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(n,`value`);i?.set?i.set.call(e,a):e.value=a}else e.value=a;let o={bubbles:!0,cancelable:!0,composed:!0};try{e.dispatchEvent(new InputEvent(`input`,{...o,inputType:`insertText`,data:a}))}catch{e.dispatchEvent(new Event(`input`,o))}e.dispatchEvent(new Event(`change`,o));try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,o)),e.dispatchEvent(new Event(`change`,o))}catch{}})}catch{}return!0}function $D(){let e={};document.querySelectorAll(`h1, h2, h3, h4, h5, h6`).forEach(t=>{if(t.id)return;let n=t.textContent.trim();if(!n)return;let r=n.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).substring(0,60);if(e[r]){let t=2;for(;e[r+`-`+t];)t++;r=r+`-`+t}e[r]=!0,t.id=r})}function eO(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={flowengage_navigate:async n=>{$(`flowengage_navigate ▶ raw parameters:`,n);let r=KD(n),i=XD(r),a=r.section_text??r.sectionText??r.section;if($(`flowengage_navigate · coerced:`,{url:i,sectionText:a}),!i){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`flowengage_navigate ✖`,e),e}if(!await mn(i,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`That page is not available in the site index; answer without navigating.`;return $(`flowengage_navigate ✖ blocked`,e),e}try{if(tD(`Navigating to ${i}...`,{spinner:!0}),oD(),UE(),XE(),$(`flowengage_navigate → shadowNavigate`,i),await gn(i),await bD(400),$D(),a&&typeof a==`string`){let e=ln(null,a);e&&BE(()=>YE(e)),$(`flowengage_navigate · highlight`,{sectionText:a,found:!!e})}let e=`OK_NAVIGATION ${i}`;return $(`flowengage_navigate ✓`,e),tD(`Navigation complete`,{spinner:!1,icon:`✅`,duration:1200}),e}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`flowengage_navigate ✖`,t),tD(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{sD(),nD(900)}},flowengage_highlight:async e=>{$(`flowengage_highlight ▶`,e);let t=KD(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText,i=ln(n||null,r||null);return i?(BE(()=>YE(i)),$(`flowengage_highlight ✓ (enqueued)`),`Highlighted the section.`):($(`flowengage_highlight ✖ no element`),`Could not find that section on the page.`)},flowengage_read_content:async e=>{$(`flowengage_read_content ▶`,e);let t=KD(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=ln(null,n);if(!t)return`Could not find section "${n}" on the page.`;let r=[t.textContent.trim()],i=t.nextElementSibling;for(;i&&!/^H[1-3]$/i.test(i.tagName);){let e=i.textContent.trim();e&&r.push(e),i=i.nextElementSibling}e=r.join(`
|
|
605
|
-
`)}else{let t=(document.querySelector(`main`)||document.querySelector(`article`)||document.querySelector(`[role="main"]`)||document.querySelector(`#content`)||document.querySelector(`.content`)||document.body).cloneNode(!0);t.querySelectorAll(`nav, footer, header, aside, script, style, noscript, .nav, .footer, .header, .sidebar`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),$(`flowengage_read_content ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return $(`flowengage_read_content ✖`,e.message),`Could not read page content: ${e.message}`}},flowengage_search:async e=>{$(`flowengage_search ▶`,e);let r=ZD(KD(e));if($(`flowengage_search · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`flowengage_search ✖ missing query`),`Missing query parameter.`;if(!t)return $(`flowengage_search ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`flowengage_search ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`flowengage_search → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`flowengage_search · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`flowengage_search ✖`,e),e}let o=a.results||[];return $(`flowengage_search ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`flowengage_search ✖`,t),t}},flowengage_page_content:async e=>{$(`flowengage_page_content ▶`,e);let r=KD(e),i=r?.url||r?.page_url||``;if($(`flowengage_page_content · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return $(`flowengage_page_content ✖ missing url`),`Missing url parameter.`;if(!t)return $(`flowengage_page_content ✖ no siteId`),`Site is not configured.`;if(!n)return $(`flowengage_page_content ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;$(`flowengage_page_content → POST`,e);let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,url:i})}),a=await r.json();if($(`flowengage_page_content · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return $(`flowengage_page_content ✖`,e),e}return $(`flowengage_page_content ✓`,`title: ${a.title}`,`sections: ${(a.sections||[]).length}`,`content: ${(a.content||``).length} chars`),JSON.stringify({title:a.title,url:a.url,sections:a.sections,content:a.content})}catch(e){let t=`Page content error: ${e.message||`network`}`;return $(`flowengage_page_content ✖`,t),t}},flowengage_end_session:async()=>($(`flowengage_end_session ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),flowengage_list_forms:async()=>{let e=OD(),t=kD();return $(`flowengage_list_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, flowengage_fill_form sets all matching URL inputs. flowengage_click_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},flowengage_fill_form:async e=>{try{$(`flowengage_fill_form ▶ raw:`,e),cD();let t=qD(e);if(!t.length&&r){let e=r(),n=JD(e);n.length?$(`flowengage_fill_form · inferred URL from last user utterance (model omitted usable fields):`,n):(n=YD(e),n.length&&$(`flowengage_fill_form · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`flowengage_fill_form · normalized fields:`,t),!t.length)return`No fields provided. Call flowengage_list_forms for field_key strings, then flowengage_fill_form with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;tD(`Filling ${String(t)}...`,{spinner:!0});let a=DD(),o=BD(a,String(t),r);if(o.length){for(let[e,t]of o.entries())lD(t),await hD(t),QD(t,r,{skipScroll:e>0}),uD(t),await bD(120);i=o,n.push(String(t));continue}let s=UD(a,String(t));s||=PD(a,String(t)),s||=FD(a,String(t),r),s&&(lD(s),await hD(s),QD(s,r),uD(s),await bD(120),i=[s],n.push(String(t)))}if(!n.length)return $(`flowengage_fill_form ✖ no matches`),`Could not match any fields. Call flowengage_list_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let a=`OK_FILLED: ${n.join(`, `)}`;return $(`flowengage_fill_form ✓`,a),tD(`Form filled`,{spinner:!1,icon:`✅`,duration:1100}),a}catch(e){let t=`flowengage_fill_form error: ${e?.message||String(e)}`;return $(`flowengage_fill_form ✖`,t),tD(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{gD(),cD(),nD(700)}},flowengage_click_button:async e=>{let t=KD(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`flowengage_click_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=GD(n,i);if(!r)return $(`flowengage_click_button ✖ no match`),`Could not find a button matching "${n}". Call flowengage_list_forms to see button texts.`;try{tD(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await hD(r),r.focus?.(),await _D(r),vD(r),r.click();let e=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`flowengage_click_button ✓`,t),tD(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`flowengage_click_button ✖`,t),tD(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{gD(),nD(700)}}};return{...a,navigateToPage:a.flowengage_navigate,highlightOnPage:a.flowengage_highlight,searchSiteContent:a.flowengage_search,getPageContent:a.flowengage_page_content,endVoiceSession:a.flowengage_end_session,listPageForms:a.flowengage_list_forms,fillFormFields:a.flowengage_fill_form,clickPageButton:a.flowengage_click_button}}function tO(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=tn();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i;try{i=await t(n)}catch(t){let n=`Tool error: ${t?.message||String(t)}`;return console.error(`[FlowEngage] voice tool ${e} threw:`,t),n}let a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var nO={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function rO(e){if(!Array.isArray(e)||e.length<2)return`linear-gradient(145deg, #dce8f022 0%, #e8dff522 45%, #f5e0e022 100%), #f7f8fa`;let[t,n,r]=e;return e.length>=3&&r?[`radial-gradient(ellipse 80% 70% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 70% 80% at 110% 30%, ${n}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 60% at 50% 110%, ${r}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `):[`radial-gradient(ellipse 80% 100% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 100% at 110% 50%, ${n}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `)}function iO(e){if(!e||typeof e!=`string`)return`#1a1a1a`;let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t,r=parseInt(n.slice(0,2),16)/255,i=parseInt(n.slice(2,4),16)/255,a=parseInt(n.slice(4,6),16)/255,o=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4;return .2126*o(r)+.7152*o(i)+.0722*o(a)>.179?`#1a1a1a`:`#ffffff`}function aO({logo:e,style:t}){if(!e)return null;if(typeof e==`string`)return(0,f.jsx)(`img`,{src:e,alt:``,style:{objectFit:`contain`,flexShrink:0,display:`block`,...t}});let n=typeof e==`function`?d.default.createElement(e):d.default.isValidElement(e)?e:null;return n?(0,f.jsx)(`span`,{className:`fe-logo-slot`,style:{display:`inline-flex`,alignItems:`center`,flexShrink:0,overflow:`hidden`,...t},children:n}):null}function oO({title:e}){return(0,f.jsx)(`div`,{style:{width:`100%`,height:`100%`,borderRadius:`16px`,background:`linear-gradient(135deg, rgba(59,130,246,0.16) 0%, rgba(59,130,246,0.08) 100%)`,color:`#2563eb`,display:`flex`,alignItems:`center`,justifyContent:`center`,fontSize:`18px`,fontWeight:700,letterSpacing:`-0.03em`},children:String(e||`FE`).split(/\s+/).filter(Boolean).slice(0,2).map(e=>e[0]?.toUpperCase()||``).join(``)||`FE`})}function sO(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(that'?s all|we'?re done)\b/i.test(n)||e===`bot`&&(/\b(I'?ll|I will|Let me|I can|I'?m going to)\s+(end|close)\s+(the\s+)?(voice\s+)?(session|call)\b/i.test(n)||/\b(ending|closing)\s+(the\s+)?(voice\s+)?session\b|\bvoice\s+session\s+(is\s+)?(now\s+)?(ended|over|closing)\b/i.test(n)||/\b(session|call)\s+(is\s+)?(now\s+)?(ended|over)\b/i.test(n)||/\bwe\s+can\s+end\s+(the\s+)?(session|call)?\s*(here|now)\b/i.test(n)||/\b(wrapping\s+up|signing\s+off)\b/i.test(n))||/^(goodbye|bye|that'?s all|we'?re done|hang up|disconnect)\b/i.test(n)):!1}function cO({orbColors:e,...t}){return(0,f.jsx)(IE,{colors:e,...t})}function lO({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a}){let o=n||nO.green,s=iO(o),c=a?72:94,l=(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:a?`14px`:`18px`},children:[(0,f.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(pp.p,{initial:{x:-16,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.36},style:{margin:`0 0 14px`,fontSize:a?`16px`:`18px`,fontWeight:700,color:`white`,lineHeight:1.4,textShadow:`0 1px 4px rgba(0,0,0,0.35)`,maxWidth:a?void 0:`210px`},children:e.entryPrompt}),(0,f.jsxs)(pp.div,{initial:{y:10,opacity:0},animate:{y:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.54},style:{display:`flex`,gap:`8px`,flexWrap:`nowrap`},children:[(0,f.jsx)(`button`,{onClick:r,style:{padding:a?`9px 20px`:`10px 28px`,borderRadius:`999px`,background:o,color:s,fontWeight:700,fontSize:a?`14px`:`15px`,border:`none`,cursor:`pointer`,whiteSpace:`nowrap`,boxShadow:`0 4px 16px ${o}66`,transition:`transform 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.04)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.yesLabel}),(0,f.jsx)(`button`,{onClick:i,style:{padding:a?`9px 16px`:`10px 22px`,borderRadius:`999px`,background:`transparent`,color:`white`,fontWeight:600,fontSize:a?`14px`:`15px`,border:`2px solid rgba(255,255,255,0.55)`,cursor:`pointer`,whiteSpace:`nowrap`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.9)`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.55)`},children:e.laterLabel})]})]}),(0,f.jsx)(pp.div,{initial:{x:120,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:220,damping:22,delay:0},style:{flexShrink:0},children:(0,f.jsx)(cO,{size:c,orbColors:t})})]});return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(pp.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.4},style:{position:`fixed`,inset:0,background:`rgba(0,0,0,0.72)`,zIndex:-1}}),a?(0,f.jsx)(`div`,{style:{position:`absolute`,bottom:0,left:0,right:0,padding:`24px 20px 40px`,overflow:`hidden`},children:l}):l]})}function uO({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a}){let o=n||nO.green,s=iO(o);return(0,f.jsxs)(pp.div,{initial:{scale:50/300,borderRadius:`50%`},animate:{scale:1,borderRadius:`24px`},transition:{type:`spring`,stiffness:260,damping:26},style:{transformOrigin:`bottom right`,background:`white`,padding:`28px 28px 24px`,width:`300px`,display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`20px`,boxShadow:`0 20px 60px rgba(0,0,0,0.2)`,position:`relative`,overflow:`hidden`},children:[(0,f.jsx)(`button`,{onClick:a,style:{position:`absolute`,top:`14px`,right:`14px`,background:`none`,border:`none`,cursor:`pointer`,color:`#9ca3af`,padding:`4px`,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,f.jsx)(cO,{size:82,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,fontSize:`17px`,fontWeight:600,color:`#111827`,textAlign:`center`,lineHeight:1.4},children:e.connectionTitle}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,width:`100%`},children:[(0,f.jsx)(`button`,{onClick:r,style:{flex:1,padding:`12px`,borderRadius:`999px`,background:o,color:s,fontWeight:700,fontSize:`15px`,border:`none`,cursor:`pointer`,transition:`transform 0.15s ease`,boxShadow:`0 4px 12px ${o}55`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.03)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.voiceLabel}),(0,f.jsx)(`button`,{onClick:i,style:{flex:1,padding:`12px`,borderRadius:`999px`,background:`transparent`,color:`#111827`,fontWeight:600,fontSize:`15px`,border:`2px solid #d1d5db`,cursor:`pointer`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`#6b7280`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`#d1d5db`},children:e.textLabel})]})]})}function dO({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,historyRef:o,onMessageSync:s}){let[c,l]=(0,d.useState)(`idle`),[u,p]=(0,d.useState)(!1),[m,h]=(0,d.useState)(!1),g=(0,d.useRef)(null),_=(0,d.useRef)(``),v=(0,d.useRef)(async()=>{}),y=(0,d.useRef)(!1),b=(0,d.useRef)(!1),x=(0,d.useRef)(!1),S=(0,d.useRef)(!1),ee=(0,d.useRef)(`minimized`),te=(0,d.useRef)(null),C=(0,d.useCallback)((e=`minimized`)=>{ee.current=e,S.current=!0,queueMicrotask(()=>{y.current||(y.current=!0,v.current?.())})},[o]),ne=(0,d.useCallback)(async e=>{S.current=!0;try{await g.current?.endSession?.()}catch{}g.current=null,l(`idle`),p(!1),y.current=!1,typeof s==`function`&&await s(o.current),e?.()},[o,s]);return v.current=()=>ne(ee.current===`chat`?t:n),(0,d.useEffect)(()=>{b.current=u},[u]),(0,d.useEffect)(()=>{let e=!1,n=null;return(async()=>{if(!r){l(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;o.current=[],_.current=``,y.current=!1,x.current=!1,S.current=!1,ee.current=`minimized`;let t=tO(eO({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>_.current,requestEndSession:()=>{C()}})),s=await nE.startSession({agentId:r,clientTools:t,onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onModeChange:({mode:t})=>{e||l(t===`speaking`?`speaking`:`listening`)},onMessage:t=>{if(e)return;let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;r&&(n===`user`&&(_.current=r),o.current=[...o.current,{sender:n,message:r,timestamp:new Date().toISOString()}],sO(n,r)&&C(`minimized`))},onError:t=>{if(!e&&!S.current&&!x.current){x.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{g.current?.setMicMuted?.(!0)}catch{}p(!0),l(`error`),C(`chat`)}},onDisconnect:()=>{if(!e&&!S.current&&!x.current){x.current=!0,console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:o.current?.length||0,lastUserText:_.current||``,wasMuted:b.current});try{g.current?.setMicMuted?.(!0)}catch{}p(!0),C(`chat`)}}});if(e){s.endSession().catch(()=>{});return}n=s,g.current=s,l(`listening`);try{let e=typeof window<`u`?window.location.href:``,n=`[]`;try{n=await t.list_page_forms()}catch{}s.sendContextualUpdate(`Page: ${e}. SiteId: ${i||`unknown`}. Forms: ${n}. Voice: call end_voice_session or say you are ending the session to stop.`)}catch{}}catch(n){e||(console.error(`[FlowEngage] startSession failed`,n),l(`error`),ee.current=`chat`,window.setTimeout(()=>{e||t?.()},0))}})(),()=>{e=!0,S.current=!0,(n||g.current)?.endSession?.().catch(()=>{})}},[r,i,a,C]),(0,d.useEffect)(()=>{if(!m)return;let e=e=>{te.current&&!te.current.contains(e.target)&&h(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[m]),(0,f.jsx)(f.Fragment,{children:(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`14px`,animation:`fe-orb-slide-up 0.42s cubic-bezier(0.16,1,0.3,1)`},children:[(0,f.jsxs)(`div`,{style:{position:`relative`},children:[c===`listening`&&(0,f.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`white`,fontSize:`18px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Listening...`}),(0,f.jsx)(cO,{size:94,voiceState:c,isMuted:u,orbColors:e})]}),c===`error`&&(0,f.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,f.jsx)(`button`,{onClick:async()=>{if(g.current)try{u?(await g.current.setMicMuted?.(!1),p(!1)):(await g.current.setMicMuted?.(!0),p(!0))}catch{}},title:u?`Unmute`:`Mute`,style:{width:`44px`,height:`44px`,borderRadius:`50%`,background:u?`#7f1d1d`:`#1f2937`,border:u?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:u?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`},children:u?(0,f.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,f.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,f.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,f.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,f.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,f.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:`currentColor`,stroke:`none`}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]})}),(0,f.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:te,children:[(0,f.jsx)(`button`,{onClick:()=>h(e=>!e),style:{width:`44px`,height:`44px`,borderRadius:`50%`,background:`#1f2937`,border:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`,transition:`background 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`},children:(0,f.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`currentColor`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.8`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.8`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.8`})]})}),m&&(0,f.jsxs)(`div`,{style:{position:`absolute`,bottom:`54px`,right:0,zIndex:9999,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,f.jsxs)(`button`,{onClick:()=>{h(!1),ee.current=`chat`,ne(t)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`path`,{d:`M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z`})}),`Enter Chat Mode`]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{onClick:()=>{h(!1),ee.current=`minimized`,ne(n)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,f.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),`End Conversation`]})]})]})]})]})})}function fO({orbColors:e}){return(0,f.jsx)(`div`,{style:{flexShrink:0,width:`36px`,height:`36px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,f.jsx)(cO,{size:36,orbColors:e})})}var pO=()=>(0,f.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,f.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})});function mO({copy:e,orbColors:t,primaryColor:n,chatBgGradient:r,logo:i,quickChatOptions:a,onQuickChatSelect:o,isMobile:s,chatHistory:c,isAiTyping:l,isAgentTyping:u,activeScreen:p,agentName:m,agentHeadshot:h,fallbackAgentName:g,input:_,setInput:v,onSubmit:y,isConversationEnded:b,isLoading:x,isRateLimited:S,rateLimitMessage:ee,selectedFile:te,onFileSelect:C,onRemoveSelectedFile:ne,attachmentError:re,isUploadingAttachment:ie,requiresEmail:ae,emailInput:oe,setEmailInput:se,emailError:ce,replyContext:le,setReplyContext:ue,webRTCError:de,micError:fe,setMicError:pe,dismissCallError:me,incomingCall:he,rejectCall:ge,acceptCall:_e,activeCallId:ve,callConnectionState:w,isCallMuted:ye,toggleCallMute:be,endWebRTCCall:xe,formatCallDuration:Se,callDurationSeconds:Ce,onCollapse:we,onStartVoice:Te,showPoweredBy:Ee}){let De=c.length>0,Oe=x||S||b,ke=!!(he||ve),[Ae,je]=(0,d.useState)(!1),Me=(0,d.useRef)(null);return(0,d.useEffect)(()=>{if(!Ae)return;let e=e=>{Me.current&&!Me.current.contains(e.target)&&je(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[Ae]),(0,f.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,inset:0,width:`100%`,height:`100dvh`,background:r,borderRadius:0,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:`fe-orb-slide-up 0.28s cubic-bezier(0.16,1,0.3,1)`}:{"--flowengage-primary":n,"--flowengage-accent":n,width:`min(390px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,background:r,borderRadius:`22px`,boxShadow:`0 24px 64px rgba(0,0,0,0.18), 0 4px 16px rgba(0,0,0,0.08)`,display:`flex`,flexDirection:`column`,overflow:`hidden`,position:`relative`,animation:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,f.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`40px minmax(0, 1fr) 40px`,alignItems:`center`,columnGap:`14px`,padding:`16px 18px 14px`,background:`transparent`,flexShrink:0},children:[(0,f.jsx)(`button`,{onClick:we,style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,f.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:`minmax(72px, 40%) minmax(0, 60%)`,alignItems:`center`},children:[(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,f.jsx)(aO,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,f.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,f.jsx)(oO,{title:e.chatTitle})})}),(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`},children:(0,f.jsx)(`span`,{style:{fontSize:`15px`,fontWeight:600,color:`#111827`,letterSpacing:`-0.01em`,lineHeight:1.2,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},title:e.chatTitle,children:e.chatTitle})})]}),(0,f.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:Me,children:[(0,f.jsx)(`button`,{type:`button`,onClick:()=>je(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,f.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`})]})}),Ae&&(0,f.jsxs)(`div`,{style:{position:`absolute`,top:`34px`,right:0,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{je(!1),Te?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]}),`Enter Voice Mode`]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{je(!1),we?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,f.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),`Close Conversation`]})]})]})]}),(0,f.jsx)(DE,{webRTCError:de,micError:fe,setMicError:pe,dismissCallError:me,incomingCall:he,rejectCall:ge,acceptCall:_e,activeCallId:ve,callConnectionState:w,formatCallDuration:Se,callDurationSeconds:Ce,endWebRTCCall:xe,isCallMuted:ye,toggleCallMute:be,isAIVoiceActive:!1,currentCallAgentName:m||g,isRateLimited:S,rateLimitMessage:ee}),(0,f.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`},children:De?(0,f.jsx)(CE,{chatHistory:c,isAiTyping:l,isAgentTyping:u,setReplyContext:ue,TypingDots:pO,primaryColor:n,agentHeadshot:h,agentDisplayName:m||g,botAvatarNode:(0,f.jsx)(fO,{orbColors:t})}):(0,f.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`22px`,padding:`28px 24px`},children:[(0,f.jsx)(cO,{size:94,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,textAlign:`center`,fontSize:`16px`,color:`#374151`,lineHeight:1.55,maxWidth:`270px`},children:e.introGreeting}),a.length>0&&(0,f.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`8px`,justifyContent:`center`,width:`100%`,padding:`0 8px`},children:a.map(e=>(0,f.jsx)(`button`,{onClick:()=>o?.(e),style:{padding:`8px 16px`,borderRadius:`999px`,background:`white`,border:`1.5px solid ${n}33`,color:n||`#374151`,fontSize:`13px`,fontWeight:500,cursor:`pointer`,transition:`all 0.15s ease`,boxShadow:`0 1px 4px rgba(0,0,0,0.06)`},onMouseEnter:e=>{e.currentTarget.style.background=`${n}12`,e.currentTarget.style.borderColor=n},onMouseLeave:e=>{e.currentTarget.style.background=`white`,e.currentTarget.style.borderColor=`${n}33`},children:e.label||e.text},e.id))})]})}),(0,f.jsx)(`div`,{style:{background:`transparent`,flexShrink:0,position:`relative`,zIndex:1,padding:ae?`6px 0 0`:`12px 0 0`},children:(0,f.jsx)(wE,{input:_,setInput:v,onSubmit:y,isConversationEnded:b,callUiActive:ke,handleToggleVoice:Te,showVoiceToggle:p===`agent`,activeScreen:p,inputDisabled:Oe,replyContext:le,clearReplyContext:()=>ue(null),onFileSelect:C,selectedFile:te,onRemoveSelectedFile:ne,attachmentError:re,isUploadingAttachment:ie,requiresEmail:ae,emailInput:oe,setEmailInput:se,emailError:ce,inputPlaceholder:e.inputPlaceholder})}),(0,f.jsx)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`12px 20px 18px`,pointerEvents:`none`},children:Ee&&(0,f.jsxs)(`span`,{style:{fontSize:`11px`,color:`#9ca3af`,letterSpacing:`0.01em`,userSelect:`none`},children:[`Powered by `,(0,f.jsx)(`strong`,{style:{fontWeight:600,color:`#6b7280`},children:`FlowEngage`})]})})]})}function hO(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatHistory:r,isOpen:i,activeScreen:a,isHumanHandled:o,agentName:s,agentHeadshot:c,visitorEmail:l,isAgentTyping:u,isAiTyping:p,isLoading:m,isRateLimited:h,rateLimitMessage:g,isConversationEnded:_,incomingCall:v,activeCallId:y,callConnectionState:b,callConnectedAt:x,isCallMuted:S,webRTCError:ee,language:te,historyRef:C,onMessageSync:ne,sendMessage:re,uploadChatFile:ie,openWidget:ae,captureVisitorEmail:oe,setVoiceMode:se,endConversation:ce,acceptCall:le,rejectCall:ue,endWebRTCCall:de,toggleCallMute:fe,dismissCallError:pe,startTyping:me,stopTyping:he,updateTypingDraft:ge}=en();(0,d.useEffect)(()=>{try{sn()}catch{}},[]);let _e=t?.widgetSettings||{},ve=n?.widgetSettings||{},w={..._e.branding||{},...ve.branding||{}},ye={..._e.theme||{},...ve.theme||{}},be=Array.isArray(ye.orbColors)&&ye.orbColors.length>0?ye.orbColors:null,xe=be?.[0]||ye.primaryColor||`#3B82F6`,Se=ye.position||`bottom-right`,Ce=w.fallbackAgentName||`Agent`,we=rO(be??ye.chatBgColors),Te=w.logo||w.logoUrl||null,Ee=te||`en`,De=_e.recommendations?.[Ee]||[],Oe=(ve.recommendations?.[Ee]??De).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),ke=Array.isArray(w.quickChatOptions)&&w.quickChatOptions.length>0?w.quickChatOptions:Oe,Ae=w.hideWatermark===!0?!1:w.showPoweredBy!==!1,je=w.chatbotEnabled!==!1&&ye.chatbotEnabled!==!1,Me=_e.greetings?.[te]||ve.greetings?.[te]||w.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,Ne={entryPrompt:w.entryPrompt||`Do you want to explore in a new way?`,yesLabel:w.yesLabel||`Yes`,laterLabel:w.laterLabel||`Later`,connectionTitle:w.connectionTitle||`How would you like to connect?`,voiceLabel:w.voiceLabel||`Voice`,textLabel:w.textLabel||`Text`,chatTitle:w.headerName||`Chat with FlowEngage`,introGreeting:Me,inputPlaceholder:w.inputPlaceholder||`Type your message`,analysingLabel:w.analysingLabel||`analysing...`},Pe=ve.elevenLabsAgentId||t?.elevenLabsAgentId||null,Fe=t?.siteId||n?.siteId||null,T=t?.apiBaseUrl||``,Ie=(0,d.useMemo)(()=>s&&String(s).trim()||t?.ownerName&&String(t.ownerName).trim()||t?.websiteName&&String(t.websiteName).trim()||`Agent`,[s,t?.ownerName,t?.websiteName]),Le=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,E=r.some(e=>e.sender===`user`),Re=(0,d.useMemo)(()=>{let e=r.findIndex(e=>e.sender===`user`);return e===-1?!1:r.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[r]),ze=!l&&E&&Re,Be=!!(ve._dashboardLivePreview||_e._dashboardLivePreview),[Ve,He]=(0,d.useState)(()=>Be?`text_chat`:`entry_prompt`),[Ue,We]=(0,d.useState)(``),[Ge,Ke]=(0,d.useState)(null),[D,O]=(0,d.useState)(l||``),[qe,Je]=(0,d.useState)(``),[Ye,Xe]=(0,d.useState)(0),[Ze,Qe]=(0,d.useState)(null),[k,$e]=(0,d.useState)(null),[et,tt]=(0,d.useState)(``),[nt,rt]=(0,d.useState)(!1),it=(0,d.useRef)(null),at=(0,d.useRef)(!1);(0,d.useLayoutEffect)(()=>{e!==`ready`||at.current||(at.current=!0,r.length>0&&He(`minimized_orb`))},[e,r]);let[ot,st]=(0,d.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,d.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>st(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,d.useEffect)(()=>{O(l||``),l&&Je(``)},[l]);let ct=(0,d.useCallback)(()=>{$e(null),tt(``)},[]),lt=(0,d.useCallback)(e=>{let t=vE(e);if(t){$e(null),tt(t);return}$e(e),tt(``)},[]);(0,d.useEffect)(()=>{if(!x||b!==`connected`){Xe(0);return}let e=()=>{let e=new Date(x).getTime();isNaN(e)||Xe(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[x,b]),(0,d.useEffect)(()=>{let e=v?.callId||y||null;if(!e){it.current=null;return}(v?.callId||b===`connecting`||b===`connected`)&&(!(!i||Ve===`minimized_orb`||Ve===`voice_mode`)&&it.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:Ve,hasIncomingCall:!!v?.callId,activeCallId:y,callConnectionState:b}),it.current=e,Ve===`voice_mode`&&se?.(!1),ae?.(),He(`text_chat`)))},[y,b,v?.callId,i,ae,se,Ve]),(0,d.useEffect)(()=>{if(!o||_){ge?.(``),he?.();return}if(!Ue.trim()||k){ge?.(``),he?.();return}me?.();let e=window.setTimeout(()=>ge?.(Ue),120),t=window.setTimeout(()=>he?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[Ue,k,o,_,me,he,ge]);let ut=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,dt=async e=>{if(e.preventDefault(),_)return;if(ze){let e=D.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){Je(`Please enter a valid email so we can continue helping you.`);return}await oe(e),Je(``);return}let t=ut(Ge);if(!Ue.trim()&&!k)return;if(k){try{rt(!0),tt(``);let e=await ie(k),n=e?.data||e,r=Ue.trim()||`Shared file: ${bE(k)}`;We(``),Ke(null),ct(),await re(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||k.name,fileType:n?.fileType||k.type,fileSize:n?.fileSize||k.size}})}catch(e){tt(e?.message||`Failed to upload the selected file.`)}finally{rt(!1)}return}let n=Ue.trim();We(``),Ke(null),await re(n,``,t)},ft=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},pt=(0,d.useCallback)(async e=>{if(_||m)return;let t=e.message||e.label||e.text||``;t.trim()&&await re(t.trim(),``)},[_,m,re]),mt=ot&&(Ve===`text_chat`||Ve===`entry_prompt`)?{inset:0}:Se===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},ht=()=>He(`minimized_orb`),gt=()=>He(`connection_modal`),_t=()=>{ae({notifyChatInitiated:!0}),se?.(!0),He(`voice_mode`)},vt=()=>{ae({notifyChatInitiated:!0}),se?.(!1),He(`text_chat`)},yt=()=>{se?.(!1),ht()};return e!==`ready`||!je?null:(0,f.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...mt},children:[Ve===`entry_prompt`&&(0,f.jsx)(lO,{copy:Ne,orbColors:be,primaryColor:xe,onYes:_t,onLater:ht,isMobile:ot}),Ve===`minimized_orb`&&(0,f.jsx)(pp.div,{layoutId:`fe-main-orb`,initial:{scale:94/50},animate:{scale:1},transition:{type:`spring`,stiffness:220,damping:26},style:{transformOrigin:`bottom right`,display:`inline-block`},children:(0,f.jsx)(cO,{size:50,orbColors:be,onClick:gt})}),Ve===`connection_modal`&&(0,f.jsx)(uO,{copy:Ne,orbColors:be,primaryColor:xe,onVoice:_t,onText:vt,onClose:ht}),Ve===`voice_mode`&&(0,f.jsx)(dO,{orbColors:be,onEnterChat:vt,onEndChat:yt,agentId:Pe,siteId:Fe,apiBaseUrl:T,historyRef:C,onMessageSync:ne},`voice`),Ve===`text_chat`&&(0,f.jsx)(mO,{copy:Ne,orbColors:be,primaryColor:xe,chatBgGradient:we,logo:Te,quickChatOptions:ke,onQuickChatSelect:pt,isMobile:ot,chatHistory:r,isAiTyping:p,isAgentTyping:u,activeScreen:a,agentName:Ie,agentHeadshot:Le,fallbackAgentName:Ce,input:Ue,setInput:We,onSubmit:dt,isConversationEnded:_,isLoading:m,isRateLimited:h,rateLimitMessage:g,selectedFile:k,onFileSelect:lt,onRemoveSelectedFile:ct,attachmentError:et,isUploadingAttachment:nt,requiresEmail:ze,emailInput:D,setEmailInput:O,emailError:qe,replyContext:Ge,setReplyContext:Ke,webRTCError:ee,micError:Ze,setMicError:Qe,dismissCallError:pe,incomingCall:v,rejectCall:ue,acceptCall:le,activeCallId:y,callConnectionState:b,isCallMuted:S,toggleCallMute:fe,endWebRTCCall:de,formatCallDuration:ft,callDurationSeconds:Ye,onCollapse:ht,onStartVoice:_t,onEndConversation:ce,showPoweredBy:Ae}),(0,f.jsx)(`style`,{children:`
|
|
605
|
+
`)}else{let t=(document.querySelector(`main`)||document.querySelector(`article`)||document.querySelector(`[role="main"]`)||document.querySelector(`#content`)||document.querySelector(`.content`)||document.body).cloneNode(!0);t.querySelectorAll(`nav, footer, header, aside, script, style, noscript, .nav, .footer, .header, .sidebar`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),$(`flowengage_read_content ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return $(`flowengage_read_content ✖`,e.message),`Could not read page content: ${e.message}`}},flowengage_search:async e=>{$(`flowengage_search ▶`,e);let r=ZD(KD(e));if($(`flowengage_search · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`flowengage_search ✖ missing query`),`Missing query parameter.`;if(!t)return $(`flowengage_search ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`flowengage_search ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`flowengage_search → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`flowengage_search · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`flowengage_search ✖`,e),e}let o=a.results||[];return $(`flowengage_search ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`flowengage_search ✖`,t),t}},flowengage_page_content:async e=>{$(`flowengage_page_content ▶`,e);let r=KD(e),i=r?.url||r?.page_url||``;if($(`flowengage_page_content · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return $(`flowengage_page_content ✖ missing url`),`Missing url parameter.`;if(!t)return $(`flowengage_page_content ✖ no siteId`),`Site is not configured.`;if(!n)return $(`flowengage_page_content ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;$(`flowengage_page_content → POST`,e);let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,url:i})}),a=await r.json();if($(`flowengage_page_content · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return $(`flowengage_page_content ✖`,e),e}return $(`flowengage_page_content ✓`,`title: ${a.title}`,`sections: ${(a.sections||[]).length}`,`content: ${(a.content||``).length} chars`),JSON.stringify({title:a.title,url:a.url,sections:a.sections,content:a.content})}catch(e){let t=`Page content error: ${e.message||`network`}`;return $(`flowengage_page_content ✖`,t),t}},flowengage_end_session:async()=>($(`flowengage_end_session ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),flowengage_list_forms:async()=>{let e=OD(),t=kD();return $(`flowengage_list_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, flowengage_fill_form sets all matching URL inputs. flowengage_click_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},flowengage_fill_form:async e=>{try{$(`flowengage_fill_form ▶ raw:`,e),cD();let t=qD(e);if(!t.length&&r){let e=r(),n=JD(e);n.length?$(`flowengage_fill_form · inferred URL from last user utterance (model omitted usable fields):`,n):(n=YD(e),n.length&&$(`flowengage_fill_form · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`flowengage_fill_form · normalized fields:`,t),!t.length)return`No fields provided. Call flowengage_list_forms for field_key strings, then flowengage_fill_form with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;tD(`Filling ${String(t)}...`,{spinner:!0});let a=DD(),o=BD(a,String(t),r);if(o.length){for(let[e,t]of o.entries())lD(t),await hD(t),QD(t,r,{skipScroll:e>0}),uD(t),await bD(120);i=o,n.push(String(t));continue}let s=UD(a,String(t));s||=PD(a,String(t)),s||=FD(a,String(t),r),s&&(lD(s),await hD(s),QD(s,r),uD(s),await bD(120),i=[s],n.push(String(t)))}if(!n.length)return $(`flowengage_fill_form ✖ no matches`),`Could not match any fields. Call flowengage_list_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let a=`OK_FILLED: ${n.join(`, `)}`;return $(`flowengage_fill_form ✓`,a),tD(`Form filled`,{spinner:!1,icon:`✅`,duration:1100}),a}catch(e){let t=`flowengage_fill_form error: ${e?.message||String(e)}`;return $(`flowengage_fill_form ✖`,t),tD(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{gD(),cD(),nD(700)}},flowengage_click_button:async e=>{let t=KD(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`flowengage_click_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=GD(n,i);if(!r)return $(`flowengage_click_button ✖ no match`),`Could not find a button matching "${n}". Call flowengage_list_forms to see button texts.`;try{tD(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await hD(r),r.focus?.(),await _D(r),vD(r),r.click();let e=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`flowengage_click_button ✓`,t),tD(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`flowengage_click_button ✖`,t),tD(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{gD(),nD(700)}}};return{...a,navigateToPage:a.flowengage_navigate,highlightOnPage:a.flowengage_highlight,searchSiteContent:a.flowengage_search,getPageContent:a.flowengage_page_content,endVoiceSession:a.flowengage_end_session,listPageForms:a.flowengage_list_forms,fillFormFields:a.flowengage_fill_form,clickPageButton:a.flowengage_click_button}}function tO(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=tn();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i;try{i=await t(n)}catch(t){let n=`Tool error: ${t?.message||String(t)}`;return console.error(`[FlowEngage] voice tool ${e} threw:`,t),n}let a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var nO={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function rO(e){if(!Array.isArray(e)||e.length<2)return`linear-gradient(145deg, #dce8f022 0%, #e8dff522 45%, #f5e0e022 100%), #f7f8fa`;let[t,n,r]=e;return e.length>=3&&r?[`radial-gradient(ellipse 80% 70% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 70% 80% at 110% 30%, ${n}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 60% at 50% 110%, ${r}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `):[`radial-gradient(ellipse 80% 100% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 100% at 110% 50%, ${n}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `)}function iO(e){if(!e||typeof e!=`string`)return`#1a1a1a`;let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t,r=parseInt(n.slice(0,2),16)/255,i=parseInt(n.slice(2,4),16)/255,a=parseInt(n.slice(4,6),16)/255,o=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4;return .2126*o(r)+.7152*o(i)+.0722*o(a)>.179?`#1a1a1a`:`#ffffff`}function aO({logo:e,style:t}){if(!e)return null;if(typeof e==`string`)return(0,f.jsx)(`img`,{src:e,alt:``,style:{objectFit:`contain`,flexShrink:0,display:`block`,...t}});let n=typeof e==`function`?d.default.createElement(e):d.default.isValidElement(e)?e:null;return n?(0,f.jsx)(`span`,{className:`fe-logo-slot`,style:{display:`inline-flex`,alignItems:`center`,flexShrink:0,overflow:`hidden`,...t},children:n}):null}function oO({title:e}){return(0,f.jsx)(`div`,{style:{width:`100%`,height:`100%`,borderRadius:`16px`,background:`linear-gradient(135deg, rgba(59,130,246,0.16) 0%, rgba(59,130,246,0.08) 100%)`,color:`#2563eb`,display:`flex`,alignItems:`center`,justifyContent:`center`,fontSize:`18px`,fontWeight:700,letterSpacing:`-0.03em`},children:String(e||`FE`).split(/\s+/).filter(Boolean).slice(0,2).map(e=>e[0]?.toUpperCase()||``).join(``)||`FE`})}function sO(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(that'?s all|we'?re done)\b/i.test(n)||e===`bot`&&(/\b(I'?ll|I will|Let me|I can|I'?m going to)\s+(end|close)\s+(the\s+)?(voice\s+)?(session|call)\b/i.test(n)||/\b(ending|closing)\s+(the\s+)?(voice\s+)?session\b|\bvoice\s+session\s+(is\s+)?(now\s+)?(ended|over|closing)\b/i.test(n)||/\b(session|call)\s+(is\s+)?(now\s+)?(ended|over)\b/i.test(n)||/\bwe\s+can\s+end\s+(the\s+)?(session|call)?\s*(here|now)\b/i.test(n)||/\b(wrapping\s+up|signing\s+off)\b/i.test(n))||/^(goodbye|bye|that'?s all|we'?re done|hang up|disconnect)\b/i.test(n)):!1}function cO({orbColors:e,...t}){return(0,f.jsx)(IE,{colors:e,...t})}function lO({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a}){let o=n||nO.green,s=iO(o),c=a?72:94,l=(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:a?`14px`:`18px`},children:[(0,f.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(pp.p,{initial:{x:-16,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.36},style:{margin:`0 0 14px`,fontSize:a?`16px`:`18px`,fontWeight:700,color:`white`,lineHeight:1.4,textShadow:`0 1px 4px rgba(0,0,0,0.35)`,maxWidth:a?void 0:`210px`},children:e.entryPrompt}),(0,f.jsxs)(pp.div,{initial:{y:10,opacity:0},animate:{y:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.54},style:{display:`flex`,gap:`8px`,flexWrap:`nowrap`},children:[(0,f.jsx)(`button`,{onClick:r,style:{padding:a?`9px 20px`:`10px 28px`,borderRadius:`999px`,background:o,color:s,fontWeight:700,fontSize:a?`14px`:`15px`,border:`none`,cursor:`pointer`,whiteSpace:`nowrap`,boxShadow:`0 4px 16px ${o}66`,transition:`transform 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.04)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.yesLabel}),(0,f.jsx)(`button`,{onClick:i,style:{padding:a?`9px 16px`:`10px 22px`,borderRadius:`999px`,background:`transparent`,color:`white`,fontWeight:600,fontSize:a?`14px`:`15px`,border:`2px solid rgba(255,255,255,0.55)`,cursor:`pointer`,whiteSpace:`nowrap`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.9)`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.55)`},children:e.laterLabel})]})]}),(0,f.jsx)(pp.div,{initial:{x:120,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:220,damping:22,delay:0},style:{flexShrink:0},children:(0,f.jsx)(cO,{size:c,orbColors:t})})]});return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(pp.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.4},style:{position:`fixed`,inset:0,background:`rgba(0,0,0,0.72)`,zIndex:-1}}),a?(0,f.jsx)(`div`,{style:{position:`absolute`,bottom:0,left:0,right:0,padding:`24px 20px 40px`,overflow:`hidden`},children:l}):l]})}function uO({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a}){let o=n||nO.green,s=iO(o);return(0,f.jsxs)(pp.div,{initial:{scale:50/300,borderRadius:`50%`},animate:{scale:1,borderRadius:`24px`},transition:{type:`spring`,stiffness:260,damping:26},style:{transformOrigin:`bottom right`,background:`white`,padding:`28px 28px 24px`,width:`300px`,display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`20px`,boxShadow:`0 20px 60px rgba(0,0,0,0.2)`,position:`relative`,overflow:`hidden`},children:[(0,f.jsx)(`button`,{onClick:a,style:{position:`absolute`,top:`14px`,right:`14px`,background:`none`,border:`none`,cursor:`pointer`,color:`#9ca3af`,padding:`4px`,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,f.jsx)(cO,{size:82,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,fontSize:`17px`,fontWeight:600,color:`#111827`,textAlign:`center`,lineHeight:1.4},children:e.connectionTitle}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,width:`100%`},children:[(0,f.jsx)(`button`,{onClick:r,style:{flex:1,padding:`12px`,borderRadius:`999px`,background:o,color:s,fontWeight:700,fontSize:`15px`,border:`none`,cursor:`pointer`,transition:`transform 0.15s ease`,boxShadow:`0 4px 12px ${o}55`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.03)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.voiceLabel}),(0,f.jsx)(`button`,{onClick:i,style:{flex:1,padding:`12px`,borderRadius:`999px`,background:`transparent`,color:`#111827`,fontWeight:600,fontSize:`15px`,border:`2px solid #d1d5db`,cursor:`pointer`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`#6b7280`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`#d1d5db`},children:e.textLabel})]})]})}function dO({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,historyRef:o,onMessageSync:s}){let[c,l]=(0,d.useState)(`idle`),[u,p]=(0,d.useState)(!1),[m,h]=(0,d.useState)(!1),g=(0,d.useRef)(null),_=(0,d.useRef)(``),v=(0,d.useRef)(async()=>{}),y=(0,d.useRef)(!1),b=(0,d.useRef)(!1),x=(0,d.useRef)(!1),S=(0,d.useRef)(!1),ee=(0,d.useRef)(`minimized`),te=(0,d.useRef)(null),C=(0,d.useCallback)((e=`minimized`)=>{ee.current=e,S.current=!0,queueMicrotask(()=>{y.current||(y.current=!0,v.current?.())})},[o]),ne=(0,d.useCallback)(async e=>{S.current=!0;try{await g.current?.endSession?.()}catch{}g.current=null,l(`idle`),p(!1),y.current=!1,typeof s==`function`&&await s(o.current),e?.()},[o,s]);return v.current=()=>ne(ee.current===`chat`?t:n),(0,d.useEffect)(()=>{b.current=u},[u]),(0,d.useEffect)(()=>{let e=!1,n=null;return(async()=>{if(!r){l(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;o.current=[],_.current=``,y.current=!1,x.current=!1,S.current=!1,ee.current=`minimized`;let t=tO(eO({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>_.current,requestEndSession:()=>{C()}})),s=await nE.startSession({agentId:r,clientTools:t,onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onModeChange:({mode:t})=>{e||l(t===`speaking`?`speaking`:`listening`)},onMessage:t=>{if(e)return;let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;r&&(n===`user`&&(_.current=r),o.current=[...o.current,{sender:n,message:r,timestamp:new Date().toISOString()}],sO(n,r)&&C(`minimized`))},onError:t=>{if(!e&&!S.current&&!x.current){x.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{g.current?.setMicMuted?.(!0)}catch{}p(!0),l(`error`),C(`chat`)}},onDisconnect:()=>{if(!e&&!S.current&&!x.current){x.current=!0,console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:o.current?.length||0,lastUserText:_.current||``,wasMuted:b.current});try{g.current?.setMicMuted?.(!0)}catch{}p(!0),C(`chat`)}}});if(e){s.endSession().catch(()=>{});return}n=s,g.current=s,l(`listening`);try{let e=typeof window<`u`?window.location.href:``,n=`[]`;try{n=await t.list_page_forms()}catch{}s.sendContextualUpdate(`Page: ${e}. SiteId: ${i||`unknown`}. Forms: ${n}. Voice: call end_voice_session or say you are ending the session to stop.`)}catch{}}catch(n){e||(console.error(`[FlowEngage] startSession failed`,n),l(`error`),ee.current=`chat`,window.setTimeout(()=>{e||t?.()},0))}})(),()=>{e=!0,S.current=!0,(n||g.current)?.endSession?.().catch(()=>{})}},[r,i,a,C]),(0,d.useEffect)(()=>{if(!m)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;te.current&&!te.current.contains(t)&&h(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[m]),(0,f.jsx)(f.Fragment,{children:(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`14px`,animation:`fe-orb-slide-up 0.42s cubic-bezier(0.16,1,0.3,1)`},children:[(0,f.jsxs)(`div`,{style:{position:`relative`},children:[c===`listening`&&(0,f.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`white`,fontSize:`18px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Listening...`}),(0,f.jsx)(cO,{size:94,voiceState:c,isMuted:u,orbColors:e})]}),c===`error`&&(0,f.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,f.jsx)(`button`,{onClick:async()=>{if(g.current)try{u?(await g.current.setMicMuted?.(!1),p(!1)):(await g.current.setMicMuted?.(!0),p(!0))}catch{}},title:u?`Unmute`:`Mute`,style:{width:`44px`,height:`44px`,borderRadius:`50%`,background:u?`#7f1d1d`:`#1f2937`,border:u?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:u?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`},children:u?(0,f.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,f.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,f.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,f.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,f.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,f.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:`currentColor`,stroke:`none`}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]})}),(0,f.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:te,children:[(0,f.jsx)(`button`,{onClick:()=>h(e=>!e),style:{width:`44px`,height:`44px`,borderRadius:`50%`,background:`#1f2937`,border:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`,transition:`background 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`},children:(0,f.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`currentColor`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.8`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.8`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.8`})]})}),m&&(0,f.jsxs)(`div`,{style:{position:`absolute`,bottom:`54px`,right:0,zIndex:9999,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,f.jsxs)(`button`,{onClick:()=>{h(!1),ee.current=`chat`,ne(t)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`path`,{d:`M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z`})}),`Enter Chat Mode`]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{onClick:()=>{h(!1),ee.current=`minimized`,ne(n)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,f.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),`End Conversation`]})]})]})]})]})})}function fO({orbColors:e}){return(0,f.jsx)(`div`,{style:{flexShrink:0,width:`36px`,height:`36px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,f.jsx)(cO,{size:36,orbColors:e})})}var pO=()=>(0,f.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,f.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})});function mO({copy:e,orbColors:t,primaryColor:n,chatBgGradient:r,logo:i,quickChatOptions:a,onQuickChatSelect:o,isMobile:s,chatHistory:c,isAiTyping:l,isAgentTyping:u,activeScreen:p,agentName:m,agentHeadshot:h,fallbackAgentName:g,input:_,setInput:v,onSubmit:y,isConversationEnded:b,isLoading:x,isRateLimited:S,rateLimitMessage:ee,selectedFile:te,onFileSelect:C,onRemoveSelectedFile:ne,attachmentError:re,isUploadingAttachment:ie,requiresEmail:ae,emailInput:oe,setEmailInput:se,emailError:ce,replyContext:le,setReplyContext:ue,webRTCError:de,micError:fe,setMicError:pe,dismissCallError:me,incomingCall:he,rejectCall:ge,acceptCall:_e,activeCallId:ve,callConnectionState:w,isCallMuted:ye,toggleCallMute:be,endWebRTCCall:xe,formatCallDuration:Se,callDurationSeconds:Ce,onCollapse:we,onStartVoice:Te,showPoweredBy:Ee}){let De=c.length>0,Oe=x||S||b,ke=!!(he||ve),[Ae,je]=(0,d.useState)(!1),Me=(0,d.useRef)(null);return(0,d.useEffect)(()=>{if(!Ae)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;Me.current&&!Me.current.contains(t)&&je(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[Ae]),(0,f.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,inset:0,width:`100%`,height:`100dvh`,background:r,borderRadius:0,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:`fe-orb-slide-up 0.28s cubic-bezier(0.16,1,0.3,1)`}:{"--flowengage-primary":n,"--flowengage-accent":n,width:`min(390px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,background:r,borderRadius:`22px`,boxShadow:`0 24px 64px rgba(0,0,0,0.18), 0 4px 16px rgba(0,0,0,0.08)`,display:`flex`,flexDirection:`column`,overflow:`hidden`,position:`relative`,animation:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,f.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`40px minmax(0, 1fr) 40px`,alignItems:`center`,columnGap:`14px`,padding:`16px 18px 14px`,background:`transparent`,flexShrink:0},children:[(0,f.jsx)(`button`,{onClick:we,style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,f.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:`minmax(72px, 40%) minmax(0, 60%)`,alignItems:`center`},children:[(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,f.jsx)(aO,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,f.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,f.jsx)(oO,{title:e.chatTitle})})}),(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`},children:(0,f.jsx)(`span`,{style:{fontSize:`15px`,fontWeight:600,color:`#111827`,letterSpacing:`-0.01em`,lineHeight:1.2,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},title:e.chatTitle,children:e.chatTitle})})]}),(0,f.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:Me,children:[(0,f.jsx)(`button`,{type:`button`,onClick:()=>je(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,f.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`})]})}),Ae&&(0,f.jsxs)(`div`,{style:{position:`absolute`,top:`34px`,right:0,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{je(!1),Te?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]}),`Enter Voice Mode`]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{je(!1),we?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,f.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),`Close Conversation`]})]})]})]}),(0,f.jsx)(DE,{webRTCError:de,micError:fe,setMicError:pe,dismissCallError:me,incomingCall:he,rejectCall:ge,acceptCall:_e,activeCallId:ve,callConnectionState:w,formatCallDuration:Se,callDurationSeconds:Ce,endWebRTCCall:xe,isCallMuted:ye,toggleCallMute:be,isAIVoiceActive:!1,currentCallAgentName:m||g,isRateLimited:S,rateLimitMessage:ee}),(0,f.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`},children:De?(0,f.jsx)(CE,{chatHistory:c,isAiTyping:l,isAgentTyping:u,setReplyContext:ue,TypingDots:pO,primaryColor:n,agentHeadshot:h,agentDisplayName:m||g,botAvatarNode:(0,f.jsx)(fO,{orbColors:t})}):(0,f.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`22px`,padding:`28px 24px`},children:[(0,f.jsx)(cO,{size:94,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,textAlign:`center`,fontSize:`16px`,color:`#374151`,lineHeight:1.55,maxWidth:`270px`},children:e.introGreeting}),a.length>0&&(0,f.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`8px`,justifyContent:`center`,width:`100%`,padding:`0 8px`},children:a.map(e=>(0,f.jsx)(`button`,{onClick:()=>o?.(e),style:{padding:`8px 16px`,borderRadius:`999px`,background:`white`,border:`1.5px solid ${n}33`,color:n||`#374151`,fontSize:`13px`,fontWeight:500,cursor:`pointer`,transition:`all 0.15s ease`,boxShadow:`0 1px 4px rgba(0,0,0,0.06)`},onMouseEnter:e=>{e.currentTarget.style.background=`${n}12`,e.currentTarget.style.borderColor=n},onMouseLeave:e=>{e.currentTarget.style.background=`white`,e.currentTarget.style.borderColor=`${n}33`},children:e.label||e.text},e.id))})]})}),(0,f.jsx)(`div`,{style:{background:`transparent`,flexShrink:0,position:`relative`,zIndex:1,padding:ae?`6px 0 0`:`12px 0 0`},children:(0,f.jsx)(wE,{input:_,setInput:v,onSubmit:y,isConversationEnded:b,callUiActive:ke,handleToggleVoice:Te,showVoiceToggle:p===`agent`,activeScreen:p,inputDisabled:Oe,replyContext:le,clearReplyContext:()=>ue(null),onFileSelect:C,selectedFile:te,onRemoveSelectedFile:ne,attachmentError:re,isUploadingAttachment:ie,requiresEmail:ae,emailInput:oe,setEmailInput:se,emailError:ce,inputPlaceholder:e.inputPlaceholder})}),(0,f.jsx)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`12px 20px 18px`,pointerEvents:`none`},children:Ee&&(0,f.jsxs)(`span`,{style:{fontSize:`11px`,color:`#9ca3af`,letterSpacing:`0.01em`,userSelect:`none`},children:[`Powered by `,(0,f.jsx)(`strong`,{style:{fontWeight:600,color:`#6b7280`},children:`FlowEngage`})]})})]})}function hO(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatHistory:r,isOpen:i,activeScreen:a,isHumanHandled:o,agentName:s,agentHeadshot:c,visitorEmail:l,isAgentTyping:u,isAiTyping:p,isLoading:m,isRateLimited:h,rateLimitMessage:g,isConversationEnded:_,incomingCall:v,activeCallId:y,callConnectionState:b,callConnectedAt:x,isCallMuted:S,webRTCError:ee,language:te,historyRef:C,onMessageSync:ne,sendMessage:re,uploadChatFile:ie,openWidget:ae,captureVisitorEmail:oe,setVoiceMode:se,endConversation:ce,acceptCall:le,rejectCall:ue,endWebRTCCall:de,toggleCallMute:fe,dismissCallError:pe,startTyping:me,stopTyping:he,updateTypingDraft:ge}=en();(0,d.useEffect)(()=>{try{sn()}catch{}},[]);let _e=t?.widgetSettings||{},ve=n?.widgetSettings||{},w={..._e.branding||{},...ve.branding||{}},ye={..._e.theme||{},...ve.theme||{}},be=Array.isArray(ye.orbColors)&&ye.orbColors.length>0?ye.orbColors:null,xe=be?.[0]||ye.primaryColor||`#3B82F6`,Se=ye.position||`bottom-right`,Ce=w.fallbackAgentName||`Agent`,we=rO(be??ye.chatBgColors),Te=w.logo||w.logoUrl||null,Ee=te||`en`,De=_e.recommendations?.[Ee]||[],Oe=(ve.recommendations?.[Ee]??De).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),ke=Array.isArray(w.quickChatOptions)&&w.quickChatOptions.length>0?w.quickChatOptions:Oe,Ae=w.hideWatermark===!0?!1:w.showPoweredBy!==!1,je=w.chatbotEnabled!==!1&&ye.chatbotEnabled!==!1,Me=_e.greetings?.[te]||ve.greetings?.[te]||w.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,Ne={entryPrompt:w.entryPrompt||`Do you want to explore in a new way?`,yesLabel:w.yesLabel||`Yes`,laterLabel:w.laterLabel||`Later`,connectionTitle:w.connectionTitle||`How would you like to connect?`,voiceLabel:w.voiceLabel||`Voice`,textLabel:w.textLabel||`Text`,chatTitle:w.headerName||`Chat with FlowEngage`,introGreeting:Me,inputPlaceholder:w.inputPlaceholder||`Type your message`,analysingLabel:w.analysingLabel||`analysing...`},Pe=ve.elevenLabsAgentId||t?.elevenLabsAgentId||null,Fe=t?.siteId||n?.siteId||null,T=t?.apiBaseUrl||``,Ie=(0,d.useMemo)(()=>s&&String(s).trim()||t?.ownerName&&String(t.ownerName).trim()||t?.websiteName&&String(t.websiteName).trim()||`Agent`,[s,t?.ownerName,t?.websiteName]),Le=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,E=r.some(e=>e.sender===`user`),Re=(0,d.useMemo)(()=>{let e=r.findIndex(e=>e.sender===`user`);return e===-1?!1:r.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[r]),ze=!l&&E&&Re,Be=!!(ve._dashboardLivePreview||_e._dashboardLivePreview),[Ve,He]=(0,d.useState)(()=>Be?`text_chat`:`entry_prompt`),[Ue,We]=(0,d.useState)(``),[Ge,Ke]=(0,d.useState)(null),[D,O]=(0,d.useState)(l||``),[qe,Je]=(0,d.useState)(``),[Ye,Xe]=(0,d.useState)(0),[Ze,Qe]=(0,d.useState)(null),[k,$e]=(0,d.useState)(null),[et,tt]=(0,d.useState)(``),[nt,rt]=(0,d.useState)(!1),it=(0,d.useRef)(null),at=(0,d.useRef)(!1);(0,d.useLayoutEffect)(()=>{e!==`ready`||at.current||(at.current=!0,r.length>0&&He(`minimized_orb`))},[e,r]);let[ot,st]=(0,d.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,d.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>st(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,d.useEffect)(()=>{O(l||``),l&&Je(``)},[l]);let ct=(0,d.useCallback)(()=>{$e(null),tt(``)},[]),lt=(0,d.useCallback)(e=>{let t=vE(e);if(t){$e(null),tt(t);return}$e(e),tt(``)},[]);(0,d.useEffect)(()=>{if(!x||b!==`connected`){Xe(0);return}let e=()=>{let e=new Date(x).getTime();isNaN(e)||Xe(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[x,b]),(0,d.useEffect)(()=>{let e=v?.callId||y||null;if(!e){it.current=null;return}(v?.callId||b===`connecting`||b===`connected`)&&(!(!i||Ve===`minimized_orb`||Ve===`voice_mode`)&&it.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:Ve,hasIncomingCall:!!v?.callId,activeCallId:y,callConnectionState:b}),it.current=e,Ve===`voice_mode`&&se?.(!1),ae?.(),He(`text_chat`)))},[y,b,v?.callId,i,ae,se,Ve]),(0,d.useEffect)(()=>{if(!o||_){ge?.(``),he?.();return}if(!Ue.trim()||k){ge?.(``),he?.();return}me?.();let e=window.setTimeout(()=>ge?.(Ue),120),t=window.setTimeout(()=>he?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[Ue,k,o,_,me,he,ge]);let ut=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,dt=async e=>{if(e.preventDefault(),_)return;if(ze){let e=D.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){Je(`Please enter a valid email so we can continue helping you.`);return}await oe(e),Je(``);return}let t=ut(Ge);if(!Ue.trim()&&!k)return;if(k){try{rt(!0),tt(``);let e=await ie(k),n=e?.data||e,r=Ue.trim()||`Shared file: ${bE(k)}`;We(``),Ke(null),ct(),await re(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||k.name,fileType:n?.fileType||k.type,fileSize:n?.fileSize||k.size}})}catch(e){tt(e?.message||`Failed to upload the selected file.`)}finally{rt(!1)}return}let n=Ue.trim();We(``),Ke(null),await re(n,``,t)},ft=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},pt=(0,d.useCallback)(async e=>{if(_||m)return;let t=e.message||e.label||e.text||``;t.trim()&&await re(t.trim(),``)},[_,m,re]),mt=ot&&(Ve===`text_chat`||Ve===`entry_prompt`)?{inset:0}:Se===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},ht=()=>He(`minimized_orb`),gt=()=>He(`connection_modal`),_t=()=>{ae({notifyChatInitiated:!0}),se?.(!0),He(`voice_mode`)},vt=()=>{ae({notifyChatInitiated:!0}),se?.(!1),He(`text_chat`)},yt=()=>{se?.(!1),ht()};return e!==`ready`||!je?null:(0,f.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...mt},children:[Ve===`entry_prompt`&&(0,f.jsx)(lO,{copy:Ne,orbColors:be,primaryColor:xe,onYes:_t,onLater:ht,isMobile:ot}),Ve===`minimized_orb`&&(0,f.jsx)(pp.div,{layoutId:`fe-main-orb`,initial:{scale:94/50},animate:{scale:1},transition:{type:`spring`,stiffness:220,damping:26},style:{transformOrigin:`bottom right`,display:`inline-block`},children:(0,f.jsx)(cO,{size:50,orbColors:be,onClick:gt})}),Ve===`connection_modal`&&(0,f.jsx)(uO,{copy:Ne,orbColors:be,primaryColor:xe,onVoice:_t,onText:vt,onClose:ht}),Ve===`voice_mode`&&(0,f.jsx)(dO,{orbColors:be,onEnterChat:vt,onEndChat:yt,agentId:Pe,siteId:Fe,apiBaseUrl:T,historyRef:C,onMessageSync:ne},`voice`),Ve===`text_chat`&&(0,f.jsx)(mO,{copy:Ne,orbColors:be,primaryColor:xe,chatBgGradient:we,logo:Te,quickChatOptions:ke,onQuickChatSelect:pt,isMobile:ot,chatHistory:r,isAiTyping:p,isAgentTyping:u,activeScreen:a,agentName:Ie,agentHeadshot:Le,fallbackAgentName:Ce,input:Ue,setInput:We,onSubmit:dt,isConversationEnded:_,isLoading:m,isRateLimited:h,rateLimitMessage:g,selectedFile:k,onFileSelect:lt,onRemoveSelectedFile:ct,attachmentError:et,isUploadingAttachment:nt,requiresEmail:ze,emailInput:D,setEmailInput:O,emailError:qe,replyContext:Ge,setReplyContext:Ke,webRTCError:ee,micError:Ze,setMicError:Qe,dismissCallError:pe,incomingCall:v,rejectCall:ue,acceptCall:le,activeCallId:y,callConnectionState:b,isCallMuted:S,toggleCallMute:fe,endWebRTCCall:de,formatCallDuration:ft,callDurationSeconds:Ye,onCollapse:ht,onStartVoice:_t,onEndConversation:ce,showPoweredBy:Ae}),(0,f.jsx)(`style`,{children:`
|
|
606
606
|
/* Force any SVG (or img) inside LogoSlot to fill the container height
|
|
607
607
|
regardless of whether the component forwards its style prop. */
|
|
608
608
|
.fe-logo-slot svg,
|
|
@@ -1862,13 +1862,17 @@ var un = ({ apiBaseUrl: e, userId: t, chatId: n, siteId: r }) => ln(e, {
|
|
|
1862
1862
|
chatId: t,
|
|
1863
1863
|
timestamp: Date.now()
|
|
1864
1864
|
});
|
|
1865
|
+
}, v = () => {
|
|
1866
|
+
_();
|
|
1867
|
+
}, y = (e) => {
|
|
1868
|
+
e.persisted || _();
|
|
1865
1869
|
};
|
|
1866
|
-
return window.addEventListener("popstate", m), window.addEventListener("hashchange", m), window.addEventListener("beforeunload",
|
|
1870
|
+
return window.addEventListener("popstate", m), window.addEventListener("hashchange", m), window.addEventListener("beforeunload", v), window.addEventListener("pagehide", y), window.addEventListener("visibilitychange", p), o(), document.hidden ? a = window.setTimeout(() => {
|
|
1867
1871
|
a = null, d(), f("hidden");
|
|
1868
1872
|
}, re) : (l(), u()), {
|
|
1869
1873
|
notifyRouteChange: m,
|
|
1870
1874
|
cleanup: () => {
|
|
1871
|
-
a &&= (window.clearTimeout(a), null), d(), window.history.pushState = h, window.history.replaceState = g, window.removeEventListener("popstate", m), window.removeEventListener("hashchange", m), window.removeEventListener("beforeunload",
|
|
1875
|
+
a &&= (window.clearTimeout(a), null), d(), window.history.pushState = h, window.history.replaceState = g, window.removeEventListener("popstate", m), window.removeEventListener("hashchange", m), window.removeEventListener("beforeunload", v), window.removeEventListener("pagehide", y), window.removeEventListener("visibilitychange", p);
|
|
1872
1876
|
}
|
|
1873
1877
|
};
|
|
1874
1878
|
}, fn = r(null), pn = () => {
|
|
@@ -28814,7 +28818,8 @@ function wO({ orbColors: e, onEnterChat: t, onEndChat: n, agentId: r, siteId: i,
|
|
|
28814
28818
|
]), c(() => {
|
|
28815
28819
|
if (!y) return;
|
|
28816
28820
|
let e = (e) => {
|
|
28817
|
-
|
|
28821
|
+
let t = e.composedPath?.()?.[0] || e.target;
|
|
28822
|
+
re.current && !re.current.contains(t) && b(!1);
|
|
28818
28823
|
};
|
|
28819
28824
|
return document.addEventListener("mousedown", e), () => document.removeEventListener("mousedown", e);
|
|
28820
28825
|
}, [y]), /* @__PURE__ */ g(h, { children: /* @__PURE__ */ _("div", {
|
|
@@ -29136,7 +29141,8 @@ function DO({ copy: e, orbColors: t, primaryColor: n, chatBgGradient: r, logo: i
|
|
|
29136
29141
|
return c(() => {
|
|
29137
29142
|
if (!je) return;
|
|
29138
29143
|
let e = (e) => {
|
|
29139
|
-
|
|
29144
|
+
let t = e.composedPath?.()?.[0] || e.target;
|
|
29145
|
+
Ne.current && !Ne.current.contains(t) && Me(!1);
|
|
29140
29146
|
};
|
|
29141
29147
|
return document.addEventListener("mousedown", e), () => document.removeEventListener("mousedown", e);
|
|
29142
29148
|
}, [je]), /* @__PURE__ */ _("div", {
|