@flowengage/react-chatbot 6.0.16 → 6.0.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use client";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(e&&(t=e(e=0)),t),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,a)=>(a=n==null?{}:e(i(n)),c(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n)),u=e=>a.call(e,`module.exports`)?e[`module.exports`]:c(t({},`__esModule`,{value:!0}),e);let d=require(`react`);d=l(d);let f=require(`react/jsx-runtime`);var p=e=>{if(!e||typeof e!=`object`)throw Error(`FlowEngage config is required`);if(!e.siteId||typeof e.siteId!=`string`)throw Error(`[FlowEngage] config.siteId is required. Pass it as <FlowEngageProvider siteId="your-site-id" /> or config={{ siteId: 'your-site-id' }}.`);let t=(e.apiBaseUrl||`https://be-flowengage-stage.oslabs.app`).replace(/\/+$/,``);return{siteId:e.siteId.trim(),apiBaseUrl:t}},m=(e,t)=>{let n=Number.parseInt(String(e??``),10);return Number.isFinite(n)&&n>0?n:t},h=m(void 0,1e4),g=m(void 0,15e3),_={chatId:`flowengage.chatId`,isOpen:`flowengage.isOpen`,activeScreen:`flowengage.activeScreen`,isHumanHandled:`flowengage.isHumanHandled`,agentName:`flowengage.agentName`,agentHeadshot:`flowengage.agentHeadshot`,visitorEmail:`flowengage.visitorEmail`},v=6e4,y=480*60,b=3e4,x=typeof window<`u`,S=e=>e?`flowengage.visitorEmail.${e}`:null,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{}},ne=()=>x?typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`:`server-chat-id`,re=e=>e?`flowengage.entrySeen.${e}`:null,C=e=>{if(!x||!e)return!1;try{let t=re(e);return t?window.localStorage.getItem(t)===`1`:!1}catch{return!1}},ie=e=>{if(!(!x||!e))try{let t=re(e);t&&window.localStorage.setItem(t,`1`)}catch{}},ae=e=>e?`flowengage.persistedChatId.${e}`:null,oe=e=>{if(!x||!e)return null;try{let t=ae(e),n=t?window.localStorage.getItem(t):null;return n&&String(n).trim()?String(n).trim():null}catch{return null}},se=e=>{if(!(!x||!e))try{let t=ae(e);t&&window.localStorage.removeItem(t)}catch{}},ce=(e,t)=>{if(!(!x||!e||!t))try{let n=ae(e);n&&window.localStorage.setItem(n,String(t).trim())}catch{}},le=()=>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:``},ue=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))}})},de=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||``},fe=(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)},pe=e=>e?`flowengage.visitorId.${e}`:null,me=()=>`v_${Date.now().toString(36)}_${typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID().replace(/-/g,``).slice(0,16):Math.random().toString(36).slice(2,18)}`,he=e=>{if(!x||!e)return null;try{let t=pe(e),n=t?window.localStorage.getItem(t):null;return n&&String(n).trim()?String(n).trim():null}catch{return null}},ge=e=>{if(!x||!e)return null;try{let t=he(e);if(t)return t;let n=me(),r=pe(e);return r&&window.localStorage.setItem(r,n),n}catch{return me()}},_e=`flowengage.tabId`,ve=()=>{if(!x)return`default`;try{let e=window.sessionStorage.getItem(_e);return e||(e=typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID().replace(/-/g,``).slice(0,12):Math.random().toString(36).slice(2,14),window.sessionStorage.setItem(_e,e)),e}catch{return`default`}},ye=e=>e?`flowengage.voice.transcript.${e}.${ve()}`:null,be=600*1e3,xe=(e,t,n={})=>{if(!x||!e)return;let r=typeof t==`string`?t.trim():``;if(!r)return;let i=Number.isFinite(n.ttlMs)?n.ttlMs:be,a={transcript:r,expiresAt:Date.now()+i};try{let t=ye(e);t&&window.localStorage.setItem(t,JSON.stringify(a))}catch{}},Se=e=>{if(!x||!e)return null;try{let t=ye(e),n=t?window.localStorage.getItem(t):null;if(!n)return null;let r=JSON.parse(n);return!r||typeof r.transcript!=`string`?null:Number.isFinite(r.expiresAt)&&Date.now()>r.expiresAt?(window.localStorage.removeItem(t),null):r}catch{return null}},Ce=e=>{if(!(!x||!e))try{let t=ye(e);t&&window.localStorage.removeItem(t)}catch{}},we=`flowengage.voice.pendingResume`,Te=()=>{if(x)try{window.sessionStorage.setItem(we,`1`)}catch{}},Ee=()=>{if(!x)return!1;try{return window.sessionStorage.getItem(we)===`1`?(window.sessionStorage.removeItem(we),!0):!1}catch{return!1}},De=`flowengage.chat.pendingReopen`,Oe=()=>{if(x)try{window.sessionStorage.setItem(De,`1`)}catch{}},ke=()=>{if(!x)return!1;try{return window.sessionStorage.getItem(De)===`1`?(window.sessionStorage.removeItem(De),!0):!1}catch{return!1}},Ae=()=>{if(!x)return!1;try{return window.sessionStorage.getItem(we)===`1`}catch{return!1}},je=e=>e?`flowengage.voice.navState.${e}.${ve()}`:null,Me=(e,t,n)=>{if(!(!x||!e||!t))try{let r=je(e);r&&window.sessionStorage.setItem(r,JSON.stringify({previousPage:String(t),targetPath:n?new URL(String(n),window.location.href).pathname:null,ts:Date.now()}))}catch{}},Ne=e=>{if(!x||!e)return null;try{let t=je(e);if(!t)return null;let n=window.sessionStorage.getItem(t);if(!n)return null;window.sessionStorage.removeItem(t);let r=JSON.parse(n);return!r||typeof r.previousPage!=`string`||Number.isFinite(r.ts)&&Date.now()-r.ts>6e4||r.targetPath&&(window.location.pathname.replace(/\/$/,``)||`/`)!==(r.targetPath.replace(/\/$/,``)||`/`)?null:{previousPage:r.previousPage}}catch{return null}},Pe=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},Fe=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}},Ie=async({apiBaseUrl:e,userId:t,siteId:n,priorChatId:r=null,forceNew:i=!1,resumeChatId:a=null,visitorId:o=null})=>{let s=`${e}/api/visitors/resolve-session`,c={siteId:n};return r&&String(r).trim()&&(c.priorChatId=String(r).trim()),i&&(c.forceNew=!0),a&&(c.resumeChatId=a),o&&(c.visitorId=o),Pe(await Fe(s,{method:`POST`,mode:`cors`,headers:{"Content-Type":`application/json`,"x-user-id":t==null?``:String(t),...n?{"x-site-id":n}:{},...o?{"x-visitor-id":o}:{}},body:JSON.stringify(c)}))},Le=async({apiBaseUrl:e,siteId:t})=>{let n=typeof window<`u`?window.location.origin:`http://localhost`;return(await Pe(await Fe(`${e}/api/widget/chatbot-loader?${new URLSearchParams({siteId:t,origin:n}).toString()}`,{method:`GET`}))).data},Re=({apiBaseUrl:e,userId:t,siteId:n,visitorId:r=null})=>{let i=(t,n)=>{let r=`${e}${t}`,i=JSON.stringify(n);if(typeof navigator<`u`&&navigator.sendBeacon)try{let e=new Blob([i],{type:`application/json`});return navigator.sendBeacon(r,e)}catch{}return typeof fetch<`u`?(fetch(r,{method:`POST`,mode:`cors`,keepalive:!0,headers:{"Content-Type":`application/json`},body:i}).catch(()=>{}),!0):!1},a=async(i,a={})=>Pe(await Fe(`${e}${i}`,{...a,headers:{"Content-Type":`application/json`,"x-user-id":t,...n?{"x-site-id":n}:{},...r?{"x-visitor-id":r}:{},...a.headers||{}}})),o=async(r,i,a={})=>{let o={"x-user-id":t,...n?{"x-site-id":n}:{},...a.headers||{}};return Pe(await Fe(`${e}${r}`,{...a,body:i,headers:o}))};return{async loadHistory(e,t=`en`,n=``){return a(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:``,lang:t,category:n})})},async sendAiMessage(e,t,n=`en`,r=``,i=null,o={}){return a(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:t,lang:n,category:r,...o||{},...i||{}})})},async uploadChatFile(e){let t=new FormData;return t.append(`file`,e),o(`/api/upload`,t,{method:`POST`})},async checkHumanHandled(e){return a(`/api/ai/check_human_handled`,{method:`POST`,body:JSON.stringify({session_id:e})})},async setChatMode(e,t){return a(`/api/ai/set_chat_mode`,{method:`POST`,body:JSON.stringify({session_id:e,mode:t})})},async toggleVoice(e){return a(`/api/ai/voice/toggle`,{method:`POST`,body:JSON.stringify({session_id:e})})},async syncVoice(e,r){return a(`/api/ai/voice/sync`,{method:`POST`,body:JSON.stringify({session_id:e,messages:r,...t?{userId:String(t)}:{},...n?{siteId:String(n)}:{}})})},async trackVisitor(e){return a(`/api/visitors/track`,{method:`POST`,body:JSON.stringify(e)})},async updateChatStatus(e,t){return a(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:t})})},async startConversation(e,t=`en`){return a(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`open`,lang:t})})},async endConversation(e){return a(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`closed`})})},async getVisitorChatHistory(){return a(`/api/visitors/my-chats`,{method:`GET`})},async getVisitorChatThread(e){return a(`/api/visitors/my-chats/${e}`,{method:`GET`})},async getSignedVoiceUrl(e){return a(`/api/voice/signed-url?chatId=${encodeURIComponent(e)}`,{method:`GET`})},async acceptCall(e,t){return a(`/api/calls/${e}/accept`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async rejectCall(e,t){return a(`/api/calls/${e}/reject`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async getIceServersConfig(){return Pe(await Fe(`${e}/api/calls/ice-config`,{method:`GET`,headers:{"x-user-id":t,...n?{"x-site-id":n}:{}}}))},async endWebRTCCall(e,t){return a(`/api/calls/${e}/end`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n,endedBy:`customer`})})},async markCustomerUnavailable(e,t){return a(`/api/calls/${e}/customer-unavailable`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async uploadRecording(e,t,n){let r=new FormData,i=`call-rec-${Date.now()}.webm`;return r.append(`audio`,t,i),r.append(`duration`,String(n)),o(`/api/calls/${e}/recording`,r,{method:`POST`})},beaconEndWebRTCCall(e,t){return i(`/api/calls/${e}/end`,{session_id:t,site_id:n,endedBy:`customer`})},beaconCustomerUnavailable(e,t){return i(`/api/calls/${e}/customer-unavailable`,{session_id:t,site_id:n})},beaconSyncVoice(r,i){if(typeof navigator>`u`||!navigator.sendBeacon)return!1;let a=new URLSearchParams;return a.append(`session_id`,r),a.append(`messages`,JSON.stringify(i)),t&&a.append(`userId`,String(t)),n&&a.append(`siteId`,String(n)),navigator.sendBeacon(`${e}/api/ai/voice/sync`,a)},beaconWidgetClosed(r){if(typeof navigator>`u`||!navigator.sendBeacon)return!1;let i=new URLSearchParams;return i.append(`chatId`,r),i.append(`type`,`widget_closed`),t&&i.append(`userId`,String(t)),n&&i.append(`siteId`,String(n)),navigator.sendBeacon(`${e}/api/chat/status`,i)}}},ze=Object.create(null);ze.open=`0`,ze.close=`1`,ze.ping=`2`,ze.pong=`3`,ze.message=`4`,ze.upgrade=`5`,ze.noop=`6`;var Be=Object.create(null);Object.keys(ze).forEach(e=>{Be[ze[e]]=e});var Ve={type:`error`,data:`parser error`},He=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,Ue=typeof ArrayBuffer==`function`,We=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Ge=({type:e,data:t},n,r)=>He&&t instanceof Blob?n?r(t):Ke(t,r):Ue&&(t instanceof ArrayBuffer||We(t))?n?r(t):Ke(new Blob([t]),r):r(ze[e]+(t||``)),Ke=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function qe(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var Je;function Ye(e,t){if(He&&e.data instanceof Blob)return e.data.arrayBuffer().then(qe).then(t);if(Ue&&(e.data instanceof ArrayBuffer||We(e.data)))return t(qe(e.data));Ge(e,!1,e=>{Je||=new TextEncoder,t(Je.encode(e))})}var Xe=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Ze=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)Ze[Xe.charCodeAt(e)]=e;var Qe=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=Ze[e.charCodeAt(r)],o=Ze[e.charCodeAt(r+1)],s=Ze[e.charCodeAt(r+2)],c=Ze[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},$e=typeof ArrayBuffer==`function`,et=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:nt(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:tt(e.substring(1),t)}:Be[n]?e.length>1?{type:Be[n],data:e.substring(1)}:{type:Be[n]}:Ve},tt=(e,t)=>$e?nt(Qe(e),t):{base64:!0,data:e},nt=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},rt=``,it=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{Ge(e,!1,e=>{r[a]=e,++i===n&&t(r.join(rt))})})},at=(e,t)=>{let n=e.split(rt),r=[];for(let e=0;e<n.length;e++){let i=et(n[e],t);if(r.push(i),i.type===`error`)break}return r};function ot(){return new TransformStream({transform(e,t){Ye(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 w;function T(e){return e.reduce((e,t)=>e+t.length,0)}function st(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 ct(e,t){w||=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=st(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=st(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=st(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(Ve);break}i=a*2**32+t.getUint32(4),r=3}else{if(T(n)<i)break;let e=st(n,i);s.enqueue(et(a?e:w.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(Ve);break}}}})}function E(e){if(e)return lt(e)}function lt(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 ut=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),dt=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),ft=`arraybuffer`;function pt(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var mt=dt.setTimeout,ht=dt.clearTimeout;function gt(e,t){t.useNativeTimers?(e.setTimeoutFn=mt.bind(dt),e.clearTimeoutFn=ht.bind(dt)):(e.setTimeoutFn=dt.setTimeout.bind(dt),e.clearTimeoutFn=dt.clearTimeout.bind(dt))}var _t=1.33;function vt(e){return typeof e==`string`?yt(e):Math.ceil((e.byteLength||e.size)*_t)}function yt(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 bt(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function xt(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function St(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 Ct=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},wt=class extends E{constructor(e){super(),this.writable=!1,gt(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 Ct(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=et(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=xt(e);return t.length?`?`+t:``}},Tt=class extends wt{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){at(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,it(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]=bt()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},Et=!1;try{Et=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var Dt=Et;function Ot(){}var kt=class extends Tt{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}},At=class e extends E{constructor(e,t,n){super(),this.createRequest=e,gt(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=pt(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=Ot,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(At.requestsCount=0,At.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,jt);else if(typeof addEventListener==`function`){let e=`onpagehide`in dt?`pagehide`:`unload`;addEventListener(e,jt,!1)}}function jt(){for(let e in At.requests)At.requests.hasOwnProperty(e)&&At.requests[e].abort()}var Mt=(function(){let e=Pt({xdomain:!1});return e&&e.responseType!==null})(),Nt=class extends kt{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=Mt&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new At(Pt,this.uri(),e)}};function Pt(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||Dt))return new XMLHttpRequest}catch{}if(!t)try{return new dt[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var Ft=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,It=class extends wt{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=Ft?{}:pt(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;Ge(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&ut(()=>{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]=bt()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},Lt=dt.WebSocket||dt.MozWebSocket,Rt={websocket:class extends It{createSocket(e,t,n){return Ft?new Lt(e,t,n):t?new Lt(e,t):new Lt(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends wt{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=ct(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=ot();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&&ut(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:Nt},zt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Bt=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function Vt(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=zt.exec(e||``),a={},o=14;for(;o--;)a[Bt[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=Ht(a,a.path),a.queryKey=Ut(a,a.query),a}function Ht(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 Ut(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var Wt=typeof addEventListener==`function`&&typeof removeEventListener==`function`,Gt=[];Wt&&addEventListener(`offline`,()=>{Gt.forEach(e=>e())},!1);var Kt=class e extends E{constructor(e,t){if(super(),this.binaryType=ft,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=Vt(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=Vt(t.host).host);gt(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=St(this.opts.query)),Wt&&(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`})},Gt.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+=vt(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,ut(()=>{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(),Wt&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=Gt.indexOf(this._offlineEventListener);e!==-1&&Gt.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};Kt.protocol=4;var qt=class extends Kt{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;Kt.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;Kt.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}},Jt=class extends qt{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=>Rt[e]).filter(e=>!!e)),super(e,n)}};Jt.protocol;function Yt(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=Vt(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 Xt=typeof ArrayBuffer==`function`,Zt=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,Qt=Object.prototype.toString,$t=typeof Blob==`function`||typeof Blob<`u`&&Qt.call(Blob)===`[object BlobConstructor]`,en=typeof File==`function`||typeof File<`u`&&Qt.call(File)===`[object FileConstructor]`;function tn(e){return Xt&&(e instanceof ArrayBuffer||Zt(e))||$t&&e instanceof Blob||en&&e instanceof File}function nn(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(nn(e[t]))return!0;return!1}if(tn(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return nn(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&nn(e[t]))return!0;return!1}function rn(e){let t=[],n=e.data,r=e;return r.data=an(n,t),r.attachments=t.length,{packet:r,buffers:t}}function an(e,t){if(!e)return e;if(tn(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]=an(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]=an(e[r],t));return n}return e}function on(e,t){return e.data=sn(e.data,t),delete e.attachments,e}function sn(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]=sn(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=sn(e[n],t));return e}var cn=s({Decoder:()=>dn,Encoder:()=>un,PacketType:()=>D,isPacketValid:()=>vn,protocol:()=>5}),ln=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],D;(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`})(D||={});var un=class{constructor(e){this.replacer=e}encode(e){return(e.type===D.EVENT||e.type===D.ACK)&&nn(e)?this.encodeAsBinary({type:e.type===D.EVENT?D.BINARY_EVENT:D.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===D.BINARY_EVENT||e.type===D.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=rn(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},dn=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===D.BINARY_EVENT;n||t.type===D.BINARY_ACK?(t.type=n?D.EVENT:D.ACK,this.reconstructor=new fn(t),t.attachments===0&&super.emitReserved(`decoded`,t)):super.emitReserved(`decoded`,t)}else if(tn(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(D[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===D.BINARY_EVENT||r.type===D.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(!mn(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 D.CONNECT:return gn(t);case D.DISCONNECT:return t===void 0;case D.CONNECT_ERROR:return typeof t==`string`||gn(t);case D.EVENT:case D.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&ln.indexOf(t[0])===-1);case D.ACK:case D.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},fn=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=on(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function pn(e){return typeof e==`string`}var mn=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function hn(e){return e===void 0||mn(e)}function gn(e){return Object.prototype.toString.call(e)===`[object Object]`}function _n(e,t){switch(e){case D.CONNECT:return t===void 0||gn(t);case D.DISCONNECT:return t===void 0;case D.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&ln.indexOf(t[0])===-1);case D.ACK:return Array.isArray(t);case D.CONNECT_ERROR:return typeof t==`string`||gn(t);default:return!1}}function vn(e){return pn(e.nsp)&&hn(e.id)&&_n(e.type,e.data)}function yn(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var bn=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),xn=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=[yn(e,`open`,this.onopen.bind(this)),yn(e,`packet`,this.onpacket.bind(this)),yn(e,`error`,this.onerror.bind(this)),yn(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(bn.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:D.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:D.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 D.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 D.EVENT:case D.BINARY_EVENT:this.onevent(e);break;case D.ACK:case D.BINARY_ACK:this.onack(e);break;case D.DISCONNECT:this.ondisconnect();break;case D.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:D.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:D.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 Sn(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}Sn.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},Sn.prototype.reset=function(){this.attempts=0},Sn.prototype.setMin=function(e){this.ms=e},Sn.prototype.setMax=function(e){this.max=e},Sn.prototype.setJitter=function(e){this.jitter=e};var Cn=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,gt(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 Sn({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||cn;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 Jt(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=yn(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=yn(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(yn(e,`ping`,this.onping.bind(this)),yn(e,`data`,this.ondata.bind(this)),yn(e,`error`,this.onerror.bind(this)),yn(e,`close`,this.onclose.bind(this)),yn(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){ut(()=>{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 xn(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)}},wn={};function Tn(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=Yt(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=wn[i]&&a in wn[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new Cn(r,t):(wn[i]||(wn[i]=new Cn(r,t)),c=wn[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(Tn,{Manager:Cn,Socket:xn,io:Tn,connect:Tn});var En=({apiBaseUrl:e,userId:t,chatId:n,siteId:r})=>Tn(e,{transports:[`polling`,`websocket`],upgrade:!0,rememberUpgrade:!1,auth:{userId:t,chatId:n,siteId:r},query:{chatId:n,siteId:r}}),Dn=({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)}}},On=(0,d.createContext)(null),kn=()=>{let e=(0,d.useContext)(On);if(!e)throw Error(`useFlowEngage must be used inside FlowEngageProvider`);return e};function An(){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 jn(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)}catch{return!1}}function O(...e){An()&&console.log(`[FlowEngage:shadowNavigate]`,...e)}var Mn=`fe_pending_nav_section`,Nn=15e3,Pn=`fe_voice_nav_state`,Fn=2e4,In=!1,Ln=null;function Rn(e=3e3){In=!0,Ln&&clearTimeout(Ln),Ln=setTimeout(()=>{In=!1,Ln=null},e)}function zn(){return In}var Bn=!1,Vn=null;function Hn(){Bn||typeof window>`u`||(Bn=!0,window.addEventListener(`popstate`,async()=>{let e=window.location.href;if(O(`popstate: body-swap to`,e),Vn){try{Yn(Vn)}catch{}try{Qn(Vn)}catch{}}try{if(await pr(e,{skipPushState:!0,isBack:!0})){O(`popstate: body-swap succeeded`);return}}catch(e){console.warn(`[FlowEngage] popstate body-swap error:`,e)}O(`popstate: body-swap failed, falling back to reload`),window.location.reload()}))}var Un=!1;function Wn(){Un||typeof window>`u`||typeof document>`u`||(Un=!0,document.addEventListener(`click`,async e=>{try{if(!window.history.state?.flowengageSpa)return}catch{return}let t=e.target.closest?.(`a[href]`);if(!t||t.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`))return;let n=t.getAttribute(`href`)||``;if(!n||n===`#`||n.startsWith(`javascript:`)||n.startsWith(`mailto:`)||n.startsWith(`tel:`)||t.hasAttribute(`download`)||t.target===`_blank`||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey)return;let r;try{if(r=new URL(n,window.location.href),r.origin!==window.location.origin)return}catch{return}if(!(r.pathname===window.location.pathname&&r.hash)&&!(r.pathname===window.location.pathname&&r.search===window.location.search)){e.preventDefault(),e.stopPropagation(),O(`link-intercept: body-swap to`,r.href),nr();try{try{Yn()}catch{}try{Qn()}catch{}if(await pr(r.href)){O(`link-intercept: body-swap succeeded`);return}}catch(e){console.warn(`[FlowEngage] link-intercept body-swap error:`,e)}O(`link-intercept: body-swap failed, falling back to normal navigation`),rr(),window.location.href=r.href}},!0))}function Gn(){if(typeof window>`u`)return null;if(window.next?.router||window.__NEXT_ROUTER__)return`nextjs`;if(window.__remixRouter||window.__staticRouterHydrationData)return`react-router`;if(window.___gatsby||window.___navigate)return`gatsby`;if(window.__VUE_ROUTER__)return`vue-router`;if(window.__NUXT__||window.$nuxt)return`nuxt`;if(window.ng?.getComponent||document.querySelector(`[ng-version]`))return`angular`;if(window.__sveltekit_data||document.querySelector(`[data-sveltekit-hydrate]`))return`sveltekit`;if(document.querySelector(`[data-astro-transition]`))return`astro`;let e=Array.from(document.body.children).filter(e=>{let t=e.tagName?.toUpperCase();return!(t===`SCRIPT`||t===`NOSCRIPT`||t===`LINK`||t===`STYLE`||e.id===`flowengage-root`)});return e.length===1&&e[0].id&&(e[0].querySelector(`[data-reactroot]`)||e[0]._reactRootContainer||e[0].__vue_app__)?`generic-spa`:null}var Kn=`data-fe-swap-css`;function qn(){typeof document>`u`||document.querySelectorAll(`[${Kn}]`).forEach(e=>e.remove())}var Jn=`fe_form_state:`;function Yn(e){if(typeof document>`u`||typeof sessionStorage>`u`)return;let t=document.querySelectorAll(`form`);if(!t.length)return;let n=[];if(t.forEach((e,t)=>{let r={};e.querySelectorAll(`input, textarea, select`).forEach(e=>{let t=e.name||e.id;t&&(e.type===`password`||e.type===`hidden`||(e.type===`checkbox`||e.type===`radio`?r[t+`::`+e.value]=e.checked:r[t]=e.value))}),Object.keys(r).length&&n.push({formIndex:t,fields:r})}),n.length)try{let t=Jn+(e||window.location.pathname);sessionStorage.setItem(t,JSON.stringify({state:n,ts:Date.now()}))}catch{}}function Xn(){if(typeof document>`u`||typeof sessionStorage>`u`)return;let e=Jn+window.location.pathname,t;try{t=JSON.parse(sessionStorage.getItem(e)||`null`)}catch{return}if(!t||!t.state)return;if(Date.now()-t.ts>1800*1e3){try{sessionStorage.removeItem(e)}catch{}return}let n=document.querySelectorAll(`form`);for(let{formIndex:e,fields:r}of t.state){let t=n[e];if(t)for(let[e,n]of Object.entries(r))if(e.includes(`::`)){let[r,i]=e.split(`::`),a=t.querySelector(`input[name="${r}"][value="${i}"], input[id="${r}"][value="${i}"]`);a&&(a.checked=!!n)}else{let r=t.querySelector(`[name="${e}"], [id="${e}"]`);if(r&&r.type!==`file`){r.value=n;try{r.dispatchEvent(new Event(`input`,{bubbles:!0}))}catch{}try{r.dispatchEvent(new Event(`change`,{bubbles:!0}))}catch{}}}}try{sessionStorage.removeItem(e)}catch{}}var Zn=`fe_scroll:`;function Qn(e){if(!(typeof window>`u`||typeof sessionStorage>`u`))try{let t=Zn+(e||window.location.pathname);sessionStorage.setItem(t,JSON.stringify({y:window.scrollY,ts:Date.now()}))}catch{}}function $n(){if(typeof window>`u`||typeof sessionStorage>`u`)return;let e=Zn+window.location.pathname,t;try{t=JSON.parse(sessionStorage.getItem(e)||`null`)}catch{return}if(t){try{sessionStorage.removeItem(e)}catch{}Date.now()-t.ts>1800*1e3||setTimeout(()=>{window.scrollTo({top:t.y,behavior:`instant`})},80)}}function er(e){if(!(typeof window>`u`))try{window.dispatchEvent(new CustomEvent(`flowengage:pageswap`,{detail:{url:e,timestamp:Date.now()}}))}catch{}}var tr=`fe-nav-loader`;function nr(){if(typeof document>`u`||document.getElementById(tr))return;let e=document.createElement(`div`);e.id=tr,e.style.cssText=[`position:fixed`,`top:0`,`left:0`,`width:0`,`height:3px`,`background:linear-gradient(90deg,#7c3aed,#6366f1)`,`z-index:2147483647`,`transition:width 0.4s ease`,`pointer-events:none`].join(`;`),document.body.appendChild(e),requestAnimationFrame(()=>{e.style.width=`70%`})}function rr(){if(typeof document>`u`)return;let e=document.getElementById(tr);e&&(e.style.width=`100%`,setTimeout(()=>{e.style.opacity=`0`,e.style.transition=`opacity 0.3s ease`,setTimeout(()=>e.remove(),350)},200))}function ir(){if(typeof window>`u`||typeof document>`u`)return;try{window.history.state?.flowengageSpa&&Hn()}catch{}let e;try{e=JSON.parse(sessionStorage.getItem(Mn)||`null`)}catch{return}if(!e)return;try{sessionStorage.removeItem(Mn)}catch{}let{sectionText:t,ts:n}=e;if(!t)return;if(Date.now()-n>Nn){O(`initNavigationHighlight: pending section expired, skipping:`,t);return}O(`initNavigationHighlight: replaying section highlight:`,t);let r=0,i=()=>{r+=1;let e=or(null,t);if(e){sr(e),O(`initNavigationHighlight: highlighted on attempt`,r);return}r<8?setTimeout(i,300):O(`initNavigationHighlight: could not find element after 8 attempts:`,t)};setTimeout(i,250)}var ar=()=>{if(typeof document>`u`||document.getElementById(`fe-highlight-styles`))return;let e=document.createElement(`style`);e.id=`fe-highlight-styles`,e.textContent=`
1
+ "use client";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(e&&(t=e(e=0)),t),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,a)=>(a=n==null?{}:e(i(n)),c(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n)),u=e=>a.call(e,`module.exports`)?e[`module.exports`]:c(t({},`__esModule`,{value:!0}),e);let d=require(`react`);d=l(d);let f=require(`react/jsx-runtime`);var p=e=>{if(!e||typeof e!=`object`)throw Error(`FlowEngage config is required`);if(!e.siteId||typeof e.siteId!=`string`)throw Error(`[FlowEngage] config.siteId is required. Pass it as <FlowEngageProvider siteId="your-site-id" /> or config={{ siteId: 'your-site-id' }}.`);let t=(e.apiBaseUrl||`https://be-flowengage-stage.oslabs.app`).replace(/\/+$/,``);return{siteId:e.siteId.trim(),apiBaseUrl:t}},m=(e,t)=>{let n=Number.parseInt(String(e??``),10);return Number.isFinite(n)&&n>0?n:t},h=m(void 0,1e4),g=m(void 0,15e3),_={chatId:`flowengage.chatId`,isOpen:`flowengage.isOpen`,activeScreen:`flowengage.activeScreen`,isHumanHandled:`flowengage.isHumanHandled`,agentName:`flowengage.agentName`,agentHeadshot:`flowengage.agentHeadshot`,visitorEmail:`flowengage.visitorEmail`},v=6e4,y=480*60,b=3e4,x=typeof window<`u`,S=e=>e?`flowengage.visitorEmail.${e}`:null,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{}},ne=()=>x?typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`:`server-chat-id`,re=e=>e?`flowengage.entrySeen.${e}`:null,C=e=>{if(!x||!e)return!1;try{let t=re(e);return t?window.localStorage.getItem(t)===`1`:!1}catch{return!1}},ie=e=>{if(!(!x||!e))try{let t=re(e);t&&window.localStorage.setItem(t,`1`)}catch{}},ae=e=>e?`flowengage.persistedChatId.${e}`:null,oe=e=>{if(!x||!e)return null;try{let t=ae(e),n=t?window.localStorage.getItem(t):null;return n&&String(n).trim()?String(n).trim():null}catch{return null}},se=e=>{if(!(!x||!e))try{let t=ae(e);t&&window.localStorage.removeItem(t)}catch{}},ce=(e,t)=>{if(!(!x||!e||!t))try{let n=ae(e);n&&window.localStorage.setItem(n,String(t).trim())}catch{}},le=()=>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:``},ue=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))}})},de=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||``},fe=(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)},pe=e=>e?`flowengage.visitorId.${e}`:null,me=()=>`v_${Date.now().toString(36)}_${typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID().replace(/-/g,``).slice(0,16):Math.random().toString(36).slice(2,18)}`,he=e=>{if(!x||!e)return null;try{let t=pe(e),n=t?window.localStorage.getItem(t):null;return n&&String(n).trim()?String(n).trim():null}catch{return null}},ge=e=>{if(!x||!e)return null;try{let t=he(e);if(t)return t;let n=me(),r=pe(e);return r&&window.localStorage.setItem(r,n),n}catch{return me()}},_e=`flowengage.tabId`,ve=()=>{if(!x)return`default`;try{let e=window.sessionStorage.getItem(_e);return e||(e=typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID().replace(/-/g,``).slice(0,12):Math.random().toString(36).slice(2,14),window.sessionStorage.setItem(_e,e)),e}catch{return`default`}},ye=e=>e?`flowengage.voice.transcript.${e}.${ve()}`:null,be=600*1e3,xe=(e,t,n={})=>{if(!x||!e)return;let r=typeof t==`string`?t.trim():``;if(!r)return;let i=Number.isFinite(n.ttlMs)?n.ttlMs:be,a={transcript:r,expiresAt:Date.now()+i};try{let t=ye(e);t&&window.localStorage.setItem(t,JSON.stringify(a))}catch{}},Se=e=>{if(!x||!e)return null;try{let t=ye(e),n=t?window.localStorage.getItem(t):null;if(!n)return null;let r=JSON.parse(n);return!r||typeof r.transcript!=`string`?null:Number.isFinite(r.expiresAt)&&Date.now()>r.expiresAt?(window.localStorage.removeItem(t),null):r}catch{return null}},Ce=e=>{if(!(!x||!e))try{let t=ye(e);t&&window.localStorage.removeItem(t)}catch{}},we=`flowengage.voice.pendingResume`,Te=()=>{if(x)try{window.sessionStorage.setItem(we,`1`)}catch{}},Ee=()=>{if(!x)return!1;try{return window.sessionStorage.getItem(we)===`1`?(window.sessionStorage.removeItem(we),!0):!1}catch{return!1}},De=`flowengage.chat.pendingReopen`,Oe=()=>{if(x)try{window.sessionStorage.setItem(De,`1`)}catch{}},ke=()=>{if(!x)return!1;try{return window.sessionStorage.getItem(De)===`1`?(window.sessionStorage.removeItem(De),!0):!1}catch{return!1}},Ae=()=>{if(!x)return!1;try{return window.sessionStorage.getItem(we)===`1`}catch{return!1}},je=e=>e?`flowengage.voice.navState.${e}.${ve()}`:null,Me=(e,t,n)=>{if(!(!x||!e||!t))try{let r=je(e);r&&window.sessionStorage.setItem(r,JSON.stringify({previousPage:String(t),targetPath:n?new URL(String(n),window.location.href).pathname:null,ts:Date.now()}))}catch{}},Ne=e=>{if(!x||!e)return null;try{let t=je(e);if(!t)return null;let n=window.sessionStorage.getItem(t);if(!n)return null;window.sessionStorage.removeItem(t);let r=JSON.parse(n);return!r||typeof r.previousPage!=`string`||Number.isFinite(r.ts)&&Date.now()-r.ts>6e4||r.targetPath&&(window.location.pathname.replace(/\/$/,``)||`/`)!==(r.targetPath.replace(/\/$/,``)||`/`)?null:{previousPage:r.previousPage}}catch{return null}},Pe=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},Fe=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}},Ie=async({apiBaseUrl:e,userId:t,siteId:n,priorChatId:r=null,forceNew:i=!1,resumeChatId:a=null,visitorId:o=null})=>{let s=`${e}/api/visitors/resolve-session`,c={siteId:n};return r&&String(r).trim()&&(c.priorChatId=String(r).trim()),i&&(c.forceNew=!0),a&&(c.resumeChatId=a),o&&(c.visitorId=o),Pe(await Fe(s,{method:`POST`,mode:`cors`,headers:{"Content-Type":`application/json`,"x-user-id":t==null?``:String(t),...n?{"x-site-id":n}:{},...o?{"x-visitor-id":o}:{}},body:JSON.stringify(c)}))},Le=async({apiBaseUrl:e,siteId:t})=>{let n=typeof window<`u`?window.location.origin:`http://localhost`;return(await Pe(await Fe(`${e}/api/widget/chatbot-loader?${new URLSearchParams({siteId:t,origin:n}).toString()}`,{method:`GET`}))).data},Re=({apiBaseUrl:e,userId:t,siteId:n,visitorId:r=null})=>{let i=(t,n)=>{let r=`${e}${t}`,i=JSON.stringify(n);if(typeof navigator<`u`&&navigator.sendBeacon)try{let e=new Blob([i],{type:`application/json`});return navigator.sendBeacon(r,e)}catch{}return typeof fetch<`u`?(fetch(r,{method:`POST`,mode:`cors`,keepalive:!0,headers:{"Content-Type":`application/json`},body:i}).catch(()=>{}),!0):!1},a=async(i,a={})=>Pe(await Fe(`${e}${i}`,{...a,headers:{"Content-Type":`application/json`,"x-user-id":t,...n?{"x-site-id":n}:{},...r?{"x-visitor-id":r}:{},...a.headers||{}}})),o=async(r,i,a={})=>{let o={"x-user-id":t,...n?{"x-site-id":n}:{},...a.headers||{}};return Pe(await Fe(`${e}${r}`,{...a,body:i,headers:o}))};return{async loadHistory(e,t=`en`,n=``){return a(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:``,lang:t,category:n})})},async sendAiMessage(e,t,n=`en`,r=``,i=null,o={}){return a(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:t,lang:n,category:r,...o||{},...i||{}})})},async uploadChatFile(e){let t=new FormData;return t.append(`file`,e),o(`/api/upload`,t,{method:`POST`})},async checkHumanHandled(e){return a(`/api/ai/check_human_handled`,{method:`POST`,body:JSON.stringify({session_id:e})})},async setChatMode(e,t){return a(`/api/ai/set_chat_mode`,{method:`POST`,body:JSON.stringify({session_id:e,mode:t})})},async toggleVoice(e){return a(`/api/ai/voice/toggle`,{method:`POST`,body:JSON.stringify({session_id:e})})},async syncVoice(e,r){return a(`/api/ai/voice/sync`,{method:`POST`,body:JSON.stringify({session_id:e,messages:r,...t?{userId:String(t)}:{},...n?{siteId:String(n)}:{}})})},async trackVisitor(e){return a(`/api/visitors/track`,{method:`POST`,body:JSON.stringify(e)})},async updateChatStatus(e,t){return a(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:t})})},async startConversation(e,t=`en`){return a(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`open`,lang:t})})},async endConversation(e){return a(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`closed`})})},async getVisitorChatHistory(){return a(`/api/visitors/my-chats`,{method:`GET`})},async getVisitorChatThread(e){return a(`/api/visitors/my-chats/${e}`,{method:`GET`})},async getSignedVoiceUrl(e){return a(`/api/voice/signed-url?chatId=${encodeURIComponent(e)}`,{method:`GET`})},async acceptCall(e,t){return a(`/api/calls/${e}/accept`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async rejectCall(e,t){return a(`/api/calls/${e}/reject`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async getIceServersConfig(){return Pe(await Fe(`${e}/api/calls/ice-config`,{method:`GET`,headers:{"x-user-id":t,...n?{"x-site-id":n}:{}}}))},async endWebRTCCall(e,t){return a(`/api/calls/${e}/end`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n,endedBy:`customer`})})},async markCustomerUnavailable(e,t){return a(`/api/calls/${e}/customer-unavailable`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async uploadRecording(e,t,n){let r=new FormData,i=`call-rec-${Date.now()}.webm`;return r.append(`audio`,t,i),r.append(`duration`,String(n)),o(`/api/calls/${e}/recording`,r,{method:`POST`})},beaconEndWebRTCCall(e,t){return i(`/api/calls/${e}/end`,{session_id:t,site_id:n,endedBy:`customer`})},beaconCustomerUnavailable(e,t){return i(`/api/calls/${e}/customer-unavailable`,{session_id:t,site_id:n})},beaconSyncVoice(r,i){if(typeof navigator>`u`||!navigator.sendBeacon)return!1;let a=new URLSearchParams;return a.append(`session_id`,r),a.append(`messages`,JSON.stringify(i)),t&&a.append(`userId`,String(t)),n&&a.append(`siteId`,String(n)),navigator.sendBeacon(`${e}/api/ai/voice/sync`,a)},beaconWidgetClosed(r){if(typeof navigator>`u`||!navigator.sendBeacon)return!1;let i=new URLSearchParams;return i.append(`chatId`,r),i.append(`type`,`widget_closed`),t&&i.append(`userId`,String(t)),n&&i.append(`siteId`,String(n)),navigator.sendBeacon(`${e}/api/chat/status`,i)}}},ze=Object.create(null);ze.open=`0`,ze.close=`1`,ze.ping=`2`,ze.pong=`3`,ze.message=`4`,ze.upgrade=`5`,ze.noop=`6`;var Be=Object.create(null);Object.keys(ze).forEach(e=>{Be[ze[e]]=e});var Ve={type:`error`,data:`parser error`},He=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,Ue=typeof ArrayBuffer==`function`,We=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Ge=({type:e,data:t},n,r)=>He&&t instanceof Blob?n?r(t):Ke(t,r):Ue&&(t instanceof ArrayBuffer||We(t))?n?r(t):Ke(new Blob([t]),r):r(ze[e]+(t||``)),Ke=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function qe(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var Je;function Ye(e,t){if(He&&e.data instanceof Blob)return e.data.arrayBuffer().then(qe).then(t);if(Ue&&(e.data instanceof ArrayBuffer||We(e.data)))return t(qe(e.data));Ge(e,!1,e=>{Je||=new TextEncoder,t(Je.encode(e))})}var Xe=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Ze=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)Ze[Xe.charCodeAt(e)]=e;var Qe=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=Ze[e.charCodeAt(r)],o=Ze[e.charCodeAt(r+1)],s=Ze[e.charCodeAt(r+2)],c=Ze[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},$e=typeof ArrayBuffer==`function`,et=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:nt(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:tt(e.substring(1),t)}:Be[n]?e.length>1?{type:Be[n],data:e.substring(1)}:{type:Be[n]}:Ve},tt=(e,t)=>$e?nt(Qe(e),t):{base64:!0,data:e},nt=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},rt=``,it=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{Ge(e,!1,e=>{r[a]=e,++i===n&&t(r.join(rt))})})},at=(e,t)=>{let n=e.split(rt),r=[];for(let e=0;e<n.length;e++){let i=et(n[e],t);if(r.push(i),i.type===`error`)break}return r};function ot(){return new TransformStream({transform(e,t){Ye(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 w;function T(e){return e.reduce((e,t)=>e+t.length,0)}function st(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 ct(e,t){w||=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=st(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=st(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=st(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(Ve);break}i=a*2**32+t.getUint32(4),r=3}else{if(T(n)<i)break;let e=st(n,i);s.enqueue(et(a?e:w.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(Ve);break}}}})}function E(e){if(e)return lt(e)}function lt(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 ut=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),dt=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),ft=`arraybuffer`;function pt(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var mt=dt.setTimeout,ht=dt.clearTimeout;function gt(e,t){t.useNativeTimers?(e.setTimeoutFn=mt.bind(dt),e.clearTimeoutFn=ht.bind(dt)):(e.setTimeoutFn=dt.setTimeout.bind(dt),e.clearTimeoutFn=dt.clearTimeout.bind(dt))}var _t=1.33;function vt(e){return typeof e==`string`?yt(e):Math.ceil((e.byteLength||e.size)*_t)}function yt(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 bt(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function xt(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function St(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 Ct=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},wt=class extends E{constructor(e){super(),this.writable=!1,gt(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 Ct(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=et(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=xt(e);return t.length?`?`+t:``}},Tt=class extends wt{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){at(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,it(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]=bt()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},Et=!1;try{Et=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var Dt=Et;function Ot(){}var kt=class extends Tt{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}},At=class e extends E{constructor(e,t,n){super(),this.createRequest=e,gt(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=pt(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=Ot,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(At.requestsCount=0,At.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,jt);else if(typeof addEventListener==`function`){let e=`onpagehide`in dt?`pagehide`:`unload`;addEventListener(e,jt,!1)}}function jt(){for(let e in At.requests)At.requests.hasOwnProperty(e)&&At.requests[e].abort()}var Mt=(function(){let e=Pt({xdomain:!1});return e&&e.responseType!==null})(),Nt=class extends kt{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=Mt&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new At(Pt,this.uri(),e)}};function Pt(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||Dt))return new XMLHttpRequest}catch{}if(!t)try{return new dt[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var Ft=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,It=class extends wt{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=Ft?{}:pt(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;Ge(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&ut(()=>{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]=bt()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},Lt=dt.WebSocket||dt.MozWebSocket,Rt={websocket:class extends It{createSocket(e,t,n){return Ft?new Lt(e,t,n):t?new Lt(e,t):new Lt(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends wt{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=ct(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=ot();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&&ut(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:Nt},zt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Bt=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function Vt(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=zt.exec(e||``),a={},o=14;for(;o--;)a[Bt[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=Ht(a,a.path),a.queryKey=Ut(a,a.query),a}function Ht(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 Ut(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var Wt=typeof addEventListener==`function`&&typeof removeEventListener==`function`,Gt=[];Wt&&addEventListener(`offline`,()=>{Gt.forEach(e=>e())},!1);var Kt=class e extends E{constructor(e,t){if(super(),this.binaryType=ft,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=Vt(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=Vt(t.host).host);gt(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=St(this.opts.query)),Wt&&(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`})},Gt.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+=vt(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,ut(()=>{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(),Wt&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=Gt.indexOf(this._offlineEventListener);e!==-1&&Gt.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};Kt.protocol=4;var qt=class extends Kt{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;Kt.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;Kt.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}},Jt=class extends qt{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=>Rt[e]).filter(e=>!!e)),super(e,n)}};Jt.protocol;function Yt(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=Vt(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 Xt=typeof ArrayBuffer==`function`,Zt=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,Qt=Object.prototype.toString,$t=typeof Blob==`function`||typeof Blob<`u`&&Qt.call(Blob)===`[object BlobConstructor]`,en=typeof File==`function`||typeof File<`u`&&Qt.call(File)===`[object FileConstructor]`;function tn(e){return Xt&&(e instanceof ArrayBuffer||Zt(e))||$t&&e instanceof Blob||en&&e instanceof File}function nn(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(nn(e[t]))return!0;return!1}if(tn(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return nn(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&nn(e[t]))return!0;return!1}function rn(e){let t=[],n=e.data,r=e;return r.data=an(n,t),r.attachments=t.length,{packet:r,buffers:t}}function an(e,t){if(!e)return e;if(tn(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]=an(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]=an(e[r],t));return n}return e}function on(e,t){return e.data=sn(e.data,t),delete e.attachments,e}function sn(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]=sn(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=sn(e[n],t));return e}var cn=s({Decoder:()=>dn,Encoder:()=>un,PacketType:()=>D,isPacketValid:()=>vn,protocol:()=>5}),ln=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],D;(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`})(D||={});var un=class{constructor(e){this.replacer=e}encode(e){return(e.type===D.EVENT||e.type===D.ACK)&&nn(e)?this.encodeAsBinary({type:e.type===D.EVENT?D.BINARY_EVENT:D.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===D.BINARY_EVENT||e.type===D.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=rn(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},dn=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===D.BINARY_EVENT;n||t.type===D.BINARY_ACK?(t.type=n?D.EVENT:D.ACK,this.reconstructor=new fn(t),t.attachments===0&&super.emitReserved(`decoded`,t)):super.emitReserved(`decoded`,t)}else if(tn(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(D[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===D.BINARY_EVENT||r.type===D.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(!mn(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 D.CONNECT:return gn(t);case D.DISCONNECT:return t===void 0;case D.CONNECT_ERROR:return typeof t==`string`||gn(t);case D.EVENT:case D.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&ln.indexOf(t[0])===-1);case D.ACK:case D.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},fn=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=on(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function pn(e){return typeof e==`string`}var mn=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function hn(e){return e===void 0||mn(e)}function gn(e){return Object.prototype.toString.call(e)===`[object Object]`}function _n(e,t){switch(e){case D.CONNECT:return t===void 0||gn(t);case D.DISCONNECT:return t===void 0;case D.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&ln.indexOf(t[0])===-1);case D.ACK:return Array.isArray(t);case D.CONNECT_ERROR:return typeof t==`string`||gn(t);default:return!1}}function vn(e){return pn(e.nsp)&&hn(e.id)&&_n(e.type,e.data)}function yn(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var bn=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),xn=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=[yn(e,`open`,this.onopen.bind(this)),yn(e,`packet`,this.onpacket.bind(this)),yn(e,`error`,this.onerror.bind(this)),yn(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(bn.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:D.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:D.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 D.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 D.EVENT:case D.BINARY_EVENT:this.onevent(e);break;case D.ACK:case D.BINARY_ACK:this.onack(e);break;case D.DISCONNECT:this.ondisconnect();break;case D.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:D.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:D.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 Sn(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}Sn.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},Sn.prototype.reset=function(){this.attempts=0},Sn.prototype.setMin=function(e){this.ms=e},Sn.prototype.setMax=function(e){this.max=e},Sn.prototype.setJitter=function(e){this.jitter=e};var Cn=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,gt(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 Sn({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||cn;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 Jt(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=yn(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=yn(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(yn(e,`ping`,this.onping.bind(this)),yn(e,`data`,this.ondata.bind(this)),yn(e,`error`,this.onerror.bind(this)),yn(e,`close`,this.onclose.bind(this)),yn(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){ut(()=>{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 xn(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)}},wn={};function Tn(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=Yt(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=wn[i]&&a in wn[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new Cn(r,t):(wn[i]||(wn[i]=new Cn(r,t)),c=wn[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(Tn,{Manager:Cn,Socket:xn,io:Tn,connect:Tn});var En=({apiBaseUrl:e,userId:t,chatId:n,siteId:r})=>Tn(e,{transports:[`polling`,`websocket`],upgrade:!0,rememberUpgrade:!1,auth:{userId:t,chatId:n,siteId:r},query:{chatId:n,siteId:r}}),Dn=({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)}}},On=(0,d.createContext)(null),kn=()=>{let e=(0,d.useContext)(On);if(!e)throw Error(`useFlowEngage must be used inside FlowEngageProvider`);return e};function An(){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 jn(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)}catch{return!1}}function O(...e){An()&&console.log(`[FlowEngage:shadowNavigate]`,...e)}var Mn=`fe_pending_nav_section`,Nn=15e3,Pn=`fe_voice_nav_state`,Fn=2e4,In=!1,Ln=null;function Rn(e=3e3){In=!0,Ln&&clearTimeout(Ln),Ln=setTimeout(()=>{In=!1,Ln=null},e)}function zn(){return In}var Bn=!1,Vn=null;function Hn(){Bn||typeof window>`u`||(Bn=!0,window.addEventListener(`popstate`,async()=>{let e=window.location.href;if(O(`popstate: body-swap to`,e),Vn){try{Yn(Vn)}catch{}try{Qn(Vn)}catch{}}try{if(await pr(e,{skipPushState:!0,isBack:!0})){O(`popstate: body-swap succeeded`);return}}catch(e){console.warn(`[FlowEngage] popstate body-swap error:`,e)}O(`popstate: body-swap failed, falling back to reload`),window.location.reload()}))}var Un=!1;function Wn(){Un||typeof window>`u`||typeof document>`u`||(Un=!0,document.addEventListener(`click`,async e=>{try{if(!window.history.state?.flowengageSpa)return}catch{return}let t=e.target.closest?.(`a[href]`);if(!t||t.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`))return;let n=t.getAttribute(`href`)||``;if(!n||n===`#`||n.startsWith(`javascript:`)||n.startsWith(`mailto:`)||n.startsWith(`tel:`)||t.hasAttribute(`download`)||t.target===`_blank`||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey)return;let r;try{if(r=new URL(n,window.location.href),r.origin!==window.location.origin)return}catch{return}if(!(r.pathname===window.location.pathname&&r.hash)&&!(r.pathname===window.location.pathname&&r.search===window.location.search)){e.preventDefault(),e.stopPropagation(),O(`link-intercept: body-swap to`,r.href),nr();try{try{Yn()}catch{}try{Qn()}catch{}if(await pr(r.href)){O(`link-intercept: body-swap succeeded`);return}}catch(e){console.warn(`[FlowEngage] link-intercept body-swap error:`,e)}O(`link-intercept: body-swap failed, falling back to normal navigation`),rr(),window.location.href=r.href}},!0))}function Gn(){if(typeof window>`u`)return null;if(window.next?.router||window.__NEXT_ROUTER__)return`nextjs`;if(window.__remixRouter||window.__staticRouterHydrationData)return`react-router`;if(window.___gatsby||window.___navigate)return`gatsby`;if(window.__VUE_ROUTER__)return`vue-router`;if(window.__NUXT__||window.$nuxt)return`nuxt`;if(window.ng?.getComponent||document.querySelector(`[ng-version]`))return`angular`;if(window.__sveltekit_data||document.querySelector(`[data-sveltekit-hydrate]`))return`sveltekit`;if(document.querySelector(`[data-astro-transition]`))return`astro`;if(window.__vite_plugin_react_preamble_installed__)return`vite-react-spa`;let e=Array.from(document.body.children).filter(e=>{let t=e.tagName?.toUpperCase();return!(t===`SCRIPT`||t===`NOSCRIPT`||t===`LINK`||t===`STYLE`||e.id===`flowengage-root`)});if(e.length===1){let t=e[0],n=!!t.querySelector(`[data-reactroot]`)||!!t._reactRootContainer,r=Object.keys(t).some(e=>e.startsWith(`__reactFiber$`)||e.startsWith(`__reactContainer$`));if(n||r||t.__vue_app__)return`generic-spa`}return null}var Kn=`data-fe-swap-css`;function qn(){typeof document>`u`||document.querySelectorAll(`[${Kn}]`).forEach(e=>e.remove())}var Jn=`fe_form_state:`;function Yn(e){if(typeof document>`u`||typeof sessionStorage>`u`)return;let t=document.querySelectorAll(`form`);if(!t.length)return;let n=[];if(t.forEach((e,t)=>{let r={};e.querySelectorAll(`input, textarea, select`).forEach(e=>{let t=e.name||e.id;t&&(e.type===`password`||e.type===`hidden`||(e.type===`checkbox`||e.type===`radio`?r[t+`::`+e.value]=e.checked:r[t]=e.value))}),Object.keys(r).length&&n.push({formIndex:t,fields:r})}),n.length)try{let t=Jn+(e||window.location.pathname);sessionStorage.setItem(t,JSON.stringify({state:n,ts:Date.now()}))}catch{}}function Xn(){if(typeof document>`u`||typeof sessionStorage>`u`)return;let e=Jn+window.location.pathname,t;try{t=JSON.parse(sessionStorage.getItem(e)||`null`)}catch{return}if(!t||!t.state)return;if(Date.now()-t.ts>1800*1e3){try{sessionStorage.removeItem(e)}catch{}return}let n=document.querySelectorAll(`form`);for(let{formIndex:e,fields:r}of t.state){let t=n[e];if(t)for(let[e,n]of Object.entries(r))if(e.includes(`::`)){let[r,i]=e.split(`::`),a=t.querySelector(`input[name="${r}"][value="${i}"], input[id="${r}"][value="${i}"]`);a&&(a.checked=!!n)}else{let r=t.querySelector(`[name="${e}"], [id="${e}"]`);if(r&&r.type!==`file`){r.value=n;try{r.dispatchEvent(new Event(`input`,{bubbles:!0}))}catch{}try{r.dispatchEvent(new Event(`change`,{bubbles:!0}))}catch{}}}}try{sessionStorage.removeItem(e)}catch{}}var Zn=`fe_scroll:`;function Qn(e){if(!(typeof window>`u`||typeof sessionStorage>`u`))try{let t=Zn+(e||window.location.pathname);sessionStorage.setItem(t,JSON.stringify({y:window.scrollY,ts:Date.now()}))}catch{}}function $n(){if(typeof window>`u`||typeof sessionStorage>`u`)return;let e=Zn+window.location.pathname,t;try{t=JSON.parse(sessionStorage.getItem(e)||`null`)}catch{return}if(t){try{sessionStorage.removeItem(e)}catch{}Date.now()-t.ts>1800*1e3||setTimeout(()=>{window.scrollTo({top:t.y,behavior:`instant`})},80)}}function er(e){if(!(typeof window>`u`))try{window.dispatchEvent(new CustomEvent(`flowengage:pageswap`,{detail:{url:e,timestamp:Date.now()}}))}catch{}}var tr=`fe-nav-loader`;function nr(){if(typeof document>`u`||document.getElementById(tr))return;let e=document.createElement(`div`);e.id=tr,e.style.cssText=[`position:fixed`,`top:0`,`left:0`,`width:0`,`height:3px`,`background:linear-gradient(90deg,#7c3aed,#6366f1)`,`z-index:2147483647`,`transition:width 0.4s ease`,`pointer-events:none`].join(`;`),document.body.appendChild(e),requestAnimationFrame(()=>{e.style.width=`70%`})}function rr(){if(typeof document>`u`)return;let e=document.getElementById(tr);e&&(e.style.width=`100%`,setTimeout(()=>{e.style.opacity=`0`,e.style.transition=`opacity 0.3s ease`,setTimeout(()=>e.remove(),350)},200))}function ir(){if(typeof window>`u`||typeof document>`u`)return;try{window.history.state?.flowengageSpa&&Hn()}catch{}let e;try{e=JSON.parse(sessionStorage.getItem(Mn)||`null`)}catch{return}if(!e)return;try{sessionStorage.removeItem(Mn)}catch{}let{sectionText:t,ts:n}=e;if(!t)return;if(Date.now()-n>Nn){O(`initNavigationHighlight: pending section expired, skipping:`,t);return}O(`initNavigationHighlight: replaying section highlight:`,t);let r=0,i=()=>{r+=1;let e=or(null,t);if(e){sr(e),O(`initNavigationHighlight: highlighted on attempt`,r);return}r<8?setTimeout(i,300):O(`initNavigationHighlight: could not find element after 8 attempts:`,t)};setTimeout(i,250)}var ar=()=>{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;
@@ -631,7 +631,7 @@ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
631
631
  <path d="M4 2L19 10.5L11 12.8L8 20L4 2Z"
632
632
  fill="white" stroke="#1e1b4b" stroke-width="1.6" stroke-linejoin="round"
633
633
  filter="url(#${Q}-csh)"/>
634
- </svg>`,xO=null,SO=!1;function CO(){return(!xO||!xO.isConnected)&&(xO=document.createElement(`div`),xO.id=`${Q}-cursor`,xO.innerHTML=bO,document.body.appendChild(xO),SO=!1),xO}async function wO(e){if(typeof document>`u`||!e)return;oO();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=CO();SO||=(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 OO(360)}function TO(e=!1){xO&&(e?(xO.classList.remove(`${Q}-cursor-visible`),SO=!1):(xO.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{SO=!1},250)))}async function EO(e){xO&&(xO.classList.add(`${Q}-cursor-click`),await OO(280),xO.classList.remove(`${Q}-cursor-click`))}function DO(e){if(!e||typeof document>`u`)return;oO();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 OO(e){return new Promise(t=>setTimeout(t,e))}function $(...e){An()&&console.log(`[FlowEngage:voice-tools]`,...e)}function kO(e){return new Promise(t=>setTimeout(t,e))}var AO=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function jO(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(AO)}catch{return!1}}function MO(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function NO(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(!jO(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function PO(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function FO(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 PO(r.join(` `))}if(e.labels&&e.labels.length)return PO(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return PO(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return PO(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return PO(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=PO(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 PO(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return PO(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?PO(o):null}function IO(){let e=[];return NO(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(jO(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=MO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function LO(){return IO().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:FO(e),placeholder:e.placeholder||null}))}function RO(){let e=[];return NO(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(jO(e)||e.disabled)return!1;try{let t=MO(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 zO(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function BO(e){let t=zO(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function VO(e,t){let n=BO(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,FO(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>zO(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 HO=28;function UO(e,t){let n=null,r=0;for(let i of e){let e=VO(i,t);e>r&&(r=e,n=i)}return!n||r<HO?null:n}function WO(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,FO(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 GO(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function KO(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 qO(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 JO(e){if(!qO(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,FO(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 YO(e,t,n){let r=String(t??``),i=String(n??``),a=QO(e,r)||UO(e,r)||WO(e,r,i);if(!a)return[];let o=new Set([a]);if(GO(i)&&KO(r))for(let t of e)t!==a&&JO(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 XO(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 ZO(e){if(!e||typeof e!=`string`)return null;let t=null;return NO(n=>{try{let r=n.getElementById(e);r&&!jO(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function QO(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=ZO(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=ZO(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 $O(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=(e.innerText||e.textContent||``).replace(/\s+/g,` `).trim(),i=[r,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-text`),e.getAttribute(`data-label`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(i.includes(n)||r.toLowerCase()===n)return 100;let a=n.split(/\s+/).filter(e=>e.length>1);if(!a.length)return 0;let o=0;for(let e of a)i.includes(e)&&(o+=1);return o/a.length*92}function ek(e,t){let n=[];NO(e=>{let t=Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"], a[href]`));n.push(...t.filter(e=>{if(jO(e)||e.disabled)return!1;try{let t=MO(e);if(t.display===`none`||t.visibility===`hidden`||t.opacity===`0`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:$O(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<28)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=XO(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function tk(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 nk(e){let t=tk(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 rk(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 ik(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 ak(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 ok(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 sk(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 ck(){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 lk(){let e=document.querySelector(`main, [role='main'], article`)||document.body;return Array.from(e.querySelectorAll(`h1, h2, h3`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200).slice(0,12)}function uk(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 i=tk(n),a=ak(i),o=i.section_text??i.sectionText??i.section,s=Array.isArray(i.expected_landmarks)?i.expected_landmarks:Array.isArray(i.expectedLandmarks)?i.expectedLandmarks:[];if($(`flowengage_navigate · coerced:`,{url:a,sectionText:o,expectedLandmarks:s}),!a){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`flowengage_navigate ✖`,e),e}if(typeof window<`u`)try{let e=new URL(a,window.location.href);e.origin!==window.location.origin&&/^https?:$/i.test(e.protocol)&&(a=e.pathname+e.search+e.hash,$(`flowengage_navigate · normalized cross-origin URL to path:`,a))}catch{}if(typeof window<`u`)try{let e=new URL(a,window.location.href);if(e.pathname===window.location.pathname&&e.search===window.location.search)return $(`flowengage_navigate ✖ already on page, skipping`),`OK_ALREADY_ON_PAGE. The visitor is already on this page. Do not navigate. Proceed directly with highlights, answering the question, or reading page content.`}catch{}if(!await dr(a,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`Page "${a}" could not be verified. Call flowengage_search with keywords from the topic to find the correct URL, then navigate to the URL from the search results.`;return $(`flowengage_navigate ✖ blocked`,e),e}try{uO(`Navigating to ${a}...`,{spinner:!0}),hO(),lD();try{let e=r?r():``;if(e&&t){let n=aO([{sender:`user`,message:e}]);n&&xe(t,n)}}catch{}Te();let e=a;try{e=new URL(a,typeof window<`u`?window.location.href:``).href}catch{}t&&typeof window<`u`&&Me(t,window.location.href,e),mr(e),$(`flowengage_navigate → real navigation`,a);let n=typeof window<`u`&&!!(window.next?.router||window.__NEXT_ROUTER__||window.__remixRouter||window.__staticRouterHydrationData||window.___gatsby||window.___navigate||window.__VUE_ROUTER__||window.__NUXT__||window.$nuxt||window.ng?.getComponent||typeof document<`u`&&document.querySelector(`[ng-version]`)||window.__sveltekit_data||typeof document<`u`&&document.querySelector(`[data-sveltekit-hydrate]`));if(typeof window<`u`&&window.__fe_triggerVoiceNavHooks&&window.__fe_triggerVoiceNavHooks(),n&&Rn(3e3),_r(a,{voiceActive:!0}).catch(()=>{}),n)try{let e=new URL(a,window.location.origin).pathname,t=Date.now()+2e3;for(;Date.now()<t&&!(typeof window<`u`&&window.location.pathname===e);)await new Promise(e=>setTimeout(e,80));let n=typeof window<`u`?window.location.pathname:e,r=typeof window<`u`?window.location.href:a,i=n===e,o=(n.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`;$(`flowengage_navigate → SPA nav complete. target:`,e,`actual:`,n);let s=[],c=Date.now()+8e3;for(;Date.now()<c&&(await new Promise(e=>setTimeout(e,250)),s=lk(),!(s.length>=1)););ck(),$(`flowengage_navigate → page headings collected:`,s);let l=s.length?s.join(` | `):`none`,u=s.length?`Use ONLY these exact heading strings for flowengage_highlight.`:`No headings were collected from the live DOM — use your knowledge base heading strings for this page to call flowengage_highlight. Follow RULE 1: call each highlight BEFORE describing its section (transition → highlight → content).`;return i?(hr(),`OK_NAVIGATE_SPA. Visitor is now on: ${r} (page: "${o}") | Section headings: ${l}. ${u} MANDATORY: call flowengage_highlight for EVERY section before describing it — never give a plain summary. Do NOT say "I have navigated you" or "I've taken you to" — start the highlighted walkthrough immediately.`):(hr(),`OK_NAVIGATE_SPA. CURRENT PAGE IS: ${r} (page: "${o}") | Section headings: ${l}. ${u} MANDATORY: call flowengage_highlight for EVERY section before describing it — never give a plain summary. Describe THIS page only — do not mention the page you tried to navigate to.`)}catch{}return`OK_NAVIGATE_RELOADING. Navigating to the page now; the voice session will resume automatically on the new page. When the session resumes, immediately introduce the new page and continue guiding the visitor — do not wait for the user to speak first.`}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`flowengage_navigate ✖`,t),uO(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{gO(),dO(900)}},flowengage_highlight:async e=>{$(`flowengage_highlight ▶`,e);let t=tk(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;ck();let i=or(n||null,r||null);if(!i&&r){let e=Date.now()+600;for(;!i&&Date.now()<e;)await new Promise(e=>setTimeout(e,50)),ck(),i=or(null,r)}if(!i){$(`flowengage_highlight ✖ no element for:`,r||n);let e=lk(),t=e.length?`Page headings: ${e.join(` | `)}. Use one of these exact strings for section_text.`:`No headings found — skip highlight and continue.`;return`HIGHLIGHT_NOT_FOUND: "${r||n}" on the current page. ${t}`}return cD(i),$(`flowengage_highlight ✓`,r||n),`OK_HIGHLIGHT: "${r||n}". WALKTHROUGH: continue immediately to the next section — do NOT pause between sections.`},flowengage_read_content:async e=>{$(`flowengage_read_content ▶`,e);let t=tk(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=or(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(`
634
+ </svg>`,xO=null,SO=!1;function CO(){return(!xO||!xO.isConnected)&&(xO=document.createElement(`div`),xO.id=`${Q}-cursor`,xO.innerHTML=bO,document.body.appendChild(xO),SO=!1),xO}async function wO(e){if(typeof document>`u`||!e)return;oO();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=CO();SO||=(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 OO(360)}function TO(e=!1){xO&&(e?(xO.classList.remove(`${Q}-cursor-visible`),SO=!1):(xO.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{SO=!1},250)))}async function EO(e){xO&&(xO.classList.add(`${Q}-cursor-click`),await OO(280),xO.classList.remove(`${Q}-cursor-click`))}function DO(e){if(!e||typeof document>`u`)return;oO();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 OO(e){return new Promise(t=>setTimeout(t,e))}function $(...e){An()&&console.log(`[FlowEngage:voice-tools]`,...e)}function kO(e){return new Promise(t=>setTimeout(t,e))}var AO=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function jO(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(AO)}catch{return!1}}function MO(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function NO(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(!jO(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function PO(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function FO(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 PO(r.join(` `))}if(e.labels&&e.labels.length)return PO(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return PO(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return PO(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return PO(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=PO(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 PO(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return PO(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?PO(o):null}function IO(){let e=[];return NO(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(jO(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=MO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function LO(){return IO().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:FO(e),placeholder:e.placeholder||null}))}function RO(){let e=[];return NO(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(jO(e)||e.disabled)return!1;try{let t=MO(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 zO(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function BO(e){let t=zO(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function VO(e,t){let n=BO(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,FO(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>zO(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 HO=28;function UO(e,t){let n=null,r=0;for(let i of e){let e=VO(i,t);e>r&&(r=e,n=i)}return!n||r<HO?null:n}function WO(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,FO(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 GO(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function KO(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 qO(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 JO(e){if(!qO(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,FO(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 YO(e,t,n){let r=String(t??``),i=String(n??``),a=QO(e,r)||UO(e,r)||WO(e,r,i);if(!a)return[];let o=new Set([a]);if(GO(i)&&KO(r))for(let t of e)t!==a&&JO(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 XO(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 ZO(e){if(!e||typeof e!=`string`)return null;let t=null;return NO(n=>{try{let r=n.getElementById(e);r&&!jO(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function QO(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=ZO(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=ZO(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 $O(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=(e.innerText||e.textContent||``).replace(/\s+/g,` `).trim(),i=[r,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-text`),e.getAttribute(`data-label`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(i.includes(n)||r.toLowerCase()===n)return 100;let a=n.split(/\s+/).filter(e=>e.length>1);if(!a.length)return 0;let o=0;for(let e of a)i.includes(e)&&(o+=1);return o/a.length*92}function ek(e,t){let n=[];NO(e=>{let t=Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"], a[href]`));n.push(...t.filter(e=>{if(jO(e)||e.disabled)return!1;try{let t=MO(e);if(t.display===`none`||t.visibility===`hidden`||t.opacity===`0`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:$O(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<28)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=XO(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function tk(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 nk(e){let t=tk(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 rk(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 ik(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 ak(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 ok(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 sk(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 ck(){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 lk(){let e=document.querySelector(`main, [role='main'], article`)||document.body;return Array.from(e.querySelectorAll(`h1, h2, h3`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200).slice(0,12)}function uk(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 i=tk(n),a=ak(i),o=i.section_text??i.sectionText??i.section,s=Array.isArray(i.expected_landmarks)?i.expected_landmarks:Array.isArray(i.expectedLandmarks)?i.expectedLandmarks:[];if($(`flowengage_navigate · coerced:`,{url:a,sectionText:o,expectedLandmarks:s}),!a){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`flowengage_navigate ✖`,e),e}if(typeof window<`u`)try{let e=new URL(a,window.location.href);e.origin!==window.location.origin&&/^https?:$/i.test(e.protocol)&&(a=e.pathname+e.search+e.hash,$(`flowengage_navigate · normalized cross-origin URL to path:`,a))}catch{}if(typeof window<`u`)try{let e=new URL(a,window.location.href);if(e.pathname===window.location.pathname&&e.search===window.location.search)return $(`flowengage_navigate ✖ already on page, skipping`),`OK_ALREADY_ON_PAGE. The visitor is already on this page. Do not navigate. Proceed directly with highlights, answering the question, or reading page content.`}catch{}if(!await dr(a,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`Page "${a}" could not be verified. Call flowengage_search with keywords from the topic to find the correct URL, then navigate to the URL from the search results.`;return $(`flowengage_navigate ✖ blocked`,e),e}try{uO(`Navigating to ${a}...`,{spinner:!0}),hO(),lD();try{let e=r?r():``;if(e&&t){let n=aO([{sender:`user`,message:e}]);n&&xe(t,n)}}catch{}Te();let e=a;try{e=new URL(a,typeof window<`u`?window.location.href:``).href}catch{}t&&typeof window<`u`&&Me(t,window.location.href,e),mr(e),$(`flowengage_navigate → real navigation`,a);let n=typeof window<`u`&&!!Gn();if(typeof window<`u`&&window.__fe_triggerVoiceNavHooks&&window.__fe_triggerVoiceNavHooks(),n&&Rn(3e3),_r(a,{voiceActive:!0}).catch(()=>{}),n)try{let e=new URL(a,window.location.origin).pathname,t=Date.now()+2e3;for(;Date.now()<t&&!(typeof window<`u`&&window.location.pathname===e);)await new Promise(e=>setTimeout(e,80));let n=typeof window<`u`?window.location.pathname:e,r=typeof window<`u`?window.location.href:a,i=n===e,o=(n.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`;$(`flowengage_navigate → SPA nav complete. target:`,e,`actual:`,n);let s=[],c=Date.now()+8e3;for(;Date.now()<c&&(await new Promise(e=>setTimeout(e,250)),s=lk(),!(s.length>=1)););ck(),$(`flowengage_navigate → page headings collected:`,s);let l=s.length?s.join(` | `):`none`,u=s.length?`Use ONLY these exact heading strings for flowengage_highlight.`:`No headings were collected from the live DOM — use your knowledge base heading strings for this page to call flowengage_highlight. Follow RULE 1: call each highlight BEFORE describing its section (transition → highlight → content).`;return i?(hr(),`OK_NAVIGATE_SPA. Visitor is now on: ${r} (page: "${o}") | Section headings: ${l}. ${u} MANDATORY: call flowengage_highlight for EVERY section before describing it — never give a plain summary. Do NOT say "I have navigated you" or "I've taken you to" — start the highlighted walkthrough immediately.`):(hr(),`OK_NAVIGATE_SPA. CURRENT PAGE IS: ${r} (page: "${o}") | Section headings: ${l}. ${u} MANDATORY: call flowengage_highlight for EVERY section before describing it — never give a plain summary. Describe THIS page only — do not mention the page you tried to navigate to.`)}catch{}return`OK_NAVIGATE_RELOADING. Navigating to the page now; the voice session will resume automatically on the new page. When the session resumes, immediately introduce the new page and continue guiding the visitor — do not wait for the user to speak first.`}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`flowengage_navigate ✖`,t),uO(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{gO(),dO(900)}},flowengage_highlight:async e=>{$(`flowengage_highlight ▶`,e);let t=tk(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;ck();let i=or(n||null,r||null);if(!i&&r){let e=Date.now()+600;for(;!i&&Date.now()<e;)await new Promise(e=>setTimeout(e,50)),ck(),i=or(null,r)}if(!i){$(`flowengage_highlight ✖ no element for:`,r||n);let e=lk(),t=e.length?`Page headings: ${e.join(` | `)}. Use one of these exact strings for section_text.`:`No headings found — skip highlight and continue.`;return`HIGHLIGHT_NOT_FOUND: "${r||n}" on the current page. ${t}`}return cD(i),$(`flowengage_highlight ✓`,r||n),`OK_HIGHLIGHT: "${r||n}". WALKTHROUGH: continue immediately to the next section — do NOT pause between sections.`},flowengage_read_content:async e=>{$(`flowengage_read_content ▶`,e);let t=tk(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=or(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(`
635
635
  `)}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=ok(tk(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.`;uO(`Searching${r?` for "${r}"`:``}…`,{spinner:!0});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}finally{dO(600)}},flowengage_page_content:async e=>{$(`flowengage_page_content ▶`,e);let r=tk(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} FALLBACK REQUIRED: This page is not in the search index. Call flowengage_read_content (no parameters) immediately to read the live page content directly from the visitor's browser — do NOT tell the visitor you cannot access the page.`}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_get_current_page:async()=>{if($(`flowengage_get_current_page ▶`),typeof window>`u`)return`Cannot determine current page (no browser context).`;let e=window.location.href,t=window.location.pathname,n=document.title||``,r=lk(),i=r.length?r.join(` | `):`none`;return $(`flowengage_get_current_page ✓`,{url:e,path:t,title:n}),$(`flowengage_get_current_page → page headings collected:`,r),`CURRENT_PAGE. URL: ${e} | Path: ${t} | Title: ${n} | Section headings: ${i}. Use ONLY these exact heading strings for flowengage_highlight — never invent or abbreviate section names.`},flowengage_list_forms:async()=>{let e=LO(),t=RO();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),_O();let t=nk(e);if(!t.length&&r){let e=r(),n=rk(e);n.length?$(`flowengage_fill_form · inferred URL from last user utterance (model omitted usable fields):`,n):(n=ik(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,r=e?.value;if(t==null||r==null)continue;uO(`Filling ${String(t)}...`,{spinner:!0});let a=IO(),o=YO(a,String(t),r);if(o.length){for(let[e,t]of o.entries())vO(t),await wO(t),sk(t,r,{skipScroll:e>0}),yO(t),await kO(120);i=o,n.push(String(t));continue}let s=QO(a,String(t));s||=UO(a,String(t)),s||=WO(a,String(t),r),s&&(vO(s),await wO(s),sk(s,r),yO(s),await kO(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),uO(`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),uO(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{TO(),_O(),dO(700)}},flowengage_click_button:async e=>{let t=tk(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=ek(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{uO(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await wO(r),r.focus?.(),await EO(r),DO(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),uO(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`flowengage_click_button ✖`,t),uO(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{TO(),dO(700)}}};return{...a,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 dk(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=An();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 fk={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function pk(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 mk(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 hk(e){let[t,n]=d.default.useState(null),r=typeof e==`string`?e.trim():``;return d.default.useEffect(()=>{if(!r){n(null);return}n(null);let e=!1,t=new window.Image;return t.onload=()=>{e||n(r)},t.onerror=()=>{e||n(null)},t.src=r,()=>{e=!0}},[r]),t}function gk({logo:e,style:t}){let n=hk(typeof e==`string`?e:null);if(!e)return null;if(typeof e==`string`)return n?(0,f.jsx)(`img`,{src:n,alt:``,style:{objectFit:`contain`,flexShrink:0,display:`block`,...t}}):null;let r=typeof e==`function`?d.default.createElement(e):d.default.isValidElement(e)?e:null;return r?(0,f.jsx)(`span`,{className:`fe-logo-slot`,style:{display:`inline-flex`,alignItems:`center`,flexShrink:0,overflow:`hidden`,...t},children:r}):null}function _k({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 vk(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 yk({orbColors:e,...t}){return(0,f.jsx)(XD,{colors:e,...t})}function bk({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a,isClosing:o}){let s=n||fk.green,c=mk(s),l=a?72:94,u=(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:a?`flex-end`:`center`,gap:a?`7px`:`9px`},children:[(0,f.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(_m.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:`14px`,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)(_m.div,{initial:{y:10,opacity:0},animate:{y:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.54},style:{display:`flex`,gap:`16px`,flexWrap:`nowrap`},children:[(0,f.jsx)(`button`,{onClick:r,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:s,color:c,fontWeight:400,fontSize:`14px`,border:`none`,cursor:`pointer`,whiteSpace:`nowrap`,boxShadow:`0 4px 16px ${s}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:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:`transparent`,color:`white`,fontWeight:400,fontSize:`14px`,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)(_m.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)(yk,{size:l,orbColors:t})})]});return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(_m.div,{initial:{opacity:0},animate:{opacity:o?0:1},transition:{duration:.28},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`,animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u}):(0,f.jsx)(`div`,{style:{animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u})]})}function xk({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o,isClosing:s}){let c=n||fk.green,l=mk(c);return(0,f.jsxs)(_m.div,{initial:{scale:50/350,borderRadius:`50%`},animate:s?{scale:50/350,opacity:0,borderRadius:`50%`}:{scale:1,borderRadius:`16px`,opacity:1},transition:{type:`spring`,stiffness:260,damping:26},style:{transformOrigin:o?`bottom center`:`bottom right`,background:`white`,width:o?`100%`:`350px`,height:`245px`,padding:`24px 40px 32px`,boxSizing:`border-box`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`space-between`,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)(yk,{size:72,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,fontSize:`16px`,fontWeight:400,color:`#111827`,textAlign:`center`,lineHeight:1.4},children:e.connectionTitle}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`16px`,width:`100%`},children:[(0,f.jsx)(`button`,{onClick:r,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:c,color:l,fontWeight:400,fontSize:`16px`,border:`none`,cursor:`pointer`,transition:`transform 0.15s ease`,boxShadow:`0 4px 12px ${c}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:{width:`127px`,height:`43px`,borderRadius:`999px`,background:`transparent`,color:`#111827`,fontWeight:400,fontSize:`16px`,border:`1.5px 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 Sk({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,chatId:o,historyRef:s,onMessageSync:c,voiceEndCounter:l}){let[u,p]=(0,d.useState)(`idle`),[m,h]=(0,d.useState)(!1),[g,_]=(0,d.useState)(!1),v=(0,d.useRef)(null),y=(0,d.useRef)(``),b=(0,d.useRef)(async()=>{}),x=(0,d.useRef)(!1),S=(0,d.useRef)(!1),ee=(0,d.useRef)(!1),te=(0,d.useRef)(!1),ne=(0,d.useRef)(`minimized`),re=(0,d.useRef)(null),C=(0,d.useRef)(null),ie=(0,d.useRef)(null),ae=(0,d.useRef)(0),oe=(0,d.useRef)(!1),se=(0,d.useRef)(`idle`),ce=(0,d.useRef)(!1),le=(0,d.useRef)(null),ue=(0,d.useRef)(null),de=(0,d.useRef)(!1),fe=(0,d.useCallback)((e=`minimized`)=>{ne.current=e,te.current=!0,queueMicrotask(()=>{x.current||(x.current=!0,b.current?.())})},[s]),pe=(0,d.useCallback)(async e=>{te.current=!0;try{lD()}catch{}if(i)try{Ne(i)}catch{}try{await v.current?.endSession?.()}catch{}let t=re.current,n=C.current;if(t&&o&&a){let e=n?Math.round((Date.now()-n)/1e3):0;fetch(`${a}/api/voice/save-chat-recording`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({chatId:o,elevenLabsConversationId:t,duration:e,siteId:i})}).catch(e=>console.warn(`[FlowEngage] save-chat-recording failed:`,e.message))}if(re.current=null,C.current=null,v.current=null,p(`idle`),h(!1),x.current=!1,xr(),i)try{Ce(i)}catch{}typeof c==`function`&&await c(s.current),e?.()},[s,c,i,o,a]);return b.current=()=>pe(ne.current===`chat`?t:n),(0,d.useEffect)(()=>{S.current=m},[m]),(0,d.useEffect)(()=>{l&&fe(`chat`)},[l]),(0,d.useEffect)(()=>{let e=!1,l=null,u=null,d=null;return(async()=>{if(!r){p(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;s.current=[],y.current=``,x.current=!1,ee.current=!1,te.current=!1,ne.current=`minimized`,br({onBeforeNavigate:()=>{if(i&&s.current.length>0)try{let e=aO(s.current);e&&xe(i,e)}catch{}if(!Gn()){let e=re.current,t=C.current;if(e&&o&&a)try{let n=t?Math.round((Date.now()-t)/1e3):0,r=JSON.stringify({chatId:o,elevenLabsConversationId:e,duration:n,siteId:i}),s=`${a}/api/voice/save-chat-recording`;fetch(s,{method:`POST`,headers:{"Content-Type":`application/json`},body:r,keepalive:!0}).catch(()=>{}),re.current=null,C.current=null}catch{}}Te()}});let t=dk(uk({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>y.current,requestEndSession:()=>{oe.current=!0}})),n=i?Se(i):null,c=!!n?.transcript,f=!!(i&&Ne(i)),m=typeof window<`u`?window.location.pathname:`/`,g=typeof document<`u`?document.title:``,_=m===`/`||m===``,b=null;try{let e=await fetch(`${a}/api/voice/signed-url?siteId=${encodeURIComponent(i||``)}`,{method:`GET`,headers:{"Content-Type":`application/json`}});if(e.ok)b=(await e.json()).signedUrl||null,b&&console.log(`[FlowEngage] ✅ Using signed ElevenLabs URL`);else if(e.status===429){let t=await e.json().catch(()=>({}));throw Error(t.message||`Too many voice sessions started. Please wait a minute before trying again.`)}else console.warn(`[FlowEngage] ⚠️ Signed URL fetch failed, falling back to agentId`)}catch(e){if(e.message&&e.message.includes(`Too many voice sessions`))throw e;console.warn(`[FlowEngage] ⚠️ Signed URL fetch error:`,e.message)}let ie={clientTools:t,connectionType:`websocket`,minSpeechDurationMs:100,...b?{signedUrl:b}:{agentId:r}},pe=(m.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),me=``;g&&g.includes(`|`)&&(me=g.split(`|`).map(e=>e.trim()).filter(Boolean).reduce((e,t)=>e.length<=t.length?e:t));let he=me||pe||`this page`;b?f?(ie.overrides={agent:{firstMessage:`I've navigated you to the ${he} page. Let me walk you through what's here.`}},console.log(`[FlowEngage] 🔄 Agent-nav resume: firstMessage set for "${he}" (${m})`)):c?ie.overrides={agent:{firstMessage:`I'm still here. Go ahead!`}}:_||(ie.overrides={agent:{firstMessage:`Hi! I see you are currently on the ${he} page. Are you looking for something specific here?`}},console.log(`[FlowEngage] 🏠 Page-context override: "${he}" for ${m}`)):c&&(ie.overrides={agent:{firstMessage:``}});let ge=!1,_e=f?`NAVIGATION RESUME — Your intro has been spoken. NOW — without waiting for the visitor to say anything — call flowengage_highlight for the first content section on this page, then speak one sentence about it. Continue section by section (highlight + one sentence each) until you have covered the key content. Prior conversation context:\n${(i?Se(i):null)?.transcript||``}\n\n`:null,ve=await aD.startSession({...ie,onConnect:({conversationId:e})=>{re.current=e,C.current=Date.now(),console.log(`[FlowEngage] 🎙️ AI chat session connected:`,e)},onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onModeChange:({mode:t})=>{if(!e){if(t===`speaking`){ue.current&&=(clearTimeout(ue.current),null),p(`speaking`),se.current=`speaking`,ce.current=!0,de.current=!1,le.current&&=(clearTimeout(le.current),null);return}if(se.current=`listening`,oe.current){oe.current=!1,fe();return}if(_e&&!ge){ge=!0;try{v.current?.sendUserMessage?.(`continue with the tour`)}catch{}}ue.current&&clearTimeout(ue.current),ue.current=setTimeout(()=>{e||se.current!==`speaking`&&(de.current||(ue.current=null,se.current=`listening`,p(`listening`),ce.current&&!S.current&&(le.current&&clearTimeout(le.current),le.current=setTimeout(()=>{if(!e&&se.current===`listening`&&!S.current)try{v.current?.sendContextualUpdate?.(`The visitor has been silent for a while. Ask one short, natural question to re-engage — for example: 'Is there anything specific you'd like to know more about?' or 'What else can I help you with today?' Keep it to one sentence.`)}catch{}},4e3))))},1200)}},onMessage:t=>{if(e)return;let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;if(r){if(n===`user`&&(y.current=r,de.current=!0,ue.current&&=(clearTimeout(ue.current),null),le.current&&=(clearTimeout(le.current),null)),s.current=[...s.current,{sender:n,message:r,timestamp:new Date().toISOString()}],i)try{let e=aO(s.current);e&&xe(i,e)}catch{}if(vk(n,r)){fe(`minimized`);return}if(S.current&&n===`bot`&&/are you still there|still there\??|hello\?|anyone there|checking in|you there|are you available|is anyone|did you step away/i.test(r))if(ae.current+=1,ae.current===2)try{v.current?.sendContextualUpdate?.(`IMPORTANT: The visitor is muted and has not responded to your last 2 checks. Make exactly ONE more check. If there is still no response, say: 'I feel like you are not active, so I'm ending this session. You can connect with me anytime.' then immediately call the flowengage_end_session tool to end the voice session. Do NOT ask again after that.`)}catch{}else ae.current>=5&&fe(`minimized`)}},onError:t=>{if(!e&&!te.current&&!ee.current&&!Ae()){ee.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{v.current?.setMicMuted?.(!0)}catch{}h(!0),p(`error`),fe(`chat`)}},onDisconnect:t=>{if(e||te.current||ee.current||Ae())return;let n=s.current?.length||0;console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:n,reason:t?.reason,closeCode:t?.context?.code,closeReason:t?.context?.reason||t?.message,lastUserText:y.current||``,wasMuted:S.current}),ee.current=!0;try{v.current?.setMicMuted?.(!0)}catch{}h(!0),fe(`chat`)}});if(e){ve.endSession().catch(()=>{});return}l=ve,v.current=ve,p(`listening`);try{let e=typeof window<`u`?window.location.href:``,r=`[]`;try{r=await t.list_page_forms()}catch{}let a=c&&!f?`RESUMING PRIOR SESSION — DO NOT GREET. The visitor is continuing the same conversation after a page reload. Do not introduce yourself or re-state your capabilities. Wait silently until the visitor speaks; if you must speak first, briefly acknowledge where you left off in one short sentence.\nPrior transcript:\n${n?.transcript||``}\n\n`:``;ve.sendContextualUpdate(`${a}Page: ${e}. SiteId: ${i||`unknown`}. Forms: ${r}. Voice: call end_voice_session or say you are ending the session to stop.`)}catch{}if(typeof window<`u`){let t=window.location.pathname,n=()=>{if(e)return;let n=window.location.pathname;if(n===t)return;if(zn()){t=n;return}t=n;let r=window.location.href,i=typeof document<`u`?document.title:``,a=typeof document<`u`?Array.from(document.querySelectorAll(`h1, h2, h3, h4`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell`)).map(e=>({tag:e.tagName,text:e.textContent.trim()})).filter(e=>e.text.length>0&&e.text.length<200).slice(0,20):[];try{v.current?.sendContextualUpdate?.(`PAGE CHANGED — visitor navigated manually. Current URL is now: ${r}. Page title: "${i}". Sections on this page: ${JSON.stringify(a)}. When the visitor asks about "this page", "current page", or "what page am I on", refer to this new URL — not any previously mentioned page.`)}catch{}};u=window.history.pushState.bind(window.history),window.history.pushState=(...e)=>{u(...e),setTimeout(n,50)},d=()=>setTimeout(n,50),window.addEventListener(`popstate`,d)}}catch(r){e||(console.error(`[FlowEngage] startSession failed`,r),r.message&&r.message.includes(`Too many voice sessions`)?(alert(r.message),n&&n(`minimized`)):(p(`error`),ne.current=`chat`,window.setTimeout(()=>{e||t?.()},0)))}})(),()=>{e=!0,te.current=!0;try{lD()}catch{}if(i)try{Ne(i)}catch{}xr(),le.current&&=(clearTimeout(le.current),null),ue.current&&=(clearTimeout(ue.current),null),ce.current=!1,de.current=!1,se.current=`idle`,u&&typeof window<`u`&&(window.history.pushState=u),d&&typeof window<`u`&&window.removeEventListener(`popstate`,d);let t=l||v.current,n=re.current,r=C.current;if(t?.endSession?.().catch(()=>{}),n&&o&&a){let e=r?Math.round((Date.now()-r)/1e3):0,t=JSON.stringify({chatId:o,elevenLabsConversationId:n,duration:e,siteId:i}),s=`${a}/api/voice/save-chat-recording`;typeof navigator<`u`&&navigator.sendBeacon&&navigator.sendBeacon(s,new Blob([t],{type:`application/json`}))||fetch(s,{method:`POST`,headers:{"Content-Type":`application/json`},body:t,keepalive:!0}).catch(()=>{}),re.current=null,C.current=null}typeof c==`function`&&s.current.length>0&&c(s.current).catch?.(()=>{})}},[r,i,a,fe]),(0,d.useEffect)(()=>{if(!g)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;ie.current&&!ie.current.contains(t)&&_(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[g]),(0,f.jsxs)(`div`,{ref:ie,style:{position:`relative`,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:[u===`listening`&&!m&&(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...`}),m&&(0,f.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`#f87171`,fontSize:`16px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Muted`}),(0,f.jsx)(yk,{size:72,voiceState:u,isMuted:m,orbColors:e})]}),u===`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(v.current)try{if(m){ae.current=0,await v.current.setMicMuted?.(!1),h(!1);try{v.current.sendContextualUpdate?.(`The visitor has unmuted. Resume normal interaction and wait for them to speak.`)}catch{}}else{ae.current=0,await v.current.setMicMuted?.(!0),h(!0);try{v.current.sendContextualUpdate?.(`The visitor has muted their microphone. Do NOT speak, ask if they are there, or prompt them in any way. Stay completely silent until they unmute.`)}catch{}}}catch{}},title:m?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:m?`#7f1d1d`:`#1f2937`,border:m?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:m?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:m?(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)(`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.jsx)(uD,{size:16,color:`currentColor`})}),(0,f.jsx)(`button`,{onClick:()=>_(e=>!e),style:{width:`24px`,height:`24px`,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)`,padding:0,flexShrink:0},children:(0,f.jsx)(vD,{size:16,color:`currentColor`})})]}),g&&(0,f.jsxs)(`div`,{style:{position:`absolute`,bottom:0,right:0,width:`230px`,zIndex:9999,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,animation:`fe-orb-fade-in 0.18s ease`,padding:`12px 12px 40px`},children:[(0,f.jsxs)(`button`,{onClick:()=>{_(!1),ne.current=`chat`,pe(t)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(yD,{}),`Enter Chat Mode`]}),(0,f.jsxs)(`button`,{onClick:()=>{_(!1),ne.current=`minimized`,pe(n)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`#E30C12`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(227,12,18,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(bD,{}),`End Conversation`]}),(0,f.jsx)(`button`,{onClick:()=>_(!1),style:{position:`absolute`,bottom:`8px`,right:`8px`,width:`24px`,height:`24px`,borderRadius:`50%`,background:`rgba(255,255,255,0.15)`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.25)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.15)`},children:(0,f.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,f.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]})})]})]})}function Ck({orbColors:e}){return(0,f.jsx)(`div`,{style:{flexShrink:0,width:`36px`,height:`36px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,f.jsx)(yk,{size:36,orbColors:e})})}var wk=()=>(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 Tk({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:ne,onRemoveSelectedFile:re,attachmentError:C,isUploadingAttachment:ie,requiresEmail:ae,emailInput:oe,setEmailInput:se,emailError:ce,emailCaptureSuccess:le,replyContext:ue,setReplyContext:de,webRTCError:fe,micError:pe,setMicError:me,dismissCallError:he,activeCallId:ge,isCallMuted:_e,toggleCallMute:ve,endWebRTCCall:ye,formatCallDuration:be,callDurationSeconds:xe,isCallMinimized:Se,onExpand:Ce,onCollapse:we,onStartVoice:Te,onNewChat:Ee,showPoweredBy:De,getVisitorChatHistory:Oe,resumeChat:ke,isSessionRestoring:Ae,isClosing:je}){let Me=c.length>0,Ne=x||S||b,Pe=!!ge,[Fe,Ie]=(0,d.useState)(!1),[Le,Re]=(0,d.useState)(!1),[ze,Be]=(0,d.useState)([]),[Ve,He]=(0,d.useState)(!1),Ue=(0,d.useRef)(null),We=async()=>{Ie(!1),Re(!0),He(!0);try{let e=await Oe();e?.data&&Be(e.data)}catch(e){console.error(e)}finally{He(!1)}},Ge=async e=>{Re(!1),ke?.(e.chatId)};return(0,d.useEffect)(()=>{if(!Fe)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;Ue.current&&!Ue.current.contains(t)&&Ie(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[Fe]),(0,f.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,left:`8px`,right:`8px`,bottom:0,width:`calc(100% - 16px)`,height:`90dvh`,background:r,borderRadius:`16px 16px 0 0`,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:je?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.28s cubic-bezier(0.16,1,0.3,1)`}:{"--flowengage-primary":n,"--flowengage-accent":n,width:`min(350px, 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:je?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`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 10px 14px`,background:`transparent`,flexShrink:0,position:`relative`,zIndex:30},children:[(0,f.jsx)(`div`,{style:{display:`flex`,gap:`8px`,alignItems:`center`},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)(gk,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,f.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,f.jsx)(_k,{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:Ue,children:[(0,f.jsx)(`button`,{type:`button`,onClick:()=>Ie(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`})]})}),Fe&&(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:()=>{Ie(!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:()=>{Ie(!1),Ee?.()},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 5H5a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-7`}),(0,f.jsx)(`path`,{d:`M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z`})]}),`Start new chat`]}),Oe&&(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:We,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:`M12 8v4l3 3M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z`})}),`Chat history`]})]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{Ie(!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)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,f.jsx)(`line`,{x1:`15`,y1:`9`,x2:`9`,y2:`15`}),(0,f.jsx)(`line`,{x1:`9`,y1:`9`,x2:`15`,y2:`15`})]}),`Close conversation`]})]})]})]}),(0,f.jsx)(VD,{webRTCError:fe,micError:pe,setMicError:me,dismissCallError:he,isRateLimited:S,rateLimitMessage:ee}),Se&&(0,f.jsx)(iO,{agentName:m,agentHeadshot:h,fallbackAgentName:g,callDurationSeconds:xe,isCallMuted:_e,formatCallDuration:be,toggleCallMute:ve,endWebRTCCall:ye,onExpand:Ce,primaryColor:n}),(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`,position:`relative`},children:[Le?(0,f.jsxs)(`div`,{style:{position:`absolute`,inset:0,background:`white`,zIndex:20,display:`flex`,flexDirection:`column`,animation:`fe-orb-fade-in 0.2s ease`},children:[(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,padding:`16px`,borderBottom:`1px solid #f3f4f6`,flexShrink:0},children:(0,f.jsxs)(`button`,{onClick:()=>Re(!1),style:{background:`none`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,color:`#6b7280`},children:[(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`15 18 9 12 15 6`})}),(0,f.jsx)(`span`,{style:{marginLeft:`8px`,fontWeight:500,fontSize:`15px`},children:`Return to Chat`})]})}),(0,f.jsx)(`div`,{style:{flex:1,overflowY:`auto`,position:`relative`},children:Ve?(0,f.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#6b7280`,fontSize:`14px`},children:`Loading past conversations...`}):ze.length>0?(0,f.jsx)(`div`,{children:ze.map(e=>(0,f.jsxs)(`div`,{onClick:()=>Ge(e),style:{padding:`16px 20px`,borderBottom:`1px solid #f3f4f6`,cursor:`pointer`,transition:`background 0.15s ease`},onMouseEnter:e=>e.currentTarget.style.background=`#f9fafb`,onMouseLeave:e=>e.currentTarget.style.background=`white`,children:[(0,f.jsxs)(`div`,{style:{fontSize:`12px`,color:`#6b7280`,marginBottom:`6px`,fontWeight:500},children:[new Date(e.createdAt).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),` at `,new Date(e.createdAt).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})]}),(0,f.jsx)(`div`,{style:{fontSize:`14.5px`,color:`#111827`,opacity:.9,overflow:`hidden`,textOverflow:`ellipsis`,display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,lineHeight:1.4},children:e.message||`Conversation`})]},e.chatId))}):(0,f.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#9ca3af`,fontSize:`14px`},children:`No previous chats found.`})})]}):null,Me?(0,f.jsx)(zD,{chatHistory:c,isAiTyping:l,isLoading:x,isAgentTyping:u,setReplyContext:de,TypingDots:wk,primaryColor:n,agentHeadshot:h,agentDisplayName:m||g,botAvatarNode:(0,f.jsx)(Ck,{orbColors:t})}):Ae?(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`16px`},children:[(0,f.jsx)(`div`,{style:{width:`28px`,height:`28px`,border:`3px solid #f3f4f6`,borderTop:`3px solid ${n}`,borderRadius:`50%`,animation:`spin 1s linear infinite`},children:(0,f.jsx)(`style`,{children:`@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }`})}),(0,f.jsx)(`div`,{style:{color:`#6b7280`,fontSize:`14px`,fontWeight:500,animation:`fe-orb-fade-in 1s infinite alternate`},children:`Loading chat...`})]}):(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)(yk,{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))})]})]}),le&&(0,f.jsxs)(`div`,{style:{margin:`0 16px 8px`,padding:`9px 14px`,borderRadius:`12px`,background:`#ecfdf5`,border:`1px solid #6ee7b7`,display:`flex`,alignItems:`center`,gap:`8px`,animation:`fe-orb-fade-in 0.2s ease`,flexShrink:0},children:[(0,f.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,stroke:`#10b981`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:(0,f.jsx)(`polyline`,{points:`20 6 9 17 4 12`})}),(0,f.jsx)(`span`,{style:{fontSize:`13px`,fontWeight:500,color:`#065f46`},children:`Email saved — we'll be in touch!`})]}),(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)(BD,{input:_,setInput:v,onSubmit:y,isConversationEnded:b,callUiActive:Pe,handleToggleVoice:Te,showVoiceToggle:p===`agent`,activeScreen:p,inputDisabled:Ne,replyContext:ue,clearReplyContext:()=>de(null),onFileSelect:ne,selectedFile:te,onRemoveSelectedFile:re,attachmentError:C,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:De&&(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 Ek(){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,chatId:ne,historyRef:re,onMessageSync:ae,sendMessage:oe,uploadChatFile:se,openWidget:ce,captureVisitorEmail:le,setVoiceMode:ue,endConversation:de,startNewChat:fe,acceptCall:pe,rejectCall:me,endWebRTCCall:he,toggleCallMute:ge,dismissCallError:_e,startTyping:ve,stopTyping:ye,updateTypingDraft:be,getVisitorChatHistory:xe,resumeChat:we,isSessionRestoring:Te,openToChatCounter:De,voiceEndCounter:Oe}=kn();(0,d.useEffect)(()=>{try{ir()}catch{}},[]),(0,d.useEffect)(()=>{De&&w!==`text_chat`&&w!==`call_screen`&&(ue?.(!1),T(`text_chat`))},[De]);let Ae=t?.widgetSettings||{},je=n?.widgetSettings||{},Me={...Ae.branding||{},...je.branding||{}},Ne={...Ae.theme||{},...je.theme||{}},Pe={...Ae.features||{},...je.features||{}},Fe=Pe.voice!==!1,Ie=Array.isArray(Ne.orbColors)&&Ne.orbColors.length>0?Ne.orbColors:null,Le=Ne.buttonColor||Ne.primaryColor||Ie?.[0]||`#3B82F6`,Re={small:50,medium:64,large:80},ze=Re[Ne.orbSize]||Re.small,Be=Ne.position||`bottom-right`,Ve=Me.fallbackAgentName||`Agent`,He=pk(Ie??Ne.chatBgColors),Ue=Me.logo||Me.logoUrl||null,We=te||`en`,Ge=Ae.recommendations?.[We]||[],Ke=(je.recommendations?.[We]??Ge).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),qe=Array.isArray(Me.quickChatOptions)&&Me.quickChatOptions.length>0?Me.quickChatOptions:Ke,Je=Me.hideWatermark===!0?!1:Me.showPoweredBy!==!1,Ye=Me.chatbotEnabled!==!1&&Ne.chatbotEnabled!==!1,Xe=Ae.greetings?.[te]||je.greetings?.[te]||Me.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,Ze={entryPrompt:Me.entryPrompt||`Do you want to explore in a new way?`,yesLabel:Me.yesLabel||`Yes`,laterLabel:Me.laterLabel||`Later`,connectionTitle:Me.connectionTitle||`How would you like to connect?`,voiceLabel:Me.voiceLabel||`Voice`,textLabel:Me.textLabel||`Text`,chatTitle:Me.headerName||`Chat with FlowEngage`,introGreeting:Xe,inputPlaceholder:Me.inputPlaceholder||`Type your message`,analysingLabel:Me.analysingLabel||`analysing...`},Qe=je.elevenLabsAgentId||t?.elevenLabsAgentId||null,$e=t?.siteId||n?.siteId||null,et=t?.apiBaseUrl||``,tt=(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]),nt=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,rt=r.some(e=>e.sender===`user`),it=(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]),at=!l&&rt&&it,ot=!!(je._dashboardLivePreview||Ae._dashboardLivePreview),[w,T]=(0,d.useState)(()=>ot?`text_chat`:`entry_prompt`),[st,ct]=(0,d.useState)(``),[E,lt]=(0,d.useState)(null),[ut,dt]=(0,d.useState)(l||``),[ft,pt]=(0,d.useState)(``),[mt,ht]=(0,d.useState)(!1),[gt,_t]=(0,d.useState)(0),[vt,yt]=(0,d.useState)(null),[bt,xt]=(0,d.useState)(null),[St,Ct]=(0,d.useState)(``),[wt,Tt]=(0,d.useState)(!1),[Et,Dt]=(0,d.useState)(!1),[Ot,kt]=(0,d.useState)(!1),At=(0,d.useRef)(null),jt=(0,d.useRef)(!1);(0,d.useLayoutEffect)(()=>{if(e!==`ready`||jt.current)return;if(jt.current=!0,!Fe){T(`minimized_orb`);return}let t=!1;try{t=gr().shouldResumeVoice}catch{}let n=Ee(),r=$e?Se($e):null,i=n||!!r?.transcript;if(t){ce?.({notifyChatInitiated:!0}),ue?.(!0),T(`voice_mode`);return}if(ke()){ce?.({notifyChatInitiated:!1}),T(`text_chat`);return}if($e)try{Ce($e)}catch{}if(i){T(`minimized_orb`);return}if(C($e)){T(`minimized_orb`);return}},[e,r]);let[Mt,Nt]=(0,d.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,d.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>Nt(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,d.useEffect)(()=>{dt(l||``),l&&pt(``)},[l]);let Pt=(0,d.useCallback)(()=>{xt(null),Ct(``)},[]),Ft=(0,d.useCallback)(e=>{let t=PD(e);if(t){xt(null),Ct(t);return}xt(e),Ct(``)},[]);(0,d.useEffect)(()=>{if(!x||b!==`connected`){_t(0);return}let e=()=>{let e=new Date(x).getTime();isNaN(e)||_t(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[x,b]);let It=(0,d.useCallback)(()=>{T(`call_screen`),Dt(!1)},[]),Lt=(0,d.useCallback)(()=>{T(`text_chat`),Dt(!0)},[]);(0,d.useEffect)(()=>{let e=v?.callId||y||null;if(!e){At.current=null;return}if(v?.callId||b===`connecting`||b===`connected`){if(w===`minimized_orb`&&Et&&y&&!v?.callId){At.current=e;return}!(!i||w===`minimized_orb`||w===`voice_mode`)&&At.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:w,hasIncomingCall:!!v?.callId,activeCallId:y,callConnectionState:b}),At.current=e,w===`voice_mode`&&ue?.(!1),ce?.(),It())}},[y,b,It,v?.callId,i,ce,ue,w]),(0,d.useEffect)(()=>{!v&&!y&&w===`call_screen`&&T(`text_chat`)},[v,y,w]),(0,d.useEffect)(()=>{!y&&Et&&Dt(!1)},[y,Et]),(0,d.useEffect)(()=>{if(!o||_){be?.(``),ye?.();return}if(!st.trim()||bt){be?.(``);let e=window.setTimeout(()=>ye?.(),100);return()=>window.clearTimeout(e)}ve?.();let e=window.setTimeout(()=>be?.(st),120),t=window.setTimeout(()=>ye?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[st,bt,o,_,ve,ye,be]);let Rt=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,zt=async e=>{if(e.preventDefault(),_)return;if(at){let e=ut.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){pt(`Please enter a valid email so we can continue helping you.`);return}await le(e),pt(``),ht(!0),setTimeout(()=>ht(!1),3e3);return}let t=Rt(E);if(!st.trim()&&!bt)return;if(bt){try{Tt(!0),Ct(``);let e=await se(bt),n=e?.data||e,r=st.trim()||`Shared file: ${ID(bt)}`;ct(``),lt(null),Pt(),await oe(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||bt.name,fileType:n?.fileType||bt.type,fileSize:n?.fileSize||bt.size}})}catch(e){Ct(e?.message||`Failed to upload the selected file.`)}finally{Tt(!1)}return}let n=st.trim();ct(``),lt(null),await oe(n,``,t)},Bt=(0,d.useCallback)(()=>{r.length!==0&&fe?.()},[r.length,fe]),Vt=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},Ht=(0,d.useCallback)(async e=>{if(_||m)return;let t=e.message||e.label||e.text||``;t.trim()&&await oe(t.trim(),``)},[_,m,oe]),Ut=Mt&&w===`entry_prompt`?{inset:0}:Mt&&w===`text_chat`?{left:0,right:0,bottom:0}:Mt&&w===`call_screen`?{left:0,right:0,bottom:0,height:`90dvh`,overflow:`hidden`,borderRadius:`16px 16px 0 0`}:Mt&&w===`connection_modal`?{left:`28px`,right:`12px`,bottom:`12px`}:w===`call_screen`?{width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,borderRadius:`22px`,overflow:`hidden`,...Be===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`}}:Be===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},Wt=(0,d.useCallback)(()=>{w!==`minimized_orb`&&(kt(!0),setTimeout(()=>{T(`minimized_orb`),kt(!1),y&&Dt(!0)},280))},[y,w]),Gt=()=>T(`connection_modal`),Kt=()=>{try{let e=window.AudioContext||window.webkitAudioContext;if(e){let t=new e;t.resume().catch(()=>{}),setTimeout(()=>t.close().catch(()=>{}),3e3)}}catch{}ce({notifyChatInitiated:!0}),ue?.(!0),T(`voice_mode`)},qt=()=>{ce({notifyChatInitiated:!0}),ue?.(!1),T(`text_chat`)},Jt=()=>{ue?.(!1),Wt()};return e!==`ready`||!Ye||Pe.chat===!1?null:(0,f.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...Ut},onWheel:e=>e.stopPropagation(),onTouchMove:e=>e.stopPropagation(),children:[w===`entry_prompt`&&(0,f.jsx)(bk,{copy:Ze,orbColors:Ie,primaryColor:Le,onYes:()=>{ie($e),Kt()},onLater:()=>{ie($e),Wt()},isMobile:Mt,isClosing:Ot}),w===`minimized_orb`&&(0,f.jsxs)(_m.div,{layoutId:`fe-main-orb`,initial:{scale:.4,opacity:0},animate:{scale:1,opacity:1},transition:{type:`spring`,stiffness:280,damping:18},style:{transformOrigin:`bottom right`,display:`inline-flex`,flexDirection:`column`,alignItems:Be===`bottom-left`?`flex-start`:`flex-end`,gap:`10px`},children:[y&&(0,f.jsxs)(`button`,{type:`button`,onClick:It,style:{maxWidth:Mt?`220px`:`240px`,padding:`10px 14px`,borderRadius:`18px`,border:`1px solid rgba(255,255,255,0.7)`,background:`rgba(255,255,255,0.94)`,backdropFilter:`blur(18px)`,WebkitBackdropFilter:`blur(18px)`,boxShadow:`0 10px 26px rgba(15,23,42,0.14)`,display:`flex`,alignItems:`center`,gap:`10px`,cursor:`pointer`,textAlign:`left`},children:[(0,f.jsx)(`span`,{style:{width:`9px`,height:`9px`,borderRadius:`50%`,background:`#22c55e`,boxShadow:`0 0 0 4px rgba(34,197,94,0.16)`,flexShrink:0}}),(0,f.jsxs)(`span`,{style:{minWidth:0},children:[(0,f.jsx)(`span`,{style:{display:`block`,fontSize:`12px`,fontWeight:700,color:`#111827`,lineHeight:1.2},children:b===`connected`?`Call in progress`:`Call is active`}),(0,f.jsx)(`span`,{style:{display:`block`,fontSize:`11px`,color:`#6b7280`,lineHeight:1.3,marginTop:`2px`,whiteSpace:`nowrap`},children:b===`connected`?`${Vt(gt)} with ${tt}`:`Tap to return to ${tt}`})]})]}),(0,f.jsx)(yk,{size:ze,orbColors:Ie,onClick:y?It:Fe?Gt:qt})]}),w===`connection_modal`&&(0,f.jsx)(xk,{copy:Ze,orbColors:Ie,primaryColor:Le,onVoice:Kt,onText:qt,onClose:Wt,isMobile:Mt,isClosing:Ot}),w===`voice_mode`&&(0,f.jsx)(Sk,{orbColors:Ie,onEnterChat:qt,onEndChat:Jt,agentId:Qe,siteId:$e,apiBaseUrl:et,chatId:ne,historyRef:re,onMessageSync:ae,voiceEndCounter:Oe},`voice`),w===`call_screen`&&(0,f.jsx)(rO,{incomingCall:v,activeCallId:y,callConnectionState:b,callDurationSeconds:gt,isCallMuted:S,agentName:tt,agentHeadshot:nt,fallbackAgentName:Ve,acceptCall:pe,rejectCall:me,endWebRTCCall:he,toggleCallMute:ge,formatCallDuration:Vt,onMinimize:Lt,primaryColor:Le,orbColors:Ie,chatHistory:r}),w===`text_chat`&&(0,f.jsx)(Tk,{isClosing:Ot,copy:Ze,orbColors:Ie,primaryColor:Le,chatBgGradient:He,logo:Ue,quickChatOptions:qe,onQuickChatSelect:Ht,isMobile:Mt,chatHistory:r,isAiTyping:p,isAgentTyping:u,activeScreen:a,agentName:tt,agentHeadshot:nt,fallbackAgentName:Ve,input:st,setInput:ct,onSubmit:zt,isConversationEnded:_,isLoading:m,isRateLimited:h,rateLimitMessage:g,selectedFile:bt,onFileSelect:Ft,onRemoveSelectedFile:Pt,attachmentError:St,isUploadingAttachment:wt,requiresEmail:at,emailInput:ut,setEmailInput:dt,emailError:ft,emailCaptureSuccess:mt,replyContext:E,setReplyContext:lt,webRTCError:ee,micError:vt,setMicError:yt,dismissCallError:_e,activeCallId:y,isCallMuted:S,toggleCallMute:ge,endWebRTCCall:he,formatCallDuration:Vt,callDurationSeconds:gt,onCollapse:Wt,onStartVoice:Kt,onNewChat:Bt,onMinimize:Lt,onExpand:It,isCallMinimized:!!y,showPoweredBy:Je,getVisitorChatHistory:xe,resumeChat:we,isSessionRestoring:Te}),(0,f.jsx)(`style`,{children:`
636
636
  /* Force any SVG (or img) inside LogoSlot to fill the container height
637
637
  regardless of whether the component forwards its style prop. */
@@ -2118,11 +2118,16 @@ function er() {
2118
2118
  if (window.ng?.getComponent || document.querySelector("[ng-version]")) return "angular";
2119
2119
  if (window.__sveltekit_data || document.querySelector("[data-sveltekit-hydrate]")) return "sveltekit";
2120
2120
  if (document.querySelector("[data-astro-transition]")) return "astro";
2121
+ if (window.__vite_plugin_react_preamble_installed__) return "vite-react-spa";
2121
2122
  let e = Array.from(document.body.children).filter((e) => {
2122
2123
  let t = e.tagName?.toUpperCase();
2123
2124
  return !(t === "SCRIPT" || t === "NOSCRIPT" || t === "LINK" || t === "STYLE" || e.id === "flowengage-root");
2124
2125
  });
2125
- return e.length === 1 && e[0].id && (e[0].querySelector("[data-reactroot]") || e[0]._reactRootContainer || e[0].__vue_app__) ? "generic-spa" : null;
2126
+ if (e.length === 1) {
2127
+ let t = e[0], n = !!t.querySelector("[data-reactroot]") || !!t._reactRootContainer, r = Object.keys(t).some((e) => e.startsWith("__reactFiber$") || e.startsWith("__reactContainer$"));
2128
+ if (n || r || t.__vue_app__) return "generic-spa";
2129
+ }
2130
+ return null;
2126
2131
  }
2127
2132
  var tr = "data-fe-swap-css";
2128
2133
  function nr() {
@@ -29382,7 +29387,7 @@ function Ck(e) {
29382
29387
  e = new URL(a, typeof window < "u" ? window.location.href : "").href;
29383
29388
  } catch {}
29384
29389
  t && typeof window < "u" && Ve(t, window.location.href, e), Cr(e), $("flowengage_navigate → real navigation", a);
29385
- let n = typeof window < "u" && !!(window.next?.router || window.__NEXT_ROUTER__ || window.__remixRouter || window.__staticRouterHydrationData || window.___gatsby || window.___navigate || window.__VUE_ROUTER__ || window.__NUXT__ || window.$nuxt || window.ng?.getComponent || typeof document < "u" && document.querySelector("[ng-version]") || window.__sveltekit_data || typeof document < "u" && document.querySelector("[data-sveltekit-hydrate]"));
29390
+ let n = typeof window < "u" && !!er();
29386
29391
  if (typeof window < "u" && window.__fe_triggerVoiceNavHooks && window.__fe_triggerVoiceNavHooks(), n && qn(3e3), Er(a, { voiceActive: !0 }).catch(() => {}), n) try {
29387
29392
  let e = new URL(a, window.location.origin).pathname, t = Date.now() + 2e3;
29388
29393
  for (; Date.now() < t && !(typeof window < "u" && window.location.pathname === e);) await new Promise((e) => setTimeout(e, 80));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flowengage/react-chatbot",
3
- "version": "6.0.16",
3
+ "version": "6.0.17",
4
4
  "description": "Embeddable AI chat widget for React — powered by FlowEngage. Drop it in with a single siteId.",
5
5
  "keywords": [
6
6
  "chatbot",