@flowengage/react-chatbot 8.0.20-test → 8.0.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/flowengage-embed.js +200 -196
- package/dist/flowengage-react-chatbot.cjs +196 -192
- package/dist/flowengage-react-chatbot.mjs +26164 -26332
- package/package.json +1 -1
|
@@ -1,5 +1,29 @@
|
|
|
1
|
-
"use client";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(e&&(t=e(e=0)),t),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,a)=>(a=n==null?{}:e(i(n)),c(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n)),u=e=>a.call(e,`module.exports`)?e[`module.exports`]:c(t({},`__esModule`,{value:!0}),e);let d=require(`react`);d=l(d);let f=require(`react/jsx-runtime`);var p=e=>{if(!e||typeof e!=`object`)throw Error(`FlowEngage config is required`);if(!e.siteId||typeof e.siteId!=`string`)throw Error(`[FlowEngage] config.siteId is required. Pass it as <FlowEngageProvider siteId="your-site-id" /> or config={{ siteId: 'your-site-id' }}.`);let t=(e.apiBaseUrl||`https://be-flowengage-dev.oslabs.app`).replace(/\/+$/,``);return{siteId:e.siteId.trim(),apiBaseUrl:t}},m=(e,t)=>{let n=Number.parseInt(String(e??``),10);return Number.isFinite(n)&&n>0?n:t},h=m(void 0,1e4),g=m(void 0,15e3),_={chatId:`flowengage.chatId`,isOpen:`flowengage.isOpen`,activeScreen:`flowengage.activeScreen`,isHumanHandled:`flowengage.isHumanHandled`,agentName:`flowengage.agentName`,agentHeadshot:`flowengage.agentHeadshot`,visitorEmail:`flowengage.visitorEmail`},v=6e4,y=480*60,b=3e4,x=typeof window<`u`,S=e=>e?`flowengage.visitorEmail.${e}`:null,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,w=(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{}},Me=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}},Ne=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},Pe=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}},Fe=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),Ne(await Pe(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)}))},Ie=async({apiBaseUrl:e,siteId:t})=>{let n=typeof window<`u`?window.location.origin:`http://localhost`;return(await Ne(await Pe(`${e}/api/widget/chatbot-loader?${new URLSearchParams({siteId:t,origin:n}).toString()}`,{method:`GET`}))).data},Le=({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={})=>Ne(await Pe(`${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 Ne(await Pe(`${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 Ne(await Pe(`${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)}}},Re=Object.create(null);Re.open=`0`,Re.close=`1`,Re.ping=`2`,Re.pong=`3`,Re.message=`4`,Re.upgrade=`5`,Re.noop=`6`;var ze=Object.create(null);Object.keys(Re).forEach(e=>{ze[Re[e]]=e});var Be={type:`error`,data:`parser error`},Ve=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,He=typeof ArrayBuffer==`function`,Ue=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,We=({type:e,data:t},n,r)=>Ve&&t instanceof Blob?n?r(t):T(t,r):He&&(t instanceof ArrayBuffer||Ue(t))?n?r(t):T(new Blob([t]),r):r(Re[e]+(t||``)),T=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function Ge(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var Ke;function qe(e,t){if(Ve&&e.data instanceof Blob)return e.data.arrayBuffer().then(Ge).then(t);if(He&&(e.data instanceof ArrayBuffer||Ue(e.data)))return t(Ge(e.data));We(e,!1,e=>{Ke||=new TextEncoder,t(Ke.encode(e))})}var Je=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Ye=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)Ye[Je.charCodeAt(e)]=e;var Xe=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=Ye[e.charCodeAt(r)],o=Ye[e.charCodeAt(r+1)],s=Ye[e.charCodeAt(r+2)],c=Ye[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},Ze=typeof ArrayBuffer==`function`,Qe=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:et(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:$e(e.substring(1),t)}:ze[n]?e.length>1?{type:ze[n],data:e.substring(1)}:{type:ze[n]}:Be},$e=(e,t)=>Ze?et(Xe(e),t):{base64:!0,data:e},et=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},tt=``,nt=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{We(e,!1,e=>{r[a]=e,++i===n&&t(r.join(tt))})})},rt=(e,t)=>{let n=e.split(tt),r=[];for(let e=0;e<n.length;e++){let i=Qe(n[e],t);if(r.push(i),i.type===`error`)break}return r};function it(){return new TransformStream({transform(e,t){qe(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 E;function D(e){return e.reduce((e,t)=>e+t.length,0)}function at(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 ot(e,t){E||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(D(n)<1)break;let e=at(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(D(n)<2)break;let e=at(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(D(n)<8)break;let e=at(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(Be);break}i=a*2**32+t.getUint32(4),r=3}else{if(D(n)<i)break;let e=at(n,i);s.enqueue(Qe(a?e:E.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(Be);break}}}})}function O(e){if(e)return st(e)}function st(e){for(var t in O.prototype)e[t]=O.prototype[t];return e}O.prototype.on=O.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},O.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},O.prototype.off=O.prototype.removeListener=O.prototype.removeAllListeners=O.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},O.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},O.prototype.emitReserved=O.prototype.emit,O.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},O.prototype.hasListeners=function(e){return!!this.listeners(e).length};var ct=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),lt=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),k=`arraybuffer`;function ut(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var dt=lt.setTimeout,ft=lt.clearTimeout;function pt(e,t){t.useNativeTimers?(e.setTimeoutFn=dt.bind(lt),e.clearTimeoutFn=ft.bind(lt)):(e.setTimeoutFn=lt.setTimeout.bind(lt),e.clearTimeoutFn=lt.clearTimeout.bind(lt))}var mt=1.33;function ht(e){return typeof e==`string`?gt(e):Math.ceil((e.byteLength||e.size)*mt)}function gt(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 _t(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function vt(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function yt(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 bt=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},xt=class extends O{constructor(e){super(),this.writable=!1,pt(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 bt(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=Qe(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=vt(e);return t.length?`?`+t:``}},St=class extends xt{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){rt(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,nt(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]=_t()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},Ct=!1;try{Ct=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var wt=Ct;function Tt(){}var Et=class extends St{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}},Dt=class e extends O{constructor(e,t,n){super(),this.createRequest=e,pt(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=ut(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=Tt,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(Dt.requestsCount=0,Dt.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,Ot);else if(typeof addEventListener==`function`){let e=`onpagehide`in lt?`pagehide`:`unload`;addEventListener(e,Ot,!1)}}function Ot(){for(let e in Dt.requests)Dt.requests.hasOwnProperty(e)&&Dt.requests[e].abort()}var kt=(function(){let e=jt({xdomain:!1});return e&&e.responseType!==null})(),At=class extends Et{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=kt&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Dt(jt,this.uri(),e)}};function jt(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||wt))return new XMLHttpRequest}catch{}if(!t)try{return new lt[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var Mt=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,Nt=class extends xt{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=Mt?{}:ut(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;We(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&ct(()=>{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]=_t()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},Pt=lt.WebSocket||lt.MozWebSocket,Ft={websocket:class extends Nt{createSocket(e,t,n){return Mt?new Pt(e,t,n):t?new Pt(e,t):new Pt(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends xt{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=ot(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=it();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&&ct(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:At},It=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Lt=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function Rt(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=It.exec(e||``),a={},o=14;for(;o--;)a[Lt[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=zt(a,a.path),a.queryKey=Bt(a,a.query),a}function zt(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 Bt(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var Vt=typeof addEventListener==`function`&&typeof removeEventListener==`function`,Ht=[];Vt&&addEventListener(`offline`,()=>{Ht.forEach(e=>e())},!1);var Ut=class e extends O{constructor(e,t){if(super(),this.binaryType=k,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=Rt(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=Rt(t.host).host);pt(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=yt(this.opts.query)),Vt&&(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`})},Ht.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+=ht(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,ct(()=>{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(),Vt&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=Ht.indexOf(this._offlineEventListener);e!==-1&&Ht.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};Ut.protocol=4;var Wt=class extends Ut{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;Ut.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;Ut.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}},Gt=class extends Wt{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=>Ft[e]).filter(e=>!!e)),super(e,n)}};Gt.protocol;function Kt(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=Rt(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 qt=typeof ArrayBuffer==`function`,Jt=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,Yt=Object.prototype.toString,Xt=typeof Blob==`function`||typeof Blob<`u`&&Yt.call(Blob)===`[object BlobConstructor]`,Zt=typeof File==`function`||typeof File<`u`&&Yt.call(File)===`[object FileConstructor]`;function Qt(e){return qt&&(e instanceof ArrayBuffer||Jt(e))||Xt&&e instanceof Blob||Zt&&e instanceof File}function $t(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if($t(e[t]))return!0;return!1}if(Qt(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return $t(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&$t(e[t]))return!0;return!1}function en(e){let t=[],n=e.data,r=e;return r.data=tn(n,t),r.attachments=t.length,{packet:r,buffers:t}}function tn(e,t){if(!e)return e;if(Qt(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]=tn(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]=tn(e[r],t));return n}return e}function nn(e,t){return e.data=rn(e.data,t),delete e.attachments,e}function rn(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]=rn(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=rn(e[n],t));return e}var an=s({Decoder:()=>cn,Encoder:()=>sn,PacketType:()=>A,isPacketValid:()=>hn,protocol:()=>5}),on=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],A;(function(e){e[e.CONNECT=0]=`CONNECT`,e[e.DISCONNECT=1]=`DISCONNECT`,e[e.EVENT=2]=`EVENT`,e[e.ACK=3]=`ACK`,e[e.CONNECT_ERROR=4]=`CONNECT_ERROR`,e[e.BINARY_EVENT=5]=`BINARY_EVENT`,e[e.BINARY_ACK=6]=`BINARY_ACK`})(A||={});var sn=class{constructor(e){this.replacer=e}encode(e){return(e.type===A.EVENT||e.type===A.ACK)&&$t(e)?this.encodeAsBinary({type:e.type===A.EVENT?A.BINARY_EVENT:A.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===A.BINARY_EVENT||e.type===A.BINARY_ACK)&&(t+=e.attachments+`-`),e.nsp&&e.nsp!==`/`&&(t+=e.nsp+`,`),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=en(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},cn=class e extends O{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e==`function`?{reviver:e}:e)}add(e){let t;if(typeof e==`string`){if(this.reconstructor)throw Error(`got plaintext data when reconstructing a packet`);t=this.decodeString(e);let n=t.type===A.BINARY_EVENT;n||t.type===A.BINARY_ACK?(t.type=n?A.EVENT:A.ACK,this.reconstructor=new ln(t),t.attachments===0&&super.emitReserved(`decoded`,t)):super.emitReserved(`decoded`,t)}else if(Qt(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved(`decoded`,t));else throw Error(`got binary data when not reconstructing a packet`);else throw Error(`Unknown type: `+e)}decodeString(t){let n=0,r={type:Number(t.charAt(0))};if(A[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===A.BINARY_EVENT||r.type===A.BINARY_ACK){let e=n+1;for(;t.charAt(++n)!==`-`&&n!=t.length;);let i=t.substring(e,n);if(i!=Number(i)||t.charAt(n)!==`-`)throw Error(`Illegal attachments`);let a=Number(i);if(!dn(a)||a<0)throw Error(`Illegal attachments`);if(a>this.opts.maxAttachments)throw Error(`too many attachments`);r.attachments=a}if(t.charAt(n+1)===`/`){let e=n+1;for(;++n&&!(t.charAt(n)===`,`||n===t.length););r.nsp=t.substring(e,n)}else r.nsp=`/`;let i=t.charAt(n+1);if(i!==``&&Number(i)==i){let e=n+1;for(;++n;){let e=t.charAt(n);if(e==null||Number(e)!=e){--n;break}if(n===t.length)break}r.id=Number(t.substring(e,n+1))}if(t.charAt(++n)){let i=this.tryParse(t.substr(n));if(e.isPayloadValid(r.type,i))r.data=i;else throw Error(`invalid payload`)}return r}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case A.CONNECT:return pn(t);case A.DISCONNECT:return t===void 0;case A.CONNECT_ERROR:return typeof t==`string`||pn(t);case A.EVENT:case A.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&on.indexOf(t[0])===-1);case A.ACK:case A.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},ln=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=nn(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function un(e){return typeof e==`string`}var dn=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function fn(e){return e===void 0||dn(e)}function pn(e){return Object.prototype.toString.call(e)===`[object Object]`}function mn(e,t){switch(e){case A.CONNECT:return t===void 0||pn(t);case A.DISCONNECT:return t===void 0;case A.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&on.indexOf(t[0])===-1);case A.ACK:return Array.isArray(t);case A.CONNECT_ERROR:return typeof t==`string`||pn(t);default:return!1}}function hn(e){return un(e.nsp)&&fn(e.id)&&mn(e.type,e.data)}function gn(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var _n=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),vn=class extends O{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=[gn(e,`open`,this.onopen.bind(this)),gn(e,`packet`,this.onpacket.bind(this)),gn(e,`error`,this.onerror.bind(this)),gn(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(_n.hasOwnProperty(e))throw Error(`"`+e.toString()+`" is a reserved event name`);if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let n={type:A.EVENT,data:t};if(n.options={},n.options.compress=this.flags.compress!==!1,typeof t[t.length-1]==`function`){let e=this.ids++,r=t.pop();this._registerAckCallback(e,r),n.id=e}let r=this.io.engine?.transport?.writable,i=this.connected&&!this.io.engine?._hasPingExpired();return this.flags.volatile&&!r||(i?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){let n=this.flags.timeout??this._opts.ackTimeout;if(n===void 0){this.acks[e]=t;return}let r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,Error(`operation has timed out`))},n),i=(...e)=>{this.io.clearTimeoutFn(r),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,r)=>{let i=(e,t)=>e?r(e):n(t);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]==`function`&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>(this._queue[0],e===null?(this._queue.shift(),t&&t(null,...r)):n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth==`function`?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:A.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved(`connect_error`,e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved(`disconnect`,e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){let t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,Error(`socket has been disconnected`))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case A.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved(`connect_error`,Error(`It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)`));break;case A.EVENT:case A.BINARY_EVENT:this.onevent(e);break;case A.ACK:case A.BINARY_ACK:this.onack(e);break;case A.DISCONNECT:this.ondisconnect();break;case A.CONNECT_ERROR:this.destroy();let t=Error(e.data.message);t.data=e.data.data,this.emitReserved(`connect_error`,t);break}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]==`string`&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...r){n||(n=!0,t.packet({type:A.ACK,id:e,data:r}))}}onack(e){let t=this.acks[e.id];typeof t==`function`&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved(`connect`)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose(`io server disconnect`)}destroy(){this.subs&&=(this.subs.forEach(e=>e()),void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:A.DISCONNECT}),this.destroy(),this.connected&&this.onclose(`io client disconnect`),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let n of t)n.apply(this,e.data)}}};function yn(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}yn.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},yn.prototype.reset=function(){this.attempts=0},yn.prototype.setMin=function(e){this.ms=e},yn.prototype.setMax=function(e){this.max=e},yn.prototype.setJitter=function(e){this.jitter=e};var bn=class extends O{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,pt(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 yn({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||an;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 Gt(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=gn(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=gn(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(gn(e,`ping`,this.onping.bind(this)),gn(e,`data`,this.ondata.bind(this)),gn(e,`error`,this.onerror.bind(this)),gn(e,`close`,this.onclose.bind(this)),gn(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){ct(()=>{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 vn(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)}},xn={};function Sn(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=Kt(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=xn[i]&&a in xn[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new bn(r,t):(xn[i]||(xn[i]=new bn(r,t)),c=xn[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(Sn,{Manager:bn,Socket:vn,io:Sn,connect:Sn});var Cn=({apiBaseUrl:e,userId:t,chatId:n,siteId:r})=>Sn(e,{transports:[`polling`,`websocket`],upgrade:!0,rememberUpgrade:!1,auth:{userId:t,chatId:n,siteId:r},query:{chatId:n,siteId:r}}),wn=({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)}}};function Tn(e,t){return t.forEach(function(t){t&&typeof t!=`string`&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!==`default`&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}var En=Object.defineProperty,Dn=(e,t,n)=>t in e?En(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,On=(e,t,n)=>Dn(e,typeof t==`symbol`?t:t+``,n),kn=class{constructor(){On(this,`_locking`),On(this,`_locks`),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e,t=new Promise(t=>e=()=>{--this._locks,t()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}};function An(e,t){if(!e)throw Error(t)}var jn=34028234663852886e22,Mn=-34028234663852886e22,Nn=4294967295,Pn=2147483647,Fn=-2147483648;function In(e){if(typeof e!=`number`)throw Error(`invalid int 32: `+typeof e);if(!Number.isInteger(e)||e>Pn||e<Fn)throw Error(`invalid int 32: `+e)}function Ln(e){if(typeof e!=`number`)throw Error(`invalid uint 32: `+typeof e);if(!Number.isInteger(e)||e>Nn||e<0)throw Error(`invalid uint 32: `+e)}function Rn(e){if(typeof e!=`number`)throw Error(`invalid float 32: `+typeof e);if(Number.isFinite(e)&&(e>jn||e<Mn))throw Error(`invalid float 32: `+e)}var zn=Symbol(`@bufbuild/protobuf/enum-type`);function Bn(e){let t=e[zn];return An(t,`missing enum type on enum object`),t}function Vn(e,t,n,r){e[zn]=Hn(t,n.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function Hn(e,t,n){let r=Object.create(null),i=Object.create(null),a=[];for(let e of t){let t=Wn(e);a.push(t),r[e.name]=t,i[e.no]=t}return{typeName:e,values:a,findName(e){return r[e]},findNumber(e){return i[e]}}}function Un(e,t,n){let r={};for(let e of t){let t=Wn(e);r[t.localName]=t.no,r[t.no]=t.localName}return Vn(r,e,t),r}function Wn(e){return`localName`in e?e:Object.assign(Object.assign({},e),{localName:e.name})}var Gn=class{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){let n=this.getType().runtime.bin,r=n.makeReadOptions(t);return n.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){let n=this.getType(),r=n.runtime.json,i=r.makeReadOptions(t);return r.readMessage(n,e,i,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`cannot decode ${this.getType().typeName} from JSON: ${e instanceof Error?e.message:String(e)}`)}return this.fromJson(n,t)}toBinary(e){let t=this.getType().runtime.bin,n=t.makeWriteOptions(e),r=n.writerFactory();return t.writeMessage(this,r,n),r.finish()}toJson(e){let t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){let t=this.toJson(e);return JSON.stringify(t,null,e?.prettySpaces??0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}};function Kn(e,t,n,r){let i=r?.localName??t.substring(t.lastIndexOf(`.`)+1),a={[i]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[i];return Object.setPrototypeOf(a.prototype,new Gn),Object.assign(a,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary(e,t){return new a().fromBinary(e,t)},fromJson(e,t){return new a().fromJson(e,t)},fromJsonString(e,t){return new a().fromJsonString(e,t)},equals(t,n){return e.util.equals(a,t,n)}}),a}function qn(){let e=0,t=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(n&15)<<28,t=(n&112)>>4,!(n&128))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(t|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}throw Error(`invalid varint`)}function Jn(e,t,n){for(let r=0;r<28;r+=7){let i=e>>>r,a=!(!(i>>>7)&&t==0),o=(a?i|128:i)&255;if(n.push(o),!a)return}let r=e>>>28&15|(t&7)<<4,i=!!(t>>3);if(n.push((i?r|128:r)&255),i){for(let e=3;e<31;e+=7){let r=t>>>e,i=!!(r>>>7),a=(i?r|128:r)&255;if(n.push(a),!i)return}n.push(t>>>31&1)}}var Yn=4294967296;function Xn(e){let t=e[0]===`-`;t&&(e=e.slice(1));let n=1e6,r=0,i=0;function a(t,a){let o=Number(e.slice(t,a));i*=n,r=r*n+o,r>=Yn&&(i+=r/Yn|0,r%=Yn)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?tr(r,i):er(r,i)}function Zn(e,t){let n=er(e,t),r=n.hi&2147483648;r&&(n=tr(n.lo,n.hi));let i=Qn(n.lo,n.hi);return r?`-`+i:i}function Qn(e,t){if({lo:e,hi:t}=$n(e,t),t<=2097151)return String(Yn*t+e);let n=e&16777215,r=(e>>>24|t<<8)&16777215,i=t>>16&65535,a=n+r*6777216+i*6710656,o=r+i*8147497,s=i*2,c=1e7;return a>=c&&(o+=Math.floor(a/c),a%=c),o>=c&&(s+=Math.floor(o/c),o%=c),s.toString()+nr(o)+nr(a)}function $n(e,t){return{lo:e>>>0,hi:t>>>0}}function er(e,t){return{lo:e|0,hi:t|0}}function tr(e,t){return t=~t,e?e=~e+1:t+=1,er(e,t)}var nr=e=>{let t=String(e);return`0000000`.slice(t.length)+t};function rr(e,t){if(e>=0){for(;e>127;)t.push(e&127|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(e&127|128),e>>=7;t.push(1)}}function ir(){let e=this.buf[this.pos++],t=e&127;if(!(e&128)||(e=this.buf[this.pos++],t|=(e&127)<<7,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<14,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<21,!(e&128)))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(e&15)<<28;for(let t=5;e&128&&t<10;t++)e=this.buf[this.pos++];if(e&128)throw Error(`invalid varint`);return this.assertBounds(),t>>>0}function ar(){let e=new DataView(new ArrayBuffer(8));if(typeof BigInt==`function`&&typeof e.getBigInt64==`function`&&typeof e.getBigUint64==`function`&&typeof e.setBigInt64==`function`&&typeof e.setBigUint64==`function`&&(typeof process!=`object`||typeof process.env!=`object`||process.env.BUF_BIGINT_DISABLE!==`1`)){let t=BigInt(`-9223372036854775808`),n=BigInt(`9223372036854775807`),r=BigInt(`0`),i=BigInt(`18446744073709551615`);return{zero:BigInt(0),supported:!0,parse(e){let r=typeof e==`bigint`?e:BigInt(e);if(r>n||r<t)throw Error(`int64 invalid: ${e}`);return r},uParse(e){let t=typeof e==`bigint`?e:BigInt(e);if(t>i||t<r)throw Error(`uint64 invalid: ${e}`);return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec(t,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)},uDec(t,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0)}}}let t=e=>An(/^-?[0-9]+$/.test(e),`int64 invalid: ${e}`),n=e=>An(/^[0-9]+$/.test(e),`uint64 invalid: ${e}`);return{zero:`0`,supported:!1,parse(e){return typeof e!=`string`&&(e=e.toString()),t(e),e},uParse(e){return typeof e!=`string`&&(e=e.toString()),n(e),e},enc(e){return typeof e!=`string`&&(e=e.toString()),t(e),Xn(e)},uEnc(e){return typeof e!=`string`&&(e=e.toString()),n(e),Xn(e)},dec(e,t){return Zn(e,t)},uDec(e,t){return Qn(e,t)}}}var or=ar(),j;(function(e){e[e.DOUBLE=1]=`DOUBLE`,e[e.FLOAT=2]=`FLOAT`,e[e.INT64=3]=`INT64`,e[e.UINT64=4]=`UINT64`,e[e.INT32=5]=`INT32`,e[e.FIXED64=6]=`FIXED64`,e[e.FIXED32=7]=`FIXED32`,e[e.BOOL=8]=`BOOL`,e[e.STRING=9]=`STRING`,e[e.BYTES=12]=`BYTES`,e[e.UINT32=13]=`UINT32`,e[e.SFIXED32=15]=`SFIXED32`,e[e.SFIXED64=16]=`SFIXED64`,e[e.SINT32=17]=`SINT32`,e[e.SINT64=18]=`SINT64`})(j||={});var sr;(function(e){e[e.BIGINT=0]=`BIGINT`,e[e.STRING=1]=`STRING`})(sr||={});function cr(e,t,n){if(t===n)return!0;if(e==j.BYTES){if(!(t instanceof Uint8Array)||!(n instanceof Uint8Array)||t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}switch(e){case j.UINT64:case j.FIXED64:case j.INT64:case j.SFIXED64:case j.SINT64:return t==n}return!1}function lr(e,t){switch(e){case j.BOOL:return!1;case j.UINT64:case j.FIXED64:case j.INT64:case j.SFIXED64:case j.SINT64:return t==0?or.zero:`0`;case j.DOUBLE:case j.FLOAT:return 0;case j.BYTES:return new Uint8Array;case j.STRING:return``;default:return 0}}function ur(e,t){switch(e){case j.BOOL:return t===!1;case j.STRING:return t===``;case j.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return t==0}}var dr;(function(e){e[e.Varint=0]=`Varint`,e[e.Bit64=1]=`Bit64`,e[e.LengthDelimited=2]=`LengthDelimited`,e[e.StartGroup=3]=`StartGroup`,e[e.EndGroup=4]=`EndGroup`,e[e.Bit32=5]=`Bit32`})(dr||={});var fr=class{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw Error(`invalid state, fork stack empty`);return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Ln(e);e>127;)this.buf.push(e&127|128),e>>>=7;return this.buf.push(e),this}int32(e){return In(e),rr(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){Rn(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){Ln(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){In(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return In(e),e=(e<<1^e>>31)>>>0,rr(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=or.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=or.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=or.enc(e);return Jn(t.lo,t.hi,this.buf),this}sint64(e){let t=or.enc(e),n=t.hi>>31;return Jn(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=or.uEnc(e);return Jn(t.lo,t.hi,this.buf),this}},pr=class{constructor(e,t){this.varint64=qn,this.uint32=ir,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw Error(`illegal tag: field no `+t+` wire type `+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case dr.Varint:for(;this.buf[this.pos++]&128;);break;case dr.Bit64:this.pos+=4;case dr.Bit32:this.pos+=4;break;case dr.LengthDelimited:let n=this.uint32();this.pos+=n;break;case dr.StartGroup:for(;;){let[e,n]=this.tag();if(n===dr.EndGroup){if(t!==void 0&&e!==t)throw Error(`invalid end group tag`);break}this.skip(n,e)}break;default:throw Error(`cant skip wire type `+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw RangeError(`premature EOF`)}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return or.dec(...this.varint64())}uint64(){return or.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,or.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return or.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return or.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}};function mr(e,t,n,r){let i;return{typeName:t,extendee:n,get field(){if(!i){let n=typeof r==`function`?r():r;n.name=t.split(`.`).pop(),n.jsonName=`[${t}]`,i=e.util.newFieldList([n]).list()[0]}return i},runtime:e}}function hr(e){let t=e.field.localName,n=Object.create(null);return n[t]=gr(e),[n,()=>n[t]]}function gr(e){let t=e.field;if(t.repeated)return[];if(t.default!==void 0)return t.default;switch(t.kind){case`enum`:return t.T.values[0].no;case`scalar`:return lr(t.T,t.L);case`message`:let e=t.T,n=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(n):n;case`map`:throw`map fields are not allowed to be extensions`}}function _r(e,t){if(!t.repeated&&(t.kind==`enum`||t.kind==`scalar`)){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter(e=>e.no===t.no)}var vr=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.split(``),yr=[];for(let e=0;e<vr.length;e++)yr[vr[e].charCodeAt(0)]=e;yr[45]=vr.indexOf(`+`),yr[95]=vr.indexOf(`/`);var br={dec(e){let t=e.length*3/4;e[e.length-2]==`=`?t-=2:e[e.length-1]==`=`&&--t;let n=new Uint8Array(t),r=0,i=0,a,o=0;for(let t=0;t<e.length;t++){if(a=yr[e.charCodeAt(t)],a===void 0)switch(e[t]){case`=`:i=0;case`
|
|
2
|
-
`:case`\r`:case` `:case` `:continue;default:throw Error(`invalid base64 string.`)}switch(i){case 0:o=a,i=1;break;case 1:n[r++]=o<<2|(a&48)>>4,o=a,i=2;break;case 2:n[r++]=(o&15)<<4|(a&60)>>2,o=a,i=3;break;case 3:n[r++]=(o&3)<<6|a,i=0;break}}if(i==1)throw Error(`invalid base64 string.`);return n.subarray(0,r)},enc(e){let t=``,n=0,r,i=0;for(let a=0;a<e.length;a++)switch(r=e[a],n){case 0:t+=vr[r>>2],i=(r&3)<<4,n=1;break;case 1:t+=vr[i|r>>4],i=(r&15)<<2,n=2;break;case 2:t+=vr[i|r>>6],t+=vr[r&63],n=0;break}return n&&(t+=vr[i],t+=`=`,n==1&&(t+=`=`)),t}};function xr(e,t,n){wr(t,e);let r=t.runtime.bin.makeReadOptions(n),i=_r(e.getType().runtime.bin.listUnknownFields(e),t.field),[a,o]=hr(t);for(let e of i)t.runtime.bin.readField(a,r.readerFactory(e.data),t.field,e.wireType,r);return o()}function Sr(e,t,n,r){wr(t,e);let i=t.runtime.bin.makeReadOptions(r),a=t.runtime.bin.makeWriteOptions(r);if(Cr(e,t)){let n=e.getType().runtime.bin.listUnknownFields(e).filter(e=>e.no!=t.field.no);e.getType().runtime.bin.discardUnknownFields(e);for(let t of n)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}let o=a.writerFactory(),s=t.field;!s.opt&&!s.repeated&&(s.kind==`enum`||s.kind==`scalar`)&&(s=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(s,n,o,a);let c=i.readerFactory(o.finish());for(;c.pos<c.len;){let[t,n]=c.tag(),r=c.skip(n,t);e.getType().runtime.bin.onUnknownField(e,t,n,r)}}function Cr(e,t){let n=e.getType();return t.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(e).find(e=>e.no==t.field.no)}function wr(e,t){An(e.extendee.typeName==t.getType().typeName,`extension ${e.typeName} can only be applied to message ${e.extendee.typeName}`)}function Tr(e,t){let n=e.localName;if(e.repeated)return t[n].length>0;if(e.oneof)return t[e.oneof.localName].case===n;switch(e.kind){case`enum`:case`scalar`:return e.opt||e.req?t[n]!==void 0:e.kind==`enum`?t[n]!==e.T.values[0].no:!ur(e.T,t[n]);case`message`:return t[n]!==void 0;case`map`:return Object.keys(t[n]).length>0}}function Er(e,t){let n=e.localName,r=!e.opt&&!e.req;if(e.repeated)t[n]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case`map`:t[n]={};break;case`enum`:t[n]=r?e.T.values[0].no:void 0;break;case`scalar`:t[n]=r?lr(e.T,e.L):void 0;break;case`message`:t[n]=void 0;break}}function Dr(e,t){if(typeof e!=`object`||!e||!Object.getOwnPropertyNames(Gn.prototype).every(t=>t in e&&typeof e[t]==`function`))return!1;let n=e.getType();return n===null||typeof n!=`function`||!(`typeName`in n)||typeof n.typeName!=`string`?!1:t===void 0?!0:n.typeName==t.typeName}function Or(e,t){return Dr(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}j.DOUBLE,j.FLOAT,j.INT64,j.UINT64,j.INT32,j.UINT32,j.BOOL,j.STRING,j.BYTES;var kr={ignoreUnknownFields:!1},Ar={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function jr(e){return e?Object.assign(Object.assign({},kr),e):kr}function Mr(e){return e?Object.assign(Object.assign({},Ar),e):Ar}var Nr=Symbol(),Pr=Symbol();function Fr(){return{makeReadOptions:jr,makeWriteOptions:Mr,readMessage(e,t,n,r){if(t==null||Array.isArray(t)||typeof t!=`object`)throw Error(`cannot decode message ${e.typeName} from JSON: ${Ir(t)}`);r??=new e;let i=new Map,a=n.typeRegistry;for(let[o,s]of Object.entries(t)){let t=e.fields.findJsonName(o);if(t){if(t.oneof){if(s===null&&t.kind==`scalar`)continue;let n=i.get(t.oneof);if(n!==void 0)throw Error(`cannot decode message ${e.typeName} from JSON: multiple keys for oneof "${t.oneof.name}" present: "${n}", "${o}"`);i.set(t.oneof,o)}Lr(r,s,t,n,e)}else{let t=!1;if(a?.findExtension&&o.startsWith(`[`)&&o.endsWith(`]`)){let i=a.findExtension(o.substring(1,o.length-1));if(i&&i.extendee.typeName==e.typeName){t=!0;let[e,a]=hr(i);Lr(e,s,i.field,n,i),Sr(r,i,a(),n)}}if(!t&&!n.ignoreUnknownFields)throw Error(`cannot decode message ${e.typeName} from JSON: key "${o}" is unknown`)}}return r},writeMessage(e,t){let n=e.getType(),r={},i;try{for(i of n.fields.byNumber()){if(!Tr(i,e)){if(i.req)throw`required field not set`;if(!t.emitDefaultValues||!Vr(i))continue}let n=i.oneof?e[i.oneof.localName].value:e[i.localName],a=Hr(i,n,t);a!==void 0&&(r[t.useProtoFieldName?i.name:i.jsonName]=a)}let a=t.typeRegistry;if(a?.findExtensionFor)for(let i of n.runtime.bin.listUnknownFields(e)){let o=a.findExtensionFor(n.typeName,i.no);if(o&&Cr(e,o)){let n=xr(e,o,t),i=Hr(o.field,n,t);i!==void 0&&(r[o.field.jsonName]=i)}}}catch(e){let t=i?`cannot encode field ${n.typeName}.${i.name} to JSON`:`cannot encode message ${n.typeName} to JSON`,r=e instanceof Error?e.message:String(e);throw Error(t+(r.length>0?`: ${r}`:``))}return r},readScalar(e,t,n){return zr(e,t,n??sr.BIGINT,!0)},writeScalar(e,t,n){if(t!==void 0&&(n||ur(e,t)))return Wr(e,t)},debug:Ir}}function Ir(e){if(e===null)return`null`;switch(typeof e){case`object`:return Array.isArray(e)?`array`:`object`;case`string`:return e.length>100?`string`:`"${e.split(`"`).join(`\\"`)}"`;default:return String(e)}}function Lr(e,t,n,r,i){let a=n.localName;if(n.repeated){if(An(n.kind!=`map`),t===null)return;if(!Array.isArray(t))throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${Ir(t)}`);let o=e[a];for(let e of t){if(e===null)throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${Ir(e)}`);switch(n.kind){case`message`:o.push(n.T.fromJson(e,r));break;case`enum`:let t=Br(n.T,e,r.ignoreUnknownFields,!0);t!==Pr&&o.push(t);break;case`scalar`:try{o.push(zr(n.T,e,n.L,!0))}catch(t){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${Ir(e)}`;throw t instanceof Error&&t.message.length>0&&(r+=`: ${t.message}`),Error(r)}break}}}else if(n.kind==`map`){if(t===null)return;if(typeof t!=`object`||Array.isArray(t))throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${Ir(t)}`);let o=e[a];for(let[e,a]of Object.entries(t)){if(a===null)throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: map value null`);let s;try{s=Rr(n.K,e)}catch(e){let r=`cannot decode map key for field ${i.typeName}.${n.name} from JSON: ${Ir(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}switch(n.V.kind){case`message`:o[s]=n.V.T.fromJson(a,r);break;case`enum`:let e=Br(n.V.T,a,r.ignoreUnknownFields,!0);e!==Pr&&(o[s]=e);break;case`scalar`:try{o[s]=zr(n.V.T,a,sr.BIGINT,!0)}catch(e){let r=`cannot decode map value for field ${i.typeName}.${n.name} from JSON: ${Ir(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}break}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:a},a=`value`),n.kind){case`message`:let o=n.T;if(t===null&&o.typeName!=`google.protobuf.Value`)return;let s=e[a];Dr(s)?s.fromJson(t,r):(e[a]=s=o.fromJson(t,r),o.fieldWrapper&&!n.oneof&&(e[a]=o.fieldWrapper.unwrapField(s)));break;case`enum`:let c=Br(n.T,t,r.ignoreUnknownFields,!1);switch(c){case Nr:Er(n,e);break;case Pr:break;default:e[a]=c;break}break;case`scalar`:try{let r=zr(n.T,t,n.L,!1);switch(r){case Nr:Er(n,e);break;default:e[a]=r;break}}catch(e){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${Ir(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}break}}function Rr(e,t){if(e===j.BOOL)switch(t){case`true`:t=!0;break;case`false`:t=!1;break}return zr(e,t,sr.BIGINT,!0).toString()}function zr(e,t,n,r){if(t===null)return r?lr(e,n):Nr;switch(e){case j.DOUBLE:case j.FLOAT:if(t===`NaN`)return NaN;if(t===`Infinity`)return 1/0;if(t===`-Infinity`)return-1/0;if(t===``||typeof t==`string`&&t.trim().length!==t.length||typeof t!=`string`&&typeof t!=`number`)break;let r=Number(t);if(Number.isNaN(r)||!Number.isFinite(r))break;return e==j.FLOAT&&Rn(r),r;case j.INT32:case j.FIXED32:case j.SFIXED32:case j.SINT32:case j.UINT32:let i;if(typeof t==`number`?i=t:typeof t==`string`&&t.length>0&&t.trim().length===t.length&&(i=Number(t)),i===void 0)break;return e==j.UINT32||e==j.FIXED32?Ln(i):In(i),i;case j.INT64:case j.SFIXED64:case j.SINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let a=or.parse(t);return n?a.toString():a;case j.FIXED64:case j.UINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let o=or.uParse(t);return n?o.toString():o;case j.BOOL:if(typeof t!=`boolean`)break;return t;case j.STRING:if(typeof t!=`string`)break;return t;case j.BYTES:if(t===``)return new Uint8Array;if(typeof t!=`string`)break;return br.dec(t)}throw Error()}function Br(e,t,n,r){if(t===null)return e.typeName==`google.protobuf.NullValue`?0:r?e.values[0].no:Nr;switch(typeof t){case`number`:if(Number.isInteger(t))return t;break;case`string`:let r=e.findName(t);if(r!==void 0)return r.no;if(n)return Pr;break}throw Error(`cannot decode enum ${e.typeName} from JSON: ${Ir(t)}`)}function Vr(e){return e.repeated||e.kind==`map`?!0:!(e.oneof||e.kind==`message`||e.opt||e.req)}function Hr(e,t,n){if(e.kind==`map`){An(typeof t==`object`&&!!t);let r={},i=Object.entries(t);switch(e.V.kind){case`scalar`:for(let[t,n]of i)r[t.toString()]=Wr(e.V.T,n);break;case`message`:for(let[e,t]of i)r[e.toString()]=t.toJson(n);break;case`enum`:let t=e.V.T;for(let[e,a]of i)r[e.toString()]=Ur(t,a,n.enumAsInteger);break}return n.emitDefaultValues||i.length>0?r:void 0}if(e.repeated){An(Array.isArray(t));let r=[];switch(e.kind){case`scalar`:for(let n=0;n<t.length;n++)r.push(Wr(e.T,t[n]));break;case`enum`:for(let i=0;i<t.length;i++)r.push(Ur(e.T,t[i],n.enumAsInteger));break;case`message`:for(let e=0;e<t.length;e++)r.push(t[e].toJson(n));break}return n.emitDefaultValues||r.length>0?r:void 0}switch(e.kind){case`scalar`:return Wr(e.T,t);case`enum`:return Ur(e.T,t,n.enumAsInteger);case`message`:return Or(e.T,t).toJson(n)}}function Ur(e,t,n){return An(typeof t==`number`),e.typeName==`google.protobuf.NullValue`?null:n?t:e.findNumber(t)?.name??t}function Wr(e,t){switch(e){case j.INT32:case j.SFIXED32:case j.SINT32:case j.FIXED32:case j.UINT32:return An(typeof t==`number`),t;case j.FLOAT:case j.DOUBLE:return An(typeof t==`number`),Number.isNaN(t)?`NaN`:t===1/0?`Infinity`:t===-1/0?`-Infinity`:t;case j.STRING:return An(typeof t==`string`),t;case j.BOOL:return An(typeof t==`boolean`),t;case j.UINT64:case j.FIXED64:case j.INT64:case j.SFIXED64:case j.SINT64:return An(typeof t==`bigint`||typeof t==`string`||typeof t==`number`),t.toString();case j.BYTES:return An(t instanceof Uint8Array),br.enc(t)}}var Gr=Symbol(`@bufbuild/protobuf/unknown-fields`),Kr={readUnknownFields:!0,readerFactory:e=>new pr(e)},qr={writeUnknownFields:!0,writerFactory:()=>new fr};function Jr(e){return e?Object.assign(Object.assign({},Kr),e):Kr}function Yr(e){return e?Object.assign(Object.assign({},qr),e):qr}function Xr(){return{makeReadOptions:Jr,makeWriteOptions:Yr,listUnknownFields(e){return e[Gr]??[]},discardUnknownFields(e){delete e[Gr]},writeUnknownFields(e,t){let n=e[Gr];if(n)for(let e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,r){let i=e;Array.isArray(i[Gr])||(i[Gr]=[]),i[Gr].push({no:t,wireType:n,data:r})},readMessage(e,t,n,r,i){let a=e.getType(),o=i?t.len:t.pos+n,s,c;for(;t.pos<o&&([s,c]=t.tag(),!(i===!0&&c==dr.EndGroup));){let n=a.fields.find(s);if(!n){let n=t.skip(c,s);r.readUnknownFields&&this.onUnknownField(e,s,c,n);continue}Zr(e,t,n,c,r)}if(i&&(c!=dr.EndGroup||s!==n))throw Error(`invalid end group tag`)},readField:Zr,writeMessage(e,t,n){let r=e.getType();for(let i of r.fields.byNumber()){if(!Tr(i,e)){if(i.req)throw Error(`cannot encode field ${r.typeName}.${i.name} to binary: required field not set`);continue}ni(i,i.oneof?e[i.oneof.localName].value:e[i.localName],t,n)}return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,r){t!==void 0&&ni(e,t,n,r)}}}function Zr(e,t,n,r,i){let{repeated:a,localName:o}=n;switch(n.oneof&&(e=e[n.oneof.localName],e.case!=o&&delete e.value,e.case=o,o=`value`),n.kind){case`scalar`:case`enum`:let s=n.kind==`enum`?j.INT32:n.T,c=ti;if(n.kind==`scalar`&&n.L>0&&(c=ei),a){let n=e[o];if(r==dr.LengthDelimited&&s!=j.STRING&&s!=j.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,s))}else n.push(c(t,s))}else e[o]=c(t,s);break;case`message`:let l=n.T;a?e[o].push(Qr(t,new l,i,n)):Dr(e[o])?Qr(t,e[o],i,n):(e[o]=Qr(t,new l,i,n),l.fieldWrapper&&!n.oneof&&!n.repeated&&(e[o]=l.fieldWrapper.unwrapField(e[o])));break;case`map`:let[u,d]=$r(n,t,i);e[o][u]=d;break}}function Qr(e,t,n,r){let i=t.getType().runtime.bin,a=r?.delimited;return i.readMessage(t,e,a?r.no:e.uint32(),n,a),t}function $r(e,t,n){let r=t.uint32(),i=t.pos+r,a,o;for(;t.pos<i;){let[r]=t.tag();switch(r){case 1:a=ti(t,e.K);break;case 2:switch(e.V.kind){case`scalar`:o=ti(t,e.V.T);break;case`enum`:o=t.int32();break;case`message`:o=Qr(t,new e.V.T,n,void 0);break}break}}if(a===void 0&&(a=lr(e.K,sr.BIGINT)),typeof a!=`string`&&typeof a!=`number`&&(a=a.toString()),o===void 0)switch(e.V.kind){case`scalar`:o=lr(e.V.T,sr.BIGINT);break;case`enum`:o=e.V.T.values[0].no;break;case`message`:o=new e.V.T;break}return[a,o]}function ei(e,t){let n=ti(e,t);return typeof n==`bigint`?n.toString():n}function ti(e,t){switch(t){case j.STRING:return e.string();case j.BOOL:return e.bool();case j.DOUBLE:return e.double();case j.FLOAT:return e.float();case j.INT32:return e.int32();case j.INT64:return e.int64();case j.UINT64:return e.uint64();case j.FIXED64:return e.fixed64();case j.BYTES:return e.bytes();case j.FIXED32:return e.fixed32();case j.SFIXED32:return e.sfixed32();case j.SFIXED64:return e.sfixed64();case j.SINT64:return e.sint64();case j.UINT32:return e.uint32();case j.SINT32:return e.sint32()}}function ni(e,t,n,r){An(t!==void 0);let i=e.repeated;switch(e.kind){case`scalar`:case`enum`:let a=e.kind==`enum`?j.INT32:e.T;if(i)if(An(Array.isArray(t)),e.packed)oi(n,a,e.no,t);else for(let r of t)ai(n,a,e.no,r);else ai(n,a,e.no,t);break;case`message`:if(i){An(Array.isArray(t));for(let i of t)ii(n,r,e,i)}else ii(n,r,e,t);break;case`map`:An(typeof t==`object`&&!!t);for(let[i,a]of Object.entries(t))ri(n,r,e,i,a);break}}function ri(e,t,n,r,i){e.tag(n.no,dr.LengthDelimited),e.fork();let a=r;switch(n.K){case j.INT32:case j.FIXED32:case j.UINT32:case j.SFIXED32:case j.SINT32:a=Number.parseInt(r);break;case j.BOOL:An(r==`true`||r==`false`),a=r==`true`;break}switch(ai(e,n.K,1,a),n.V.kind){case`scalar`:ai(e,n.V.T,2,i);break;case`enum`:ai(e,j.INT32,2,i);break;case`message`:An(i!==void 0),e.tag(2,dr.LengthDelimited).bytes(i.toBinary(t));break}e.join()}function ii(e,t,n,r){let i=Or(n.T,r);n.delimited?e.tag(n.no,dr.StartGroup).raw(i.toBinary(t)).tag(n.no,dr.EndGroup):e.tag(n.no,dr.LengthDelimited).bytes(i.toBinary(t))}function ai(e,t,n,r){An(r!==void 0);let[i,a]=si(t);e.tag(n,i)[a](r)}function oi(e,t,n,r){if(!r.length)return;e.tag(n,dr.LengthDelimited).fork();let[,i]=si(t);for(let t=0;t<r.length;t++)e[i](r[t]);e.join()}function si(e){let t=dr.Varint;switch(e){case j.BYTES:case j.STRING:t=dr.LengthDelimited;break;case j.DOUBLE:case j.FIXED64:case j.SFIXED64:t=dr.Bit64;break;case j.FIXED32:case j.SFIXED32:case j.FLOAT:t=dr.Bit32;break}let n=j[e].toLowerCase();return[t,n]}function ci(){return{setEnumType:Vn,initPartial(e,t){if(e===void 0)return;let n=t.getType();for(let r of n.fields.byMember()){let n=r.localName,i=t,a=e;if(a[n]!=null)switch(r.kind){case`oneof`:let e=a[n].case;if(e===void 0)continue;let t=r.findField(e),o=a[n].value;t&&t.kind==`message`&&!Dr(o,t.T)?o=new t.T(o):t&&t.kind===`scalar`&&t.T===j.BYTES&&(o=ui(o)),i[n]={case:e,value:o};break;case`scalar`:case`enum`:let s=a[n];r.T===j.BYTES&&(s=r.repeated?s.map(ui):ui(s)),i[n]=s;break;case`map`:switch(r.V.kind){case`scalar`:case`enum`:if(r.V.T===j.BYTES)for(let[e,t]of Object.entries(a[n]))i[n][e]=ui(t);else Object.assign(i[n],a[n]);break;case`message`:let e=r.V.T;for(let t of Object.keys(a[n])){let r=a[n][t];e.fieldWrapper||(r=new e(r)),i[n][t]=r}break}break;case`message`:let c=r.T;if(r.repeated)i[n]=a[n].map(e=>Dr(e,c)?e:new c(e));else{let e=a[n];c.fieldWrapper?c.typeName===`google.protobuf.BytesValue`?i[n]=ui(e):i[n]=e:i[n]=Dr(e,c)?e:new c(e)}break}}},equals(e,t,n){return t===n?!0:!t||!n?!1:e.fields.byMember().every(e=>{let r=t[e.localName],i=n[e.localName];if(e.repeated){if(r.length!==i.length)return!1;switch(e.kind){case`message`:return r.every((t,n)=>e.T.equals(t,i[n]));case`scalar`:return r.every((t,n)=>cr(e.T,t,i[n]));case`enum`:return r.every((e,t)=>cr(j.INT32,e,i[t]))}throw Error(`repeated cannot contain ${e.kind}`)}switch(e.kind){case`message`:let t=r,n=i;return e.T.fieldWrapper&&(t!==void 0&&!Dr(t)&&(t=e.T.fieldWrapper.wrapField(t)),n!==void 0&&!Dr(n)&&(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case`enum`:return cr(j.INT32,r,i);case`scalar`:return cr(e.T,r,i);case`oneof`:if(r.case!==i.case)return!1;let a=e.findField(r.case);if(a===void 0)return!0;switch(a.kind){case`message`:return a.T.equals(r.value,i.value);case`enum`:return cr(j.INT32,r.value,i.value);case`scalar`:return cr(a.T,r.value,i.value)}throw Error(`oneof cannot contain ${a.kind}`);case`map`:let o=Object.keys(r).concat(Object.keys(i));switch(e.V.kind){case`message`:let t=e.V.T;return o.every(e=>t.equals(r[e],i[e]));case`enum`:return o.every(e=>cr(j.INT32,r[e],i[e]));case`scalar`:let n=e.V.T;return o.every(e=>cr(n,r[e],i[e]))}break}})},clone(e){let t=e.getType(),n=new t,r=n;for(let n of t.fields.byMember()){let t=e[n.localName],i;if(n.repeated)i=t.map(li);else if(n.kind==`map`){i=r[n.localName];for(let[e,n]of Object.entries(t))i[e]=li(n)}else i=n.kind==`oneof`?n.findField(t.case)?{case:t.case,value:li(t.value)}:{case:void 0}:li(t);r[n.localName]=i}for(let n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(r,n.no,n.wireType,n.data);return n}}}function li(e){if(e===void 0)return e;if(Dr(e))return e.clone();if(e instanceof Uint8Array){let t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function ui(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function di(e,t,n){return{syntax:e,json:Fr(),bin:Xr(),util:Object.assign(Object.assign({},ci()),{newFieldList:t,initFields:n}),makeMessageType(e,t,n){return Kn(this,e,t,n)},makeEnum:Un,makeEnumType:Hn,getEnumType:Bn,makeExtension(e,t,n){return mr(this,e,t,n)}}}var fi=class{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){let e={};for(let t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){let e={};for(let t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||=this._normalizer(this._fields),this.all}byNumber(){return this.numbersAsc||=this.list().concat().sort((e,t)=>e.no-t.no),this.numbersAsc}byMember(){if(!this.members){this.members=[];let e=this.members,t;for(let n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}};function pi(e,t){let n=gi(e);return t?n:xi(bi(n))}function mi(e){return pi(e,!1)}var hi=gi;function gi(e){let t=!1,n=[];for(let r=0;r<e.length;r++){let i=e.charAt(r);switch(i){case`_`:t=!0;break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n.push(i),t=!1;break;default:t&&(t=!1,i=i.toUpperCase()),n.push(i);break}}return n.join(``)}var _i=new Set([`constructor`,`toString`,`toJSON`,`valueOf`]),vi=new Set([`getType`,`clone`,`equals`,`fromBinary`,`fromJson`,`fromJsonString`,`toBinary`,`toJson`,`toJsonString`,`toObject`]),yi=e=>`${e}\$`,bi=e=>vi.has(e)?yi(e):e,xi=e=>_i.has(e)?yi(e):e,Si=class{constructor(e){this.kind=`oneof`,this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=mi(e)}addField(e){An(e.oneof===this,`field ${e.name} not one of ${this.name}`),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}};function Ci(e,t){let n=[],r;for(let t of typeof e==`function`?e():e){let e=t;if(e.localName=pi(t.name,t.oneof!==void 0),e.jsonName=t.jsonName??hi(t.name),e.repeated=t.repeated??!1,t.kind==`scalar`&&(e.L=t.L??sr.BIGINT),e.delimited=t.delimited??!1,e.req=t.req??!1,e.opt=t.opt??!1,t.packed===void 0&&(e.packed=t.kind==`enum`||t.kind==`scalar`&&t.T!=j.BYTES&&t.T!=j.STRING),t.oneof!==void 0){let n=typeof t.oneof==`string`?t.oneof:t.oneof.name;(!r||r.name!=n)&&(r=new Si(n)),e.oneof=r,r.addField(e)}n.push(e)}return n}var M=di(`proto3`,e=>new fi(e,e=>Ci(e)),e=>{for(let t of e.getType().fields.byMember()){if(t.opt)continue;let n=t.localName,r=e;if(t.repeated){r[n]=[];continue}switch(t.kind){case`oneof`:r[n]={case:void 0};break;case`enum`:r[n]=0;break;case`map`:r[n]={};break;case`scalar`:r[n]=lr(t.T,t.L);break}}}),wi=class e extends Gn{constructor(e){super(),this.seconds=or.zero,this.nanos=0,M.util.initPartial(e,this)}fromJson(e,t){if(typeof e!=`string`)throw Error(`cannot decode google.protobuf.Timestamp from JSON: ${M.json.debug(e)}`);let n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw Error(`cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string`);let r=Date.parse(n[1]+`-`+n[2]+`-`+n[3]+`T`+n[4]+`:`+n[5]+`:`+n[6]+(n[8]?n[8]:`Z`));if(Number.isNaN(r))throw Error(`cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string`);if(r<Date.parse(`0001-01-01T00:00:00Z`)||r>Date.parse(`9999-12-31T23:59:59Z`))throw Error(`cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);return this.seconds=or.parse(r/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt(`1`+n[7]+`0`.repeat(9-n[7].length))-1e9),this}toJson(e){let t=Number(this.seconds)*1e3;if(t<Date.parse(`0001-01-01T00:00:00Z`)||t>Date.parse(`9999-12-31T23:59:59Z`))throw Error(`cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);if(this.nanos<0)throw Error(`cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative`);let n=`Z`;if(this.nanos>0){let e=(this.nanos+1e9).toString().substring(1);n=e.substring(3)===`000000`?`.`+e.substring(0,3)+`Z`:e.substring(6)===`000`?`.`+e.substring(0,6)+`Z`:`.`+e+`Z`}return new Date(t).toISOString().replace(`.000Z`,n)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return e.fromDate(new Date)}static fromDate(t){let n=t.getTime();return new e({seconds:or.parse(Math.floor(n/1e3)),nanos:n%1e3*1e6})}static fromBinary(t,n){return new e().fromBinary(t,n)}static fromJson(t,n){return new e().fromJson(t,n)}static fromJsonString(t,n){return new e().fromJsonString(t,n)}static equals(t,n){return M.util.equals(e,t,n)}};wi.runtime=M,wi.typeName=`google.protobuf.Timestamp`,wi.fields=M.util.newFieldList(()=>[{no:1,name:`seconds`,kind:`scalar`,T:3},{no:2,name:`nanos`,kind:`scalar`,T:5}]);var Ti=M.makeMessageType(`livekit.MetricsBatch`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:wi},{no:3,name:`str_data`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`time_series`,kind:`message`,T:Ei,repeated:!0},{no:5,name:`events`,kind:`message`,T:Oi,repeated:!0}]),Ei=M.makeMessageType(`livekit.TimeSeriesMetric`,()=>[{no:1,name:`label`,kind:`scalar`,T:13},{no:2,name:`participant_identity`,kind:`scalar`,T:13},{no:3,name:`track_sid`,kind:`scalar`,T:13},{no:4,name:`samples`,kind:`message`,T:Di,repeated:!0},{no:5,name:`rid`,kind:`scalar`,T:13}]),Di=M.makeMessageType(`livekit.MetricSample`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:wi},{no:3,name:`value`,kind:`scalar`,T:2}]),Oi=M.makeMessageType(`livekit.EventMetric`,()=>[{no:1,name:`label`,kind:`scalar`,T:13},{no:2,name:`participant_identity`,kind:`scalar`,T:13},{no:3,name:`track_sid`,kind:`scalar`,T:13},{no:4,name:`start_timestamp_ms`,kind:`scalar`,T:3},{no:5,name:`end_timestamp_ms`,kind:`scalar`,T:3,opt:!0},{no:6,name:`normalized_start_timestamp`,kind:`message`,T:wi},{no:7,name:`normalized_end_timestamp`,kind:`message`,T:wi,opt:!0},{no:8,name:`metadata`,kind:`scalar`,T:9},{no:9,name:`rid`,kind:`scalar`,T:13}]),ki=M.makeEnum(`livekit.BackupCodecPolicy`,[{no:0,name:`PREFER_REGRESSION`},{no:1,name:`SIMULCAST`},{no:2,name:`REGRESSION`}]),Ai=M.makeEnum(`livekit.TrackType`,[{no:0,name:`AUDIO`},{no:1,name:`VIDEO`},{no:2,name:`DATA`}]),ji=M.makeEnum(`livekit.TrackSource`,[{no:0,name:`UNKNOWN`},{no:1,name:`CAMERA`},{no:2,name:`MICROPHONE`},{no:3,name:`SCREEN_SHARE`},{no:4,name:`SCREEN_SHARE_AUDIO`}]),Mi=M.makeEnum(`livekit.VideoQuality`,[{no:0,name:`LOW`},{no:1,name:`MEDIUM`},{no:2,name:`HIGH`},{no:3,name:`OFF`}]),Ni=M.makeEnum(`livekit.ConnectionQuality`,[{no:0,name:`POOR`},{no:1,name:`GOOD`},{no:2,name:`EXCELLENT`},{no:3,name:`LOST`}]),Pi=M.makeEnum(`livekit.ClientConfigSetting`,[{no:0,name:`UNSET`},{no:1,name:`DISABLED`},{no:2,name:`ENABLED`}]),Fi=M.makeEnum(`livekit.DisconnectReason`,[{no:0,name:`UNKNOWN_REASON`},{no:1,name:`CLIENT_INITIATED`},{no:2,name:`DUPLICATE_IDENTITY`},{no:3,name:`SERVER_SHUTDOWN`},{no:4,name:`PARTICIPANT_REMOVED`},{no:5,name:`ROOM_DELETED`},{no:6,name:`STATE_MISMATCH`},{no:7,name:`JOIN_FAILURE`},{no:8,name:`MIGRATION`},{no:9,name:`SIGNAL_CLOSE`},{no:10,name:`ROOM_CLOSED`},{no:11,name:`USER_UNAVAILABLE`},{no:12,name:`USER_REJECTED`},{no:13,name:`SIP_TRUNK_FAILURE`},{no:14,name:`CONNECTION_TIMEOUT`},{no:15,name:`MEDIA_FAILURE`}]),Ii=M.makeEnum(`livekit.ReconnectReason`,[{no:0,name:`RR_UNKNOWN`},{no:1,name:`RR_SIGNAL_DISCONNECTED`},{no:2,name:`RR_PUBLISHER_FAILED`},{no:3,name:`RR_SUBSCRIBER_FAILED`},{no:4,name:`RR_SWITCH_CANDIDATE`}]),Li=M.makeEnum(`livekit.SubscriptionError`,[{no:0,name:`SE_UNKNOWN`},{no:1,name:`SE_CODEC_UNSUPPORTED`},{no:2,name:`SE_TRACK_NOTFOUND`}]),Ri=M.makeEnum(`livekit.AudioTrackFeature`,[{no:0,name:`TF_STEREO`},{no:1,name:`TF_NO_DTX`},{no:2,name:`TF_AUTO_GAIN_CONTROL`},{no:3,name:`TF_ECHO_CANCELLATION`},{no:4,name:`TF_NOISE_SUPPRESSION`},{no:5,name:`TF_ENHANCED_NOISE_CANCELLATION`},{no:6,name:`TF_PRECONNECT_BUFFER`}]),zi=M.makeMessageType(`livekit.Room`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`empty_timeout`,kind:`scalar`,T:13},{no:14,name:`departure_timeout`,kind:`scalar`,T:13},{no:4,name:`max_participants`,kind:`scalar`,T:13},{no:5,name:`creation_time`,kind:`scalar`,T:3},{no:15,name:`creation_time_ms`,kind:`scalar`,T:3},{no:6,name:`turn_password`,kind:`scalar`,T:9},{no:7,name:`enabled_codecs`,kind:`message`,T:Bi,repeated:!0},{no:8,name:`metadata`,kind:`scalar`,T:9},{no:9,name:`num_participants`,kind:`scalar`,T:13},{no:11,name:`num_publishers`,kind:`scalar`,T:13},{no:10,name:`active_recording`,kind:`scalar`,T:8},{no:13,name:`version`,kind:`message`,T:xa}]),Bi=M.makeMessageType(`livekit.Codec`,()=>[{no:1,name:`mime`,kind:`scalar`,T:9},{no:2,name:`fmtp_line`,kind:`scalar`,T:9}]),Vi=M.makeMessageType(`livekit.ParticipantPermission`,()=>[{no:1,name:`can_subscribe`,kind:`scalar`,T:8},{no:2,name:`can_publish`,kind:`scalar`,T:8},{no:3,name:`can_publish_data`,kind:`scalar`,T:8},{no:9,name:`can_publish_sources`,kind:`enum`,T:M.getEnumType(ji),repeated:!0},{no:7,name:`hidden`,kind:`scalar`,T:8},{no:8,name:`recorder`,kind:`scalar`,T:8},{no:10,name:`can_update_metadata`,kind:`scalar`,T:8},{no:11,name:`agent`,kind:`scalar`,T:8},{no:12,name:`can_subscribe_metrics`,kind:`scalar`,T:8}]),Hi=M.makeMessageType(`livekit.ParticipantInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`identity`,kind:`scalar`,T:9},{no:3,name:`state`,kind:`enum`,T:M.getEnumType(Ui)},{no:4,name:`tracks`,kind:`message`,T:qi,repeated:!0},{no:5,name:`metadata`,kind:`scalar`,T:9},{no:6,name:`joined_at`,kind:`scalar`,T:3},{no:17,name:`joined_at_ms`,kind:`scalar`,T:3},{no:9,name:`name`,kind:`scalar`,T:9},{no:10,name:`version`,kind:`scalar`,T:13},{no:11,name:`permission`,kind:`message`,T:Vi},{no:12,name:`region`,kind:`scalar`,T:9},{no:13,name:`is_publisher`,kind:`scalar`,T:8},{no:14,name:`kind`,kind:`enum`,T:M.getEnumType(Wi)},{no:15,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:16,name:`disconnect_reason`,kind:`enum`,T:M.getEnumType(Fi)},{no:18,name:`kind_details`,kind:`enum`,T:M.getEnumType(Gi),repeated:!0},{no:19,name:`data_tracks`,kind:`message`,T:Ji,repeated:!0}]),Ui=M.makeEnum(`livekit.ParticipantInfo.State`,[{no:0,name:`JOINING`},{no:1,name:`JOINED`},{no:2,name:`ACTIVE`},{no:3,name:`DISCONNECTED`}]),Wi=M.makeEnum(`livekit.ParticipantInfo.Kind`,[{no:0,name:`STANDARD`},{no:1,name:`INGRESS`},{no:2,name:`EGRESS`},{no:3,name:`SIP`},{no:4,name:`AGENT`},{no:7,name:`CONNECTOR`},{no:8,name:`BRIDGE`}]),Gi=M.makeEnum(`livekit.ParticipantInfo.KindDetail`,[{no:0,name:`CLOUD_AGENT`},{no:1,name:`FORWARDED`},{no:2,name:`CONNECTOR_WHATSAPP`},{no:3,name:`CONNECTOR_TWILIO`},{no:4,name:`BRIDGE_RTSP`}]),N=M.makeEnum(`livekit.Encryption.Type`,[{no:0,name:`NONE`},{no:1,name:`GCM`},{no:2,name:`CUSTOM`}]),Ki=M.makeMessageType(`livekit.SimulcastCodecInfo`,()=>[{no:1,name:`mime_type`,kind:`scalar`,T:9},{no:2,name:`mid`,kind:`scalar`,T:9},{no:3,name:`cid`,kind:`scalar`,T:9},{no:4,name:`layers`,kind:`message`,T:Xi,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:M.getEnumType(Zi)},{no:6,name:`sdp_cid`,kind:`scalar`,T:9}]),qi=M.makeMessageType(`livekit.TrackInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`type`,kind:`enum`,T:M.getEnumType(Ai)},{no:3,name:`name`,kind:`scalar`,T:9},{no:4,name:`muted`,kind:`scalar`,T:8},{no:5,name:`width`,kind:`scalar`,T:13},{no:6,name:`height`,kind:`scalar`,T:13},{no:7,name:`simulcast`,kind:`scalar`,T:8},{no:8,name:`disable_dtx`,kind:`scalar`,T:8},{no:9,name:`source`,kind:`enum`,T:M.getEnumType(ji)},{no:10,name:`layers`,kind:`message`,T:Xi,repeated:!0},{no:11,name:`mime_type`,kind:`scalar`,T:9},{no:12,name:`mid`,kind:`scalar`,T:9},{no:13,name:`codecs`,kind:`message`,T:Ki,repeated:!0},{no:14,name:`stereo`,kind:`scalar`,T:8},{no:15,name:`disable_red`,kind:`scalar`,T:8},{no:16,name:`encryption`,kind:`enum`,T:M.getEnumType(N)},{no:17,name:`stream`,kind:`scalar`,T:9},{no:18,name:`version`,kind:`message`,T:xa},{no:19,name:`audio_features`,kind:`enum`,T:M.getEnumType(Ri),repeated:!0},{no:20,name:`backup_codec_policy`,kind:`enum`,T:M.getEnumType(ki)}]),Ji=M.makeMessageType(`livekit.DataTrackInfo`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13},{no:2,name:`sid`,kind:`scalar`,T:9},{no:3,name:`name`,kind:`scalar`,T:9},{no:4,name:`encryption`,kind:`enum`,T:M.getEnumType(N)}]),Yi=M.makeMessageType(`livekit.DataTrackSubscriptionOptions`,()=>[{no:1,name:`target_fps`,kind:`scalar`,T:13,opt:!0}]),Xi=M.makeMessageType(`livekit.VideoLayer`,()=>[{no:1,name:`quality`,kind:`enum`,T:M.getEnumType(Mi)},{no:2,name:`width`,kind:`scalar`,T:13},{no:3,name:`height`,kind:`scalar`,T:13},{no:4,name:`bitrate`,kind:`scalar`,T:13},{no:5,name:`ssrc`,kind:`scalar`,T:13},{no:6,name:`spatial_layer`,kind:`scalar`,T:5},{no:7,name:`rid`,kind:`scalar`,T:9},{no:8,name:`repair_ssrc`,kind:`scalar`,T:13}]),Zi=M.makeEnum(`livekit.VideoLayer.Mode`,[{no:0,name:`MODE_UNUSED`},{no:1,name:`ONE_SPATIAL_LAYER_PER_STREAM`},{no:2,name:`MULTIPLE_SPATIAL_LAYERS_PER_STREAM`},{no:3,name:`ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR`}]),Qi=M.makeMessageType(`livekit.DataPacket`,()=>[{no:1,name:`kind`,kind:`enum`,T:M.getEnumType($i)},{no:4,name:`participant_identity`,kind:`scalar`,T:9},{no:5,name:`destination_identities`,kind:`scalar`,T:9,repeated:!0},{no:2,name:`user`,kind:`message`,T:ia,oneof:`value`},{no:3,name:`speaker`,kind:`message`,T:na,oneof:`value`},{no:6,name:`sip_dtmf`,kind:`message`,T:aa,oneof:`value`},{no:7,name:`transcription`,kind:`message`,T:oa,oneof:`value`},{no:8,name:`metrics`,kind:`message`,T:Ti,oneof:`value`},{no:9,name:`chat_message`,kind:`message`,T:ca,oneof:`value`},{no:10,name:`rpc_request`,kind:`message`,T:la,oneof:`value`},{no:11,name:`rpc_ack`,kind:`message`,T:ua,oneof:`value`},{no:12,name:`rpc_response`,kind:`message`,T:da,oneof:`value`},{no:13,name:`stream_header`,kind:`message`,T:Ta,oneof:`value`},{no:14,name:`stream_chunk`,kind:`message`,T:Ea,oneof:`value`},{no:15,name:`stream_trailer`,kind:`message`,T:Da,oneof:`value`},{no:18,name:`encrypted_packet`,kind:`message`,T:ea,oneof:`value`},{no:16,name:`sequence`,kind:`scalar`,T:13},{no:17,name:`participant_sid`,kind:`scalar`,T:9}]),$i=M.makeEnum(`livekit.DataPacket.Kind`,[{no:0,name:`RELIABLE`},{no:1,name:`LOSSY`}]),ea=M.makeMessageType(`livekit.EncryptedPacket`,()=>[{no:1,name:`encryption_type`,kind:`enum`,T:M.getEnumType(N)},{no:2,name:`iv`,kind:`scalar`,T:12},{no:3,name:`key_index`,kind:`scalar`,T:13},{no:4,name:`encrypted_value`,kind:`scalar`,T:12}]),ta=M.makeMessageType(`livekit.EncryptedPacketPayload`,()=>[{no:1,name:`user`,kind:`message`,T:ia,oneof:`value`},{no:3,name:`chat_message`,kind:`message`,T:ca,oneof:`value`},{no:4,name:`rpc_request`,kind:`message`,T:la,oneof:`value`},{no:5,name:`rpc_ack`,kind:`message`,T:ua,oneof:`value`},{no:6,name:`rpc_response`,kind:`message`,T:da,oneof:`value`},{no:7,name:`stream_header`,kind:`message`,T:Ta,oneof:`value`},{no:8,name:`stream_chunk`,kind:`message`,T:Ea,oneof:`value`},{no:9,name:`stream_trailer`,kind:`message`,T:Da,oneof:`value`}]),na=M.makeMessageType(`livekit.ActiveSpeakerUpdate`,()=>[{no:1,name:`speakers`,kind:`message`,T:ra,repeated:!0}]),ra=M.makeMessageType(`livekit.SpeakerInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`level`,kind:`scalar`,T:2},{no:3,name:`active`,kind:`scalar`,T:8}]),ia=M.makeMessageType(`livekit.UserPacket`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:5,name:`participant_identity`,kind:`scalar`,T:9},{no:2,name:`payload`,kind:`scalar`,T:12},{no:3,name:`destination_sids`,kind:`scalar`,T:9,repeated:!0},{no:6,name:`destination_identities`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`topic`,kind:`scalar`,T:9,opt:!0},{no:8,name:`id`,kind:`scalar`,T:9,opt:!0},{no:9,name:`start_time`,kind:`scalar`,T:4,opt:!0},{no:10,name:`end_time`,kind:`scalar`,T:4,opt:!0},{no:11,name:`nonce`,kind:`scalar`,T:12}]),aa=M.makeMessageType(`livekit.SipDTMF`,()=>[{no:3,name:`code`,kind:`scalar`,T:13},{no:4,name:`digit`,kind:`scalar`,T:9}]),oa=M.makeMessageType(`livekit.Transcription`,()=>[{no:2,name:`transcribed_participant_identity`,kind:`scalar`,T:9},{no:3,name:`track_id`,kind:`scalar`,T:9},{no:4,name:`segments`,kind:`message`,T:sa,repeated:!0}]),sa=M.makeMessageType(`livekit.TranscriptionSegment`,()=>[{no:1,name:`id`,kind:`scalar`,T:9},{no:2,name:`text`,kind:`scalar`,T:9},{no:3,name:`start_time`,kind:`scalar`,T:4},{no:4,name:`end_time`,kind:`scalar`,T:4},{no:5,name:`final`,kind:`scalar`,T:8},{no:6,name:`language`,kind:`scalar`,T:9}]),ca=M.makeMessageType(`livekit.ChatMessage`,()=>[{no:1,name:`id`,kind:`scalar`,T:9},{no:2,name:`timestamp`,kind:`scalar`,T:3},{no:3,name:`edit_timestamp`,kind:`scalar`,T:3,opt:!0},{no:4,name:`message`,kind:`scalar`,T:9},{no:5,name:`deleted`,kind:`scalar`,T:8},{no:6,name:`generated`,kind:`scalar`,T:8}]),la=M.makeMessageType(`livekit.RpcRequest`,()=>[{no:1,name:`id`,kind:`scalar`,T:9},{no:2,name:`method`,kind:`scalar`,T:9},{no:3,name:`payload`,kind:`scalar`,T:9},{no:4,name:`response_timeout_ms`,kind:`scalar`,T:13},{no:5,name:`version`,kind:`scalar`,T:13}]),ua=M.makeMessageType(`livekit.RpcAck`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:9}]),da=M.makeMessageType(`livekit.RpcResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:9},{no:2,name:`payload`,kind:`scalar`,T:9,oneof:`value`},{no:3,name:`error`,kind:`message`,T:fa,oneof:`value`}]),fa=M.makeMessageType(`livekit.RpcError`,()=>[{no:1,name:`code`,kind:`scalar`,T:13},{no:2,name:`message`,kind:`scalar`,T:9},{no:3,name:`data`,kind:`scalar`,T:9}]),pa=M.makeMessageType(`livekit.ParticipantTracks`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sids`,kind:`scalar`,T:9,repeated:!0}]),ma=M.makeMessageType(`livekit.ServerInfo`,()=>[{no:1,name:`edition`,kind:`enum`,T:M.getEnumType(ha)},{no:2,name:`version`,kind:`scalar`,T:9},{no:3,name:`protocol`,kind:`scalar`,T:5},{no:4,name:`region`,kind:`scalar`,T:9},{no:5,name:`node_id`,kind:`scalar`,T:9},{no:6,name:`debug_info`,kind:`scalar`,T:9},{no:7,name:`agent_protocol`,kind:`scalar`,T:5}]),ha=M.makeEnum(`livekit.ServerInfo.Edition`,[{no:0,name:`Standard`},{no:1,name:`Cloud`}]),ga=M.makeMessageType(`livekit.ClientInfo`,()=>[{no:1,name:`sdk`,kind:`enum`,T:M.getEnumType(_a)},{no:2,name:`version`,kind:`scalar`,T:9},{no:3,name:`protocol`,kind:`scalar`,T:5},{no:4,name:`os`,kind:`scalar`,T:9},{no:5,name:`os_version`,kind:`scalar`,T:9},{no:6,name:`device_model`,kind:`scalar`,T:9},{no:7,name:`browser`,kind:`scalar`,T:9},{no:8,name:`browser_version`,kind:`scalar`,T:9},{no:9,name:`address`,kind:`scalar`,T:9},{no:10,name:`network`,kind:`scalar`,T:9},{no:11,name:`other_sdks`,kind:`scalar`,T:9}]),_a=M.makeEnum(`livekit.ClientInfo.SDK`,[{no:0,name:`UNKNOWN`},{no:1,name:`JS`},{no:2,name:`SWIFT`},{no:3,name:`ANDROID`},{no:4,name:`FLUTTER`},{no:5,name:`GO`},{no:6,name:`UNITY`},{no:7,name:`REACT_NATIVE`},{no:8,name:`RUST`},{no:9,name:`PYTHON`},{no:10,name:`CPP`},{no:11,name:`UNITY_WEB`},{no:12,name:`NODE`},{no:13,name:`UNREAL`},{no:14,name:`ESP32`}]),va=M.makeMessageType(`livekit.ClientConfiguration`,()=>[{no:1,name:`video`,kind:`message`,T:ya},{no:2,name:`screen`,kind:`message`,T:ya},{no:3,name:`resume_connection`,kind:`enum`,T:M.getEnumType(Pi)},{no:4,name:`disabled_codecs`,kind:`message`,T:ba},{no:5,name:`force_relay`,kind:`enum`,T:M.getEnumType(Pi)}]),ya=M.makeMessageType(`livekit.VideoConfiguration`,()=>[{no:1,name:`hardware_encoder`,kind:`enum`,T:M.getEnumType(Pi)}]),ba=M.makeMessageType(`livekit.DisabledCodecs`,()=>[{no:1,name:`codecs`,kind:`message`,T:Bi,repeated:!0},{no:2,name:`publish`,kind:`message`,T:Bi,repeated:!0}]),xa=M.makeMessageType(`livekit.TimedVersion`,()=>[{no:1,name:`unix_micro`,kind:`scalar`,T:3},{no:2,name:`ticks`,kind:`scalar`,T:5}]),Sa=M.makeEnum(`livekit.DataStream.OperationType`,[{no:0,name:`CREATE`},{no:1,name:`UPDATE`},{no:2,name:`DELETE`},{no:3,name:`REACTION`}]),Ca=M.makeMessageType(`livekit.DataStream.TextHeader`,()=>[{no:1,name:`operation_type`,kind:`enum`,T:M.getEnumType(Sa)},{no:2,name:`version`,kind:`scalar`,T:5},{no:3,name:`reply_to_stream_id`,kind:`scalar`,T:9},{no:4,name:`attached_stream_ids`,kind:`scalar`,T:9,repeated:!0},{no:5,name:`generated`,kind:`scalar`,T:8}],{localName:`DataStream_TextHeader`}),wa=M.makeMessageType(`livekit.DataStream.ByteHeader`,()=>[{no:1,name:`name`,kind:`scalar`,T:9}],{localName:`DataStream_ByteHeader`}),Ta=M.makeMessageType(`livekit.DataStream.Header`,()=>[{no:1,name:`stream_id`,kind:`scalar`,T:9},{no:2,name:`timestamp`,kind:`scalar`,T:3},{no:3,name:`topic`,kind:`scalar`,T:9},{no:4,name:`mime_type`,kind:`scalar`,T:9},{no:5,name:`total_length`,kind:`scalar`,T:4,opt:!0},{no:7,name:`encryption_type`,kind:`enum`,T:M.getEnumType(N)},{no:8,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:9,name:`text_header`,kind:`message`,T:Ca,oneof:`content_header`},{no:10,name:`byte_header`,kind:`message`,T:wa,oneof:`content_header`}],{localName:`DataStream_Header`}),Ea=M.makeMessageType(`livekit.DataStream.Chunk`,()=>[{no:1,name:`stream_id`,kind:`scalar`,T:9},{no:2,name:`chunk_index`,kind:`scalar`,T:4},{no:3,name:`content`,kind:`scalar`,T:12},{no:4,name:`version`,kind:`scalar`,T:5},{no:5,name:`iv`,kind:`scalar`,T:12,opt:!0}],{localName:`DataStream_Chunk`}),Da=M.makeMessageType(`livekit.DataStream.Trailer`,()=>[{no:1,name:`stream_id`,kind:`scalar`,T:9},{no:2,name:`reason`,kind:`scalar`,T:9},{no:3,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}}],{localName:`DataStream_Trailer`}),Oa=M.makeMessageType(`livekit.SubscribedAudioCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`enabled`,kind:`scalar`,T:8}]),ka=M.makeEnum(`livekit.SignalTarget`,[{no:0,name:`PUBLISHER`},{no:1,name:`SUBSCRIBER`}]),Aa=M.makeEnum(`livekit.StreamState`,[{no:0,name:`ACTIVE`},{no:1,name:`PAUSED`}]),ja=M.makeEnum(`livekit.CandidateProtocol`,[{no:0,name:`UDP`},{no:1,name:`TCP`},{no:2,name:`TLS`}]),Ma=M.makeMessageType(`livekit.SignalRequest`,()=>[{no:1,name:`offer`,kind:`message`,T:Ja,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:Ja,oneof:`message`},{no:3,name:`trickle`,kind:`message`,T:Ha,oneof:`message`},{no:4,name:`add_track`,kind:`message`,T:Fa,oneof:`message`},{no:5,name:`mute`,kind:`message`,T:Ua,oneof:`message`},{no:6,name:`subscription`,kind:`message`,T:Xa,oneof:`message`},{no:7,name:`track_setting`,kind:`message`,T:$a,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:no,oneof:`message`},{no:10,name:`update_layers`,kind:`message`,T:io,oneof:`message`},{no:11,name:`subscription_permission`,kind:`message`,T:yo,oneof:`message`},{no:12,name:`sync_state`,kind:`message`,T:So,oneof:`message`},{no:13,name:`simulate`,kind:`message`,T:To,oneof:`message`},{no:14,name:`ping`,kind:`scalar`,T:3,oneof:`message`},{no:15,name:`update_metadata`,kind:`message`,T:ao,oneof:`message`},{no:16,name:`ping_req`,kind:`message`,T:Eo,oneof:`message`},{no:17,name:`update_audio_track`,kind:`message`,T:eo,oneof:`message`},{no:18,name:`update_video_track`,kind:`message`,T:to,oneof:`message`},{no:19,name:`publish_data_track_request`,kind:`message`,T:Ia,oneof:`message`},{no:20,name:`unpublish_data_track_request`,kind:`message`,T:Ra,oneof:`message`},{no:21,name:`update_data_subscription`,kind:`message`,T:Za,oneof:`message`}]),Na=M.makeMessageType(`livekit.SignalResponse`,()=>[{no:1,name:`join`,kind:`message`,T:Wa,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:Ja,oneof:`message`},{no:3,name:`offer`,kind:`message`,T:Ja,oneof:`message`},{no:4,name:`trickle`,kind:`message`,T:Ha,oneof:`message`},{no:5,name:`update`,kind:`message`,T:Ya,oneof:`message`},{no:6,name:`track_published`,kind:`message`,T:Ka,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:no,oneof:`message`},{no:9,name:`mute`,kind:`message`,T:Ua,oneof:`message`},{no:10,name:`speakers_changed`,kind:`message`,T:so,oneof:`message`},{no:11,name:`room_update`,kind:`message`,T:co,oneof:`message`},{no:12,name:`connection_quality`,kind:`message`,T:uo,oneof:`message`},{no:13,name:`stream_state_update`,kind:`message`,T:po,oneof:`message`},{no:14,name:`subscribed_quality_update`,kind:`message`,T:go,oneof:`message`},{no:15,name:`subscription_permission_update`,kind:`message`,T:bo,oneof:`message`},{no:16,name:`refresh_token`,kind:`scalar`,T:9,oneof:`message`},{no:17,name:`track_unpublished`,kind:`message`,T:qa,oneof:`message`},{no:18,name:`pong`,kind:`scalar`,T:3,oneof:`message`},{no:19,name:`reconnect`,kind:`message`,T:Ga,oneof:`message`},{no:20,name:`pong_resp`,kind:`message`,T:Do,oneof:`message`},{no:21,name:`subscription_response`,kind:`message`,T:Ao,oneof:`message`},{no:22,name:`request_response`,kind:`message`,T:jo,oneof:`message`},{no:23,name:`track_subscribed`,kind:`message`,T:No,oneof:`message`},{no:24,name:`room_moved`,kind:`message`,T:xo,oneof:`message`},{no:25,name:`media_sections_requirement`,kind:`message`,T:Ro,oneof:`message`},{no:26,name:`subscribed_audio_codec_update`,kind:`message`,T:_o,oneof:`message`},{no:27,name:`publish_data_track_response`,kind:`message`,T:La,oneof:`message`},{no:28,name:`unpublish_data_track_response`,kind:`message`,T:za,oneof:`message`},{no:29,name:`data_track_subscriber_handles`,kind:`message`,T:Ba,oneof:`message`}]),Pa=M.makeMessageType(`livekit.SimulcastCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`cid`,kind:`scalar`,T:9},{no:4,name:`layers`,kind:`message`,T:Xi,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:M.getEnumType(Zi)}]),Fa=M.makeMessageType(`livekit.AddTrackRequest`,()=>[{no:1,name:`cid`,kind:`scalar`,T:9},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`type`,kind:`enum`,T:M.getEnumType(Ai)},{no:4,name:`width`,kind:`scalar`,T:13},{no:5,name:`height`,kind:`scalar`,T:13},{no:6,name:`muted`,kind:`scalar`,T:8},{no:7,name:`disable_dtx`,kind:`scalar`,T:8},{no:8,name:`source`,kind:`enum`,T:M.getEnumType(ji)},{no:9,name:`layers`,kind:`message`,T:Xi,repeated:!0},{no:10,name:`simulcast_codecs`,kind:`message`,T:Pa,repeated:!0},{no:11,name:`sid`,kind:`scalar`,T:9},{no:12,name:`stereo`,kind:`scalar`,T:8},{no:13,name:`disable_red`,kind:`scalar`,T:8},{no:14,name:`encryption`,kind:`enum`,T:M.getEnumType(N)},{no:15,name:`stream`,kind:`scalar`,T:9},{no:16,name:`backup_codec_policy`,kind:`enum`,T:M.getEnumType(ki)},{no:17,name:`audio_features`,kind:`enum`,T:M.getEnumType(Ri),repeated:!0}]),Ia=M.makeMessageType(`livekit.PublishDataTrackRequest`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`encryption`,kind:`enum`,T:M.getEnumType(N)}]),La=M.makeMessageType(`livekit.PublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:Ji}]),Ra=M.makeMessageType(`livekit.UnpublishDataTrackRequest`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13}]),za=M.makeMessageType(`livekit.UnpublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:Ji}]),Ba=M.makeMessageType(`livekit.DataTrackSubscriberHandles`,()=>[{no:1,name:`sub_handles`,kind:`map`,K:13,V:{kind:`message`,T:Va}}]),Va=M.makeMessageType(`livekit.DataTrackSubscriberHandles.PublishedDataTrack`,()=>[{no:1,name:`publisher_identity`,kind:`scalar`,T:9},{no:2,name:`publisher_sid`,kind:`scalar`,T:9},{no:3,name:`track_sid`,kind:`scalar`,T:9}],{localName:`DataTrackSubscriberHandles_PublishedDataTrack`}),Ha=M.makeMessageType(`livekit.TrickleRequest`,()=>[{no:1,name:`candidateInit`,kind:`scalar`,T:9},{no:2,name:`target`,kind:`enum`,T:M.getEnumType(ka)},{no:3,name:`final`,kind:`scalar`,T:8}]),Ua=M.makeMessageType(`livekit.MuteTrackRequest`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`muted`,kind:`scalar`,T:8}]),Wa=M.makeMessageType(`livekit.JoinResponse`,()=>[{no:1,name:`room`,kind:`message`,T:zi},{no:2,name:`participant`,kind:`message`,T:Hi},{no:3,name:`other_participants`,kind:`message`,T:Hi,repeated:!0},{no:4,name:`server_version`,kind:`scalar`,T:9},{no:5,name:`ice_servers`,kind:`message`,T:oo,repeated:!0},{no:6,name:`subscriber_primary`,kind:`scalar`,T:8},{no:7,name:`alternative_url`,kind:`scalar`,T:9},{no:8,name:`client_configuration`,kind:`message`,T:va},{no:9,name:`server_region`,kind:`scalar`,T:9},{no:10,name:`ping_timeout`,kind:`scalar`,T:5},{no:11,name:`ping_interval`,kind:`scalar`,T:5},{no:12,name:`server_info`,kind:`message`,T:ma},{no:13,name:`sif_trailer`,kind:`scalar`,T:12},{no:14,name:`enabled_publish_codecs`,kind:`message`,T:Bi,repeated:!0},{no:15,name:`fast_publish`,kind:`scalar`,T:8}]),Ga=M.makeMessageType(`livekit.ReconnectResponse`,()=>[{no:1,name:`ice_servers`,kind:`message`,T:oo,repeated:!0},{no:2,name:`client_configuration`,kind:`message`,T:va},{no:3,name:`server_info`,kind:`message`,T:ma},{no:4,name:`last_message_seq`,kind:`scalar`,T:13}]),Ka=M.makeMessageType(`livekit.TrackPublishedResponse`,()=>[{no:1,name:`cid`,kind:`scalar`,T:9},{no:2,name:`track`,kind:`message`,T:qi}]),qa=M.makeMessageType(`livekit.TrackUnpublishedResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),Ja=M.makeMessageType(`livekit.SessionDescription`,()=>[{no:1,name:`type`,kind:`scalar`,T:9},{no:2,name:`sdp`,kind:`scalar`,T:9},{no:3,name:`id`,kind:`scalar`,T:13},{no:4,name:`mid_to_track_id`,kind:`map`,K:9,V:{kind:`scalar`,T:9}}]),Ya=M.makeMessageType(`livekit.ParticipantUpdate`,()=>[{no:1,name:`participants`,kind:`message`,T:Hi,repeated:!0}]),Xa=M.makeMessageType(`livekit.UpdateSubscription`,()=>[{no:1,name:`track_sids`,kind:`scalar`,T:9,repeated:!0},{no:2,name:`subscribe`,kind:`scalar`,T:8},{no:3,name:`participant_tracks`,kind:`message`,T:pa,repeated:!0}]),Za=M.makeMessageType(`livekit.UpdateDataSubscription`,()=>[{no:1,name:`updates`,kind:`message`,T:Qa,repeated:!0}]),Qa=M.makeMessageType(`livekit.UpdateDataSubscription.Update`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribe`,kind:`scalar`,T:8},{no:3,name:`options`,kind:`message`,T:Yi}],{localName:`UpdateDataSubscription_Update`}),$a=M.makeMessageType(`livekit.UpdateTrackSettings`,()=>[{no:1,name:`track_sids`,kind:`scalar`,T:9,repeated:!0},{no:3,name:`disabled`,kind:`scalar`,T:8},{no:4,name:`quality`,kind:`enum`,T:M.getEnumType(Mi)},{no:5,name:`width`,kind:`scalar`,T:13},{no:6,name:`height`,kind:`scalar`,T:13},{no:7,name:`fps`,kind:`scalar`,T:13},{no:8,name:`priority`,kind:`scalar`,T:13}]),eo=M.makeMessageType(`livekit.UpdateLocalAudioTrack`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`features`,kind:`enum`,T:M.getEnumType(Ri),repeated:!0}]),to=M.makeMessageType(`livekit.UpdateLocalVideoTrack`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`width`,kind:`scalar`,T:13},{no:3,name:`height`,kind:`scalar`,T:13}]),no=M.makeMessageType(`livekit.LeaveRequest`,()=>[{no:1,name:`can_reconnect`,kind:`scalar`,T:8},{no:2,name:`reason`,kind:`enum`,T:M.getEnumType(Fi)},{no:3,name:`action`,kind:`enum`,T:M.getEnumType(ro)},{no:4,name:`regions`,kind:`message`,T:Oo}]),ro=M.makeEnum(`livekit.LeaveRequest.Action`,[{no:0,name:`DISCONNECT`},{no:1,name:`RESUME`},{no:2,name:`RECONNECT`}]),io=M.makeMessageType(`livekit.UpdateVideoLayers`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`layers`,kind:`message`,T:Xi,repeated:!0}]),ao=M.makeMessageType(`livekit.UpdateParticipantMetadata`,()=>[{no:1,name:`metadata`,kind:`scalar`,T:9},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:4,name:`request_id`,kind:`scalar`,T:13}]),oo=M.makeMessageType(`livekit.ICEServer`,()=>[{no:1,name:`urls`,kind:`scalar`,T:9,repeated:!0},{no:2,name:`username`,kind:`scalar`,T:9},{no:3,name:`credential`,kind:`scalar`,T:9}]),so=M.makeMessageType(`livekit.SpeakersChanged`,()=>[{no:1,name:`speakers`,kind:`message`,T:ra,repeated:!0}]),co=M.makeMessageType(`livekit.RoomUpdate`,()=>[{no:1,name:`room`,kind:`message`,T:zi}]),lo=M.makeMessageType(`livekit.ConnectionQualityInfo`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`quality`,kind:`enum`,T:M.getEnumType(Ni)},{no:3,name:`score`,kind:`scalar`,T:2}]),uo=M.makeMessageType(`livekit.ConnectionQualityUpdate`,()=>[{no:1,name:`updates`,kind:`message`,T:lo,repeated:!0}]),fo=M.makeMessageType(`livekit.StreamStateInfo`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sid`,kind:`scalar`,T:9},{no:3,name:`state`,kind:`enum`,T:M.getEnumType(Aa)}]),po=M.makeMessageType(`livekit.StreamStateUpdate`,()=>[{no:1,name:`stream_states`,kind:`message`,T:fo,repeated:!0}]),mo=M.makeMessageType(`livekit.SubscribedQuality`,()=>[{no:1,name:`quality`,kind:`enum`,T:M.getEnumType(Mi)},{no:2,name:`enabled`,kind:`scalar`,T:8}]),ho=M.makeMessageType(`livekit.SubscribedCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`qualities`,kind:`message`,T:mo,repeated:!0}]),go=M.makeMessageType(`livekit.SubscribedQualityUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_qualities`,kind:`message`,T:mo,repeated:!0},{no:3,name:`subscribed_codecs`,kind:`message`,T:ho,repeated:!0}]),_o=M.makeMessageType(`livekit.SubscribedAudioCodecUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_audio_codecs`,kind:`message`,T:Oa,repeated:!0}]),vo=M.makeMessageType(`livekit.TrackPermission`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`all_tracks`,kind:`scalar`,T:8},{no:3,name:`track_sids`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`participant_identity`,kind:`scalar`,T:9}]),yo=M.makeMessageType(`livekit.SubscriptionPermission`,()=>[{no:1,name:`all_participants`,kind:`scalar`,T:8},{no:2,name:`track_permissions`,kind:`message`,T:vo,repeated:!0}]),bo=M.makeMessageType(`livekit.SubscriptionPermissionUpdate`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sid`,kind:`scalar`,T:9},{no:3,name:`allowed`,kind:`scalar`,T:8}]),xo=M.makeMessageType(`livekit.RoomMovedResponse`,()=>[{no:1,name:`room`,kind:`message`,T:zi},{no:2,name:`token`,kind:`scalar`,T:9},{no:3,name:`participant`,kind:`message`,T:Hi},{no:4,name:`other_participants`,kind:`message`,T:Hi,repeated:!0}]),So=M.makeMessageType(`livekit.SyncState`,()=>[{no:1,name:`answer`,kind:`message`,T:Ja},{no:2,name:`subscription`,kind:`message`,T:Xa},{no:3,name:`publish_tracks`,kind:`message`,T:Ka,repeated:!0},{no:4,name:`data_channels`,kind:`message`,T:wo,repeated:!0},{no:5,name:`offer`,kind:`message`,T:Ja},{no:6,name:`track_sids_disabled`,kind:`scalar`,T:9,repeated:!0},{no:7,name:`datachannel_receive_states`,kind:`message`,T:Co,repeated:!0},{no:8,name:`publish_data_tracks`,kind:`message`,T:La,repeated:!0}]),Co=M.makeMessageType(`livekit.DataChannelReceiveState`,()=>[{no:1,name:`publisher_sid`,kind:`scalar`,T:9},{no:2,name:`last_seq`,kind:`scalar`,T:13}]),wo=M.makeMessageType(`livekit.DataChannelInfo`,()=>[{no:1,name:`label`,kind:`scalar`,T:9},{no:2,name:`id`,kind:`scalar`,T:13},{no:3,name:`target`,kind:`enum`,T:M.getEnumType(ka)}]),To=M.makeMessageType(`livekit.SimulateScenario`,()=>[{no:1,name:`speaker_update`,kind:`scalar`,T:5,oneof:`scenario`},{no:2,name:`node_failure`,kind:`scalar`,T:8,oneof:`scenario`},{no:3,name:`migration`,kind:`scalar`,T:8,oneof:`scenario`},{no:4,name:`server_leave`,kind:`scalar`,T:8,oneof:`scenario`},{no:5,name:`switch_candidate_protocol`,kind:`enum`,T:M.getEnumType(ja),oneof:`scenario`},{no:6,name:`subscriber_bandwidth`,kind:`scalar`,T:3,oneof:`scenario`},{no:7,name:`disconnect_signal_on_resume`,kind:`scalar`,T:8,oneof:`scenario`},{no:8,name:`disconnect_signal_on_resume_no_messages`,kind:`scalar`,T:8,oneof:`scenario`},{no:9,name:`leave_request_full_reconnect`,kind:`scalar`,T:8,oneof:`scenario`}]),Eo=M.makeMessageType(`livekit.Ping`,()=>[{no:1,name:`timestamp`,kind:`scalar`,T:3},{no:2,name:`rtt`,kind:`scalar`,T:3}]),Do=M.makeMessageType(`livekit.Pong`,()=>[{no:1,name:`last_ping_timestamp`,kind:`scalar`,T:3},{no:2,name:`timestamp`,kind:`scalar`,T:3}]),Oo=M.makeMessageType(`livekit.RegionSettings`,()=>[{no:1,name:`regions`,kind:`message`,T:ko,repeated:!0}]),ko=M.makeMessageType(`livekit.RegionInfo`,()=>[{no:1,name:`region`,kind:`scalar`,T:9},{no:2,name:`url`,kind:`scalar`,T:9},{no:3,name:`distance`,kind:`scalar`,T:3}]),Ao=M.makeMessageType(`livekit.SubscriptionResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`err`,kind:`enum`,T:M.getEnumType(Li)}]),jo=M.makeMessageType(`livekit.RequestResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`reason`,kind:`enum`,T:M.getEnumType(Mo)},{no:3,name:`message`,kind:`scalar`,T:9},{no:4,name:`trickle`,kind:`message`,T:Ha,oneof:`request`},{no:5,name:`add_track`,kind:`message`,T:Fa,oneof:`request`},{no:6,name:`mute`,kind:`message`,T:Ua,oneof:`request`},{no:7,name:`update_metadata`,kind:`message`,T:ao,oneof:`request`},{no:8,name:`update_audio_track`,kind:`message`,T:eo,oneof:`request`},{no:9,name:`update_video_track`,kind:`message`,T:to,oneof:`request`},{no:10,name:`publish_data_track`,kind:`message`,T:Ia,oneof:`request`},{no:11,name:`unpublish_data_track`,kind:`message`,T:Ra,oneof:`request`}]),Mo=M.makeEnum(`livekit.RequestResponse.Reason`,[{no:0,name:`OK`},{no:1,name:`NOT_FOUND`},{no:2,name:`NOT_ALLOWED`},{no:3,name:`LIMIT_EXCEEDED`},{no:4,name:`QUEUED`},{no:5,name:`UNSUPPORTED_TYPE`},{no:6,name:`UNCLASSIFIED_ERROR`},{no:7,name:`INVALID_HANDLE`},{no:8,name:`INVALID_NAME`},{no:9,name:`DUPLICATE_HANDLE`},{no:10,name:`DUPLICATE_NAME`}]),No=M.makeMessageType(`livekit.TrackSubscribed`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),Po=M.makeMessageType(`livekit.ConnectionSettings`,()=>[{no:1,name:`auto_subscribe`,kind:`scalar`,T:8},{no:2,name:`adaptive_stream`,kind:`scalar`,T:8},{no:3,name:`subscriber_allow_pause`,kind:`scalar`,T:8,opt:!0},{no:4,name:`disable_ice_lite`,kind:`scalar`,T:8},{no:5,name:`auto_subscribe_data_track`,kind:`scalar`,T:8,opt:!0}]),Fo=M.makeMessageType(`livekit.JoinRequest`,()=>[{no:1,name:`client_info`,kind:`message`,T:ga},{no:2,name:`connection_settings`,kind:`message`,T:Po},{no:3,name:`metadata`,kind:`scalar`,T:9},{no:4,name:`participant_attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:5,name:`add_track_requests`,kind:`message`,T:Fa,repeated:!0},{no:6,name:`publisher_offer`,kind:`message`,T:Ja},{no:7,name:`reconnect`,kind:`scalar`,T:8},{no:8,name:`reconnect_reason`,kind:`enum`,T:M.getEnumType(Ii)},{no:9,name:`participant_sid`,kind:`scalar`,T:9},{no:10,name:`sync_state`,kind:`message`,T:So}]),Io=M.makeMessageType(`livekit.WrappedJoinRequest`,()=>[{no:1,name:`compression`,kind:`enum`,T:M.getEnumType(Lo)},{no:2,name:`join_request`,kind:`scalar`,T:12}]),Lo=M.makeEnum(`livekit.WrappedJoinRequest.Compression`,[{no:0,name:`NONE`},{no:1,name:`GZIP`}]),Ro=M.makeMessageType(`livekit.MediaSectionsRequirement`,()=>[{no:1,name:`num_audios`,kind:`scalar`,T:13},{no:2,name:`num_videos`,kind:`scalar`,T:13}]);function zo(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var Bo={exports:{}},Vo=Bo.exports,Ho;function Uo(){return Ho?Bo.exports:(Ho=1,(function(e){(function(t,n){e.exports?e.exports=n():t.log=n()})(Vo,function(){var e=function(){},t=`undefined`,n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=[`trace`,`debug`,`info`,`warn`,`error`],i={},a=null;function o(e,t){var n=e[t];if(typeof n.bind==`function`)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch{return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(r){return r===`debug`&&(r=`log`),typeof console===t?!1:r===`trace`&&n?s:console[r]===void 0?console.log===void 0?e:o(console,`log`):o(console,r)}function l(){for(var n=this.getLevel(),i=0;i<r.length;i++){var a=r[i];this[a]=i<n?e:this.methodFactory(a,n,this.name)}if(this.log=this.debug,typeof console===t&&n<this.levels.SILENT)return`No console available for logging`}function u(e){return function(){typeof console!==t&&(l.call(this),this[e].apply(this,arguments))}}function d(e,t,n){return c(e)||u.apply(this,arguments)}function f(e,n){var o=this,s,c,u,f=`loglevel`;typeof e==`string`?f+=`:`+e:typeof e==`symbol`&&(f=void 0);function p(e){var n=(r[e]||`silent`).toUpperCase();if(!(typeof window===t||!f)){try{window.localStorage[f]=n;return}catch{}try{window.document.cookie=encodeURIComponent(f)+`=`+n+`;`}catch{}}}function m(){var e;if(!(typeof window===t||!f)){try{e=window.localStorage[f]}catch{}if(typeof e===t)try{var n=window.document.cookie,r=encodeURIComponent(f),i=n.indexOf(r+`=`);i!==-1&&(e=/^([^;]+)/.exec(n.slice(i+r.length+1))[1])}catch{}return o.levels[e]===void 0&&(e=void 0),e}}function h(){if(!(typeof window===t||!f)){try{window.localStorage.removeItem(f)}catch{}try{window.document.cookie=encodeURIComponent(f)+`=; expires=Thu, 01 Jan 1970 00:00:00 UTC`}catch{}}}function g(e){var t=e;if(typeof t==`string`&&o.levels[t.toUpperCase()]!==void 0&&(t=o.levels[t.toUpperCase()]),typeof t==`number`&&t>=0&&t<=o.levels.SILENT)return t;throw TypeError(`log.setLevel() called with invalid level: `+e)}o.name=e,o.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},o.methodFactory=n||d,o.getLevel=function(){return u??c??s},o.setLevel=function(e,t){return u=g(e),t!==!1&&p(u),l.call(o)},o.setDefaultLevel=function(e){c=g(e),m()||o.setLevel(e,!1)},o.resetLevel=function(){u=null,h(),l.call(o)},o.enableAll=function(e){o.setLevel(o.levels.TRACE,e)},o.disableAll=function(e){o.setLevel(o.levels.SILENT,e)},o.rebuild=function(){if(a!==o&&(s=g(a.getLevel())),l.call(o),a===o)for(var e in i)i[e].rebuild()},s=g(a?a.getLevel():`WARN`);var _=m();_!=null&&(u=g(_)),l.call(o)}a=new f,a.getLogger=function(e){if(typeof e!=`symbol`&&typeof e!=`string`||e===``)throw TypeError(`You must supply a name when creating a logger.`);var t=i[e];return t||=i[e]=new f(e,a.methodFactory),t};var p=typeof window===t?void 0:window.log;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=p),a},a.getLoggers=function(){return i},a.default=a,a})})(Bo),Bo.exports)}var Wo=Uo(),Go;(function(e){e[e.trace=0]=`trace`,e[e.debug=1]=`debug`,e[e.info=2]=`info`,e[e.warn=3]=`warn`,e[e.error=4]=`error`,e[e.silent=5]=`silent`})(Go||={});var Ko;(function(e){e.Default=`livekit`,e.Room=`livekit-room`,e.TokenSource=`livekit-token-source`,e.Participant=`livekit-participant`,e.Track=`livekit-track`,e.Publication=`livekit-track-publication`,e.Engine=`livekit-engine`,e.Signal=`livekit-signal`,e.PCManager=`livekit-pc-manager`,e.PCTransport=`livekit-pc-transport`,e.E2EE=`lk-e2ee`,e.DataTracks=`livekit-data-tracks`})(Ko||={});var P=Wo.getLogger(`livekit`);Object.values(Ko).map(e=>Wo.getLogger(e)),P.setDefaultLevel(Go.info);function qo(e){let t=Wo.getLogger(e);return t.setDefaultLevel(P.getLevel()),t}var Jo=Wo.getLogger(`lk-e2ee`),Yo=7e3,Xo=[0,300,4*300,9*300,16*300,Yo,Yo,Yo,Yo,Yo],Zo=class{constructor(e){this._retryDelays=e===void 0?Xo:[...e]}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;let t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}};function Qo(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function F(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function $o(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function es(e){return this instanceof es?(this.v=e,this):new es(e)}function ts(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),s(`next`),s(`throw`),s(`return`,o),i[Symbol.asyncIterator]=function(){return this},i;function o(e){return function(t){return Promise.resolve(t).then(e,d)}}function s(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof es?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function ns(e){var t,n;return t={},r(`next`),r(`throw`,function(e){throw e}),r(`return`),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:es(e[r](t)),done:!1}:i?i(t):t}:i}}function rs(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof $o==`function`?$o(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}var is={exports:{}},as;function os(){if(as)return is.exports;as=1;var e=typeof Reflect==`object`?Reflect:null,t=e&&typeof e.apply==`function`?e.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},n=e&&typeof e.ownKeys==`function`?e.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};function r(e){console&&console.warn&&console.warn(e)}var i=Number.isNaN||function(e){return e!==e};function a(){a.init.call(this)}is.exports=a,is.exports.once=_,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var o=10;function s(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(a,`defaultMaxListeners`,{enumerable:!0,get:function(){return o},set:function(e){if(typeof e!=`number`||e<0||i(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);o=e}}),a.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},a.prototype.setMaxListeners=function(e){if(typeof e!=`number`||e<0||i(e))throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+e+`.`);return this._maxListeners=e,this};function c(e){return e._maxListeners===void 0?a.defaultMaxListeners:e._maxListeners}a.prototype.getMaxListeners=function(){return c(this)},a.prototype.emit=function(e){for(var n=[],r=1;r<arguments.length;r++)n.push(arguments[r]);var i=e===`error`,a=this._events;if(a!==void 0)i&&=a.error===void 0;else if(!i)return!1;if(i){var o;if(n.length>0&&(o=n[0]),o instanceof Error)throw o;var s=Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)t(c,this,n);else for(var l=c.length,u=m(c,l),r=0;r<l;++r)t(u[r],this,n);return!0};function l(e,t,n,i){var a,o,l;if(s(n),o=e._events,o===void 0?(o=e._events=Object.create(null),e._eventsCount=0):(o.newListener!==void 0&&(e.emit(`newListener`,t,n.listener?n.listener:n),o=e._events),l=o[t]),l===void 0)l=o[t]=n,++e._eventsCount;else if(typeof l==`function`?l=o[t]=i?[n,l]:[l,n]:i?l.unshift(n):l.push(n),a=c(e),a>0&&l.length>a&&!l.warned){l.warned=!0;var u=Error(`Possible EventEmitter memory leak detected. `+l.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);u.name=`MaxListenersExceededWarning`,u.emitter=e,u.type=t,u.count=l.length,r(u)}return e}a.prototype.addListener=function(e,t){return l(this,e,t,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(e,t){return l(this,e,t,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=u.bind(r);return i.listener=n,r.wrapFn=i,i}a.prototype.once=function(e,t){return s(t),this.on(e,d(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){return s(t),this.prependListener(e,d(this,e,t)),this},a.prototype.removeListener=function(e,t){var n,r,i,a,o;if(s(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():h(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||t)}return this},a.prototype.off=a.prototype.removeListener,a.prototype.removeAllListeners=function(e){var t,n=this._events,r;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),a;for(r=0;r<i.length;++r)a=i[r],a!==`removeListener`&&this.removeAllListeners(a);return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t==`function`)this.removeListener(e,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this};function f(e,t,n){var r=e._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?g(i):m(i,i.length)}a.prototype.listeners=function(e){return f(this,e,!0)},a.prototype.rawListeners=function(e){return f(this,e,!1)},a.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):p.call(e,t)},a.prototype.listenerCount=p;function p(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}a.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function m(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function h(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function g(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function _(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){typeof e.removeListener==`function`&&e.removeListener(`error`,i),n([].slice.call(arguments))}y(e,t,a,{once:!0}),t!==`error`&&v(e,i,{once:!0})})}function v(e,t,n){typeof e.on==`function`&&y(e,`error`,t,n)}function y(e,t,n,r){if(typeof e.on==`function`)r.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener==`function`)e.addEventListener(t,function i(a){r.once&&e.removeEventListener(t,i),n(a)});else throw TypeError(`The "emitter" argument must be of type EventEmitter. Received type `+typeof e)}return is.exports}var ss=os(),cs=!0,ls=!0;function us(e,t,n){let r=e.match(t);return r&&r.length>=n&&parseFloat(r[n],10)}function ds(e,t,n){if(!e.RTCPeerConnection)return;let r=e.RTCPeerConnection.prototype,i=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return i.apply(this,arguments);let a=e=>{let t=n(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,a),i.apply(this,[e,a])};let a=r.removeEventListener;r.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t]||!this._eventMap[t].has(n))return a.apply(this,arguments);let r=this._eventMap[t].get(n);return this._eventMap[t].delete(n),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,a.apply(this,[e,r])},Object.defineProperty(r,`on`+t,{get(){return this[`_on`+t]},set(e){this[`_on`+t]&&(this.removeEventListener(t,this[`_on`+t]),delete this[`_on`+t]),e&&this.addEventListener(t,this[`_on`+t]=e)},enumerable:!0,configurable:!0})}function fs(e){return typeof e==`boolean`?(cs=e,e?`adapter.js logging disabled`:`adapter.js logging enabled`):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function ps(e){return typeof e==`boolean`?(ls=!e,`adapter.js deprecation warnings `+(e?`disabled`:`enabled`)):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function ms(){if(typeof window==`object`){if(cs)return;typeof console<`u`&&typeof console.log==`function`&&console.log.apply(console,arguments)}}function hs(e,t){ls&&console.warn(e+` is deprecated, please use `+t+` instead.`)}function gs(e){let t={browser:null,version:null};if(e===void 0||!e.navigator||!e.navigator.userAgent)return t.browser=`Not a browser.`,t;let{navigator:n}=e;if(n.userAgentData&&n.userAgentData.brands){let e=n.userAgentData.brands.find(e=>e.brand===`Chromium`);if(e)return{browser:`chrome`,version:parseInt(e.version,10)}}if(n.mozGetUserMedia)t.browser=`firefox`,t.version=parseInt(us(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||e.isSecureContext===!1&&e.webkitRTCPeerConnection)t.browser=`chrome`,t.version=parseInt(us(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(e.RTCPeerConnection&&n.userAgent.match(/AppleWebKit\/(\d+)\./))t.browser=`safari`,t.version=parseInt(us(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&`currentDirection`in e.RTCRtpTransceiver.prototype,t._safariVersion=us(n.userAgent,/Version\/(\d+(\.?\d+))/,1);else return t.browser=`Not a supported browser.`,t;return t}function _s(e){return Object.prototype.toString.call(e)===`[object Object]`}function vs(e){return _s(e)?Object.keys(e).reduce(function(t,n){let r=_s(e[n]),i=r?vs(e[n]):e[n],a=r&&!Object.keys(i).length;return i===void 0||a?t:Object.assign(t,{[n]:i})},{}):e}function ys(e,t,n){!t||n.has(t.id)||(n.set(t.id,t),Object.keys(t).forEach(r=>{r.endsWith(`Id`)?ys(e,e.get(t[r]),n):r.endsWith(`Ids`)&&t[r].forEach(t=>{ys(e,e.get(t),n)})}))}function bs(e,t,n){let r=n?`outbound-rtp`:`inbound-rtp`,i=new Map;if(t===null)return i;let a=[];return e.forEach(e=>{e.type===`track`&&e.trackIdentifier===t.id&&a.push(e)}),a.forEach(t=>{e.forEach(n=>{n.type===r&&n.trackId===t.id&&ys(e,n,i)})}),i}var xs=ms;function Ss(e,t){let n=e&&e.navigator;if(!n.mediaDevices)return;let r=function(e){if(typeof e!=`object`||e.mandatory||e.optional)return e;let t={};return Object.keys(e).forEach(n=>{if(n===`require`||n===`advanced`||n===`mediaSource`)return;let r=typeof e[n]==`object`?e[n]:{ideal:e[n]};r.exact!==void 0&&typeof r.exact==`number`&&(r.min=r.max=r.exact);let i=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):t===`deviceId`?`sourceId`:t};if(r.ideal!==void 0){t.optional=t.optional||[];let e={};typeof r.ideal==`number`?(e[i(`min`,n)]=r.ideal,t.optional.push(e),e={},e[i(`max`,n)]=r.ideal,t.optional.push(e)):(e[i(``,n)]=r.ideal,t.optional.push(e))}r.exact!==void 0&&typeof r.exact!=`number`?(t.mandatory=t.mandatory||{},t.mandatory[i(``,n)]=r.exact):[`min`,`max`].forEach(e=>{r[e]!==void 0&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,n)]=r[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},i=function(e,i){if(t.version>=61)return i(e);if(e=JSON.parse(JSON.stringify(e)),e&&typeof e.audio==`object`){let t=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};e=JSON.parse(JSON.stringify(e)),t(e.audio,`autoGainControl`,`googAutoGainControl`),t(e.audio,`noiseSuppression`,`googNoiseSuppression`),e.audio=r(e.audio)}if(e&&typeof e.video==`object`){let a=e.video.facingMode;a&&=typeof a==`object`?a:{ideal:a};let o=t.version<66;if(a&&(a.exact===`user`||a.exact===`environment`||a.ideal===`user`||a.ideal===`environment`)&&!(n.mediaDevices.getSupportedConstraints&&n.mediaDevices.getSupportedConstraints().facingMode&&!o)){delete e.video.facingMode;let t;if(a.exact===`environment`||a.ideal===`environment`?t=[`back`,`rear`]:(a.exact===`user`||a.ideal===`user`)&&(t=[`front`]),t)return n.mediaDevices.enumerateDevices().then(n=>{n=n.filter(e=>e.kind===`videoinput`);let o=n.find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!o&&n.length&&t.includes(`back`)&&(o=n[n.length-1]),o&&(e.video.deviceId=a.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=r(e.video),xs(`chrome: `+JSON.stringify(e)),i(e)})}e.video=r(e.video)}return xs(`chrome: `+JSON.stringify(e)),i(e)},a=function(e){return t.version>=64?e:{name:{PermissionDeniedError:`NotAllowedError`,PermissionDismissedError:`NotAllowedError`,InvalidStateError:`NotAllowedError`,DevicesNotFoundError:`NotFoundError`,ConstraintNotSatisfiedError:`OverconstrainedError`,TrackStartError:`NotReadableError`,MediaDeviceFailedDueToShutdown:`NotAllowedError`,MediaDeviceKillSwitchOn:`NotAllowedError`,TabCaptureError:`AbortError`,ScreenCaptureError:`AbortError`,DeviceCaptureError:`AbortError`}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&`: `)+this.message}}};if(n.getUserMedia=function(e,t,r){i(e,e=>{n.webkitGetUserMedia(e,t,e=>{r&&r(a(e))})})}.bind(n),n.mediaDevices.getUserMedia){let e=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(t){return i(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException(``,`NotFoundError`);return e},e=>Promise.reject(a(e))))}}}function Cs(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function ws(e){if(typeof e==`object`&&e.RTCPeerConnection&&!(`ontrack`in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,`ontrack`,{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener(`track`,this._ontrack),this.addEventListener(`track`,this._ontrack=e)},enumerable:!0,configurable:!0});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener(`addtrack`,n=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.track.id):{track:n.track};let i=new Event(`track`);i.track=n.track,i.receiver=r,i.transceiver={receiver:r},i.streams=[t.stream],this.dispatchEvent(i)}),t.stream.getTracks().forEach(n=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.id):{track:n};let i=new Event(`track`);i.track=n,i.receiver=r,i.transceiver={receiver:r},i.streams=[t.stream],this.dispatchEvent(i)})},this.addEventListener(`addstream`,this._ontrackpoly)),t.apply(this,arguments)}}else ds(e,`track`,e=>(e.transceiver||Object.defineProperty(e,`transceiver`,{value:{receiver:e.receiver}}),e))}function Ts(e){if(typeof e==`object`&&e.RTCPeerConnection&&!(`getSenders`in e.RTCPeerConnection.prototype)&&`createDTMFSender`in e.RTCPeerConnection.prototype){let t=function(e,t){return{track:t,get dtmf(){return this._dtmf===void 0&&(t.kind===`audio`?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){let i=n.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};let r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){r.apply(this,arguments);let t=this._senders.indexOf(e);t!==-1&&this._senders.splice(t,1)}}let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach(e=>{let t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if(typeof e==`object`&&e.RTCPeerConnection&&`getSenders`in e.RTCPeerConnection.prototype&&`createDTMFSender`in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!(`dtmf`in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,`dtmf`,{get(){return this._dtmf===void 0&&(this.track.kind===`audio`?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Es(e){if(!(typeof e==`object`&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!(`getStats`in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>bs(t,e.track,!0))}}if(!(`getStats`in e.RTCRtpReceiver.prototype)){let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),ds(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>bs(t,e.track,!1))}}if(!(`getStats`in e.RTCRtpSender.prototype&&`getStats`in e.RTCRtpReceiver.prototype))return;let t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){let e=arguments[0],t,n,r;return this.getSenders().forEach(n=>{n.track===e&&(t?r=!0:t=n)}),this.getReceivers().forEach(t=>(t.track===e&&(n?r=!0:n=t),t.track===e)),r||t&&n?Promise.reject(new DOMException(`There are more than one sender or receiver for the track.`,`InvalidAccessError`)):t?t.getStats():n?n.getStats():Promise.reject(new DOMException(`There is no sender or receiver for the track.`,`InvalidAccessError`))}return t.apply(this,arguments)}}function Ds(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let r=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?this._shimmedLocalStreams[n.id].indexOf(r)===-1&&this._shimmedLocalStreams[n.id].push(r):this._shimmedLocalStreams[n.id]=[n,r],r};let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException(`Track already exists.`,`InvalidAccessError`)});let t=this.getSenders();n.apply(this,arguments);let r=this.getSenders().filter(e=>t.indexOf(e)===-1);this._shimmedLocalStreams[e.id]=[e].concat(r)};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};let i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{let n=this._shimmedLocalStreams[t].indexOf(e);n!==-1&&this._shimmedLocalStreams[t].splice(n,1),this._shimmedLocalStreams[t].length===1&&delete this._shimmedLocalStreams[t]}),i.apply(this,arguments)}}function Os(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Ds(e);let n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let e=n.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};let r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException(`Track already exists.`,`InvalidAccessError`)}),!this._reverseStreams[t.id]){let n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}r.apply(this,[t])};let i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,n){if(this.signalingState===`closed`)throw new DOMException(`The RTCPeerConnection's signalingState is 'closed'.`,`InvalidStateError`);let r=[].slice.call(arguments,1);if(r.length!==1||!r[0].getTracks().find(e=>e===t))throw new DOMException(`The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.`,`NotSupportedError`);if(this.getSenders().find(e=>e.track===t))throw new DOMException(`Track already exists.`,`InvalidAccessError`);this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let i=this._streams[n.id];if(i)i.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event(`negotiationneeded`))});else{let r=new e.MediaStream([t]);this._streams[n.id]=r,this._reverseStreams[r.id]=n,this.addStream(r)}return this.getSenders().find(e=>e.track===t)};function a(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(i.id,`g`),r.id)}),new RTCSessionDescription({type:t.type,sdp:n})}function o(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(r.id,`g`),i.id)}),new RTCSessionDescription({type:t.type,sdp:n})}[`createOffer`,`createAnswer`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){let e=arguments;return arguments.length&&typeof arguments[0]==`function`?n.apply(this,[t=>{let n=a(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then(e=>a(this,e))}};e.RTCPeerConnection.prototype[t]=r[t]});let s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type||(arguments[0]=o(this,arguments[0])),s.apply(this,arguments)};let c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,`localDescription`);Object.defineProperty(e.RTCPeerConnection.prototype,`localDescription`,{get(){let e=c.get.apply(this);return e.type===``?e:a(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if(this.signalingState===`closed`)throw new DOMException(`The RTCPeerConnection's signalingState is 'closed'.`,`InvalidStateError`);if(!e._pc)throw new DOMException(`Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.`,`TypeError`);if(e._pc!==this)throw new DOMException(`Sender was not created by this connection.`,`InvalidAccessError`);this._streams=this._streams||{};let t;Object.keys(this._streams).forEach(n=>{this._streams[n].getTracks().find(t=>e.track===t)&&(t=this._streams[n])}),t&&(t.getTracks().length===1?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event(`negotiationneeded`)))}}function ks(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&[`setLocalDescription`,`setRemoteDescription`,`addIceCandidate`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t===`addIceCandidate`?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]})}function As(e,t){ds(e,`negotiationneeded`,e=>{let n=e.target;if(!((t.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics===`plan-b`)&&n.signalingState!==`stable`))return e})}var js=Object.freeze({__proto__:null,fixNegotiationNeeded:As,shimAddTrackRemoveTrack:Os,shimAddTrackRemoveTrackWithNative:Ds,shimGetSendersWithDtmf:Ts,shimGetUserMedia:Ss,shimMediaStream:Cs,shimOnTrack:ws,shimPeerConnection:ks,shimSenderReceiverGetStats:Es});function Ms(e,t){let n=e&&e.navigator,r=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,r){hs(`navigator.getUserMedia`,`navigator.mediaDevices.getUserMedia`),n.mediaDevices.getUserMedia(e).then(t,r)},!(t.version>55&&`autoGainControl`in n.mediaDevices.getSupportedConstraints())){let e=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},t=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(n){return typeof n==`object`&&typeof n.audio==`object`&&(n=JSON.parse(JSON.stringify(n)),e(n.audio,`autoGainControl`,`mozAutoGainControl`),e(n.audio,`noiseSuppression`,`mozNoiseSuppression`)),t(n)},r&&r.prototype.getSettings){let t=r.prototype.getSettings;r.prototype.getSettings=function(){let n=t.apply(this,arguments);return e(n,`mozAutoGainControl`,`autoGainControl`),e(n,`mozNoiseSuppression`,`noiseSuppression`),n}}if(r&&r.prototype.applyConstraints){let t=r.prototype.applyConstraints;r.prototype.applyConstraints=function(n){return this.kind===`audio`&&typeof n==`object`&&(n=JSON.parse(JSON.stringify(n)),e(n,`autoGainControl`,`mozAutoGainControl`),e(n,`noiseSuppression`,`mozNoiseSuppression`)),t.apply(this,[n])}}}}function Ns(e,t){e.navigator.mediaDevices&&`getDisplayMedia`in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){let e=new DOMException(`getDisplayMedia without video constraints is undefined`);return e.name=`NotFoundError`,e.code=8,Promise.reject(e)}return n.video===!0?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)})}function Ps(e){typeof e==`object`&&e.RTCTrackEvent&&`receiver`in e.RTCTrackEvent.prototype&&!(`transceiver`in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,`transceiver`,{get(){return{receiver:this.receiver}}})}function Fs(e,t){if(typeof e!=`object`||!(e.RTCPeerConnection||e.mozRTCPeerConnection))return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&[`setLocalDescription`,`setRemoteDescription`,`addIceCandidate`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t===`addIceCandidate`?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]});let n={inboundrtp:`inbound-rtp`,outboundrtp:`outbound-rtp`,candidatepair:`candidate-pair`,localcandidate:`local-candidate`,remotecandidate:`remote-candidate`},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let[e,i,a]=arguments;return r.apply(this,[e||null]).then(e=>{if(t.version<53&&!i)try{e.forEach(e=>{e.type=n[e.type]||e.type})}catch(t){if(t.name!==`TypeError`)throw t;e.forEach((t,r)=>{e.set(r,Object.assign({},t,{type:n[t.type]||t.type}))})}return e}).then(i,a)}}function Is(e){if(!(typeof e==`object`&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&`getStats`in e.RTCRtpSender.prototype)return;let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Ls(e){if(!(typeof e==`object`&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&`getStats`in e.RTCRtpReceiver.prototype)return;let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),ds(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Rs(e){!e.RTCPeerConnection||`removeStream`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){hs(`removeStream`,`removeTrack`),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function zs(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Bs(e){if(!(typeof e==`object`&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;e===void 0&&(e=[]),e=[...e];let n=e.length>0;n&&e.forEach(e=>{if(`rid`in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw TypeError(`Invalid RID value provided.`);if(`scaleResolutionDownBy`in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw RangeError(`scale_resolution_down_by must be >= 1.0`);if(`maxFramerate`in e&&!(parseFloat(e.maxFramerate)>=0))throw RangeError(`max_framerate must be >= 0.0`)});let r=t.apply(this,arguments);if(n){let{sender:t}=r,n=t.getParameters();(!(`encodings`in n)||n.encodings.length===1&&Object.keys(n.encodings[0]).length===0)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return r})}function Vs(e){if(!(typeof e==`object`&&e.RTCRtpSender))return;let t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){let e=t.apply(this,arguments);return`encodings`in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Hs(e){if(!(typeof e==`object`&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function Us(e){if(!(typeof e==`object`&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var Ws=Object.freeze({__proto__:null,shimAddTransceiver:Bs,shimCreateAnswer:Us,shimCreateOffer:Hs,shimGetDisplayMedia:Ns,shimGetParameters:Vs,shimGetUserMedia:Ms,shimOnTrack:Ps,shimPeerConnection:Fs,shimRTCDataChannel:zs,shimReceiverGetStats:Ls,shimRemoveStream:Rs,shimSenderGetStats:Is});function Gs(e){if(!(typeof e!=`object`||!e.RTCPeerConnection)){if(`getLocalStreams`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||=[],this._localStreams}),!(`addStream`in e.RTCPeerConnection.prototype)){let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||=[],this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(n=>t.call(this,n,e)),e.getVideoTracks().forEach(n=>t.call(this,n,e))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var n=arguments.length,r=Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return r&&r.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}`removeStream`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||=[];let t=this._localStreams.indexOf(e);if(t===-1)return;this._localStreams.splice(t,1);let n=e.getTracks();this.getSenders().forEach(e=>{n.includes(e.track)&&this.removeTrack(e)})})}}function Ks(e){if(!(typeof e!=`object`||!e.RTCPeerConnection)&&(`getRemoteStreams`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!(`onaddstream`in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,`onaddstream`,{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener(`addstream`,this._onaddstream),this.removeEventListener(`track`,this._onaddstreampoly)),this.addEventListener(`addstream`,this._onaddstream=e),this.addEventListener(`track`,this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||=[],this._remoteStreams.includes(e))return;this._remoteStreams.push(e);let t=new Event(`addstream`);t.stream=e,this.dispatchEvent(t)})})}});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){let e=this;return this._onaddstreampoly||this.addEventListener(`track`,this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||=[],e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);let n=new Event(`addstream`);n.stream=t,e.dispatchEvent(n)})}),t.apply(e,arguments)}}}function qs(e){if(typeof e!=`object`||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype,n=t.createOffer,r=t.createAnswer,i=t.setLocalDescription,a=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){let r=arguments.length>=2?arguments[2]:arguments[0],i=n.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){let n=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[n]);return t?(i.then(e,t),Promise.resolve()):i};let s=function(e,t,n){let r=i.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r};t.setLocalDescription=s,s=function(e,t,n){let r=a.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},t.setRemoteDescription=s,s=function(e,t,n){let r=o.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},t.addIceCandidate=s}function Js(e){let t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){let e=t.mediaDevices,n=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>n(Ys(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,r){t.mediaDevices.getUserMedia(e).then(n,r)}.bind(t))}function Ys(e){return e&&e.video!==void 0?Object.assign({},e,{video:vs(e.video)}):e}function Xs(e){if(!e.RTCPeerConnection)return;let t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){let t=[];for(let n=0;n<e.iceServers.length;n++){let r=e.iceServers[n];r.urls===void 0&&r.url?(hs(`RTCIceServer.url`,`RTCIceServer.urls`),r=JSON.parse(JSON.stringify(r)),r.urls=r.url,delete r.url,t.push(r)):t.push(e.iceServers[n])}e.iceServers=t}return new t(e,n)},e.RTCPeerConnection.prototype=t.prototype,`generateCertificate`in t&&Object.defineProperty(e.RTCPeerConnection,`generateCertificate`,{get(){return t.generateCertificate}})}function Zs(e){typeof e==`object`&&e.RTCTrackEvent&&`receiver`in e.RTCTrackEvent.prototype&&!(`transceiver`in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,`transceiver`,{get(){return{receiver:this.receiver}}})}function Qs(e){let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){e.offerToReceiveAudio!==void 0&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);let t=this.getTransceivers().find(e=>e.receiver.track.kind===`audio`);e.offerToReceiveAudio===!1&&t?t.direction===`sendrecv`?t.setDirection?t.setDirection(`sendonly`):t.direction=`sendonly`:t.direction===`recvonly`&&(t.setDirection?t.setDirection(`inactive`):t.direction=`inactive`):e.offerToReceiveAudio===!0&&!t&&this.addTransceiver(`audio`,{direction:`recvonly`}),e.offerToReceiveVideo!==void 0&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);let n=this.getTransceivers().find(e=>e.receiver.track.kind===`video`);e.offerToReceiveVideo===!1&&n?n.direction===`sendrecv`?n.setDirection?n.setDirection(`sendonly`):n.direction=`sendonly`:n.direction===`recvonly`&&(n.setDirection?n.setDirection(`inactive`):n.direction=`inactive`):e.offerToReceiveVideo===!0&&!n&&this.addTransceiver(`video`,{direction:`recvonly`})}return t.apply(this,arguments)}}function $s(e){typeof e!=`object`||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var ec=Object.freeze({__proto__:null,shimAudioContext:$s,shimCallbacksAPI:qs,shimConstraints:Ys,shimCreateOfferLegacy:Qs,shimGetUserMedia:Js,shimLocalStreamsAPI:Gs,shimRTCIceServerUrls:Xs,shimRemoteStreamsAPI:Ks,shimTrackEventTransceiver:Zs}),tc={exports:{}},nc;function rc(){return nc?tc.exports:(nc=1,(function(e){let t={};t.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split(`
|
|
1
|
+
"use client";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(e&&(t=e(e=0)),t),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,a)=>(a=n==null?{}:e(i(n)),c(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n)),u=e=>a.call(e,`module.exports`)?e[`module.exports`]:c(t({},`__esModule`,{value:!0}),e);let d=require(`react`);d=l(d);let f=require(`react/jsx-runtime`);var p=e=>{if(!e||typeof e!=`object`)throw Error(`FlowEngage config is required`);if(!e.siteId||typeof e.siteId!=`string`)throw Error(`[FlowEngage] config.siteId is required. Pass it as <FlowEngageProvider siteId="your-site-id" /> or config={{ siteId: 'your-site-id' }}.`);let t=(e.apiBaseUrl||`https://be-flowengage-dev.oslabs.app`).replace(/\/+$/,``);return{siteId:e.siteId.trim(),apiBaseUrl:t}},m=(e,t)=>{let n=Number.parseInt(String(e??``),10);return Number.isFinite(n)&&n>0?n:t},h=m(void 0,1e4),g=m(void 0,15e3),_={chatId:`flowengage.chatId`,isOpen:`flowengage.isOpen`,activeScreen:`flowengage.activeScreen`,isHumanHandled:`flowengage.isHumanHandled`,agentName:`flowengage.agentName`,agentHeadshot:`flowengage.agentHeadshot`,visitorEmail:`flowengage.visitorEmail`},v=6e4,y=480*60,b=3e4,x=typeof window<`u`,S=e=>e?`flowengage.visitorEmail.${e}`:null,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,ie=e=>{if(!x||!e)return!1;try{let t=re(e);return t?window.localStorage.getItem(t)===`1`:!1}catch{return!1}},ae=e=>{if(!(!x||!e))try{let t=re(e);t&&window.localStorage.setItem(t,`1`)}catch{}},oe=e=>e?`flowengage.persistedChatId.${e}`:null,se=e=>{if(!x||!e)return null;try{let t=oe(e),n=t?window.localStorage.getItem(t):null;return n&&String(n).trim()?String(n).trim():null}catch{return null}},ce=e=>{if(!(!x||!e))try{let t=oe(e);t&&window.localStorage.removeItem(t)}catch{}},le=(e,t)=>{if(!(!x||!e||!t))try{let n=oe(e);n&&window.localStorage.setItem(n,String(t).trim())}catch{}},C=()=>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,w=(e,t,n,r)=>{if(!(!x||!e||!t))try{let i=je(e);i&&window.sessionStorage.setItem(i,JSON.stringify({previousPage:String(t),targetPath:n?new URL(String(n),window.location.href).pathname:null,pageName:r||null,ts:Date.now()}))}catch{}},Me=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,pageName:r.pageName||null}}catch{return null}},Ne=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},Pe=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}},Fe=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),Ne(await Pe(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)}))},Ie=async({apiBaseUrl:e,siteId:t})=>{let n=typeof window<`u`?window.location.origin:`http://localhost`;return(await Ne(await Pe(`${e}/api/widget/chatbot-loader?${new URLSearchParams({siteId:t,origin:n}).toString()}`,{method:`GET`}))).data},Le=({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={})=>Ne(await Pe(`${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 Ne(await Pe(`${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 Ne(await Pe(`${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)}}},Re=Object.create(null);Re.open=`0`,Re.close=`1`,Re.ping=`2`,Re.pong=`3`,Re.message=`4`,Re.upgrade=`5`,Re.noop=`6`;var ze=Object.create(null);Object.keys(Re).forEach(e=>{ze[Re[e]]=e});var Be={type:`error`,data:`parser error`},Ve=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,He=typeof ArrayBuffer==`function`,Ue=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,We=({type:e,data:t},n,r)=>Ve&&t instanceof Blob?n?r(t):T(t,r):He&&(t instanceof ArrayBuffer||Ue(t))?n?r(t):T(new Blob([t]),r):r(Re[e]+(t||``)),T=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function Ge(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var Ke;function qe(e,t){if(Ve&&e.data instanceof Blob)return e.data.arrayBuffer().then(Ge).then(t);if(He&&(e.data instanceof ArrayBuffer||Ue(e.data)))return t(Ge(e.data));We(e,!1,e=>{Ke||=new TextEncoder,t(Ke.encode(e))})}var Je=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Ye=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)Ye[Je.charCodeAt(e)]=e;var Xe=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=Ye[e.charCodeAt(r)],o=Ye[e.charCodeAt(r+1)],s=Ye[e.charCodeAt(r+2)],c=Ye[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},Ze=typeof ArrayBuffer==`function`,Qe=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:et(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:$e(e.substring(1),t)}:ze[n]?e.length>1?{type:ze[n],data:e.substring(1)}:{type:ze[n]}:Be},$e=(e,t)=>Ze?et(Xe(e),t):{base64:!0,data:e},et=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},tt=``,nt=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{We(e,!1,e=>{r[a]=e,++i===n&&t(r.join(tt))})})},rt=(e,t)=>{let n=e.split(tt),r=[];for(let e=0;e<n.length;e++){let i=Qe(n[e],t);if(r.push(i),i.type===`error`)break}return r};function E(){return new TransformStream({transform(e,t){qe(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 D;function it(e){return e.reduce((e,t)=>e+t.length,0)}function at(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 ot(e,t){D||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(it(n)<1)break;let e=at(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(it(n)<2)break;let e=at(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(it(n)<8)break;let e=at(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(Be);break}i=a*2**32+t.getUint32(4),r=3}else{if(it(n)<i)break;let e=at(n,i);s.enqueue(Qe(a?e:D.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(Be);break}}}})}function O(e){if(e)return st(e)}function st(e){for(var t in O.prototype)e[t]=O.prototype[t];return e}O.prototype.on=O.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},O.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},O.prototype.off=O.prototype.removeListener=O.prototype.removeAllListeners=O.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},O.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},O.prototype.emitReserved=O.prototype.emit,O.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},O.prototype.hasListeners=function(e){return!!this.listeners(e).length};var k=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),A=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),ct=`arraybuffer`;function lt(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var ut=A.setTimeout,dt=A.clearTimeout;function ft(e,t){t.useNativeTimers?(e.setTimeoutFn=ut.bind(A),e.clearTimeoutFn=dt.bind(A)):(e.setTimeoutFn=A.setTimeout.bind(A),e.clearTimeoutFn=A.clearTimeout.bind(A))}var pt=1.33;function mt(e){return typeof e==`string`?ht(e):Math.ceil((e.byteLength||e.size)*pt)}function ht(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 gt(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function _t(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function vt(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 yt=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},bt=class extends O{constructor(e){super(),this.writable=!1,ft(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 yt(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=Qe(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=_t(e);return t.length?`?`+t:``}},xt=class extends bt{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){rt(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,nt(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]=gt()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},St=!1;try{St=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var Ct=St;function wt(){}var Tt=class extends xt{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}},Et=class e extends O{constructor(e,t,n){super(),this.createRequest=e,ft(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=lt(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=wt,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(Et.requestsCount=0,Et.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,Dt);else if(typeof addEventListener==`function`){let e=`onpagehide`in A?`pagehide`:`unload`;addEventListener(e,Dt,!1)}}function Dt(){for(let e in Et.requests)Et.requests.hasOwnProperty(e)&&Et.requests[e].abort()}var Ot=(function(){let e=At({xdomain:!1});return e&&e.responseType!==null})(),kt=class extends Tt{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=Ot&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Et(At,this.uri(),e)}};function At(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||Ct))return new XMLHttpRequest}catch{}if(!t)try{return new A[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var jt=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,Mt=class extends bt{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=jt?{}:lt(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;We(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&k(()=>{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]=gt()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},Nt=A.WebSocket||A.MozWebSocket,Pt={websocket:class extends Mt{createSocket(e,t,n){return jt?new Nt(e,t,n):t?new Nt(e,t):new Nt(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends bt{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=ot(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=E();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&&k(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:kt},Ft=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,It=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function Lt(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=Ft.exec(e||``),a={},o=14;for(;o--;)a[It[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=Rt(a,a.path),a.queryKey=zt(a,a.query),a}function Rt(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 zt(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var Bt=typeof addEventListener==`function`&&typeof removeEventListener==`function`,Vt=[];Bt&&addEventListener(`offline`,()=>{Vt.forEach(e=>e())},!1);var Ht=class e extends O{constructor(e,t){if(super(),this.binaryType=ct,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=Lt(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=Lt(t.host).host);ft(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=vt(this.opts.query)),Bt&&(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`})},Vt.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+=mt(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,k(()=>{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(),Bt&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=Vt.indexOf(this._offlineEventListener);e!==-1&&Vt.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};Ht.protocol=4;var Ut=class extends Ht{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;Ht.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;Ht.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}},Wt=class extends Ut{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=>Pt[e]).filter(e=>!!e)),super(e,n)}};Wt.protocol;function Gt(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=Lt(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 Kt=typeof ArrayBuffer==`function`,qt=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,Jt=Object.prototype.toString,Yt=typeof Blob==`function`||typeof Blob<`u`&&Jt.call(Blob)===`[object BlobConstructor]`,Xt=typeof File==`function`||typeof File<`u`&&Jt.call(File)===`[object FileConstructor]`;function Zt(e){return Kt&&(e instanceof ArrayBuffer||qt(e))||Yt&&e instanceof Blob||Xt&&e instanceof File}function Qt(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(Qt(e[t]))return!0;return!1}if(Zt(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return Qt(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Qt(e[t]))return!0;return!1}function $t(e){let t=[],n=e.data,r=e;return r.data=en(n,t),r.attachments=t.length,{packet:r,buffers:t}}function en(e,t){if(!e)return e;if(Zt(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]=en(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]=en(e[r],t));return n}return e}function tn(e,t){return e.data=nn(e.data,t),delete e.attachments,e}function nn(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]=nn(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=nn(e[n],t));return e}var rn=s({Decoder:()=>sn,Encoder:()=>on,PacketType:()=>j,isPacketValid:()=>mn,protocol:()=>5}),an=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],j;(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`})(j||={});var on=class{constructor(e){this.replacer=e}encode(e){return(e.type===j.EVENT||e.type===j.ACK)&&Qt(e)?this.encodeAsBinary({type:e.type===j.EVENT?j.BINARY_EVENT:j.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===j.BINARY_EVENT||e.type===j.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=$t(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},sn=class e extends O{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===j.BINARY_EVENT;n||t.type===j.BINARY_ACK?(t.type=n?j.EVENT:j.ACK,this.reconstructor=new cn(t),t.attachments===0&&super.emitReserved(`decoded`,t)):super.emitReserved(`decoded`,t)}else if(Zt(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(j[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===j.BINARY_EVENT||r.type===j.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(!un(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 j.CONNECT:return fn(t);case j.DISCONNECT:return t===void 0;case j.CONNECT_ERROR:return typeof t==`string`||fn(t);case j.EVENT:case j.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&an.indexOf(t[0])===-1);case j.ACK:case j.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},cn=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=tn(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function ln(e){return typeof e==`string`}var un=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function dn(e){return e===void 0||un(e)}function fn(e){return Object.prototype.toString.call(e)===`[object Object]`}function pn(e,t){switch(e){case j.CONNECT:return t===void 0||fn(t);case j.DISCONNECT:return t===void 0;case j.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&an.indexOf(t[0])===-1);case j.ACK:return Array.isArray(t);case j.CONNECT_ERROR:return typeof t==`string`||fn(t);default:return!1}}function mn(e){return ln(e.nsp)&&dn(e.id)&&pn(e.type,e.data)}function hn(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var gn=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),_n=class extends O{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=[hn(e,`open`,this.onopen.bind(this)),hn(e,`packet`,this.onpacket.bind(this)),hn(e,`error`,this.onerror.bind(this)),hn(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(gn.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:j.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:j.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 j.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 j.EVENT:case j.BINARY_EVENT:this.onevent(e);break;case j.ACK:case j.BINARY_ACK:this.onack(e);break;case j.DISCONNECT:this.ondisconnect();break;case j.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:j.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:j.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 vn(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}vn.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},vn.prototype.reset=function(){this.attempts=0},vn.prototype.setMin=function(e){this.ms=e},vn.prototype.setMax=function(e){this.max=e},vn.prototype.setJitter=function(e){this.jitter=e};var yn=class extends O{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,ft(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 vn({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||rn;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 Wt(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=hn(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=hn(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(hn(e,`ping`,this.onping.bind(this)),hn(e,`data`,this.ondata.bind(this)),hn(e,`error`,this.onerror.bind(this)),hn(e,`close`,this.onclose.bind(this)),hn(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){k(()=>{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 _n(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)}},bn={};function xn(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=Gt(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=bn[i]&&a in bn[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new yn(r,t):(bn[i]||(bn[i]=new yn(r,t)),c=bn[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(xn,{Manager:yn,Socket:_n,io:xn,connect:xn});var Sn=({apiBaseUrl:e,userId:t,chatId:n,siteId:r})=>xn(e,{transports:[`polling`,`websocket`],upgrade:!0,rememberUpgrade:!1,auth:{userId:t,chatId:n,siteId:r},query:{chatId:n,siteId:r}}),Cn=({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)}}},wn=(0,d.createContext)(null),Tn=()=>{let e=(0,d.useContext)(wn);if(!e)throw Error(`useFlowEngage must be used inside FlowEngageProvider`);return e};function En(){if(typeof window>`u`)return!1;try{let e=window.localStorage?.getItem(`FE_DEBUG_VOICE`);if(e===`0`||e===`false`)return!1;if(e===`1`||e===`true`)return!0}catch{}return window.__FE_DEBUG_VOICE_TOOLS__===!1?!1:window.__FE_DEBUG_VOICE_TOOLS__===!0}var Dn=80;function On(e){requestAnimationFrame(()=>{let t=e.getBoundingClientRect(),n=t.top+t.height/2,r=Dn+(window.innerHeight-Dn)/2,i=window.pageYOffset+n-r;window.scrollTo({top:Math.max(0,i),behavior:`smooth`})})}function kn(e){e&&(e.hasAttribute(`data-fe-highlighted`)||(An(),e.classList?.remove(`fe-highlight-section`,`fe-highlight-speaking`,`fe-highlight-exiting`),On(e),e.setAttribute(`data-fe-orig-style`,e.style.cssText),e.setAttribute(`data-fe-highlighted`,`true`),e.style.outline=`3px solid #2563eb`,e.style.outlineOffset=`8px`,e.style.background=`rgba(37, 99, 235, 0.08)`,e.style.borderRadius=`8px`,e.style.padding=`12px 16px`,e.style.transition=`all 0.4s ease`))}function An(){let e=document.querySelector(`[data-fe-highlighted]`);e&&(e.style.cssText=e.getAttribute(`data-fe-orig-style`)||``,e.removeAttribute(`data-fe-highlighted`),e.removeAttribute(`data-fe-orig-style`))}var jn=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function Mn(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(jn)}catch{return!1}}function Nn(e){let t=e.cloneNode(!0);return t.querySelectorAll(`[aria-hidden], svg, .icon, [class*="icon"]`).forEach(e=>e.remove()),t.textContent.replace(/\s+/g,` `).trim()}function M(...e){En()&&console.log(`[FlowEngage:shadowNavigate]`,...e)}var Pn=`fe_pending_nav_section`,Fn=15e3,In=`fe_voice_nav_state`,Ln=2e4,Rn=!1,zn=null;function Bn(e=3e3){Rn=!0,zn&&clearTimeout(zn),zn=setTimeout(()=>{Rn=!1,zn=null},e)}function Vn(){return Rn}var Hn=!1,Un=null;function Wn(){Hn||typeof window>`u`||(Hn=!0,window.addEventListener(`popstate`,async()=>{let e=window.location.href;if(M(`popstate: body-swap to`,e),Un){try{$n(Un)}catch{}try{nr(Un)}catch{}}try{if(await _r(e,{skipPushState:!0,isBack:!0})){M(`popstate: body-swap succeeded`);return}}catch(e){console.warn(`[FlowEngage] popstate body-swap error:`,e)}M(`popstate: body-swap failed, falling back to reload`),window.location.reload()}))}var Gn=!1;function Kn(){Gn||typeof window>`u`||typeof document>`u`||(Gn=!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(),M(`link-intercept: body-swap to`,r.href),or();try{try{$n()}catch{}try{nr()}catch{}if(await _r(r.href)){M(`link-intercept: body-swap succeeded`);return}}catch(e){console.warn(`[FlowEngage] link-intercept body-swap error:`,e)}M(`link-intercept: body-swap failed, falling back to normal navigation`),sr(),window.location.href=r.href}},!0))}var qn=null;function Jn(e){qn=e===`spa`||e===`traditional`?e:null}function Yn(){if(typeof window>`u`||qn===`traditional`)return null;if(window.next?.router||window.__NEXT_ROUTER__)return`nextjs`;if(window.__remixRouter||window.__staticRouterHydrationData)return`react-router`;if(window.___gatsby||window.___navigate)return`gatsby`;if(window.__VUE_ROUTER__)return`vue-router`;if(window.__NUXT__||window.$nuxt)return`nuxt`;if(window.ng?.getComponent||document.querySelector(`[ng-version]`))return`angular`;if(window[Symbol.for(`wouter_v3`)])return`wouter`;if(window.__sveltekit_data||document.querySelector(`[data-sveltekit-hydrate]`))return`sveltekit`;if(document.querySelector(`[data-astro-transition]`))return`astro`;for(let e of document.body.children)if(e.tagName?.toUpperCase()===`DIV`&&e.id!==`flowengage-root`&&(e.id===`root`||e.id===`app`)&&e.children.length>0)return`generic-spa`;return qn===`spa`?`backend-spa`:null}var Xn=`data-fe-swap-css`;function Zn(){typeof document>`u`||document.querySelectorAll(`[${Xn}]`).forEach(e=>e.remove())}var Qn=`fe_form_state:`;function $n(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=Qn+(e||window.location.pathname);sessionStorage.setItem(t,JSON.stringify({state:n,ts:Date.now()}))}catch{}}function er(){if(typeof document>`u`||typeof sessionStorage>`u`)return;let e=Qn+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 tr=`fe_scroll:`;function nr(e){if(!(typeof window>`u`||typeof sessionStorage>`u`))try{let t=tr+(e||window.location.pathname);sessionStorage.setItem(t,JSON.stringify({y:window.scrollY,ts:Date.now()}))}catch{}}function rr(){if(typeof window>`u`||typeof sessionStorage>`u`)return;let e=tr+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 ir(e){if(!(typeof window>`u`))try{window.dispatchEvent(new CustomEvent(`flowengage:pageswap`,{detail:{url:e,timestamp:Date.now()}}))}catch{}}var ar=`fe-nav-loader`;function or(){if(typeof document>`u`||document.getElementById(ar))return;let e=document.createElement(`div`);e.id=ar,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 sr(){if(typeof document>`u`)return;let e=document.getElementById(ar);e&&(e.style.width=`100%`,setTimeout(()=>{e.style.opacity=`0`,e.style.transition=`opacity 0.3s ease`,setTimeout(()=>e.remove(),350)},200))}function cr(){if(typeof window>`u`||typeof document>`u`)return;try{window.history.state?.flowengageSpa&&Wn()}catch{}let e;try{e=JSON.parse(sessionStorage.getItem(Pn)||`null`)}catch{return}if(!e)return;try{sessionStorage.removeItem(Pn)}catch{}let{sectionText:t,ts:n}=e;if(!t)return;if(Date.now()-n>Fn){M(`initNavigationHighlight: pending section expired, skipping:`,t);return}M(`initNavigationHighlight: replaying section highlight:`,t);let r=0,i=()=>{r+=1;let e=ur(null,t);if(e){dr(e),M(`initNavigationHighlight: highlighted on attempt`,r);return}r<8?setTimeout(i,300):M(`initNavigationHighlight: could not find element after 8 attempts:`,t)};setTimeout(i,250)}var lr=()=>{if(typeof document>`u`||document.getElementById(`fe-highlight-styles`))return;let e=document.createElement(`style`);e.id=`fe-highlight-styles`,e.textContent=`
|
|
2
|
+
.fe-highlight-section {
|
|
3
|
+
outline: 3px solid #7c3aed !important;
|
|
4
|
+
box-shadow: 0 0 15px rgba(124, 58, 237, 0.6) !important;
|
|
5
|
+
transition: outline-color 0.3s ease, box-shadow 0.3s ease !important;
|
|
6
|
+
border-radius: 8px !important;
|
|
7
|
+
position: relative;
|
|
8
|
+
}
|
|
9
|
+
/* Smooth fade-in for the speaking highlight */
|
|
10
|
+
.fe-highlight-section.fe-highlight-speaking {
|
|
11
|
+
outline-color: #6366f1 !important;
|
|
12
|
+
box-shadow: 0 0 20px rgba(99, 102, 241, 0.45), 0 0 4px rgba(99, 102, 241, 0.3) !important;
|
|
13
|
+
animation: fe-hl-pulse 2s ease-in-out infinite !important;
|
|
14
|
+
}
|
|
15
|
+
@keyframes fe-hl-pulse {
|
|
16
|
+
0%, 100% { box-shadow: 0 0 15px rgba(99, 102, 241, 0.40), 0 0 4px rgba(99, 102, 241, 0.25); }
|
|
17
|
+
50% { box-shadow: 0 0 25px rgba(99, 102, 241, 0.55), 0 0 8px rgba(99, 102, 241, 0.35); }
|
|
18
|
+
}
|
|
19
|
+
/* Exit transition — the old highlight fades out */
|
|
20
|
+
.fe-highlight-exiting {
|
|
21
|
+
outline: 3px solid transparent !important;
|
|
22
|
+
box-shadow: none !important;
|
|
23
|
+
transition: outline-color 0.25s ease, box-shadow 0.25s ease !important;
|
|
24
|
+
}
|
|
25
|
+
`,document.head.appendChild(e)};function ur(e,t){if(typeof document>`u`)return null;if(e){let n=document.getElementById(e)||document.querySelector(`[data-section="${e}"]`);if(n)return n;t||=e.replace(/[-_]+/g,` `).trim()}if(!t)return null;let n=t.toLowerCase().trim(),r=n.split(/\s+/).filter(e=>e.length>2),i=Array.from(document.querySelectorAll(`h1.h2.h3.h4.h5.h6.[data-section].section[id].[id].main li.article li.[role='main'] li.[class*='card'].[class*='Card'].[class*='feature'].[class*='Feature'].[class*='tier'].[class*='Tier'].[class*='plan'].[class*='Plan'].[class*='pricing'].[class*='Pricing'].[class*='testimonial'].[class*='Testimonial'].[class*='team'].[class*='Team'].[class*='service'].[class*='Service'].[class*='block'].[role='listitem'].[role='article'].[role='region'].dt.dd`.split(`.`).join(`, `))).filter(e=>{if(Mn(e))return!1;let t=e.textContent.trim();return!(t.length<3||t.length>5e3||e.closest(`nav, footer, header, aside, .nav, .footer, .header`))});for(let e of i)if(Nn(e).toLowerCase()===n)return e;for(let e of i){let t=Nn(e).toLowerCase();if(t.startsWith(n)||t.endsWith(n))return e}let a=[];for(let e of i){let t=Nn(e).toLowerCase();t.includes(n)&&a.push({el:e,len:t.length})}if(a.length)return a.sort((e,t)=>e.len-t.len),a[0].el;for(let e of i){let t=Nn(e).toLowerCase();if(t.length>3&&n.includes(t))return e}if(r.length>0){let e=null,t=0;for(let n of i){let i=Nn(n).toLowerCase(),a=0;for(let e of r)i.includes(e)&&a++;let o=a/r.length;o>t&&o>=.6&&(t=o,e=n)}if(e)return e}let o=Array.from(document.querySelectorAll(`main [role='group']`)).filter(e=>!Mn(e)),s=[];for(let e of o){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();t.length<15||t.length>8e3||t.includes(n)&&s.push({el:e,len:t.length})}if(s.length)return s.sort((e,t)=>e.len-t.len),s[0].el;if(r.length>0){let e=Array.from(document.querySelectorAll(`main a[href], article a[href], .views-row a[href], h2 a[href], h3 a[href], .card a[href], [class*='teaser'] a[href]`)).filter(e=>{if(Mn(e))return!1;try{let t=e.getAttribute(`href`)||``;if(!t||t===`#`||t.startsWith(`javascript:`))return!1}catch{return!1}let t=e.textContent.replace(/\s+/g,` `).trim();return t.length>=3&&t.length<=220}),t=null,n=0;for(let i of e){let e=i.textContent.replace(/\s+/g,` `).toLowerCase(),a=0;for(let t of r)e.includes(t)&&a++;let o=a/r.length;o>n&&o>=.5&&(n=o,t=i)}if(t)return t.closest(`article`)||t.closest(`.views-row`)||t}let c=document.querySelectorAll(`section, article, .card, [class*='feature'], [class*='service']`);for(let e of c){if(Mn(e))continue;let t=e.querySelector(`h1, h2, h3, h4, h5, h6`);if(t){let r=t.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(r.includes(n)||n.includes(r))return e}}let l=document.querySelectorAll(`li, strong, blockquote, dt`);for(let e of l){if(Mn(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e.tagName===`STRONG`&&e.parentElement?.tagName===`LI`?e.parentElement:e}let u=Array.from(document.querySelectorAll(`a[href]`)).filter(e=>!Mn(e));u.sort((e,t)=>(e.textContent||``).trim().length-(t.textContent||``).trim().length);for(let e of u){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e}let d=document.querySelectorAll(`p`);for(let e of d){if(Mn(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<800)return e}return null}function dr(e,{speaking:t=!1,scroll:n=!0}={}){if(!e||typeof document>`u`)return;lr();let r=document.querySelectorAll(`.fe-highlight-section`);for(let t of r)t!==e&&(t.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`),t.classList.add(`fe-highlight-exiting`),setTimeout(()=>t.classList.remove(`fe-highlight-exiting`),300));if(e.classList.remove(`fe-highlight-exiting`),e.classList.add(`fe-highlight-section`),t?e.classList.add(`fe-highlight-speaking`):e.classList.remove(`fe-highlight-speaking`),n)try{e.scrollIntoView({behavior:`smooth`,block:`center`})}catch{try{e.scrollIntoView(!0)}catch{}}}function fr(){typeof document>`u`||(document.querySelectorAll(`.fe-highlight-section, .fe-highlight-exiting`).forEach(e=>e.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`,`fe-highlight-exiting`)),An())}function pr(e){if(typeof window>`u`)return e;try{let t=new URL(String(e).trim(),window.location.href);return!/^https?:$/i.test(t.protocol)||t.origin===window.location.origin?t.href:new URL(t.pathname+t.search+t.hash,window.location.origin).href}catch{return e}}async function mr(e){if(typeof window>`u`)return!1;try{let t=new URL(String(e).trim(),window.location.href),n=t.origin===window.location.origin?t.href:new URL(t.pathname+t.search+t.hash,window.location.origin).href;return(await fetch(n,{method:`HEAD`,mode:`same-origin`,cache:`no-store`})).ok}catch{return!1}}async function hr(e,{siteId:t,apiBaseUrl:n}){if(!e)return!1;let r=!1;try{r=!!Yn()}catch{r=!1}let i=()=>r?!1:mr(e);if(!t||!n)return console.warn(`[FlowEngage] shouldProceedWithNavigation: missing siteId or apiBaseUrl`),i();let a=String(n).replace(/\/$/,``),o=new URLSearchParams({siteId:String(t),url:String(e).trim()});try{let e=await(await fetch(`${a}/api/widget/navigate-allowed?${o.toString()}`)).json().catch(()=>({}));return e.success&&e.allowed?!0:i()}catch(e){return console.warn(`[FlowEngage] navigate-allowed check failed:`,e?.message),i()}}function gr(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(Pn,JSON.stringify({sectionText:e,ts:Date.now()}))}catch{}}async function _r(e,{skipPushState:t=!1,isBack:n=!1}={}){if(typeof window>`u`||typeof document>`u`)return!1;try{if(new URL(e,window.location.href).origin!==window.location.origin)return!1}catch{return!1}or();let r=new AbortController,i=setTimeout(()=>r.abort(),8e3);try{let a=await fetch(e,{credentials:`same-origin`,cache:`no-store`,signal:r.signal});if(clearTimeout(i),!a.ok)return sr(),!1;let o=await a.text(),s=new DOMParser().parseFromString(o,`text/html`),c=document.getElementById(`flowengage-root`);if(!c)return sr(),!1;try{typeof window.Drupal?.detachBehaviors==`function`&&window.Drupal.detachBehaviors(document.body,window.drupalSettings)}catch{}document.querySelectorAll(`script`).forEach(e=>{e.setAttribute(`data-fe-original`,`true`)}),Array.from(document.body.children).forEach(e=>{if(e===c)return;let t=e.tagName?.toUpperCase();t===`AUDIO`||t===`VIDEO`||e.remove()}),Zn();let l=new Set(Array.from(document.querySelectorAll(`link[rel='stylesheet']`)).map(e=>{try{return new URL(e.getAttribute(`href`)||``,window.location.href).href}catch{return``}}));for(let t of Array.from(s.head.querySelectorAll(`link[rel='stylesheet']`))){let n=t.getAttribute(`href`);if(!n)continue;let r;try{r=new URL(n,e).href}catch{continue}if(l.has(r))continue;let i=document.createElement(`link`);i.rel=`stylesheet`,i.href=r,i.setAttribute(Xn,`true`),t.media&&(i.media=t.media),document.head.appendChild(i)}for(let e of Array.from(s.head.querySelectorAll(`style`))){if(!e.textContent.trim())continue;let t=e.textContent.trim().slice(0,120);if(Array.from(document.head.querySelectorAll(`style:not([data-fe-swap-css])`)).some(e=>e.textContent.trim().slice(0,120)===t))continue;let n=document.createElement(`style`);n.textContent=e.textContent,n.setAttribute(Xn,`true`),document.head.appendChild(n)}Array.from(s.body.children).forEach(e=>{e.tagName?.toUpperCase()!==`SCRIPT`&&document.body.insertBefore(document.importNode(e,!0),c)});let u=document.querySelectorAll(`script:not([data-fe-replayed])`);for(let e of u){if(e.closest(`#flowengage-root, .flowengage-shell`)||e.hasAttribute(`data-fe-original`)||e.hasAttribute(`data-fe-replayed`))continue;let t=e.getAttribute(`src`),n=e.getAttribute(`type`)||``;if(!(n&&n!==`text/javascript`&&n!==``&&!n.includes(`drupal-ajax`))){if(n.includes(`drupal-ajax`)){e.setAttribute(`data-fe-replayed`,`true`);try{let t=JSON.parse(e.textContent);if(Array.isArray(t))for(let e of t){if((e.command===`insert`||e.command===`insert_new_content`)&&e.selector&&e.data){let t=document.querySelector(e.selector);t&&(e.method===`replaceWith`?t.outerHTML=e.data:e.method===`html`||e.method===`replace`?t.innerHTML=e.data:e.method===`append`?t.insertAdjacentHTML(`beforeend`,e.data):e.method===`prepend`?t.insertAdjacentHTML(`afterbegin`,e.data):t.innerHTML=e.data,M(`trySpaNavigate: BigPipe replacement →`,e.selector))}if(e.command===`settings`&&e.settings)try{window.drupalSettings&&typeof window.drupalSettings==`object`&&Object.assign(window.drupalSettings,e.settings)}catch{}}}catch(e){M(`trySpaNavigate: BigPipe parse error:`,e.message)}continue}if(!t&&e.textContent.trim()){let t=e.textContent;if(/window\.location\s*[.=]|location\s*\.\s*(href|assign|replace|reload)\s*[=(]/i.test(t)){e.setAttribute(`data-fe-replayed`,`true`);continue}let n=document.createElement(`script`);n.textContent=t,n.setAttribute(`data-fe-replayed`,`true`),e.parentNode.replaceChild(n,e)}}}try{for(let e of Array.from(s.querySelectorAll(`script`))){let t=(e.textContent||``).match(/drupalSettings\s*[,=]\s*(\{[\s\S]*?\})\s*[;)]/);if(t){try{let e=JSON.parse(t[1]);window.drupalSettings&&typeof window.drupalSettings==`object`?Object.assign(window.drupalSettings,e):window.drupalSettings=e,M(`trySpaNavigate: updated drupalSettings from new page`)}catch{}break}}}catch{}let d=window.location.assign.bind(window.location),f=window.location.replace.bind(window.location),p=!0;window.location.assign=e=>{if(p){M(`trySpaNavigate: blocked location.assign from replayed script:`,e);return}return d(e)},window.location.replace=e=>{if(p){M(`trySpaNavigate: blocked location.replace from replayed script:`,e);return}return f(e)};function m(e){let t=e.toLowerCase();return!!(/\/jquery[.\-\/]/.test(t)||/\/jquery\.min\.js/.test(t)||/\/jquery-once/.test(t)||/\/jquery\.once/.test(t)||/\/jquery\.ui[\./]/.test(t)||/\/jqueryui/.test(t)||/\/core\/misc\//.test(t)||/\/core\/modules\//.test(t)||/\/misc\/drupal\.js/.test(t)||/\/lodash[.\-\/]/.test(t)||/\/underscore[.\-\/]/.test(t)||/\/backbone[.\-\/]/.test(t)||/\/modernizr[.\-\/]/.test(t)||/\/popper[.\-\/]/.test(t)||/\/bootstrap\.min\.js/.test(t)||/\/bootstrap\.bundle/.test(t))}let h=new Set(Array.from(document.querySelectorAll(`script[src]`)).map(e=>{try{return new URL(e.getAttribute(`src`)||``,window.location.href).href}catch{return``}}));function g(t,n){let r=t.getAttribute(`src`)||``;if(r.includes(`flowengage`))return;let i=document.createElement(`script`);if(r){let n;try{n=new URL(r,e).href}catch{return}if(h.has(n)){if(m(n))return;M(`trySpaNavigate: re-running theme/custom script:`,n)}h.add(n),i.src=n,i.async=t.async,i.defer=t.defer}else if(t.textContent.trim()){let e=t.textContent;if(/window\.location\s*[.=]|location\s*\.\s*(href|assign|replace|reload)\s*[=(]/i.test(e)){M(`trySpaNavigate: skipping inline script with navigation:`,e.slice(0,120));return}if(/^\s*\(?\s*(?:window\.)?drupalSettings\s*[,=]/.test(e))return;i.textContent=e}else return;let a=t.getAttribute(`type`);a&&a!==`text/javascript`&&a!==``&&(i.type=a),n.parentNode.insertBefore(i,n)}for(let e of Array.from(s.head.querySelectorAll(`script`)))g(e,c);for(let e of Array.from(s.body.querySelectorAll(`script`)))g(e,c);try{typeof window.Drupal?.attachBehaviors==`function`&&window.Drupal.attachBehaviors(document.body,window.drupalSettings)}catch{}try{typeof window.jQuery==`function`&&(window.jQuery(document).trigger(`ready`),window.dispatchEvent(new Event(`resize`)))}catch{}try{document.dispatchEvent(new Event(`DOMContentLoaded`,{bubbles:!0,cancelable:!1}))}catch{}try{window.dispatchEvent(new Event(`load`))}catch{}try{let e=document.querySelectorAll(`iframe:not([data-fe-skip-reload])`);for(let t of e){if(t.closest(`#flowengage-root, .flowengage-shell`))continue;let e=t.getAttribute(`src`)||t.src;e&&e!==`about:blank`&&!e.startsWith(`javascript:`)&&(M(`trySpaNavigate: reloading iframe:`,e),t.src=e)}}catch{}try{let e=document.querySelectorAll(`.g-recaptcha, [data-sitekey]`);if(e.length>0){if(typeof window.grecaptcha?.render==`function`){for(let t of e)if(!t.closest(`#flowengage-root`)){t.innerHTML=``;try{window.grecaptcha.render(t,{sitekey:t.getAttribute(`data-sitekey`)||``}),M(`trySpaNavigate: re-rendered reCAPTCHA`)}catch{}}}else if(!document.querySelector(`script[src*='recaptcha']`)){let e=document.createElement(`script`);e.src=`https://www.google.com/recaptcha/api.js?render=explicit`,e.async=!0,document.head.appendChild(e),M(`trySpaNavigate: injected reCAPTCHA script`)}}}catch{}if(setTimeout(()=>{p=!1,window.location.assign=d,window.location.replace=f},2e3),s.title&&(document.title=s.title),!t)try{history.pushState({flowengageSpa:!0},``,e)}catch{}if(Wn(),Kn(),n){try{er()}catch{}try{rr()}catch{}}else window.scrollTo(0,0);sr(),ir(e);try{sessionStorage.removeItem(Pn)}catch{}try{sessionStorage.removeItem(In)}catch{}try{Un=new URL(e,window.location.origin).pathname}catch{}return M(`trySpaNavigate: succeeded →`,e),!0}catch{return clearTimeout(i),sr(),!1}}function vr(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(In,JSON.stringify({voiceWasActive:!0,targetUrl:String(e),ts:Date.now()}))}catch{}}function yr(){if(!(typeof sessionStorage>`u`))try{sessionStorage.removeItem(In)}catch{}}function br(){if(typeof window>`u`||typeof sessionStorage>`u`)return{shouldResumeVoice:!1,targetUrl:null};let e;try{e=JSON.parse(sessionStorage.getItem(In)||`null`)}catch{return{shouldResumeVoice:!1,targetUrl:null}}if(!e)return{shouldResumeVoice:!1,targetUrl:null};try{sessionStorage.removeItem(In)}catch{}return e.voiceWasActive?Date.now()-e.ts>Ln?(M(`initVoiceNavResume: state expired, skipping`),{shouldResumeVoice:!1,targetUrl:null}):(M(`initVoiceNavResume: voice was active during navigation to`,e.targetUrl),{shouldResumeVoice:!0,targetUrl:e.targetUrl||null}):{shouldResumeVoice:!1,targetUrl:null}}async function xr(e,t={}){if(typeof window>`u`)return!1;let{sectionText:n,voiceActive:r=!1}=t;try{let t=pr(e),i=new URL(t,window.location.origin);if(i.hash&&i.pathname===window.location.pathname){let e=document.getElementById(i.hash.slice(1));if(e)return e.scrollIntoView({behavior:`smooth`,block:`start`}),!0}if(i.pathname===window.location.pathname&&i.search===window.location.search&&!i.hash)return!1;let a=i.pathname+i.search+i.hash,o=window.next?.router;if(o?.push)return new Promise(e=>{let t=()=>{o.events?.off(`routeChangeComplete`,t),e(!0)};o.events?.on(`routeChangeComplete`,t),o.push(a),setTimeout(t,5e3)});if(window.__NEXT_ROUTER__?.push)return window.__NEXT_ROUTER__.push(a),!0;if(Yn()){n&&gr(n);try{window.history.pushState({},``,i.href),window.dispatchEvent(new PopStateEvent(`popstate`,{state:{}}))}catch{}return!0}return n&&gr(n),r||Oe(),window.location.assign(i.href),!0}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t),n&&gr(n);try{window.location.href=pr(e)}catch{window.location.href=e}return!0}}var Sr=!1,Cr=null;function wr(e){Cr=e,typeof window<`u`&&(window.__fe_triggerVoiceNavHooks=()=>{try{e.onBeforeNavigate()}catch{}}),!Sr&&(Sr=!0,!(typeof document>`u`)&&(document.addEventListener(`click`,e=>{if(!Cr)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&&!r.hash)){M(`voice-link-hook: saving state before navigation →`,r.href);try{Cr.onBeforeNavigate()}catch{}}},!0),document.addEventListener(`submit`,e=>{if(Cr&&!e.target?.closest?.(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)){M(`voice-form-hook: saving state before form submit`);try{Cr.onBeforeNavigate()}catch{}}},!0)))}function Tr(){Cr=null,M(`voice-nav-hooks: deactivated`)}var Er=e=>!e||typeof e!=`string`?e:e.replace(/<human_assistance_request[^>]*>/gi,``).replace(/<\/human_assistance_request>/gi,``).replace(/<navigate[^>]*\/>/gi,``).replace(/<navigate[^>]*>[\s\S]*?<\/navigate>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*>[\s\S]*?<\/[a-z]+(?:_[a-z]+)+>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*\/>/gi,``).trim(),Dr=(e=[])=>e.filter(e=>e.type!==`call_recording`&&!(typeof e.message==`string`&&e.message.includes(`AI chat recording`))).map(e=>({...e,message:Er(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`}));function Or(e){if(!e||typeof e!=`string`)return null;let t=e.match(/<navigate([^>]*?)(?:\/>|>[\s\S]*?<\/navigate>)/i);if(!t)return null;let n=t[1],r=n.match(/url=["']([^"']+)["']/i);if(!r)return null;let i=n.match(/section=["']([^"']+)["']/i)||n.match(/highlight=["']([^"']+)["']/i);return{url:r[1].trim(),section:i?.[1]?.trim()||null}}var kr=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,Ar=(e={})=>{if(!e?.candidate)return null;if(typeof e.candidate==`object`)return e.candidate;let t=e.sdpMid!==void 0&&e.sdpMid!==null&&e.sdpMid!==``,n=e.sdpMLineIndex!==void 0&&e.sdpMLineIndex!==null;return!t&&!n?null:{candidate:e.candidate,...t?{sdpMid:e.sdpMid}:{},...n?{sdpMLineIndex:e.sdpMLineIndex}:{}}},jr=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t},Mr=(e=[],t,n=6)=>!t?.message||e.slice(-n).some(e=>e.sender===`system`&&e.message===t.message)?e:[...e,t];function Nr({siteId:e,config:t,children:n,language:r=`en`}){let i=(0,d.useMemo)(()=>e?{...t||{},siteId:e}:t||null,[e,t]),[a,o]=(0,d.useState)(0),[s,c]=(0,d.useState)(`booting`),[l,u]=(0,d.useState)(null),[m,h]=(0,d.useState)(null),[g,_]=(0,d.useState)(``),[x,S]=(0,d.useState)([]),[re,ie]=(0,d.useState)(C().isOpen),[ae,oe]=(0,d.useState)(C().activeScreen),[pe,me]=(0,d.useState)(C().isHumanHandled),[he,_e]=(0,d.useState)(C().agentName),[ve,ye]=(0,d.useState)(C().agentHeadshot),[be,xe]=(0,d.useState)(()=>de(i?.siteId)),[Se,Ce]=(0,d.useState)(!1),[we,Ee]=(0,d.useState)(!1),[De,Oe]=(0,d.useState)(`idle`),[ke,Ae]=(0,d.useState)(!1),[je,w]=(0,d.useState)(!1),[Me,Ne]=(0,d.useState)(``),[Pe,Re]=(0,d.useState)(!1),[ze,Be]=(0,d.useState)(0),[Ve,He]=(0,d.useState)(0),[Ue,We]=(0,d.useState)(!1),[T,Ge]=(0,d.useState)(null),[Ke,qe]=(0,d.useState)(null),[Je,Ye]=(0,d.useState)(`idle`),[Xe,Ze]=(0,d.useState)(null),[Qe,$e]=(0,d.useState)(!1),[et,tt]=(0,d.useState)(``),[nt,rt]=(0,d.useState)(!1),E=(0,d.useRef)(null),D=(0,d.useRef)(null),it=(0,d.useRef)(``),at=(0,d.useRef)(!1),ot=(0,d.useRef)(null),O=(0,d.useRef)(null),st=(0,d.useRef)(null),k=(0,d.useRef)(null),A=(0,d.useRef)(null),ct=(0,d.useRef)(null),lt=(0,d.useRef)(null),ut=(0,d.useRef)(!1),dt=(0,d.useRef)([]),ft=(0,d.useRef)(null),pt=(0,d.useRef)(null),mt=(0,d.useRef)(null),ht=(0,d.useRef)(!1),gt=(0,d.useRef)(!1),_t=(0,d.useRef)(``),vt=(0,d.useRef)(null),yt=(0,d.useRef)(null),bt=(0,d.useRef)([]),xt=(0,d.useRef)(0),St=(0,d.useRef)(he),Ct=(0,d.useRef)([]),wt=(0,d.useRef)(!1),Tt=(0,d.useRef)(!1),Et=(0,d.useRef)(i),Dt=(0,d.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),Ot=(0,d.useCallback)((e={})=>{let t=!!e.is_human_handled;return me(t),t?(oe(`agent`),e.agent_info?.name&&_e(e.agent_info.name),e.agent_info?.headshot&&ye(e.agent_info.headshot),t):(oe(`ai`),t)},[]),kt=(0,d.useMemo)(()=>{let e=m?.widgetSettings?.call?.maxDurationSeconds??i?.widgetSettings?.call?.maxDurationSeconds??i?.callMaxDurationSeconds,t=Number(e);return Number.isFinite(t)&&t>0?t:y},[i,m]);(0,d.useEffect)(()=>{O.current=T},[T]),(0,d.useEffect)(()=>{St.current=he},[he]),(0,d.useEffect)(()=>{Tt.current=Pe},[Pe]),(0,d.useEffect)(()=>{Et.current=i},[i]);let At=()=>{tt(``)},jt=(0,d.useCallback)(()=>{mt.current&&=(window.clearTimeout(mt.current),null)},[]),Mt=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return xe(t),fe(t,i?.siteId),t};(0,d.useEffect)(()=>{let e=i?.siteId;e&&xe(de(e))},[i?.siteId]);let Nt=(e=`unspecified`)=>{let t=ft.current||ct.current?.callId,n=xt.current,r=vt.current;if(vt.current=null,xt.current=0,r&&r.state!==`inactive`){r.onstop=()=>{let e=bt.current;if(bt.current=[],e.length>0&&t&&D.current){let r=new Blob(e,{type:e[0].type}),i=n>0?Math.round((Date.now()-n)/1e3):0;D.current.uploadRecording(t,r,i).then(e=>console.log(`[FlowEngageCall] recording upload success`,e)).catch(e=>console.warn(`[FlowEngageCall] recording upload failed`,e))}};try{r.stop()}catch{r.onstop=null,bt.current=[]}}else if(r&&r.state===`inactive`){let e=bt.current;if(bt.current=[],e.length>0&&t&&D.current){let r=new Blob(e,{type:e[0].type}),i=n>0?Math.round((Date.now()-n)/1e3):0;D.current.uploadRecording(t,r,i).then(e=>console.log(`[FlowEngageCall] recording upload success`,e)).catch(e=>console.warn(`[FlowEngageCall] recording upload failed`,e))}}else bt.current=[];if(yt.current){try{yt.current.close()}catch{}yt.current=null}st.current&&=(st.current.close(),null),k.current&&=(k.current.getTracks().forEach(e=>e.stop()),null),A.current&&=(A.current.srcObject=null,A.current.remove(),null),jt(),ct.current=null,dt.current=[],ft.current=null,pt.current=null,ht.current=!1,$e(!1),Ge(null),qe(null),Ye(`idle`),Ze(null)},Pt=(e=new Date().toISOString())=>{let t=E.current,n=ft.current||ct.current?.callId;if(!(!t?.connected||!n||ht.current)){ht.current=!0,t.emit(`call:connected`,{callId:n,chatId:it.current,connectedAt:e});try{let e=k.current,t=A.current?.srcObject;if(e&&t&&!vt.current){bt.current=[];let n=new(window.AudioContext||window.webkitAudioContext);yt.current=n;let r=n.createMediaStreamDestination();n.createMediaStreamSource(e).connect(r),n.createMediaStreamSource(t).connect(r);let i=window.MediaRecorder.isTypeSupported(`audio/webm`)?`audio/webm`:`audio/mp4`,a=new window.MediaRecorder(r.stream,{mimeType:i});a.ondataavailable=e=>{e.data&&e.data.size>0&&bt.current.push(e.data)},vt.current=a,xt.current=Date.now(),a.start(1e3),setTimeout(()=>{try{if(!window.speechSynthesis)return;let e=new SpeechSynthesisUtterance(`This call is being recorded for quality and training purposes.`);if(e.rate=.95,e.pitch=1,e.volume=1,window.MediaStreamTrackGenerator||window.AudioContext)try{let t=n.createMediaStreamDestination();e.onstart=()=>{try{let i=document.createElement(`audio`);i.style.display=`none`,i.srcObject=t.stream,document.body.appendChild(i),i.play().catch(()=>{});let a=n.createMediaStreamSource(t.stream);a.connect(r),e.onend=()=>{try{a.disconnect()}catch{}try{i.remove()}catch{}}}catch{}}}catch{}window.speechSynthesis.speak(e)}catch{}},200)}}catch{}}},Ft=(e={})=>{if(!e.callId)return;let t=pt.current===e.callId,n=ft.current===e.callId,r=O.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(jt(),Ge(null),t||n){ft.current=e.callId,qe(e.callId),Ye(e=>e===`connected`?e:`connecting`),ie(!0);return}Ye(`idle`)}},It=(e={})=>{if(!e.callId)return;let t=pt.current===e.callId,n=ft.current===e.callId,r=O.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(jt(),n){Nt();return}pt.current=null,ct.current=null,dt.current=[],Ge(null),Ye(`idle`)}},Lt=async(e={})=>{let t=st.current,n=E.current,r=e.sdpOffer||e.offer?.sdp;if(!t||!n?.connected||!r||!e.callId){console.log(`[FlowEngageProvider] deferring remote offer until peer/socket ready`,{callId:e.callId,chatId:it.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),ct.current=e;return}if(await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),dt.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:it.current,queuedCount:dt.current.length});for(let e of dt.current)await t.addIceCandidate(new RTCIceCandidate(e));dt.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:it.current})};(0,d.useEffect)(()=>{ue({isOpen:re,activeScreen:ae,isHumanHandled:pe,agentName:he,agentHeadshot:ve})},[re,ae,pe,he,ve]),(0,d.useEffect)(()=>{let e=!0;return(async()=>{rt(!0);try{let t=p(i),n=await Ie(t);if(!e)return;let a=t.siteId,o=se(a),s=ge(a),l=``;try{let e=at.current,r=ot.current;if(at.current=!1,ot.current=null,l=(await Fe({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:a,priorChatId:e||r?null:o||ee(),forceNew:e,resumeChatId:r,visitorId:s}))?.data?.chatId,!l)throw Error(`resolve-session returned no chatId`);te(),le(a,l)}catch(e){console.warn(`[FlowEngageProvider] resolve-session failed, reusing persisted or ephemeral chat id`,e?.message||e),l=o||ne(),le(a,l)}it.current=l;let u=Le({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId,visitorId:s});D.current=u,h({...n,apiBaseUrl:t.apiBaseUrl}),_(l);let d=n?.widgetSettings?.branding?.fallbackAgentName||`Agent`,f=Sn({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:l,siteId:t.siteId});E.current=f,f.on(`connect`,()=>{Oe(`connected`)}),f.on(`disconnect`,()=>{Oe(`disconnected`)}),f.on(`aiTyping`,()=>{Ee(!0)}),f.on(`ai:typing`,()=>{Ee(!0)}),f.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:Er(t.message)};Ee(!1),Ce(!1),!(n.type===`call_recording`||typeof n.message==`string`&&n.message.includes(`AI chat recording`))&&S(e=>[...e.filter(e=>!e.isPending),{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}])}),f.on(`conversationStarted`,e=>{e?.message&&S(t=>[...t,{id:`system-start-${Date.now()}`,sender:`system`,message:e.message,timestamp:new Date().toISOString(),isPending:!1}])}),f.on(`message:new`,e=>{let t=e.message||e,n={...t,message:Er(t.message)};Ee(!1),!(n.type===`call_recording`||typeof n.message==`string`&&n.message.includes(`AI chat recording`))&&((n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&Ce(!1),S(e=>n.sender===`bot`||n.sender===`ai`?[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]:e.some(e=>e.id===n.messageId||e.sender===n.sender&&e.message===n.message&&e.isPending)?e.map(e=>e.sender===n.sender&&e.message===n.message&&e.isPending?{...n,isPending:!1,id:n.messageId||e.id}:e):[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]),(n.sender===`agent`||n.agent_name)&&(me(!0),oe(`agent`),_e(jr([n.agent_name,n.agentName,n.metadata?.agentName],d)),n.sender_headshot&&ye(n.sender_headshot),ie(!0),Be(e=>e+1)))});let m=(e={})=>{let t=jr([e.agent?.name,e.agentName,e.agent_name,St.current],d);me(!0),oe(`agent`),_e(t),ye(e.agent?.headshot||null),ie(!0),Be(e=>e+1),S(e=>Mr(e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}))},g=(e={})=>{let t=jr([e.agent?.name,e.agentName,e.agent_name,St.current],d);me(!1),oe(`ai`),S(e=>Mr(e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}))};f.on(`agent:joined`,m),f.on(`agentJoined`,m),f.on(`agent:left`,g),f.on(`agentLeft`,g),f.on(`conversationEnded`,e=>{We(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;S(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),f.on(`chat:history_update`,e=>{let t=Dr(e.chat_history||[]);S(t),t.length===0&&(We(!1),me(!1),oe(`ai`),Ee(!1),Ce(!1))}),f.on(`conversation:reset`,()=>{S([]),We(!1),me(!1),oe(`ai`),Ee(!1),Ce(!1)}),f.on(`voice:end_session`,(e={})=>{console.log(`[FlowEngageProvider] voice:end_session received — ending ElevenLabs session`),He(e=>e+1),ie(!0),Be(e=>e+1)}),f.on(`typing:start`,e=>{e.sender===`agent`&&Ce(!0)}),f.on(`typing:stop`,e=>{e.sender===`agent`&&Ce(!1)}),f.on(`call:incoming`,(e={})=>{let t=jr([e.agentName,e.ownerName,e.agent?.name,St.current],`Agent`);At(),jt(),ht.current=!1,Ge({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),_e(e=>jr([t,e],`Agent`)),Ye(`incoming`),Ze(null),ie(!0)}),f.on(`call:offer`,async(e={})=>{ct.current=e;try{await Lt(e)}catch(e){console.error(`[FlowEngageProvider] failed to apply remote offer`,e)}}),f.on(`call:ice-candidate-from-agent`,async(e={})=>{if(e.candidate)try{let t=Ar(e);if(!t){console.warn(`[FlowEngageProvider] ignoring invalid ICE candidate payload`,e);return}if(!st.current||!st.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||it.current,queueSize:dt.current.length+1}),dt.current.push(t);return}await st.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),f.on(`call:ended`,()=>{At(),Nt(`socket:call_ended`)}),f.on(`call:accepted`,(e={})=>{Ft(e)}),f.on(`call:accepted_by_other`,(e={})=>{Ft(e)}),f.on(`call:rejected`,(e={})=>{It(e)}),f.on(`call:missed`,(e={})=>{It(e)}),f.on(`call:failed`,(e={})=>{It(e)}),f.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=pt.current===e.callId,n=ft.current===e.callId,r=ct.current?.callId===e.callId,i=O.current?.callId===e.callId;if(!t&&!n&&!r){i&&(Ge(null),Ye(`idle`));return}ht.current=!0,pt.current=null,ft.current=e.callId,qe(e.callId),Ge(null),Ye(`connected`),Ze(e.connectedAt||new Date().toISOString()),ie(!0)}),f.on(`call:unavailable`,(e={})=>{Nt(`socket:call_unavailable`),tt(kr(e,`This visitor is not available for a call right now.`)),ie(!0)}),f.on(`call:error`,(e={})=>{Nt(`socket:call_error`),tt(kr(e,`We couldn't connect the call right now.`)),ie(!0)}),f.on(`visitor:navigate`,async({url:e,section:n,highlight:r}={})=>{e&&await hr(e,{siteId:t.siteId,apiBaseUrl:t.apiBaseUrl})&&xr(e,{voiceActive:Tt.current}).then(e=>{let t=n||r;t&&setTimeout(()=>{let e=ur(null,t);e&&dr(e)},e?300:150)})}),f.on(`visitor:highlight`,({sectionId:e,sectionText:t}={})=>{if(!e&&!t)return;let n=ur(e||null,t||null);n&&dr(n)}),f.on(`visitor:clear_highlight`,()=>{fr()}),Dt.current=Cn({socket:f,chatId:l});let v=await u.loadHistory(l,r);if(!e)return;S(Dr(v.chat_history||[])),me(!!v.is_human_handled),oe(v.is_human_handled?`agent`:ae);let y=v?.visitor_email||v?.visitorEmail;if(y&&String(y).trim()&&Mt(String(y).trim()),await new Promise(e=>setTimeout(e,500)),!e)return;c(`ready`)}catch(t){if(!e)return;u(t),c(`error`)}finally{e&&rt(!1)}})(),()=>{e=!1,Dt.current?.cleanup?.(),Nt(),E.current?.disconnect()}},[i,r,a]),(0,d.useEffect)(()=>()=>{if(Pe&&!wt.current&&Ct.current.length>0){let e=it.current,t=Ct.current,n=D.current;n&&e&&t.length>0&&(console.log(`[FlowEngageProvider] safety-net: syncing voice transcript on unmount`),n.beaconSyncVoice(e,t)||n.syncVoice(e,t).catch(()=>{}),wt.current=!0)}},[Pe,m]);let Rt=(0,d.useRef)(null),zt=(0,d.useRef)(!1);(0,d.useEffect)(()=>{let e=D.current;!e||!g||Rt.current!==re&&(re&&Rt.current!==null?(e.updateChatStatus(g,`open`).catch(()=>{}),zt.current=!0):Rt.current===!0&&e.updateChatStatus(g,`widget_closed`).catch(()=>{}),Rt.current=re)},[re,g]),(0,d.useEffect)(()=>{let e=()=>{let e=it.current,t=D.current;!e||!t||typeof navigator>`u`||t.beaconWidgetClosed?.(e)||t.updateChatStatus(e,`widget_closed`).catch(()=>{})};return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[]),(0,d.useEffect)(()=>{if(!D.current||!g||s!==`ready`)return;let e=window.setInterval(async()=>{try{let e=await D.current.checkHumanHandled(g);me(!!e.is_human_handled),e.is_human_handled&&(oe(`agent`),e.agent_info?.name&&_e(jr([e.agent_info.name],`Agent`)),e.agent_info?.headshot&&ye(e.agent_info.headshot)),Ot(e)}catch{}},1e4);return()=>window.clearInterval(e)},[g,s,Ot]);let Bt=async()=>{if(!(!T?.callId||!D.current||!E.current||!g)){At(),pt.current=T.callId,jt();try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});k.current=e;let t=[{urls:`stun:stun.l.google.com:19302`}];try{let e=await D.current.getIceServersConfig();e?.data?.iceServers?.length&&(t=e.data.iceServers)}catch(e){console.warn(`[FlowEngageProvider] ice-config fetch failed, using STUN default`,e)}let n=new RTCPeerConnection({iceServers:t});st.current=n,n.onconnectionstatechange=()=>{let e=n.connectionState;if(e===`connected`){let e=new Date().toISOString();Ye(`connected`),Ze(t=>t||e),Pt(e);return}if(e===`connecting`){Ye(e=>e===`connected`?e:`connecting`);return}(e===`failed`||e===`closed`)&&Nt(`peer:connection_${e}`)},n.oniceconnectionstatechange=()=>{let e=n.iceConnectionState;if(e===`connected`||e===`completed`){let e=new Date().toISOString();Ye(`connected`),Ze(t=>t||e),Pt(e);return}if(e===`checking`||e===`new`){Ye(e=>e===`connected`?e:`connecting`);return}(e===`failed`||e===`closed`)&&Nt(`peer:ice_${e}`)},n.onsignalingstatechange=()=>{},n.onicegatheringstatechange=()=>{},e.getTracks().forEach(t=>{n.addTrack(t,e)}),n.onicecandidate=e=>{if(!e.candidate||!E.current?.connected)return;let t=e.candidate;E.current.emit(`call:ice-candidate`,{callId:T.callId,candidate:t.candidate,sdpMid:t.sdpMid,sdpMLineIndex:t.sdpMLineIndex,chatId:g,from:`customer`})},n.ontrack=e=>{let[t]=e.streams||[],[n]=t?.getAudioTracks?.()||[];if(!A.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,e.playsInline=!0,e.onplay=()=>{},e.onpause=()=>{},e.onended=()=>{},e.onerror=e=>{},A.current=e,document.body.appendChild(e)}A.current.srcObject=e.streams[0];let r=T?.callId,i=r&&(pt.current===r||ft.current===r);if(!ht.current&&i){let e=new Date().toISOString();Ye(`connected`),Ze(t=>t||e),ft.current=r,qe(r),Pt(e)}A.current.srcObject=t||null;let a=A.current.play?.();a?.catch&&a.catch(e=>{})};let r=ct.current;r&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:r.callId||T.callId,chatId:g}),await Lt({...r,callId:r.callId||T.callId})),await D.current.acceptCall(T.callId,g),E.current?.emit(`call:accepted`,{callId:T.callId,chatId:g}),ft.current=T.callId,qe(T.callId),Ye(e=>e===`connected`||ht.current?`connected`:`connecting`),Ge(null),ie(!0)}catch(e){if(pt.current=null,Nt(`accept_call_failed`),e?.status===404||e?.status===409||e?.status===422){tt(kr(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await D.current.rejectCall(T.callId,g)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}tt(`Microphone access was denied. Please allow microphone access to accept the call.`);return}tt(`We couldn't connect the call right now. Please try again.`)}}},Vt=async()=>{if(!T?.callId||!D.current||!g){Nt(`reject_call_without_server_context`);return}let e=T.callId;jt(),At(),E.current?.emit(`call:rejected`,{callId:e,chatId:g,reason:`visitor_declined`});try{await D.current.rejectCall(e,g)}catch(e){tt(kr(e,`We couldn't decline the call cleanly.`))}finally{Nt(`reject_call_finally`)}},Ht=(0,d.useRef)(Vt);Ht.current=Vt,(0,d.useEffect)(()=>{if(!T?.callId||Ke){jt();return}let e=T.callId;return jt(),mt.current=window.setTimeout(()=>{O.current?.callId===e&&pt.current!==e&&ft.current!==e&&Ht.current()},b),()=>{mt.current&&=(window.clearTimeout(mt.current),null)}},[Ke,jt,T?.callId]);let Ut=async()=>{if(!Ke||!D.current||!g){Nt(`end_call_without_server_context`);return}At();try{await D.current.endWebRTCCall(Ke,g)}catch(e){tt(kr(e,`The call ended locally, but the server could not be updated.`))}finally{Nt(`end_call_finally`)}},Wt=()=>{let e=k.current?.getAudioTracks?.()||[],t=st.current?.getSenders?.().map(e=>e.track).filter(e=>e?.kind===`audio`)||[],n=[...e,...t].filter(Boolean);if(n.length===0)return;let r=!Qe;n.forEach(e=>{e.enabled=!r}),$e(r)},Gt=async(e={})=>{let t=e.notifyChatInitiated===!0;if(zt.current=!0,ie(!0),!(!t||!D.current||!g||typeof window>`u`)){try{await D.current.trackVisitor({chatId:g,currentPagePath:window.location.pathname||`/`})}catch{}try{await D.current.updateChatStatus(g,`open`)}catch{}}},Kt=async e=>{let t=Mt(e);if(!t||!D.current||!it.current)return t;try{await D.current.trackVisitor({chatId:it.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},qt=()=>{!g||!E.current?.connected||gt.current||(gt.current=!0,E.current.emit(`typing:start`,{chatId:g,sender:`user`}))},Jt=()=>{!g||!E.current?.connected||!gt.current||(gt.current=!1,E.current.emit(`typing:stop`,{chatId:g,sender:`user`}))},Yt=(e=``)=>{let t=typeof e==`string`?e:``;!g||!E.current?.connected||t!==``&&_t.current===t||(_t.current=t,E.current.emit(`typing:update`,{chatId:g,sender:`user`,text:t}))};function Xt(){if(typeof document>`u`)return null;try{let e=(document.querySelector(`main`)||document.querySelector(`[role='main']`)||document.querySelector(`article`)||document.querySelector(`#content`)||document.querySelector(`.content`)||document.body).cloneNode(!0);e.querySelectorAll(`nav, footer, header, aside, script, style, noscript, #flowengage-root, .flowengage-shell, .flowengage-widget-root, [id*='flowengage'], [class*='flowengage']`).forEach(e=>e.remove());let t=e.textContent.replace(/\s+/g,` `).trim();return t.length>0?t.substring(0,3e3):null}catch{return null}}let Zt=async(e,t=``,n=null,a={})=>{let o=typeof e==`string`?e.trim():``;if(!o||!D.current||!g||s!==`ready`||Ue)return;Jt();let c=/^\s*(yes|yeah|sure|ok|okay|go ahead|take me(?: there)?(?!\s+\w)|navigate(?!\s+(?:me\s+)?to\s+\w)|yep|absolutely|please do|do it|let'?s go|go there|show me(?!\s+(?:the|a|an)\s+\w)|go to it|bring me there|navigate me there)\b/i,l=/^\s*(?:yes|yeah|sure|ok|okay|yep|absolutely)\s+(?!(?:please|do\s+it|let'?s|that|this|there|it|thanks|go|cool|great|perfect|sounds|alright|proceed)\b)\w/i,d=/\b(take me|navigate|go to|show me|bring me|open|go there|navigate to|take me to|let'?s go to)\b/i;if(lt.current&&c.test(o)&&!l.test(o)){let{url:e,section:t}=lt.current;lt.current=null,ut.current=!0,console.log(`[FWH Nav] Client-side nav firing →`,e),xr(e,{voiceActive:Tt.current}).then(e=>{!t||!Tt.current||setTimeout(()=>{let e=ur(null,t);e&&dr(e)},e?300:150)})}else c.test(o)||(lt.current=null);let f=`pending-user-${Date.now()}`,p={id:f,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,type:a?.type||`text`,metadata:a?.metadata||void 0,...n||{}};S(e=>[...e,p]);let m=pe;if(m)try{m=Ot(await D.current.checkHumanHandled(g))}catch{}if(m&&E.current?.connected){E.current.emit(`customer:message`,{chatId:g,content:e,sender:`user`,email:be||void 0,type:a?.type||`text`,metadata:a?.metadata||{},...n||{}});return}Ae(!0);try{let s=await D.current.sendAiMessage(g,e,r,t,{...n||{},...be?{email:be}:{}},{...a,currentPageUrl:typeof window<`u`?window.location.href:void 0,currentPageTitle:typeof window<`u`?document.title:void 0,currentPagePath:typeof window<`u`?window.location.pathname:void 0,currentPageContent:Xt()||void 0}),c=s.chat_history||[];if(console.log(`[FWH Nav Debug] API response fields:`,{has_navigate:!!s.navigate,navigate:s.navigate,has_pending_navigate:!!s.pending_navigate,pending_navigate:s.pending_navigate,last_bot_msg:[...c].reverse().find(e=>e.sender===`bot`)?.message?.substring(0,80)}),s.pending_navigate?.url){let e={url:s.pending_navigate.url,section:s.pending_navigate.section||null};d.test(o)?(console.log(`[FWH Nav] Auto-navigating (intent detected) →`,e.url),hr(e.url,{siteId:i?.siteId,apiBaseUrl:i?.apiBaseUrl}).then(t=>{t&&xr(e.url,{voiceActive:Tt.current}).then(t=>{e.section&&setTimeout(()=>{let t=ur(null,e.section);t&&dr(t)},t?300:150)})})):(lt.current=e,console.log(`[FWH Nav] Stored pending nav →`,lt.current))}if(s.navigate?.url)if(ut.current)ut.current=!1;else{let{url:e,section:t}=s.navigate;xr(e,{voiceActive:Tt.current}).then(e=>{!t||!Tt.current||setTimeout(()=>{let e=ur(null,t);e&&dr(e)},e?300:150)})}else{let e=[...c].reverse().find(e=>e.sender===`bot`||e.sender===`assistant`);if(e?.message){let t=Or(e.message);t&&hr(t.url,{siteId:Et.current?.siteId,apiBaseUrl:Et.current?.apiBaseUrl}).then(e=>{e&&xr(t.url,{voiceActive:Tt.current}).then(e=>{!t.section||!Tt.current||setTimeout(()=>{let e=ur(null,t.section);e&&dr(e)},e?300:150)})})}}S(Dr(c)),me(!!s.is_human_handled),oe(s.is_human_handled?`agent`:`ai`),Ee(!1),Ae(!1),await D.current.updateChatStatus(g,`messageSent`)}catch(e){S(e=>e.filter(e=>e.id!==f)),Ee(!1),Ae(!1),e.status===429?(w(!0),Ne(e.message),window.setTimeout(()=>{w(!1),Ne(``)},v)):u(e)}},Qt=async e=>{if(!D.current||!e)throw Error(`Upload is unavailable right now.`);return D.current.uploadChatFile(e)},$t=async e=>{if(!(!D.current||!g)){try{let t=e?`voice`:`text`;await D.current.setChatMode(g,t)}catch{}Re(e),e&&(wt.current=!1)}},en=async e=>{if(wt.current)return;if(wt.current=!0,!D.current||!g||!e?.length){Re(!1);return}let t=()=>{let t=Dr(e);S(e=>{if(!e.length)return t;let n=e[e.length-1],r=t[0];return n&&r&&n.sender===r.sender&&n.message===r.message?e:[...e,...t]})};try{let n=await D.current.syncVoice(g,e);if(n?.chat_history?.length)S(Dr(n.chat_history));else if(n?.success)try{let e=await D.current.loadHistory(g,r);e?.chat_history?.length?S(Dr(e.chat_history)):t()}catch{t()}else t()}catch{t()}finally{Re(!1)}},tn=async()=>{if(!(!D.current||!g)){Pe&&!wt.current&&Ct.current.length>0&&await en(Ct.current);try{await D.current.endConversation(g)}catch{try{await D.current.updateChatStatus(g,`ended`)}catch{}}We(!0),S(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:`This conversation has ended. Thank you for reaching out!`,timestamp:new Date().toISOString(),isPending:!1}])}};(0,d.useEffect)(()=>{if(Je!==`connected`||!Ke||!g||!Xe||!kt)return;let e=new Date(Xe).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,kt*1e3-t),r=window.setTimeout(()=>{tt(`The call ended because it reached the time limit.`),Ut()},n);return()=>window.clearTimeout(r)},[Ke,Xe,Je,g,Ut,kt]),(0,d.useEffect)(()=>{let e=()=>{let e=it.current,t=D.current;if(!t||!e)return;if(Tt.current&&Ct.current.length>0&&Te(),!wt.current&&Ct.current.length>0&&(t.beaconSyncVoice(e,Ct.current)||t.syncVoice(e,Ct.current).catch(()=>{}),wt.current=!0),ft.current){t.beaconEndWebRTCCall(ft.current,e);return}let n=pt.current||O.current?.callId;n&&t.beaconCustomerUnavailable(n,e)};return window.addEventListener(`pagehide`,e),window.addEventListener(`beforeunload`,e),()=>{window.removeEventListener(`pagehide`,e),window.removeEventListener(`beforeunload`,e)}},[]);let nn=(0,d.useCallback)(()=>{let e=i?.siteId;ce(e),at.current=!0,ot.current=null,E.current?.disconnect(),S([]),_(``),it.current=``,We(!1),me(!1),_e(null),ye(null),rt(!0),o(e=>e+1)},[i?.siteId]),rn=(0,d.useCallback)(e=>{i?.siteId,at.current=!1,ot.current=e,E.current?.disconnect(),S([]),_(``),it.current=``,We(!1),me(!1),_e(null),ye(null),rt(!0),o(e=>e+1)},[i?.siteId]),an=(0,d.useMemo)(()=>({status:s,error:l,runtimeConfig:m,resolvedConfig:i,chatId:g,chatHistory:x,isOpen:re,activeScreen:ae,isHumanHandled:pe,agentName:he,agentHeadshot:ve,visitorEmail:be,isAgentTyping:Se,isAiTyping:we,connectionStatus:De,isLoading:ke,isVoiceMode:Pe,isRateLimited:je,rateLimitMessage:Me,isConversationEnded:Ue,isSessionRestoring:nt,openToChatCounter:ze,voiceEndCounter:Ve,incomingCall:T,activeCallId:Ke,callConnectionState:Je,callConnectedAt:Xe,isCallMuted:Qe,webRTCError:et,language:r,historyRef:Ct,hasSyncedRef:wt,dismissCallError:At,captureVisitorEmail:Kt,startTyping:qt,stopTyping:Jt,updateTypingDraft:Yt,notifyRouteChange:()=>Dt.current?.notifyRouteChange?.(),openWidget:Gt,closeWidget:()=>ie(!1),toggleWidget:()=>{if(re){ie(!1);return}Gt({notifyChatInitiated:!0})},sendMessage:Zt,uploadChatFile:Qt,setVoiceMode:$t,onMessageSync:en,endConversation:tn,startNewChat:nn,resumeChat:rn,getVisitorChatHistory:()=>D.current?.getVisitorChatHistory?.(),getVisitorChatThread:e=>D.current?.getVisitorChatThread?.(e),acceptCall:Bt,rejectCall:Vt,endWebRTCCall:Ut,toggleCallMute:Wt}),[s,l,m,i,g,x,re,ae,pe,he,ve,be,Se,we,De,ke,Pe,je,Me,Ue,nt,ze,Ve,T,Ke,Je,Xe,Qe,et,r,Kt,qt,Jt,Yt,Bt,Vt,Ut,Wt,Gt,Zt,Qt,$t,en,tn,nn,At]);return(0,f.jsx)(wn.Provider,{value:an,children:n})}var Pr=(0,d.createContext)({});function Fr(e){let t=(0,d.useRef)(null);return t.current===null&&(t.current=e()),t.current}var Ir=typeof window<`u`?d.useLayoutEffect:d.useEffect,Lr=(0,d.createContext)(null);function Rr(e,t){e.indexOf(t)===-1&&e.push(t)}function zr(e,t){let n=e.indexOf(t);n>-1&&e.splice(n,1)}var Br=(e,t,n)=>n>t?t:n<e?e:n;function Vr(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}var Hr=()=>{},Ur=()=>{};typeof process<`u`&&process.env.NODE_ENV!==`production`&&(Hr=(e,t,n)=>{!e&&typeof console<`u`&&console.warn(Vr(t,n))},Ur=(e,t,n)=>{if(!e)throw Error(Vr(t,n))});var Wr={},Gr=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function Kr(e){return typeof e==`object`&&!!e}var qr=e=>/^0[^.\s]+$/u.test(e);function Jr(e){let t;return()=>(t===void 0&&(t=e()),t)}var Yr=e=>e,Xr=(e,t)=>n=>t(e(n)),Zr=(...e)=>e.reduce(Xr),Qr=(e,t,n)=>{let r=t-e;return r===0?1:(n-e)/r},$r=class{constructor(){this.subscriptions=[]}add(e){return Rr(this.subscriptions,e),()=>zr(this.subscriptions,e)}notify(e,t,n){let r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](e,t,n);else for(let i=0;i<r;i++){let r=this.subscriptions[i];r&&r(e,t,n)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}},ei=e=>e*1e3,ti=e=>e/1e3;function ni(e,t){return t?1e3/t*e:0}var ri=new Set;function ii(e,t,n){e||ri.has(t)||(console.warn(Vr(t,n)),ri.add(t))}var ai=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,oi=1e-7,si=12;function ci(e,t,n,r,i){let a,o,s=0;do o=t+(n-t)/2,a=ai(o,r,i)-e,a>0?n=o:t=o;while(Math.abs(a)>oi&&++s<si);return o}function li(e,t,n,r){if(e===t&&n===r)return Yr;let i=t=>ci(t,0,1,e,n);return e=>e===0||e===1?e:ai(i(e),t,r)}var ui=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,di=e=>t=>1-e(1-t),fi=li(.33,1.53,.69,.99),pi=di(fi),mi=ui(pi),hi=e=>e>=1?1:(e*=2)<1?.5*pi(e):.5*(2-2**(-10*(e-1))),gi=e=>1-Math.sin(Math.acos(e)),_i=di(gi),vi=ui(gi),yi=li(.42,0,1,1),bi=li(0,0,.58,1),xi=li(.42,0,.58,1),Si=e=>Array.isArray(e)&&typeof e[0]!=`number`,Ci=e=>Array.isArray(e)&&typeof e[0]==`number`,wi={linear:Yr,easeIn:yi,easeInOut:xi,easeOut:bi,circIn:gi,circInOut:vi,circOut:_i,backIn:pi,backInOut:mi,backOut:fi,anticipate:hi},Ti=e=>typeof e==`string`,Ei=e=>{if(Ci(e)){Ur(e.length===4,`Cubic bezier arrays must contain four numerical values.`,`cubic-bezier-length`);let[t,n,r,i]=e;return li(t,n,r,i)}else if(Ti(e))return Ur(wi[e]!==void 0,`Invalid easing type '${e}'`,`invalid-easing-type`),wi[e];return e},Di=[`setup`,`read`,`resolveKeyframes`,`preUpdate`,`update`,`preRender`,`render`,`postRender`],Oi={value:null,addProjectionMetrics:null};function ki(e,t){let n=new Set,r=new Set,i=!1,a=!1,o=new WeakSet,s={delta:0,timestamp:0,isProcessing:!1},c=0;function l(t){o.has(t)&&(u.schedule(t),e()),c++,t(s)}let u={schedule:(e,t=!1,a=!1)=>{let s=a&&i?n:r;return t&&o.add(e),s.add(e),e},cancel:e=>{r.delete(e),o.delete(e)},process:e=>{if(s=e,i){a=!0;return}i=!0;let o=n;n=r,r=o,n.forEach(l),t&&Oi.value&&Oi.value.frameloop[t].push(c),c=0,n.clear(),i=!1,a&&(a=!1,u.process(e))}};return u}var Ai=40;function ji(e,t){let n=!1,r=!0,i={delta:0,timestamp:0,isProcessing:!1},a=()=>n=!0,o=Di.reduce((e,n)=>(e[n]=ki(a,t?n:void 0),e),{}),{setup:s,read:c,resolveKeyframes:l,preUpdate:u,update:d,preRender:f,render:p,postRender:m}=o,h=()=>{let a=Wr.useManualTiming,o=a?i.timestamp:performance.now();n=!1,a||(i.delta=r?1e3/60:Math.max(Math.min(o-i.timestamp,Ai),1)),i.timestamp=o,i.isProcessing=!0,s.process(i),c.process(i),l.process(i),u.process(i),d.process(i),f.process(i),p.process(i),m.process(i),i.isProcessing=!1,n&&t&&(r=!1,e(h))},g=()=>{n=!0,r=!0,i.isProcessing||e(h)};return{schedule:Di.reduce((e,t)=>{let r=o[t];return e[t]=(e,t=!1,i=!1)=>(n||g(),r.schedule(e,t,i)),e},{}),cancel:e=>{for(let t=0;t<Di.length;t++)o[Di[t]].cancel(e)},state:i,steps:o}}var{schedule:N,cancel:Mi,state:Ni,steps:Pi}=ji(typeof requestAnimationFrame<`u`?requestAnimationFrame:Yr,!0),Fi;function Ii(){Fi=void 0}var Li={now:()=>(Fi===void 0&&Li.set(Ni.isProcessing||Wr.useManualTiming?Ni.timestamp:performance.now()),Fi),set:e=>{Fi=e,queueMicrotask(Ii)}},Ri={layout:0,mainThread:0,waapi:0},zi=e=>t=>typeof t==`string`&&t.startsWith(e),Bi=zi(`--`),Vi=zi(`var(--`),Hi=e=>Vi(e)?Ui.test(e.split(`/*`)[0].trim()):!1,Ui=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function Wi(e){return typeof e==`string`?e.split(`/*`)[0].includes(`var(--`):!1}var Gi={test:e=>typeof e==`number`,parse:parseFloat,transform:e=>e},Ki={...Gi,transform:e=>Br(0,1,e)},qi={...Gi,default:1},Ji=e=>Math.round(e*1e5)/1e5,Yi=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Xi(e){return e==null}var Zi=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Qi=(e,t)=>n=>!!(typeof n==`string`&&Zi.test(n)&&n.startsWith(e)||t&&!Xi(n)&&Object.prototype.hasOwnProperty.call(n,t)),$i=(e,t,n)=>r=>{if(typeof r!=`string`)return r;let[i,a,o,s]=r.match(Yi);return{[e]:parseFloat(i),[t]:parseFloat(a),[n]:parseFloat(o),alpha:s===void 0?1:parseFloat(s)}},ea=e=>Br(0,255,e),ta={...Gi,transform:e=>Math.round(ea(e))},na={test:Qi(`rgb`,`red`),parse:$i(`red`,`green`,`blue`),transform:({red:e,green:t,blue:n,alpha:r=1})=>`rgba(`+ta.transform(e)+`, `+ta.transform(t)+`, `+ta.transform(n)+`, `+Ji(Ki.transform(r))+`)`};function ra(e){let t=``,n=``,r=``,i=``;return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),r=e.substring(5,7),i=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),r=e.substring(3,4),i=e.substring(4,5),t+=t,n+=n,r+=r,i+=i),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(r,16),alpha:i?parseInt(i,16)/255:1}}var ia={test:Qi(`#`),parse:ra,transform:na.transform},aa=e=>({test:t=>typeof t==`string`&&t.endsWith(e)&&t.split(` `).length===1,parse:parseFloat,transform:t=>`${t}${e}`}),oa=aa(`deg`),sa=aa(`%`),P=aa(`px`),ca=aa(`vh`),la=aa(`vw`),ua={...sa,parse:e=>sa.parse(e)/100,transform:e=>sa.transform(e*100)},da={test:Qi(`hsl`,`hue`),parse:$i(`hue`,`saturation`,`lightness`),transform:({hue:e,saturation:t,lightness:n,alpha:r=1})=>`hsla(`+Math.round(e)+`, `+sa.transform(Ji(t))+`, `+sa.transform(Ji(n))+`, `+Ji(Ki.transform(r))+`)`},fa={test:e=>na.test(e)||ia.test(e)||da.test(e),parse:e=>na.test(e)?na.parse(e):da.test(e)?da.parse(e):ia.parse(e),transform:e=>typeof e==`string`?e:e.hasOwnProperty(`red`)?na.transform(e):da.transform(e),getAnimatableNone:e=>{let t=fa.parse(e);return t.alpha=0,fa.transform(t)}},pa=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function ma(e){return isNaN(e)&&typeof e==`string`&&(e.match(Yi)?.length||0)+(e.match(pa)?.length||0)>0}var ha=`number`,ga=`color`,_a=`var`,va=`var(`,ya="${}",ba=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function xa(e){let t=e.toString(),n=[],r={color:[],number:[],var:[]},i=[],a=0;return{values:n,split:t.replace(ba,e=>(fa.test(e)?(r.color.push(a),i.push(ga),n.push(fa.parse(e))):e.startsWith(va)?(r.var.push(a),i.push(_a),n.push(e)):(r.number.push(a),i.push(ha),n.push(parseFloat(e))),++a,ya)).split(ya),indexes:r,types:i}}function Sa(e){return xa(e).values}function Ca({split:e,types:t}){let n=e.length;return r=>{let i=``;for(let a=0;a<n;a++)if(i+=e[a],r[a]!==void 0){let e=t[a];e===ha?i+=Ji(r[a]):e===ga?i+=fa.transform(r[a]):i+=r[a]}return i}}function wa(e){return Ca(xa(e))}var Ta=e=>typeof e==`number`?0:fa.test(e)?fa.getAnimatableNone(e):e,Ea=(e,t)=>typeof e==`number`?t?.trim().endsWith(`/`)?e:0:Ta(e);function Da(e){let t=xa(e);return Ca(t)(t.values.map((e,n)=>Ea(e,t.split[n])))}var Oa={test:ma,parse:Sa,createTransformer:wa,getAnimatableNone:Da};function ka(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function Aa({hue:e,saturation:t,lightness:n,alpha:r}){e/=360,t/=100,n/=100;let i=0,a=0,o=0;if(!t)i=a=o=n;else{let r=n<.5?n*(1+t):n+t-n*t,s=2*n-r;i=ka(s,r,e+1/3),a=ka(s,r,e),o=ka(s,r,e-1/3)}return{red:Math.round(i*255),green:Math.round(a*255),blue:Math.round(o*255),alpha:r}}function ja(e,t){return n=>n>0?t:e}var Ma=(e,t,n)=>e+(t-e)*n,Na=(e,t,n)=>{let r=e*e,i=n*(t*t-r)+r;return i<0?0:Math.sqrt(i)},Pa=[ia,na,da],Fa=e=>Pa.find(t=>t.test(e));function Ia(e){let t=Fa(e);if(Hr(!!t,`'${e}' is not an animatable color. Use the equivalent color code instead.`,`color-not-animatable`),!t)return!1;let n=t.parse(e);return t===da&&(n=Aa(n)),n}var La=(e,t)=>{let n=Ia(e),r=Ia(t);if(!n||!r)return ja(e,t);let i={...n};return e=>(i.red=Na(n.red,r.red,e),i.green=Na(n.green,r.green,e),i.blue=Na(n.blue,r.blue,e),i.alpha=Ma(n.alpha,r.alpha,e),na.transform(i))},Ra=new Set([`none`,`hidden`]);function za(e,t){return Ra.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function Ba(e,t){return n=>Ma(e,t,n)}function Va(e){return typeof e==`number`?Ba:typeof e==`string`?Hi(e)?ja:fa.test(e)?La:Ga:Array.isArray(e)?Ha:typeof e==`object`?fa.test(e)?La:Ua:ja}function Ha(e,t){let n=[...e],r=n.length,i=e.map((e,n)=>Va(e)(e,t[n]));return e=>{for(let t=0;t<r;t++)n[t]=i[t](e);return n}}function Ua(e,t){let n={...e,...t},r={};for(let i in n)e[i]!==void 0&&t[i]!==void 0&&(r[i]=Va(e[i])(e[i],t[i]));return e=>{for(let t in r)n[t]=r[t](e);return n}}function Wa(e,t){let n=[],r={color:0,var:0,number:0};for(let i=0;i<t.values.length;i++){let a=t.types[i],o=e.indexes[a][r[a]];n[i]=e.values[o]??0,r[a]++}return n}var Ga=(e,t)=>{let n=Oa.createTransformer(t),r=xa(e),i=xa(t);return r.indexes.var.length===i.indexes.var.length&&r.indexes.color.length===i.indexes.color.length&&r.indexes.number.length>=i.indexes.number.length?Ra.has(e)&&!i.values.length||Ra.has(t)&&!r.values.length?za(e,t):Zr(Ha(Wa(r,i),i.values),n):(Hr(!0,`Complex values '${e}' and '${t}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,`complex-values-different`),ja(e,t))};function Ka(e,t,n){return typeof e==`number`&&typeof t==`number`&&typeof n==`number`?Ma(e,t,n):Va(e)(e,t)}var qa=e=>{let t=({timestamp:t})=>e(t);return{start:(e=!0)=>N.update(t,e),stop:()=>Mi(t),now:()=>Ni.isProcessing?Ni.timestamp:Li.now()}},Ja=(e,t,n=10)=>{let r=``,i=Math.max(Math.round(t/n),2);for(let t=0;t<i;t++)r+=Math.round(e(t/(i-1))*1e4)/1e4+`, `;return`linear(${r.substring(0,r.length-2)})`},Ya=2e4;function Xa(e){let t=0,n=e.next(t);for(;!n.done&&t<2e4;)t+=50,n=e.next(t);return t>=2e4?1/0:t}function Za(e,t=100,n){let r=n({...e,keyframes:[0,t]}),i=Math.min(Xa(r),Ya);return{type:`keyframes`,ease:e=>r.next(i*e).value/t,duration:ti(i)}}var Qa={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1};function $a(e,t){return e*Math.sqrt(1-t*t)}var eo=12;function to(e,t,n){let r=n;for(let n=1;n<eo;n++)r-=e(r)/t(r);return r}var no=.001;function ro({duration:e=Qa.duration,bounce:t=Qa.bounce,velocity:n=Qa.velocity,mass:r=Qa.mass}){let i,a;Hr(e<=ei(Qa.maxDuration),`Spring duration must be 10 seconds or less`,`spring-duration-limit`);let o=1-t;o=Br(Qa.minDamping,Qa.maxDamping,o),e=Br(Qa.minDuration,Qa.maxDuration,ti(e)),o<1?(i=t=>{let r=t*o,i=r*e,a=r-n,s=$a(t,o),c=Math.exp(-i);return no-a/s*c},a=t=>{let r=t*o*e,a=r*n+n,s=o**2*t**2*e,c=Math.exp(-r),l=$a(t**2,o);return(-i(t)+no>0?-1:1)*((a-s)*c)/l}):(i=t=>{let r=Math.exp(-t*e),i=(t-n)*e+1;return-no+r*i},a=t=>Math.exp(-t*e)*((n-t)*(e*e)));let s=5/e,c=to(i,a,s);if(e=ei(e),isNaN(c))return{stiffness:Qa.stiffness,damping:Qa.damping,duration:e};{let t=c**2*r;return{stiffness:t,damping:o*2*Math.sqrt(r*t),duration:e}}}var io=[`duration`,`bounce`],ao=[`stiffness`,`damping`,`mass`];function oo(e,t){return t.some(t=>e[t]!==void 0)}function so(e){let t={velocity:Qa.velocity,stiffness:Qa.stiffness,damping:Qa.damping,mass:Qa.mass,isResolvedFromDuration:!1,...e};if(!oo(e,ao)&&oo(e,io))if(t.velocity=0,e.visualDuration){let n=e.visualDuration,r=2*Math.PI/(n*1.2),i=r*r,a=2*Br(.05,1,1-(e.bounce||0))*Math.sqrt(i);t={...t,mass:Qa.mass,stiffness:i,damping:a}}else{let n=ro({...e,velocity:0});t={...t,...n,mass:Qa.mass},t.isResolvedFromDuration=!0}return t}function co(e=Qa.visualDuration,t=Qa.bounce){let n=typeof e==`object`?e:{visualDuration:e,keyframes:[0,1],bounce:t},{restSpeed:r,restDelta:i}=n,a=n.keyframes[0],o=n.keyframes[n.keyframes.length-1],s={done:!1,value:a},{stiffness:c,damping:l,mass:u,duration:d,velocity:f,isResolvedFromDuration:p}=so({...n,velocity:-ti(n.velocity||0)}),m=f||0,h=l/(2*Math.sqrt(c*u)),g=o-a,_=ti(Math.sqrt(c/u)),v=Math.abs(g)<5;r||=v?Qa.restSpeed.granular:Qa.restSpeed.default,i||=v?Qa.restDelta.granular:Qa.restDelta.default;let y,b,x,S,ee,te;if(h<1)x=$a(_,h),S=(m+h*_*g)/x,y=e=>o-Math.exp(-h*_*e)*(S*Math.sin(x*e)+g*Math.cos(x*e)),ee=h*_*S+g*x,te=h*_*g-S*x,b=e=>Math.exp(-h*_*e)*(ee*Math.sin(x*e)+te*Math.cos(x*e));else if(h===1){y=e=>o-Math.exp(-_*e)*(g+(m+_*g)*e);let e=m+_*g;b=t=>Math.exp(-_*t)*(_*e*t-m)}else{let e=_*Math.sqrt(h*h-1);y=t=>{let n=Math.exp(-h*_*t),r=Math.min(e*t,300);return o-n*((m+h*_*g)*Math.sinh(r)+e*g*Math.cosh(r))/e};let t=(m+h*_*g)/e,n=h*_*t-g*e,r=h*_*g-t*e;b=t=>{let i=Math.exp(-h*_*t),a=Math.min(e*t,300);return i*(n*Math.sinh(a)+r*Math.cosh(a))}}let ne={calculatedDuration:p&&d||null,velocity:e=>ei(b(e)),next:e=>{if(!p&&h<1){let t=Math.exp(-h*_*e),n=Math.sin(x*e),a=Math.cos(x*e),c=o-t*(S*n+g*a),l=ei(t*(ee*n+te*a));return s.done=Math.abs(l)<=r&&Math.abs(o-c)<=i,s.value=s.done?o:c,s}let t=y(e);if(p)s.done=e>=d;else{let n=ei(b(e));s.done=Math.abs(n)<=r&&Math.abs(o-t)<=i}return s.value=s.done?o:t,s},toString:()=>{let e=Math.min(Xa(ne),Ya),t=Ja(t=>ne.next(e*t).value,e,30);return e+`ms `+t},toTransition:()=>{}};return ne}co.applyToOptions=e=>{let t=Za(e,100,co);return e.ease=t.ease,e.duration=ei(t.duration),e.type=`keyframes`,e};var lo=5;function uo(e,t,n){let r=Math.max(t-lo,0);return ni(n-e(r),t-r)}function fo({keyframes:e,velocity:t=0,power:n=.8,timeConstant:r=325,bounceDamping:i=10,bounceStiffness:a=500,modifyTarget:o,min:s,max:c,restDelta:l=.5,restSpeed:u}){let d=e[0],f={done:!1,value:d},p=e=>s!==void 0&&e<s||c!==void 0&&e>c,m=e=>s===void 0?c:c===void 0||Math.abs(s-e)<Math.abs(c-e)?s:c,h=n*t,g=d+h,_=o===void 0?g:o(g);_!==g&&(h=_-d);let v=e=>-h*Math.exp(-e/r),y=e=>_+v(e),b=e=>{let t=v(e),n=y(e);f.done=Math.abs(t)<=l,f.value=f.done?_:n},x,S,ee=e=>{p(f.value)&&(x=e,S=co({keyframes:[f.value,m(f.value)],velocity:uo(y,e,f.value),damping:i,stiffness:a,restDelta:l,restSpeed:u}))};return ee(0),{calculatedDuration:null,next:e=>{let t=!1;return!S&&x===void 0&&(t=!0,b(e),ee(e)),x!==void 0&&e>=x?S.next(e-x):(!t&&b(e),f)}}}function po(e,t,n){let r=[],i=n||Wr.mix||Ka,a=e.length-1;for(let n=0;n<a;n++){let a=i(e[n],e[n+1]);t&&(a=Zr(Array.isArray(t)?t[n]||Yr:t,a)),r.push(a)}return r}function mo(e,t,{clamp:n=!0,ease:r,mixer:i}={}){let a=e.length;if(Ur(a===t.length,`Both input and output ranges must be the same length`,`range-length`),a===1)return()=>t[0];if(a===2&&t[0]===t[1])return()=>t[1];let o=e[0]===e[1];e[0]>e[a-1]&&(e=[...e].reverse(),t=[...t].reverse());let s=po(t,r,i),c=s.length,l=n=>{if(o&&n<e[0])return t[0];let r=0;if(c>1)for(;r<e.length-2&&!(n<e[r+1]);r++);let i=Qr(e[r],e[r+1],n);return s[r](i)};return n?t=>l(Br(e[0],e[a-1],t)):l}function ho(e,t){let n=e[e.length-1];for(let r=1;r<=t;r++){let i=Qr(0,t,r);e.push(Ma(n,1,i))}}function go(e){let t=[0];return ho(t,e.length-1),t}function _o(e,t){return e.map(e=>e*t)}function vo(e,t){return e.map(()=>t||xi).splice(0,e.length-1)}function yo({duration:e=300,keyframes:t,times:n,ease:r=`easeInOut`}){let i=Si(r)?r.map(Ei):Ei(r),a={done:!1,value:t[0]},o=mo(_o(n&&n.length===t.length?n:go(t),e),t,{ease:Array.isArray(i)?i:vo(t,i)});return{calculatedDuration:e,next:t=>(a.value=o(t),a.done=t>=e,a)}}var bo=e=>e!==null;function xo(e,{repeat:t,repeatType:n=`loop`},r,i=1){let a=e.filter(bo),o=i<0||t&&n!==`loop`&&t%2==1?0:a.length-1;return!o||r===void 0?a[o]:r}var So={decay:fo,inertia:fo,tween:yo,keyframes:yo,spring:co};function Co(e){typeof e.type==`string`&&(e.type=So[e.type])}var wo=class{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,t){return this.finished.then(e,t)}},To=e=>e/100,Eo=class extends wo{constructor(e){super(),this.state=`idle`,this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.delayState={done:!1,value:void 0},this.stop=()=>{let{motionValue:e}=this.options;e&&e.updatedAt!==Li.now()&&this.tick(Li.now()),this.isStopped=!0,this.state!==`idle`&&(this.teardown(),this.options.onStop?.())},Ri.mainThread++,this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){let{options:e}=this;Co(e);let{type:t=yo,repeat:n=0,repeatDelay:r=0,repeatType:i,velocity:a=0}=e,{keyframes:o}=e,s=t||yo;process.env.NODE_ENV!==`production`&&s!==yo&&Ur(o.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${o}`,`spring-two-frames`),s!==yo&&typeof o[0]!=`number`&&(this.mixKeyframes=Zr(To,Ka(o[0],o[1])),o=[0,100]);let c=s({...e,keyframes:o});i===`mirror`&&(this.mirroredGenerator=s({...e,keyframes:[...o].reverse(),velocity:-a})),c.calculatedDuration===null&&(c.calculatedDuration=Xa(c));let{calculatedDuration:l}=c;this.calculatedDuration=l,this.resolvedDuration=l+r,this.totalDuration=this.resolvedDuration*(n+1)-r,this.generator=c}updateTime(e){let t=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime===null?this.currentTime=t:this.currentTime=this.holdTime}tick(e,t=!1){let{generator:n,totalDuration:r,mixKeyframes:i,mirroredGenerator:a,resolvedDuration:o,calculatedDuration:s}=this;if(this.startTime===null)return n.next(0);let{delay:c=0,keyframes:l,repeat:u,repeatType:d,repeatDelay:f,type:p,onUpdate:m,finalKeyframe:h}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-r/this.speed,this.startTime)),t?this.currentTime=e:this.updateTime(e);let g=this.currentTime-c*(this.playbackSpeed>=0?1:-1),_=this.playbackSpeed>=0?g<0:g>r;this.currentTime=Math.max(g,0),this.state===`finished`&&this.holdTime===null&&(this.currentTime=r);let v=this.currentTime,y=n;if(u){let e=Math.min(this.currentTime,r)/o,t=Math.floor(e),n=e%1;!n&&e>=1&&(n=1),n===1&&t--,t=Math.min(t,u+1),t%2&&(d===`reverse`?(n=1-n,f&&(n-=f/o)):d===`mirror`&&(y=a)),v=Br(0,1,n)*o}let b;_?(this.delayState.value=l[0],b=this.delayState):b=y.next(v),i&&!_&&(b.value=i(b.value));let{done:x}=b;!_&&s!==null&&(x=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);let S=this.holdTime===null&&(this.state===`finished`||this.state===`running`&&x);return S&&p!==fo&&(b.value=xo(l,this.options,h,this.speed)),m&&m(b.value),S&&this.finish(),b}then(e,t){return this.finished.then(e,t)}get duration(){return ti(this.calculatedDuration)}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+ti(e)}get time(){return ti(this.currentTime)}set time(e){e=ei(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),this.driver?this.driver.start(!1):(this.startTime=0,this.state=`paused`,this.holdTime=e,this.tick(e))}getGeneratorVelocity(){let e=this.currentTime;if(e<=0)return this.options.velocity||0;if(this.generator.velocity)return this.generator.velocity(e);let t=this.generator.next(e).value;return uo(e=>this.generator.next(e).value,e,t)}get speed(){return this.playbackSpeed}set speed(e){let t=this.playbackSpeed!==e;t&&this.driver&&this.updateTime(Li.now()),this.playbackSpeed=e,t&&this.driver&&(this.time=ti(this.currentTime))}play(){if(this.isStopped)return;let{driver:e=qa,startTime:t}=this.options;this.driver||=e(e=>this.tick(e)),this.options.onPlay?.();let n=this.driver.now();this.state===`finished`?(this.updateFinished(),this.startTime=n):this.holdTime===null?this.startTime||=t??n:this.startTime=n-this.holdTime,this.state===`finished`&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state=`running`,this.driver.start()}pause(){this.state=`paused`,this.updateTime(Li.now()),this.holdTime=this.currentTime}complete(){this.state!==`running`&&this.play(),this.state=`finished`,this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state=`finished`,this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state=`idle`,this.stopDriver(),this.startTime=this.holdTime=null,Ri.mainThread--}stopDriver(){this.driver&&=(this.driver.stop(),void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){return this.options.allowFlatten&&(this.options.type=`keyframes`,this.options.ease=`linear`,this.initAnimation()),this.driver?.stop(),e.observe(this)}};function Do(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}var Oo=e=>e*180/Math.PI,ko=e=>jo(Oo(Math.atan2(e[1],e[0]))),Ao={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:ko,rotateZ:ko,skewX:e=>Oo(Math.atan(e[1])),skewY:e=>Oo(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},jo=e=>(e%=360,e<0&&(e+=360),e),Mo=ko,No=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),Po=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),Fo={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:No,scaleY:Po,scale:e=>(No(e)+Po(e))/2,rotateX:e=>jo(Oo(Math.atan2(e[6],e[5]))),rotateY:e=>jo(Oo(Math.atan2(-e[2],e[0]))),rotateZ:Mo,rotate:Mo,skewX:e=>Oo(Math.atan(e[4])),skewY:e=>Oo(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function Io(e){return e.includes(`scale`)?1:0}function Lo(e,t){if(!e||e===`none`)return Io(t);let n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u),r,i;if(n)r=Fo,i=n;else{let t=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=Ao,i=t}if(!i)return Io(t);let a=r[t],o=i[1].split(`,`).map(zo);return typeof a==`function`?a(o):o[a]}var Ro=(e,t)=>{let{transform:n=`none`}=getComputedStyle(e);return Lo(n,t)};function zo(e){return parseFloat(e.trim())}var Bo=[`transformPerspective`,`x`,`y`,`z`,`translateX`,`translateY`,`translateZ`,`scale`,`scaleX`,`scaleY`,`rotate`,`rotateX`,`rotateY`,`rotateZ`,`skew`,`skewX`,`skewY`],Vo=new Set(Bo),Ho=e=>e===Gi||e===P,Uo=new Set([`x`,`y`,`z`]),Wo=Bo.filter(e=>!Uo.has(e));function Go(e){let t=[];return Wo.forEach(n=>{let r=e.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith(`scale`)?1:0))}),t}var Ko={width:({x:e},{paddingLeft:t=`0`,paddingRight:n=`0`,boxSizing:r})=>{let i=e.max-e.min;return r===`border-box`?i:i-parseFloat(t)-parseFloat(n)},height:({y:e},{paddingTop:t=`0`,paddingBottom:n=`0`,boxSizing:r})=>{let i=e.max-e.min;return r===`border-box`?i:i-parseFloat(t)-parseFloat(n)},top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:(e,{transform:t})=>Lo(t,`x`),y:(e,{transform:t})=>Lo(t,`y`)};Ko.translateX=Ko.x,Ko.translateY=Ko.y;var qo=new Set,Jo=!1,Yo=!1,Xo=!1;function Zo(){if(Yo){let e=Array.from(qo).filter(e=>e.needsMeasurement),t=new Set(e.map(e=>e.element)),n=new Map;t.forEach(e=>{let t=Go(e);t.length&&(n.set(e,t),e.render())}),e.forEach(e=>e.measureInitialState()),t.forEach(e=>{e.render();let t=n.get(e);t&&t.forEach(([t,n])=>{e.getValue(t)?.set(n)})}),e.forEach(e=>e.measureEndState()),e.forEach(e=>{e.suspendedScrollY!==void 0&&window.scrollTo(0,e.suspendedScrollY)})}Yo=!1,Jo=!1,qo.forEach(e=>e.complete(Xo)),qo.clear()}function Qo(){qo.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(Yo=!0)})}function $o(){Xo=!0,Qo(),Zo(),Xo=!1}var es=class{constructor(e,t,n,r,i,a=!1){this.state=`pending`,this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=t,this.name=n,this.motionValue=r,this.element=i,this.isAsync=a}scheduleResolve(){this.state=`scheduled`,this.isAsync?(qo.add(this),Jo||(Jo=!0,N.read(Qo),N.resolveKeyframes(Zo))):(this.readKeyframes(),this.complete())}readKeyframes(){let{unresolvedKeyframes:e,name:t,element:n,motionValue:r}=this;if(e[0]===null){let i=r?.get(),a=e[e.length-1];if(i!==void 0)e[0]=i;else if(n&&t){let r=n.readValue(t,a);r!=null&&(e[0]=r)}e[0]===void 0&&(e[0]=a),r&&i===void 0&&r.set(e[0])}Do(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state=`complete`,this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),qo.delete(this)}cancel(){this.state===`scheduled`&&(qo.delete(this),this.state=`pending`)}resume(){this.state===`pending`&&this.scheduleResolve()}},ts=e=>e.startsWith(`--`);function ns(e,t,n){ts(t)?e.style.setProperty(t,n):e.style[t]=n}var rs={};function is(e,t){let n=Jr(e);return()=>rs[t]??n()}var as=is(()=>window.ScrollTimeline!==void 0,`scrollTimeline`),os=is(()=>{try{document.createElement(`div`).animate({opacity:0},{easing:`linear(0, 1)`})}catch{return!1}return!0},`linearEasing`),ss=([e,t,n,r])=>`cubic-bezier(${e}, ${t}, ${n}, ${r})`,cs={linear:`linear`,ease:`ease`,easeIn:`ease-in`,easeOut:`ease-out`,easeInOut:`ease-in-out`,circIn:ss([0,.65,.55,1]),circOut:ss([.55,0,1,.45]),backIn:ss([.31,.01,.66,-.59]),backOut:ss([.33,1.53,.69,.99])};function ls(e,t){if(e)return typeof e==`function`?os()?Ja(e,t):`ease-out`:Ci(e)?ss(e):Array.isArray(e)?e.map(e=>ls(e,t)||cs.easeOut):cs[e]}function us(e,t,n,{delay:r=0,duration:i=300,repeat:a=0,repeatType:o=`loop`,ease:s=`easeOut`,times:c}={},l=void 0){let u={[t]:n};c&&(u.offset=c);let d=ls(s,i);Array.isArray(d)&&(u.easing=d),Oi.value&&Ri.waapi++;let f={delay:r,duration:i,easing:Array.isArray(d)?`linear`:d,fill:`both`,iterations:a+1,direction:o===`reverse`?`alternate`:`normal`};l&&(f.pseudoElement=l);let p=e.animate(u,f);return Oi.value&&p.finished.finally(()=>{Ri.waapi--}),p}function ds(e){return typeof e==`function`&&`applyToOptions`in e}function fs({type:e,...t}){return ds(e)&&os()?e.applyToOptions(t):(t.duration??=300,t.ease??=`easeOut`,t)}var ps=class extends wo{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!e)return;let{element:t,name:n,keyframes:r,pseudoElement:i,allowFlatten:a=!1,finalKeyframe:o,onComplete:s}=e;this.isPseudoElement=!!i,this.allowFlatten=a,this.options=e,Ur(typeof e.type!=`string`,`Mini animate() doesn't support "type" as a string.`,`mini-spring`);let c=fs(e);this.animation=us(t,n,r,c,i),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){let e=xo(r,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(e),ns(t,n,e),this.animation.cancel()}s?.(),this.notifyFinished()}}play(){this.isStopped||(this.manualStartTime=null,this.animation.play(),this.state===`finished`&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;let{state:e}=this;e===`idle`||e===`finished`||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){let e=this.options?.element;!this.isPseudoElement&&e?.isConnected&&this.animation.commitStyles?.()}get duration(){let e=this.animation.effect?.getComputedTiming?.().duration||0;return ti(Number(e))}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+ti(e)}get time(){return ti(Number(this.animation.currentTime)||0)}set time(e){let t=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=ei(e),t&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime===null?this.animation.playState:`finished`}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(e){this.manualStartTime=this.animation.startTime=e}attachTimeline({timeline:e,rangeStart:t,rangeEnd:n,observe:r}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:`linear`}),this.animation.onfinish=null,e&&as()?(this.animation.timeline=e,t&&(this.animation.rangeStart=t),n&&(this.animation.rangeEnd=n),Yr):r(this)}},ms={anticipate:hi,backInOut:mi,circInOut:vi};function hs(e){return e in ms}function gs(e){typeof e.ease==`string`&&hs(e.ease)&&(e.ease=ms[e.ease])}var _s=10,vs=class extends ps{constructor(e){gs(e),Co(e),super(e),e.startTime!==void 0&&e.autoplay!==!1&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){let{motionValue:t,onUpdate:n,onComplete:r,element:i,...a}=this.options;if(!t)return;if(e!==void 0){t.set(e);return}let o=new Eo({...a,autoplay:!1}),s=Math.max(_s,Li.now()-this.startTime),c=Br(0,_s,s-_s),l=o.sample(s).value,{name:u}=this.options;i&&u&&ns(i,u,l),t.setWithVelocity(o.sample(Math.max(0,s-c)).value,l,c),o.stop()}},ys=(e,t)=>t===`zIndex`?!1:!!(typeof e==`number`||Array.isArray(e)||typeof e==`string`&&(Oa.test(e)||e===`0`)&&!e.startsWith(`url(`));function bs(e){let t=e[0];if(e.length===1)return!0;for(let n=0;n<e.length;n++)if(e[n]!==t)return!0}function xs(e,t,n,r){let i=e[0];if(i===null)return!1;if(t===`display`||t===`visibility`)return!0;let a=e[e.length-1],o=ys(i,t),s=ys(a,t);return Hr(o===s,`You are trying to animate ${t} from "${i}" to "${a}". "${o?a:i}" is not an animatable value.`,`value-not-animatable`),!o||!s?!1:bs(e)||(n===`spring`||ds(n))&&r}function Ss(e){e.duration=0,e.type=`keyframes`}var Cs=new Set([`opacity`,`clipPath`,`filter`,`transform`]),ws=/^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;function Ts(e){for(let t=0;t<e.length;t++)if(typeof e[t]==`string`&&ws.test(e[t]))return!0;return!1}var Es=new Set([`color`,`backgroundColor`,`outlineColor`,`fill`,`stroke`,`borderColor`,`borderTopColor`,`borderRightColor`,`borderBottomColor`,`borderLeftColor`]),Ds=Jr(()=>Object.hasOwnProperty.call(Element.prototype,`animate`));function Os(e){let{motionValue:t,name:n,repeatDelay:r,repeatType:i,damping:a,type:o,keyframes:s}=e;if(!(t?.owner?.current instanceof HTMLElement))return!1;let{onUpdate:c,transformTemplate:l}=t.owner.getProps();return Ds()&&n&&(Cs.has(n)||Es.has(n)&&Ts(s))&&(n!==`transform`||!l)&&!c&&!r&&i!==`mirror`&&a!==0&&o!==`inertia`}var ks=40,As=class extends wo{constructor({autoplay:e=!0,delay:t=0,type:n=`keyframes`,repeat:r=0,repeatDelay:i=0,repeatType:a=`loop`,keyframes:o,name:s,motionValue:c,element:l,...u}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=Li.now();let d={autoplay:e,delay:t,type:n,repeat:r,repeatDelay:i,repeatType:a,name:s,motionValue:c,element:l,...u};this.keyframeResolver=new(l?.KeyframeResolver||es)(o,(e,t,n)=>this.onKeyframesResolved(e,t,d,!n),s,c,l),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(e,t,n,r){this.keyframeResolver=void 0;let{name:i,type:a,velocity:o,delay:s,isHandoff:c,onUpdate:l}=n;this.resolvedAt=Li.now();let u=!0;xs(e,i,a,o)||(u=!1,(Wr.instantAnimations||!s)&&l?.(xo(e,n,t)),e[0]=e[e.length-1],Ss(n),n.repeat=0);let d={startTime:r?this.resolvedAt&&this.resolvedAt-this.createdAt>ks?this.resolvedAt:this.createdAt:void 0,finalKeyframe:t,...n,keyframes:e},f=u&&!c&&Os(d),p=d.motionValue?.owner?.current,m;if(f)try{m=new vs({...d,element:p})}catch{m=new Eo(d)}else m=new Eo(d);m.finished.then(()=>{this.notifyFinished()}).catch(Yr),this.pendingTimeline&&=(this.stopTimeline=m.attachTimeline(this.pendingTimeline),void 0),this._animation=m}get finished(){return this._animation?this.animation.finished:this._finished}then(e,t){return this.finished.finally(e).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),$o()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}};function js(e,t,n,r=0,i=1){let a=Array.from(e).sort((e,t)=>e.sortNodePosition(t)).indexOf(t),o=e.size,s=(o-1)*r;return typeof n==`function`?n(a,o):i===1?a*r:s-a*r}var Ms=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Ns(e){let t=Ms.exec(e);if(!t)return[,];let[,n,r,i]=t;return[`--${n??r}`,i]}var Ps=4;function Fs(e,t,n=1){Ur(n<=Ps,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,`max-css-var-depth`);let[r,i]=Ns(e);if(!r)return;let a=window.getComputedStyle(t).getPropertyValue(r);if(a){let e=a.trim();return Gr(e)?parseFloat(e):e}return Hi(i)?Fs(i,t,n+1):i}var Is={type:`spring`,stiffness:500,damping:25,restSpeed:10},Ls=e=>({type:`spring`,stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),Rs={type:`keyframes`,duration:.8},zs={type:`keyframes`,ease:[.25,.1,.35,1],duration:.3},Bs=(e,{keyframes:t})=>t.length>2?Rs:Vo.has(e)?e.startsWith(`scale`)?Ls(t[1]):Is:zs;function Vs(e,t){if(e?.inherit&&t){let{inherit:n,...r}=e;return{...t,...r}}return e}function Hs(e,t){let n=e?.[t]??e?.default??e;return n===e?n:Vs(n,e)}var Us=new Set([`when`,`delay`,`delayChildren`,`staggerChildren`,`staggerDirection`,`repeat`,`repeatType`,`repeatDelay`,`from`,`elapsed`]);function Ws(e){for(let t in e)if(!Us.has(t))return!0;return!1}var Gs=(e,t,n,r={},i,a)=>o=>{let s=Hs(r,e)||{},c=s.delay||r.delay||0,{elapsed:l=0}=r;l-=ei(c);let u={keyframes:Array.isArray(n)?n:[null,n],ease:`easeOut`,velocity:t.getVelocity(),...s,delay:-l,onUpdate:e=>{t.set(e),s.onUpdate&&s.onUpdate(e)},onComplete:()=>{o(),s.onComplete&&s.onComplete()},name:e,motionValue:t,element:a?void 0:i};Ws(s)||Object.assign(u,Bs(e,u)),u.duration&&=ei(u.duration),u.repeatDelay&&=ei(u.repeatDelay),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(Ss(u),u.delay===0&&(d=!0)),(Wr.instantAnimations||Wr.skipAnimations||i?.shouldSkipAnimations)&&(d=!0,Ss(u),u.delay=0),u.allowFlatten=!s.type&&!s.ease,d&&!a&&t.get()!==void 0){let e=xo(u.keyframes,s);if(e!==void 0){N.update(()=>{u.onUpdate(e),u.onComplete()});return}}return s.isSync?new Eo(u):new As(u)};function Ks(e){let t=[{},{}];return e?.values.forEach((e,n)=>{t[0][n]=e.get(),t[1][n]=e.getVelocity()}),t}function qs(e,t,n,r){if(typeof t==`function`){let[i,a]=Ks(r);t=t(n===void 0?e.custom:n,i,a)}if(typeof t==`string`&&(t=e.variants&&e.variants[t]),typeof t==`function`){let[i,a]=Ks(r);t=t(n===void 0?e.custom:n,i,a)}return t}function Js(e,t,n){let r=e.getProps();return qs(r,t,n===void 0?r.custom:n,e)}var Ys=new Set([`width`,`height`,`top`,`left`,`right`,`bottom`,...Bo]),Xs=30,Zs=e=>!isNaN(parseFloat(e)),Qs={current:void 0},$s=class{constructor(e,t={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=e=>{let t=Li.now();if(this.updatedAt!==t&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(e),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(let e of this.dependents)e.dirty()},this.hasAnimated=!1,this.setCurrent(e),this.owner=t.owner}setCurrent(e){this.current=e,this.updatedAt=Li.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=Zs(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return process.env.NODE_ENV!==`production`&&ii(!1,`value.onChange(callback) is deprecated. Switch to value.on("change", callback).`),this.on(`change`,e)}on(e,t){this.events[e]||(this.events[e]=new $r);let n=this.events[e].add(t);return e===`change`?()=>{n(),N.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(let e in this.events)this.events[e].clear()}attach(e,t){this.passiveEffect=e,this.stopPassiveEffect=t}set(e){this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e)}setWithVelocity(e,t,n){this.set(t),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-n}jump(e,t=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,t&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(e){this.dependents||=new Set,this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return Qs.current&&Qs.current.push(this),this.current}getPrevious(){return this.prev}getVelocity(){let e=Li.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Xs)return 0;let t=Math.min(this.updatedAt-this.prevUpdatedAt,Xs);return ni(parseFloat(this.current)-parseFloat(this.prevFrameValue),t)}start(e){return this.stop(),new Promise(t=>{this.hasAnimated=!0,this.animation=e(t),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}};function ec(e,t){return new $s(e,t)}var tc=e=>Array.isArray(e);function nc(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,ec(n))}function rc(e){return tc(e)?e[e.length-1]||0:e}function ic(e,t){let{transitionEnd:n={},transition:r={},...i}=Js(e,t)||{};i={...i,...n};for(let t in i)nc(e,t,rc(i[t]))}var ac=e=>!!(e&&e.getVelocity);function oc(e){return!!(ac(e)&&e.add)}function sc(e,t){let n=e.getValue(`willChange`);if(oc(n))return n.add(t);if(!n&&Wr.WillChange){let n=new Wr.WillChange(`auto`);e.addValue(`willChange`,n),n.add(t)}}function cc(e){return e.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}var lc=`data-`+cc(`framerAppearId`);function uc(e){return e.props[lc]}function dc({protectedKeys:e,needsAnimating:t},n){let r=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function fc(e,t,{delay:n=0,transitionOverride:r,type:i}={}){let{transition:a,transitionEnd:o,...s}=t,c=e.getDefaultTransition();a=a?Vs(a,c):c;let l=a?.reduceMotion;r&&(a=r);let u=[],d=i&&e.animationState&&e.animationState.getState()[i];for(let t in s){let r=e.getValue(t,e.latestValues[t]??null),i=s[t];if(i===void 0||d&&dc(d,t))continue;let o={delay:n,...Hs(a||{},t)},c=r.get();if(c!==void 0&&!r.isAnimating()&&!Array.isArray(i)&&i===c&&!o.velocity){N.update(()=>r.set(i));continue}let f=!1;if(window.MotionHandoffAnimation){let n=uc(e);if(n){let e=window.MotionHandoffAnimation(n,t,N);e!==null&&(o.startTime=e,f=!0)}}sc(e,t);let p=l??e.shouldReduceMotion;r.start(Gs(t,r,i,p&&Ys.has(t)?{type:!1}:o,e,f));let m=r.animation;m&&u.push(m)}if(o){let t=()=>N.update(()=>{o&&ic(e,o)});u.length?Promise.all(u).then(t):t()}return u}function pc(e,t,n={}){let r=Js(e,t,n.type===`exit`?e.presenceContext?.custom:void 0),{transition:i=e.getDefaultTransition()||{}}=r||{};n.transitionOverride&&(i=n.transitionOverride);let a=r?()=>Promise.all(fc(e,r,n)):()=>Promise.resolve(),o=e.variantChildren&&e.variantChildren.size?(r=0)=>{let{delayChildren:a=0,staggerChildren:o,staggerDirection:s}=i;return mc(e,t,r,a,o,s,n)}:()=>Promise.resolve(),{when:s}=i;if(s){let[e,t]=s===`beforeChildren`?[a,o]:[o,a];return e().then(()=>t())}else return Promise.all([a(),o(n.delay)])}function mc(e,t,n=0,r=0,i=0,a=1,o){let s=[];for(let c of e.variantChildren)c.notify(`AnimationStart`,t),s.push(pc(c,t,{...o,delay:n+(typeof r==`function`?0:r)+js(e.variantChildren,c,r,i,a)}).then(()=>c.notify(`AnimationComplete`,t)));return Promise.all(s)}function hc(e,t,n={}){e.notify(`AnimationStart`,t);let r;if(Array.isArray(t)){let i=t.map(t=>pc(e,t,n));r=Promise.all(i)}else if(typeof t==`string`)r=pc(e,t,n);else{let i=typeof t==`function`?Js(e,t,n.custom):t;r=Promise.all(fc(e,i,n))}return r.then(()=>{e.notify(`AnimationComplete`,t)})}var gc={test:e=>e===`auto`,parse:e=>e},_c=e=>t=>t.test(e),vc=[Gi,P,sa,oa,la,ca,gc],yc=e=>vc.find(_c(e));function bc(e){return typeof e==`number`?e===0:e===null?!0:e===`none`||e===`0`||qr(e)}var xc=new Set([`brightness`,`contrast`,`saturate`,`opacity`]);function Sc(e){let[t,n]=e.slice(0,-1).split(`(`);if(t===`drop-shadow`)return e;let[r]=n.match(Yi)||[];if(!r)return e;let i=n.replace(r,``),a=xc.has(t)?1:0;return r!==n&&(a*=100),t+`(`+a+i+`)`}var Cc=/\b([a-z-]*)\(.*?\)/gu,wc={...Oa,getAnimatableNone:e=>{let t=e.match(Cc);return t?t.map(Sc).join(` `):e}},Tc={...Oa,getAnimatableNone:e=>{let t=Oa.parse(e);return Oa.createTransformer(e)(t.map(e=>typeof e==`number`?0:typeof e==`object`?{...e,alpha:1}:e))}},Ec={...Gi,transform:Math.round},Dc={borderWidth:P,borderTopWidth:P,borderRightWidth:P,borderBottomWidth:P,borderLeftWidth:P,borderRadius:P,borderTopLeftRadius:P,borderTopRightRadius:P,borderBottomRightRadius:P,borderBottomLeftRadius:P,width:P,maxWidth:P,height:P,maxHeight:P,top:P,right:P,bottom:P,left:P,inset:P,insetBlock:P,insetBlockStart:P,insetBlockEnd:P,insetInline:P,insetInlineStart:P,insetInlineEnd:P,padding:P,paddingTop:P,paddingRight:P,paddingBottom:P,paddingLeft:P,paddingBlock:P,paddingBlockStart:P,paddingBlockEnd:P,paddingInline:P,paddingInlineStart:P,paddingInlineEnd:P,margin:P,marginTop:P,marginRight:P,marginBottom:P,marginLeft:P,marginBlock:P,marginBlockStart:P,marginBlockEnd:P,marginInline:P,marginInlineStart:P,marginInlineEnd:P,fontSize:P,backgroundPositionX:P,backgroundPositionY:P,rotate:oa,rotateX:oa,rotateY:oa,rotateZ:oa,scale:qi,scaleX:qi,scaleY:qi,scaleZ:qi,skew:oa,skewX:oa,skewY:oa,distance:P,translateX:P,translateY:P,translateZ:P,x:P,y:P,z:P,perspective:P,transformPerspective:P,opacity:Ki,originX:ua,originY:ua,originZ:P,zIndex:Ec,fillOpacity:Ki,strokeOpacity:Ki,numOctaves:Ec},Oc={...Dc,color:fa,backgroundColor:fa,outlineColor:fa,fill:fa,stroke:fa,borderColor:fa,borderTopColor:fa,borderRightColor:fa,borderBottomColor:fa,borderLeftColor:fa,filter:wc,WebkitFilter:wc,mask:Tc,WebkitMask:Tc},kc=e=>Oc[e],Ac=new Set([wc,Tc]);function jc(e,t){let n=kc(e);return Ac.has(n)||(n=Oa),n.getAnimatableNone?n.getAnimatableNone(t):void 0}var Mc=new Set([`auto`,`none`,`0`]);function Nc(e,t,n){let r=0,i;for(;r<e.length&&!i;){let t=e[r];typeof t==`string`&&!Mc.has(t)&&xa(t).values.length&&(i=e[r]),r++}if(i&&n)for(let r of t)e[r]=jc(n,i)}var Pc=class extends es{constructor(e,t,n,r,i){super(e,t,n,r,i,!0)}readKeyframes(){let{unresolvedKeyframes:e,element:t,name:n}=this;if(!t||!t.current)return;super.readKeyframes();for(let n=0;n<e.length;n++){let r=e[n];if(typeof r==`string`&&(r=r.trim(),Hi(r))){let i=Fs(r,t.current);i!==void 0&&(e[n]=i),n===e.length-1&&(this.finalKeyframe=r)}}if(this.resolveNoneKeyframes(),!Ys.has(n)||e.length!==2)return;let[r,i]=e,a=yc(r),o=yc(i);if(Wi(r)!==Wi(i)&&Ko[n]){this.needsMeasurement=!0;return}if(a!==o)if(Ho(a)&&Ho(o))for(let t=0;t<e.length;t++){let n=e[t];typeof n==`string`&&(e[t]=parseFloat(n))}else Ko[n]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){let{unresolvedKeyframes:e,name:t}=this,n=[];for(let t=0;t<e.length;t++)(e[t]===null||bc(e[t]))&&n.push(t);n.length&&Nc(e,n,t)}measureInitialState(){let{element:e,unresolvedKeyframes:t,name:n}=this;if(!e||!e.current)return;n===`height`&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Ko[n](e.measureViewportBox(),window.getComputedStyle(e.current)),t[0]=this.measuredOrigin;let r=t[t.length-1];r!==void 0&&e.getValue(n,r).jump(r,!1)}measureEndState(){let{element:e,name:t,unresolvedKeyframes:n}=this;if(!e||!e.current)return;let r=e.getValue(t);r&&r.jump(this.measuredOrigin,!1);let i=n.length-1,a=n[i];n[i]=Ko[t](e.measureViewportBox(),window.getComputedStyle(e.current)),a!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=a),this.removedTransforms?.length&&this.removedTransforms.forEach(([t,n])=>{e.getValue(t).set(n)}),this.resolveNoneKeyframes()}};function Fc(e,t,n){if(e==null)return[];if(e instanceof EventTarget)return[e];if(typeof e==`string`){let r=document;t&&(r=t.current);let i=n?.[e]??r.querySelectorAll(e);return i?Array.from(i):[]}return Array.from(e).filter(e=>e!=null)}var Ic=(e,t)=>t&&typeof e==`number`?t.transform(e):e;function Lc(e){return Kr(e)&&`offsetHeight`in e&&!(`ownerSVGElement`in e)}var{schedule:Rc,cancel:zc}=ji(queueMicrotask,!1),Bc={x:!1,y:!1};function Vc(){return Bc.x||Bc.y}function Hc(e){return e===`x`||e===`y`?Bc[e]?null:(Bc[e]=!0,()=>{Bc[e]=!1}):Bc.x||Bc.y?null:(Bc.x=Bc.y=!0,()=>{Bc.x=Bc.y=!1})}function Uc(e,t){let n=Fc(e),r=new AbortController;return[n,{passive:!0,...t,signal:r.signal},()=>r.abort()]}function Wc(e){return!(e.pointerType===`touch`||Vc())}function Gc(e,t,n={}){let[r,i,a]=Uc(e,n);return r.forEach(e=>{let n=!1,r=!1,a,o=()=>{e.removeEventListener(`pointerleave`,u)},s=e=>{a&&=(a(e),void 0),o()},c=e=>{n=!1,window.removeEventListener(`pointerup`,c),window.removeEventListener(`pointercancel`,c),r&&(r=!1,s(e))},l=()=>{n=!0,window.addEventListener(`pointerup`,c,i),window.addEventListener(`pointercancel`,c,i)},u=e=>{if(e.pointerType!==`touch`){if(n){r=!0;return}s(e)}};e.addEventListener(`pointerenter`,n=>{if(!Wc(n))return;r=!1;let o=t(e,n);typeof o==`function`&&(a=o,e.addEventListener(`pointerleave`,u,i))},i),e.addEventListener(`pointerdown`,l,i)}),a}var Kc=(e,t)=>t?e===t?!0:Kc(e,t.parentElement):!1,qc=e=>e.pointerType===`mouse`?typeof e.button!=`number`||e.button<=0:e.isPrimary!==!1,Jc=new Set([`BUTTON`,`INPUT`,`SELECT`,`TEXTAREA`,`A`]);function Yc(e){return Jc.has(e.tagName)||e.isContentEditable===!0}var Xc=new Set([`INPUT`,`SELECT`,`TEXTAREA`]);function Zc(e){return Xc.has(e.tagName)||e.isContentEditable===!0}var Qc=new WeakSet;function $c(e){return t=>{t.key===`Enter`&&e(t)}}function el(e,t){e.dispatchEvent(new PointerEvent(`pointer`+t,{isPrimary:!0,bubbles:!0}))}var tl=(e,t)=>{let n=e.currentTarget;if(!n)return;let r=$c(()=>{if(Qc.has(n))return;el(n,`down`);let e=$c(()=>{el(n,`up`)});n.addEventListener(`keyup`,e,t),n.addEventListener(`blur`,()=>el(n,`cancel`),t)});n.addEventListener(`keydown`,r,t),n.addEventListener(`blur`,()=>n.removeEventListener(`keydown`,r),t)};function nl(e){return qc(e)&&!Vc()}var rl=new WeakSet;function il(e,t,n={}){let[r,i,a]=Uc(e,n),o=e=>{let r=e.currentTarget;if(!nl(e)||rl.has(e))return;Qc.add(r),n.stopPropagation&&rl.add(e);let a=t(r,e),o=(e,t)=>{window.removeEventListener(`pointerup`,s),window.removeEventListener(`pointercancel`,c),Qc.has(r)&&Qc.delete(r),nl(e)&&typeof a==`function`&&a(e,{success:t})},s=e=>{o(e,r===window||r===document||n.useGlobalTarget||Kc(r,e.target))},c=e=>{o(e,!1)};window.addEventListener(`pointerup`,s,i),window.addEventListener(`pointercancel`,c,i)};return r.forEach(e=>{(n.useGlobalTarget?window:e).addEventListener(`pointerdown`,o,i),Lc(e)&&(e.addEventListener(`focus`,e=>tl(e,i)),!Yc(e)&&!e.hasAttribute(`tabindex`)&&(e.tabIndex=0))}),a}function al(e){return Kr(e)&&`ownerSVGElement`in e}var ol=new WeakMap,sl,cl=(e,t,n)=>(r,i)=>i&&i[0]?i[0][e+`Size`]:al(r)&&`getBBox`in r?r.getBBox()[t]:r[n],ll=cl(`inline`,`width`,`offsetWidth`),ul=cl(`block`,`height`,`offsetHeight`);function dl({target:e,borderBoxSize:t}){ol.get(e)?.forEach(n=>{n(e,{get width(){return ll(e,t)},get height(){return ul(e,t)}})})}function fl(e){e.forEach(dl)}function pl(){typeof ResizeObserver>`u`||(sl=new ResizeObserver(fl))}function ml(e,t){sl||pl();let n=Fc(e);return n.forEach(e=>{let n=ol.get(e);n||(n=new Set,ol.set(e,n)),n.add(t),sl?.observe(e)}),()=>{n.forEach(e=>{let n=ol.get(e);n?.delete(t),n?.size||sl?.unobserve(e)})}}var hl=new Set,gl;function _l(){gl=()=>{let e={get width(){return window.innerWidth},get height(){return window.innerHeight}};hl.forEach(t=>t(e))},window.addEventListener(`resize`,gl)}function vl(e){return hl.add(e),gl||_l(),()=>{hl.delete(e),!hl.size&&typeof gl==`function`&&(window.removeEventListener(`resize`,gl),gl=void 0)}}function yl(e,t){return typeof e==`function`?vl(e):ml(e,t)}function bl(e){return al(e)&&e.tagName===`svg`}var xl=[...vc,fa,Oa],Sl=e=>xl.find(_c(e)),Cl=()=>({translate:0,scale:1,origin:0,originPoint:0}),wl=()=>({x:Cl(),y:Cl()}),Tl=()=>({min:0,max:0}),El=()=>({x:Tl(),y:Tl()}),Dl=new WeakMap;function Ol(e){return typeof e==`object`&&!!e&&typeof e.start==`function`}function kl(e){return typeof e==`string`||Array.isArray(e)}var Al=[`animate`,`whileInView`,`whileFocus`,`whileHover`,`whileTap`,`whileDrag`,`exit`],jl=[`initial`,...Al];function Ml(e){return Ol(e.animate)||jl.some(t=>kl(e[t]))}function Nl(e){return!!(Ml(e)||e.variants)}function Pl(e,t,n){for(let r in t){let i=t[r],a=n[r];if(ac(i))e.addValue(r,i);else if(ac(a))e.addValue(r,ec(i,{owner:e}));else if(a!==i)if(e.hasValue(r)){let t=e.getValue(r);t.liveStyle===!0?t.jump(i):t.hasAnimated||t.set(i)}else{let t=e.getStaticValue(r);e.addValue(r,ec(t===void 0?i:t,{owner:e}))}}for(let r in n)t[r]===void 0&&e.removeValue(r);return t}var Fl={current:null},Il={current:!1},Ll=typeof window<`u`;function Rl(){if(Il.current=!0,Ll)if(window.matchMedia){let e=window.matchMedia(`(prefers-reduced-motion)`),t=()=>Fl.current=e.matches;e.addEventListener(`change`,t),t()}else Fl.current=!1}var zl=[`AnimationStart`,`AnimationComplete`,`Update`,`BeforeLayoutMeasure`,`LayoutMeasure`,`LayoutAnimationStart`,`LayoutAnimationComplete`],Bl={};function Vl(e){Bl=e}function Hl(){return Bl}var Ul=class{scrapeMotionValuesFromProps(e,t,n){return{}}constructor({parent:e,props:t,presenceContext:n,reducedMotionConfig:r,skipAnimations:i,blockInitialAnimation:a,visualState:o},s={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.shouldSkipAnimations=!1,this.values=new Map,this.KeyframeResolver=es,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify(`Update`,this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{let e=Li.now();this.renderScheduledAt<e&&(this.renderScheduledAt=e,N.render(this.render,!1,!0))};let{latestValues:c,renderState:l}=o;this.latestValues=c,this.baseTarget={...c},this.initialValues=t.initial?{...c}:{},this.renderState=l,this.parent=e,this.props=t,this.presenceContext=n,this.depth=e?e.depth+1:0,this.reducedMotionConfig=r,this.skipAnimationsConfig=i,this.options=s,this.blockInitialAnimation=!!a,this.isControllingVariants=Ml(t),this.isVariantNode=Nl(t),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);let{willChange:u,...d}=this.scrapeMotionValuesFromProps(t,{},this);for(let e in d){let t=d[e];c[e]!==void 0&&ac(t)&&t.set(c[e])}}mount(e){if(this.hasBeenMounted)for(let e in this.initialValues)this.values.get(e)?.jump(this.initialValues[e]),this.latestValues[e]=this.initialValues[e];this.current=e,Dl.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((e,t)=>this.bindToMotionValue(t,e)),this.reducedMotionConfig===`never`?this.shouldReduceMotion=!1:this.reducedMotionConfig===`always`?this.shouldReduceMotion=!0:(Il.current||Rl(),this.shouldReduceMotion=Fl.current),process.env.NODE_ENV!==`production`&&ii(this.shouldReduceMotion!==!0,`You have Reduced Motion enabled on your device. Animations may not appear as expected.`,`reduced-motion-disabled`),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,this.parent?.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){this.projection&&this.projection.unmount(),Mi(this.notifyUpdate),Mi(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(let e in this.events)this.events[e].clear();for(let e in this.features){let t=this.features[e];t&&(t.unmount(),t.isMounted=!1)}this.current=null}addChild(e){this.children.add(e),this.enteringChildren??=new Set,this.enteringChildren.add(e)}removeChild(e){this.children.delete(e),this.enteringChildren&&this.enteringChildren.delete(e)}bindToMotionValue(e,t){if(this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)(),t.accelerate&&Cs.has(e)&&this.current instanceof HTMLElement){let{factory:n,keyframes:r,times:i,ease:a,duration:o}=t.accelerate,s=new ps({element:this.current,name:e,keyframes:r,times:i,ease:a,duration:ei(o)}),c=n(s);this.valueSubscriptions.set(e,()=>{c(),s.cancel()});return}let n=Vo.has(e);n&&this.onBindTransform&&this.onBindTransform();let r=t.on(`change`,t=>{this.latestValues[e]=t,this.props.onUpdate&&N.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()}),i;typeof window<`u`&&window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,e,t)),this.valueSubscriptions.set(e,()=>{r(),i&&i(),t.owner&&t.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e=`animation`;for(e in Bl){let t=Bl[e];if(!t)continue;let{isEnabled:n,Feature:r}=t;if(!this.features[e]&&r&&n(this.props)&&(this.features[e]=new r(this)),this.features[e]){let t=this.features[e];t.isMounted?t.update():(t.mount(),t.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):El()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,t){this.latestValues[e]=t}update(e,t){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=t;for(let t=0;t<zl.length;t++){let n=zl[t];this.propEventSubscriptions[n]&&(this.propEventSubscriptions[n](),delete this.propEventSubscriptions[n]);let r=e[`on`+n];r&&(this.propEventSubscriptions[n]=this.on(n,r))}this.prevMotionValues=Pl(this,this.scrapeMotionValuesFromProps(e,this.prevProps||{},this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(e){return this.props.variants?this.props.variants[e]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(e){let t=this.getClosestVariantNode();if(t)return t.variantChildren&&t.variantChildren.add(e),()=>t.variantChildren.delete(e)}addValue(e,t){let n=this.values.get(e);t!==n&&(n&&this.removeValue(e),this.bindToMotionValue(e,t),this.values.set(e,t),this.latestValues[e]=t.get())}removeValue(e){this.values.delete(e);let t=this.valueSubscriptions.get(e);t&&(t(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,t){if(this.props.values&&this.props.values[e])return this.props.values[e];let n=this.values.get(e);return n===void 0&&t!==void 0&&(n=ec(t===null?void 0:t,{owner:this}),this.addValue(e,n)),n}readValue(e,t){let n=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return n!=null&&(typeof n==`string`&&(Gr(n)||qr(n))?n=parseFloat(n):!Sl(n)&&Oa.test(t)&&(n=jc(e,t)),this.setBaseTarget(e,ac(n)?n.get():n)),ac(n)?n.get():n}setBaseTarget(e,t){this.baseTarget[e]=t}getBaseTarget(e){let{initial:t}=this.props,n;if(typeof t==`string`||typeof t==`object`){let r=qs(this.props,t,this.presenceContext?.custom);r&&(n=r[e])}if(t&&n!==void 0)return n;let r=this.getBaseTargetFromProps(this.props,e);return r!==void 0&&!ac(r)?r:this.initialValues[e]!==void 0&&n===void 0?void 0:this.baseTarget[e]}on(e,t){return this.events[e]||(this.events[e]=new $r),this.events[e].add(t)}notify(e,...t){this.events[e]&&this.events[e].notify(...t)}scheduleRenderMicrotask(){Rc.render(this.render)}},Wl=class extends Ul{constructor(){super(...arguments),this.KeyframeResolver=Pc}sortInstanceNodePosition(e,t){return e.compareDocumentPosition(t)&2?1:-1}getBaseTargetFromProps(e,t){let n=e.style;return n?n[t]:void 0}removeValueFromRenderState(e,{vars:t,style:n}){delete t[e],delete n[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);let{children:e}=this.props;ac(e)&&(this.childSubscription=e.on(`change`,e=>{this.current&&(this.current.textContent=`${e}`)}))}},Gl=class{constructor(e){this.isMounted=!1,this.node=e}update(){}};function Kl({top:e,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:e,max:r}}}function ql({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function Jl(e,t){if(!t)return e;let n=t({x:e.left,y:e.top}),r=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:r.y,right:r.x}}function Yl(e){return e===void 0||e===1}function Xl({scale:e,scaleX:t,scaleY:n}){return!Yl(e)||!Yl(t)||!Yl(n)}function Zl(e){return Xl(e)||Ql(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function Ql(e){return $l(e.x)||$l(e.y)}function $l(e){return e&&e!==`0%`}function eu(e,t,n){return n+t*(e-n)}function tu(e,t,n,r,i){return i!==void 0&&(e=eu(e,i,r)),eu(e,n,r)+t}function nu(e,t=0,n=1,r,i){e.min=tu(e.min,t,n,r,i),e.max=tu(e.max,t,n,r,i)}function ru(e,{x:t,y:n}){nu(e.x,t.translate,t.scale,t.originPoint),nu(e.y,n.translate,n.scale,n.originPoint)}var iu=.999999999999,au=1.0000000000001;function ou(e,t,n,r=!1){let i=n.length;if(!i)return;t.x=t.y=1;let a,o;for(let s=0;s<i;s++){a=n[s],o=a.projectionDelta;let{visualElement:i}=a.options;i&&i.props.style&&i.props.style.display===`contents`||(r&&a.options.layoutScroll&&a.scroll&&a!==a.root&&(su(e.x,-a.scroll.offset.x),su(e.y,-a.scroll.offset.y)),o&&(t.x*=o.x.scale,t.y*=o.y.scale,ru(e,o)),r&&Zl(a.latestValues)&&uu(e,a.latestValues,a.layout?.layoutBox))}t.x<au&&t.x>iu&&(t.x=1),t.y<au&&t.y>iu&&(t.y=1)}function su(e,t){e.min+=t,e.max+=t}function cu(e,t,n,r,i=.5){nu(e,t,n,Ma(e.min,e.max,i),r)}function lu(e,t){return typeof e==`string`?parseFloat(e)/100*(t.max-t.min):e}function uu(e,t,n){let r=n??e;cu(e.x,lu(t.x,r.x),t.scaleX,t.scale,t.originX),cu(e.y,lu(t.y,r.y),t.scaleY,t.scale,t.originY)}function du(e,t){return Kl(Jl(e.getBoundingClientRect(),t))}function fu(e,t,n){let r=du(e,n),{scroll:i}=t;return i&&(su(r.x,i.offset.x),su(r.y,i.offset.y)),r}var pu={x:`translateX`,y:`translateY`,z:`translateZ`,transformPerspective:`perspective`},mu=Bo.length;function hu(e,t,n){let r=``,i=!0;for(let a=0;a<mu;a++){let o=Bo[a],s=e[o];if(s===void 0)continue;let c=!0;if(typeof s==`number`)c=s===(o.startsWith(`scale`)?1:0);else{let e=parseFloat(s);c=o.startsWith(`scale`)?e===1:e===0}if(!c||n){let e=Ic(s,Dc[o]);if(!c){i=!1;let t=pu[o]||o;r+=`${t}(${e}) `}n&&(t[o]=e)}}return r=r.trim(),n?r=n(t,i?``:r):i&&(r=`none`),r}function gu(e,t,n){let{style:r,vars:i,transformOrigin:a}=e,o=!1,s=!1;for(let e in t){let n=t[e];if(Vo.has(e)){o=!0;continue}else if(Bi(e)){i[e]=n;continue}else{let t=Ic(n,Dc[e]);e.startsWith(`origin`)?(s=!0,a[e]=t):r[e]=t}}if(t.transform||(o||n?r.transform=hu(t,e.transform,n):r.transform&&=`none`),s){let{originX:e=`50%`,originY:t=`50%`,originZ:n=0}=a;r.transformOrigin=`${e} ${t} ${n}`}}function _u(e,{style:t,vars:n},r,i){let a=e.style,o;for(o in t)a[o]=t[o];for(o in i?.applyProjectionStyles(a,r),n)a.setProperty(o,n[o])}function vu(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}var yu={correct:(e,t)=>{if(!t.target)return e;if(typeof e==`string`)if(P.test(e))e=parseFloat(e);else return e;return`${vu(e,t.target.x)}% ${vu(e,t.target.y)}%`}},bu={correct:(e,{treeScale:t,projectionDelta:n})=>{let r=e,i=Oa.parse(e);if(i.length>5)return r;let a=Oa.createTransformer(e),o=typeof i[0]==`number`?0:1,s=n.x.scale*t.x,c=n.y.scale*t.y;i[0+o]/=s,i[1+o]/=c;let l=Ma(s,c,.5);return typeof i[2+o]==`number`&&(i[2+o]/=l),typeof i[3+o]==`number`&&(i[3+o]/=l),a(i)}},xu={borderRadius:{...yu,applyTo:[`borderTopLeftRadius`,`borderTopRightRadius`,`borderBottomLeftRadius`,`borderBottomRightRadius`]},borderTopLeftRadius:yu,borderTopRightRadius:yu,borderBottomLeftRadius:yu,borderBottomRightRadius:yu,boxShadow:bu};function Su(e,{layout:t,layoutId:n}){return Vo.has(e)||e.startsWith(`origin`)||(t||n!==void 0)&&(!!xu[e]||e===`opacity`)}function Cu(e,t,n){let r=e.style,i=t?.style,a={};if(!r)return a;for(let t in r)(ac(r[t])||i&&ac(i[t])||Su(t,e)||n?.getValue(t)?.liveStyle!==void 0)&&(a[t]=r[t]);return a}function wu(e){return window.getComputedStyle(e)}var Tu=class extends Wl{constructor(){super(...arguments),this.type=`html`,this.renderInstance=_u}readValueFromInstance(e,t){if(Vo.has(t))return this.projection?.isProjecting?Io(t):Ro(e,t);{let n=wu(e),r=(Bi(t)?n.getPropertyValue(t):n[t])||0;return typeof r==`string`?r.trim():r}}measureInstanceViewportBox(e,{transformPagePoint:t}){return du(e,t)}build(e,t,n){gu(e,t,n.transformTemplate)}scrapeMotionValuesFromProps(e,t,n){return Cu(e,t,n)}},Eu={offset:`stroke-dashoffset`,array:`stroke-dasharray`},Du={offset:`strokeDashoffset`,array:`strokeDasharray`};function Ou(e,t,n=1,r=0,i=!0){e.pathLength=1;let a=i?Eu:Du;e[a.offset]=`${-r}`,e[a.array]=`${t} ${n}`}var ku=[`offsetDistance`,`offsetPath`,`offsetRotate`,`offsetAnchor`];function Au(e,{attrX:t,attrY:n,attrScale:r,pathLength:i,pathSpacing:a=1,pathOffset:o=0,...s},c,l,u){if(gu(e,s,l),c){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};let{attrs:d,style:f}=e;d.transform&&(f.transform=d.transform,delete d.transform),(f.transform||d.transformOrigin)&&(f.transformOrigin=d.transformOrigin??`50% 50%`,delete d.transformOrigin),f.transform&&(f.transformBox=u?.transformBox??`fill-box`,delete d.transformBox);for(let e of ku)d[e]!==void 0&&(f[e]=d[e],delete d[e]);t!==void 0&&(d.x=t),n!==void 0&&(d.y=n),r!==void 0&&(d.scale=r),i!==void 0&&Ou(d,i,a,o,!1)}var ju=new Set([`baseFrequency`,`diffuseConstant`,`kernelMatrix`,`kernelUnitLength`,`keySplines`,`keyTimes`,`limitingConeAngle`,`markerHeight`,`markerWidth`,`numOctaves`,`targetX`,`targetY`,`surfaceScale`,`specularConstant`,`specularExponent`,`stdDeviation`,`tableValues`,`viewBox`,`gradientTransform`,`pathLength`,`startOffset`,`textLength`,`lengthAdjust`]),Mu=e=>typeof e==`string`&&e.toLowerCase()===`svg`;function Nu(e,t,n,r){_u(e,t,void 0,r);for(let n in t.attrs)e.setAttribute(ju.has(n)?n:cc(n),t.attrs[n])}function Pu(e,t,n){let r=Cu(e,t,n);for(let n in e)if(ac(e[n])||ac(t[n])){let t=Bo.indexOf(n)===-1?n:`attr`+n.charAt(0).toUpperCase()+n.substring(1);r[t]=e[n]}return r}var Fu=class extends Wl{constructor(){super(...arguments),this.type=`svg`,this.isSVGTag=!1,this.measureInstanceViewportBox=El}getBaseTargetFromProps(e,t){return e[t]}readValueFromInstance(e,t){if(Vo.has(t)){let e=kc(t);return e&&e.default||0}return t=ju.has(t)?t:cc(t),e.getAttribute(t)}scrapeMotionValuesFromProps(e,t,n){return Pu(e,t,n)}build(e,t,n){Au(e,t,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,t,n,r){Nu(e,t,n,r)}mount(e){this.isSVGTag=Mu(e.tagName),super.mount(e)}},Iu=jl.length;function Lu(e){if(!e)return;if(!e.isControllingVariants){let t=e.parent&&Lu(e.parent)||{};return e.props.initial!==void 0&&(t.initial=e.props.initial),t}let t={};for(let n=0;n<Iu;n++){let r=jl[n],i=e.props[r];(kl(i)||i===!1)&&(t[r]=i)}return t}function Ru(e,t){if(!Array.isArray(t))return!1;let n=t.length;if(n!==e.length)return!1;for(let r=0;r<n;r++)if(t[r]!==e[r])return!1;return!0}var zu=[...Al].reverse(),Bu=Al.length;function Vu(e){return t=>Promise.all(t.map(({animation:t,options:n})=>hc(e,t,n)))}function Hu(e){let t=Vu(e),n=Gu(),r=!0,i=!1,a=t=>(n,r)=>{let i=Js(e,r,t===`exit`?e.presenceContext?.custom:void 0);if(i){let{transition:e,transitionEnd:t,...r}=i;n={...n,...r,...t}}return n};function o(n){t=n(e)}function s(o){let{props:s}=e,c=Lu(e.parent)||{},l=[],u=new Set,d={},f=1/0;for(let t=0;t<Bu;t++){let p=zu[t],m=n[p],h=s[p]===void 0?c[p]:s[p],g=kl(h),_=p===o?m.isActive:null;_===!1&&(f=t);let v=h===c[p]&&h!==s[p]&&g;if(v&&(r||i)&&e.manuallyAnimateOnMount&&(v=!1),m.protectedKeys={...d},!m.isActive&&_===null||!h&&!m.prevProp||Ol(h)||typeof h==`boolean`)continue;if(p===`exit`&&m.isActive&&_!==!0){m.prevResolvedValues&&(d={...d,...m.prevResolvedValues});continue}let y=Uu(m.prevProp,h),b=y||p===o&&m.isActive&&!v&&g||t>f&&g,x=!1,S=Array.isArray(h)?h:[h],ee=S.reduce(a(p),{});_===!1&&(ee={});let{prevResolvedValues:te={}}=m,ne={...te,...ee},re=t=>{b=!0,u.has(t)&&(x=!0,u.delete(t)),m.needsAnimating[t]=!0;let n=e.getValue(t);n&&(n.liveStyle=!1)};for(let e in ne){let t=ee[e],n=te[e];if(d.hasOwnProperty(e))continue;let r=!1;r=tc(t)&&tc(n)?!Ru(t,n):t!==n,r?t==null?u.add(e):re(e):t!==void 0&&u.has(e)?re(e):m.protectedKeys[e]=!0}m.prevProp=h,m.prevResolvedValues=ee,m.isActive&&(d={...d,...ee}),(r||i)&&e.blockInitialAnimation&&(b=!1);let ie=v&&y;b&&(!ie||x)&&l.push(...S.map(t=>{let n={type:p};if(typeof t==`string`&&(r||i)&&!ie&&e.manuallyAnimateOnMount&&e.parent){let{parent:r}=e,i=Js(r,t);if(r.enteringChildren&&i){let{delayChildren:t}=i.transition||{};n.delay=js(r.enteringChildren,e,t)}}return{animation:t,options:n}}))}if(u.size){let t={};if(typeof s.initial!=`boolean`){let n=Js(e,Array.isArray(s.initial)?s.initial[0]:s.initial);n&&n.transition&&(t.transition=n.transition)}u.forEach(n=>{let r=e.getBaseTarget(n),i=e.getValue(n);i&&(i.liveStyle=!0),t[n]=r??null}),l.push({animation:t})}let p=!!l.length;return r&&(s.initial===!1||s.initial===s.animate)&&!e.manuallyAnimateOnMount&&(p=!1),r=!1,i=!1,p?t(l):Promise.resolve()}function c(t,r){if(n[t].isActive===r)return Promise.resolve();e.variantChildren?.forEach(e=>e.animationState?.setActive(t,r)),n[t].isActive=r;let i=s(t);for(let e in n)n[e].protectedKeys={};return i}return{animateChanges:s,setActive:c,setAnimateFunction:o,getState:()=>n,reset:()=>{n=Gu(),i=!0}}}function Uu(e,t){return typeof t==`string`?t!==e:Array.isArray(t)?!Ru(t,e):!1}function Wu(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Gu(){return{animate:Wu(!0),whileInView:Wu(),whileHover:Wu(),whileTap:Wu(),whileDrag:Wu(),whileFocus:Wu(),exit:Wu()}}function Ku(e,t){e.min=t.min,e.max=t.max}function qu(e,t){Ku(e.x,t.x),Ku(e.y,t.y)}function Ju(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}var Yu=1e-4,Xu=1-Yu,Zu=1+Yu,Qu=.01,$u=0-Qu,ed=0+Qu;function td(e){return e.max-e.min}function nd(e,t,n){return Math.abs(e-t)<=n}function rd(e,t,n,r=.5){e.origin=r,e.originPoint=Ma(t.min,t.max,e.origin),e.scale=td(n)/td(t),e.translate=Ma(n.min,n.max,e.origin)-e.originPoint,(e.scale>=Xu&&e.scale<=Zu||isNaN(e.scale))&&(e.scale=1),(e.translate>=$u&&e.translate<=ed||isNaN(e.translate))&&(e.translate=0)}function id(e,t,n,r){rd(e.x,t.x,n.x,r?r.originX:void 0),rd(e.y,t.y,n.y,r?r.originY:void 0)}function ad(e,t,n,r=0){e.min=(r?Ma(n.min,n.max,r):n.min)+t.min,e.max=e.min+td(t)}function od(e,t,n,r){ad(e.x,t.x,n.x,r?.x),ad(e.y,t.y,n.y,r?.y)}function sd(e,t,n,r=0){let i=r?Ma(n.min,n.max,r):n.min;e.min=t.min-i,e.max=e.min+td(t)}function cd(e,t,n,r){sd(e.x,t.x,n.x,r?.x),sd(e.y,t.y,n.y,r?.y)}function ld(e,t,n,r,i){return e-=t,e=eu(e,1/n,r),i!==void 0&&(e=eu(e,1/i,r)),e}function ud(e,t=0,n=1,r=.5,i,a=e,o=e){if(sa.test(t)&&(t=parseFloat(t),t=Ma(o.min,o.max,t/100)-o.min),typeof t!=`number`)return;let s=Ma(a.min,a.max,r);e===a&&(s-=t),e.min=ld(e.min,t,n,s,i),e.max=ld(e.max,t,n,s,i)}function dd(e,t,[n,r,i],a,o){ud(e,t[n],t[r],t[i],t.scale,a,o)}var fd=[`x`,`scaleX`,`originX`],pd=[`y`,`scaleY`,`originY`];function md(e,t,n,r){dd(e.x,t,fd,n?n.x:void 0,r?r.x:void 0),dd(e.y,t,pd,n?n.y:void 0,r?r.y:void 0)}function hd(e){return e.translate===0&&e.scale===1}function gd(e){return hd(e.x)&&hd(e.y)}function _d(e,t){return e.min===t.min&&e.max===t.max}function vd(e,t){return _d(e.x,t.x)&&_d(e.y,t.y)}function yd(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function bd(e,t){return yd(e.x,t.x)&&yd(e.y,t.y)}function xd(e){return td(e.x)/td(e.y)}function Sd(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}function Cd(e){return[e(`x`),e(`y`)]}function wd(e,t,n){let r=``,i=e.x.translate/t.x,a=e.y.translate/t.y,o=n?.z||0;if((i||a||o)&&(r=`translate3d(${i}px, ${a}px, ${o}px) `),(t.x!==1||t.y!==1)&&(r+=`scale(${1/t.x}, ${1/t.y}) `),n){let{transformPerspective:e,rotate:t,rotateX:i,rotateY:a,skewX:o,skewY:s}=n;e&&(r=`perspective(${e}px) ${r}`),t&&(r+=`rotate(${t}deg) `),i&&(r+=`rotateX(${i}deg) `),a&&(r+=`rotateY(${a}deg) `),o&&(r+=`skewX(${o}deg) `),s&&(r+=`skewY(${s}deg) `)}let s=e.x.scale*t.x,c=e.y.scale*t.y;return(s!==1||c!==1)&&(r+=`scale(${s}, ${c})`),r||`none`}var Td=[`borderTopLeftRadius`,`borderTopRightRadius`,`borderBottomLeftRadius`,`borderBottomRightRadius`],Ed=Td.length,Dd=e=>typeof e==`string`?parseFloat(e):e,Od=e=>typeof e==`number`||P.test(e);function kd(e,t,n,r,i,a){i?(e.opacity=Ma(0,n.opacity??1,jd(r)),e.opacityExit=Ma(t.opacity??1,0,Md(r))):a&&(e.opacity=Ma(t.opacity??1,n.opacity??1,r));for(let i=0;i<Ed;i++){let a=Td[i],o=Ad(t,a),s=Ad(n,a);o===void 0&&s===void 0||(o||=0,s||=0,o===0||s===0||Od(o)===Od(s)?(e[a]=Math.max(Ma(Dd(o),Dd(s),r),0),(sa.test(s)||sa.test(o))&&(e[a]+=`%`)):e[a]=s)}(t.rotate||n.rotate)&&(e.rotate=Ma(t.rotate||0,n.rotate||0,r))}function Ad(e,t){return e[t]===void 0?e.borderRadius:e[t]}var jd=Nd(0,.5,_i),Md=Nd(.5,.95,Yr);function Nd(e,t,n){return r=>r<e?0:r>t?1:n(Qr(e,t,r))}function Pd(e,t,n){let r=ac(e)?e:ec(e);return r.start(Gs(``,r,t,n)),r.animation}function Fd(e,t,n,r={passive:!0}){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n)}var Id=(e,t)=>e.depth-t.depth,Ld=class{constructor(){this.children=[],this.isDirty=!1}add(e){Rr(this.children,e),this.isDirty=!0}remove(e){zr(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(Id),this.isDirty=!1,this.children.forEach(e)}};function Rd(e,t){let n=Li.now(),r=({timestamp:i})=>{let a=i-n;a>=t&&(Mi(r),e(a-t))};return N.setup(r,!0),()=>Mi(r)}function zd(e){return ac(e)?e.get():e}var Bd=class{constructor(){this.members=[]}add(e){Rr(this.members,e);for(let t=this.members.length-1;t>=0;t--){let n=this.members[t];if(n===e||n===this.lead||n===this.prevLead)continue;let r=n.instance;(!r||r.isConnected===!1)&&!n.snapshot&&(zr(this.members,n),n.unmount())}e.scheduleRender()}remove(e){if(zr(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){let e=this.members[this.members.length-1];e&&this.promote(e)}}relegate(e){for(let t=this.members.indexOf(e)-1;t>=0;t--){let e=this.members[t];if(e.isPresent!==!1&&e.instance?.isConnected!==!1)return this.promote(e),!0}return!1}promote(e,t){let n=this.lead;if(e!==n&&(this.prevLead=n,this.lead=e,e.show(),n)){n.updateSnapshot(),e.scheduleRender();let{layoutDependency:r}=n.options,{layoutDependency:i}=e.options;(r===void 0||r!==i)&&(e.resumeFrom=n,t&&(n.preserveOpacity=!0),n.snapshot&&(e.snapshot=n.snapshot,e.snapshot.latestValues=n.animationValues||n.latestValues),e.root?.isUpdating&&(e.isLayoutDirty=!0)),e.options.crossfade===!1&&n.hide()}}exitAnimationComplete(){this.members.forEach(e=>{e.options.onExitComplete?.(),e.resumingFrom?.options.onExitComplete?.()})}scheduleRender(){this.members.forEach(e=>e.instance&&e.scheduleRender(!1))}removeLeadSnapshot(){this.lead?.snapshot&&(this.lead.snapshot=void 0)}},Vd={hasAnimatedSinceResize:!0,hasEverUpdated:!1},Hd={nodes:0,calculatedTargetDeltas:0,calculatedProjections:0},Ud=[``,`X`,`Y`,`Z`],Wd=1e3,Gd=0;function Kd(e,t,n,r){let{latestValues:i}=t;i[e]&&(n[e]=i[e],t.setStaticValue(e,0),r&&(r[e]=0))}function qd(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;let{visualElement:t}=e.options;if(!t)return;let n=uc(t);if(window.MotionHasOptimisedAnimation(n,`transform`)){let{layout:t,layoutId:r}=e.options;window.MotionCancelOptimisedAnimation(n,`transform`,N,!(t||r))}let{parent:r}=e;r&&!r.hasCheckedOptimisedAppear&&qd(r)}function Jd({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:i}){return class{constructor(e={},n=t?.()){this.id=Gd++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.layoutVersion=0,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,Oi.value&&(Hd.nodes=Hd.calculatedTargetDeltas=Hd.calculatedProjections=0),this.nodes.forEach(Zd),this.nodes.forEach(sf),this.nodes.forEach(cf),this.nodes.forEach(Qd),Oi.addProjectionMetrics&&Oi.addProjectionMetrics(Hd)},this.resolvedRelativeTargetAt=0,this.linkedParentVersion=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=e,this.root=n?n.root||n:this,this.path=n?[...n.path,n]:[],this.parent=n,this.depth=n?n.depth+1:0;for(let e=0;e<this.path.length;e++)this.path[e].shouldResetTransform=!0;this.root===this&&(this.nodes=new Ld)}addEventListener(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,new $r),this.eventHandlers.get(e).add(t)}notifyListeners(e,...t){let n=this.eventHandlers.get(e);n&&n.notify(...t)}hasListeners(e){return this.eventHandlers.has(e)}mount(t){if(this.instance)return;this.isSVG=al(t)&&!bl(t),this.instance=t;let{layoutId:n,layout:r,visualElement:i}=this.options;if(i&&!i.current&&i.mount(t),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(r||n)&&(this.isLayoutDirty=!0),e){let n,r=0,i=()=>this.root.updateBlockedByResize=!1;N.read(()=>{r=window.innerWidth}),e(t,()=>{let e=window.innerWidth;e!==r&&(r=e,this.root.updateBlockedByResize=!0,n&&n(),n=Rd(i,250),Vd.hasAnimatedSinceResize&&(Vd.hasAnimatedSinceResize=!1,this.nodes.forEach(of)))})}n&&this.root.registerSharedNode(n,this),this.options.animate!==!1&&i&&(n||r)&&this.addEventListener(`didUpdate`,({delta:e,hasLayoutChanged:t,hasRelativeLayoutChanged:n,layout:r})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}let a=this.options.transition||i.getDefaultTransition()||hf,{onLayoutAnimationStart:o,onLayoutAnimationComplete:s}=i.getProps(),c=!this.targetLayout||!bd(this.targetLayout,r),l=!t&&n;if(this.options.layoutRoot||this.resumeFrom||l||t&&(c||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);let t={...Hs(a,`layout`),onPlay:o,onComplete:s};(i.shouldReduceMotion||this.options.layoutRoot)&&(t.delay=0,t.type=!1),this.startAnimation(t),this.setAnimationOrigin(e,l)}else t||of(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=r})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);let e=this.getStack();e&&e.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Mi(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(lf),this.animationId++)}getTransformTemplate(){let{visualElement:e}=this.options;return e&&e.getProps().transformTemplate}willUpdate(e=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&qd(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let e=0;e<this.path.length;e++){let t=this.path[e];t.shouldResetTransform=!0,(typeof t.latestValues.x==`string`||typeof t.latestValues.y==`string`)&&(t.isLayoutDirty=!0),t.updateScroll(`snapshot`),t.options.layoutRoot&&t.willUpdate(!1)}let{layoutId:t,layout:n}=this.options;if(t===void 0&&!n)return;let r=this.getTransformTemplate();this.prevTransformTemplateValue=r?r(this.latestValues,``):void 0,this.updateSnapshot(),e&&this.notifyListeners(`willUpdate`)}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){let e=this.updateBlockedByResize;this.unblockUpdate(),this.updateBlockedByResize=!1,this.clearAllSnapshots(),e&&this.nodes.forEach(tf),this.nodes.forEach(ef);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(nf);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(rf),this.nodes.forEach(af),this.nodes.forEach(Yd),this.nodes.forEach(Xd)):this.nodes.forEach(nf),this.clearAllSnapshots();let e=Li.now();Ni.delta=Br(0,1e3/60,e-Ni.timestamp),Ni.timestamp=e,Ni.isProcessing=!0,Pi.update.process(Ni),Pi.preRender.process(Ni),Pi.render.process(Ni),Ni.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Rc.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach($d),this.sharedNodes.forEach(uf)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,N.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){N.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!td(this.snapshot.measuredBox.x)&&!td(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let e=0;e<this.path.length;e++)this.path[e].updateScroll();let e=this.layout;this.layout=this.measure(!1),this.layoutVersion++,this.layoutCorrected||=El(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners(`measure`,this.layout.layoutBox);let{visualElement:t}=this.options;t&&t.notify(`LayoutMeasure`,this.layout.layoutBox,e?e.layoutBox:void 0)}updateScroll(e=`measure`){let t=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===e&&(t=!1),t&&this.instance){let t=r(this.instance);this.scroll={animationId:this.root.animationId,phase:e,isRoot:t,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:t}}}resetTransform(){if(!i)return;let e=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,t=this.projectionDelta&&!gd(this.projectionDelta),n=this.getTransformTemplate(),r=n?n(this.latestValues,``):void 0,a=r!==this.prevTransformTemplateValue;e&&this.instance&&(t||Zl(this.latestValues)||a)&&(i(this.instance,r),this.shouldResetTransform=!1,this.scheduleRender())}measure(e=!0){let t=this.measurePageBox(),n=this.removeElementScroll(t);return e&&(n=this.removeTransform(n)),yf(n),{animationId:this.root.animationId,measuredBox:t,layoutBox:n,latestValues:{},source:this.id}}measurePageBox(){let{visualElement:e}=this.options;if(!e)return El();let t=e.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(xf))){let{scroll:e}=this.root;e&&(su(t.x,e.offset.x),su(t.y,e.offset.y))}return t}removeElementScroll(e){let t=El();if(qu(t,e),this.scroll?.wasRoot)return t;for(let n=0;n<this.path.length;n++){let r=this.path[n],{scroll:i,options:a}=r;r!==this.root&&i&&a.layoutScroll&&(i.wasRoot&&qu(t,e),su(t.x,i.offset.x),su(t.y,i.offset.y))}return t}applyTransform(e,t=!1,n){let r=n||El();qu(r,e);for(let e=0;e<this.path.length;e++){let n=this.path[e];!t&&n.options.layoutScroll&&n.scroll&&n!==n.root&&(su(r.x,-n.scroll.offset.x),su(r.y,-n.scroll.offset.y)),Zl(n.latestValues)&&uu(r,n.latestValues,n.layout?.layoutBox)}return Zl(this.latestValues)&&uu(r,this.latestValues,this.layout?.layoutBox),r}removeTransform(e){let t=El();qu(t,e);for(let e=0;e<this.path.length;e++){let n=this.path[e];if(!Zl(n.latestValues))continue;let r;n.instance&&(Xl(n.latestValues)&&n.updateSnapshot(),r=El(),qu(r,n.measurePageBox())),md(t,n.latestValues,n.snapshot?.layoutBox,r)}return Zl(this.latestValues)&&md(t,this.latestValues),t}setTargetDelta(e){this.targetDelta=e,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(e){this.options={...this.options,...e,crossfade:e.crossfade===void 0?!0:e.crossfade}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==Ni.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(e=!1){let t=this.getLead();this.isProjectionDirty||=t.isProjectionDirty,this.isTransformDirty||=t.isTransformDirty,this.isSharedProjectionDirty||=t.isSharedProjectionDirty;let n=!!this.resumingFrom||this!==t;if(!(e||n&&this.isSharedProjectionDirty||this.isProjectionDirty||this.parent?.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;let{layout:r,layoutId:i}=this.options;if(!this.layout||!(r||i))return;this.resolvedRelativeTargetAt=Ni.timestamp;let a=this.getClosestProjectingParent();a&&this.linkedParentVersion!==a.layoutVersion&&!a.options.layoutRoot&&this.removeRelativeTarget(),!this.targetDelta&&!this.relativeTarget&&(this.options.layoutAnchor!==!1&&a&&a.layout?this.createRelativeTarget(a,this.layout.layoutBox,a.layout.layoutBox):this.removeRelativeTarget()),!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=El(),this.targetWithTransforms=El()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),od(this.target,this.relativeTarget,this.relativeParent.target,this.options.layoutAnchor||void 0)):this.targetDelta?(this.resumingFrom?this.applyTransform(this.layout.layoutBox,!1,this.target):qu(this.target,this.layout.layoutBox),ru(this.target,this.targetDelta)):qu(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget&&(this.attemptToResolveRelativeTarget=!1,this.options.layoutAnchor!==!1&&a&&!!a.resumingFrom==!!this.resumingFrom&&!a.options.layoutScroll&&a.target&&this.animationProgress!==1?this.createRelativeTarget(a,this.target,a.target):this.relativeParent=this.relativeTarget=void 0),Oi.value&&Hd.calculatedTargetDeltas++)}getClosestProjectingParent(){if(!(!this.parent||Xl(this.parent.latestValues)||Ql(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}createRelativeTarget(e,t,n){this.relativeParent=e,this.linkedParentVersion=e.layoutVersion,this.forceRelativeParentToResolveTarget(),this.relativeTarget=El(),this.relativeTargetOrigin=El(),cd(this.relativeTargetOrigin,t,n,this.options.layoutAnchor||void 0),qu(this.relativeTarget,this.relativeTargetOrigin)}removeRelativeTarget(){this.relativeParent=this.relativeTarget=void 0}calcProjection(){let e=this.getLead(),t=!!this.resumingFrom||this!==e,n=!0;if((this.isProjectionDirty||this.parent?.isProjectionDirty)&&(n=!1),t&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(n=!1),this.resolvedRelativeTargetAt===Ni.timestamp&&(n=!1),n)return;let{layout:r,layoutId:i}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(r||i))return;qu(this.layoutCorrected,this.layout.layoutBox);let a=this.treeScale.x,o=this.treeScale.y;ou(this.layoutCorrected,this.treeScale,this.path,t),e.layout&&!e.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(e.target=e.layout.layoutBox,e.targetWithTransforms=El());let{target:s}=e;if(!s){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Ju(this.prevProjectionDelta.x,this.projectionDelta.x),Ju(this.prevProjectionDelta.y,this.projectionDelta.y)),id(this.projectionDelta,this.layoutCorrected,s,this.latestValues),(this.treeScale.x!==a||this.treeScale.y!==o||!Sd(this.projectionDelta.x,this.prevProjectionDelta.x)||!Sd(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners(`projectionUpdate`,s)),Oi.value&&Hd.calculatedProjections++}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(e=!0){if(this.options.visualElement?.scheduleRender(),e){let e=this.getStack();e&&e.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=wl(),this.projectionDelta=wl(),this.projectionDeltaWithTransform=wl()}setAnimationOrigin(e,t=!1){let n=this.snapshot,r=n?n.latestValues:{},i={...this.latestValues},a=wl();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!t;let o=El(),s=(n?n.source:void 0)!==(this.layout?this.layout.source:void 0),c=this.getStack(),l=!c||c.members.length<=1,u=!!(s&&!l&&this.options.crossfade===!0&&!this.path.some(mf));this.animationProgress=0;let d;this.mixTargetDelta=t=>{let n=t/1e3;df(a.x,e.x,n),df(a.y,e.y,n),this.setTargetDelta(a),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(cd(o,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),pf(this.relativeTarget,this.relativeTargetOrigin,o,n),d&&vd(this.relativeTarget,d)&&(this.isProjectionDirty=!1),d||=El(),qu(d,this.relativeTarget)),s&&(this.animationValues=i,kd(i,r,this.latestValues,n,u,l)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=n},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(e){this.notifyListeners(`animationStart`),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&=(Mi(this.pendingAnimation),void 0),this.pendingAnimation=N.update(()=>{Vd.hasAnimatedSinceResize=!0,Ri.layout++,this.motionValue||=ec(0),this.motionValue.jump(0,!1),this.currentAnimation=Pd(this.motionValue,[0,1e3],{...e,velocity:0,isSync:!0,onUpdate:t=>{this.mixTargetDelta(t),e.onUpdate&&e.onUpdate(t)},onStop:()=>{Ri.layout--},onComplete:()=>{Ri.layout--,e.onComplete&&e.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);let e=this.getStack();e&&e.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners(`animationComplete`)}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(Wd),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){let e=this.getLead(),{targetWithTransforms:t,target:n,layout:r,latestValues:i}=e;if(!(!t||!n||!r)){if(this!==e&&this.layout&&r&&bf(this.options.animationType,this.layout.layoutBox,r.layoutBox)){n=this.target||El();let t=td(this.layout.layoutBox.x);n.x.min=e.target.x.min,n.x.max=n.x.min+t;let r=td(this.layout.layoutBox.y);n.y.min=e.target.y.min,n.y.max=n.y.min+r}qu(t,n),uu(t,i),id(this.projectionDeltaWithTransform,this.layoutCorrected,t,i)}}registerSharedNode(e,t){this.sharedNodes.has(e)||this.sharedNodes.set(e,new Bd),this.sharedNodes.get(e).add(t);let n=t.options.initialPromotionConfig;t.promote({transition:n?n.transition:void 0,preserveFollowOpacity:n&&n.shouldPreserveFollowOpacity?n.shouldPreserveFollowOpacity(t):void 0})}isLead(){let e=this.getStack();return e?e.lead===this:!0}getLead(){let{layoutId:e}=this.options;return e&&this.getStack()?.lead||this}getPrevLead(){let{layoutId:e}=this.options;return e?this.getStack()?.prevLead:void 0}getStack(){let{layoutId:e}=this.options;if(e)return this.root.sharedNodes.get(e)}promote({needsReset:e,transition:t,preserveFollowOpacity:n}={}){let r=this.getStack();r&&r.promote(this,n),e&&(this.projectionDelta=void 0,this.needsReset=!0),t&&this.setOptions({transition:t})}relegate(){let e=this.getStack();return e?e.relegate(this):!1}resetSkewAndRotation(){let{visualElement:e}=this.options;if(!e)return;let t=!1,{latestValues:n}=e;if((n.z||n.rotate||n.rotateX||n.rotateY||n.rotateZ||n.skewX||n.skewY)&&(t=!0),!t)return;let r={};n.z&&Kd(`z`,e,r,this.animationValues);for(let t=0;t<Ud.length;t++)Kd(`rotate${Ud[t]}`,e,r,this.animationValues),Kd(`skew${Ud[t]}`,e,r,this.animationValues);e.render();for(let t in r)e.setStaticValue(t,r[t]),this.animationValues&&(this.animationValues[t]=r[t]);e.scheduleRender()}applyProjectionStyles(e,t){if(!this.instance||this.isSVG)return;if(!this.isVisible){e.visibility=`hidden`;return}let n=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,e.visibility=``,e.opacity=``,e.pointerEvents=zd(t?.pointerEvents)||``,e.transform=n?n(this.latestValues,``):`none`;return}let r=this.getLead();if(!this.projectionDelta||!this.layout||!r.target){this.options.layoutId&&(e.opacity=this.latestValues.opacity===void 0?1:this.latestValues.opacity,e.pointerEvents=zd(t?.pointerEvents)||``),this.hasProjected&&!Zl(this.latestValues)&&(e.transform=n?n({},``):`none`,this.hasProjected=!1);return}e.visibility=``;let i=r.animationValues||r.latestValues;this.applyTransformsToTarget();let a=wd(this.projectionDeltaWithTransform,this.treeScale,i);n&&(a=n(i,a)),e.transform=a;let{x:o,y:s}=this.projectionDelta;e.transformOrigin=`${o.origin*100}% ${s.origin*100}% 0`,r.animationValues?e.opacity=r===this?i.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:i.opacityExit:e.opacity=r===this?i.opacity===void 0?``:i.opacity:i.opacityExit===void 0?0:i.opacityExit;for(let t in xu){if(i[t]===void 0)continue;let{correct:n,applyTo:o,isCSSVariable:s}=xu[t],c=a===`none`?i[t]:n(i[t],r);if(o){let t=o.length;for(let n=0;n<t;n++)e[o[n]]=c}else s?this.options.visualElement.renderState.vars[t]=c:e[t]=c}this.options.layoutId&&(e.pointerEvents=r===this?zd(t?.pointerEvents)||``:`none`)}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(e=>e.currentAnimation?.stop()),this.root.nodes.forEach(ef),this.root.sharedNodes.clear()}}}function Yd(e){e.updateLayout()}function Xd(e){let t=e.resumeFrom?.snapshot||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners(`didUpdate`)){let{layoutBox:n,measuredBox:r}=e.layout,{animationType:i}=e.options,a=t.source!==e.layout.source;if(i===`size`)Cd(e=>{let r=a?t.measuredBox[e]:t.layoutBox[e],i=td(r);r.min=n[e].min,r.max=r.min+i});else if(i===`x`||i===`y`){let e=i===`x`?`y`:`x`;Ku(a?t.measuredBox[e]:t.layoutBox[e],n[e])}else bf(i,t.layoutBox,n)&&Cd(r=>{let i=a?t.measuredBox[r]:t.layoutBox[r],o=td(n[r]);i.max=i.min+o,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[r].max=e.relativeTarget[r].min+o)});let o=wl();id(o,n,t.layoutBox);let s=wl();a?id(s,e.applyTransform(r,!0),t.measuredBox):id(s,n,t.layoutBox);let c=!gd(o),l=!1;if(!e.resumeFrom){let r=e.getClosestProjectingParent();if(r&&!r.resumeFrom){let{snapshot:i,layout:a}=r;if(i&&a){let o=e.options.layoutAnchor||void 0,s=El();cd(s,t.layoutBox,i.layoutBox,o);let c=El();cd(c,n,a.layoutBox,o),bd(s,c)||(l=!0),r.options.layoutRoot&&(e.relativeTarget=c,e.relativeTargetOrigin=s,e.relativeParent=r)}}}e.notifyListeners(`didUpdate`,{layout:n,snapshot:t,delta:s,layoutDelta:o,hasLayoutChanged:c,hasRelativeLayoutChanged:l})}else if(e.isLead()){let{onExitComplete:t}=e.options;t&&t()}e.options.transition=void 0}function Zd(e){Oi.value&&Hd.nodes++,e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty),e.isTransformDirty||=e.parent.isTransformDirty)}function Qd(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function $d(e){e.clearSnapshot()}function ef(e){e.clearMeasurements()}function tf(e){e.isLayoutDirty=!0,e.updateLayout()}function nf(e){e.isLayoutDirty=!1}function rf(e){e.isAnimationBlocked&&e.layout&&!e.isLayoutDirty&&(e.snapshot=e.layout,e.isLayoutDirty=!0)}function af(e){let{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify(`BeforeLayoutMeasure`),e.resetTransform()}function of(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function sf(e){e.resolveTargetDelta()}function cf(e){e.calcProjection()}function lf(e){e.resetSkewAndRotation()}function uf(e){e.removeLeadSnapshot()}function df(e,t,n){e.translate=Ma(t.translate,0,n),e.scale=Ma(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function ff(e,t,n,r){e.min=Ma(t.min,n.min,r),e.max=Ma(t.max,n.max,r)}function pf(e,t,n,r){ff(e.x,t.x,n.x,r),ff(e.y,t.y,n.y,r)}function mf(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}var hf={duration:.45,ease:[.4,0,.1,1]},gf=e=>typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),_f=gf(`applewebkit/`)&&!gf(`chrome/`)?Math.round:Yr;function vf(e){e.min=_f(e.min),e.max=_f(e.max)}function yf(e){vf(e.x),vf(e.y)}function bf(e,t,n){return e===`position`||e===`preserve-aspect`&&!nd(xd(t),xd(n),.2)}function xf(e){return e!==e.root&&e.scroll?.wasRoot}var Sf=Jd({attachResizeListener:(e,t)=>Fd(e,`resize`,t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body?.scrollLeft||0,y:document.documentElement.scrollTop||document.body?.scrollTop||0}),checkIsScrollRoot:()=>!0}),Cf={current:void 0},wf=Jd({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Cf.current){let e=new Sf({});e.mount(window),e.setOptions({layoutScroll:!0}),Cf.current=e}return Cf.current},resetTransform:(e,t)=>{e.style.transform=t===void 0?`none`:t},checkIsScrollRoot:e=>window.getComputedStyle(e).position===`fixed`}),Tf=(0,d.createContext)({transformPagePoint:e=>e,isStatic:!1,reducedMotion:`never`});function Ef(e=!0){let t=(0,d.useContext)(Lr);if(t===null)return[!0,null];let{isPresent:n,onExitComplete:r,register:i}=t,a=(0,d.useId)();(0,d.useEffect)(()=>{if(e)return i(a)},[e]);let o=(0,d.useCallback)(()=>e&&r&&r(a),[a,r,e]);return!n&&r?[!1,o]:[!0]}var Df=(0,d.createContext)({strict:!1}),Of={animation:[`animate`,`variants`,`whileHover`,`whileTap`,`exit`,`whileInView`,`whileFocus`,`whileDrag`],exit:[`exit`],drag:[`drag`,`dragControls`],focus:[`whileFocus`],hover:[`whileHover`,`onHoverStart`,`onHoverEnd`],tap:[`whileTap`,`onTap`,`onTapStart`,`onTapCancel`],pan:[`onPan`,`onPanStart`,`onPanSessionStart`,`onPanEnd`],inView:[`whileInView`,`onViewportEnter`,`onViewportLeave`],layout:[`layout`,`layoutId`]},kf=!1;function Af(){if(kf)return;let e={};for(let t in Of)e[t]={isEnabled:e=>Of[t].some(t=>!!e[t])};Vl(e),kf=!0}function jf(){return Af(),Hl()}function Mf(e){let t=jf();for(let n in e)t[n]={...t[n],...e[n]};Vl(t)}var Nf=new Set(`animate.exit.variants.initial.style.values.variants.transition.transformTemplate.custom.inherit.onBeforeLayoutMeasure.onAnimationStart.onAnimationComplete.onUpdate.onDragStart.onDrag.onDragEnd.onMeasureDragConstraints.onDirectionLock.onDragTransitionEnd._dragX._dragY.onHoverStart.onHoverEnd.onViewportEnter.onViewportLeave.globalTapTarget.propagate.ignoreStrict.viewport`.split(`.`));function Pf(e){return e.startsWith(`while`)||e.startsWith(`drag`)&&e!==`draggable`||e.startsWith(`layout`)||e.startsWith(`onTap`)||e.startsWith(`onPan`)||e.startsWith(`onLayout`)||Nf.has(e)}var Ff=s({default:()=>If}),If,Lf=o((()=>{throw If={},Error(`Could not resolve "@emotion/is-prop-valid" imported by "framer-motion". Is it installed?`)})),Rf=e=>!Pf(e);function zf(e){typeof e==`function`&&(Rf=t=>t.startsWith(`on`)?!Pf(t):e(t))}try{zf((Lf(),u(Ff)).default)}catch{}function Bf(e,t,n){let r={};for(let i in e)i===`values`&&typeof e.values==`object`||ac(e[i])||(Rf(i)||n===!0&&Pf(i)||!t&&!Pf(i)||e.draggable&&i.startsWith(`onDrag`))&&(r[i]=e[i]);return r}var Vf=(0,d.createContext)({});function Hf(e,t){if(Ml(e)){let{initial:t,animate:n}=e;return{initial:t===!1||kl(t)?t:void 0,animate:kl(n)?n:void 0}}return e.inherit===!1?{}:t}function Uf(e){let{initial:t,animate:n}=Hf(e,(0,d.useContext)(Vf));return(0,d.useMemo)(()=>({initial:t,animate:n}),[Wf(t),Wf(n)])}function Wf(e){return Array.isArray(e)?e.join(` `):e}var Gf=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Kf(e,t,n){for(let r in t)!ac(t[r])&&!Su(r,n)&&(e[r]=t[r])}function qf({transformTemplate:e},t){return(0,d.useMemo)(()=>{let n=Gf();return gu(n,t,e),Object.assign({},n.vars,n.style)},[t])}function Jf(e,t){let n=e.style||{},r={};return Kf(r,n,e),Object.assign(r,qf(e,t)),r}function Yf(e,t){let n={},r=Jf(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout=`none`,r.touchAction=e.drag===!0?`none`:`pan-${e.drag===`x`?`y`:`x`}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=r,n}var Xf=()=>({...Gf(),attrs:{}});function Zf(e,t,n,r){let i=(0,d.useMemo)(()=>{let n=Xf();return Au(n,t,Mu(r),e.transformTemplate,e.style),{...n.attrs,style:{...n.style}}},[t]);if(e.style){let t={};Kf(t,e.style,e),i.style={...t,...i.style}}return i}var Qf=[`animate`,`circle`,`defs`,`desc`,`ellipse`,`g`,`image`,`line`,`filter`,`marker`,`mask`,`metadata`,`path`,`pattern`,`polygon`,`polyline`,`rect`,`stop`,`switch`,`symbol`,`svg`,`text`,`tspan`,`use`,`view`];function $f(e){return typeof e!=`string`||e.includes(`-`)?!1:!!(Qf.indexOf(e)>-1||/[A-Z]/u.test(e))}function ep(e,t,n,{latestValues:r},i,a=!1,o){let s=(o??$f(e)?Zf:Yf)(t,r,i,e),c=Bf(t,typeof e==`string`,a),l=e===d.Fragment?{}:{...c,...s,ref:n},{children:u}=t,f=(0,d.useMemo)(()=>ac(u)?u.get():u,[u]);return(0,d.createElement)(e,{...l,children:f})}function tp({scrapeMotionValuesFromProps:e,createRenderState:t},n,r,i){return{latestValues:np(n,r,i,e),renderState:t()}}function np(e,t,n,r){let i={},a=r(e,{});for(let e in a)i[e]=zd(a[e]);let{initial:o,animate:s}=e,c=Ml(e),l=Nl(e);t&&l&&!c&&e.inherit!==!1&&(o===void 0&&(o=t.initial),s===void 0&&(s=t.animate));let u=n?n.initial===!1:!1;u||=o===!1;let d=u?s:o;if(d&&typeof d!=`boolean`&&!Ol(d)){let t=Array.isArray(d)?d:[d];for(let n=0;n<t.length;n++){let r=qs(e,t[n]);if(r){let{transitionEnd:e,transition:t,...n}=r;for(let e in n){let t=n[e];if(Array.isArray(t)){let e=u?t.length-1:0;t=t[e]}t!==null&&(i[e]=t)}for(let t in e)i[t]=e[t]}}}return i}var rp=e=>(t,n)=>{let r=(0,d.useContext)(Vf),i=(0,d.useContext)(Lr),a=()=>tp(e,t,r,i);return n?a():Fr(a)},ip=rp({scrapeMotionValuesFromProps:Cu,createRenderState:Gf}),ap=rp({scrapeMotionValuesFromProps:Pu,createRenderState:Xf}),op=Symbol.for(`motionComponentSymbol`);function sp(e,t,n){let r=(0,d.useRef)(n);(0,d.useInsertionEffect)(()=>{r.current=n});let i=(0,d.useRef)(null);return(0,d.useCallback)(n=>{n&&e.onMount?.(n);let a=r.current;if(typeof a==`function`)if(n){let e=a(n);typeof e==`function`&&(i.current=e)}else i.current?(i.current(),i.current=null):a(n);else a&&(a.current=n);t&&(n?t.mount(n):t.unmount())},[t])}var cp=(0,d.createContext)({});function lp(e){return e&&typeof e==`object`&&Object.prototype.hasOwnProperty.call(e,`current`)}function up(e,t,n,r,i,a){let{visualElement:o}=(0,d.useContext)(Vf),s=(0,d.useContext)(Df),c=(0,d.useContext)(Lr),l=(0,d.useContext)(Tf),u=l.reducedMotion,f=l.skipAnimations,p=(0,d.useRef)(null),m=(0,d.useRef)(!1);r||=s.renderer,!p.current&&r&&(p.current=r(e,{visualState:t,parent:o,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:f,isSVG:a}),m.current&&p.current&&(p.current.manuallyAnimateOnMount=!0));let h=p.current,g=(0,d.useContext)(cp);h&&!h.projection&&i&&(h.type===`html`||h.type===`svg`)&&dp(p.current,n,i,g);let _=(0,d.useRef)(!1);(0,d.useInsertionEffect)(()=>{h&&_.current&&h.update(n,c)});let v=n[lc],y=(0,d.useRef)(!!v&&typeof window<`u`&&!window.MotionHandoffIsComplete?.(v)&&window.MotionHasOptimisedAnimation?.(v));return Ir(()=>{m.current=!0,h&&(_.current=!0,window.MotionIsMounted=!0,h.updateFeatures(),h.scheduleRenderMicrotask(),y.current&&h.animationState&&h.animationState.animateChanges())}),(0,d.useEffect)(()=>{h&&(!y.current&&h.animationState&&h.animationState.animateChanges(),y.current&&=(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(v)}),!1),h.enteringChildren=void 0)}),h}function dp(e,t,n,r){let{layoutId:i,layout:a,drag:o,dragConstraints:s,layoutScroll:c,layoutRoot:l,layoutAnchor:u,layoutCrossfade:d}=t;e.projection=new n(e.latestValues,t[`data-framer-portal-id`]?void 0:fp(e.parent)),e.projection.setOptions({layoutId:i,layout:a,alwaysMeasureLayout:!!o||s&&lp(s),visualElement:e,animationType:typeof a==`string`?a:`both`,initialPromotionConfig:r,crossfade:d,layoutScroll:c,layoutRoot:l,layoutAnchor:u})}function fp(e){if(e)return e.options.allowProjection===!1?fp(e.parent):e.projection}function pp(e,{forwardMotionProps:t=!1,type:n}={},r,i){r&&Mf(r);let a=n?n===`svg`:$f(e),o=a?ap:ip;function s(n,s){let c,l={...(0,d.useContext)(Tf),...n,layoutId:mp(n)},{isStatic:u}=l,p=Uf(n),m=o(n,u);if(!u&&typeof window<`u`){hp(l,r);let t=gp(l);c=t.MeasureLayout,p.visualElement=up(e,m,l,i,t.ProjectionNode,a)}return(0,f.jsxs)(Vf.Provider,{value:p,children:[c&&p.visualElement?(0,f.jsx)(c,{visualElement:p.visualElement,...l}):null,ep(e,n,sp(m,p.visualElement,s),m,u,t,a)]})}s.displayName=`motion.${typeof e==`string`?e:`create(${e.displayName??e.name??``})`}`;let c=(0,d.forwardRef)(s);return c[op]=e,c}function mp({layoutId:e}){let t=(0,d.useContext)(Pr).id;return t&&e!==void 0?t+`-`+e:e}function hp(e,t){let n=(0,d.useContext)(Df).strict;if(process.env.NODE_ENV!==`production`&&t&&n){let t="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";e.ignoreStrict?Hr(!1,t,`lazy-strict-mode`):Ur(!1,t,`lazy-strict-mode`)}}function gp(e){let{drag:t,layout:n}=jf();if(!t&&!n)return{};let r={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}function _p(e,t){if(typeof Proxy>`u`)return pp;let n=new Map,r=(n,r)=>pp(n,r,e,t);return new Proxy((e,t)=>(process.env.NODE_ENV!==`production`&&ii(!1,`motion() is deprecated. Use motion.create() instead.`),r(e,t)),{get:(i,a)=>a===`create`?r:(n.has(a)||n.set(a,pp(a,void 0,e,t)),n.get(a))})}var vp=(e,t)=>t.isSVG??$f(e)?new Fu(t):new Tu(t,{allowProjection:e!==d.Fragment}),yp=class extends Gl{constructor(e){super(e),e.animationState||=Hu(e)}updateAnimationControlsSubscription(){let{animate:e}=this.node.getProps();Ol(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){let{animate:e}=this.node.getProps(),{animate:t}=this.node.prevProps||{};e!==t&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}},bp=0,xp={animation:{Feature:yp},exit:{Feature:class extends Gl{constructor(){super(...arguments),this.id=bp++,this.isExitComplete=!1}update(){if(!this.node.presenceContext)return;let{isPresent:e,onExitComplete:t}=this.node.presenceContext,{isPresent:n}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===n)return;if(e&&n===!1){if(this.isExitComplete){let{initial:e,custom:t}=this.node.getProps();if(typeof e==`string`){let n=Js(this.node,e,t);if(n){let{transition:e,transitionEnd:t,...r}=n;for(let e in r)this.node.getValue(e)?.jump(r[e])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive(`exit`,!1);this.isExitComplete=!1;return}let r=this.node.animationState.setActive(`exit`,!e);t&&!e&&r.then(()=>{this.isExitComplete=!0,t(this.id)})}mount(){let{register:e,onExitComplete:t}=this.node.presenceContext||{};t&&t(this.id),e&&(this.unmount=e(this.id))}unmount(){}}}};function Sp(e){return{point:{x:e.pageX,y:e.pageY}}}var Cp=e=>t=>qc(t)&&e(t,Sp(t));function wp(e,t,n,r){return Fd(e,t,Cp(n),r)}var Tp=({current:e})=>e?e.ownerDocument.defaultView:null,Ep=(e,t)=>Math.abs(e-t);function Dp(e,t){let n=Ep(e.x,t.x),r=Ep(e.y,t.y);return Math.sqrt(n**2+r**2)}var Op=new Set([`auto`,`scroll`]),kp=class{constructor(e,t,{transformPagePoint:n,contextWindow:r=window,dragSnapToOrigin:i=!1,distanceThreshold:a=3,element:o}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=e=>{this.handleScroll(e.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=Ap(this.lastRawMoveEventInfo,this.transformPagePoint));let e=Mp(this.lastMoveEventInfo,this.history),t=this.startEvent!==null,n=Dp(e.offset,{x:0,y:0})>=this.distanceThreshold;if(!t&&!n)return;let{point:r}=e,{timestamp:i}=Ni;this.history.push({...r,timestamp:i});let{onStart:a,onMove:o}=this.handlers;t||(a&&a(this.lastMoveEvent,e),this.startEvent=this.lastMoveEvent),o&&o(this.lastMoveEvent,e)},this.handlePointerMove=(e,t)=>{this.lastMoveEvent=e,this.lastRawMoveEventInfo=t,this.lastMoveEventInfo=Ap(t,this.transformPagePoint),N.update(this.updatePoint,!0)},this.handlePointerUp=(e,t)=>{this.end();let{onEnd:n,onSessionEnd:r,resumeAnimation:i}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&i&&i(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;let a=Mp(e.type===`pointercancel`?this.lastMoveEventInfo:Ap(t,this.transformPagePoint),this.history);this.startEvent&&n&&n(e,a),r&&r(e,a)},!qc(e))return;this.dragSnapToOrigin=i,this.handlers=t,this.transformPagePoint=n,this.distanceThreshold=a,this.contextWindow=r||window;let s=Ap(Sp(e),this.transformPagePoint),{point:c}=s,{timestamp:l}=Ni;this.history=[{...c,timestamp:l}];let{onSessionStart:u}=t;u&&u(e,Mp(s,this.history)),this.removeListeners=Zr(wp(this.contextWindow,`pointermove`,this.handlePointerMove),wp(this.contextWindow,`pointerup`,this.handlePointerUp),wp(this.contextWindow,`pointercancel`,this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(e){let t=e.parentElement;for(;t;){let e=getComputedStyle(t);(Op.has(e.overflowX)||Op.has(e.overflowY))&&this.scrollPositions.set(t,{x:t.scrollLeft,y:t.scrollTop}),t=t.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener(`scroll`,this.onElementScroll,{capture:!0}),window.addEventListener(`scroll`,this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener(`scroll`,this.onElementScroll,{capture:!0}),window.removeEventListener(`scroll`,this.onWindowScroll)}}handleScroll(e){let t=this.scrollPositions.get(e);if(!t)return;let n=e===window,r=n?{x:window.scrollX,y:window.scrollY}:{x:e.scrollLeft,y:e.scrollTop},i={x:r.x-t.x,y:r.y-t.y};i.x===0&&i.y===0||(n?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=i.x,this.lastMoveEventInfo.point.y+=i.y):this.history.length>0&&(this.history[0].x-=i.x,this.history[0].y-=i.y),this.scrollPositions.set(e,r),N.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),Mi(this.updatePoint)}};function Ap(e,t){return t?{point:t(e.point)}:e}function jp(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Mp({point:e},t){return{point:e,delta:jp(e,Pp(t)),offset:jp(e,Np(t)),velocity:Fp(t,.1)}}function Np(e){return e[0]}function Pp(e){return e[e.length-1]}function Fp(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,r=null,i=Pp(e);for(;n>=0&&(r=e[n],!(i.timestamp-r.timestamp>ei(t)));)n--;if(!r)return{x:0,y:0};r===e[0]&&e.length>2&&i.timestamp-r.timestamp>ei(t)*2&&(r=e[1]);let a=ti(i.timestamp-r.timestamp);if(a===0)return{x:0,y:0};let o={x:(i.x-r.x)/a,y:(i.y-r.y)/a};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}function Ip(e,{min:t,max:n},r){return t!==void 0&&e<t?e=r?Ma(t,e,r.min):Math.max(e,t):n!==void 0&&e>n&&(e=r?Ma(n,e,r.max):Math.min(e,n)),e}function Lp(e,t,n){return{min:t===void 0?void 0:e.min+t,max:n===void 0?void 0:e.max+n-(e.max-e.min)}}function Rp(e,{top:t,left:n,bottom:r,right:i}){return{x:Lp(e.x,n,i),y:Lp(e.y,t,r)}}function zp(e,t){let n=t.min-e.min,r=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,r]=[r,n]),{min:n,max:r}}function Bp(e,t){return{x:zp(e.x,t.x),y:zp(e.y,t.y)}}function Vp(e,t){let n=.5,r=td(e),i=td(t);return i>r?n=Qr(t.min,t.max-r,e.min):r>i&&(n=Qr(e.min,e.max-i,t.min)),Br(0,1,n)}function Hp(e,t){let n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}var Up=.35;function Wp(e=Up){return e===!1?e=0:e===!0&&(e=Up),{x:Gp(e,`left`,`right`),y:Gp(e,`top`,`bottom`)}}function Gp(e,t,n){return{min:Kp(e,t),max:Kp(e,n)}}function Kp(e,t){return typeof e==`number`?e:e[t]||0}var qp=new WeakMap,Jp=class{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=El(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:t=!1,distanceThreshold:n}={}){let{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;let i=e=>{t&&this.snapToCursor(Sp(e).point),this.stopAnimation()},a=(e,t)=>{let{drag:n,dragPropagation:r,onDragStart:i}=this.getProps();if(n&&!r&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Hc(n),!this.openDragLock))return;this.latestPointerEvent=e,this.latestPanInfo=t,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Cd(e=>{let t=this.getAxisMotionValue(e).get()||0;if(sa.test(t)){let{projection:n}=this.visualElement;if(n&&n.layout){let r=n.layout.layoutBox[e];r&&(t=td(r)*(parseFloat(t)/100))}}this.originPoint[e]=t}),i&&N.update(()=>i(e,t),!1,!0),sc(this.visualElement,`transform`);let{animationState:a}=this.visualElement;a&&a.setActive(`whileDrag`,!0)},o=(e,t)=>{this.latestPointerEvent=e,this.latestPanInfo=t;let{dragPropagation:n,dragDirectionLock:r,onDirectionLock:i,onDrag:a}=this.getProps();if(!n&&!this.openDragLock)return;let{offset:o}=t;if(r&&this.currentDirection===null){this.currentDirection=Qp(o),this.currentDirection!==null&&i&&i(this.currentDirection);return}this.updateAxis(`x`,t.point,o),this.updateAxis(`y`,t.point,o),this.visualElement.render(),a&&N.update(()=>a(e,t),!1,!0)},s=(e,t)=>{this.latestPointerEvent=e,this.latestPanInfo=t,this.stop(e,t),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>{let{dragSnapToOrigin:e}=this.getProps();(e||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:l}=this.getProps();this.panSession=new kp(e,{onSessionStart:i,onStart:a,onMove:o,onSessionEnd:s,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:l,distanceThreshold:n,contextWindow:Tp(this.visualElement),element:this.visualElement.current})}stop(e,t){let n=e||this.latestPointerEvent,r=t||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!r||!n)return;let{velocity:a}=r;this.startAnimation(a);let{onDragEnd:o}=this.getProps();o&&N.postRender(()=>o(n,r))}cancel(){this.isDragging=!1;let{projection:e,animationState:t}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.endPanSession();let{dragPropagation:n}=this.getProps();!n&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),t&&t.setActive(`whileDrag`,!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(e,t,n){let{drag:r}=this.getProps();if(!n||!Zp(e,r,this.currentDirection))return;let i=this.getAxisMotionValue(e),a=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(a=Ip(a,this.constraints[e],this.elastic[e])),i.set(a)}resolveConstraints(){let{dragConstraints:e,dragElastic:t}=this.getProps(),n=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,r=this.constraints;e&&lp(e)?this.constraints||=this.resolveRefConstraints():e&&n?this.constraints=Rp(n.layoutBox,e):this.constraints=!1,this.elastic=Wp(t),r!==this.constraints&&!lp(e)&&n&&this.constraints&&!this.hasMutatedConstraints&&Cd(e=>{this.constraints!==!1&&this.getAxisMotionValue(e)&&(this.constraints[e]=Hp(n.layoutBox[e],this.constraints[e]))})}resolveRefConstraints(){let{dragConstraints:e,onMeasureDragConstraints:t}=this.getProps();if(!e||!lp(e))return!1;let n=e.current;Ur(n!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.",`drag-constraints-ref`);let{projection:r}=this.visualElement;if(!r||!r.layout)return!1;let i=fu(n,r.root,this.visualElement.getTransformPagePoint()),a=Bp(r.layout.layoutBox,i);if(t){let e=t(ql(a));this.hasMutatedConstraints=!!e,e&&(a=Kl(e))}return a}startAnimation(e){let{drag:t,dragMomentum:n,dragElastic:r,dragTransition:i,dragSnapToOrigin:a,onDragTransitionEnd:o}=this.getProps(),s=this.constraints||{},c=Cd(o=>{if(!Zp(o,t,this.currentDirection))return;let c=s&&s[o]||{};(a===!0||a===o)&&(c={min:0,max:0});let l=r?200:1e6,u=r?40:1e7,d={type:`inertia`,velocity:n?e[o]:0,bounceStiffness:l,bounceDamping:u,timeConstant:750,restDelta:1,restSpeed:10,...i,...c};return this.startAxisValueAnimation(o,d)});return Promise.all(c).then(o)}startAxisValueAnimation(e,t){let n=this.getAxisMotionValue(e);return sc(this.visualElement,e),n.start(Gs(e,n,0,t,this.visualElement,!1))}stopAnimation(){Cd(e=>this.getAxisMotionValue(e).stop())}getAxisMotionValue(e){let t=`_drag${e.toUpperCase()}`,n=this.visualElement.getProps();return n[t]||this.visualElement.getValue(e,(n.initial?n.initial[e]:void 0)||0)}snapToCursor(e){Cd(t=>{let{drag:n}=this.getProps();if(!Zp(t,n,this.currentDirection))return;let{projection:r}=this.visualElement,i=this.getAxisMotionValue(t);if(r&&r.layout){let{min:n,max:a}=r.layout.layoutBox[t],o=i.get()||0;i.set(e[t]-Ma(n,a,.5)+o)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;let{drag:e,dragConstraints:t}=this.getProps(),{projection:n}=this.visualElement;if(!lp(t)||!n||!this.constraints)return;this.stopAnimation();let r={x:0,y:0};Cd(e=>{let t=this.getAxisMotionValue(e);if(t&&this.constraints!==!1){let n=t.get();r[e]=Vp({min:n,max:n},this.constraints[e])}});let{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},``):`none`,n.root&&n.root.updateScroll(),n.updateLayout(),this.constraints=!1,this.resolveConstraints(),Cd(t=>{if(!Zp(t,e,null))return;let n=this.getAxisMotionValue(t),{min:i,max:a}=this.constraints[t];n.set(Ma(i,a,r[t]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;qp.set(this.visualElement,this);let e=this.visualElement.current,t=wp(e,`pointerdown`,t=>{let{drag:n,dragListener:r=!0}=this.getProps(),i=t.target,a=i!==e&&Zc(i);n&&r&&!a&&this.start(t)}),n,r=()=>{let{dragConstraints:t}=this.getProps();lp(t)&&t.current&&(this.constraints=this.resolveRefConstraints(),n||=Xp(e,t.current,()=>this.scalePositionWithinConstraints()))},{projection:i}=this.visualElement,a=i.addEventListener(`measure`,r);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),N.read(r);let o=Fd(window,`resize`,()=>this.scalePositionWithinConstraints()),s=i.addEventListener(`didUpdate`,(({delta:e,hasLayoutChanged:t})=>{this.isDragging&&t&&(Cd(t=>{let n=this.getAxisMotionValue(t);n&&(this.originPoint[t]+=e[t].translate,n.set(n.get()+e[t].translate))}),this.visualElement.render())}));return()=>{o(),t(),a(),s&&s(),n&&n()}}getProps(){let e=this.visualElement.getProps(),{drag:t=!1,dragDirectionLock:n=!1,dragPropagation:r=!1,dragConstraints:i=!1,dragElastic:a=Up,dragMomentum:o=!0}=e;return{...e,drag:t,dragDirectionLock:n,dragPropagation:r,dragConstraints:i,dragElastic:a,dragMomentum:o}}};function Yp(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function Xp(e,t,n){let r=yl(e,Yp(n)),i=yl(t,Yp(n));return()=>{r(),i()}}function Zp(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Qp(e,t=10){let n=null;return Math.abs(e.y)>t?n=`y`:Math.abs(e.x)>t&&(n=`x`),n}var $p=class extends Gl{constructor(e){super(e),this.removeGroupControls=Yr,this.removeListeners=Yr,this.controls=new Jp(e)}mount(){let{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Yr}update(){let{dragControls:e}=this.node.getProps(),{dragControls:t}=this.node.prevProps||{};e!==t&&(this.removeGroupControls(),e&&(this.removeGroupControls=e.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}},em=e=>(t,n)=>{e&&N.update(()=>e(t,n),!1,!0)},tm=class extends Gl{constructor(){super(...arguments),this.removePointerDownListener=Yr}onPointerDown(e){this.session=new kp(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Tp(this.node)})}createPanHandlers(){let{onPanSessionStart:e,onPanStart:t,onPan:n,onPanEnd:r}=this.node.getProps();return{onSessionStart:em(e),onStart:em(t),onMove:em(n),onEnd:(e,t)=>{delete this.session,r&&N.postRender(()=>r(e,t))}}}mount(){this.removePointerDownListener=wp(this.node.current,`pointerdown`,e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}},nm=!1,rm=class extends d.Component{componentDidMount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:n,layoutId:r}=this.props,{projection:i}=e;i&&(t.group&&t.group.add(i),n&&n.register&&r&&n.register(i),nm&&i.root.didUpdate(),i.addEventListener(`animationComplete`,()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Vd.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){let{layoutDependency:t,visualElement:n,drag:r,isPresent:i}=this.props,{projection:a}=n;return a?(a.isPresent=i,e.layoutDependency!==t&&a.setOptions({...a.options,layoutDependency:t}),nm=!0,r||e.layoutDependency!==t||t===void 0||e.isPresent!==i?a.willUpdate():this.safeToRemove(),e.isPresent!==i&&(i?a.promote():a.relegate()||N.postRender(()=>{let e=a.getStack();(!e||!e.members.length)&&this.safeToRemove()})),null):null}componentDidUpdate(){let{visualElement:e,layoutAnchor:t}=this.props,{projection:n}=e;n&&(n.options.layoutAnchor=t,n.root.didUpdate(),Rc.postRender(()=>{!n.currentAnimation&&n.isLead()&&this.safeToRemove()}))}componentWillUnmount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:n}=this.props,{projection:r}=e;nm=!0,r&&(r.scheduleCheckAfterUnmount(),t&&t.group&&t.group.remove(r),n&&n.deregister&&n.deregister(r))}safeToRemove(){let{safeToRemove:e}=this.props;e&&e()}render(){return null}};function im(e){let[t,n]=Ef(),r=(0,d.useContext)(Pr);return(0,f.jsx)(rm,{...e,layoutGroup:r,switchLayoutGroup:(0,d.useContext)(cp),isPresent:t,safeToRemove:n})}var am={pan:{Feature:tm},drag:{Feature:$p,ProjectionNode:wf,MeasureLayout:im}};function om(e,t,n){let{props:r}=e;e.animationState&&r.whileHover&&e.animationState.setActive(`whileHover`,n===`Start`);let i=r[`onHover`+n];i&&N.postRender(()=>i(t,Sp(t)))}var sm=class extends Gl{mount(){let{current:e}=this.node;e&&(this.unmount=Gc(e,(e,t)=>(om(this.node,t,`Start`),e=>om(this.node,e,`End`))))}unmount(){}},cm=class extends Gl{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(`:focus-visible`)}catch{e=!0}!e||!this.node.animationState||(this.node.animationState.setActive(`whileFocus`,!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive(`whileFocus`,!1),this.isActive=!1)}mount(){this.unmount=Zr(Fd(this.node.current,`focus`,()=>this.onFocus()),Fd(this.node.current,`blur`,()=>this.onBlur()))}unmount(){}};function lm(e,t,n){let{props:r}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&r.whileTap&&e.animationState.setActive(`whileTap`,n===`Start`);let i=r[`onTap`+(n===`End`?``:n)];i&&N.postRender(()=>i(t,Sp(t)))}var um=class extends Gl{mount(){let{current:e}=this.node;if(!e)return;let{globalTapTarget:t,propagate:n}=this.node.props;this.unmount=il(e,(e,t)=>(lm(this.node,t,`Start`),(e,{success:t})=>lm(this.node,e,t?`End`:`Cancel`)),{useGlobalTarget:t,stopPropagation:n?.tap===!1})}unmount(){}},dm=new WeakMap,fm=new WeakMap,pm=e=>{let t=dm.get(e.target);t&&t(e)},mm=e=>{e.forEach(pm)};function hm({root:e,...t}){let n=e||document;fm.has(n)||fm.set(n,{});let r=fm.get(n),i=JSON.stringify(t);return r[i]||(r[i]=new IntersectionObserver(mm,{root:e,...t})),r[i]}function gm(e,t,n){let r=hm(t);return dm.set(e,n),r.observe(e),()=>{dm.delete(e),r.unobserve(e)}}var _m={some:0,all:1},vm=class extends Gl{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.stopObserver?.();let{viewport:e={}}=this.node.getProps(),{root:t,margin:n,amount:r=`some`,once:i}=e,a={root:t?t.current:void 0,rootMargin:n,threshold:typeof r==`number`?r:_m[r]};this.stopObserver=gm(this.node.current,a,e=>{let{isIntersecting:t}=e;if(this.isInView===t||(this.isInView=t,i&&!t&&this.hasEnteredView))return;t&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive(`whileInView`,t);let{onViewportEnter:n,onViewportLeave:r}=this.node.getProps(),a=t?n:r;a&&a(e)})}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>`u`)return;let{props:e,prevProps:t}=this.node;[`amount`,`margin`,`root`].some(ym(e,t))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}};function ym({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}var bm={inView:{Feature:vm},tap:{Feature:um},focus:{Feature:cm},hover:{Feature:sm}},xm={layout:{ProjectionNode:wf,MeasureLayout:im}},Sm=_p({...xp,...bm,...am,...xm},vp);function Cm(e,t){return t.forEach(function(t){t&&typeof t!=`string`&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!==`default`&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}var wm=Object.defineProperty,Tm=(e,t,n)=>t in e?wm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Em=(e,t,n)=>Tm(e,typeof t==`symbol`?t:t+``,n),Dm=class{constructor(){Em(this,`_locking`),Em(this,`_locks`),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e,t=new Promise(t=>e=()=>{--this._locks,t()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}};function Om(e,t){if(!e)throw Error(t)}var km=34028234663852886e22,Am=-34028234663852886e22,jm=4294967295,Mm=2147483647,Nm=-2147483648;function Pm(e){if(typeof e!=`number`)throw Error(`invalid int 32: `+typeof e);if(!Number.isInteger(e)||e>Mm||e<Nm)throw Error(`invalid int 32: `+e)}function Fm(e){if(typeof e!=`number`)throw Error(`invalid uint 32: `+typeof e);if(!Number.isInteger(e)||e>jm||e<0)throw Error(`invalid uint 32: `+e)}function Im(e){if(typeof e!=`number`)throw Error(`invalid float 32: `+typeof e);if(Number.isFinite(e)&&(e>km||e<Am))throw Error(`invalid float 32: `+e)}var Lm=Symbol(`@bufbuild/protobuf/enum-type`);function Rm(e){let t=e[Lm];return Om(t,`missing enum type on enum object`),t}function zm(e,t,n,r){e[Lm]=Bm(t,n.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function Bm(e,t,n){let r=Object.create(null),i=Object.create(null),a=[];for(let e of t){let t=Hm(e);a.push(t),r[e.name]=t,i[e.no]=t}return{typeName:e,values:a,findName(e){return r[e]},findNumber(e){return i[e]}}}function Vm(e,t,n){let r={};for(let e of t){let t=Hm(e);r[t.localName]=t.no,r[t.no]=t.localName}return zm(r,e,t),r}function Hm(e){return`localName`in e?e:Object.assign(Object.assign({},e),{localName:e.name})}var Um=class{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){let n=this.getType().runtime.bin,r=n.makeReadOptions(t);return n.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){let n=this.getType(),r=n.runtime.json,i=r.makeReadOptions(t);return r.readMessage(n,e,i,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`cannot decode ${this.getType().typeName} from JSON: ${e instanceof Error?e.message:String(e)}`)}return this.fromJson(n,t)}toBinary(e){let t=this.getType().runtime.bin,n=t.makeWriteOptions(e),r=n.writerFactory();return t.writeMessage(this,r,n),r.finish()}toJson(e){let t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){let t=this.toJson(e);return JSON.stringify(t,null,e?.prettySpaces??0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}};function Wm(e,t,n,r){let i=r?.localName??t.substring(t.lastIndexOf(`.`)+1),a={[i]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[i];return Object.setPrototypeOf(a.prototype,new Um),Object.assign(a,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary(e,t){return new a().fromBinary(e,t)},fromJson(e,t){return new a().fromJson(e,t)},fromJsonString(e,t){return new a().fromJsonString(e,t)},equals(t,n){return e.util.equals(a,t,n)}}),a}function Gm(){let e=0,t=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(n&15)<<28,t=(n&112)>>4,!(n&128))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(t|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}throw Error(`invalid varint`)}function Km(e,t,n){for(let r=0;r<28;r+=7){let i=e>>>r,a=!(!(i>>>7)&&t==0),o=(a?i|128:i)&255;if(n.push(o),!a)return}let r=e>>>28&15|(t&7)<<4,i=!!(t>>3);if(n.push((i?r|128:r)&255),i){for(let e=3;e<31;e+=7){let r=t>>>e,i=!!(r>>>7),a=(i?r|128:r)&255;if(n.push(a),!i)return}n.push(t>>>31&1)}}var qm=4294967296;function Jm(e){let t=e[0]===`-`;t&&(e=e.slice(1));let n=1e6,r=0,i=0;function a(t,a){let o=Number(e.slice(t,a));i*=n,r=r*n+o,r>=qm&&(i+=r/qm|0,r%=qm)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?$m(r,i):Qm(r,i)}function Ym(e,t){let n=Qm(e,t),r=n.hi&2147483648;r&&(n=$m(n.lo,n.hi));let i=Xm(n.lo,n.hi);return r?`-`+i:i}function Xm(e,t){if({lo:e,hi:t}=Zm(e,t),t<=2097151)return String(qm*t+e);let n=e&16777215,r=(e>>>24|t<<8)&16777215,i=t>>16&65535,a=n+r*6777216+i*6710656,o=r+i*8147497,s=i*2,c=1e7;return a>=c&&(o+=Math.floor(a/c),a%=c),o>=c&&(s+=Math.floor(o/c),o%=c),s.toString()+eh(o)+eh(a)}function Zm(e,t){return{lo:e>>>0,hi:t>>>0}}function Qm(e,t){return{lo:e|0,hi:t|0}}function $m(e,t){return t=~t,e?e=~e+1:t+=1,Qm(e,t)}var eh=e=>{let t=String(e);return`0000000`.slice(t.length)+t};function th(e,t){if(e>=0){for(;e>127;)t.push(e&127|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(e&127|128),e>>=7;t.push(1)}}function nh(){let e=this.buf[this.pos++],t=e&127;if(!(e&128)||(e=this.buf[this.pos++],t|=(e&127)<<7,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<14,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<21,!(e&128)))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(e&15)<<28;for(let t=5;e&128&&t<10;t++)e=this.buf[this.pos++];if(e&128)throw Error(`invalid varint`);return this.assertBounds(),t>>>0}function rh(){let e=new DataView(new ArrayBuffer(8));if(typeof BigInt==`function`&&typeof e.getBigInt64==`function`&&typeof e.getBigUint64==`function`&&typeof e.setBigInt64==`function`&&typeof e.setBigUint64==`function`&&(typeof process!=`object`||typeof process.env!=`object`||process.env.BUF_BIGINT_DISABLE!==`1`)){let t=BigInt(`-9223372036854775808`),n=BigInt(`9223372036854775807`),r=BigInt(`0`),i=BigInt(`18446744073709551615`);return{zero:BigInt(0),supported:!0,parse(e){let r=typeof e==`bigint`?e:BigInt(e);if(r>n||r<t)throw Error(`int64 invalid: ${e}`);return r},uParse(e){let t=typeof e==`bigint`?e:BigInt(e);if(t>i||t<r)throw Error(`uint64 invalid: ${e}`);return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec(t,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)},uDec(t,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0)}}}let t=e=>Om(/^-?[0-9]+$/.test(e),`int64 invalid: ${e}`),n=e=>Om(/^[0-9]+$/.test(e),`uint64 invalid: ${e}`);return{zero:`0`,supported:!1,parse(e){return typeof e!=`string`&&(e=e.toString()),t(e),e},uParse(e){return typeof e!=`string`&&(e=e.toString()),n(e),e},enc(e){return typeof e!=`string`&&(e=e.toString()),t(e),Jm(e)},uEnc(e){return typeof e!=`string`&&(e=e.toString()),n(e),Jm(e)},dec(e,t){return Ym(e,t)},uDec(e,t){return Xm(e,t)}}}var ih=rh(),F;(function(e){e[e.DOUBLE=1]=`DOUBLE`,e[e.FLOAT=2]=`FLOAT`,e[e.INT64=3]=`INT64`,e[e.UINT64=4]=`UINT64`,e[e.INT32=5]=`INT32`,e[e.FIXED64=6]=`FIXED64`,e[e.FIXED32=7]=`FIXED32`,e[e.BOOL=8]=`BOOL`,e[e.STRING=9]=`STRING`,e[e.BYTES=12]=`BYTES`,e[e.UINT32=13]=`UINT32`,e[e.SFIXED32=15]=`SFIXED32`,e[e.SFIXED64=16]=`SFIXED64`,e[e.SINT32=17]=`SINT32`,e[e.SINT64=18]=`SINT64`})(F||={});var ah;(function(e){e[e.BIGINT=0]=`BIGINT`,e[e.STRING=1]=`STRING`})(ah||={});function oh(e,t,n){if(t===n)return!0;if(e==F.BYTES){if(!(t instanceof Uint8Array)||!(n instanceof Uint8Array)||t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}switch(e){case F.UINT64:case F.FIXED64:case F.INT64:case F.SFIXED64:case F.SINT64:return t==n}return!1}function sh(e,t){switch(e){case F.BOOL:return!1;case F.UINT64:case F.FIXED64:case F.INT64:case F.SFIXED64:case F.SINT64:return t==0?ih.zero:`0`;case F.DOUBLE:case F.FLOAT:return 0;case F.BYTES:return new Uint8Array;case F.STRING:return``;default:return 0}}function ch(e,t){switch(e){case F.BOOL:return t===!1;case F.STRING:return t===``;case F.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return t==0}}var lh;(function(e){e[e.Varint=0]=`Varint`,e[e.Bit64=1]=`Bit64`,e[e.LengthDelimited=2]=`LengthDelimited`,e[e.StartGroup=3]=`StartGroup`,e[e.EndGroup=4]=`EndGroup`,e[e.Bit32=5]=`Bit32`})(lh||={});var uh=class{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw Error(`invalid state, fork stack empty`);return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Fm(e);e>127;)this.buf.push(e&127|128),e>>>=7;return this.buf.push(e),this}int32(e){return Pm(e),th(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){Im(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){Fm(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Pm(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Pm(e),e=(e<<1^e>>31)>>>0,th(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=ih.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=ih.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=ih.enc(e);return Km(t.lo,t.hi,this.buf),this}sint64(e){let t=ih.enc(e),n=t.hi>>31;return Km(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=ih.uEnc(e);return Km(t.lo,t.hi,this.buf),this}},dh=class{constructor(e,t){this.varint64=Gm,this.uint32=nh,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw Error(`illegal tag: field no `+t+` wire type `+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case lh.Varint:for(;this.buf[this.pos++]&128;);break;case lh.Bit64:this.pos+=4;case lh.Bit32:this.pos+=4;break;case lh.LengthDelimited:let n=this.uint32();this.pos+=n;break;case lh.StartGroup:for(;;){let[e,n]=this.tag();if(n===lh.EndGroup){if(t!==void 0&&e!==t)throw Error(`invalid end group tag`);break}this.skip(n,e)}break;default:throw Error(`cant skip wire type `+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw RangeError(`premature EOF`)}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return ih.dec(...this.varint64())}uint64(){return ih.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,ih.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return ih.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return ih.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}};function fh(e,t,n,r){let i;return{typeName:t,extendee:n,get field(){if(!i){let n=typeof r==`function`?r():r;n.name=t.split(`.`).pop(),n.jsonName=`[${t}]`,i=e.util.newFieldList([n]).list()[0]}return i},runtime:e}}function ph(e){let t=e.field.localName,n=Object.create(null);return n[t]=mh(e),[n,()=>n[t]]}function mh(e){let t=e.field;if(t.repeated)return[];if(t.default!==void 0)return t.default;switch(t.kind){case`enum`:return t.T.values[0].no;case`scalar`:return sh(t.T,t.L);case`message`:let e=t.T,n=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(n):n;case`map`:throw`map fields are not allowed to be extensions`}}function hh(e,t){if(!t.repeated&&(t.kind==`enum`||t.kind==`scalar`)){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter(e=>e.no===t.no)}var gh=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.split(``),_h=[];for(let e=0;e<gh.length;e++)_h[gh[e].charCodeAt(0)]=e;_h[45]=gh.indexOf(`+`),_h[95]=gh.indexOf(`/`);var vh={dec(e){let t=e.length*3/4;e[e.length-2]==`=`?t-=2:e[e.length-1]==`=`&&--t;let n=new Uint8Array(t),r=0,i=0,a,o=0;for(let t=0;t<e.length;t++){if(a=_h[e.charCodeAt(t)],a===void 0)switch(e[t]){case`=`:i=0;case`
|
|
26
|
+
`:case`\r`:case` `:case` `:continue;default:throw Error(`invalid base64 string.`)}switch(i){case 0:o=a,i=1;break;case 1:n[r++]=o<<2|(a&48)>>4,o=a,i=2;break;case 2:n[r++]=(o&15)<<4|(a&60)>>2,o=a,i=3;break;case 3:n[r++]=(o&3)<<6|a,i=0;break}}if(i==1)throw Error(`invalid base64 string.`);return n.subarray(0,r)},enc(e){let t=``,n=0,r,i=0;for(let a=0;a<e.length;a++)switch(r=e[a],n){case 0:t+=gh[r>>2],i=(r&3)<<4,n=1;break;case 1:t+=gh[i|r>>4],i=(r&15)<<2,n=2;break;case 2:t+=gh[i|r>>6],t+=gh[r&63],n=0;break}return n&&(t+=gh[i],t+=`=`,n==1&&(t+=`=`)),t}};function yh(e,t,n){Sh(t,e);let r=t.runtime.bin.makeReadOptions(n),i=hh(e.getType().runtime.bin.listUnknownFields(e),t.field),[a,o]=ph(t);for(let e of i)t.runtime.bin.readField(a,r.readerFactory(e.data),t.field,e.wireType,r);return o()}function bh(e,t,n,r){Sh(t,e);let i=t.runtime.bin.makeReadOptions(r),a=t.runtime.bin.makeWriteOptions(r);if(xh(e,t)){let n=e.getType().runtime.bin.listUnknownFields(e).filter(e=>e.no!=t.field.no);e.getType().runtime.bin.discardUnknownFields(e);for(let t of n)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}let o=a.writerFactory(),s=t.field;!s.opt&&!s.repeated&&(s.kind==`enum`||s.kind==`scalar`)&&(s=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(s,n,o,a);let c=i.readerFactory(o.finish());for(;c.pos<c.len;){let[t,n]=c.tag(),r=c.skip(n,t);e.getType().runtime.bin.onUnknownField(e,t,n,r)}}function xh(e,t){let n=e.getType();return t.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(e).find(e=>e.no==t.field.no)}function Sh(e,t){Om(e.extendee.typeName==t.getType().typeName,`extension ${e.typeName} can only be applied to message ${e.extendee.typeName}`)}function Ch(e,t){let n=e.localName;if(e.repeated)return t[n].length>0;if(e.oneof)return t[e.oneof.localName].case===n;switch(e.kind){case`enum`:case`scalar`:return e.opt||e.req?t[n]!==void 0:e.kind==`enum`?t[n]!==e.T.values[0].no:!ch(e.T,t[n]);case`message`:return t[n]!==void 0;case`map`:return Object.keys(t[n]).length>0}}function wh(e,t){let n=e.localName,r=!e.opt&&!e.req;if(e.repeated)t[n]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case`map`:t[n]={};break;case`enum`:t[n]=r?e.T.values[0].no:void 0;break;case`scalar`:t[n]=r?sh(e.T,e.L):void 0;break;case`message`:t[n]=void 0;break}}function Th(e,t){if(typeof e!=`object`||!e||!Object.getOwnPropertyNames(Um.prototype).every(t=>t in e&&typeof e[t]==`function`))return!1;let n=e.getType();return n===null||typeof n!=`function`||!(`typeName`in n)||typeof n.typeName!=`string`?!1:t===void 0?!0:n.typeName==t.typeName}function Eh(e,t){return Th(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}F.DOUBLE,F.FLOAT,F.INT64,F.UINT64,F.INT32,F.UINT32,F.BOOL,F.STRING,F.BYTES;var Dh={ignoreUnknownFields:!1},Oh={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function kh(e){return e?Object.assign(Object.assign({},Dh),e):Dh}function Ah(e){return e?Object.assign(Object.assign({},Oh),e):Oh}var jh=Symbol(),Mh=Symbol();function Nh(){return{makeReadOptions:kh,makeWriteOptions:Ah,readMessage(e,t,n,r){if(t==null||Array.isArray(t)||typeof t!=`object`)throw Error(`cannot decode message ${e.typeName} from JSON: ${Ph(t)}`);r??=new e;let i=new Map,a=n.typeRegistry;for(let[o,s]of Object.entries(t)){let t=e.fields.findJsonName(o);if(t){if(t.oneof){if(s===null&&t.kind==`scalar`)continue;let n=i.get(t.oneof);if(n!==void 0)throw Error(`cannot decode message ${e.typeName} from JSON: multiple keys for oneof "${t.oneof.name}" present: "${n}", "${o}"`);i.set(t.oneof,o)}Fh(r,s,t,n,e)}else{let t=!1;if(a?.findExtension&&o.startsWith(`[`)&&o.endsWith(`]`)){let i=a.findExtension(o.substring(1,o.length-1));if(i&&i.extendee.typeName==e.typeName){t=!0;let[e,a]=ph(i);Fh(e,s,i.field,n,i),bh(r,i,a(),n)}}if(!t&&!n.ignoreUnknownFields)throw Error(`cannot decode message ${e.typeName} from JSON: key "${o}" is unknown`)}}return r},writeMessage(e,t){let n=e.getType(),r={},i;try{for(i of n.fields.byNumber()){if(!Ch(i,e)){if(i.req)throw`required field not set`;if(!t.emitDefaultValues||!zh(i))continue}let n=i.oneof?e[i.oneof.localName].value:e[i.localName],a=Bh(i,n,t);a!==void 0&&(r[t.useProtoFieldName?i.name:i.jsonName]=a)}let a=t.typeRegistry;if(a?.findExtensionFor)for(let i of n.runtime.bin.listUnknownFields(e)){let o=a.findExtensionFor(n.typeName,i.no);if(o&&xh(e,o)){let n=yh(e,o,t),i=Bh(o.field,n,t);i!==void 0&&(r[o.field.jsonName]=i)}}}catch(e){let t=i?`cannot encode field ${n.typeName}.${i.name} to JSON`:`cannot encode message ${n.typeName} to JSON`,r=e instanceof Error?e.message:String(e);throw Error(t+(r.length>0?`: ${r}`:``))}return r},readScalar(e,t,n){return Lh(e,t,n??ah.BIGINT,!0)},writeScalar(e,t,n){if(t!==void 0&&(n||ch(e,t)))return Hh(e,t)},debug:Ph}}function Ph(e){if(e===null)return`null`;switch(typeof e){case`object`:return Array.isArray(e)?`array`:`object`;case`string`:return e.length>100?`string`:`"${e.split(`"`).join(`\\"`)}"`;default:return String(e)}}function Fh(e,t,n,r,i){let a=n.localName;if(n.repeated){if(Om(n.kind!=`map`),t===null)return;if(!Array.isArray(t))throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${Ph(t)}`);let o=e[a];for(let e of t){if(e===null)throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${Ph(e)}`);switch(n.kind){case`message`:o.push(n.T.fromJson(e,r));break;case`enum`:let t=Rh(n.T,e,r.ignoreUnknownFields,!0);t!==Mh&&o.push(t);break;case`scalar`:try{o.push(Lh(n.T,e,n.L,!0))}catch(t){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${Ph(e)}`;throw t instanceof Error&&t.message.length>0&&(r+=`: ${t.message}`),Error(r)}break}}}else if(n.kind==`map`){if(t===null)return;if(typeof t!=`object`||Array.isArray(t))throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${Ph(t)}`);let o=e[a];for(let[e,a]of Object.entries(t)){if(a===null)throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: map value null`);let s;try{s=Ih(n.K,e)}catch(e){let r=`cannot decode map key for field ${i.typeName}.${n.name} from JSON: ${Ph(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}switch(n.V.kind){case`message`:o[s]=n.V.T.fromJson(a,r);break;case`enum`:let e=Rh(n.V.T,a,r.ignoreUnknownFields,!0);e!==Mh&&(o[s]=e);break;case`scalar`:try{o[s]=Lh(n.V.T,a,ah.BIGINT,!0)}catch(e){let r=`cannot decode map value for field ${i.typeName}.${n.name} from JSON: ${Ph(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}break}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:a},a=`value`),n.kind){case`message`:let o=n.T;if(t===null&&o.typeName!=`google.protobuf.Value`)return;let s=e[a];Th(s)?s.fromJson(t,r):(e[a]=s=o.fromJson(t,r),o.fieldWrapper&&!n.oneof&&(e[a]=o.fieldWrapper.unwrapField(s)));break;case`enum`:let c=Rh(n.T,t,r.ignoreUnknownFields,!1);switch(c){case jh:wh(n,e);break;case Mh:break;default:e[a]=c;break}break;case`scalar`:try{let r=Lh(n.T,t,n.L,!1);switch(r){case jh:wh(n,e);break;default:e[a]=r;break}}catch(e){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${Ph(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}break}}function Ih(e,t){if(e===F.BOOL)switch(t){case`true`:t=!0;break;case`false`:t=!1;break}return Lh(e,t,ah.BIGINT,!0).toString()}function Lh(e,t,n,r){if(t===null)return r?sh(e,n):jh;switch(e){case F.DOUBLE:case F.FLOAT:if(t===`NaN`)return NaN;if(t===`Infinity`)return 1/0;if(t===`-Infinity`)return-1/0;if(t===``||typeof t==`string`&&t.trim().length!==t.length||typeof t!=`string`&&typeof t!=`number`)break;let r=Number(t);if(Number.isNaN(r)||!Number.isFinite(r))break;return e==F.FLOAT&&Im(r),r;case F.INT32:case F.FIXED32:case F.SFIXED32:case F.SINT32:case F.UINT32:let i;if(typeof t==`number`?i=t:typeof t==`string`&&t.length>0&&t.trim().length===t.length&&(i=Number(t)),i===void 0)break;return e==F.UINT32||e==F.FIXED32?Fm(i):Pm(i),i;case F.INT64:case F.SFIXED64:case F.SINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let a=ih.parse(t);return n?a.toString():a;case F.FIXED64:case F.UINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let o=ih.uParse(t);return n?o.toString():o;case F.BOOL:if(typeof t!=`boolean`)break;return t;case F.STRING:if(typeof t!=`string`)break;return t;case F.BYTES:if(t===``)return new Uint8Array;if(typeof t!=`string`)break;return vh.dec(t)}throw Error()}function Rh(e,t,n,r){if(t===null)return e.typeName==`google.protobuf.NullValue`?0:r?e.values[0].no:jh;switch(typeof t){case`number`:if(Number.isInteger(t))return t;break;case`string`:let r=e.findName(t);if(r!==void 0)return r.no;if(n)return Mh;break}throw Error(`cannot decode enum ${e.typeName} from JSON: ${Ph(t)}`)}function zh(e){return e.repeated||e.kind==`map`?!0:!(e.oneof||e.kind==`message`||e.opt||e.req)}function Bh(e,t,n){if(e.kind==`map`){Om(typeof t==`object`&&!!t);let r={},i=Object.entries(t);switch(e.V.kind){case`scalar`:for(let[t,n]of i)r[t.toString()]=Hh(e.V.T,n);break;case`message`:for(let[e,t]of i)r[e.toString()]=t.toJson(n);break;case`enum`:let t=e.V.T;for(let[e,a]of i)r[e.toString()]=Vh(t,a,n.enumAsInteger);break}return n.emitDefaultValues||i.length>0?r:void 0}if(e.repeated){Om(Array.isArray(t));let r=[];switch(e.kind){case`scalar`:for(let n=0;n<t.length;n++)r.push(Hh(e.T,t[n]));break;case`enum`:for(let i=0;i<t.length;i++)r.push(Vh(e.T,t[i],n.enumAsInteger));break;case`message`:for(let e=0;e<t.length;e++)r.push(t[e].toJson(n));break}return n.emitDefaultValues||r.length>0?r:void 0}switch(e.kind){case`scalar`:return Hh(e.T,t);case`enum`:return Vh(e.T,t,n.enumAsInteger);case`message`:return Eh(e.T,t).toJson(n)}}function Vh(e,t,n){return Om(typeof t==`number`),e.typeName==`google.protobuf.NullValue`?null:n?t:e.findNumber(t)?.name??t}function Hh(e,t){switch(e){case F.INT32:case F.SFIXED32:case F.SINT32:case F.FIXED32:case F.UINT32:return Om(typeof t==`number`),t;case F.FLOAT:case F.DOUBLE:return Om(typeof t==`number`),Number.isNaN(t)?`NaN`:t===1/0?`Infinity`:t===-1/0?`-Infinity`:t;case F.STRING:return Om(typeof t==`string`),t;case F.BOOL:return Om(typeof t==`boolean`),t;case F.UINT64:case F.FIXED64:case F.INT64:case F.SFIXED64:case F.SINT64:return Om(typeof t==`bigint`||typeof t==`string`||typeof t==`number`),t.toString();case F.BYTES:return Om(t instanceof Uint8Array),vh.enc(t)}}var Uh=Symbol(`@bufbuild/protobuf/unknown-fields`),Wh={readUnknownFields:!0,readerFactory:e=>new dh(e)},Gh={writeUnknownFields:!0,writerFactory:()=>new uh};function Kh(e){return e?Object.assign(Object.assign({},Wh),e):Wh}function qh(e){return e?Object.assign(Object.assign({},Gh),e):Gh}function Jh(){return{makeReadOptions:Kh,makeWriteOptions:qh,listUnknownFields(e){return e[Uh]??[]},discardUnknownFields(e){delete e[Uh]},writeUnknownFields(e,t){let n=e[Uh];if(n)for(let e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,r){let i=e;Array.isArray(i[Uh])||(i[Uh]=[]),i[Uh].push({no:t,wireType:n,data:r})},readMessage(e,t,n,r,i){let a=e.getType(),o=i?t.len:t.pos+n,s,c;for(;t.pos<o&&([s,c]=t.tag(),!(i===!0&&c==lh.EndGroup));){let n=a.fields.find(s);if(!n){let n=t.skip(c,s);r.readUnknownFields&&this.onUnknownField(e,s,c,n);continue}Yh(e,t,n,c,r)}if(i&&(c!=lh.EndGroup||s!==n))throw Error(`invalid end group tag`)},readField:Yh,writeMessage(e,t,n){let r=e.getType();for(let i of r.fields.byNumber()){if(!Ch(i,e)){if(i.req)throw Error(`cannot encode field ${r.typeName}.${i.name} to binary: required field not set`);continue}eg(i,i.oneof?e[i.oneof.localName].value:e[i.localName],t,n)}return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,r){t!==void 0&&eg(e,t,n,r)}}}function Yh(e,t,n,r,i){let{repeated:a,localName:o}=n;switch(n.oneof&&(e=e[n.oneof.localName],e.case!=o&&delete e.value,e.case=o,o=`value`),n.kind){case`scalar`:case`enum`:let s=n.kind==`enum`?F.INT32:n.T,c=$h;if(n.kind==`scalar`&&n.L>0&&(c=Qh),a){let n=e[o];if(r==lh.LengthDelimited&&s!=F.STRING&&s!=F.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,s))}else n.push(c(t,s))}else e[o]=c(t,s);break;case`message`:let l=n.T;a?e[o].push(Xh(t,new l,i,n)):Th(e[o])?Xh(t,e[o],i,n):(e[o]=Xh(t,new l,i,n),l.fieldWrapper&&!n.oneof&&!n.repeated&&(e[o]=l.fieldWrapper.unwrapField(e[o])));break;case`map`:let[u,d]=Zh(n,t,i);e[o][u]=d;break}}function Xh(e,t,n,r){let i=t.getType().runtime.bin,a=r?.delimited;return i.readMessage(t,e,a?r.no:e.uint32(),n,a),t}function Zh(e,t,n){let r=t.uint32(),i=t.pos+r,a,o;for(;t.pos<i;){let[r]=t.tag();switch(r){case 1:a=$h(t,e.K);break;case 2:switch(e.V.kind){case`scalar`:o=$h(t,e.V.T);break;case`enum`:o=t.int32();break;case`message`:o=Xh(t,new e.V.T,n,void 0);break}break}}if(a===void 0&&(a=sh(e.K,ah.BIGINT)),typeof a!=`string`&&typeof a!=`number`&&(a=a.toString()),o===void 0)switch(e.V.kind){case`scalar`:o=sh(e.V.T,ah.BIGINT);break;case`enum`:o=e.V.T.values[0].no;break;case`message`:o=new e.V.T;break}return[a,o]}function Qh(e,t){let n=$h(e,t);return typeof n==`bigint`?n.toString():n}function $h(e,t){switch(t){case F.STRING:return e.string();case F.BOOL:return e.bool();case F.DOUBLE:return e.double();case F.FLOAT:return e.float();case F.INT32:return e.int32();case F.INT64:return e.int64();case F.UINT64:return e.uint64();case F.FIXED64:return e.fixed64();case F.BYTES:return e.bytes();case F.FIXED32:return e.fixed32();case F.SFIXED32:return e.sfixed32();case F.SFIXED64:return e.sfixed64();case F.SINT64:return e.sint64();case F.UINT32:return e.uint32();case F.SINT32:return e.sint32()}}function eg(e,t,n,r){Om(t!==void 0);let i=e.repeated;switch(e.kind){case`scalar`:case`enum`:let a=e.kind==`enum`?F.INT32:e.T;if(i)if(Om(Array.isArray(t)),e.packed)ig(n,a,e.no,t);else for(let r of t)rg(n,a,e.no,r);else rg(n,a,e.no,t);break;case`message`:if(i){Om(Array.isArray(t));for(let i of t)ng(n,r,e,i)}else ng(n,r,e,t);break;case`map`:Om(typeof t==`object`&&!!t);for(let[i,a]of Object.entries(t))tg(n,r,e,i,a);break}}function tg(e,t,n,r,i){e.tag(n.no,lh.LengthDelimited),e.fork();let a=r;switch(n.K){case F.INT32:case F.FIXED32:case F.UINT32:case F.SFIXED32:case F.SINT32:a=Number.parseInt(r);break;case F.BOOL:Om(r==`true`||r==`false`),a=r==`true`;break}switch(rg(e,n.K,1,a),n.V.kind){case`scalar`:rg(e,n.V.T,2,i);break;case`enum`:rg(e,F.INT32,2,i);break;case`message`:Om(i!==void 0),e.tag(2,lh.LengthDelimited).bytes(i.toBinary(t));break}e.join()}function ng(e,t,n,r){let i=Eh(n.T,r);n.delimited?e.tag(n.no,lh.StartGroup).raw(i.toBinary(t)).tag(n.no,lh.EndGroup):e.tag(n.no,lh.LengthDelimited).bytes(i.toBinary(t))}function rg(e,t,n,r){Om(r!==void 0);let[i,a]=ag(t);e.tag(n,i)[a](r)}function ig(e,t,n,r){if(!r.length)return;e.tag(n,lh.LengthDelimited).fork();let[,i]=ag(t);for(let t=0;t<r.length;t++)e[i](r[t]);e.join()}function ag(e){let t=lh.Varint;switch(e){case F.BYTES:case F.STRING:t=lh.LengthDelimited;break;case F.DOUBLE:case F.FIXED64:case F.SFIXED64:t=lh.Bit64;break;case F.FIXED32:case F.SFIXED32:case F.FLOAT:t=lh.Bit32;break}let n=F[e].toLowerCase();return[t,n]}function og(){return{setEnumType:zm,initPartial(e,t){if(e===void 0)return;let n=t.getType();for(let r of n.fields.byMember()){let n=r.localName,i=t,a=e;if(a[n]!=null)switch(r.kind){case`oneof`:let e=a[n].case;if(e===void 0)continue;let t=r.findField(e),o=a[n].value;t&&t.kind==`message`&&!Th(o,t.T)?o=new t.T(o):t&&t.kind===`scalar`&&t.T===F.BYTES&&(o=cg(o)),i[n]={case:e,value:o};break;case`scalar`:case`enum`:let s=a[n];r.T===F.BYTES&&(s=r.repeated?s.map(cg):cg(s)),i[n]=s;break;case`map`:switch(r.V.kind){case`scalar`:case`enum`:if(r.V.T===F.BYTES)for(let[e,t]of Object.entries(a[n]))i[n][e]=cg(t);else Object.assign(i[n],a[n]);break;case`message`:let e=r.V.T;for(let t of Object.keys(a[n])){let r=a[n][t];e.fieldWrapper||(r=new e(r)),i[n][t]=r}break}break;case`message`:let c=r.T;if(r.repeated)i[n]=a[n].map(e=>Th(e,c)?e:new c(e));else{let e=a[n];c.fieldWrapper?c.typeName===`google.protobuf.BytesValue`?i[n]=cg(e):i[n]=e:i[n]=Th(e,c)?e:new c(e)}break}}},equals(e,t,n){return t===n?!0:!t||!n?!1:e.fields.byMember().every(e=>{let r=t[e.localName],i=n[e.localName];if(e.repeated){if(r.length!==i.length)return!1;switch(e.kind){case`message`:return r.every((t,n)=>e.T.equals(t,i[n]));case`scalar`:return r.every((t,n)=>oh(e.T,t,i[n]));case`enum`:return r.every((e,t)=>oh(F.INT32,e,i[t]))}throw Error(`repeated cannot contain ${e.kind}`)}switch(e.kind){case`message`:let t=r,n=i;return e.T.fieldWrapper&&(t!==void 0&&!Th(t)&&(t=e.T.fieldWrapper.wrapField(t)),n!==void 0&&!Th(n)&&(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case`enum`:return oh(F.INT32,r,i);case`scalar`:return oh(e.T,r,i);case`oneof`:if(r.case!==i.case)return!1;let a=e.findField(r.case);if(a===void 0)return!0;switch(a.kind){case`message`:return a.T.equals(r.value,i.value);case`enum`:return oh(F.INT32,r.value,i.value);case`scalar`:return oh(a.T,r.value,i.value)}throw Error(`oneof cannot contain ${a.kind}`);case`map`:let o=Object.keys(r).concat(Object.keys(i));switch(e.V.kind){case`message`:let t=e.V.T;return o.every(e=>t.equals(r[e],i[e]));case`enum`:return o.every(e=>oh(F.INT32,r[e],i[e]));case`scalar`:let n=e.V.T;return o.every(e=>oh(n,r[e],i[e]))}break}})},clone(e){let t=e.getType(),n=new t,r=n;for(let n of t.fields.byMember()){let t=e[n.localName],i;if(n.repeated)i=t.map(sg);else if(n.kind==`map`){i=r[n.localName];for(let[e,n]of Object.entries(t))i[e]=sg(n)}else i=n.kind==`oneof`?n.findField(t.case)?{case:t.case,value:sg(t.value)}:{case:void 0}:sg(t);r[n.localName]=i}for(let n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(r,n.no,n.wireType,n.data);return n}}}function sg(e){if(e===void 0)return e;if(Th(e))return e.clone();if(e instanceof Uint8Array){let t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function cg(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function lg(e,t,n){return{syntax:e,json:Nh(),bin:Jh(),util:Object.assign(Object.assign({},og()),{newFieldList:t,initFields:n}),makeMessageType(e,t,n){return Wm(this,e,t,n)},makeEnum:Vm,makeEnumType:Bm,getEnumType:Rm,makeExtension(e,t,n){return fh(this,e,t,n)}}}var ug=class{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){let e={};for(let t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){let e={};for(let t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||=this._normalizer(this._fields),this.all}byNumber(){return this.numbersAsc||=this.list().concat().sort((e,t)=>e.no-t.no),this.numbersAsc}byMember(){if(!this.members){this.members=[];let e=this.members,t;for(let n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}};function dg(e,t){let n=mg(e);return t?n:yg(vg(n))}function fg(e){return dg(e,!1)}var pg=mg;function mg(e){let t=!1,n=[];for(let r=0;r<e.length;r++){let i=e.charAt(r);switch(i){case`_`:t=!0;break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n.push(i),t=!1;break;default:t&&(t=!1,i=i.toUpperCase()),n.push(i);break}}return n.join(``)}var hg=new Set([`constructor`,`toString`,`toJSON`,`valueOf`]),gg=new Set([`getType`,`clone`,`equals`,`fromBinary`,`fromJson`,`fromJsonString`,`toBinary`,`toJson`,`toJsonString`,`toObject`]),_g=e=>`${e}\$`,vg=e=>gg.has(e)?_g(e):e,yg=e=>hg.has(e)?_g(e):e,bg=class{constructor(e){this.kind=`oneof`,this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=fg(e)}addField(e){Om(e.oneof===this,`field ${e.name} not one of ${this.name}`),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}};function xg(e,t){let n=[],r;for(let t of typeof e==`function`?e():e){let e=t;if(e.localName=dg(t.name,t.oneof!==void 0),e.jsonName=t.jsonName??pg(t.name),e.repeated=t.repeated??!1,t.kind==`scalar`&&(e.L=t.L??ah.BIGINT),e.delimited=t.delimited??!1,e.req=t.req??!1,e.opt=t.opt??!1,t.packed===void 0&&(e.packed=t.kind==`enum`||t.kind==`scalar`&&t.T!=F.BYTES&&t.T!=F.STRING),t.oneof!==void 0){let n=typeof t.oneof==`string`?t.oneof:t.oneof.name;(!r||r.name!=n)&&(r=new bg(n)),e.oneof=r,r.addField(e)}n.push(e)}return n}var I=lg(`proto3`,e=>new ug(e,e=>xg(e)),e=>{for(let t of e.getType().fields.byMember()){if(t.opt)continue;let n=t.localName,r=e;if(t.repeated){r[n]=[];continue}switch(t.kind){case`oneof`:r[n]={case:void 0};break;case`enum`:r[n]=0;break;case`map`:r[n]={};break;case`scalar`:r[n]=sh(t.T,t.L);break}}}),Sg=class e extends Um{constructor(e){super(),this.seconds=ih.zero,this.nanos=0,I.util.initPartial(e,this)}fromJson(e,t){if(typeof e!=`string`)throw Error(`cannot decode google.protobuf.Timestamp from JSON: ${I.json.debug(e)}`);let n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw Error(`cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string`);let r=Date.parse(n[1]+`-`+n[2]+`-`+n[3]+`T`+n[4]+`:`+n[5]+`:`+n[6]+(n[8]?n[8]:`Z`));if(Number.isNaN(r))throw Error(`cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string`);if(r<Date.parse(`0001-01-01T00:00:00Z`)||r>Date.parse(`9999-12-31T23:59:59Z`))throw Error(`cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);return this.seconds=ih.parse(r/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt(`1`+n[7]+`0`.repeat(9-n[7].length))-1e9),this}toJson(e){let t=Number(this.seconds)*1e3;if(t<Date.parse(`0001-01-01T00:00:00Z`)||t>Date.parse(`9999-12-31T23:59:59Z`))throw Error(`cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);if(this.nanos<0)throw Error(`cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative`);let n=`Z`;if(this.nanos>0){let e=(this.nanos+1e9).toString().substring(1);n=e.substring(3)===`000000`?`.`+e.substring(0,3)+`Z`:e.substring(6)===`000`?`.`+e.substring(0,6)+`Z`:`.`+e+`Z`}return new Date(t).toISOString().replace(`.000Z`,n)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return e.fromDate(new Date)}static fromDate(t){let n=t.getTime();return new e({seconds:ih.parse(Math.floor(n/1e3)),nanos:n%1e3*1e6})}static fromBinary(t,n){return new e().fromBinary(t,n)}static fromJson(t,n){return new e().fromJson(t,n)}static fromJsonString(t,n){return new e().fromJsonString(t,n)}static equals(t,n){return I.util.equals(e,t,n)}};Sg.runtime=I,Sg.typeName=`google.protobuf.Timestamp`,Sg.fields=I.util.newFieldList(()=>[{no:1,name:`seconds`,kind:`scalar`,T:3},{no:2,name:`nanos`,kind:`scalar`,T:5}]);var Cg=I.makeMessageType(`livekit.MetricsBatch`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:Sg},{no:3,name:`str_data`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`time_series`,kind:`message`,T:wg,repeated:!0},{no:5,name:`events`,kind:`message`,T:Eg,repeated:!0}]),wg=I.makeMessageType(`livekit.TimeSeriesMetric`,()=>[{no:1,name:`label`,kind:`scalar`,T:13},{no:2,name:`participant_identity`,kind:`scalar`,T:13},{no:3,name:`track_sid`,kind:`scalar`,T:13},{no:4,name:`samples`,kind:`message`,T:Tg,repeated:!0},{no:5,name:`rid`,kind:`scalar`,T:13}]),Tg=I.makeMessageType(`livekit.MetricSample`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:Sg},{no:3,name:`value`,kind:`scalar`,T:2}]),Eg=I.makeMessageType(`livekit.EventMetric`,()=>[{no:1,name:`label`,kind:`scalar`,T:13},{no:2,name:`participant_identity`,kind:`scalar`,T:13},{no:3,name:`track_sid`,kind:`scalar`,T:13},{no:4,name:`start_timestamp_ms`,kind:`scalar`,T:3},{no:5,name:`end_timestamp_ms`,kind:`scalar`,T:3,opt:!0},{no:6,name:`normalized_start_timestamp`,kind:`message`,T:Sg},{no:7,name:`normalized_end_timestamp`,kind:`message`,T:Sg,opt:!0},{no:8,name:`metadata`,kind:`scalar`,T:9},{no:9,name:`rid`,kind:`scalar`,T:13}]),Dg=I.makeEnum(`livekit.BackupCodecPolicy`,[{no:0,name:`PREFER_REGRESSION`},{no:1,name:`SIMULCAST`},{no:2,name:`REGRESSION`}]),Og=I.makeEnum(`livekit.TrackType`,[{no:0,name:`AUDIO`},{no:1,name:`VIDEO`},{no:2,name:`DATA`}]),kg=I.makeEnum(`livekit.TrackSource`,[{no:0,name:`UNKNOWN`},{no:1,name:`CAMERA`},{no:2,name:`MICROPHONE`},{no:3,name:`SCREEN_SHARE`},{no:4,name:`SCREEN_SHARE_AUDIO`}]),Ag=I.makeEnum(`livekit.VideoQuality`,[{no:0,name:`LOW`},{no:1,name:`MEDIUM`},{no:2,name:`HIGH`},{no:3,name:`OFF`}]),jg=I.makeEnum(`livekit.ConnectionQuality`,[{no:0,name:`POOR`},{no:1,name:`GOOD`},{no:2,name:`EXCELLENT`},{no:3,name:`LOST`}]),Mg=I.makeEnum(`livekit.ClientConfigSetting`,[{no:0,name:`UNSET`},{no:1,name:`DISABLED`},{no:2,name:`ENABLED`}]),Ng=I.makeEnum(`livekit.DisconnectReason`,[{no:0,name:`UNKNOWN_REASON`},{no:1,name:`CLIENT_INITIATED`},{no:2,name:`DUPLICATE_IDENTITY`},{no:3,name:`SERVER_SHUTDOWN`},{no:4,name:`PARTICIPANT_REMOVED`},{no:5,name:`ROOM_DELETED`},{no:6,name:`STATE_MISMATCH`},{no:7,name:`JOIN_FAILURE`},{no:8,name:`MIGRATION`},{no:9,name:`SIGNAL_CLOSE`},{no:10,name:`ROOM_CLOSED`},{no:11,name:`USER_UNAVAILABLE`},{no:12,name:`USER_REJECTED`},{no:13,name:`SIP_TRUNK_FAILURE`},{no:14,name:`CONNECTION_TIMEOUT`},{no:15,name:`MEDIA_FAILURE`}]),Pg=I.makeEnum(`livekit.ReconnectReason`,[{no:0,name:`RR_UNKNOWN`},{no:1,name:`RR_SIGNAL_DISCONNECTED`},{no:2,name:`RR_PUBLISHER_FAILED`},{no:3,name:`RR_SUBSCRIBER_FAILED`},{no:4,name:`RR_SWITCH_CANDIDATE`}]),Fg=I.makeEnum(`livekit.SubscriptionError`,[{no:0,name:`SE_UNKNOWN`},{no:1,name:`SE_CODEC_UNSUPPORTED`},{no:2,name:`SE_TRACK_NOTFOUND`}]),Ig=I.makeEnum(`livekit.AudioTrackFeature`,[{no:0,name:`TF_STEREO`},{no:1,name:`TF_NO_DTX`},{no:2,name:`TF_AUTO_GAIN_CONTROL`},{no:3,name:`TF_ECHO_CANCELLATION`},{no:4,name:`TF_NOISE_SUPPRESSION`},{no:5,name:`TF_ENHANCED_NOISE_CANCELLATION`},{no:6,name:`TF_PRECONNECT_BUFFER`}]),Lg=I.makeMessageType(`livekit.Room`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`empty_timeout`,kind:`scalar`,T:13},{no:14,name:`departure_timeout`,kind:`scalar`,T:13},{no:4,name:`max_participants`,kind:`scalar`,T:13},{no:5,name:`creation_time`,kind:`scalar`,T:3},{no:15,name:`creation_time_ms`,kind:`scalar`,T:3},{no:6,name:`turn_password`,kind:`scalar`,T:9},{no:7,name:`enabled_codecs`,kind:`message`,T:Rg,repeated:!0},{no:8,name:`metadata`,kind:`scalar`,T:9},{no:9,name:`num_participants`,kind:`scalar`,T:13},{no:11,name:`num_publishers`,kind:`scalar`,T:13},{no:10,name:`active_recording`,kind:`scalar`,T:8},{no:13,name:`version`,kind:`message`,T:y_}]),Rg=I.makeMessageType(`livekit.Codec`,()=>[{no:1,name:`mime`,kind:`scalar`,T:9},{no:2,name:`fmtp_line`,kind:`scalar`,T:9}]),zg=I.makeMessageType(`livekit.ParticipantPermission`,()=>[{no:1,name:`can_subscribe`,kind:`scalar`,T:8},{no:2,name:`can_publish`,kind:`scalar`,T:8},{no:3,name:`can_publish_data`,kind:`scalar`,T:8},{no:9,name:`can_publish_sources`,kind:`enum`,T:I.getEnumType(kg),repeated:!0},{no:7,name:`hidden`,kind:`scalar`,T:8},{no:8,name:`recorder`,kind:`scalar`,T:8},{no:10,name:`can_update_metadata`,kind:`scalar`,T:8},{no:11,name:`agent`,kind:`scalar`,T:8},{no:12,name:`can_subscribe_metrics`,kind:`scalar`,T:8}]),Bg=I.makeMessageType(`livekit.ParticipantInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`identity`,kind:`scalar`,T:9},{no:3,name:`state`,kind:`enum`,T:I.getEnumType(Vg)},{no:4,name:`tracks`,kind:`message`,T:Gg,repeated:!0},{no:5,name:`metadata`,kind:`scalar`,T:9},{no:6,name:`joined_at`,kind:`scalar`,T:3},{no:17,name:`joined_at_ms`,kind:`scalar`,T:3},{no:9,name:`name`,kind:`scalar`,T:9},{no:10,name:`version`,kind:`scalar`,T:13},{no:11,name:`permission`,kind:`message`,T:zg},{no:12,name:`region`,kind:`scalar`,T:9},{no:13,name:`is_publisher`,kind:`scalar`,T:8},{no:14,name:`kind`,kind:`enum`,T:I.getEnumType(Hg)},{no:15,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:16,name:`disconnect_reason`,kind:`enum`,T:I.getEnumType(Ng)},{no:18,name:`kind_details`,kind:`enum`,T:I.getEnumType(Ug),repeated:!0},{no:19,name:`data_tracks`,kind:`message`,T:Kg,repeated:!0}]),Vg=I.makeEnum(`livekit.ParticipantInfo.State`,[{no:0,name:`JOINING`},{no:1,name:`JOINED`},{no:2,name:`ACTIVE`},{no:3,name:`DISCONNECTED`}]),Hg=I.makeEnum(`livekit.ParticipantInfo.Kind`,[{no:0,name:`STANDARD`},{no:1,name:`INGRESS`},{no:2,name:`EGRESS`},{no:3,name:`SIP`},{no:4,name:`AGENT`},{no:7,name:`CONNECTOR`},{no:8,name:`BRIDGE`}]),Ug=I.makeEnum(`livekit.ParticipantInfo.KindDetail`,[{no:0,name:`CLOUD_AGENT`},{no:1,name:`FORWARDED`},{no:2,name:`CONNECTOR_WHATSAPP`},{no:3,name:`CONNECTOR_TWILIO`},{no:4,name:`BRIDGE_RTSP`}]),L=I.makeEnum(`livekit.Encryption.Type`,[{no:0,name:`NONE`},{no:1,name:`GCM`},{no:2,name:`CUSTOM`}]),Wg=I.makeMessageType(`livekit.SimulcastCodecInfo`,()=>[{no:1,name:`mime_type`,kind:`scalar`,T:9},{no:2,name:`mid`,kind:`scalar`,T:9},{no:3,name:`cid`,kind:`scalar`,T:9},{no:4,name:`layers`,kind:`message`,T:Jg,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:I.getEnumType(Yg)},{no:6,name:`sdp_cid`,kind:`scalar`,T:9}]),Gg=I.makeMessageType(`livekit.TrackInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`type`,kind:`enum`,T:I.getEnumType(Og)},{no:3,name:`name`,kind:`scalar`,T:9},{no:4,name:`muted`,kind:`scalar`,T:8},{no:5,name:`width`,kind:`scalar`,T:13},{no:6,name:`height`,kind:`scalar`,T:13},{no:7,name:`simulcast`,kind:`scalar`,T:8},{no:8,name:`disable_dtx`,kind:`scalar`,T:8},{no:9,name:`source`,kind:`enum`,T:I.getEnumType(kg)},{no:10,name:`layers`,kind:`message`,T:Jg,repeated:!0},{no:11,name:`mime_type`,kind:`scalar`,T:9},{no:12,name:`mid`,kind:`scalar`,T:9},{no:13,name:`codecs`,kind:`message`,T:Wg,repeated:!0},{no:14,name:`stereo`,kind:`scalar`,T:8},{no:15,name:`disable_red`,kind:`scalar`,T:8},{no:16,name:`encryption`,kind:`enum`,T:I.getEnumType(L)},{no:17,name:`stream`,kind:`scalar`,T:9},{no:18,name:`version`,kind:`message`,T:y_},{no:19,name:`audio_features`,kind:`enum`,T:I.getEnumType(Ig),repeated:!0},{no:20,name:`backup_codec_policy`,kind:`enum`,T:I.getEnumType(Dg)}]),Kg=I.makeMessageType(`livekit.DataTrackInfo`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13},{no:2,name:`sid`,kind:`scalar`,T:9},{no:3,name:`name`,kind:`scalar`,T:9},{no:4,name:`encryption`,kind:`enum`,T:I.getEnumType(L)}]),qg=I.makeMessageType(`livekit.DataTrackSubscriptionOptions`,()=>[{no:1,name:`target_fps`,kind:`scalar`,T:13,opt:!0}]),Jg=I.makeMessageType(`livekit.VideoLayer`,()=>[{no:1,name:`quality`,kind:`enum`,T:I.getEnumType(Ag)},{no:2,name:`width`,kind:`scalar`,T:13},{no:3,name:`height`,kind:`scalar`,T:13},{no:4,name:`bitrate`,kind:`scalar`,T:13},{no:5,name:`ssrc`,kind:`scalar`,T:13},{no:6,name:`spatial_layer`,kind:`scalar`,T:5},{no:7,name:`rid`,kind:`scalar`,T:9},{no:8,name:`repair_ssrc`,kind:`scalar`,T:13}]),Yg=I.makeEnum(`livekit.VideoLayer.Mode`,[{no:0,name:`MODE_UNUSED`},{no:1,name:`ONE_SPATIAL_LAYER_PER_STREAM`},{no:2,name:`MULTIPLE_SPATIAL_LAYERS_PER_STREAM`},{no:3,name:`ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR`}]),Xg=I.makeMessageType(`livekit.DataPacket`,()=>[{no:1,name:`kind`,kind:`enum`,T:I.getEnumType(Zg)},{no:4,name:`participant_identity`,kind:`scalar`,T:9},{no:5,name:`destination_identities`,kind:`scalar`,T:9,repeated:!0},{no:2,name:`user`,kind:`message`,T:n_,oneof:`value`},{no:3,name:`speaker`,kind:`message`,T:e_,oneof:`value`},{no:6,name:`sip_dtmf`,kind:`message`,T:r_,oneof:`value`},{no:7,name:`transcription`,kind:`message`,T:i_,oneof:`value`},{no:8,name:`metrics`,kind:`message`,T:Cg,oneof:`value`},{no:9,name:`chat_message`,kind:`message`,T:o_,oneof:`value`},{no:10,name:`rpc_request`,kind:`message`,T:s_,oneof:`value`},{no:11,name:`rpc_ack`,kind:`message`,T:c_,oneof:`value`},{no:12,name:`rpc_response`,kind:`message`,T:l_,oneof:`value`},{no:13,name:`stream_header`,kind:`message`,T:C_,oneof:`value`},{no:14,name:`stream_chunk`,kind:`message`,T:w_,oneof:`value`},{no:15,name:`stream_trailer`,kind:`message`,T:T_,oneof:`value`},{no:18,name:`encrypted_packet`,kind:`message`,T:Qg,oneof:`value`},{no:16,name:`sequence`,kind:`scalar`,T:13},{no:17,name:`participant_sid`,kind:`scalar`,T:9}]),Zg=I.makeEnum(`livekit.DataPacket.Kind`,[{no:0,name:`RELIABLE`},{no:1,name:`LOSSY`}]),Qg=I.makeMessageType(`livekit.EncryptedPacket`,()=>[{no:1,name:`encryption_type`,kind:`enum`,T:I.getEnumType(L)},{no:2,name:`iv`,kind:`scalar`,T:12},{no:3,name:`key_index`,kind:`scalar`,T:13},{no:4,name:`encrypted_value`,kind:`scalar`,T:12}]),$g=I.makeMessageType(`livekit.EncryptedPacketPayload`,()=>[{no:1,name:`user`,kind:`message`,T:n_,oneof:`value`},{no:3,name:`chat_message`,kind:`message`,T:o_,oneof:`value`},{no:4,name:`rpc_request`,kind:`message`,T:s_,oneof:`value`},{no:5,name:`rpc_ack`,kind:`message`,T:c_,oneof:`value`},{no:6,name:`rpc_response`,kind:`message`,T:l_,oneof:`value`},{no:7,name:`stream_header`,kind:`message`,T:C_,oneof:`value`},{no:8,name:`stream_chunk`,kind:`message`,T:w_,oneof:`value`},{no:9,name:`stream_trailer`,kind:`message`,T:T_,oneof:`value`}]),e_=I.makeMessageType(`livekit.ActiveSpeakerUpdate`,()=>[{no:1,name:`speakers`,kind:`message`,T:t_,repeated:!0}]),t_=I.makeMessageType(`livekit.SpeakerInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`level`,kind:`scalar`,T:2},{no:3,name:`active`,kind:`scalar`,T:8}]),n_=I.makeMessageType(`livekit.UserPacket`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:5,name:`participant_identity`,kind:`scalar`,T:9},{no:2,name:`payload`,kind:`scalar`,T:12},{no:3,name:`destination_sids`,kind:`scalar`,T:9,repeated:!0},{no:6,name:`destination_identities`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`topic`,kind:`scalar`,T:9,opt:!0},{no:8,name:`id`,kind:`scalar`,T:9,opt:!0},{no:9,name:`start_time`,kind:`scalar`,T:4,opt:!0},{no:10,name:`end_time`,kind:`scalar`,T:4,opt:!0},{no:11,name:`nonce`,kind:`scalar`,T:12}]),r_=I.makeMessageType(`livekit.SipDTMF`,()=>[{no:3,name:`code`,kind:`scalar`,T:13},{no:4,name:`digit`,kind:`scalar`,T:9}]),i_=I.makeMessageType(`livekit.Transcription`,()=>[{no:2,name:`transcribed_participant_identity`,kind:`scalar`,T:9},{no:3,name:`track_id`,kind:`scalar`,T:9},{no:4,name:`segments`,kind:`message`,T:a_,repeated:!0}]),a_=I.makeMessageType(`livekit.TranscriptionSegment`,()=>[{no:1,name:`id`,kind:`scalar`,T:9},{no:2,name:`text`,kind:`scalar`,T:9},{no:3,name:`start_time`,kind:`scalar`,T:4},{no:4,name:`end_time`,kind:`scalar`,T:4},{no:5,name:`final`,kind:`scalar`,T:8},{no:6,name:`language`,kind:`scalar`,T:9}]),o_=I.makeMessageType(`livekit.ChatMessage`,()=>[{no:1,name:`id`,kind:`scalar`,T:9},{no:2,name:`timestamp`,kind:`scalar`,T:3},{no:3,name:`edit_timestamp`,kind:`scalar`,T:3,opt:!0},{no:4,name:`message`,kind:`scalar`,T:9},{no:5,name:`deleted`,kind:`scalar`,T:8},{no:6,name:`generated`,kind:`scalar`,T:8}]),s_=I.makeMessageType(`livekit.RpcRequest`,()=>[{no:1,name:`id`,kind:`scalar`,T:9},{no:2,name:`method`,kind:`scalar`,T:9},{no:3,name:`payload`,kind:`scalar`,T:9},{no:4,name:`response_timeout_ms`,kind:`scalar`,T:13},{no:5,name:`version`,kind:`scalar`,T:13}]),c_=I.makeMessageType(`livekit.RpcAck`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:9}]),l_=I.makeMessageType(`livekit.RpcResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:9},{no:2,name:`payload`,kind:`scalar`,T:9,oneof:`value`},{no:3,name:`error`,kind:`message`,T:u_,oneof:`value`}]),u_=I.makeMessageType(`livekit.RpcError`,()=>[{no:1,name:`code`,kind:`scalar`,T:13},{no:2,name:`message`,kind:`scalar`,T:9},{no:3,name:`data`,kind:`scalar`,T:9}]),d_=I.makeMessageType(`livekit.ParticipantTracks`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sids`,kind:`scalar`,T:9,repeated:!0}]),f_=I.makeMessageType(`livekit.ServerInfo`,()=>[{no:1,name:`edition`,kind:`enum`,T:I.getEnumType(p_)},{no:2,name:`version`,kind:`scalar`,T:9},{no:3,name:`protocol`,kind:`scalar`,T:5},{no:4,name:`region`,kind:`scalar`,T:9},{no:5,name:`node_id`,kind:`scalar`,T:9},{no:6,name:`debug_info`,kind:`scalar`,T:9},{no:7,name:`agent_protocol`,kind:`scalar`,T:5}]),p_=I.makeEnum(`livekit.ServerInfo.Edition`,[{no:0,name:`Standard`},{no:1,name:`Cloud`}]),m_=I.makeMessageType(`livekit.ClientInfo`,()=>[{no:1,name:`sdk`,kind:`enum`,T:I.getEnumType(h_)},{no:2,name:`version`,kind:`scalar`,T:9},{no:3,name:`protocol`,kind:`scalar`,T:5},{no:4,name:`os`,kind:`scalar`,T:9},{no:5,name:`os_version`,kind:`scalar`,T:9},{no:6,name:`device_model`,kind:`scalar`,T:9},{no:7,name:`browser`,kind:`scalar`,T:9},{no:8,name:`browser_version`,kind:`scalar`,T:9},{no:9,name:`address`,kind:`scalar`,T:9},{no:10,name:`network`,kind:`scalar`,T:9},{no:11,name:`other_sdks`,kind:`scalar`,T:9}]),h_=I.makeEnum(`livekit.ClientInfo.SDK`,[{no:0,name:`UNKNOWN`},{no:1,name:`JS`},{no:2,name:`SWIFT`},{no:3,name:`ANDROID`},{no:4,name:`FLUTTER`},{no:5,name:`GO`},{no:6,name:`UNITY`},{no:7,name:`REACT_NATIVE`},{no:8,name:`RUST`},{no:9,name:`PYTHON`},{no:10,name:`CPP`},{no:11,name:`UNITY_WEB`},{no:12,name:`NODE`},{no:13,name:`UNREAL`},{no:14,name:`ESP32`}]),g_=I.makeMessageType(`livekit.ClientConfiguration`,()=>[{no:1,name:`video`,kind:`message`,T:__},{no:2,name:`screen`,kind:`message`,T:__},{no:3,name:`resume_connection`,kind:`enum`,T:I.getEnumType(Mg)},{no:4,name:`disabled_codecs`,kind:`message`,T:v_},{no:5,name:`force_relay`,kind:`enum`,T:I.getEnumType(Mg)}]),__=I.makeMessageType(`livekit.VideoConfiguration`,()=>[{no:1,name:`hardware_encoder`,kind:`enum`,T:I.getEnumType(Mg)}]),v_=I.makeMessageType(`livekit.DisabledCodecs`,()=>[{no:1,name:`codecs`,kind:`message`,T:Rg,repeated:!0},{no:2,name:`publish`,kind:`message`,T:Rg,repeated:!0}]),y_=I.makeMessageType(`livekit.TimedVersion`,()=>[{no:1,name:`unix_micro`,kind:`scalar`,T:3},{no:2,name:`ticks`,kind:`scalar`,T:5}]),b_=I.makeEnum(`livekit.DataStream.OperationType`,[{no:0,name:`CREATE`},{no:1,name:`UPDATE`},{no:2,name:`DELETE`},{no:3,name:`REACTION`}]),x_=I.makeMessageType(`livekit.DataStream.TextHeader`,()=>[{no:1,name:`operation_type`,kind:`enum`,T:I.getEnumType(b_)},{no:2,name:`version`,kind:`scalar`,T:5},{no:3,name:`reply_to_stream_id`,kind:`scalar`,T:9},{no:4,name:`attached_stream_ids`,kind:`scalar`,T:9,repeated:!0},{no:5,name:`generated`,kind:`scalar`,T:8}],{localName:`DataStream_TextHeader`}),S_=I.makeMessageType(`livekit.DataStream.ByteHeader`,()=>[{no:1,name:`name`,kind:`scalar`,T:9}],{localName:`DataStream_ByteHeader`}),C_=I.makeMessageType(`livekit.DataStream.Header`,()=>[{no:1,name:`stream_id`,kind:`scalar`,T:9},{no:2,name:`timestamp`,kind:`scalar`,T:3},{no:3,name:`topic`,kind:`scalar`,T:9},{no:4,name:`mime_type`,kind:`scalar`,T:9},{no:5,name:`total_length`,kind:`scalar`,T:4,opt:!0},{no:7,name:`encryption_type`,kind:`enum`,T:I.getEnumType(L)},{no:8,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:9,name:`text_header`,kind:`message`,T:x_,oneof:`content_header`},{no:10,name:`byte_header`,kind:`message`,T:S_,oneof:`content_header`}],{localName:`DataStream_Header`}),w_=I.makeMessageType(`livekit.DataStream.Chunk`,()=>[{no:1,name:`stream_id`,kind:`scalar`,T:9},{no:2,name:`chunk_index`,kind:`scalar`,T:4},{no:3,name:`content`,kind:`scalar`,T:12},{no:4,name:`version`,kind:`scalar`,T:5},{no:5,name:`iv`,kind:`scalar`,T:12,opt:!0}],{localName:`DataStream_Chunk`}),T_=I.makeMessageType(`livekit.DataStream.Trailer`,()=>[{no:1,name:`stream_id`,kind:`scalar`,T:9},{no:2,name:`reason`,kind:`scalar`,T:9},{no:3,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}}],{localName:`DataStream_Trailer`}),E_=I.makeMessageType(`livekit.SubscribedAudioCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`enabled`,kind:`scalar`,T:8}]),D_=I.makeEnum(`livekit.SignalTarget`,[{no:0,name:`PUBLISHER`},{no:1,name:`SUBSCRIBER`}]),O_=I.makeEnum(`livekit.StreamState`,[{no:0,name:`ACTIVE`},{no:1,name:`PAUSED`}]),k_=I.makeEnum(`livekit.CandidateProtocol`,[{no:0,name:`UDP`},{no:1,name:`TCP`},{no:2,name:`TLS`}]),A_=I.makeMessageType(`livekit.SignalRequest`,()=>[{no:1,name:`offer`,kind:`message`,T:K_,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:K_,oneof:`message`},{no:3,name:`trickle`,kind:`message`,T:B_,oneof:`message`},{no:4,name:`add_track`,kind:`message`,T:N_,oneof:`message`},{no:5,name:`mute`,kind:`message`,T:V_,oneof:`message`},{no:6,name:`subscription`,kind:`message`,T:J_,oneof:`message`},{no:7,name:`track_setting`,kind:`message`,T:Z_,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:ev,oneof:`message`},{no:10,name:`update_layers`,kind:`message`,T:nv,oneof:`message`},{no:11,name:`subscription_permission`,kind:`message`,T:gv,oneof:`message`},{no:12,name:`sync_state`,kind:`message`,T:yv,oneof:`message`},{no:13,name:`simulate`,kind:`message`,T:Sv,oneof:`message`},{no:14,name:`ping`,kind:`scalar`,T:3,oneof:`message`},{no:15,name:`update_metadata`,kind:`message`,T:rv,oneof:`message`},{no:16,name:`ping_req`,kind:`message`,T:Cv,oneof:`message`},{no:17,name:`update_audio_track`,kind:`message`,T:Q_,oneof:`message`},{no:18,name:`update_video_track`,kind:`message`,T:$_,oneof:`message`},{no:19,name:`publish_data_track_request`,kind:`message`,T:P_,oneof:`message`},{no:20,name:`unpublish_data_track_request`,kind:`message`,T:I_,oneof:`message`},{no:21,name:`update_data_subscription`,kind:`message`,T:Y_,oneof:`message`}]),j_=I.makeMessageType(`livekit.SignalResponse`,()=>[{no:1,name:`join`,kind:`message`,T:H_,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:K_,oneof:`message`},{no:3,name:`offer`,kind:`message`,T:K_,oneof:`message`},{no:4,name:`trickle`,kind:`message`,T:B_,oneof:`message`},{no:5,name:`update`,kind:`message`,T:q_,oneof:`message`},{no:6,name:`track_published`,kind:`message`,T:W_,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:ev,oneof:`message`},{no:9,name:`mute`,kind:`message`,T:V_,oneof:`message`},{no:10,name:`speakers_changed`,kind:`message`,T:av,oneof:`message`},{no:11,name:`room_update`,kind:`message`,T:ov,oneof:`message`},{no:12,name:`connection_quality`,kind:`message`,T:cv,oneof:`message`},{no:13,name:`stream_state_update`,kind:`message`,T:uv,oneof:`message`},{no:14,name:`subscribed_quality_update`,kind:`message`,T:pv,oneof:`message`},{no:15,name:`subscription_permission_update`,kind:`message`,T:_v,oneof:`message`},{no:16,name:`refresh_token`,kind:`scalar`,T:9,oneof:`message`},{no:17,name:`track_unpublished`,kind:`message`,T:G_,oneof:`message`},{no:18,name:`pong`,kind:`scalar`,T:3,oneof:`message`},{no:19,name:`reconnect`,kind:`message`,T:U_,oneof:`message`},{no:20,name:`pong_resp`,kind:`message`,T:wv,oneof:`message`},{no:21,name:`subscription_response`,kind:`message`,T:Dv,oneof:`message`},{no:22,name:`request_response`,kind:`message`,T:Ov,oneof:`message`},{no:23,name:`track_subscribed`,kind:`message`,T:Av,oneof:`message`},{no:24,name:`room_moved`,kind:`message`,T:vv,oneof:`message`},{no:25,name:`media_sections_requirement`,kind:`message`,T:Fv,oneof:`message`},{no:26,name:`subscribed_audio_codec_update`,kind:`message`,T:mv,oneof:`message`},{no:27,name:`publish_data_track_response`,kind:`message`,T:F_,oneof:`message`},{no:28,name:`unpublish_data_track_response`,kind:`message`,T:L_,oneof:`message`},{no:29,name:`data_track_subscriber_handles`,kind:`message`,T:R_,oneof:`message`}]),M_=I.makeMessageType(`livekit.SimulcastCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`cid`,kind:`scalar`,T:9},{no:4,name:`layers`,kind:`message`,T:Jg,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:I.getEnumType(Yg)}]),N_=I.makeMessageType(`livekit.AddTrackRequest`,()=>[{no:1,name:`cid`,kind:`scalar`,T:9},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`type`,kind:`enum`,T:I.getEnumType(Og)},{no:4,name:`width`,kind:`scalar`,T:13},{no:5,name:`height`,kind:`scalar`,T:13},{no:6,name:`muted`,kind:`scalar`,T:8},{no:7,name:`disable_dtx`,kind:`scalar`,T:8},{no:8,name:`source`,kind:`enum`,T:I.getEnumType(kg)},{no:9,name:`layers`,kind:`message`,T:Jg,repeated:!0},{no:10,name:`simulcast_codecs`,kind:`message`,T:M_,repeated:!0},{no:11,name:`sid`,kind:`scalar`,T:9},{no:12,name:`stereo`,kind:`scalar`,T:8},{no:13,name:`disable_red`,kind:`scalar`,T:8},{no:14,name:`encryption`,kind:`enum`,T:I.getEnumType(L)},{no:15,name:`stream`,kind:`scalar`,T:9},{no:16,name:`backup_codec_policy`,kind:`enum`,T:I.getEnumType(Dg)},{no:17,name:`audio_features`,kind:`enum`,T:I.getEnumType(Ig),repeated:!0}]),P_=I.makeMessageType(`livekit.PublishDataTrackRequest`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`encryption`,kind:`enum`,T:I.getEnumType(L)}]),F_=I.makeMessageType(`livekit.PublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:Kg}]),I_=I.makeMessageType(`livekit.UnpublishDataTrackRequest`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13}]),L_=I.makeMessageType(`livekit.UnpublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:Kg}]),R_=I.makeMessageType(`livekit.DataTrackSubscriberHandles`,()=>[{no:1,name:`sub_handles`,kind:`map`,K:13,V:{kind:`message`,T:z_}}]),z_=I.makeMessageType(`livekit.DataTrackSubscriberHandles.PublishedDataTrack`,()=>[{no:1,name:`publisher_identity`,kind:`scalar`,T:9},{no:2,name:`publisher_sid`,kind:`scalar`,T:9},{no:3,name:`track_sid`,kind:`scalar`,T:9}],{localName:`DataTrackSubscriberHandles_PublishedDataTrack`}),B_=I.makeMessageType(`livekit.TrickleRequest`,()=>[{no:1,name:`candidateInit`,kind:`scalar`,T:9},{no:2,name:`target`,kind:`enum`,T:I.getEnumType(D_)},{no:3,name:`final`,kind:`scalar`,T:8}]),V_=I.makeMessageType(`livekit.MuteTrackRequest`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`muted`,kind:`scalar`,T:8}]),H_=I.makeMessageType(`livekit.JoinResponse`,()=>[{no:1,name:`room`,kind:`message`,T:Lg},{no:2,name:`participant`,kind:`message`,T:Bg},{no:3,name:`other_participants`,kind:`message`,T:Bg,repeated:!0},{no:4,name:`server_version`,kind:`scalar`,T:9},{no:5,name:`ice_servers`,kind:`message`,T:iv,repeated:!0},{no:6,name:`subscriber_primary`,kind:`scalar`,T:8},{no:7,name:`alternative_url`,kind:`scalar`,T:9},{no:8,name:`client_configuration`,kind:`message`,T:g_},{no:9,name:`server_region`,kind:`scalar`,T:9},{no:10,name:`ping_timeout`,kind:`scalar`,T:5},{no:11,name:`ping_interval`,kind:`scalar`,T:5},{no:12,name:`server_info`,kind:`message`,T:f_},{no:13,name:`sif_trailer`,kind:`scalar`,T:12},{no:14,name:`enabled_publish_codecs`,kind:`message`,T:Rg,repeated:!0},{no:15,name:`fast_publish`,kind:`scalar`,T:8}]),U_=I.makeMessageType(`livekit.ReconnectResponse`,()=>[{no:1,name:`ice_servers`,kind:`message`,T:iv,repeated:!0},{no:2,name:`client_configuration`,kind:`message`,T:g_},{no:3,name:`server_info`,kind:`message`,T:f_},{no:4,name:`last_message_seq`,kind:`scalar`,T:13}]),W_=I.makeMessageType(`livekit.TrackPublishedResponse`,()=>[{no:1,name:`cid`,kind:`scalar`,T:9},{no:2,name:`track`,kind:`message`,T:Gg}]),G_=I.makeMessageType(`livekit.TrackUnpublishedResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),K_=I.makeMessageType(`livekit.SessionDescription`,()=>[{no:1,name:`type`,kind:`scalar`,T:9},{no:2,name:`sdp`,kind:`scalar`,T:9},{no:3,name:`id`,kind:`scalar`,T:13},{no:4,name:`mid_to_track_id`,kind:`map`,K:9,V:{kind:`scalar`,T:9}}]),q_=I.makeMessageType(`livekit.ParticipantUpdate`,()=>[{no:1,name:`participants`,kind:`message`,T:Bg,repeated:!0}]),J_=I.makeMessageType(`livekit.UpdateSubscription`,()=>[{no:1,name:`track_sids`,kind:`scalar`,T:9,repeated:!0},{no:2,name:`subscribe`,kind:`scalar`,T:8},{no:3,name:`participant_tracks`,kind:`message`,T:d_,repeated:!0}]),Y_=I.makeMessageType(`livekit.UpdateDataSubscription`,()=>[{no:1,name:`updates`,kind:`message`,T:X_,repeated:!0}]),X_=I.makeMessageType(`livekit.UpdateDataSubscription.Update`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribe`,kind:`scalar`,T:8},{no:3,name:`options`,kind:`message`,T:qg}],{localName:`UpdateDataSubscription_Update`}),Z_=I.makeMessageType(`livekit.UpdateTrackSettings`,()=>[{no:1,name:`track_sids`,kind:`scalar`,T:9,repeated:!0},{no:3,name:`disabled`,kind:`scalar`,T:8},{no:4,name:`quality`,kind:`enum`,T:I.getEnumType(Ag)},{no:5,name:`width`,kind:`scalar`,T:13},{no:6,name:`height`,kind:`scalar`,T:13},{no:7,name:`fps`,kind:`scalar`,T:13},{no:8,name:`priority`,kind:`scalar`,T:13}]),Q_=I.makeMessageType(`livekit.UpdateLocalAudioTrack`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`features`,kind:`enum`,T:I.getEnumType(Ig),repeated:!0}]),$_=I.makeMessageType(`livekit.UpdateLocalVideoTrack`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`width`,kind:`scalar`,T:13},{no:3,name:`height`,kind:`scalar`,T:13}]),ev=I.makeMessageType(`livekit.LeaveRequest`,()=>[{no:1,name:`can_reconnect`,kind:`scalar`,T:8},{no:2,name:`reason`,kind:`enum`,T:I.getEnumType(Ng)},{no:3,name:`action`,kind:`enum`,T:I.getEnumType(tv)},{no:4,name:`regions`,kind:`message`,T:Tv}]),tv=I.makeEnum(`livekit.LeaveRequest.Action`,[{no:0,name:`DISCONNECT`},{no:1,name:`RESUME`},{no:2,name:`RECONNECT`}]),nv=I.makeMessageType(`livekit.UpdateVideoLayers`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`layers`,kind:`message`,T:Jg,repeated:!0}]),rv=I.makeMessageType(`livekit.UpdateParticipantMetadata`,()=>[{no:1,name:`metadata`,kind:`scalar`,T:9},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:4,name:`request_id`,kind:`scalar`,T:13}]),iv=I.makeMessageType(`livekit.ICEServer`,()=>[{no:1,name:`urls`,kind:`scalar`,T:9,repeated:!0},{no:2,name:`username`,kind:`scalar`,T:9},{no:3,name:`credential`,kind:`scalar`,T:9}]),av=I.makeMessageType(`livekit.SpeakersChanged`,()=>[{no:1,name:`speakers`,kind:`message`,T:t_,repeated:!0}]),ov=I.makeMessageType(`livekit.RoomUpdate`,()=>[{no:1,name:`room`,kind:`message`,T:Lg}]),sv=I.makeMessageType(`livekit.ConnectionQualityInfo`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`quality`,kind:`enum`,T:I.getEnumType(jg)},{no:3,name:`score`,kind:`scalar`,T:2}]),cv=I.makeMessageType(`livekit.ConnectionQualityUpdate`,()=>[{no:1,name:`updates`,kind:`message`,T:sv,repeated:!0}]),lv=I.makeMessageType(`livekit.StreamStateInfo`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sid`,kind:`scalar`,T:9},{no:3,name:`state`,kind:`enum`,T:I.getEnumType(O_)}]),uv=I.makeMessageType(`livekit.StreamStateUpdate`,()=>[{no:1,name:`stream_states`,kind:`message`,T:lv,repeated:!0}]),dv=I.makeMessageType(`livekit.SubscribedQuality`,()=>[{no:1,name:`quality`,kind:`enum`,T:I.getEnumType(Ag)},{no:2,name:`enabled`,kind:`scalar`,T:8}]),fv=I.makeMessageType(`livekit.SubscribedCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`qualities`,kind:`message`,T:dv,repeated:!0}]),pv=I.makeMessageType(`livekit.SubscribedQualityUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_qualities`,kind:`message`,T:dv,repeated:!0},{no:3,name:`subscribed_codecs`,kind:`message`,T:fv,repeated:!0}]),mv=I.makeMessageType(`livekit.SubscribedAudioCodecUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_audio_codecs`,kind:`message`,T:E_,repeated:!0}]),hv=I.makeMessageType(`livekit.TrackPermission`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`all_tracks`,kind:`scalar`,T:8},{no:3,name:`track_sids`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`participant_identity`,kind:`scalar`,T:9}]),gv=I.makeMessageType(`livekit.SubscriptionPermission`,()=>[{no:1,name:`all_participants`,kind:`scalar`,T:8},{no:2,name:`track_permissions`,kind:`message`,T:hv,repeated:!0}]),_v=I.makeMessageType(`livekit.SubscriptionPermissionUpdate`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sid`,kind:`scalar`,T:9},{no:3,name:`allowed`,kind:`scalar`,T:8}]),vv=I.makeMessageType(`livekit.RoomMovedResponse`,()=>[{no:1,name:`room`,kind:`message`,T:Lg},{no:2,name:`token`,kind:`scalar`,T:9},{no:3,name:`participant`,kind:`message`,T:Bg},{no:4,name:`other_participants`,kind:`message`,T:Bg,repeated:!0}]),yv=I.makeMessageType(`livekit.SyncState`,()=>[{no:1,name:`answer`,kind:`message`,T:K_},{no:2,name:`subscription`,kind:`message`,T:J_},{no:3,name:`publish_tracks`,kind:`message`,T:W_,repeated:!0},{no:4,name:`data_channels`,kind:`message`,T:xv,repeated:!0},{no:5,name:`offer`,kind:`message`,T:K_},{no:6,name:`track_sids_disabled`,kind:`scalar`,T:9,repeated:!0},{no:7,name:`datachannel_receive_states`,kind:`message`,T:bv,repeated:!0},{no:8,name:`publish_data_tracks`,kind:`message`,T:F_,repeated:!0}]),bv=I.makeMessageType(`livekit.DataChannelReceiveState`,()=>[{no:1,name:`publisher_sid`,kind:`scalar`,T:9},{no:2,name:`last_seq`,kind:`scalar`,T:13}]),xv=I.makeMessageType(`livekit.DataChannelInfo`,()=>[{no:1,name:`label`,kind:`scalar`,T:9},{no:2,name:`id`,kind:`scalar`,T:13},{no:3,name:`target`,kind:`enum`,T:I.getEnumType(D_)}]),Sv=I.makeMessageType(`livekit.SimulateScenario`,()=>[{no:1,name:`speaker_update`,kind:`scalar`,T:5,oneof:`scenario`},{no:2,name:`node_failure`,kind:`scalar`,T:8,oneof:`scenario`},{no:3,name:`migration`,kind:`scalar`,T:8,oneof:`scenario`},{no:4,name:`server_leave`,kind:`scalar`,T:8,oneof:`scenario`},{no:5,name:`switch_candidate_protocol`,kind:`enum`,T:I.getEnumType(k_),oneof:`scenario`},{no:6,name:`subscriber_bandwidth`,kind:`scalar`,T:3,oneof:`scenario`},{no:7,name:`disconnect_signal_on_resume`,kind:`scalar`,T:8,oneof:`scenario`},{no:8,name:`disconnect_signal_on_resume_no_messages`,kind:`scalar`,T:8,oneof:`scenario`},{no:9,name:`leave_request_full_reconnect`,kind:`scalar`,T:8,oneof:`scenario`}]),Cv=I.makeMessageType(`livekit.Ping`,()=>[{no:1,name:`timestamp`,kind:`scalar`,T:3},{no:2,name:`rtt`,kind:`scalar`,T:3}]),wv=I.makeMessageType(`livekit.Pong`,()=>[{no:1,name:`last_ping_timestamp`,kind:`scalar`,T:3},{no:2,name:`timestamp`,kind:`scalar`,T:3}]),Tv=I.makeMessageType(`livekit.RegionSettings`,()=>[{no:1,name:`regions`,kind:`message`,T:Ev,repeated:!0}]),Ev=I.makeMessageType(`livekit.RegionInfo`,()=>[{no:1,name:`region`,kind:`scalar`,T:9},{no:2,name:`url`,kind:`scalar`,T:9},{no:3,name:`distance`,kind:`scalar`,T:3}]),Dv=I.makeMessageType(`livekit.SubscriptionResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`err`,kind:`enum`,T:I.getEnumType(Fg)}]),Ov=I.makeMessageType(`livekit.RequestResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`reason`,kind:`enum`,T:I.getEnumType(kv)},{no:3,name:`message`,kind:`scalar`,T:9},{no:4,name:`trickle`,kind:`message`,T:B_,oneof:`request`},{no:5,name:`add_track`,kind:`message`,T:N_,oneof:`request`},{no:6,name:`mute`,kind:`message`,T:V_,oneof:`request`},{no:7,name:`update_metadata`,kind:`message`,T:rv,oneof:`request`},{no:8,name:`update_audio_track`,kind:`message`,T:Q_,oneof:`request`},{no:9,name:`update_video_track`,kind:`message`,T:$_,oneof:`request`},{no:10,name:`publish_data_track`,kind:`message`,T:P_,oneof:`request`},{no:11,name:`unpublish_data_track`,kind:`message`,T:I_,oneof:`request`}]),kv=I.makeEnum(`livekit.RequestResponse.Reason`,[{no:0,name:`OK`},{no:1,name:`NOT_FOUND`},{no:2,name:`NOT_ALLOWED`},{no:3,name:`LIMIT_EXCEEDED`},{no:4,name:`QUEUED`},{no:5,name:`UNSUPPORTED_TYPE`},{no:6,name:`UNCLASSIFIED_ERROR`},{no:7,name:`INVALID_HANDLE`},{no:8,name:`INVALID_NAME`},{no:9,name:`DUPLICATE_HANDLE`},{no:10,name:`DUPLICATE_NAME`}]),Av=I.makeMessageType(`livekit.TrackSubscribed`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),jv=I.makeMessageType(`livekit.ConnectionSettings`,()=>[{no:1,name:`auto_subscribe`,kind:`scalar`,T:8},{no:2,name:`adaptive_stream`,kind:`scalar`,T:8},{no:3,name:`subscriber_allow_pause`,kind:`scalar`,T:8,opt:!0},{no:4,name:`disable_ice_lite`,kind:`scalar`,T:8},{no:5,name:`auto_subscribe_data_track`,kind:`scalar`,T:8,opt:!0}]),Mv=I.makeMessageType(`livekit.JoinRequest`,()=>[{no:1,name:`client_info`,kind:`message`,T:m_},{no:2,name:`connection_settings`,kind:`message`,T:jv},{no:3,name:`metadata`,kind:`scalar`,T:9},{no:4,name:`participant_attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:5,name:`add_track_requests`,kind:`message`,T:N_,repeated:!0},{no:6,name:`publisher_offer`,kind:`message`,T:K_},{no:7,name:`reconnect`,kind:`scalar`,T:8},{no:8,name:`reconnect_reason`,kind:`enum`,T:I.getEnumType(Pg)},{no:9,name:`participant_sid`,kind:`scalar`,T:9},{no:10,name:`sync_state`,kind:`message`,T:yv}]),Nv=I.makeMessageType(`livekit.WrappedJoinRequest`,()=>[{no:1,name:`compression`,kind:`enum`,T:I.getEnumType(Pv)},{no:2,name:`join_request`,kind:`scalar`,T:12}]),Pv=I.makeEnum(`livekit.WrappedJoinRequest.Compression`,[{no:0,name:`NONE`},{no:1,name:`GZIP`}]),Fv=I.makeMessageType(`livekit.MediaSectionsRequirement`,()=>[{no:1,name:`num_audios`,kind:`scalar`,T:13},{no:2,name:`num_videos`,kind:`scalar`,T:13}]);function Iv(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var Lv={exports:{}},Rv=Lv.exports,zv;function Bv(){return zv?Lv.exports:(zv=1,(function(e){(function(t,n){e.exports?e.exports=n():t.log=n()})(Rv,function(){var e=function(){},t=`undefined`,n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=[`trace`,`debug`,`info`,`warn`,`error`],i={},a=null;function o(e,t){var n=e[t];if(typeof n.bind==`function`)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch{return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(r){return r===`debug`&&(r=`log`),typeof console===t?!1:r===`trace`&&n?s:console[r]===void 0?console.log===void 0?e:o(console,`log`):o(console,r)}function l(){for(var n=this.getLevel(),i=0;i<r.length;i++){var a=r[i];this[a]=i<n?e:this.methodFactory(a,n,this.name)}if(this.log=this.debug,typeof console===t&&n<this.levels.SILENT)return`No console available for logging`}function u(e){return function(){typeof console!==t&&(l.call(this),this[e].apply(this,arguments))}}function d(e,t,n){return c(e)||u.apply(this,arguments)}function f(e,n){var o=this,s,c,u,f=`loglevel`;typeof e==`string`?f+=`:`+e:typeof e==`symbol`&&(f=void 0);function p(e){var n=(r[e]||`silent`).toUpperCase();if(!(typeof window===t||!f)){try{window.localStorage[f]=n;return}catch{}try{window.document.cookie=encodeURIComponent(f)+`=`+n+`;`}catch{}}}function m(){var e;if(!(typeof window===t||!f)){try{e=window.localStorage[f]}catch{}if(typeof e===t)try{var n=window.document.cookie,r=encodeURIComponent(f),i=n.indexOf(r+`=`);i!==-1&&(e=/^([^;]+)/.exec(n.slice(i+r.length+1))[1])}catch{}return o.levels[e]===void 0&&(e=void 0),e}}function h(){if(!(typeof window===t||!f)){try{window.localStorage.removeItem(f)}catch{}try{window.document.cookie=encodeURIComponent(f)+`=; expires=Thu, 01 Jan 1970 00:00:00 UTC`}catch{}}}function g(e){var t=e;if(typeof t==`string`&&o.levels[t.toUpperCase()]!==void 0&&(t=o.levels[t.toUpperCase()]),typeof t==`number`&&t>=0&&t<=o.levels.SILENT)return t;throw TypeError(`log.setLevel() called with invalid level: `+e)}o.name=e,o.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},o.methodFactory=n||d,o.getLevel=function(){return u??c??s},o.setLevel=function(e,t){return u=g(e),t!==!1&&p(u),l.call(o)},o.setDefaultLevel=function(e){c=g(e),m()||o.setLevel(e,!1)},o.resetLevel=function(){u=null,h(),l.call(o)},o.enableAll=function(e){o.setLevel(o.levels.TRACE,e)},o.disableAll=function(e){o.setLevel(o.levels.SILENT,e)},o.rebuild=function(){if(a!==o&&(s=g(a.getLevel())),l.call(o),a===o)for(var e in i)i[e].rebuild()},s=g(a?a.getLevel():`WARN`);var _=m();_!=null&&(u=g(_)),l.call(o)}a=new f,a.getLogger=function(e){if(typeof e!=`symbol`&&typeof e!=`string`||e===``)throw TypeError(`You must supply a name when creating a logger.`);var t=i[e];return t||=i[e]=new f(e,a.methodFactory),t};var p=typeof window===t?void 0:window.log;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=p),a},a.getLoggers=function(){return i},a.default=a,a})})(Lv),Lv.exports)}var Vv=Bv(),Hv;(function(e){e[e.trace=0]=`trace`,e[e.debug=1]=`debug`,e[e.info=2]=`info`,e[e.warn=3]=`warn`,e[e.error=4]=`error`,e[e.silent=5]=`silent`})(Hv||={});var Uv;(function(e){e.Default=`livekit`,e.Room=`livekit-room`,e.TokenSource=`livekit-token-source`,e.Participant=`livekit-participant`,e.Track=`livekit-track`,e.Publication=`livekit-track-publication`,e.Engine=`livekit-engine`,e.Signal=`livekit-signal`,e.PCManager=`livekit-pc-manager`,e.PCTransport=`livekit-pc-transport`,e.E2EE=`lk-e2ee`,e.DataTracks=`livekit-data-tracks`})(Uv||={});var R=Vv.getLogger(`livekit`);Object.values(Uv).map(e=>Vv.getLogger(e)),R.setDefaultLevel(Hv.info);function Wv(e){let t=Vv.getLogger(e);return t.setDefaultLevel(R.getLevel()),t}var Gv=Vv.getLogger(`lk-e2ee`),Kv=7e3,qv=[0,300,4*300,9*300,16*300,Kv,Kv,Kv,Kv,Kv],Jv=class{constructor(e){this._retryDelays=e===void 0?qv:[...e]}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;let t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}};function Yv(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function z(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function Xv(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function Zv(e){return this instanceof Zv?(this.v=e,this):new Zv(e)}function Qv(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),s(`next`),s(`throw`),s(`return`,o),i[Symbol.asyncIterator]=function(){return this},i;function o(e){return function(t){return Promise.resolve(t).then(e,d)}}function s(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof Zv?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function $v(e){var t,n;return t={},r(`next`),r(`throw`,function(e){throw e}),r(`return`),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:Zv(e[r](t)),done:!1}:i?i(t):t}:i}}function ey(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof Xv==`function`?Xv(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}var ty={exports:{}},ny;function ry(){if(ny)return ty.exports;ny=1;var e=typeof Reflect==`object`?Reflect:null,t=e&&typeof e.apply==`function`?e.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},n=e&&typeof e.ownKeys==`function`?e.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};function r(e){console&&console.warn&&console.warn(e)}var i=Number.isNaN||function(e){return e!==e};function a(){a.init.call(this)}ty.exports=a,ty.exports.once=_,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var o=10;function s(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(a,`defaultMaxListeners`,{enumerable:!0,get:function(){return o},set:function(e){if(typeof e!=`number`||e<0||i(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);o=e}}),a.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},a.prototype.setMaxListeners=function(e){if(typeof e!=`number`||e<0||i(e))throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+e+`.`);return this._maxListeners=e,this};function c(e){return e._maxListeners===void 0?a.defaultMaxListeners:e._maxListeners}a.prototype.getMaxListeners=function(){return c(this)},a.prototype.emit=function(e){for(var n=[],r=1;r<arguments.length;r++)n.push(arguments[r]);var i=e===`error`,a=this._events;if(a!==void 0)i&&=a.error===void 0;else if(!i)return!1;if(i){var o;if(n.length>0&&(o=n[0]),o instanceof Error)throw o;var s=Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)t(c,this,n);else for(var l=c.length,u=m(c,l),r=0;r<l;++r)t(u[r],this,n);return!0};function l(e,t,n,i){var a,o,l;if(s(n),o=e._events,o===void 0?(o=e._events=Object.create(null),e._eventsCount=0):(o.newListener!==void 0&&(e.emit(`newListener`,t,n.listener?n.listener:n),o=e._events),l=o[t]),l===void 0)l=o[t]=n,++e._eventsCount;else if(typeof l==`function`?l=o[t]=i?[n,l]:[l,n]:i?l.unshift(n):l.push(n),a=c(e),a>0&&l.length>a&&!l.warned){l.warned=!0;var u=Error(`Possible EventEmitter memory leak detected. `+l.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);u.name=`MaxListenersExceededWarning`,u.emitter=e,u.type=t,u.count=l.length,r(u)}return e}a.prototype.addListener=function(e,t){return l(this,e,t,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(e,t){return l(this,e,t,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=u.bind(r);return i.listener=n,r.wrapFn=i,i}a.prototype.once=function(e,t){return s(t),this.on(e,d(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){return s(t),this.prependListener(e,d(this,e,t)),this},a.prototype.removeListener=function(e,t){var n,r,i,a,o;if(s(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():h(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||t)}return this},a.prototype.off=a.prototype.removeListener,a.prototype.removeAllListeners=function(e){var t,n=this._events,r;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),a;for(r=0;r<i.length;++r)a=i[r],a!==`removeListener`&&this.removeAllListeners(a);return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t==`function`)this.removeListener(e,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this};function f(e,t,n){var r=e._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?g(i):m(i,i.length)}a.prototype.listeners=function(e){return f(this,e,!0)},a.prototype.rawListeners=function(e){return f(this,e,!1)},a.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):p.call(e,t)},a.prototype.listenerCount=p;function p(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}a.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function m(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function h(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function g(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function _(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){typeof e.removeListener==`function`&&e.removeListener(`error`,i),n([].slice.call(arguments))}y(e,t,a,{once:!0}),t!==`error`&&v(e,i,{once:!0})})}function v(e,t,n){typeof e.on==`function`&&y(e,`error`,t,n)}function y(e,t,n,r){if(typeof e.on==`function`)r.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener==`function`)e.addEventListener(t,function i(a){r.once&&e.removeEventListener(t,i),n(a)});else throw TypeError(`The "emitter" argument must be of type EventEmitter. Received type `+typeof e)}return ty.exports}var iy=ry(),ay=!0,oy=!0;function sy(e,t,n){let r=e.match(t);return r&&r.length>=n&&parseFloat(r[n],10)}function cy(e,t,n){if(!e.RTCPeerConnection)return;let r=e.RTCPeerConnection.prototype,i=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return i.apply(this,arguments);let a=e=>{let t=n(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,a),i.apply(this,[e,a])};let a=r.removeEventListener;r.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t]||!this._eventMap[t].has(n))return a.apply(this,arguments);let r=this._eventMap[t].get(n);return this._eventMap[t].delete(n),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,a.apply(this,[e,r])},Object.defineProperty(r,`on`+t,{get(){return this[`_on`+t]},set(e){this[`_on`+t]&&(this.removeEventListener(t,this[`_on`+t]),delete this[`_on`+t]),e&&this.addEventListener(t,this[`_on`+t]=e)},enumerable:!0,configurable:!0})}function ly(e){return typeof e==`boolean`?(ay=e,e?`adapter.js logging disabled`:`adapter.js logging enabled`):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function uy(e){return typeof e==`boolean`?(oy=!e,`adapter.js deprecation warnings `+(e?`disabled`:`enabled`)):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function dy(){if(typeof window==`object`){if(ay)return;typeof console<`u`&&typeof console.log==`function`&&console.log.apply(console,arguments)}}function fy(e,t){oy&&console.warn(e+` is deprecated, please use `+t+` instead.`)}function py(e){let t={browser:null,version:null};if(e===void 0||!e.navigator||!e.navigator.userAgent)return t.browser=`Not a browser.`,t;let{navigator:n}=e;if(n.userAgentData&&n.userAgentData.brands){let e=n.userAgentData.brands.find(e=>e.brand===`Chromium`);if(e)return{browser:`chrome`,version:parseInt(e.version,10)}}if(n.mozGetUserMedia)t.browser=`firefox`,t.version=parseInt(sy(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||e.isSecureContext===!1&&e.webkitRTCPeerConnection)t.browser=`chrome`,t.version=parseInt(sy(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(e.RTCPeerConnection&&n.userAgent.match(/AppleWebKit\/(\d+)\./))t.browser=`safari`,t.version=parseInt(sy(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&`currentDirection`in e.RTCRtpTransceiver.prototype,t._safariVersion=sy(n.userAgent,/Version\/(\d+(\.?\d+))/,1);else return t.browser=`Not a supported browser.`,t;return t}function my(e){return Object.prototype.toString.call(e)===`[object Object]`}function hy(e){return my(e)?Object.keys(e).reduce(function(t,n){let r=my(e[n]),i=r?hy(e[n]):e[n],a=r&&!Object.keys(i).length;return i===void 0||a?t:Object.assign(t,{[n]:i})},{}):e}function gy(e,t,n){!t||n.has(t.id)||(n.set(t.id,t),Object.keys(t).forEach(r=>{r.endsWith(`Id`)?gy(e,e.get(t[r]),n):r.endsWith(`Ids`)&&t[r].forEach(t=>{gy(e,e.get(t),n)})}))}function _y(e,t,n){let r=n?`outbound-rtp`:`inbound-rtp`,i=new Map;if(t===null)return i;let a=[];return e.forEach(e=>{e.type===`track`&&e.trackIdentifier===t.id&&a.push(e)}),a.forEach(t=>{e.forEach(n=>{n.type===r&&n.trackId===t.id&&gy(e,n,i)})}),i}var vy=dy;function yy(e,t){let n=e&&e.navigator;if(!n.mediaDevices)return;let r=function(e){if(typeof e!=`object`||e.mandatory||e.optional)return e;let t={};return Object.keys(e).forEach(n=>{if(n===`require`||n===`advanced`||n===`mediaSource`)return;let r=typeof e[n]==`object`?e[n]:{ideal:e[n]};r.exact!==void 0&&typeof r.exact==`number`&&(r.min=r.max=r.exact);let i=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):t===`deviceId`?`sourceId`:t};if(r.ideal!==void 0){t.optional=t.optional||[];let e={};typeof r.ideal==`number`?(e[i(`min`,n)]=r.ideal,t.optional.push(e),e={},e[i(`max`,n)]=r.ideal,t.optional.push(e)):(e[i(``,n)]=r.ideal,t.optional.push(e))}r.exact!==void 0&&typeof r.exact!=`number`?(t.mandatory=t.mandatory||{},t.mandatory[i(``,n)]=r.exact):[`min`,`max`].forEach(e=>{r[e]!==void 0&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,n)]=r[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},i=function(e,i){if(t.version>=61)return i(e);if(e=JSON.parse(JSON.stringify(e)),e&&typeof e.audio==`object`){let t=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};e=JSON.parse(JSON.stringify(e)),t(e.audio,`autoGainControl`,`googAutoGainControl`),t(e.audio,`noiseSuppression`,`googNoiseSuppression`),e.audio=r(e.audio)}if(e&&typeof e.video==`object`){let a=e.video.facingMode;a&&=typeof a==`object`?a:{ideal:a};let o=t.version<66;if(a&&(a.exact===`user`||a.exact===`environment`||a.ideal===`user`||a.ideal===`environment`)&&!(n.mediaDevices.getSupportedConstraints&&n.mediaDevices.getSupportedConstraints().facingMode&&!o)){delete e.video.facingMode;let t;if(a.exact===`environment`||a.ideal===`environment`?t=[`back`,`rear`]:(a.exact===`user`||a.ideal===`user`)&&(t=[`front`]),t)return n.mediaDevices.enumerateDevices().then(n=>{n=n.filter(e=>e.kind===`videoinput`);let o=n.find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!o&&n.length&&t.includes(`back`)&&(o=n[n.length-1]),o&&(e.video.deviceId=a.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=r(e.video),vy(`chrome: `+JSON.stringify(e)),i(e)})}e.video=r(e.video)}return vy(`chrome: `+JSON.stringify(e)),i(e)},a=function(e){return t.version>=64?e:{name:{PermissionDeniedError:`NotAllowedError`,PermissionDismissedError:`NotAllowedError`,InvalidStateError:`NotAllowedError`,DevicesNotFoundError:`NotFoundError`,ConstraintNotSatisfiedError:`OverconstrainedError`,TrackStartError:`NotReadableError`,MediaDeviceFailedDueToShutdown:`NotAllowedError`,MediaDeviceKillSwitchOn:`NotAllowedError`,TabCaptureError:`AbortError`,ScreenCaptureError:`AbortError`,DeviceCaptureError:`AbortError`}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&`: `)+this.message}}};if(n.getUserMedia=function(e,t,r){i(e,e=>{n.webkitGetUserMedia(e,t,e=>{r&&r(a(e))})})}.bind(n),n.mediaDevices.getUserMedia){let e=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(t){return i(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException(``,`NotFoundError`);return e},e=>Promise.reject(a(e))))}}}function by(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function xy(e){if(typeof e==`object`&&e.RTCPeerConnection&&!(`ontrack`in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,`ontrack`,{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener(`track`,this._ontrack),this.addEventListener(`track`,this._ontrack=e)},enumerable:!0,configurable:!0});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener(`addtrack`,n=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.track.id):{track:n.track};let i=new Event(`track`);i.track=n.track,i.receiver=r,i.transceiver={receiver:r},i.streams=[t.stream],this.dispatchEvent(i)}),t.stream.getTracks().forEach(n=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.id):{track:n};let i=new Event(`track`);i.track=n,i.receiver=r,i.transceiver={receiver:r},i.streams=[t.stream],this.dispatchEvent(i)})},this.addEventListener(`addstream`,this._ontrackpoly)),t.apply(this,arguments)}}else cy(e,`track`,e=>(e.transceiver||Object.defineProperty(e,`transceiver`,{value:{receiver:e.receiver}}),e))}function Sy(e){if(typeof e==`object`&&e.RTCPeerConnection&&!(`getSenders`in e.RTCPeerConnection.prototype)&&`createDTMFSender`in e.RTCPeerConnection.prototype){let t=function(e,t){return{track:t,get dtmf(){return this._dtmf===void 0&&(t.kind===`audio`?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){let i=n.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};let r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){r.apply(this,arguments);let t=this._senders.indexOf(e);t!==-1&&this._senders.splice(t,1)}}let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach(e=>{let t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if(typeof e==`object`&&e.RTCPeerConnection&&`getSenders`in e.RTCPeerConnection.prototype&&`createDTMFSender`in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!(`dtmf`in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,`dtmf`,{get(){return this._dtmf===void 0&&(this.track.kind===`audio`?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Cy(e){if(!(typeof e==`object`&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!(`getStats`in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>_y(t,e.track,!0))}}if(!(`getStats`in e.RTCRtpReceiver.prototype)){let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),cy(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>_y(t,e.track,!1))}}if(!(`getStats`in e.RTCRtpSender.prototype&&`getStats`in e.RTCRtpReceiver.prototype))return;let t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){let e=arguments[0],t,n,r;return this.getSenders().forEach(n=>{n.track===e&&(t?r=!0:t=n)}),this.getReceivers().forEach(t=>(t.track===e&&(n?r=!0:n=t),t.track===e)),r||t&&n?Promise.reject(new DOMException(`There are more than one sender or receiver for the track.`,`InvalidAccessError`)):t?t.getStats():n?n.getStats():Promise.reject(new DOMException(`There is no sender or receiver for the track.`,`InvalidAccessError`))}return t.apply(this,arguments)}}function wy(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let r=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?this._shimmedLocalStreams[n.id].indexOf(r)===-1&&this._shimmedLocalStreams[n.id].push(r):this._shimmedLocalStreams[n.id]=[n,r],r};let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException(`Track already exists.`,`InvalidAccessError`)});let t=this.getSenders();n.apply(this,arguments);let r=this.getSenders().filter(e=>t.indexOf(e)===-1);this._shimmedLocalStreams[e.id]=[e].concat(r)};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};let i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{let n=this._shimmedLocalStreams[t].indexOf(e);n!==-1&&this._shimmedLocalStreams[t].splice(n,1),this._shimmedLocalStreams[t].length===1&&delete this._shimmedLocalStreams[t]}),i.apply(this,arguments)}}function Ty(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return wy(e);let n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let e=n.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};let r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException(`Track already exists.`,`InvalidAccessError`)}),!this._reverseStreams[t.id]){let n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}r.apply(this,[t])};let i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,n){if(this.signalingState===`closed`)throw new DOMException(`The RTCPeerConnection's signalingState is 'closed'.`,`InvalidStateError`);let r=[].slice.call(arguments,1);if(r.length!==1||!r[0].getTracks().find(e=>e===t))throw new DOMException(`The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.`,`NotSupportedError`);if(this.getSenders().find(e=>e.track===t))throw new DOMException(`Track already exists.`,`InvalidAccessError`);this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let i=this._streams[n.id];if(i)i.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event(`negotiationneeded`))});else{let r=new e.MediaStream([t]);this._streams[n.id]=r,this._reverseStreams[r.id]=n,this.addStream(r)}return this.getSenders().find(e=>e.track===t)};function a(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(i.id,`g`),r.id)}),new RTCSessionDescription({type:t.type,sdp:n})}function o(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(r.id,`g`),i.id)}),new RTCSessionDescription({type:t.type,sdp:n})}[`createOffer`,`createAnswer`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){let e=arguments;return arguments.length&&typeof arguments[0]==`function`?n.apply(this,[t=>{let n=a(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then(e=>a(this,e))}};e.RTCPeerConnection.prototype[t]=r[t]});let s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type||(arguments[0]=o(this,arguments[0])),s.apply(this,arguments)};let c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,`localDescription`);Object.defineProperty(e.RTCPeerConnection.prototype,`localDescription`,{get(){let e=c.get.apply(this);return e.type===``?e:a(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if(this.signalingState===`closed`)throw new DOMException(`The RTCPeerConnection's signalingState is 'closed'.`,`InvalidStateError`);if(!e._pc)throw new DOMException(`Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.`,`TypeError`);if(e._pc!==this)throw new DOMException(`Sender was not created by this connection.`,`InvalidAccessError`);this._streams=this._streams||{};let t;Object.keys(this._streams).forEach(n=>{this._streams[n].getTracks().find(t=>e.track===t)&&(t=this._streams[n])}),t&&(t.getTracks().length===1?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event(`negotiationneeded`)))}}function Ey(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&[`setLocalDescription`,`setRemoteDescription`,`addIceCandidate`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t===`addIceCandidate`?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]})}function Dy(e,t){cy(e,`negotiationneeded`,e=>{let n=e.target;if(!((t.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics===`plan-b`)&&n.signalingState!==`stable`))return e})}var Oy=Object.freeze({__proto__:null,fixNegotiationNeeded:Dy,shimAddTrackRemoveTrack:Ty,shimAddTrackRemoveTrackWithNative:wy,shimGetSendersWithDtmf:Sy,shimGetUserMedia:yy,shimMediaStream:by,shimOnTrack:xy,shimPeerConnection:Ey,shimSenderReceiverGetStats:Cy});function ky(e,t){let n=e&&e.navigator,r=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,r){fy(`navigator.getUserMedia`,`navigator.mediaDevices.getUserMedia`),n.mediaDevices.getUserMedia(e).then(t,r)},!(t.version>55&&`autoGainControl`in n.mediaDevices.getSupportedConstraints())){let e=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},t=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(n){return typeof n==`object`&&typeof n.audio==`object`&&(n=JSON.parse(JSON.stringify(n)),e(n.audio,`autoGainControl`,`mozAutoGainControl`),e(n.audio,`noiseSuppression`,`mozNoiseSuppression`)),t(n)},r&&r.prototype.getSettings){let t=r.prototype.getSettings;r.prototype.getSettings=function(){let n=t.apply(this,arguments);return e(n,`mozAutoGainControl`,`autoGainControl`),e(n,`mozNoiseSuppression`,`noiseSuppression`),n}}if(r&&r.prototype.applyConstraints){let t=r.prototype.applyConstraints;r.prototype.applyConstraints=function(n){return this.kind===`audio`&&typeof n==`object`&&(n=JSON.parse(JSON.stringify(n)),e(n,`autoGainControl`,`mozAutoGainControl`),e(n,`noiseSuppression`,`mozNoiseSuppression`)),t.apply(this,[n])}}}}function Ay(e,t){e.navigator.mediaDevices&&`getDisplayMedia`in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){let e=new DOMException(`getDisplayMedia without video constraints is undefined`);return e.name=`NotFoundError`,e.code=8,Promise.reject(e)}return n.video===!0?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)})}function jy(e){typeof e==`object`&&e.RTCTrackEvent&&`receiver`in e.RTCTrackEvent.prototype&&!(`transceiver`in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,`transceiver`,{get(){return{receiver:this.receiver}}})}function My(e,t){if(typeof e!=`object`||!(e.RTCPeerConnection||e.mozRTCPeerConnection))return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&[`setLocalDescription`,`setRemoteDescription`,`addIceCandidate`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t===`addIceCandidate`?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]});let n={inboundrtp:`inbound-rtp`,outboundrtp:`outbound-rtp`,candidatepair:`candidate-pair`,localcandidate:`local-candidate`,remotecandidate:`remote-candidate`},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let[e,i,a]=arguments;return r.apply(this,[e||null]).then(e=>{if(t.version<53&&!i)try{e.forEach(e=>{e.type=n[e.type]||e.type})}catch(t){if(t.name!==`TypeError`)throw t;e.forEach((t,r)=>{e.set(r,Object.assign({},t,{type:n[t.type]||t.type}))})}return e}).then(i,a)}}function Ny(e){if(!(typeof e==`object`&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&`getStats`in e.RTCRtpSender.prototype)return;let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Py(e){if(!(typeof e==`object`&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&`getStats`in e.RTCRtpReceiver.prototype)return;let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),cy(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Fy(e){!e.RTCPeerConnection||`removeStream`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){fy(`removeStream`,`removeTrack`),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function Iy(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Ly(e){if(!(typeof e==`object`&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;e===void 0&&(e=[]),e=[...e];let n=e.length>0;n&&e.forEach(e=>{if(`rid`in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw TypeError(`Invalid RID value provided.`);if(`scaleResolutionDownBy`in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw RangeError(`scale_resolution_down_by must be >= 1.0`);if(`maxFramerate`in e&&!(parseFloat(e.maxFramerate)>=0))throw RangeError(`max_framerate must be >= 0.0`)});let r=t.apply(this,arguments);if(n){let{sender:t}=r,n=t.getParameters();(!(`encodings`in n)||n.encodings.length===1&&Object.keys(n.encodings[0]).length===0)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return r})}function Ry(e){if(!(typeof e==`object`&&e.RTCRtpSender))return;let t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){let e=t.apply(this,arguments);return`encodings`in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function zy(e){if(!(typeof e==`object`&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function By(e){if(!(typeof e==`object`&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var Vy=Object.freeze({__proto__:null,shimAddTransceiver:Ly,shimCreateAnswer:By,shimCreateOffer:zy,shimGetDisplayMedia:Ay,shimGetParameters:Ry,shimGetUserMedia:ky,shimOnTrack:jy,shimPeerConnection:My,shimRTCDataChannel:Iy,shimReceiverGetStats:Py,shimRemoveStream:Fy,shimSenderGetStats:Ny});function Hy(e){if(!(typeof e!=`object`||!e.RTCPeerConnection)){if(`getLocalStreams`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||=[],this._localStreams}),!(`addStream`in e.RTCPeerConnection.prototype)){let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||=[],this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(n=>t.call(this,n,e)),e.getVideoTracks().forEach(n=>t.call(this,n,e))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var n=arguments.length,r=Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return r&&r.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}`removeStream`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||=[];let t=this._localStreams.indexOf(e);if(t===-1)return;this._localStreams.splice(t,1);let n=e.getTracks();this.getSenders().forEach(e=>{n.includes(e.track)&&this.removeTrack(e)})})}}function Uy(e){if(!(typeof e!=`object`||!e.RTCPeerConnection)&&(`getRemoteStreams`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!(`onaddstream`in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,`onaddstream`,{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener(`addstream`,this._onaddstream),this.removeEventListener(`track`,this._onaddstreampoly)),this.addEventListener(`addstream`,this._onaddstream=e),this.addEventListener(`track`,this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||=[],this._remoteStreams.includes(e))return;this._remoteStreams.push(e);let t=new Event(`addstream`);t.stream=e,this.dispatchEvent(t)})})}});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){let e=this;return this._onaddstreampoly||this.addEventListener(`track`,this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||=[],e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);let n=new Event(`addstream`);n.stream=t,e.dispatchEvent(n)})}),t.apply(e,arguments)}}}function Wy(e){if(typeof e!=`object`||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype,n=t.createOffer,r=t.createAnswer,i=t.setLocalDescription,a=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){let r=arguments.length>=2?arguments[2]:arguments[0],i=n.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){let n=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[n]);return t?(i.then(e,t),Promise.resolve()):i};let s=function(e,t,n){let r=i.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r};t.setLocalDescription=s,s=function(e,t,n){let r=a.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},t.setRemoteDescription=s,s=function(e,t,n){let r=o.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},t.addIceCandidate=s}function Gy(e){let t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){let e=t.mediaDevices,n=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>n(Ky(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,r){t.mediaDevices.getUserMedia(e).then(n,r)}.bind(t))}function Ky(e){return e&&e.video!==void 0?Object.assign({},e,{video:hy(e.video)}):e}function qy(e){if(!e.RTCPeerConnection)return;let t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){let t=[];for(let n=0;n<e.iceServers.length;n++){let r=e.iceServers[n];r.urls===void 0&&r.url?(fy(`RTCIceServer.url`,`RTCIceServer.urls`),r=JSON.parse(JSON.stringify(r)),r.urls=r.url,delete r.url,t.push(r)):t.push(e.iceServers[n])}e.iceServers=t}return new t(e,n)},e.RTCPeerConnection.prototype=t.prototype,`generateCertificate`in t&&Object.defineProperty(e.RTCPeerConnection,`generateCertificate`,{get(){return t.generateCertificate}})}function Jy(e){typeof e==`object`&&e.RTCTrackEvent&&`receiver`in e.RTCTrackEvent.prototype&&!(`transceiver`in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,`transceiver`,{get(){return{receiver:this.receiver}}})}function Yy(e){let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){e.offerToReceiveAudio!==void 0&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);let t=this.getTransceivers().find(e=>e.receiver.track.kind===`audio`);e.offerToReceiveAudio===!1&&t?t.direction===`sendrecv`?t.setDirection?t.setDirection(`sendonly`):t.direction=`sendonly`:t.direction===`recvonly`&&(t.setDirection?t.setDirection(`inactive`):t.direction=`inactive`):e.offerToReceiveAudio===!0&&!t&&this.addTransceiver(`audio`,{direction:`recvonly`}),e.offerToReceiveVideo!==void 0&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);let n=this.getTransceivers().find(e=>e.receiver.track.kind===`video`);e.offerToReceiveVideo===!1&&n?n.direction===`sendrecv`?n.setDirection?n.setDirection(`sendonly`):n.direction=`sendonly`:n.direction===`recvonly`&&(n.setDirection?n.setDirection(`inactive`):n.direction=`inactive`):e.offerToReceiveVideo===!0&&!n&&this.addTransceiver(`video`,{direction:`recvonly`})}return t.apply(this,arguments)}}function Xy(e){typeof e!=`object`||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Zy=Object.freeze({__proto__:null,shimAudioContext:Xy,shimCallbacksAPI:Wy,shimConstraints:Ky,shimCreateOfferLegacy:Yy,shimGetUserMedia:Gy,shimLocalStreamsAPI:Hy,shimRTCIceServerUrls:qy,shimRemoteStreamsAPI:Uy,shimTrackEventTransceiver:Jy}),Qy={exports:{}},$y;function eb(){return $y?Qy.exports:($y=1,(function(e){let t={};t.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split(`
|
|
3
27
|
`).map(e=>e.trim())},t.splitSections=function(e){return e.split(`
|
|
4
28
|
m=`).map((e,t)=>(t>0?`m=`+e:e).trim()+`\r
|
|
5
29
|
`)},t.getDescription=function(e){let n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){let n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter(e=>e.indexOf(n)===0)},t.parseCandidate=function(e){let t;t=e.indexOf(`a=candidate:`)===0?e.substring(12).split(` `):e.substring(10).split(` `);let n={foundation:t[0],component:{1:`rtp`,2:`rtcp`}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case`raddr`:n.relatedAddress=t[e+1];break;case`rport`:n.relatedPort=parseInt(t[e+1],10);break;case`tcptype`:n.tcpType=t[e+1];break;case`ufrag`:n.ufrag=t[e+1],n.usernameFragment=t[e+1];break;default:n[t[e]]===void 0&&(n[t[e]]=t[e+1]);break}return n},t.writeCandidate=function(e){let t=[];t.push(e.foundation);let n=e.component;n===`rtp`?t.push(1):n===`rtcp`?t.push(2):t.push(n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);let r=e.type;return t.push(`typ`),t.push(r),r!==`host`&&e.relatedAddress&&e.relatedPort&&(t.push(`raddr`),t.push(e.relatedAddress),t.push(`rport`),t.push(e.relatedPort)),e.tcpType&&e.protocol.toLowerCase()===`tcp`&&(t.push(`tcptype`),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push(`ufrag`),t.push(e.usernameFragment||e.ufrag)),`candidate:`+t.join(` `)},t.parseIceOptions=function(e){return e.substring(14).split(` `)},t.parseRtpMap=function(e){let t=e.substring(9).split(` `),n={payloadType:parseInt(t.shift(),10)};return t=t[0].split(`/`),n.name=t[0],n.clockRate=parseInt(t[1],10),n.channels=t.length===3?parseInt(t[2],10):1,n.numChannels=n.channels,n},t.writeRtpMap=function(e){let t=e.payloadType;e.preferredPayloadType!==void 0&&(t=e.preferredPayloadType);let n=e.channels||e.numChannels||1;return`a=rtpmap:`+t+` `+e.name+`/`+e.clockRate+(n===1?``:`/`+n)+`\r
|
|
@@ -30,12 +54,12 @@ a=ice-pwd:`+e.password+`\r
|
|
|
30
54
|
o=`+(r||`thisisadapterortc`)+` `+i+` `+a+` IN IP4 127.0.0.1\r
|
|
31
55
|
s=-\r
|
|
32
56
|
t=0 0\r
|
|
33
|
-
`},t.getDirection=function(e,n){let r=t.splitLines(e);for(let e=0;e<r.length;e++)switch(r[e]){case`a=sendrecv`:case`a=sendonly`:case`a=recvonly`:case`a=inactive`:return r[e].substring(2)}return n?t.getDirection(n):`sendrecv`},t.getKind=function(e){return t.splitLines(e)[0].split(` `)[0].substring(2)},t.isRejected=function(e){return e.split(` `,2)[1]===`0`},t.parseMLine=function(e){let n=t.splitLines(e)[0].substring(2).split(` `);return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(` `)}},t.parseOLine=function(e){let n=t.matchPrefix(e,`o=`)[0].substring(2).split(` `);return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if(typeof e!=`string`||e.length===0)return!1;let n=t.splitLines(e);for(let e=0;e<n.length;e++)if(n[e].length<2||n[e].charAt(1)!==`=`)return!1;return!0},e.exports=t})(
|
|
57
|
+
`},t.getDirection=function(e,n){let r=t.splitLines(e);for(let e=0;e<r.length;e++)switch(r[e]){case`a=sendrecv`:case`a=sendonly`:case`a=recvonly`:case`a=inactive`:return r[e].substring(2)}return n?t.getDirection(n):`sendrecv`},t.getKind=function(e){return t.splitLines(e)[0].split(` `)[0].substring(2)},t.isRejected=function(e){return e.split(` `,2)[1]===`0`},t.parseMLine=function(e){let n=t.splitLines(e)[0].substring(2).split(` `);return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(` `)}},t.parseOLine=function(e){let n=t.matchPrefix(e,`o=`)[0].substring(2).split(` `);return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if(typeof e!=`string`||e.length===0)return!1;let n=t.splitLines(e);for(let e=0;e<n.length;e++)if(n[e].length<2||n[e].charAt(1)!==`=`)return!1;return!0},e.exports=t})(Qy),Qy.exports)}var tb=eb(),nb=Iv(tb),rb=Cm({__proto__:null,default:nb},[tb]);function ib(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&`foundation`in e.RTCIceCandidate.prototype)return;let t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if(typeof e==`object`&&e.candidate&&e.candidate.indexOf(`a=`)===0&&(e=JSON.parse(JSON.stringify(e)),e.candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){let n=new t(e),r=nb.parseCandidate(e.candidate);for(let e in r)e in n||Object.defineProperty(n,e,{value:r[e]});return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,cy(e,`icecandidate`,t=>(t.candidate&&Object.defineProperty(t,`candidate`,{value:new e.RTCIceCandidate(t.candidate),writable:`false`}),t))}function ab(e){!e.RTCIceCandidate||e.RTCIceCandidate&&`relayProtocol`in e.RTCIceCandidate.prototype||cy(e,`icecandidate`,e=>{if(e.candidate){let t=nb.parseCandidate(e.candidate.candidate);t.type===`relay`&&(e.candidate.relayProtocol={0:`tls`,1:`tcp`,2:`udp`}[t.priority>>24])}return e})}function ob(e,t){if(!e.RTCPeerConnection)return;`sctp`in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,`sctp`,{get(){return this._sctp===void 0?null:this._sctp}});let n=function(e){if(!e||!e.sdp)return!1;let t=nb.splitSections(e.sdp);return t.shift(),t.some(e=>{let t=nb.parseMLine(e);return t&&t.kind===`application`&&t.protocol.indexOf(`SCTP`)!==-1})},r=function(e){let t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(t===null||t.length<2)return-1;let n=parseInt(t[1],10);return n===n?n:-1},i=function(e){let n=65536;return t.browser===`firefox`&&(n=t.version<57?e===-1?16384:2147483637:t.version<60?t.version===57?65535:65536:2147483637),n},a=function(e,n){let r=65536;t.browser===`firefox`&&t.version===57&&(r=65535);let i=nb.matchPrefix(e.sdp,`a=max-message-size:`);return i.length>0?r=parseInt(i[0].substring(19),10):t.browser===`firefox`&&n!==-1&&(r=2147483637),r},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,t.browser===`chrome`&&t.version>=76){let{sdpSemantics:e}=this.getConfiguration();e===`plan-b`&&Object.defineProperty(this,`sctp`,{get(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(n(arguments[0])){let e=r(arguments[0]),t=i(e),n=a(arguments[0],e),o;o=t===0&&n===0?1/0:t===0||n===0?Math.max(t,n):Math.min(t,n);let s={};Object.defineProperty(s,`maxMessageSize`,{get(){return o}}),this._sctp=s}return o.apply(this,arguments)}}function sb(e){if(!(e.RTCPeerConnection&&`createDataChannel`in e.RTCPeerConnection.prototype))return;function t(e,t){let n=e.send;e.send=function(){let r=arguments[0],i=r.length||r.size||r.byteLength;if(e.readyState===`open`&&t.sctp&&i>t.sctp.maxMessageSize)throw TypeError(`Message too large (can send a maximum of `+t.sctp.maxMessageSize+` bytes)`);return n.apply(e,arguments)}}let n=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){let e=n.apply(this,arguments);return t(e,this),e},cy(e,`datachannel`,e=>(t(e.channel,e.target),e))}function cb(e){if(!e.RTCPeerConnection||`connectionState`in e.RTCPeerConnection.prototype)return;let t=e.RTCPeerConnection.prototype;Object.defineProperty(t,`connectionState`,{get(){return{completed:`connected`,checking:`connecting`}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,`onconnectionstatechange`,{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener(`connectionstatechange`,this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener(`connectionstatechange`,this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),[`setLocalDescription`,`setRemoteDescription`].forEach(e=>{let n=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{let t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;let n=new Event(`connectionstatechange`,e);t.dispatchEvent(n)}return e},this.addEventListener(`iceconnectionstatechange`,this._connectionstatechangepoly)),n.apply(this,arguments)}})}function lb(e,t){if(!e.RTCPeerConnection||t.browser===`chrome`&&t.version>=71||t.browser===`safari`&&t._safariVersion>=13.1)return;let n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&t.sdp.indexOf(`
|
|
34
58
|
a=extmap-allow-mixed`)!==-1){let n=t.sdp.split(`
|
|
35
59
|
`).filter(e=>e.trim()!==`a=extmap-allow-mixed`).join(`
|
|
36
|
-
`);e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:n}):t.sdp=n}return n.apply(this,arguments)}}function pc(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let n=e.RTCPeerConnection.prototype.addIceCandidate;!n||n.length===0||(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(t.browser===`chrome`&&t.version<78||t.browser===`firefox`&&t.version<68||t.browser===`safari`)&&arguments[0]&&arguments[0].candidate===``?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function mc(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let n=e.RTCPeerConnection.prototype.setLocalDescription;!n||n.length===0||(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if(typeof e!=`object`||e.type&&e.sdp)return n.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case`stable`:case`have-local-offer`:case`have-remote-pranswer`:e.type=`offer`;break;default:e.type=`answer`;break}return e.sdp||e.type!==`offer`&&e.type!==`answer`?n.apply(this,[e]):(e.type===`offer`?this.createOffer:this.createAnswer).apply(this).then(e=>n.apply(this,[e]))})}var hc=Object.freeze({__proto__:null,removeExtmapAllowMixed:fc,shimAddIceCandidateNullOrEmpty:pc,shimConnectionState:dc,shimMaxMessageSize:lc,shimParameterlessSetLocalDescription:mc,shimRTCIceCandidate:sc,shimRTCIceCandidateRelayProtocol:cc,shimSendThrowTypeError:uc});function gc(){let{window:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},n=ms,r=gs(e),i={browserDetails:r,commonShim:hc,extractVersion:us,disableLog:fs,disableWarnings:ps,sdp:oc};switch(r.browser){case`chrome`:if(!js||!ks||!t.shimChrome)return n(`Chrome shim is not included in this adapter release.`),i;if(r.version===null)return n(`Chrome shim can not determine version, not shimming.`),i;n(`adapter.js shimming chrome.`),i.browserShim=js,pc(e,r),mc(e),Ss(e,r),Cs(e),ks(e,r),ws(e),Os(e,r),Ts(e),Es(e),As(e,r),sc(e),cc(e),dc(e),lc(e,r),uc(e),fc(e,r);break;case`firefox`:if(!Ws||!Fs||!t.shimFirefox)return n(`Firefox shim is not included in this adapter release.`),i;n(`adapter.js shimming firefox.`),i.browserShim=Ws,pc(e,r),mc(e),Ms(e,r),Fs(e,r),Ps(e),Rs(e),Is(e),Ls(e),zs(e),Bs(e),Vs(e),Hs(e),Us(e),sc(e),dc(e),lc(e,r),uc(e);break;case`safari`:if(!ec||!t.shimSafari)return n(`Safari shim is not included in this adapter release.`),i;n(`adapter.js shimming safari.`),i.browserShim=ec,pc(e,r),mc(e),Xs(e),Qs(e),qs(e),Gs(e),Ks(e),Zs(e),Js(e),$s(e),sc(e),cc(e),lc(e,r),uc(e),fc(e,r);break;default:n(`Unsupported browser!`);break}return i}gc({window:typeof window>`u`?void 0:window});var _c,vc,yc=class extends (vc=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}};_c=yc,yc.resolve=e=>Reflect.get(vc,`resolve`,_c).call(_c,e);var bc=/version\/(\d+(\.?_?\d+)+)/i,xc;function Sc(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(e===void 0&&typeof navigator>`u`)return;let n=(e??navigator.userAgent).toLowerCase();return(xc===void 0||t)&&(xc=Cc.find(e=>{let{test:t}=e;return t.test(n)})?.describe(n)),xc}var Cc=[{test:/firefox|iceweasel|fxios/i,describe(e){return{name:`Firefox`,version:wc(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes(`fxios`)?`iOS`:void 0,osVersion:Tc(e)}}},{test:/chrom|crios|crmo/i,describe(e){return{name:`Chrome`,version:wc(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes(`crios`)?`iOS`:void 0,osVersion:Tc(e)}}},{test:/safari|applewebkit/i,describe(e){return{name:`Safari`,version:wc(bc,e),os:e.includes(`mobile/`)?`iOS`:`macOS`,osVersion:Tc(e)}}}];function wc(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,r=t.match(e);return r&&r.length>=n&&r[n]||``}function Tc(e){return e.includes(`mac os`)?wc(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,`.`):void 0}var Ec=`2.18.1`,Dc=class extends Error{constructor(e,t,n){super(t||`an error has occurred`),this.name=`LiveKitError`,this.code=e,n?.cause!==void 0&&(this.cause=n?.cause)}},Oc=class extends Dc{},I;(function(e){e[e.NotAllowed=0]=`NotAllowed`,e[e.ServerUnreachable=1]=`ServerUnreachable`,e[e.InternalError=2]=`InternalError`,e[e.Cancelled=3]=`Cancelled`,e[e.LeaveRequest=4]=`LeaveRequest`,e[e.Timeout=5]=`Timeout`,e[e.WebSocket=6]=`WebSocket`,e[e.ServiceNotFound=7]=`ServiceNotFound`})(I||={});var L=class e extends Oc{constructor(e,t,n,r){super(1,e),this.name=`ConnectionError`,this.status=n,this.reason=t,this.context=r,this.reasonName=I[t]}static notAllowed(t,n,r){return new e(t,I.NotAllowed,n,r)}static timeout(t){return new e(t,I.Timeout)}static leaveRequest(t,n){return new e(t,I.LeaveRequest,void 0,n)}static internal(t,n){return new e(t,I.InternalError,void 0,n)}static cancelled(t){return new e(t,I.Cancelled)}static serverUnreachable(t,n){return new e(t,I.ServerUnreachable,n)}static websocket(t,n,r){return new e(t,I.WebSocket,n,r)}static serviceNotFound(t,n){return new e(t,I.ServiceNotFound,void 0,n)}},kc=class extends Dc{constructor(e){super(21,e??`device is unsupported`),this.name=`DeviceUnsupportedError`}},Ac=class extends Dc{constructor(e){super(20,e??`track is invalid`),this.name=`TrackInvalidError`}},jc=class extends Dc{constructor(e){super(10,e??`unsupported server`),this.name=`UnsupportedServer`}},Mc=class extends Dc{constructor(e){super(12,e??`unexpected connection state`),this.name=`UnexpectedConnectionState`}},Nc=class extends Dc{constructor(e){super(13,e??`unable to negotiate`),this.name=`NegotiationError`}},Pc=class extends Dc{constructor(e,t){super(15,e),this.name=`PublishTrackError`,this.status=t}},Fc=class extends Oc{constructor(e,t){super(15,e),this.name=`SignalRequestError`,this.reason=t,this.reasonName=typeof t==`string`?t:Mo[t]}},Ic;(function(e){e[e.AlreadyOpened=0]=`AlreadyOpened`,e[e.AbnormalEnd=1]=`AbnormalEnd`,e[e.DecodeFailed=2]=`DecodeFailed`,e[e.LengthExceeded=3]=`LengthExceeded`,e[e.Incomplete=4]=`Incomplete`,e[e.HandlerAlreadyRegistered=7]=`HandlerAlreadyRegistered`,e[e.EncryptionTypeMismatch=8]=`EncryptionTypeMismatch`})(Ic||={});var Lc=class extends Oc{constructor(e,t){super(16,e),this.name=`DataStreamError`,this.reason=t,this.reasonName=Ic[t]}},Rc=class extends Dc{constructor(e){super(18,e),this.name=`SignalReconnectError`}},zc;(function(e){e.PermissionDenied=`PermissionDenied`,e.NotFound=`NotFound`,e.DeviceInUse=`DeviceInUse`,e.Other=`Other`})(zc||={}),(function(e){function t(t){if(t&&`name`in t)return t.name===`NotFoundError`||t.name===`DevicesNotFoundError`?e.NotFound:t.name===`NotAllowedError`||t.name===`PermissionDeniedError`?e.PermissionDenied:t.name===`NotReadableError`||t.name===`TrackStartError`?e.DeviceInUse:e.Other}e.getFailure=t})(zc||={});var Bc=class{};Bc.setTimeout=function(){return setTimeout(...arguments)},Bc.setInterval=function(){return setInterval(...arguments)},Bc.clearTimeout=function(){return clearTimeout(...arguments)},Bc.clearInterval=function(){return clearInterval(...arguments)};var R;(function(e){e.Connected=`connected`,e.Reconnecting=`reconnecting`,e.SignalReconnecting=`signalReconnecting`,e.Reconnected=`reconnected`,e.Disconnected=`disconnected`,e.ConnectionStateChanged=`connectionStateChanged`,e.Moved=`moved`,e.MediaDevicesChanged=`mediaDevicesChanged`,e.ParticipantConnected=`participantConnected`,e.ParticipantDisconnected=`participantDisconnected`,e.TrackPublished=`trackPublished`,e.TrackSubscribed=`trackSubscribed`,e.TrackSubscriptionFailed=`trackSubscriptionFailed`,e.TrackUnpublished=`trackUnpublished`,e.TrackUnsubscribed=`trackUnsubscribed`,e.TrackMuted=`trackMuted`,e.TrackUnmuted=`trackUnmuted`,e.LocalTrackPublished=`localTrackPublished`,e.LocalTrackUnpublished=`localTrackUnpublished`,e.LocalAudioSilenceDetected=`localAudioSilenceDetected`,e.ActiveSpeakersChanged=`activeSpeakersChanged`,e.ParticipantMetadataChanged=`participantMetadataChanged`,e.ParticipantNameChanged=`participantNameChanged`,e.ParticipantAttributesChanged=`participantAttributesChanged`,e.ParticipantActive=`participantActive`,e.RoomMetadataChanged=`roomMetadataChanged`,e.DataReceived=`dataReceived`,e.SipDTMFReceived=`sipDTMFReceived`,e.TranscriptionReceived=`transcriptionReceived`,e.ConnectionQualityChanged=`connectionQualityChanged`,e.TrackStreamStateChanged=`trackStreamStateChanged`,e.TrackSubscriptionPermissionChanged=`trackSubscriptionPermissionChanged`,e.TrackSubscriptionStatusChanged=`trackSubscriptionStatusChanged`,e.AudioPlaybackStatusChanged=`audioPlaybackChanged`,e.VideoPlaybackStatusChanged=`videoPlaybackChanged`,e.MediaDevicesError=`mediaDevicesError`,e.ParticipantPermissionsChanged=`participantPermissionsChanged`,e.SignalConnected=`signalConnected`,e.RecordingStatusChanged=`recordingStatusChanged`,e.ParticipantEncryptionStatusChanged=`participantEncryptionStatusChanged`,e.EncryptionError=`encryptionError`,e.DCBufferStatusChanged=`dcBufferStatusChanged`,e.ActiveDeviceChanged=`activeDeviceChanged`,e.ChatMessage=`chatMessage`,e.LocalTrackSubscribed=`localTrackSubscribed`,e.MetricsReceived=`metricsReceived`,e.DataTrackPublished=`dataTrackPublished`,e.DataTrackUnpublished=`dataTrackUnpublished`,e.LocalDataTrackPublished=`localDataTrackPublished`,e.LocalDataTrackUnpublished=`localDataTrackUnpublished`})(R||={});var z;(function(e){e.TrackPublished=`trackPublished`,e.TrackSubscribed=`trackSubscribed`,e.TrackSubscriptionFailed=`trackSubscriptionFailed`,e.TrackUnpublished=`trackUnpublished`,e.TrackUnsubscribed=`trackUnsubscribed`,e.TrackMuted=`trackMuted`,e.TrackUnmuted=`trackUnmuted`,e.LocalTrackPublished=`localTrackPublished`,e.LocalTrackUnpublished=`localTrackUnpublished`,e.LocalTrackCpuConstrained=`localTrackCpuConstrained`,e.LocalSenderCreated=`localSenderCreated`,e.ParticipantMetadataChanged=`participantMetadataChanged`,e.ParticipantNameChanged=`participantNameChanged`,e.DataReceived=`dataReceived`,e.SipDTMFReceived=`sipDTMFReceived`,e.TranscriptionReceived=`transcriptionReceived`,e.IsSpeakingChanged=`isSpeakingChanged`,e.ConnectionQualityChanged=`connectionQualityChanged`,e.TrackStreamStateChanged=`trackStreamStateChanged`,e.TrackSubscriptionPermissionChanged=`trackSubscriptionPermissionChanged`,e.TrackSubscriptionStatusChanged=`trackSubscriptionStatusChanged`,e.TrackCpuConstrained=`trackCpuConstrained`,e.MediaDevicesError=`mediaDevicesError`,e.AudioStreamAcquired=`audioStreamAcquired`,e.ParticipantPermissionsChanged=`participantPermissionsChanged`,e.PCTrackAdded=`pcTrackAdded`,e.AttributesChanged=`attributesChanged`,e.LocalTrackSubscribed=`localTrackSubscribed`,e.ChatMessage=`chatMessage`,e.Active=`active`})(z||={});var B;(function(e){e.TransportsCreated=`transportsCreated`,e.Connected=`connected`,e.Disconnected=`disconnected`,e.Resuming=`resuming`,e.Resumed=`resumed`,e.Restarting=`restarting`,e.Restarted=`restarted`,e.SignalResumed=`signalResumed`,e.SignalRestarted=`signalRestarted`,e.Closing=`closing`,e.MediaTrackAdded=`mediaTrackAdded`,e.ActiveSpeakersUpdate=`activeSpeakersUpdate`,e.DataPacketReceived=`dataPacketReceived`,e.RTPVideoMapUpdate=`rtpVideoMapUpdate`,e.DCBufferStatusChanged=`dcBufferStatusChanged`,e.ParticipantUpdate=`participantUpdate`,e.RoomUpdate=`roomUpdate`,e.SpeakersChanged=`speakersChanged`,e.StreamStateChanged=`streamStateChanged`,e.ConnectionQualityUpdate=`connectionQualityUpdate`,e.SubscriptionError=`subscriptionError`,e.SubscriptionPermissionUpdate=`subscriptionPermissionUpdate`,e.RemoteMute=`remoteMute`,e.SubscribedQualityUpdate=`subscribedQualityUpdate`,e.LocalTrackUnpublished=`localTrackUnpublished`,e.LocalTrackSubscribed=`localTrackSubscribed`,e.Offline=`offline`,e.SignalRequestResponse=`signalRequestResponse`,e.SignalConnected=`signalConnected`,e.RoomMoved=`roomMoved`,e.PublishDataTrackResponse=`publishDataTrackResponse`,e.UnPublishDataTrackResponse=`unPublishDataTrackResponse`,e.DataTrackSubscriberHandles=`dataTrackSubscriberHandles`,e.DataTrackPacketReceived=`dataTrackPacketReceived`,e.Joined=`joined`})(B||={});var V;(function(e){e.Message=`message`,e.Muted=`muted`,e.Unmuted=`unmuted`,e.Restarted=`restarted`,e.Ended=`ended`,e.Subscribed=`subscribed`,e.Unsubscribed=`unsubscribed`,e.CpuConstrained=`cpuConstrained`,e.UpdateSettings=`updateSettings`,e.UpdateSubscription=`updateSubscription`,e.AudioPlaybackStarted=`audioPlaybackStarted`,e.AudioPlaybackFailed=`audioPlaybackFailed`,e.AudioSilenceDetected=`audioSilenceDetected`,e.VisibilityChanged=`visibilityChanged`,e.VideoDimensionsChanged=`videoDimensionsChanged`,e.VideoPlaybackStarted=`videoPlaybackStarted`,e.VideoPlaybackFailed=`videoPlaybackFailed`,e.ElementAttached=`elementAttached`,e.ElementDetached=`elementDetached`,e.UpstreamPaused=`upstreamPaused`,e.UpstreamResumed=`upstreamResumed`,e.SubscriptionPermissionChanged=`subscriptionPermissionChanged`,e.SubscriptionStatusChanged=`subscriptionStatusChanged`,e.SubscriptionFailed=`subscriptionFailed`,e.TrackProcessorUpdate=`trackProcessorUpdate`,e.AudioTrackFeatureUpdate=`audioTrackFeatureUpdate`,e.TranscriptionReceived=`transcriptionReceived`,e.TimeSyncUpdate=`timeSyncUpdate`,e.PreConnectBufferFlushed=`preConnectBufferFlushed`})(V||={});function Vc(e){return e===void 0?e:typeof structuredClone==`function`?typeof e==`object`&&e?structuredClone(Object.assign({},e)):structuredClone(e):JSON.parse(JSON.stringify(e))}var H=class{constructor(e,t,n,r,i){if(typeof e==`object`)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&n!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:r,priority:i};else throw TypeError(`Unsupported options: provide at least width, height and maxBitrate`)}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}},Hc=[`vp8`,`h264`],Uc=[`vp8`,`h264`,`vp9`,`av1`,`h265`];function Wc(e){return!!Hc.find(t=>t===e)}var Gc=Wc,Kc;(function(e){e[e.PREFER_REGRESSION=0]=`PREFER_REGRESSION`,e[e.SIMULCAST=1]=`SIMULCAST`,e[e.REGRESSION=2]=`REGRESSION`})(Kc||={});var qc;(function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:24e3},e.music={maxBitrate:48e3},e.musicStereo={maxBitrate:64e3},e.musicHighQuality={maxBitrate:96e3},e.musicHighQualityStereo={maxBitrate:128e3}})(qc||={});var Jc={h90:new H(160,90,9e4,20),h180:new H(320,180,16e4,20),h216:new H(384,216,18e4,20),h360:new H(640,360,45e4,20),h540:new H(960,540,8e5,25),h720:new H(1280,720,17e5,30),h1080:new H(1920,1080,3e6,30),h1440:new H(2560,1440,5e6,30),h2160:new H(3840,2160,8e6,30)},Yc={h120:new H(160,120,7e4,20),h180:new H(240,180,125e3,20),h240:new H(320,240,14e4,20),h360:new H(480,360,33e4,20),h480:new H(640,480,5e5,20),h540:new H(720,540,6e5,25),h720:new H(960,720,13e5,30),h1080:new H(1440,1080,23e5,30),h1440:new H(1920,1440,38e5,30)},Xc={h360fps3:new H(640,360,2e5,3,`medium`),h360fps15:new H(640,360,4e5,15,`medium`),h720fps5:new H(1280,720,8e5,5,`medium`),h720fps15:new H(1280,720,15e5,15,`medium`),h720fps30:new H(1280,720,2e6,30,`medium`),h1080fps15:new H(1920,1080,25e5,15,`medium`),h1080fps30:new H(1920,1080,5e6,30,`medium`),original:new H(0,0,7e6,30,`medium`)};function Zc(e,t,n){var r,i;let{optionsWithoutProcessor:a,audioProcessor:o,videoProcessor:s}=ll(e??{}),c=t?.processor,l=n?.processor,u=a??{};return u.audio===!0&&(u.audio={}),u.video===!0&&(u.video={}),u.audio&&(Qc(u.audio,t),(r=u.audio).deviceId??(r.deviceId={ideal:`default`}),(o||c)&&(u.audio.processor=o??c)),u.video&&(Qc(u.video,n),(i=u.video).deviceId??(i.deviceId={ideal:`default`}),(s||l)&&(u.video.processor=s??l)),u}function Qc(e,t){return Object.keys(t).forEach(n=>{e[n]===void 0&&(e[n]=t[n])}),e}function $c(e){var t,n;let r={};if(e.video)if(typeof e.video==`object`){let n={},i=n,a=e.video;Object.keys(a).forEach(e=>{switch(e){case`resolution`:Qc(i,a.resolution);break;default:i[e]=a[e]}}),r.video=n,(t=r.video).deviceId??(t.deviceId={ideal:`default`})}else r.video=e.video?{deviceId:{ideal:`default`}}:!1;else r.video=!1;return e.audio?typeof e.audio==`object`?(r.audio=e.audio,(n=r.audio).deviceId??(n.deviceId={ideal:`default`})):r.audio={deviceId:{ideal:`default`}}:r.audio=!1,r}function el(e){return F(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){let n=tl();if(n){let r=n.createAnalyser();r.fftSize=2048;let i=r.frequencyBinCount,a=new Uint8Array(i);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield xl(t),r.getByteTimeDomainData(a);let o=a.some(e=>e!==128&&e!==0);return n.close(),!o}return!1}()})}function tl(){let e=typeof window<`u`&&(window.AudioContext||window.webkitAudioContext);if(e){let t=new e({latencyHint:`interactive`});if(t.state===`suspended`&&typeof window<`u`&&window.document?.body){let e=()=>F(this,void 0,void 0,function*(){var n;try{t.state===`suspended`&&(yield t.resume())}catch(e){console.warn(`Error trying to auto-resume audio context`,e)}finally{(n=window.document.body)==null||n.removeEventListener(`click`,e)}});t.addEventListener(`statechange`,()=>{var n;t.state===`closed`&&((n=window.document.body)==null||n.removeEventListener(`click`,e))}),window.document.body.addEventListener(`click`,e)}return t}}function nl(e){return e===`audioinput`?W.Source.Microphone:e===`videoinput`?W.Source.Camera:W.Source.Unknown}function rl(e){if(e===W.Source.Microphone)return`audioinput`;if(e===W.Source.Camera)return`videoinput`}function il(e){let t=e.video??!0;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(t=typeof t==`boolean`?{}:t,t=jl()?Object.assign(Object.assign({},t),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},t),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:e.audio??!1,video:t,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}function al(e){return e.split(`/`)[1].toLowerCase()}function ol(e){let t=[];return e.forEach(e=>{e.track!==void 0&&t.push(new Ka({cid:e.track.mediaStreamID,track:e.trackInfo}))}),t}function U(e){return`mediaStreamTrack`in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?U(e.track):{})}}function sl(){return typeof RTCRtpReceiver<`u`&&`getSynchronizationSources`in RTCRtpReceiver}function cl(e,t){e===void 0&&(e={}),t===void 0&&(t={});let n=[...Object.keys(t),...Object.keys(e)],r={};for(let i of n)e[i]!==t[i]&&(r[i]=t[i]??``);return r}function ll(e){let t=Object.assign({},e),n,r;return typeof t.audio==`object`&&t.audio.processor&&(n=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),typeof t.video==`object`&&t.video.processor&&(r=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:n,videoProcessor:r,optionsWithoutProcessor:Vc(t)}}function ul(e){switch(e){case ji.CAMERA:return W.Source.Camera;case ji.MICROPHONE:return W.Source.Microphone;case ji.SCREEN_SHARE:return W.Source.ScreenShare;case ji.SCREEN_SHARE_AUDIO:return W.Source.ScreenShareAudio;default:return W.Source.Unknown}}function dl(e,t){return e.width*e.height<t.width*t.height}function fl(e,t){return e.layers?.find(e=>e.quality===t)}var pl=5e3,ml=[],hl;(function(e){e[e.LOW=0]=`LOW`,e[e.MEDIUM=1]=`MEDIUM`,e[e.HIGH=2]=`HIGH`})(hl||={});var W=class e extends ss.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.attachedElements=[],this.isMuted=!1,this._streamState=e.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=P,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState===`hidden`?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),pl):this.handleAppVisibilityChanged()},this.log=qo(r.loggerName??Ko.Track),this.loggerContextCb=r.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=e.Source.Unknown}get logContext(){return Object.assign(Object.assign({},this.loggerContextCb?.call(this)),U(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let n=`audio`;this.kind===e.Kind.Video&&(n=`video`),this.attachedElements.length===0&&this.kind===e.Kind.Video&&this.addAppVisibilityListener(),t||(n===`audio`&&(ml.forEach(e=>{e.parentElement===null&&!t&&(t=e)}),t&&ml.splice(ml.indexOf(t),1)),t||=document.createElement(n)),this.attachedElements.includes(t)||this.attachedElements.push(t),gl(this.mediaStreamTrack,t);let r=t.srcObject.getTracks(),i=r.some(e=>e.kind===`audio`);return t.play().then(()=>{this.emit(i?V.AudioPlaybackStarted:V.VideoPlaybackStarted)}).catch(e=>{e.name===`NotAllowedError`?this.emit(i?V.AudioPlaybackFailed:V.VideoPlaybackFailed,e):e.name===`AbortError`?P.debug(`${i?`audio`:`video`} playback aborted, likely due to new play request`):P.warn(`could not playback ${i?`audio`:`video`}`,e),i&&t&&r.some(e=>e.kind===`video`)&&e.name===`NotAllowedError`&&(t.muted=!0,t.play().catch(()=>{}))}),this.emit(V.ElementAttached,t),t}detach(e){try{if(e){_l(this.mediaStreamTrack,e);let t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(V.ElementDetached,e)),e}let t=[];return this.attachedElements.forEach(e=>{_l(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(V.ElementDetached,e)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=qo(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),ml.forEach(e=>{e.parentElement||(t=!1)}),t&&ml.push(e)}}handleAppVisibilityChanged(){return F(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState===`hidden`,!this.isInBackground&&this.kind===e.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Ll()?(this.isInBackground=document.visibilityState===`hidden`,document.addEventListener(`visibilitychange`,this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Ll()&&document.removeEventListener(`visibilitychange`,this.appVisibilityChangedListener)}};function gl(e,t){let n;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream;let r;r=e.kind===`audio`?n.getAudioTracks():n.getVideoTracks(),r.includes(e)||(r.forEach(e=>{n.removeTrack(e)}),n.addTrack(e)),(!jl()||!(t instanceof HTMLVideoElement))&&(t.autoplay=!0),t.muted=n.getAudioTracks().length===0,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(jl()||kl())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=n,t.play().catch(()=>{})},0))}function _l(e,t){if(t.srcObject instanceof MediaStream){let n=t.srcObject;n.removeTrack(e),n.getTracks().length>0?t.srcObject=n:t.srcObject=null}}(function(e){let t;(function(e){e.Audio=`audio`,e.Video=`video`,e.Unknown=`unknown`})(t=e.Kind||={});let n;(function(e){e.Camera=`camera`,e.Microphone=`microphone`,e.ScreenShare=`screen_share`,e.ScreenShareAudio=`screen_share_audio`,e.Unknown=`unknown`})(n=e.Source||={});let r;(function(e){e.Active=`active`,e.Paused=`paused`,e.Unknown=`unknown`})(r=e.StreamState||={});function i(e){switch(e){case t.Audio:return Ai.AUDIO;case t.Video:return Ai.VIDEO;default:return Ai.DATA}}e.kindToProto=i;function a(e){switch(e){case Ai.AUDIO:return t.Audio;case Ai.VIDEO:return t.Video;default:return t.Unknown}}e.kindFromProto=a;function o(e){switch(e){case n.Camera:return ji.CAMERA;case n.Microphone:return ji.MICROPHONE;case n.ScreenShare:return ji.SCREEN_SHARE;case n.ScreenShareAudio:return ji.SCREEN_SHARE_AUDIO;default:return ji.UNKNOWN}}e.sourceToProto=o;function s(e){switch(e){case ji.CAMERA:return n.Camera;case ji.MICROPHONE:return n.Microphone;case ji.SCREEN_SHARE:return n.ScreenShare;case ji.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}}e.sourceFromProto=s;function c(e){switch(e){case Aa.ACTIVE:return r.Active;case Aa.PAUSED:return r.Paused;default:return r.Unknown}}e.streamStateFromProto=c})(W||={});var vl=`|`,yl=`https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension`;function bl(e){let t=e.split(vl);return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,``]}function xl(e){return new yc(t=>Bc.setTimeout(t,e))}function Sl(){return`addTransceiver`in RTCPeerConnection.prototype}function Cl(){return`addTrack`in RTCPeerConnection.prototype}function wl(){if(!(`getCapabilities`in RTCRtpSender)||jl()||kl())return!1;let e=RTCRtpSender.getCapabilities(`video`),t=!1;if(e){for(let n of e.codecs)if(n.mimeType.toLowerCase()===`video/av1`){t=!0;break}}return t}function Tl(){if(!(`getCapabilities`in RTCRtpSender)||kl())return!1;if(jl()){let e=Sc();if(e?.version&&Wl(e.version,`16`)<0||e?.os===`iOS`&&e?.osVersion&&Wl(e.osVersion,`16`)<0)return!1}let e=RTCRtpSender.getCapabilities(`video`),t=!1;if(e){for(let n of e.codecs)if(n.mimeType.toLowerCase()===`video/vp9`){t=!0;break}}return t}function El(e){return e===`av1`||e===`vp9`}function Dl(e){return!document||Ml()?!1:(e||=document.createElement(`audio`),`setSinkId`in e)}function Ol(){return typeof RTCPeerConnection>`u`?!1:Sl()||Cl()}function kl(){return Sc()?.name===`Firefox`}function Al(){let e=Sc();return!!e&&e.name===`Chrome`&&e.os!==`iOS`}function jl(){return Sc()?.name===`Safari`}function Ml(){let e=Sc();return e?.name===`Safari`||e?.os===`iOS`}function Nl(){let e=Sc();return e?.name===`Safari`&&e.version.startsWith(`17.`)||e?.os===`iOS`&&!!e?.osVersion&&Wl(e.osVersion,`17`)>=0}function Pl(e){return e||=Sc(),e?.name===`Safari`&&Wl(e.version,`18.3`)>0||e?.os===`iOS`&&!!e?.osVersion&&Wl(e.osVersion,`18.3`)>0}function Fl(){return Ll()?navigator.userAgentData?.mobile??/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function Il(){let e=Sc(),t=`17.2`;if(e)return e.name!==`Safari`&&e.os!==`iOS`||e.os===`iOS`&&e.osVersion&&Wl(e.osVersion,t)>=0?!0:e.name===`Safari`&&Wl(e.version,t)>=0}function Ll(){return typeof document<`u`}function Rl(){return navigator.product==`ReactNative`}function zl(e){return e.hostname.endsWith(`.livekit.cloud`)||e.hostname.endsWith(`.livekit.run`)}function Bl(e){return zl(e)?e.hostname.split(`.`)[0]:null}function Vl(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Hl(){if(!Rl())return;let e=Vl();if(e)return e.platform}function Ul(){if(Ll())return window.devicePixelRatio;if(Rl()){let e=Vl();if(e)return e.devicePixelRatio}return 1}function Wl(e,t){let n=e.split(`.`),r=t.split(`.`),i=Math.min(n.length,r.length);for(let e=0;e<i;++e){let t=parseInt(n[e],10),a=parseInt(r[e],10);if(t>a)return 1;if(t<a)return-1;if(e===i-1&&t===a)return 0}return e===``&&t!==``?-1:t===``?1:n.length==r.length?0:n.length<r.length?-1:1}function Gl(e){for(let t of e)t.target.handleResize(t)}function Kl(e){for(let t of e)t.target.handleVisibilityChanged(t)}var ql=null,Jl=()=>(ql||=new ResizeObserver(Gl),ql),Yl=null,Xl=()=>(Yl||=new IntersectionObserver(Kl,{root:null,rootMargin:`0px`}),Yl);function Zl(){let e=new ga({sdk:_a.JS,protocol:16,version:Ec});return Rl()&&(e.os=Hl()??``),e}function Ql(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,i=document.createElement(`canvas`);i.width=e,i.height=t;let a=i.getContext(`2d`);a?.fillRect(0,0,i.width,i.height),r&&a&&(a.beginPath(),a.arc(e/2,t/2,50,0,Math.PI*2,!0),a.closePath(),a.fillStyle=`grey`,a.fill());let[o]=i.captureStream().getTracks();if(!o)throw Error(`Could not get empty media stream video track`);return o.enabled=n,o}var $l;function eu(){if(!$l){let e=new AudioContext,t=e.createOscillator(),n=e.createGain();n.gain.setValueAtTime(0,0);let r=e.createMediaStreamDestination();if(t.connect(n),n.connect(r),t.start(),[$l]=r.stream.getAudioTracks(),!$l)throw Error(`Could not get empty media stream audio track`);$l.enabled=!1}return $l.clone()}var tu=class{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,n)=>F(this,void 0,void 0,function*(){this.resolve=t,this.reject=n,e&&(yield e(t,n))})).finally(()=>{var e;this._isResolved=!0,(e=this.onFinally)==null||e.call(this)})}};function nu(e){return Uc.includes(e)}function ru(e){if(typeof e==`string`||typeof e==`number`)return e;if(Array.isArray(e))return e[0];if(e.exact!==void 0)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal!==void 0)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error(`could not unwrap constraint`)}function iu(e){return e.startsWith(`http`)?e.replace(/^(http)/,`ws`):e}function au(e){return e.startsWith(`ws`)?e.replace(/^(ws)/,`http`):e}function ou(e,t){return e.segments.map(e=>{let{id:n,text:r,language:i,startTime:a,endTime:o,final:s}=e,c=t.get(n)??Date.now(),l=Date.now();return s?t.delete(n):t.set(n,c),{id:n,text:r,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:s,language:i,firstReceivedTime:c,lastReceivedTime:l}})}function su(e){let{id:t,timestamp:n,message:r,editTimestamp:i}=e;return{id:t,timestamp:Number.parseInt(n.toString()),editTimestamp:i?Number.parseInt(i.toString()):void 0,message:r}}function cu(e){switch(e.reason){case I.LeaveRequest:return e.context;case I.Cancelled:return Fi.CLIENT_INITIATED;case I.NotAllowed:return Fi.USER_REJECTED;case I.ServerUnreachable:return Fi.JOIN_FAILURE;default:return Fi.UNKNOWN_REASON}}function lu(e){return e===void 0?void 0:Number(e)}function uu(e){return e===void 0?void 0:BigInt(e)}function du(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function fu(e){return!!e&&e.kind==W.Kind.Audio}function pu(e){return!!e&&e.kind==W.Kind.Video}function mu(e){return du(e)&&pu(e)}function hu(e){return du(e)&&fu(e)}function gu(e){return!!e&&!e.isLocal}function _u(e){return!!e&&!e.isLocal}function vu(e){return gu(e)&&pu(e)}function yu(e){return e.isLocal}function bu(e,t){let n=[],r=new TextEncoder().encode(e);for(;r.length>t;){let e=t;for(;e>0;){let t=r[e];if(t!==void 0&&(t&192)!=128)break;e--}n.push(r.slice(0,e)),r=r.slice(e)}return r.length>0&&n.push(r),n}function xu(e){let t=e.get(`Cache-Control`);if(t){let e=t.match(/(?:^|[,\s])max-age=(\d+)/)?.[1];if(e)return parseInt(e,10)}}function Su(){return typeof CompressionStream<`u`}function Cu(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=wu(e,t);return n?r:Du(r,`v1`)}function wu(e,t){let n=new URL(iu(e));return t.forEach((e,t)=>{n.searchParams.set(t,e)}),Du(n,`rtc`)}function Tu(e){return Du(new URL(au(e)),`validate`)}function Eu(e){return e.endsWith(`/`)?e:`${e}/`}function Du(e,t){return e.pathname=`${Eu(e.pathname)}${t}`,e}function Ou(e){if(typeof e==`string`)return Na.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return Na.fromBinary(new Uint8Array(e));throw Error(`could not decode websocket message: ${typeof e}`)}function ku(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Unknown reason`;if(!(e instanceof AbortSignal))return t;let n=e.reason;switch(typeof n){case`string`:return n;case`object`:return n instanceof Error?n.message:t;default:return`toString`in n?n.toString():t}}var Au=`lk_e2ee`,ju;(function(e){e.SetKey=`setKey`,e.RatchetRequest=`ratchetRequest`,e.KeyRatcheted=`keyRatcheted`})(ju||={});var Mu;(function(e){e.KeyRatcheted=`keyRatcheted`})(Mu||={});var Nu;(function(e){e.ParticipantEncryptionStatusChanged=`participantEncryptionStatusChanged`,e.EncryptionError=`encryptionError`})(Nu||={});var Pu;(function(e){e.Error=`cryptorError`})(Pu||={});function Fu(){return Lu()||Iu()}function Iu(){return window.RTCRtpScriptTransform!==void 0}function Lu(){return window.RTCRtpSender!==void 0&&window.RTCRtpSender.prototype.createEncodedStreams!==void 0}function Ru(e){if(e.value?.case!==`sipDtmf`&&e.value?.case!==`metrics`&&e.value?.case!==`speaker`&&e.value?.case!==`transcription`&&e.value?.case!==`encryptedPacket`)return new ta({value:e.value})}ss.EventEmitter;var zu;(function(e){e[e.InvalidKey=0]=`InvalidKey`,e[e.MissingKey=1]=`MissingKey`,e[e.InternalError=2]=`InternalError`})(zu||={});var Bu=class extends ss.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=e=>{let{kind:t,data:n}=e.data;switch(t){case`error`:if(P.error(n.error.message),n.uuid){let e=this.decryptDataRequests.get(n.uuid);if(e?.reject){e.reject(n.error);break}let t=this.encryptDataRequests.get(n.uuid);if(t?.reject){t.reject(n.error);break}}this.emit(Nu.EncryptionError,n.error,n.participantIdentity);break;case`initAck`:n.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)});break;case`enable`:if(n.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)}),this.encryptionEnabled!==n.enabled&&n.participantIdentity===this.room?.localParticipant.identity)this.emit(Nu.ParticipantEncryptionStatusChanged,n.enabled,this.room.localParticipant),this.encryptionEnabled=n.enabled;else if(n.participantIdentity){let e=this.room?.getParticipantByIdentity(n.participantIdentity);if(!e)throw TypeError(`couldn't set encryption status, participant not found${n.participantIdentity}`);this.emit(Nu.ParticipantEncryptionStatusChanged,n.enabled,e)}break;case`ratchetKey`:this.keyProvider.emit(ju.KeyRatcheted,n.ratchetResult,n.participantIdentity,n.keyIndex);break;case`decryptDataResponse`:let e=this.decryptDataRequests.get(n.uuid);e?.resolve&&e.resolve(n);break;case`encryptDataResponse`:let t=this.encryptDataRequests.get(n.uuid);t?.resolve&&t.resolve(n);break}},this.onWorkerError=e=>{P.error(`e2ee worker encountered an error:`,{error:e.error}),this.emit(Nu.EncryptionError,e.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!Fu())throw new kc(`tried to setup end-to-end encryption on an unsupported browser`);if(P.info(`setting up e2ee`),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);let t={kind:`init`,data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Jo.getLevel()}};this.worker&&(P.info(`initializing worker`,{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){P.debug(`set e2ee to ${e} for participant ${t}`),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?P.warn(`ignoring server sent trailer as it's empty`):this.postSifTrailer(e)}setupEngine(e){e.on(B.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(R.TrackPublished,(e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==N.NONE,t.identity)),e.on(R.ConnectionStateChanged,t=>{t===q.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==N.NONE,e.identity)})})}).on(R.TrackUnsubscribed,(e,t,n)=>{var r;let i={kind:`removeTransform`,data:{participantIdentity:n.identity,trackId:e.mediaStreamID}};(r=this.worker)==null||r.postMessage(i)}).on(R.TrackSubscribed,(e,t,n)=>{this.setupE2EEReceiver(e,n.identity,t.trackInfo)}).on(R.SignalConnected,()=>{if(!this.room)throw TypeError(`expected room to be present on signal connect`);let e=t.getLatestManuallySetKeyIndex();t.getKeys().forEach(t=>{this.postKey(t,e===(t.keyIndex??0))}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(z.LocalSenderCreated,(e,t)=>F(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),e.localParticipant.on(z.LocalTrackPublished,e=>{if(!pu(e.track)||!Ml())return;let t={kind:`updateCodec`,data:{trackId:e.track.mediaStreamID,codec:al(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}),t.on(ju.SetKey,(e,t)=>this.postKey(e,t??!0)).on(ju.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}encryptData(e){return F(this,void 0,void 0,function*(){if(!this.worker)throw Error(`could not encrypt data, worker is missing`);let t=crypto.randomUUID(),n={kind:`encryptDataRequest`,data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},r=new tu;return r.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,r),this.worker.postMessage(n),r.promise})}handleEncryptedData(e,t,n,r){if(!this.worker)throw Error(`could not handle encrypted data, worker is missing`);let i=crypto.randomUUID(),a={kind:`decryptDataRequest`,data:{uuid:i,payload:e,iv:t,participantIdentity:n,keyIndex:r}},o=new tu;return o.onFinally=()=>{this.decryptDataRequests.delete(i)},this.decryptDataRequests.set(i,o),this.worker.postMessage(a),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error(`could not ratchet key, worker is missing`);let n={kind:`ratchetRequest`,data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e,t){let{key:n,participantIdentity:r,keyIndex:i}=e;if(!this.worker)throw Error(`could not set key, worker is missing`);let a={kind:`setKey`,data:{participantIdentity:r,isPublisher:r===this.room?.localParticipant.identity,key:n,keyIndex:i,updateCurrentKeyIndex:t}};this.worker.postMessage(a)}postEnable(e,t){if(this.worker){let n={kind:`enable`,data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}else throw ReferenceError(`failed to enable e2ee, worker is not ready`)}postRTPMap(e){if(!this.worker)throw TypeError(`could not post rtp map, worker is missing`);if(!this.room?.localParticipant.identity)throw TypeError(`could not post rtp map, local participant identity is missing`);let t={kind:`setRTPMap`,data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}postSifTrailer(e){if(!this.worker)throw Error(`could not post SIF trailer, worker is missing`);let t={kind:`setSifTrailer`,data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,n){if(e.receiver){if(!n?.mimeType||n.mimeType===``)throw TypeError(`MimeType missing from trackInfo, cannot set up E2EE cryptor`);this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind===`video`?al(n.mimeType):void 0)}}setupE2EESender(e,t){if(!du(e)||!t){t||P.warn(`early return because sender is not ready`);return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,n,r){return F(this,void 0,void 0,function*(){if(this.worker){if(Iu()&&!Al()){let i={kind:`decode`,participantIdentity:n,trackId:t,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,i)}else{if(Au in e&&r){let e={kind:`updateCodec`,data:{trackId:t,codec:r,participantIdentity:n}};this.worker.postMessage(e);return}let i=e.writableStream,a=e.readableStream;if(!i||!a){let t=e.createEncodedStreams();e.writableStream=t.writable,i=t.writable,e.readableStream=t.readable,a=t.readable}let o={kind:`decode`,data:{readableStream:a,writableStream:i,trackId:t,codec:r,participantIdentity:n,isReuse:Au in e}};this.worker.postMessage(o,[a,i])}e[Au]=!0}})}handleSender(e,t,n){if(!(Au in e||!this.worker)){if(!this.room?.localParticipant.identity||this.room.localParticipant.identity===``)throw TypeError(`local identity needs to be known in order to set up encrypted sender`);if(Iu()&&!Al()){P.info(`initialize script transform`);let r={kind:`encode`,participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{P.info(`initialize encoded streams`);let r=e.createEncodedStreams(),i={kind:`encode`,data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(i,[r.readable,r.writable])}e[Au]=!0}}},Vu=500,Hu=15e3,Uu=class e{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||=new e,this._instance}addFailedConnectionAttempt(e){let t=Bl(new URL(e));if(!t)return;let n=this.failedConnectionAttempts.get(t)??0;this.failedConnectionAttempts.set(t,n+1),this.backOffPromises.set(t,xl(Math.min(Vu*2**n,Hu)))}getBackOffPromise(e){let t=new URL(e),n=t&&Bl(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){let t=new URL(e),n=t&&Bl(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}};Uu._instance=null;var Wu=`default`,Gu=class e{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new e),this.instance}get previousDevices(){return this._previousDevices}getDevices(t){return F(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){if(e.userMediaPromiseMap?.size>0){P.debug(`awaiting getUserMedia promise`);try{t?yield e.userMediaPromiseMap.get(t):yield Promise.all(e.userMediaPromiseMap.values())}catch{P.warn(`error waiting for media permissons`)}}let i=yield navigator.mediaDevices.enumerateDevices();if(r&&!(jl()&&n.hasDeviceInUse(t))&&(i.filter(e=>e.kind===t).length===0||i.some(e=>{let n=e.label===``,r=t?e.kind===t:!0;return n&&r}))){let e={video:t!==`audioinput`&&t!==`audiooutput`,audio:t!==`videoinput`&&{deviceId:{ideal:`default`}}},n=yield navigator.mediaDevices.getUserMedia(e);i=yield navigator.mediaDevices.enumerateDevices(),n.getTracks().forEach(e=>{e.stop()})}return n._previousDevices=i,t&&(i=i.filter(e=>e.kind===t)),i}()})}normalizeDeviceId(e,t,n){return F(this,void 0,void 0,function*(){if(t!==Wu)return t;let r=yield this.getDevices(e),i=r.find(e=>e.deviceId===Wu);if(!i){P.warn(`could not reliably determine default device`);return}let a=r.find(e=>e.deviceId!==Wu&&e.groupId===(n??i.groupId));if(!a){P.warn(`could not reliably determine default device`);return}return a?.deviceId})}hasDeviceInUse(t){return t?e.userMediaPromiseMap.has(t):e.userMediaPromiseMap.size>0}};Gu.mediaDeviceKinds=[`audioinput`,`audiooutput`,`videoinput`],Gu.userMediaPromiseMap=new Map;var Ku=65535,qu=4294967295,Ju=class e{static u16(t){return new e(t,Ku)}static u32(t){return new e(t,qu)}constructor(e,t){if(this.value=e,e<0)throw Error(`WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0`);if(t>2**53-1)throw Error(`WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.`);this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new e(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t+e)}decrement(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t-e)}getThenIncrement(){let t=this.value;return this.increment(),new e(t,this.maxSize)}isBefore(e){let t=this.value>>>0,n=(e.value>>>0)-t>>>0;return n!==0&&n<this.maxSize+1}},Yu=class e{static fromRtpTicks(t){return new e(t,9e4)}static rtpRandom(){let t=Math.round(Math.random()*qu);return e.fromRtpTicks(t)}constructor(e,t){this.timestamp=Ju.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new e(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}},Xu=class e{constructor(e,t,n){this.epoch=t,this.base=n,this.previous=n.clone(),this.rateInHz=e}static startingNow(t,n){return new e(n,new Date,t)}static startingAtTime(t,n,r){return new e(r,t,n)}static rtpStartingNow(t){return e.startingNow(t,9e4)}static rtpStartingAtTime(t,n){return e.startingAtTime(t,n,9e4)}now(){return this.at(new Date)}at(t){let n=t.getTime()-this.epoch.getTime(),r=e.durationInMsToTicks(n,this.rateInHz),i=this.base.clone();return i.wrappingAdd(r),i.isBefore(this.previous)&&(i=this.previous),this.previous=i.clone(),i.clone()}static durationInMsToTicks(e,t){let n=(e*1e6*t+5e8)/1e9;return Math.round(n)}};function Zu(e){if(e instanceof DataView)return e;if(e instanceof ArrayBuffer)return new DataView(e);if(e instanceof Uint8Array)return new DataView(e.buffer,e.byteOffset,e.byteLength);throw Error(`Error coercing ${e} to DataView - input was not DataView, ArrayBuffer, or Uint8Array.`)}var Qu;(function(e){e[e.Reserved=0]=`Reserved`,e[e.TooLarge=1]=`TooLarge`})(Qu||={});var $u=class e extends Oc{constructor(e,t){super(19,e),this.name=`DataTrackHandleError`,this.reason=t,this.reasonName=Qu[t]}isReason(e){return this.reason===e}static tooLarge(){return new e(`Value too large to be a valid track handle`,Qu.TooLarge)}static reserved(t){return new e(`0x${t.toString(16)} is a reserved value.`,Qu.Reserved)}},ed={fromNumber(e){if(e===0)throw $u.reserved(e);if(e>Ku)throw $u.tooLarge();return e}},td=class{constructor(){this.value=0}get(){return this.value+=1,this.value>Ku?null:this.value}},nd={from(e){return{sid:e.sid,pubHandle:e.pubHandle,name:e.name,usesE2ee:e.encryption!==N.NONE}},toProtobuf(e){return new Ji({sid:e.sid,pubHandle:e.pubHandle,name:e.name,encryption:e.usesE2ee?N.GCM:N.NONE})}},rd;(function(e){e[e.WAITING=0]=`WAITING`,e[e.RUNNING=1]=`RUNNING`,e[e.COMPLETED=2]=`COMPLETED`})(rd||={});var id=class{constructor(){this.pendingTasks=new Map,this.taskMutex=new kn,this.nextTaskIndex=0}run(e){return F(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:rd.WAITING};this.pendingTasks.set(t.id,t);let n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=rd.RUNNING,yield e()}finally{t.status=rd.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return F(this,void 0,void 0,function*(){return this.run(()=>F(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}},ad=class{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(t.signal?.aborted)throw new DOMException(`This operation was aborted`,`AbortError`);this.url=e;let n=new WebSocket(e,t.protocols??[]);n.binaryType=`arraybuffer`,this.ws=n;let r=function(){let{closeCode:e,reason:t}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return n.close(e,t)};this.opened=new yc((e,t)=>{let i=()=>{t(L.websocket(`Encountered websocket error during connection establishment`))};n.onopen=()=>{e({readable:new ReadableStream({start(e){n.onmessage=t=>{let{data:n}=t;return e.enqueue(n)},n.onerror=t=>e.error(t)},cancel:r}),writable:new WritableStream({write(e){n.send(e)},abort(){n.close()},close:r}),protocol:n.protocol,extensions:n.extensions}),n.removeEventListener(`error`,i)},n.addEventListener(`error`,i)}),this.closed=new yc((e,t)=>{let r=()=>F(this,void 0,void 0,function*(){let r=new yc(e=>{n.readyState!==WebSocket.CLOSED&&n.addEventListener(`close`,t=>{e(t)},{once:!0})}),i=yield yc.race([xl(250),r]);i?e(i):t(L.websocket(`Encountered unspecified websocket error without a timely close event`))});n.onclose=t=>{let{code:i,reason:a}=t;e({closeCode:i,reason:a}),n.removeEventListener(`error`,r)},n.addEventListener(`error`,r)}),t.signal&&(t.signal.onabort=()=>n.close()),this.close=r}},od=[`syncState`,`trickle`,`offer`,`answer`,`simulate`,`leave`];function sd(e){let t=od.indexOf(e.case)>=0;return P.trace(`request allowed to bypass queue:`,{canPass:t,req:e}),t}var G;(function(e){e[e.CONNECTING=0]=`CONNECTING`,e[e.CONNECTED=1]=`CONNECTED`,e[e.RECONNECTING=2]=`RECONNECTING`,e[e.DISCONNECTING=3]=`DISCONNECTING`,e[e.DISCONNECTED=4]=`DISCONNECTED`})(G||={});var cd=250,ld=class{get currentState(){return this.state}get isDisconnected(){return this.state===G.DISCONNECTING||this.state===G.DISCONNECTED}get isEstablishingConnection(){return this.state===G.CONNECTING||this.state===G.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.rtt=0,this.state=G.DISCONNECTED,this.log=P,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=qo(t.loggerName??Ko.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new id,this.queuedRequests=[],this.closingLock=new kn,this.connectionLock=new kn,this.state=G.DISCONNECTED}get logContext(){return this.loggerContextCb?.call(this)??{}}join(e,t,n,r){return F(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,o=arguments.length>5?arguments[5]:void 0;return function*(){return i.state=G.CONNECTING,i.options=n,yield i.connect(e,t,n,r,a,o)}()})}reconnect(e,t,n,r){return F(this,void 0,void 0,function*(){if(!this.options){this.log.warn(`attempted to reconnect without signal options being set, ignoring`,this.logContext);return}return this.state=G.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:r}),void 0,this.useV0SignalPath)})}connect(e,t,n,r){return F(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,o=arguments.length>5?arguments[5]:void 0;return function*(){let s=yield i.connectionLock.lock();i.connectOptions=n,i.useV0SignalPath=a;let c=Zl(),l=Cu(e,a?fd(t,c,n):yield pd(t,c,n,o),a).toString(),u=Tu(l).toString();return new Promise((e,t)=>F(i,void 0,void 0,function*(){try{let i=!1,a=e=>F(this,void 0,void 0,function*(){if(i)return;i=!0;let n=ku(e instanceof Event?e.currentTarget:e,`Abort handler called`);this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(n)).catch(e=>{this.log.error(e),this.close()}):this.close(),o(),t(L.cancelled(n))});r?.addEventListener(`abort`,a);let o=()=>{clearTimeout(s),r?.removeEventListener(`abort`,a)},s=setTimeout(()=>{a(L.timeout(`room connection has timed out (signal)`))},n.websocketTimeout),c=(e,t)=>{this.handleSignalConnected(e,s,t)},d=new URL(l);d.searchParams.has(`access_token`)&&d.searchParams.set(`access_token`,`<redacted>`),this.log.debug(`connecting to ${d}`,Object.assign({reconnect:n.reconnect,reconnectReason:n.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new ad(l);try{this.ws.closed.then(e=>{this.isEstablishingConnection&&t(L.internal(`Websocket got closed during a (re)connection attempt: ${e.reason}`)),e.closeCode!==1e3&&(this.log.warn(`websocket closed`,Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.closeCode,wasClean:e.closeCode===1e3,state:this.state})),this.state===G.CONNECTED&&this.handleOnClose(e.reason??`Unexpected WS error`))}).catch(e=>{this.isEstablishingConnection&&t(L.internal(`Websocket error during a (re)connection attempt: ${e}`))});let r=yield this.ws.opened.catch(e=>F(this,void 0,void 0,function*(){if(this.state!==G.CONNECTED){this.state=G.DISCONNECTED,clearTimeout(s),t(yield this.handleConnectionError(e,u));return}this.handleWSError(e),t(e)}));if(clearTimeout(s),!r)return;let i=r.readable.getReader();this.streamWriter=r.writable.getWriter();let a=yield i.read();if(i.releaseLock(),!a.value)throw L.internal(`no message received as first message`);let o=Ou(a.value),l=this.validateFirstMessage(o,n.reconnect??!1);if(!l.isValid){t(l.error);return}o.message?.case===`join`&&(this.pingTimeoutDuration=o.message.value.pingTimeout,this.pingIntervalDuration=o.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug(`ping config`,Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.onJoined&&this.onJoined(o.message.value)),c(r,l.shouldProcessFirstMessage?o:void 0),e(l.response)}catch(e){t(e)}finally{o()}}finally{s()}}))}()})}startReadingLoop(e,t){return F(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield xl(this.signalLatency));let{done:t,value:n}=yield e.read();if(t)break;let r=Ou(n);this.handleSignalResponse(r)}})}close(){return F(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Close method called on signal client`;return function*(){if([G.DISCONNECTING||G.DISCONNECTED].includes(e.state)){e.log.debug(`ignoring signal close as it's already in disconnecting state`);return}let r=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=G.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:n});let t=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([t,xl(cd)])}}catch(t){e.log.debug(`websocket error while closing`,Object.assign(Object.assign({},e.logContext),{error:t}))}finally{t&&(e.state=G.DISCONNECTED),r()}}()})}sendOffer(e,t){this.log.debug(`sending offer`,Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:`offer`,value:dd(e,t)})}sendAnswer(e,t){return this.log.debug(`sending answer`,Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:`answer`,value:dd(e,t)})}sendIceCandidate(e,t){return this.log.debug(`sending ice candidate`,Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:`trickle`,value:new Ha({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:`mute`,value:new Ua({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:`addTrack`,value:e})}sendUpdateLocalMetadata(e,t){return F(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){let i=n.getNextRequestId();return yield n.sendRequest({case:`updateMetadata`,value:new ao({requestId:i,metadata:e,name:t,attributes:r})}),i}()})}sendUpdateTrackSettings(e){this.sendRequest({case:`trackSetting`,value:e})}sendUpdateSubscription(e){return this.sendRequest({case:`subscription`,value:e})}sendSyncState(e){return this.sendRequest({case:`syncState`,value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:`updateLayers`,value:new io({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:`subscriptionPermission`,value:new yo({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:`simulate`,value:e})}sendPing(){return Promise.all([this.sendRequest({case:`ping`,value:or.parse(Date.now())}),this.sendRequest({case:`pingReq`,value:new Eo({timestamp:or.parse(Date.now()),rtt:or.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:`updateAudioTrack`,value:new eo({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:`leave`,value:new no({reason:Fi.CLIENT_INITIATED,action:ro.DISCONNECT})})}sendPublishDataTrackRequest(e,t,n){return this.sendRequest({case:`publishDataTrackRequest`,value:new Ia({pubHandle:e,name:t,encryption:n?N.GCM:N.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:`unpublishDataTrackRequest`,value:new Ra({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:`updateDataSubscription`,value:new Za({updates:[new Qa({trackSid:e,subscribe:t})]})})}sendRequest(e){return F(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!n&&!sd(e)&&t.state===G.RECONNECTING){t.queuedRequests.push(()=>F(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));return}if(n||(yield t.requestQueue.flush()),t.signalLatency&&(yield xl(t.signalLatency)),t.isDisconnected){t.log.debug(`skipping signal request (type: ${e.case}) - SignalClient disconnected`);return}if(!t.streamWriter){t.log.error(`cannot send signal request before connected, type: ${e?.case}`,t.logContext);return}let r=new Ma({message:e});try{t.useJSON?yield t.streamWriter.write(r.toJsonString()):yield t.streamWriter.write(r.toBinary())}catch(e){t.log.error(`error sending signal message`,Object.assign(Object.assign({},t.logContext),{error:e}))}}()})}handleSignalResponse(e){let t=e.message;if(t==null){this.log.debug(`received unsupported message`,this.logContext);return}let n=!1;if(t.case===`answer`){let e=ud(t.value);this.onAnswer&&this.onAnswer(e,t.value.id,t.value.midToTrackId)}else if(t.case===`offer`){let e=ud(t.value);this.onOffer&&this.onOffer(e,t.value.id,t.value.midToTrackId)}else if(t.case===`trickle`){let e=JSON.parse(t.value.candidateInit);this.onTrickle&&this.onTrickle(e,t.value.target)}else t.case===`update`?this.onParticipantUpdate&&this.onParticipantUpdate(t.value.participants??[]):t.case===`trackPublished`?this.onLocalTrackPublished&&this.onLocalTrackPublished(t.value):t.case===`speakersChanged`?this.onSpeakersChanged&&this.onSpeakersChanged(t.value.speakers??[]):t.case===`leave`?this.onLeave&&this.onLeave(t.value):t.case===`mute`?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(t.value.sid,t.value.muted):t.case===`roomUpdate`?this.onRoomUpdate&&t.value.room&&this.onRoomUpdate(t.value.room):t.case===`connectionQuality`?this.onConnectionQuality&&this.onConnectionQuality(t.value):t.case===`streamStateUpdate`?this.onStreamStateUpdate&&this.onStreamStateUpdate(t.value):t.case===`subscribedQualityUpdate`?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(t.value):t.case===`subscriptionPermissionUpdate`?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(t.value):t.case===`refreshToken`?this.onTokenRefresh&&this.onTokenRefresh(t.value):t.case===`trackUnpublished`?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(t.value):t.case===`subscriptionResponse`?this.onSubscriptionError&&this.onSubscriptionError(t.value):t.case===`pong`||(t.case===`pongResp`?(this.rtt=Date.now()-Number.parseInt(t.value.lastPingTimestamp.toString()),this.resetPingTimeout(),n=!0):t.case===`requestResponse`?this.onRequestResponse&&this.onRequestResponse(t.value):t.case===`trackSubscribed`?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(t.value.trackSid):t.case===`roomMoved`?(this.onTokenRefresh&&this.onTokenRefresh(t.value.token),this.onRoomMoved&&this.onRoomMoved(t.value)):t.case===`mediaSectionsRequirement`?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(t.value):t.case===`publishDataTrackResponse`?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(t.value):t.case===`unpublishDataTrackResponse`?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(t.value):t.case===`dataTrackSubscriberHandles`?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(t.value):this.log.debug(`unsupported message`,Object.assign(Object.assign({},this.logContext),{msgCase:t.case})));n||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){let e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return F(this,void 0,void 0,function*(){if(this.state===G.DISCONNECTED)return;let t=this.onClose;yield this.close(void 0,e),this.log.debug(`websocket connection closed: ${e}`,Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error(`websocket error`,Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn(`ping timeout duration not set`,this.logContext);return}this.pingTimeout=Bc.setTimeout(()=>{this.log.warn(`ping timeout triggered. last pong received at: ${new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()}`,this.logContext),this.handleOnClose(`ping timeout`)},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Bc.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn(`ping interval duration not set`,this.logContext);return}this.log.debug(`start ping interval`,this.logContext),this.pingInterval=Bc.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug(`clearing ping interval`,this.logContext),this.clearPingTimeout(),this.pingInterval&&Bc.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n){this.state=G.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),n)}validateFirstMessage(e,t){return e.message?.case===`join`?{isValid:!0,response:e.message.value}:this.state===G.RECONNECTING&&e.message?.case!==`leave`?e.message?.case===`reconnect`?{isValid:!0,response:e.message.value}:(this.log.debug(`declaring signal reconnected without reconnect response received`,this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&e.message?.case===`leave`?{isValid:!1,error:L.leaveRequest(`Received leave request while trying to (re)connect`,e.message.value.reason)}:t?{isValid:!1,error:L.internal(`Unexpected first message`)}:{isValid:!1,error:L.internal(`did not receive join response, got ${e.message?.case} instead`)}}handleConnectionError(e,t){return F(this,void 0,void 0,function*(){try{let n=yield fetch(t);switch(n.status){case 404:return L.serviceNotFound(`v1 RTC path not found. Consider upgrading your LiveKit server version`,`v0-rtc`);case 401:case 403:let e=yield n.text();return L.notAllowed(e,n.status);default:break}return e instanceof L?e:L.internal(`Encountered unknown websocket error during connection: ${e}`,{status:n.status,statusText:n.statusText})}catch(e){return e instanceof L?e:L.serverUnreachable(e instanceof Error?e.message:`server was not reachable`)}})}};function ud(e){let t={type:`offer`,sdp:e.sdp};switch(e.type){case`answer`:case`offer`:case`pranswer`:case`rollback`:t.type=e.type;break}return t}function dd(e,t){return new Ja({sdp:e.sdp,type:e.type,id:t})}function fd(e,t,n){let r=new URLSearchParams;return r.set(`access_token`,e),n.reconnect&&(r.set(`reconnect`,`1`),n.sid&&r.set(`sid`,n.sid)),r.set(`auto_subscribe`,n.autoSubscribe?`1`:`0`),r.set(`sdk`,Rl()?`reactnative`:`js`),r.set(`version`,t.version),r.set(`protocol`,t.protocol.toString()),t.deviceModel&&r.set(`device_model`,t.deviceModel),t.os&&r.set(`os`,t.os),t.osVersion&&r.set(`os_version`,t.osVersion),t.browser&&r.set(`browser`,t.browser),t.browserVersion&&r.set(`browser_version`,t.browserVersion),n.adaptiveStream&&r.set(`adaptive_stream`,`1`),n.reconnectReason&&r.set(`reconnect_reason`,n.reconnectReason.toString()),navigator.connection?.type&&r.set(`network`,navigator.connection.type),r}function pd(e,t,n,r){return F(this,void 0,void 0,function*(){let i=new URLSearchParams;i.set(`access_token`,e);let a=new Fo({clientInfo:t,connectionSettings:new Po({autoSubscribe:!!n.autoSubscribe,adaptiveStream:!!n.adaptiveStream}),reconnect:!!n.reconnect,participantSid:n.sid?n.sid:void 0,publisherOffer:r});n.reconnectReason&&(a.reconnectReason=n.reconnectReason);let o=a.toBinary(),s,c;if(Su()){let e=new CompressionStream(`gzip`),t=e.writable.getWriter();t.write(new Uint8Array(o)),t.close();let n=[],r=e.readable.getReader();for(;;){let{done:e,value:t}=yield r.read();if(e)break;n.push(t)}let i=n.reduce((e,t)=>e+t.length,0),a=new Uint8Array(i),l=0;for(let e of n)a.set(e,l),l+=e.length;s=a,c=Lo.GZIP}else s=o,c=Lo.NONE;let l=new Io({joinRequest:s,compression:c}).toBinary();return i.set(`join_request`,(e=>{let t=Array.from(e,e=>String.fromCodePoint(e)).join(``);return btoa(t)})(l).replace(/\+/g,`-`).replace(/\//g,`_`)),i})}var md=class{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){let e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){let t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}},hd=class{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){let n=Date.now();n-this._lastCleanup>this.ttl/2&&this.cleanup();let r=n+this.ttl;return this._map.set(e,{value:t,expiresAt:r}),this}get(e){let t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){let t=this._map.get(e);return t?t.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){let e=Date.now();for(let[t,n]of this._map.entries())n.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(let[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e(n.value,t,this.asValueMap())}map(e){this.cleanup();let t=[],n=this.asValueMap();for(let[r,i]of n.entries())t.push(e(i,r,n));return t}asValueMap(){let e=new Map;for(let[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e.set(t,n.value);return e}},gd={},_d={},vd={exports:{}},yd;function bd(){if(yd)return vd.exports;yd=1;var e=vd.exports={v:[{name:`version`,reg:/^(\d*)$/}],o:[{name:`origin`,reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:[`username`,`sessionId`,`sessionVersion`,`netType`,`ipVer`,`address`],format:`%s %s %d %s IP%d %s`}],s:[{name:`name`}],i:[{name:`description`}],u:[{name:`uri`}],e:[{name:`email`}],p:[{name:`phone`}],z:[{name:`timezones`}],r:[{name:`repeats`}],t:[{name:`timing`,reg:/^(\d*) (\d*)/,names:[`start`,`stop`],format:`%d %d`}],c:[{name:`connection`,reg:/^IN IP(\d) (\S*)/,names:[`version`,`ip`],format:`IN IP%d %s`}],b:[{push:`bandwidth`,reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:[`type`,`limit`],format:`%s:%s`}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:[`type`,`port`,`protocol`,`payloads`],format:`%s %d %s %s`}],a:[{push:`rtp`,reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:[`payload`,`codec`,`rate`,`encoding`],format:function(e){return e.encoding?`rtpmap:%d %s/%s/%s`:e.rate?`rtpmap:%d %s/%s`:`rtpmap:%d %s`}},{push:`fmtp`,reg:/^fmtp:(\d*) ([\S| ]*)/,names:[`payload`,`config`],format:`fmtp:%d %s`},{name:`control`,reg:/^control:(.*)/,format:`control:%s`},{name:`rtcp`,reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:[`port`,`netType`,`ipVer`,`address`],format:function(e){return e.address==null?`rtcp:%d`:`rtcp:%d %s IP%d %s`}},{push:`rtcpFbTrrInt`,reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:[`payload`,`value`],format:`rtcp-fb:%s trr-int %d`},{push:`rtcpFb`,reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:[`payload`,`type`,`subtype`],format:function(e){return e.subtype==null?`rtcp-fb:%s %s`:`rtcp-fb:%s %s %s`}},{push:`ext`,reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:[`value`,`direction`,`encrypt-uri`,`uri`,`config`],format:function(e){return`extmap:%d`+(e.direction?`/%s`:`%v`)+(e[`encrypt-uri`]?` %s`:`%v`)+` %s`+(e.config?` %s`:``)}},{name:`extmapAllowMixed`,reg:/^(extmap-allow-mixed)/},{push:`crypto`,reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:[`id`,`suite`,`config`,`sessionConfig`],format:function(e){return e.sessionConfig==null?`crypto:%d %s %s`:`crypto:%d %s %s %s`}},{name:`setup`,reg:/^setup:(\w*)/,format:`setup:%s`},{name:`connectionType`,reg:/^connection:(new|existing)/,format:`connection:%s`},{name:`mid`,reg:/^mid:([^\s]*)/,format:`mid:%s`},{name:`msid`,reg:/^msid:(.*)/,format:`msid:%s`},{name:`ptime`,reg:/^ptime:(\d*(?:\.\d*)*)/,format:`ptime:%d`},{name:`maxptime`,reg:/^maxptime:(\d*(?:\.\d*)*)/,format:`maxptime:%d`},{name:`direction`,reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:`icelite`,reg:/^(ice-lite)/},{name:`iceUfrag`,reg:/^ice-ufrag:(\S*)/,format:`ice-ufrag:%s`},{name:`icePwd`,reg:/^ice-pwd:(\S*)/,format:`ice-pwd:%s`},{name:`fingerprint`,reg:/^fingerprint:(\S*) (\S*)/,names:[`type`,`hash`],format:`fingerprint:%s %s`},{push:`candidates`,reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:[`foundation`,`component`,`transport`,`priority`,`ip`,`port`,`type`,`raddr`,`rport`,`tcptype`,`generation`,`network-id`,`network-cost`],format:function(e){var t=`candidate:%s %d %s %d %s %d typ %s`;return t+=e.raddr==null?`%v%v`:` raddr %s rport %d`,t+=e.tcptype==null?`%v`:` tcptype %s`,e.generation!=null&&(t+=` generation %d`),t+=e[`network-id`]==null?`%v`:` network-id %d`,t+=e[`network-cost`]==null?`%v`:` network-cost %d`,t}},{name:`endOfCandidates`,reg:/^(end-of-candidates)/},{name:`remoteCandidates`,reg:/^remote-candidates:(.*)/,format:`remote-candidates:%s`},{name:`iceOptions`,reg:/^ice-options:(\S*)/,format:`ice-options:%s`},{push:`ssrcs`,reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:[`id`,`attribute`,`value`],format:function(e){var t=`ssrc:%d`;return e.attribute!=null&&(t+=` %s`,e.value!=null&&(t+=`:%s`)),t}},{push:`ssrcGroups`,reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:[`semantics`,`ssrcs`],format:`ssrc-group:%s %s`},{name:`msidSemantic`,reg:/^msid-semantic:\s?(\w*) (\S*)/,names:[`semantic`,`token`],format:`msid-semantic: %s %s`},{push:`groups`,reg:/^group:(\w*) (.*)/,names:[`type`,`mids`],format:`group:%s %s`},{name:`rtcpMux`,reg:/^(rtcp-mux)/},{name:`rtcpRsize`,reg:/^(rtcp-rsize)/},{name:`sctpmap`,reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:[`sctpmapNumber`,`app`,`maxMessageSize`],format:function(e){return e.maxMessageSize==null?`sctpmap:%s %s`:`sctpmap:%s %s %s`}},{name:`xGoogleFlag`,reg:/^x-google-flag:([^\s]*)/,format:`x-google-flag:%s`},{push:`rids`,reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:[`id`,`direction`,`params`],format:function(e){return e.params?`rid:%s %s %s`:`rid:%s %s`}},{push:`imageattrs`,reg:RegExp(`^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?`),names:[`pt`,`dir1`,`attrs1`,`dir2`,`attrs2`],format:function(e){return`imageattr:%s %s %s`+(e.dir2?` %s %s`:``)}},{name:`simulcast`,reg:RegExp(`^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$`),names:[`dir1`,`list1`,`dir2`,`list2`],format:function(e){return`simulcast:%s %s`+(e.dir2?` %s %s`:``)}},{name:`simulcast_03`,reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:[`value`],format:`simulcast: %s`},{name:`framerate`,reg:/^framerate:(\d+(?:$|\.\d+))/,format:`framerate:%s`},{name:`sourceFilter`,reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:[`filterMode`,`netType`,`addressTypes`,`destAddress`,`srcList`],format:`source-filter: %s %s %s %s %s`},{name:`bundleOnly`,reg:/^(bundle-only)/},{name:`label`,reg:/^label:(.+)/,format:`label:%s`},{name:`sctpPort`,reg:/^sctp-port:(\d+)$/,format:`sctp-port:%s`},{name:`maxMessageSize`,reg:/^max-message-size:(\d+)$/,format:`max-message-size:%s`},{push:`tsRefClocks`,reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:[`clksrc`,`clksrcExt`],format:function(e){return`ts-refclk:%s`+(e.clksrcExt==null?``:`=%s`)}},{name:`mediaClk`,reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:[`id`,`mediaClockName`,`mediaClockValue`,`rateNumerator`,`rateDenominator`],format:function(e){var t=`mediaclk:`;return t+=e.id==null?`%v%s`:`id=%s %s`,t+=e.mediaClockValue==null?``:`=%s`,t+=e.rateNumerator==null?``:` rate=%s`,t+=e.rateDenominator==null?``:`/%s`,t}},{name:`keywords`,reg:/^keywds:(.+)$/,format:`keywds:%s`},{name:`content`,reg:/^content:(.+)/,format:`content:%s`},{name:`bfcpFloorCtrl`,reg:/^floorctrl:(c-only|s-only|c-s)/,format:`floorctrl:%s`},{name:`bfcpConfId`,reg:/^confid:(\d+)/,format:`confid:%s`},{name:`bfcpUserId`,reg:/^userid:(\d+)/,format:`userid:%s`},{name:`bfcpFloorId`,reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:[`id`,`mStream`],format:`floorid:%s mstrm:%s`},{push:`invalid`,names:[`value`]}]};return Object.keys(e).forEach(function(t){e[t].forEach(function(e){e.reg||=/(.*)/,e.format||=`%s`})}),vd.exports}var xd;function Sd(){return xd?_d:(xd=1,(function(e){var t=function(e){return String(Number(e))===e?Number(e):e},n=function(e,n,r,i){if(i&&!r)n[i]=t(e[1]);else for(var a=0;a<r.length;a+=1)e[a+1]!=null&&(n[r[a]]=t(e[a+1]))},r=function(e,t,r){var i=e.name&&e.names;e.push&&!t[e.push]?t[e.push]=[]:i&&!t[e.name]&&(t[e.name]={});var a=e.push?{}:i?t[e.name]:t;n(r.match(e.reg),a,e.names,e.name),e.push&&t[e.push].push(a)},i=bd(),a=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},n=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(a).forEach(function(e){var t=e[0],a=e.slice(2);t===`m`&&(n.push({rtp:[],fmtp:[]}),o=n[n.length-1]);for(var s=0;s<(i[t]||[]).length;s+=1){var c=i[t][s];if(c.reg.test(a))return r(c,o,a)}}),t.media=n,t};var o=function(e,n){var r=n.split(/=(.+)/,2);return r.length===2?e[r[0]]=t(r[1]):r.length===1&&n.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(` `).map(Number)},e.parseRemoteCandidates=function(e){for(var n=[],r=e.split(` `).map(t),i=0;i<r.length;i+=3)n.push({component:r[i],ip:r[i+1],port:r[i+2]});return n},e.parseImageAttributes=function(e){return e.split(` `).map(function(e){return e.substring(1,e.length-1).split(`,`).reduce(o,{})})},e.parseSimulcastStreamList=function(e){return e.split(`;`).map(function(e){return e.split(`,`).map(function(e){var n,r=!1;return e[0]===`~`?(n=t(e.substring(1,e.length)),r=!0):n=t(e),{scid:n,paused:r}})})}})(_d),_d)}var Cd,wd;function Td(){if(wd)return Cd;wd=1;var e=bd(),t=/%[sdv%]/g,n=function(e){var n=1,r=arguments,i=r.length;return e.replace(t,function(e){if(n>=i)return e;var t=r[n];switch(n+=1,e){case`%%`:return`%`;case`%s`:return String(t);case`%d`:return Number(t);case`%v`:return``}})},r=function(e,t,r){var i=t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format,a=[e+`=`+i];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?a.push(r[t.name][s]):a.push(r[t.names[o]])}else a.push(r[t.name]);return n.apply(null,a)},i=[`v`,`o`,`s`,`i`,`u`,`e`,`p`,`c`,`b`,`t`,`r`,`z`,`a`],a=[`i`,`c`,`b`,`a`];return Cd=function(t,n){n||={},t.version??=0,t.name??=` `,t.media.forEach(function(e){e.payloads??=``});var o=n.outerOrder||i,s=n.innerOrder||a,c=[];return o.forEach(function(n){e[n].forEach(function(e){e.name in t&&t[e.name]!=null?c.push(r(n,e,t)):e.push in t&&t[e.push]!=null&&t[e.push].forEach(function(t){c.push(r(n,e,t))})})}),t.media.forEach(function(t){c.push(r(`m`,e.m[0],t)),s.forEach(function(n){e[n].forEach(function(e){e.name in t&&t[e.name]!=null?c.push(r(n,e,t)):e.push in t&&t[e.push]!=null&&t[e.push].forEach(function(t){c.push(r(n,e,t))})})})}),c.join(`\r
|
|
60
|
+
`);e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:n}):t.sdp=n}return n.apply(this,arguments)}}function ub(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let n=e.RTCPeerConnection.prototype.addIceCandidate;!n||n.length===0||(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(t.browser===`chrome`&&t.version<78||t.browser===`firefox`&&t.version<68||t.browser===`safari`)&&arguments[0]&&arguments[0].candidate===``?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function db(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let n=e.RTCPeerConnection.prototype.setLocalDescription;!n||n.length===0||(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if(typeof e!=`object`||e.type&&e.sdp)return n.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case`stable`:case`have-local-offer`:case`have-remote-pranswer`:e.type=`offer`;break;default:e.type=`answer`;break}return e.sdp||e.type!==`offer`&&e.type!==`answer`?n.apply(this,[e]):(e.type===`offer`?this.createOffer:this.createAnswer).apply(this).then(e=>n.apply(this,[e]))})}var fb=Object.freeze({__proto__:null,removeExtmapAllowMixed:lb,shimAddIceCandidateNullOrEmpty:ub,shimConnectionState:cb,shimMaxMessageSize:ob,shimParameterlessSetLocalDescription:db,shimRTCIceCandidate:ib,shimRTCIceCandidateRelayProtocol:ab,shimSendThrowTypeError:sb});function pb(){let{window:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},n=dy,r=py(e),i={browserDetails:r,commonShim:fb,extractVersion:sy,disableLog:ly,disableWarnings:uy,sdp:rb};switch(r.browser){case`chrome`:if(!Oy||!Ey||!t.shimChrome)return n(`Chrome shim is not included in this adapter release.`),i;if(r.version===null)return n(`Chrome shim can not determine version, not shimming.`),i;n(`adapter.js shimming chrome.`),i.browserShim=Oy,ub(e,r),db(e),yy(e,r),by(e),Ey(e,r),xy(e),Ty(e,r),Sy(e),Cy(e),Dy(e,r),ib(e),ab(e),cb(e),ob(e,r),sb(e),lb(e,r);break;case`firefox`:if(!Vy||!My||!t.shimFirefox)return n(`Firefox shim is not included in this adapter release.`),i;n(`adapter.js shimming firefox.`),i.browserShim=Vy,ub(e,r),db(e),ky(e,r),My(e,r),jy(e),Fy(e),Ny(e),Py(e),Iy(e),Ly(e),Ry(e),zy(e),By(e),ib(e),cb(e),ob(e,r),sb(e);break;case`safari`:if(!Zy||!t.shimSafari)return n(`Safari shim is not included in this adapter release.`),i;n(`adapter.js shimming safari.`),i.browserShim=Zy,ub(e,r),db(e),qy(e),Yy(e),Wy(e),Hy(e),Uy(e),Jy(e),Gy(e),Xy(e),ib(e),ab(e),ob(e,r),sb(e),lb(e,r);break;default:n(`Unsupported browser!`);break}return i}pb({window:typeof window>`u`?void 0:window});var mb,hb,gb=class extends (hb=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}};mb=gb,gb.resolve=e=>Reflect.get(hb,`resolve`,mb).call(mb,e);var _b=/version\/(\d+(\.?_?\d+)+)/i,vb;function yb(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(e===void 0&&typeof navigator>`u`)return;let n=(e??navigator.userAgent).toLowerCase();return(vb===void 0||t)&&(vb=bb.find(e=>{let{test:t}=e;return t.test(n)})?.describe(n)),vb}var bb=[{test:/firefox|iceweasel|fxios/i,describe(e){return{name:`Firefox`,version:xb(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes(`fxios`)?`iOS`:void 0,osVersion:Sb(e)}}},{test:/chrom|crios|crmo/i,describe(e){return{name:`Chrome`,version:xb(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes(`crios`)?`iOS`:void 0,osVersion:Sb(e)}}},{test:/safari|applewebkit/i,describe(e){return{name:`Safari`,version:xb(_b,e),os:e.includes(`mobile/`)?`iOS`:`macOS`,osVersion:Sb(e)}}}];function xb(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,r=t.match(e);return r&&r.length>=n&&r[n]||``}function Sb(e){return e.includes(`mac os`)?xb(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,`.`):void 0}var Cb=`2.18.1`,wb=class extends Error{constructor(e,t,n){super(t||`an error has occurred`),this.name=`LiveKitError`,this.code=e,n?.cause!==void 0&&(this.cause=n?.cause)}},Tb=class extends wb{},Eb;(function(e){e[e.NotAllowed=0]=`NotAllowed`,e[e.ServerUnreachable=1]=`ServerUnreachable`,e[e.InternalError=2]=`InternalError`,e[e.Cancelled=3]=`Cancelled`,e[e.LeaveRequest=4]=`LeaveRequest`,e[e.Timeout=5]=`Timeout`,e[e.WebSocket=6]=`WebSocket`,e[e.ServiceNotFound=7]=`ServiceNotFound`})(Eb||={});var B=class e extends Tb{constructor(e,t,n,r){super(1,e),this.name=`ConnectionError`,this.status=n,this.reason=t,this.context=r,this.reasonName=Eb[t]}static notAllowed(t,n,r){return new e(t,Eb.NotAllowed,n,r)}static timeout(t){return new e(t,Eb.Timeout)}static leaveRequest(t,n){return new e(t,Eb.LeaveRequest,void 0,n)}static internal(t,n){return new e(t,Eb.InternalError,void 0,n)}static cancelled(t){return new e(t,Eb.Cancelled)}static serverUnreachable(t,n){return new e(t,Eb.ServerUnreachable,n)}static websocket(t,n,r){return new e(t,Eb.WebSocket,n,r)}static serviceNotFound(t,n){return new e(t,Eb.ServiceNotFound,void 0,n)}},Db=class extends wb{constructor(e){super(21,e??`device is unsupported`),this.name=`DeviceUnsupportedError`}},Ob=class extends wb{constructor(e){super(20,e??`track is invalid`),this.name=`TrackInvalidError`}},kb=class extends wb{constructor(e){super(10,e??`unsupported server`),this.name=`UnsupportedServer`}},Ab=class extends wb{constructor(e){super(12,e??`unexpected connection state`),this.name=`UnexpectedConnectionState`}},jb=class extends wb{constructor(e){super(13,e??`unable to negotiate`),this.name=`NegotiationError`}},Mb=class extends wb{constructor(e,t){super(15,e),this.name=`PublishTrackError`,this.status=t}},Nb=class extends Tb{constructor(e,t){super(15,e),this.name=`SignalRequestError`,this.reason=t,this.reasonName=typeof t==`string`?t:kv[t]}},Pb;(function(e){e[e.AlreadyOpened=0]=`AlreadyOpened`,e[e.AbnormalEnd=1]=`AbnormalEnd`,e[e.DecodeFailed=2]=`DecodeFailed`,e[e.LengthExceeded=3]=`LengthExceeded`,e[e.Incomplete=4]=`Incomplete`,e[e.HandlerAlreadyRegistered=7]=`HandlerAlreadyRegistered`,e[e.EncryptionTypeMismatch=8]=`EncryptionTypeMismatch`})(Pb||={});var Fb=class extends Tb{constructor(e,t){super(16,e),this.name=`DataStreamError`,this.reason=t,this.reasonName=Pb[t]}},Ib=class extends wb{constructor(e){super(18,e),this.name=`SignalReconnectError`}},Lb;(function(e){e.PermissionDenied=`PermissionDenied`,e.NotFound=`NotFound`,e.DeviceInUse=`DeviceInUse`,e.Other=`Other`})(Lb||={}),(function(e){function t(t){if(t&&`name`in t)return t.name===`NotFoundError`||t.name===`DevicesNotFoundError`?e.NotFound:t.name===`NotAllowedError`||t.name===`PermissionDeniedError`?e.PermissionDenied:t.name===`NotReadableError`||t.name===`TrackStartError`?e.DeviceInUse:e.Other}e.getFailure=t})(Lb||={});var Rb=class{};Rb.setTimeout=function(){return setTimeout(...arguments)},Rb.setInterval=function(){return setInterval(...arguments)},Rb.clearTimeout=function(){return clearTimeout(...arguments)},Rb.clearInterval=function(){return clearInterval(...arguments)};var V;(function(e){e.Connected=`connected`,e.Reconnecting=`reconnecting`,e.SignalReconnecting=`signalReconnecting`,e.Reconnected=`reconnected`,e.Disconnected=`disconnected`,e.ConnectionStateChanged=`connectionStateChanged`,e.Moved=`moved`,e.MediaDevicesChanged=`mediaDevicesChanged`,e.ParticipantConnected=`participantConnected`,e.ParticipantDisconnected=`participantDisconnected`,e.TrackPublished=`trackPublished`,e.TrackSubscribed=`trackSubscribed`,e.TrackSubscriptionFailed=`trackSubscriptionFailed`,e.TrackUnpublished=`trackUnpublished`,e.TrackUnsubscribed=`trackUnsubscribed`,e.TrackMuted=`trackMuted`,e.TrackUnmuted=`trackUnmuted`,e.LocalTrackPublished=`localTrackPublished`,e.LocalTrackUnpublished=`localTrackUnpublished`,e.LocalAudioSilenceDetected=`localAudioSilenceDetected`,e.ActiveSpeakersChanged=`activeSpeakersChanged`,e.ParticipantMetadataChanged=`participantMetadataChanged`,e.ParticipantNameChanged=`participantNameChanged`,e.ParticipantAttributesChanged=`participantAttributesChanged`,e.ParticipantActive=`participantActive`,e.RoomMetadataChanged=`roomMetadataChanged`,e.DataReceived=`dataReceived`,e.SipDTMFReceived=`sipDTMFReceived`,e.TranscriptionReceived=`transcriptionReceived`,e.ConnectionQualityChanged=`connectionQualityChanged`,e.TrackStreamStateChanged=`trackStreamStateChanged`,e.TrackSubscriptionPermissionChanged=`trackSubscriptionPermissionChanged`,e.TrackSubscriptionStatusChanged=`trackSubscriptionStatusChanged`,e.AudioPlaybackStatusChanged=`audioPlaybackChanged`,e.VideoPlaybackStatusChanged=`videoPlaybackChanged`,e.MediaDevicesError=`mediaDevicesError`,e.ParticipantPermissionsChanged=`participantPermissionsChanged`,e.SignalConnected=`signalConnected`,e.RecordingStatusChanged=`recordingStatusChanged`,e.ParticipantEncryptionStatusChanged=`participantEncryptionStatusChanged`,e.EncryptionError=`encryptionError`,e.DCBufferStatusChanged=`dcBufferStatusChanged`,e.ActiveDeviceChanged=`activeDeviceChanged`,e.ChatMessage=`chatMessage`,e.LocalTrackSubscribed=`localTrackSubscribed`,e.MetricsReceived=`metricsReceived`,e.DataTrackPublished=`dataTrackPublished`,e.DataTrackUnpublished=`dataTrackUnpublished`,e.LocalDataTrackPublished=`localDataTrackPublished`,e.LocalDataTrackUnpublished=`localDataTrackUnpublished`})(V||={});var H;(function(e){e.TrackPublished=`trackPublished`,e.TrackSubscribed=`trackSubscribed`,e.TrackSubscriptionFailed=`trackSubscriptionFailed`,e.TrackUnpublished=`trackUnpublished`,e.TrackUnsubscribed=`trackUnsubscribed`,e.TrackMuted=`trackMuted`,e.TrackUnmuted=`trackUnmuted`,e.LocalTrackPublished=`localTrackPublished`,e.LocalTrackUnpublished=`localTrackUnpublished`,e.LocalTrackCpuConstrained=`localTrackCpuConstrained`,e.LocalSenderCreated=`localSenderCreated`,e.ParticipantMetadataChanged=`participantMetadataChanged`,e.ParticipantNameChanged=`participantNameChanged`,e.DataReceived=`dataReceived`,e.SipDTMFReceived=`sipDTMFReceived`,e.TranscriptionReceived=`transcriptionReceived`,e.IsSpeakingChanged=`isSpeakingChanged`,e.ConnectionQualityChanged=`connectionQualityChanged`,e.TrackStreamStateChanged=`trackStreamStateChanged`,e.TrackSubscriptionPermissionChanged=`trackSubscriptionPermissionChanged`,e.TrackSubscriptionStatusChanged=`trackSubscriptionStatusChanged`,e.TrackCpuConstrained=`trackCpuConstrained`,e.MediaDevicesError=`mediaDevicesError`,e.AudioStreamAcquired=`audioStreamAcquired`,e.ParticipantPermissionsChanged=`participantPermissionsChanged`,e.PCTrackAdded=`pcTrackAdded`,e.AttributesChanged=`attributesChanged`,e.LocalTrackSubscribed=`localTrackSubscribed`,e.ChatMessage=`chatMessage`,e.Active=`active`})(H||={});var U;(function(e){e.TransportsCreated=`transportsCreated`,e.Connected=`connected`,e.Disconnected=`disconnected`,e.Resuming=`resuming`,e.Resumed=`resumed`,e.Restarting=`restarting`,e.Restarted=`restarted`,e.SignalResumed=`signalResumed`,e.SignalRestarted=`signalRestarted`,e.Closing=`closing`,e.MediaTrackAdded=`mediaTrackAdded`,e.ActiveSpeakersUpdate=`activeSpeakersUpdate`,e.DataPacketReceived=`dataPacketReceived`,e.RTPVideoMapUpdate=`rtpVideoMapUpdate`,e.DCBufferStatusChanged=`dcBufferStatusChanged`,e.ParticipantUpdate=`participantUpdate`,e.RoomUpdate=`roomUpdate`,e.SpeakersChanged=`speakersChanged`,e.StreamStateChanged=`streamStateChanged`,e.ConnectionQualityUpdate=`connectionQualityUpdate`,e.SubscriptionError=`subscriptionError`,e.SubscriptionPermissionUpdate=`subscriptionPermissionUpdate`,e.RemoteMute=`remoteMute`,e.SubscribedQualityUpdate=`subscribedQualityUpdate`,e.LocalTrackUnpublished=`localTrackUnpublished`,e.LocalTrackSubscribed=`localTrackSubscribed`,e.Offline=`offline`,e.SignalRequestResponse=`signalRequestResponse`,e.SignalConnected=`signalConnected`,e.RoomMoved=`roomMoved`,e.PublishDataTrackResponse=`publishDataTrackResponse`,e.UnPublishDataTrackResponse=`unPublishDataTrackResponse`,e.DataTrackSubscriberHandles=`dataTrackSubscriberHandles`,e.DataTrackPacketReceived=`dataTrackPacketReceived`,e.Joined=`joined`})(U||={});var W;(function(e){e.Message=`message`,e.Muted=`muted`,e.Unmuted=`unmuted`,e.Restarted=`restarted`,e.Ended=`ended`,e.Subscribed=`subscribed`,e.Unsubscribed=`unsubscribed`,e.CpuConstrained=`cpuConstrained`,e.UpdateSettings=`updateSettings`,e.UpdateSubscription=`updateSubscription`,e.AudioPlaybackStarted=`audioPlaybackStarted`,e.AudioPlaybackFailed=`audioPlaybackFailed`,e.AudioSilenceDetected=`audioSilenceDetected`,e.VisibilityChanged=`visibilityChanged`,e.VideoDimensionsChanged=`videoDimensionsChanged`,e.VideoPlaybackStarted=`videoPlaybackStarted`,e.VideoPlaybackFailed=`videoPlaybackFailed`,e.ElementAttached=`elementAttached`,e.ElementDetached=`elementDetached`,e.UpstreamPaused=`upstreamPaused`,e.UpstreamResumed=`upstreamResumed`,e.SubscriptionPermissionChanged=`subscriptionPermissionChanged`,e.SubscriptionStatusChanged=`subscriptionStatusChanged`,e.SubscriptionFailed=`subscriptionFailed`,e.TrackProcessorUpdate=`trackProcessorUpdate`,e.AudioTrackFeatureUpdate=`audioTrackFeatureUpdate`,e.TranscriptionReceived=`transcriptionReceived`,e.TimeSyncUpdate=`timeSyncUpdate`,e.PreConnectBufferFlushed=`preConnectBufferFlushed`})(W||={});function zb(e){return e===void 0?e:typeof structuredClone==`function`?typeof e==`object`&&e?structuredClone(Object.assign({},e)):structuredClone(e):JSON.parse(JSON.stringify(e))}var G=class{constructor(e,t,n,r,i){if(typeof e==`object`)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&n!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:r,priority:i};else throw TypeError(`Unsupported options: provide at least width, height and maxBitrate`)}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}},Bb=[`vp8`,`h264`],Vb=[`vp8`,`h264`,`vp9`,`av1`,`h265`];function Hb(e){return!!Bb.find(t=>t===e)}var Ub=Hb,Wb;(function(e){e[e.PREFER_REGRESSION=0]=`PREFER_REGRESSION`,e[e.SIMULCAST=1]=`SIMULCAST`,e[e.REGRESSION=2]=`REGRESSION`})(Wb||={});var Gb;(function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:24e3},e.music={maxBitrate:48e3},e.musicStereo={maxBitrate:64e3},e.musicHighQuality={maxBitrate:96e3},e.musicHighQualityStereo={maxBitrate:128e3}})(Gb||={});var Kb={h90:new G(160,90,9e4,20),h180:new G(320,180,16e4,20),h216:new G(384,216,18e4,20),h360:new G(640,360,45e4,20),h540:new G(960,540,8e5,25),h720:new G(1280,720,17e5,30),h1080:new G(1920,1080,3e6,30),h1440:new G(2560,1440,5e6,30),h2160:new G(3840,2160,8e6,30)},qb={h120:new G(160,120,7e4,20),h180:new G(240,180,125e3,20),h240:new G(320,240,14e4,20),h360:new G(480,360,33e4,20),h480:new G(640,480,5e5,20),h540:new G(720,540,6e5,25),h720:new G(960,720,13e5,30),h1080:new G(1440,1080,23e5,30),h1440:new G(1920,1440,38e5,30)},Jb={h360fps3:new G(640,360,2e5,3,`medium`),h360fps15:new G(640,360,4e5,15,`medium`),h720fps5:new G(1280,720,8e5,5,`medium`),h720fps15:new G(1280,720,15e5,15,`medium`),h720fps30:new G(1280,720,2e6,30,`medium`),h1080fps15:new G(1920,1080,25e5,15,`medium`),h1080fps30:new G(1920,1080,5e6,30,`medium`),original:new G(0,0,7e6,30,`medium`)};function Yb(e,t,n){var r,i;let{optionsWithoutProcessor:a,audioProcessor:o,videoProcessor:s}=sx(e??{}),c=t?.processor,l=n?.processor,u=a??{};return u.audio===!0&&(u.audio={}),u.video===!0&&(u.video={}),u.audio&&(Xb(u.audio,t),(r=u.audio).deviceId??(r.deviceId={ideal:`default`}),(o||c)&&(u.audio.processor=o??c)),u.video&&(Xb(u.video,n),(i=u.video).deviceId??(i.deviceId={ideal:`default`}),(s||l)&&(u.video.processor=s??l)),u}function Xb(e,t){return Object.keys(t).forEach(n=>{e[n]===void 0&&(e[n]=t[n])}),e}function Zb(e){var t,n;let r={};if(e.video)if(typeof e.video==`object`){let n={},i=n,a=e.video;Object.keys(a).forEach(e=>{switch(e){case`resolution`:Xb(i,a.resolution);break;default:i[e]=a[e]}}),r.video=n,(t=r.video).deviceId??(t.deviceId={ideal:`default`})}else r.video=e.video?{deviceId:{ideal:`default`}}:!1;else r.video=!1;return e.audio?typeof e.audio==`object`?(r.audio=e.audio,(n=r.audio).deviceId??(n.deviceId={ideal:`default`})):r.audio={deviceId:{ideal:`default`}}:r.audio=!1,r}function Qb(e){return z(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){let n=$b();if(n){let r=n.createAnalyser();r.fftSize=2048;let i=r.frequencyBinCount,a=new Uint8Array(i);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield yx(t),r.getByteTimeDomainData(a);let o=a.some(e=>e!==128&&e!==0);return n.close(),!o}return!1}()})}function $b(){let e=typeof window<`u`&&(window.AudioContext||window.webkitAudioContext);if(e){let t=new e({latencyHint:`interactive`});if(t.state===`suspended`&&typeof window<`u`&&window.document?.body){let e=()=>z(this,void 0,void 0,function*(){var n;try{t.state===`suspended`&&(yield t.resume())}catch(e){console.warn(`Error trying to auto-resume audio context`,e)}finally{(n=window.document.body)==null||n.removeEventListener(`click`,e)}});t.addEventListener(`statechange`,()=>{var n;t.state===`closed`&&((n=window.document.body)==null||n.removeEventListener(`click`,e))}),window.document.body.addEventListener(`click`,e)}return t}}function ex(e){return e===`audioinput`?q.Source.Microphone:e===`videoinput`?q.Source.Camera:q.Source.Unknown}function tx(e){if(e===q.Source.Microphone)return`audioinput`;if(e===q.Source.Camera)return`videoinput`}function nx(e){let t=e.video??!0;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(t=typeof t==`boolean`?{}:t,t=kx()?Object.assign(Object.assign({},t),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},t),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:e.audio??!1,video:t,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}function rx(e){return e.split(`/`)[1].toLowerCase()}function ix(e){let t=[];return e.forEach(e=>{e.track!==void 0&&t.push(new W_({cid:e.track.mediaStreamID,track:e.trackInfo}))}),t}function K(e){return`mediaStreamTrack`in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?K(e.track):{})}}function ax(){return typeof RTCRtpReceiver<`u`&&`getSynchronizationSources`in RTCRtpReceiver}function ox(e,t){e===void 0&&(e={}),t===void 0&&(t={});let n=[...Object.keys(t),...Object.keys(e)],r={};for(let i of n)e[i]!==t[i]&&(r[i]=t[i]??``);return r}function sx(e){let t=Object.assign({},e),n,r;return typeof t.audio==`object`&&t.audio.processor&&(n=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),typeof t.video==`object`&&t.video.processor&&(r=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:n,videoProcessor:r,optionsWithoutProcessor:zb(t)}}function cx(e){switch(e){case kg.CAMERA:return q.Source.Camera;case kg.MICROPHONE:return q.Source.Microphone;case kg.SCREEN_SHARE:return q.Source.ScreenShare;case kg.SCREEN_SHARE_AUDIO:return q.Source.ScreenShareAudio;default:return q.Source.Unknown}}function lx(e,t){return e.width*e.height<t.width*t.height}function ux(e,t){return e.layers?.find(e=>e.quality===t)}var dx=5e3,fx=[],px;(function(e){e[e.LOW=0]=`LOW`,e[e.MEDIUM=1]=`MEDIUM`,e[e.HIGH=2]=`HIGH`})(px||={});var q=class e extends iy.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.attachedElements=[],this.isMuted=!1,this._streamState=e.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=R,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState===`hidden`?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),dx):this.handleAppVisibilityChanged()},this.log=Wv(r.loggerName??Uv.Track),this.loggerContextCb=r.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=e.Source.Unknown}get logContext(){return Object.assign(Object.assign({},this.loggerContextCb?.call(this)),K(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let n=`audio`;this.kind===e.Kind.Video&&(n=`video`),this.attachedElements.length===0&&this.kind===e.Kind.Video&&this.addAppVisibilityListener(),t||(n===`audio`&&(fx.forEach(e=>{e.parentElement===null&&!t&&(t=e)}),t&&fx.splice(fx.indexOf(t),1)),t||=document.createElement(n)),this.attachedElements.includes(t)||this.attachedElements.push(t),mx(this.mediaStreamTrack,t);let r=t.srcObject.getTracks(),i=r.some(e=>e.kind===`audio`);return t.play().then(()=>{this.emit(i?W.AudioPlaybackStarted:W.VideoPlaybackStarted)}).catch(e=>{e.name===`NotAllowedError`?this.emit(i?W.AudioPlaybackFailed:W.VideoPlaybackFailed,e):e.name===`AbortError`?R.debug(`${i?`audio`:`video`} playback aborted, likely due to new play request`):R.warn(`could not playback ${i?`audio`:`video`}`,e),i&&t&&r.some(e=>e.kind===`video`)&&e.name===`NotAllowedError`&&(t.muted=!0,t.play().catch(()=>{}))}),this.emit(W.ElementAttached,t),t}detach(e){try{if(e){hx(this.mediaStreamTrack,e);let t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(W.ElementDetached,e)),e}let t=[];return this.attachedElements.forEach(e=>{hx(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(W.ElementDetached,e)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=Wv(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),fx.forEach(e=>{e.parentElement||(t=!1)}),t&&fx.push(e)}}handleAppVisibilityChanged(){return z(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState===`hidden`,!this.isInBackground&&this.kind===e.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Fx()?(this.isInBackground=document.visibilityState===`hidden`,document.addEventListener(`visibilitychange`,this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Fx()&&document.removeEventListener(`visibilitychange`,this.appVisibilityChangedListener)}};function mx(e,t){let n;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream;let r;r=e.kind===`audio`?n.getAudioTracks():n.getVideoTracks(),r.includes(e)||(r.forEach(e=>{n.removeTrack(e)}),n.addTrack(e)),(!kx()||!(t instanceof HTMLVideoElement))&&(t.autoplay=!0),t.muted=n.getAudioTracks().length===0,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(kx()||Dx())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=n,t.play().catch(()=>{})},0))}function hx(e,t){if(t.srcObject instanceof MediaStream){let n=t.srcObject;n.removeTrack(e),n.getTracks().length>0?t.srcObject=n:t.srcObject=null}}(function(e){let t;(function(e){e.Audio=`audio`,e.Video=`video`,e.Unknown=`unknown`})(t=e.Kind||={});let n;(function(e){e.Camera=`camera`,e.Microphone=`microphone`,e.ScreenShare=`screen_share`,e.ScreenShareAudio=`screen_share_audio`,e.Unknown=`unknown`})(n=e.Source||={});let r;(function(e){e.Active=`active`,e.Paused=`paused`,e.Unknown=`unknown`})(r=e.StreamState||={});function i(e){switch(e){case t.Audio:return Og.AUDIO;case t.Video:return Og.VIDEO;default:return Og.DATA}}e.kindToProto=i;function a(e){switch(e){case Og.AUDIO:return t.Audio;case Og.VIDEO:return t.Video;default:return t.Unknown}}e.kindFromProto=a;function o(e){switch(e){case n.Camera:return kg.CAMERA;case n.Microphone:return kg.MICROPHONE;case n.ScreenShare:return kg.SCREEN_SHARE;case n.ScreenShareAudio:return kg.SCREEN_SHARE_AUDIO;default:return kg.UNKNOWN}}e.sourceToProto=o;function s(e){switch(e){case kg.CAMERA:return n.Camera;case kg.MICROPHONE:return n.Microphone;case kg.SCREEN_SHARE:return n.ScreenShare;case kg.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}}e.sourceFromProto=s;function c(e){switch(e){case O_.ACTIVE:return r.Active;case O_.PAUSED:return r.Paused;default:return r.Unknown}}e.streamStateFromProto=c})(q||={});var gx=`|`,_x=`https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension`;function vx(e){let t=e.split(gx);return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,``]}function yx(e){return new gb(t=>Rb.setTimeout(t,e))}function bx(){return`addTransceiver`in RTCPeerConnection.prototype}function xx(){return`addTrack`in RTCPeerConnection.prototype}function Sx(){if(!(`getCapabilities`in RTCRtpSender)||kx()||Dx())return!1;let e=RTCRtpSender.getCapabilities(`video`),t=!1;if(e){for(let n of e.codecs)if(n.mimeType.toLowerCase()===`video/av1`){t=!0;break}}return t}function Cx(){if(!(`getCapabilities`in RTCRtpSender)||Dx())return!1;if(kx()){let e=yb();if(e?.version&&Hx(e.version,`16`)<0||e?.os===`iOS`&&e?.osVersion&&Hx(e.osVersion,`16`)<0)return!1}let e=RTCRtpSender.getCapabilities(`video`),t=!1;if(e){for(let n of e.codecs)if(n.mimeType.toLowerCase()===`video/vp9`){t=!0;break}}return t}function wx(e){return e===`av1`||e===`vp9`}function Tx(e){return!document||Ax()?!1:(e||=document.createElement(`audio`),`setSinkId`in e)}function Ex(){return typeof RTCPeerConnection>`u`?!1:bx()||xx()}function Dx(){return yb()?.name===`Firefox`}function Ox(){let e=yb();return!!e&&e.name===`Chrome`&&e.os!==`iOS`}function kx(){return yb()?.name===`Safari`}function Ax(){let e=yb();return e?.name===`Safari`||e?.os===`iOS`}function jx(){let e=yb();return e?.name===`Safari`&&e.version.startsWith(`17.`)||e?.os===`iOS`&&!!e?.osVersion&&Hx(e.osVersion,`17`)>=0}function Mx(e){return e||=yb(),e?.name===`Safari`&&Hx(e.version,`18.3`)>0||e?.os===`iOS`&&!!e?.osVersion&&Hx(e.osVersion,`18.3`)>0}function Nx(){return Fx()?navigator.userAgentData?.mobile??/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function Px(){let e=yb(),t=`17.2`;if(e)return e.name!==`Safari`&&e.os!==`iOS`||e.os===`iOS`&&e.osVersion&&Hx(e.osVersion,t)>=0?!0:e.name===`Safari`&&Hx(e.version,t)>=0}function Fx(){return typeof document<`u`}function Ix(){return navigator.product==`ReactNative`}function Lx(e){return e.hostname.endsWith(`.livekit.cloud`)||e.hostname.endsWith(`.livekit.run`)}function Rx(e){return Lx(e)?e.hostname.split(`.`)[0]:null}function zx(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Bx(){if(!Ix())return;let e=zx();if(e)return e.platform}function Vx(){if(Fx())return window.devicePixelRatio;if(Ix()){let e=zx();if(e)return e.devicePixelRatio}return 1}function Hx(e,t){let n=e.split(`.`),r=t.split(`.`),i=Math.min(n.length,r.length);for(let e=0;e<i;++e){let t=parseInt(n[e],10),a=parseInt(r[e],10);if(t>a)return 1;if(t<a)return-1;if(e===i-1&&t===a)return 0}return e===``&&t!==``?-1:t===``?1:n.length==r.length?0:n.length<r.length?-1:1}function Ux(e){for(let t of e)t.target.handleResize(t)}function Wx(e){for(let t of e)t.target.handleVisibilityChanged(t)}var Gx=null,Kx=()=>(Gx||=new ResizeObserver(Ux),Gx),qx=null,Jx=()=>(qx||=new IntersectionObserver(Wx,{root:null,rootMargin:`0px`}),qx);function Yx(){let e=new m_({sdk:h_.JS,protocol:16,version:Cb});return Ix()&&(e.os=Bx()??``),e}function Xx(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,i=document.createElement(`canvas`);i.width=e,i.height=t;let a=i.getContext(`2d`);a?.fillRect(0,0,i.width,i.height),r&&a&&(a.beginPath(),a.arc(e/2,t/2,50,0,Math.PI*2,!0),a.closePath(),a.fillStyle=`grey`,a.fill());let[o]=i.captureStream().getTracks();if(!o)throw Error(`Could not get empty media stream video track`);return o.enabled=n,o}var Zx;function Qx(){if(!Zx){let e=new AudioContext,t=e.createOscillator(),n=e.createGain();n.gain.setValueAtTime(0,0);let r=e.createMediaStreamDestination();if(t.connect(n),n.connect(r),t.start(),[Zx]=r.stream.getAudioTracks(),!Zx)throw Error(`Could not get empty media stream audio track`);Zx.enabled=!1}return Zx.clone()}var $x=class{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,n)=>z(this,void 0,void 0,function*(){this.resolve=t,this.reject=n,e&&(yield e(t,n))})).finally(()=>{var e;this._isResolved=!0,(e=this.onFinally)==null||e.call(this)})}};function eS(e){return Vb.includes(e)}function tS(e){if(typeof e==`string`||typeof e==`number`)return e;if(Array.isArray(e))return e[0];if(e.exact!==void 0)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal!==void 0)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error(`could not unwrap constraint`)}function nS(e){return e.startsWith(`http`)?e.replace(/^(http)/,`ws`):e}function rS(e){return e.startsWith(`ws`)?e.replace(/^(ws)/,`http`):e}function iS(e,t){return e.segments.map(e=>{let{id:n,text:r,language:i,startTime:a,endTime:o,final:s}=e,c=t.get(n)??Date.now(),l=Date.now();return s?t.delete(n):t.set(n,c),{id:n,text:r,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:s,language:i,firstReceivedTime:c,lastReceivedTime:l}})}function aS(e){let{id:t,timestamp:n,message:r,editTimestamp:i}=e;return{id:t,timestamp:Number.parseInt(n.toString()),editTimestamp:i?Number.parseInt(i.toString()):void 0,message:r}}function oS(e){switch(e.reason){case Eb.LeaveRequest:return e.context;case Eb.Cancelled:return Ng.CLIENT_INITIATED;case Eb.NotAllowed:return Ng.USER_REJECTED;case Eb.ServerUnreachable:return Ng.JOIN_FAILURE;default:return Ng.UNKNOWN_REASON}}function sS(e){return e===void 0?void 0:Number(e)}function cS(e){return e===void 0?void 0:BigInt(e)}function lS(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function uS(e){return!!e&&e.kind==q.Kind.Audio}function dS(e){return!!e&&e.kind==q.Kind.Video}function fS(e){return lS(e)&&dS(e)}function pS(e){return lS(e)&&uS(e)}function mS(e){return!!e&&!e.isLocal}function hS(e){return!!e&&!e.isLocal}function gS(e){return mS(e)&&dS(e)}function _S(e){return e.isLocal}function vS(e,t){let n=[],r=new TextEncoder().encode(e);for(;r.length>t;){let e=t;for(;e>0;){let t=r[e];if(t!==void 0&&(t&192)!=128)break;e--}n.push(r.slice(0,e)),r=r.slice(e)}return r.length>0&&n.push(r),n}function yS(e){let t=e.get(`Cache-Control`);if(t){let e=t.match(/(?:^|[,\s])max-age=(\d+)/)?.[1];if(e)return parseInt(e,10)}}function bS(){return typeof CompressionStream<`u`}function xS(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=SS(e,t);return n?r:TS(r,`v1`)}function SS(e,t){let n=new URL(nS(e));return t.forEach((e,t)=>{n.searchParams.set(t,e)}),TS(n,`rtc`)}function CS(e){return TS(new URL(rS(e)),`validate`)}function wS(e){return e.endsWith(`/`)?e:`${e}/`}function TS(e,t){return e.pathname=`${wS(e.pathname)}${t}`,e}function ES(e){if(typeof e==`string`)return j_.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return j_.fromBinary(new Uint8Array(e));throw Error(`could not decode websocket message: ${typeof e}`)}function DS(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Unknown reason`;if(!(e instanceof AbortSignal))return t;let n=e.reason;switch(typeof n){case`string`:return n;case`object`:return n instanceof Error?n.message:t;default:return`toString`in n?n.toString():t}}var OS=`lk_e2ee`,kS;(function(e){e.SetKey=`setKey`,e.RatchetRequest=`ratchetRequest`,e.KeyRatcheted=`keyRatcheted`})(kS||={});var AS;(function(e){e.KeyRatcheted=`keyRatcheted`})(AS||={});var jS;(function(e){e.ParticipantEncryptionStatusChanged=`participantEncryptionStatusChanged`,e.EncryptionError=`encryptionError`})(jS||={});var MS;(function(e){e.Error=`cryptorError`})(MS||={});function NS(){return FS()||PS()}function PS(){return window.RTCRtpScriptTransform!==void 0}function FS(){return window.RTCRtpSender!==void 0&&window.RTCRtpSender.prototype.createEncodedStreams!==void 0}function IS(e){if(e.value?.case!==`sipDtmf`&&e.value?.case!==`metrics`&&e.value?.case!==`speaker`&&e.value?.case!==`transcription`&&e.value?.case!==`encryptedPacket`)return new $g({value:e.value})}iy.EventEmitter;var LS;(function(e){e[e.InvalidKey=0]=`InvalidKey`,e[e.MissingKey=1]=`MissingKey`,e[e.InternalError=2]=`InternalError`})(LS||={});var RS=class extends iy.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=e=>{let{kind:t,data:n}=e.data;switch(t){case`error`:if(R.error(n.error.message),n.uuid){let e=this.decryptDataRequests.get(n.uuid);if(e?.reject){e.reject(n.error);break}let t=this.encryptDataRequests.get(n.uuid);if(t?.reject){t.reject(n.error);break}}this.emit(jS.EncryptionError,n.error,n.participantIdentity);break;case`initAck`:n.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)});break;case`enable`:if(n.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)}),this.encryptionEnabled!==n.enabled&&n.participantIdentity===this.room?.localParticipant.identity)this.emit(jS.ParticipantEncryptionStatusChanged,n.enabled,this.room.localParticipant),this.encryptionEnabled=n.enabled;else if(n.participantIdentity){let e=this.room?.getParticipantByIdentity(n.participantIdentity);if(!e)throw TypeError(`couldn't set encryption status, participant not found${n.participantIdentity}`);this.emit(jS.ParticipantEncryptionStatusChanged,n.enabled,e)}break;case`ratchetKey`:this.keyProvider.emit(kS.KeyRatcheted,n.ratchetResult,n.participantIdentity,n.keyIndex);break;case`decryptDataResponse`:let e=this.decryptDataRequests.get(n.uuid);e?.resolve&&e.resolve(n);break;case`encryptDataResponse`:let t=this.encryptDataRequests.get(n.uuid);t?.resolve&&t.resolve(n);break}},this.onWorkerError=e=>{R.error(`e2ee worker encountered an error:`,{error:e.error}),this.emit(jS.EncryptionError,e.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!NS())throw new Db(`tried to setup end-to-end encryption on an unsupported browser`);if(R.info(`setting up e2ee`),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);let t={kind:`init`,data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Gv.getLevel()}};this.worker&&(R.info(`initializing worker`,{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){R.debug(`set e2ee to ${e} for participant ${t}`),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?R.warn(`ignoring server sent trailer as it's empty`):this.postSifTrailer(e)}setupEngine(e){e.on(U.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(V.TrackPublished,(e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==L.NONE,t.identity)),e.on(V.ConnectionStateChanged,t=>{t===Y.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==L.NONE,e.identity)})})}).on(V.TrackUnsubscribed,(e,t,n)=>{var r;let i={kind:`removeTransform`,data:{participantIdentity:n.identity,trackId:e.mediaStreamID}};(r=this.worker)==null||r.postMessage(i)}).on(V.TrackSubscribed,(e,t,n)=>{this.setupE2EEReceiver(e,n.identity,t.trackInfo)}).on(V.SignalConnected,()=>{if(!this.room)throw TypeError(`expected room to be present on signal connect`);let e=t.getLatestManuallySetKeyIndex();t.getKeys().forEach(t=>{this.postKey(t,e===(t.keyIndex??0))}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(H.LocalSenderCreated,(e,t)=>z(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),e.localParticipant.on(H.LocalTrackPublished,e=>{if(!dS(e.track)||!Ax())return;let t={kind:`updateCodec`,data:{trackId:e.track.mediaStreamID,codec:rx(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}),t.on(kS.SetKey,(e,t)=>this.postKey(e,t??!0)).on(kS.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}encryptData(e){return z(this,void 0,void 0,function*(){if(!this.worker)throw Error(`could not encrypt data, worker is missing`);let t=crypto.randomUUID(),n={kind:`encryptDataRequest`,data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},r=new $x;return r.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,r),this.worker.postMessage(n),r.promise})}handleEncryptedData(e,t,n,r){if(!this.worker)throw Error(`could not handle encrypted data, worker is missing`);let i=crypto.randomUUID(),a={kind:`decryptDataRequest`,data:{uuid:i,payload:e,iv:t,participantIdentity:n,keyIndex:r}},o=new $x;return o.onFinally=()=>{this.decryptDataRequests.delete(i)},this.decryptDataRequests.set(i,o),this.worker.postMessage(a),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error(`could not ratchet key, worker is missing`);let n={kind:`ratchetRequest`,data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e,t){let{key:n,participantIdentity:r,keyIndex:i}=e;if(!this.worker)throw Error(`could not set key, worker is missing`);let a={kind:`setKey`,data:{participantIdentity:r,isPublisher:r===this.room?.localParticipant.identity,key:n,keyIndex:i,updateCurrentKeyIndex:t}};this.worker.postMessage(a)}postEnable(e,t){if(this.worker){let n={kind:`enable`,data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}else throw ReferenceError(`failed to enable e2ee, worker is not ready`)}postRTPMap(e){if(!this.worker)throw TypeError(`could not post rtp map, worker is missing`);if(!this.room?.localParticipant.identity)throw TypeError(`could not post rtp map, local participant identity is missing`);let t={kind:`setRTPMap`,data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}postSifTrailer(e){if(!this.worker)throw Error(`could not post SIF trailer, worker is missing`);let t={kind:`setSifTrailer`,data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,n){if(e.receiver){if(!n?.mimeType||n.mimeType===``)throw TypeError(`MimeType missing from trackInfo, cannot set up E2EE cryptor`);this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind===`video`?rx(n.mimeType):void 0)}}setupE2EESender(e,t){if(!lS(e)||!t){t||R.warn(`early return because sender is not ready`);return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,n,r){return z(this,void 0,void 0,function*(){if(this.worker){if(PS()&&!Ox()){let i={kind:`decode`,participantIdentity:n,trackId:t,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,i)}else{if(OS in e&&r){let e={kind:`updateCodec`,data:{trackId:t,codec:r,participantIdentity:n}};this.worker.postMessage(e);return}let i=e.writableStream,a=e.readableStream;if(!i||!a){let t=e.createEncodedStreams();e.writableStream=t.writable,i=t.writable,e.readableStream=t.readable,a=t.readable}let o={kind:`decode`,data:{readableStream:a,writableStream:i,trackId:t,codec:r,participantIdentity:n,isReuse:OS in e}};this.worker.postMessage(o,[a,i])}e[OS]=!0}})}handleSender(e,t,n){if(!(OS in e||!this.worker)){if(!this.room?.localParticipant.identity||this.room.localParticipant.identity===``)throw TypeError(`local identity needs to be known in order to set up encrypted sender`);if(PS()&&!Ox()){R.info(`initialize script transform`);let r={kind:`encode`,participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{R.info(`initialize encoded streams`);let r=e.createEncodedStreams(),i={kind:`encode`,data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(i,[r.readable,r.writable])}e[OS]=!0}}},zS=500,BS=15e3,VS=class e{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||=new e,this._instance}addFailedConnectionAttempt(e){let t=Rx(new URL(e));if(!t)return;let n=this.failedConnectionAttempts.get(t)??0;this.failedConnectionAttempts.set(t,n+1),this.backOffPromises.set(t,yx(Math.min(zS*2**n,BS)))}getBackOffPromise(e){let t=new URL(e),n=t&&Rx(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){let t=new URL(e),n=t&&Rx(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}};VS._instance=null;var HS=`default`,US=class e{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new e),this.instance}get previousDevices(){return this._previousDevices}getDevices(t){return z(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){if(e.userMediaPromiseMap?.size>0){R.debug(`awaiting getUserMedia promise`);try{t?yield e.userMediaPromiseMap.get(t):yield Promise.all(e.userMediaPromiseMap.values())}catch{R.warn(`error waiting for media permissons`)}}let i=yield navigator.mediaDevices.enumerateDevices();if(r&&!(kx()&&n.hasDeviceInUse(t))&&(i.filter(e=>e.kind===t).length===0||i.some(e=>{let n=e.label===``,r=t?e.kind===t:!0;return n&&r}))){let e={video:t!==`audioinput`&&t!==`audiooutput`,audio:t!==`videoinput`&&{deviceId:{ideal:`default`}}},n=yield navigator.mediaDevices.getUserMedia(e);i=yield navigator.mediaDevices.enumerateDevices(),n.getTracks().forEach(e=>{e.stop()})}return n._previousDevices=i,t&&(i=i.filter(e=>e.kind===t)),i}()})}normalizeDeviceId(e,t,n){return z(this,void 0,void 0,function*(){if(t!==HS)return t;let r=yield this.getDevices(e),i=r.find(e=>e.deviceId===HS);if(!i){R.warn(`could not reliably determine default device`);return}let a=r.find(e=>e.deviceId!==HS&&e.groupId===(n??i.groupId));if(!a){R.warn(`could not reliably determine default device`);return}return a?.deviceId})}hasDeviceInUse(t){return t?e.userMediaPromiseMap.has(t):e.userMediaPromiseMap.size>0}};US.mediaDeviceKinds=[`audioinput`,`audiooutput`,`videoinput`],US.userMediaPromiseMap=new Map;var WS=65535,GS=4294967295,KS=class e{static u16(t){return new e(t,WS)}static u32(t){return new e(t,GS)}constructor(e,t){if(this.value=e,e<0)throw Error(`WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0`);if(t>2**53-1)throw Error(`WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.`);this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new e(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t+e)}decrement(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t-e)}getThenIncrement(){let t=this.value;return this.increment(),new e(t,this.maxSize)}isBefore(e){let t=this.value>>>0,n=(e.value>>>0)-t>>>0;return n!==0&&n<this.maxSize+1}},qS=class e{static fromRtpTicks(t){return new e(t,9e4)}static rtpRandom(){let t=Math.round(Math.random()*GS);return e.fromRtpTicks(t)}constructor(e,t){this.timestamp=KS.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new e(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}},JS=class e{constructor(e,t,n){this.epoch=t,this.base=n,this.previous=n.clone(),this.rateInHz=e}static startingNow(t,n){return new e(n,new Date,t)}static startingAtTime(t,n,r){return new e(r,t,n)}static rtpStartingNow(t){return e.startingNow(t,9e4)}static rtpStartingAtTime(t,n){return e.startingAtTime(t,n,9e4)}now(){return this.at(new Date)}at(t){let n=t.getTime()-this.epoch.getTime(),r=e.durationInMsToTicks(n,this.rateInHz),i=this.base.clone();return i.wrappingAdd(r),i.isBefore(this.previous)&&(i=this.previous),this.previous=i.clone(),i.clone()}static durationInMsToTicks(e,t){let n=(e*1e6*t+5e8)/1e9;return Math.round(n)}};function YS(e){if(e instanceof DataView)return e;if(e instanceof ArrayBuffer)return new DataView(e);if(e instanceof Uint8Array)return new DataView(e.buffer,e.byteOffset,e.byteLength);throw Error(`Error coercing ${e} to DataView - input was not DataView, ArrayBuffer, or Uint8Array.`)}var XS;(function(e){e[e.Reserved=0]=`Reserved`,e[e.TooLarge=1]=`TooLarge`})(XS||={});var ZS=class e extends Tb{constructor(e,t){super(19,e),this.name=`DataTrackHandleError`,this.reason=t,this.reasonName=XS[t]}isReason(e){return this.reason===e}static tooLarge(){return new e(`Value too large to be a valid track handle`,XS.TooLarge)}static reserved(t){return new e(`0x${t.toString(16)} is a reserved value.`,XS.Reserved)}},QS={fromNumber(e){if(e===0)throw ZS.reserved(e);if(e>WS)throw ZS.tooLarge();return e}},$S=class{constructor(){this.value=0}get(){return this.value+=1,this.value>WS?null:this.value}},eC={from(e){return{sid:e.sid,pubHandle:e.pubHandle,name:e.name,usesE2ee:e.encryption!==L.NONE}},toProtobuf(e){return new Kg({sid:e.sid,pubHandle:e.pubHandle,name:e.name,encryption:e.usesE2ee?L.GCM:L.NONE})}},tC;(function(e){e[e.WAITING=0]=`WAITING`,e[e.RUNNING=1]=`RUNNING`,e[e.COMPLETED=2]=`COMPLETED`})(tC||={});var nC=class{constructor(){this.pendingTasks=new Map,this.taskMutex=new Dm,this.nextTaskIndex=0}run(e){return z(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:tC.WAITING};this.pendingTasks.set(t.id,t);let n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=tC.RUNNING,yield e()}finally{t.status=tC.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return z(this,void 0,void 0,function*(){return this.run(()=>z(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}},rC=class{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(t.signal?.aborted)throw new DOMException(`This operation was aborted`,`AbortError`);this.url=e;let n=new WebSocket(e,t.protocols??[]);n.binaryType=`arraybuffer`,this.ws=n;let r=function(){let{closeCode:e,reason:t}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return n.close(e,t)};this.opened=new gb((e,t)=>{let i=()=>{t(B.websocket(`Encountered websocket error during connection establishment`))};n.onopen=()=>{e({readable:new ReadableStream({start(e){n.onmessage=t=>{let{data:n}=t;return e.enqueue(n)},n.onerror=t=>e.error(t)},cancel:r}),writable:new WritableStream({write(e){n.send(e)},abort(){n.close()},close:r}),protocol:n.protocol,extensions:n.extensions}),n.removeEventListener(`error`,i)},n.addEventListener(`error`,i)}),this.closed=new gb((e,t)=>{let r=()=>z(this,void 0,void 0,function*(){let r=new gb(e=>{n.readyState!==WebSocket.CLOSED&&n.addEventListener(`close`,t=>{e(t)},{once:!0})}),i=yield gb.race([yx(250),r]);i?e(i):t(B.websocket(`Encountered unspecified websocket error without a timely close event`))});n.onclose=t=>{let{code:i,reason:a}=t;e({closeCode:i,reason:a}),n.removeEventListener(`error`,r)},n.addEventListener(`error`,r)}),t.signal&&(t.signal.onabort=()=>n.close()),this.close=r}},iC=[`syncState`,`trickle`,`offer`,`answer`,`simulate`,`leave`];function aC(e){let t=iC.indexOf(e.case)>=0;return R.trace(`request allowed to bypass queue:`,{canPass:t,req:e}),t}var oC;(function(e){e[e.CONNECTING=0]=`CONNECTING`,e[e.CONNECTED=1]=`CONNECTED`,e[e.RECONNECTING=2]=`RECONNECTING`,e[e.DISCONNECTING=3]=`DISCONNECTING`,e[e.DISCONNECTED=4]=`DISCONNECTED`})(oC||={});var sC=250,cC=class{get currentState(){return this.state}get isDisconnected(){return this.state===oC.DISCONNECTING||this.state===oC.DISCONNECTED}get isEstablishingConnection(){return this.state===oC.CONNECTING||this.state===oC.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.rtt=0,this.state=oC.DISCONNECTED,this.log=R,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=Wv(t.loggerName??Uv.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new nC,this.queuedRequests=[],this.closingLock=new Dm,this.connectionLock=new Dm,this.state=oC.DISCONNECTED}get logContext(){return this.loggerContextCb?.call(this)??{}}join(e,t,n,r){return z(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,o=arguments.length>5?arguments[5]:void 0;return function*(){return i.state=oC.CONNECTING,i.options=n,yield i.connect(e,t,n,r,a,o)}()})}reconnect(e,t,n,r){return z(this,void 0,void 0,function*(){if(!this.options){this.log.warn(`attempted to reconnect without signal options being set, ignoring`,this.logContext);return}return this.state=oC.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:r}),void 0,this.useV0SignalPath)})}connect(e,t,n,r){return z(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,o=arguments.length>5?arguments[5]:void 0;return function*(){let s=yield i.connectionLock.lock();i.connectOptions=n,i.useV0SignalPath=a;let c=Yx(),l=xS(e,a?dC(t,c,n):yield fC(t,c,n,o),a).toString(),u=CS(l).toString();return new Promise((e,t)=>z(i,void 0,void 0,function*(){try{let i=!1,a=e=>z(this,void 0,void 0,function*(){if(i)return;i=!0;let n=DS(e instanceof Event?e.currentTarget:e,`Abort handler called`);this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(n)).catch(e=>{this.log.error(e),this.close()}):this.close(),o(),t(B.cancelled(n))});r?.addEventListener(`abort`,a);let o=()=>{clearTimeout(s),r?.removeEventListener(`abort`,a)},s=setTimeout(()=>{a(B.timeout(`room connection has timed out (signal)`))},n.websocketTimeout),c=(e,t)=>{this.handleSignalConnected(e,s,t)},d=new URL(l);d.searchParams.has(`access_token`)&&d.searchParams.set(`access_token`,`<redacted>`),this.log.debug(`connecting to ${d}`,Object.assign({reconnect:n.reconnect,reconnectReason:n.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new rC(l);try{this.ws.closed.then(e=>{this.isEstablishingConnection&&t(B.internal(`Websocket got closed during a (re)connection attempt: ${e.reason}`)),e.closeCode!==1e3&&(this.log.warn(`websocket closed`,Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.closeCode,wasClean:e.closeCode===1e3,state:this.state})),this.state===oC.CONNECTED&&this.handleOnClose(e.reason??`Unexpected WS error`))}).catch(e=>{this.isEstablishingConnection&&t(B.internal(`Websocket error during a (re)connection attempt: ${e}`))});let r=yield this.ws.opened.catch(e=>z(this,void 0,void 0,function*(){if(this.state!==oC.CONNECTED){this.state=oC.DISCONNECTED,clearTimeout(s),t(yield this.handleConnectionError(e,u));return}this.handleWSError(e),t(e)}));if(clearTimeout(s),!r)return;let i=r.readable.getReader();this.streamWriter=r.writable.getWriter();let a=yield i.read();if(i.releaseLock(),!a.value)throw B.internal(`no message received as first message`);let o=ES(a.value),l=this.validateFirstMessage(o,n.reconnect??!1);if(!l.isValid){t(l.error);return}o.message?.case===`join`&&(this.pingTimeoutDuration=o.message.value.pingTimeout,this.pingIntervalDuration=o.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug(`ping config`,Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.onJoined&&this.onJoined(o.message.value)),c(r,l.shouldProcessFirstMessage?o:void 0),e(l.response)}catch(e){t(e)}finally{o()}}finally{s()}}))}()})}startReadingLoop(e,t){return z(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield yx(this.signalLatency));let{done:t,value:n}=yield e.read();if(t)break;let r=ES(n);this.handleSignalResponse(r)}})}close(){return z(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Close method called on signal client`;return function*(){if([oC.DISCONNECTING||oC.DISCONNECTED].includes(e.state)){e.log.debug(`ignoring signal close as it's already in disconnecting state`);return}let r=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=oC.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:n});let t=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([t,yx(sC)])}}catch(t){e.log.debug(`websocket error while closing`,Object.assign(Object.assign({},e.logContext),{error:t}))}finally{t&&(e.state=oC.DISCONNECTED),r()}}()})}sendOffer(e,t){this.log.debug(`sending offer`,Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:`offer`,value:uC(e,t)})}sendAnswer(e,t){return this.log.debug(`sending answer`,Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:`answer`,value:uC(e,t)})}sendIceCandidate(e,t){return this.log.debug(`sending ice candidate`,Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:`trickle`,value:new B_({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:`mute`,value:new V_({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:`addTrack`,value:e})}sendUpdateLocalMetadata(e,t){return z(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){let i=n.getNextRequestId();return yield n.sendRequest({case:`updateMetadata`,value:new rv({requestId:i,metadata:e,name:t,attributes:r})}),i}()})}sendUpdateTrackSettings(e){this.sendRequest({case:`trackSetting`,value:e})}sendUpdateSubscription(e){return this.sendRequest({case:`subscription`,value:e})}sendSyncState(e){return this.sendRequest({case:`syncState`,value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:`updateLayers`,value:new nv({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:`subscriptionPermission`,value:new gv({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:`simulate`,value:e})}sendPing(){return Promise.all([this.sendRequest({case:`ping`,value:ih.parse(Date.now())}),this.sendRequest({case:`pingReq`,value:new Cv({timestamp:ih.parse(Date.now()),rtt:ih.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:`updateAudioTrack`,value:new Q_({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:`leave`,value:new ev({reason:Ng.CLIENT_INITIATED,action:tv.DISCONNECT})})}sendPublishDataTrackRequest(e,t,n){return this.sendRequest({case:`publishDataTrackRequest`,value:new P_({pubHandle:e,name:t,encryption:n?L.GCM:L.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:`unpublishDataTrackRequest`,value:new I_({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:`updateDataSubscription`,value:new Y_({updates:[new X_({trackSid:e,subscribe:t})]})})}sendRequest(e){return z(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!n&&!aC(e)&&t.state===oC.RECONNECTING){t.queuedRequests.push(()=>z(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));return}if(n||(yield t.requestQueue.flush()),t.signalLatency&&(yield yx(t.signalLatency)),t.isDisconnected){t.log.debug(`skipping signal request (type: ${e.case}) - SignalClient disconnected`);return}if(!t.streamWriter){t.log.error(`cannot send signal request before connected, type: ${e?.case}`,t.logContext);return}let r=new A_({message:e});try{t.useJSON?yield t.streamWriter.write(r.toJsonString()):yield t.streamWriter.write(r.toBinary())}catch(e){t.log.error(`error sending signal message`,Object.assign(Object.assign({},t.logContext),{error:e}))}}()})}handleSignalResponse(e){let t=e.message;if(t==null){this.log.debug(`received unsupported message`,this.logContext);return}let n=!1;if(t.case===`answer`){let e=lC(t.value);this.onAnswer&&this.onAnswer(e,t.value.id,t.value.midToTrackId)}else if(t.case===`offer`){let e=lC(t.value);this.onOffer&&this.onOffer(e,t.value.id,t.value.midToTrackId)}else if(t.case===`trickle`){let e=JSON.parse(t.value.candidateInit);this.onTrickle&&this.onTrickle(e,t.value.target)}else t.case===`update`?this.onParticipantUpdate&&this.onParticipantUpdate(t.value.participants??[]):t.case===`trackPublished`?this.onLocalTrackPublished&&this.onLocalTrackPublished(t.value):t.case===`speakersChanged`?this.onSpeakersChanged&&this.onSpeakersChanged(t.value.speakers??[]):t.case===`leave`?this.onLeave&&this.onLeave(t.value):t.case===`mute`?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(t.value.sid,t.value.muted):t.case===`roomUpdate`?this.onRoomUpdate&&t.value.room&&this.onRoomUpdate(t.value.room):t.case===`connectionQuality`?this.onConnectionQuality&&this.onConnectionQuality(t.value):t.case===`streamStateUpdate`?this.onStreamStateUpdate&&this.onStreamStateUpdate(t.value):t.case===`subscribedQualityUpdate`?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(t.value):t.case===`subscriptionPermissionUpdate`?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(t.value):t.case===`refreshToken`?this.onTokenRefresh&&this.onTokenRefresh(t.value):t.case===`trackUnpublished`?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(t.value):t.case===`subscriptionResponse`?this.onSubscriptionError&&this.onSubscriptionError(t.value):t.case===`pong`||(t.case===`pongResp`?(this.rtt=Date.now()-Number.parseInt(t.value.lastPingTimestamp.toString()),this.resetPingTimeout(),n=!0):t.case===`requestResponse`?this.onRequestResponse&&this.onRequestResponse(t.value):t.case===`trackSubscribed`?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(t.value.trackSid):t.case===`roomMoved`?(this.onTokenRefresh&&this.onTokenRefresh(t.value.token),this.onRoomMoved&&this.onRoomMoved(t.value)):t.case===`mediaSectionsRequirement`?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(t.value):t.case===`publishDataTrackResponse`?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(t.value):t.case===`unpublishDataTrackResponse`?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(t.value):t.case===`dataTrackSubscriberHandles`?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(t.value):this.log.debug(`unsupported message`,Object.assign(Object.assign({},this.logContext),{msgCase:t.case})));n||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){let e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return z(this,void 0,void 0,function*(){if(this.state===oC.DISCONNECTED)return;let t=this.onClose;yield this.close(void 0,e),this.log.debug(`websocket connection closed: ${e}`,Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error(`websocket error`,Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn(`ping timeout duration not set`,this.logContext);return}this.pingTimeout=Rb.setTimeout(()=>{this.log.warn(`ping timeout triggered. last pong received at: ${new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()}`,this.logContext),this.handleOnClose(`ping timeout`)},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Rb.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn(`ping interval duration not set`,this.logContext);return}this.log.debug(`start ping interval`,this.logContext),this.pingInterval=Rb.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug(`clearing ping interval`,this.logContext),this.clearPingTimeout(),this.pingInterval&&Rb.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n){this.state=oC.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),n)}validateFirstMessage(e,t){return e.message?.case===`join`?{isValid:!0,response:e.message.value}:this.state===oC.RECONNECTING&&e.message?.case!==`leave`?e.message?.case===`reconnect`?{isValid:!0,response:e.message.value}:(this.log.debug(`declaring signal reconnected without reconnect response received`,this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&e.message?.case===`leave`?{isValid:!1,error:B.leaveRequest(`Received leave request while trying to (re)connect`,e.message.value.reason)}:t?{isValid:!1,error:B.internal(`Unexpected first message`)}:{isValid:!1,error:B.internal(`did not receive join response, got ${e.message?.case} instead`)}}handleConnectionError(e,t){return z(this,void 0,void 0,function*(){try{let n=yield fetch(t);switch(n.status){case 404:return B.serviceNotFound(`v1 RTC path not found. Consider upgrading your LiveKit server version`,`v0-rtc`);case 401:case 403:let e=yield n.text();return B.notAllowed(e,n.status);default:break}return e instanceof B?e:B.internal(`Encountered unknown websocket error during connection: ${e}`,{status:n.status,statusText:n.statusText})}catch(e){return e instanceof B?e:B.serverUnreachable(e instanceof Error?e.message:`server was not reachable`)}})}};function lC(e){let t={type:`offer`,sdp:e.sdp};switch(e.type){case`answer`:case`offer`:case`pranswer`:case`rollback`:t.type=e.type;break}return t}function uC(e,t){return new K_({sdp:e.sdp,type:e.type,id:t})}function dC(e,t,n){let r=new URLSearchParams;return r.set(`access_token`,e),n.reconnect&&(r.set(`reconnect`,`1`),n.sid&&r.set(`sid`,n.sid)),r.set(`auto_subscribe`,n.autoSubscribe?`1`:`0`),r.set(`sdk`,Ix()?`reactnative`:`js`),r.set(`version`,t.version),r.set(`protocol`,t.protocol.toString()),t.deviceModel&&r.set(`device_model`,t.deviceModel),t.os&&r.set(`os`,t.os),t.osVersion&&r.set(`os_version`,t.osVersion),t.browser&&r.set(`browser`,t.browser),t.browserVersion&&r.set(`browser_version`,t.browserVersion),n.adaptiveStream&&r.set(`adaptive_stream`,`1`),n.reconnectReason&&r.set(`reconnect_reason`,n.reconnectReason.toString()),navigator.connection?.type&&r.set(`network`,navigator.connection.type),r}function fC(e,t,n,r){return z(this,void 0,void 0,function*(){let i=new URLSearchParams;i.set(`access_token`,e);let a=new Mv({clientInfo:t,connectionSettings:new jv({autoSubscribe:!!n.autoSubscribe,adaptiveStream:!!n.adaptiveStream}),reconnect:!!n.reconnect,participantSid:n.sid?n.sid:void 0,publisherOffer:r});n.reconnectReason&&(a.reconnectReason=n.reconnectReason);let o=a.toBinary(),s,c;if(bS()){let e=new CompressionStream(`gzip`),t=e.writable.getWriter();t.write(new Uint8Array(o)),t.close();let n=[],r=e.readable.getReader();for(;;){let{done:e,value:t}=yield r.read();if(e)break;n.push(t)}let i=n.reduce((e,t)=>e+t.length,0),a=new Uint8Array(i),l=0;for(let e of n)a.set(e,l),l+=e.length;s=a,c=Pv.GZIP}else s=o,c=Pv.NONE;let l=new Nv({joinRequest:s,compression:c}).toBinary();return i.set(`join_request`,(e=>{let t=Array.from(e,e=>String.fromCodePoint(e)).join(``);return btoa(t)})(l).replace(/\+/g,`-`).replace(/\//g,`_`)),i})}var pC=class{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){let e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){let t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}},mC=class{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){let n=Date.now();n-this._lastCleanup>this.ttl/2&&this.cleanup();let r=n+this.ttl;return this._map.set(e,{value:t,expiresAt:r}),this}get(e){let t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){let t=this._map.get(e);return t?t.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){let e=Date.now();for(let[t,n]of this._map.entries())n.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(let[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e(n.value,t,this.asValueMap())}map(e){this.cleanup();let t=[],n=this.asValueMap();for(let[r,i]of n.entries())t.push(e(i,r,n));return t}asValueMap(){let e=new Map;for(let[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e.set(t,n.value);return e}},hC={},gC={},_C={exports:{}},vC;function yC(){if(vC)return _C.exports;vC=1;var e=_C.exports={v:[{name:`version`,reg:/^(\d*)$/}],o:[{name:`origin`,reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:[`username`,`sessionId`,`sessionVersion`,`netType`,`ipVer`,`address`],format:`%s %s %d %s IP%d %s`}],s:[{name:`name`}],i:[{name:`description`}],u:[{name:`uri`}],e:[{name:`email`}],p:[{name:`phone`}],z:[{name:`timezones`}],r:[{name:`repeats`}],t:[{name:`timing`,reg:/^(\d*) (\d*)/,names:[`start`,`stop`],format:`%d %d`}],c:[{name:`connection`,reg:/^IN IP(\d) (\S*)/,names:[`version`,`ip`],format:`IN IP%d %s`}],b:[{push:`bandwidth`,reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:[`type`,`limit`],format:`%s:%s`}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:[`type`,`port`,`protocol`,`payloads`],format:`%s %d %s %s`}],a:[{push:`rtp`,reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:[`payload`,`codec`,`rate`,`encoding`],format:function(e){return e.encoding?`rtpmap:%d %s/%s/%s`:e.rate?`rtpmap:%d %s/%s`:`rtpmap:%d %s`}},{push:`fmtp`,reg:/^fmtp:(\d*) ([\S| ]*)/,names:[`payload`,`config`],format:`fmtp:%d %s`},{name:`control`,reg:/^control:(.*)/,format:`control:%s`},{name:`rtcp`,reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:[`port`,`netType`,`ipVer`,`address`],format:function(e){return e.address==null?`rtcp:%d`:`rtcp:%d %s IP%d %s`}},{push:`rtcpFbTrrInt`,reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:[`payload`,`value`],format:`rtcp-fb:%s trr-int %d`},{push:`rtcpFb`,reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:[`payload`,`type`,`subtype`],format:function(e){return e.subtype==null?`rtcp-fb:%s %s`:`rtcp-fb:%s %s %s`}},{push:`ext`,reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:[`value`,`direction`,`encrypt-uri`,`uri`,`config`],format:function(e){return`extmap:%d`+(e.direction?`/%s`:`%v`)+(e[`encrypt-uri`]?` %s`:`%v`)+` %s`+(e.config?` %s`:``)}},{name:`extmapAllowMixed`,reg:/^(extmap-allow-mixed)/},{push:`crypto`,reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:[`id`,`suite`,`config`,`sessionConfig`],format:function(e){return e.sessionConfig==null?`crypto:%d %s %s`:`crypto:%d %s %s %s`}},{name:`setup`,reg:/^setup:(\w*)/,format:`setup:%s`},{name:`connectionType`,reg:/^connection:(new|existing)/,format:`connection:%s`},{name:`mid`,reg:/^mid:([^\s]*)/,format:`mid:%s`},{name:`msid`,reg:/^msid:(.*)/,format:`msid:%s`},{name:`ptime`,reg:/^ptime:(\d*(?:\.\d*)*)/,format:`ptime:%d`},{name:`maxptime`,reg:/^maxptime:(\d*(?:\.\d*)*)/,format:`maxptime:%d`},{name:`direction`,reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:`icelite`,reg:/^(ice-lite)/},{name:`iceUfrag`,reg:/^ice-ufrag:(\S*)/,format:`ice-ufrag:%s`},{name:`icePwd`,reg:/^ice-pwd:(\S*)/,format:`ice-pwd:%s`},{name:`fingerprint`,reg:/^fingerprint:(\S*) (\S*)/,names:[`type`,`hash`],format:`fingerprint:%s %s`},{push:`candidates`,reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:[`foundation`,`component`,`transport`,`priority`,`ip`,`port`,`type`,`raddr`,`rport`,`tcptype`,`generation`,`network-id`,`network-cost`],format:function(e){var t=`candidate:%s %d %s %d %s %d typ %s`;return t+=e.raddr==null?`%v%v`:` raddr %s rport %d`,t+=e.tcptype==null?`%v`:` tcptype %s`,e.generation!=null&&(t+=` generation %d`),t+=e[`network-id`]==null?`%v`:` network-id %d`,t+=e[`network-cost`]==null?`%v`:` network-cost %d`,t}},{name:`endOfCandidates`,reg:/^(end-of-candidates)/},{name:`remoteCandidates`,reg:/^remote-candidates:(.*)/,format:`remote-candidates:%s`},{name:`iceOptions`,reg:/^ice-options:(\S*)/,format:`ice-options:%s`},{push:`ssrcs`,reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:[`id`,`attribute`,`value`],format:function(e){var t=`ssrc:%d`;return e.attribute!=null&&(t+=` %s`,e.value!=null&&(t+=`:%s`)),t}},{push:`ssrcGroups`,reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:[`semantics`,`ssrcs`],format:`ssrc-group:%s %s`},{name:`msidSemantic`,reg:/^msid-semantic:\s?(\w*) (\S*)/,names:[`semantic`,`token`],format:`msid-semantic: %s %s`},{push:`groups`,reg:/^group:(\w*) (.*)/,names:[`type`,`mids`],format:`group:%s %s`},{name:`rtcpMux`,reg:/^(rtcp-mux)/},{name:`rtcpRsize`,reg:/^(rtcp-rsize)/},{name:`sctpmap`,reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:[`sctpmapNumber`,`app`,`maxMessageSize`],format:function(e){return e.maxMessageSize==null?`sctpmap:%s %s`:`sctpmap:%s %s %s`}},{name:`xGoogleFlag`,reg:/^x-google-flag:([^\s]*)/,format:`x-google-flag:%s`},{push:`rids`,reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:[`id`,`direction`,`params`],format:function(e){return e.params?`rid:%s %s %s`:`rid:%s %s`}},{push:`imageattrs`,reg:RegExp(`^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?`),names:[`pt`,`dir1`,`attrs1`,`dir2`,`attrs2`],format:function(e){return`imageattr:%s %s %s`+(e.dir2?` %s %s`:``)}},{name:`simulcast`,reg:RegExp(`^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$`),names:[`dir1`,`list1`,`dir2`,`list2`],format:function(e){return`simulcast:%s %s`+(e.dir2?` %s %s`:``)}},{name:`simulcast_03`,reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:[`value`],format:`simulcast: %s`},{name:`framerate`,reg:/^framerate:(\d+(?:$|\.\d+))/,format:`framerate:%s`},{name:`sourceFilter`,reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:[`filterMode`,`netType`,`addressTypes`,`destAddress`,`srcList`],format:`source-filter: %s %s %s %s %s`},{name:`bundleOnly`,reg:/^(bundle-only)/},{name:`label`,reg:/^label:(.+)/,format:`label:%s`},{name:`sctpPort`,reg:/^sctp-port:(\d+)$/,format:`sctp-port:%s`},{name:`maxMessageSize`,reg:/^max-message-size:(\d+)$/,format:`max-message-size:%s`},{push:`tsRefClocks`,reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:[`clksrc`,`clksrcExt`],format:function(e){return`ts-refclk:%s`+(e.clksrcExt==null?``:`=%s`)}},{name:`mediaClk`,reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:[`id`,`mediaClockName`,`mediaClockValue`,`rateNumerator`,`rateDenominator`],format:function(e){var t=`mediaclk:`;return t+=e.id==null?`%v%s`:`id=%s %s`,t+=e.mediaClockValue==null?``:`=%s`,t+=e.rateNumerator==null?``:` rate=%s`,t+=e.rateDenominator==null?``:`/%s`,t}},{name:`keywords`,reg:/^keywds:(.+)$/,format:`keywds:%s`},{name:`content`,reg:/^content:(.+)/,format:`content:%s`},{name:`bfcpFloorCtrl`,reg:/^floorctrl:(c-only|s-only|c-s)/,format:`floorctrl:%s`},{name:`bfcpConfId`,reg:/^confid:(\d+)/,format:`confid:%s`},{name:`bfcpUserId`,reg:/^userid:(\d+)/,format:`userid:%s`},{name:`bfcpFloorId`,reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:[`id`,`mStream`],format:`floorid:%s mstrm:%s`},{push:`invalid`,names:[`value`]}]};return Object.keys(e).forEach(function(t){e[t].forEach(function(e){e.reg||=/(.*)/,e.format||=`%s`})}),_C.exports}var bC;function xC(){return bC?gC:(bC=1,(function(e){var t=function(e){return String(Number(e))===e?Number(e):e},n=function(e,n,r,i){if(i&&!r)n[i]=t(e[1]);else for(var a=0;a<r.length;a+=1)e[a+1]!=null&&(n[r[a]]=t(e[a+1]))},r=function(e,t,r){var i=e.name&&e.names;e.push&&!t[e.push]?t[e.push]=[]:i&&!t[e.name]&&(t[e.name]={});var a=e.push?{}:i?t[e.name]:t;n(r.match(e.reg),a,e.names,e.name),e.push&&t[e.push].push(a)},i=yC(),a=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},n=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(a).forEach(function(e){var t=e[0],a=e.slice(2);t===`m`&&(n.push({rtp:[],fmtp:[]}),o=n[n.length-1]);for(var s=0;s<(i[t]||[]).length;s+=1){var c=i[t][s];if(c.reg.test(a))return r(c,o,a)}}),t.media=n,t};var o=function(e,n){var r=n.split(/=(.+)/,2);return r.length===2?e[r[0]]=t(r[1]):r.length===1&&n.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(` `).map(Number)},e.parseRemoteCandidates=function(e){for(var n=[],r=e.split(` `).map(t),i=0;i<r.length;i+=3)n.push({component:r[i],ip:r[i+1],port:r[i+2]});return n},e.parseImageAttributes=function(e){return e.split(` `).map(function(e){return e.substring(1,e.length-1).split(`,`).reduce(o,{})})},e.parseSimulcastStreamList=function(e){return e.split(`;`).map(function(e){return e.split(`,`).map(function(e){var n,r=!1;return e[0]===`~`?(n=t(e.substring(1,e.length)),r=!0):n=t(e),{scid:n,paused:r}})})}})(gC),gC)}var SC,CC;function wC(){if(CC)return SC;CC=1;var e=yC(),t=/%[sdv%]/g,n=function(e){var n=1,r=arguments,i=r.length;return e.replace(t,function(e){if(n>=i)return e;var t=r[n];switch(n+=1,e){case`%%`:return`%`;case`%s`:return String(t);case`%d`:return Number(t);case`%v`:return``}})},r=function(e,t,r){var i=t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format,a=[e+`=`+i];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?a.push(r[t.name][s]):a.push(r[t.names[o]])}else a.push(r[t.name]);return n.apply(null,a)},i=[`v`,`o`,`s`,`i`,`u`,`e`,`p`,`c`,`b`,`t`,`r`,`z`,`a`],a=[`i`,`c`,`b`,`a`];return SC=function(t,n){n||={},t.version??=0,t.name??=` `,t.media.forEach(function(e){e.payloads??=``});var o=n.outerOrder||i,s=n.innerOrder||a,c=[];return o.forEach(function(n){e[n].forEach(function(e){e.name in t&&t[e.name]!=null?c.push(r(n,e,t)):e.push in t&&t[e.push]!=null&&t[e.push].forEach(function(t){c.push(r(n,e,t))})})}),t.media.forEach(function(t){c.push(r(`m`,e.m[0],t)),s.forEach(function(n){e[n].forEach(function(e){e.name in t&&t[e.name]!=null?c.push(r(n,e,t)):e.push in t&&t[e.push]!=null&&t[e.push].forEach(function(t){c.push(r(n,e,t))})})})}),c.join(`\r
|
|
37
61
|
`)+`\r
|
|
38
|
-
`},Cd}var Ed;function Dd(){if(Ed)return gd;Ed=1;var e=Sd(),t=Td();return gd.grammar=bd(),gd.write=t,gd.parse=e.parse,gd.parseParams=e.parseParams,gd.parseFmtpConfig=e.parseFmtpConfig,gd.parsePayloads=e.parsePayloads,gd.parseRemoteCandidates=e.parseRemoteCandidates,gd.parseImageAttributes=e.parseImageAttributes,gd.parseSimulcastStreamList=e.parseSimulcastStreamList,gd}var Od=Dd();function kd(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:50,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r,i=n.isImmediate??!1,a=n.callback??!1,o=n.maxWait,s=Date.now(),c=[];function l(){if(o!==void 0){let e=Date.now()-s;if(e+t>=o)return o-e}return t}let u=function(){for(var t=arguments.length,n=Array(t),o=0;o<t;o++)n[o]=arguments[o];let u=this;return new Promise((t,o)=>{let d=function(){if(r=void 0,s=Date.now(),!i){let t=e.apply(u,n);a&&a(t),c.forEach(e=>{let{resolve:n}=e;return n(t)}),c=[]}},f=i&&r===void 0;if(r!==void 0&&Bc.clearTimeout(r),r=Bc.setTimeout(d,l()),f){let r=e.apply(u,n);return a&&a(r),t(r)}c.push({resolve:t,reject:o})})};return u.cancel=function(e){r!==void 0&&Bc.clearTimeout(r),c.forEach(t=>{let{reject:n}=t;return n(e)}),c=[]},u}var Ad=.7,jd=20,Md={NegotiationStarted:`negotiationStarted`,NegotiationComplete:`negotiationComplete`,RTPVideoPayloadTypes:`rtpVideoPayloadTypes`},Nd=class extends ss.EventEmitter{get pc(){return this._pc||=this.createPC(),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),this.log=P,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=kd(e=>F(this,void 0,void 0,function*(){this.emit(Md.NegotiationStarted);try{yield this.createAndSendOffer()}catch(t){if(e)e(t);else throw t}}),jd),this.close=()=>{this._pc&&=(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,null)},this.log=qo(t.loggerName??Ko.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new kn}createPC(){let e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&((t=this.onIceCandidate)==null||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;(t=this.onIceCandidateError)==null||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)==null||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)==null||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)==null||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;(t=this.onDataChannel)==null||t.call(this,e)},e.ontrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)},e}get logContext(){var e;return Object.assign({},(e=this.loggerOptions).loggerContextCb?.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState===`connected`||this.pc.iceConnectionState===`completed`)}addIceCandidate(e){return F(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return F(this,void 0,void 0,function*(){if(e.type===`answer`&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn(`ignoring answer for old offer`,Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let n;if(e.type===`offer`){let{stereoMids:t,nackMids:n}=Fd(e);this.remoteStereoMids=t,this.remoteNackMids=n}else if(e.type===`answer`){if(this.pendingInitialOffer){let e=this.pendingInitialOffer;this.pendingInitialOffer=void 0;let t=Od.parse(e.sdp??``);t.media.forEach(e=>{Id(e)}),this.log.debug(`setting pending initial offer before processing answer`,this.logContext),yield this.setMungedSDP(e,Od.write(t))}let t=Od.parse(e.sdp??``);t.media.forEach(e=>{let t=Ld(e.mid);e.type===`audio`&&this.trackBitrates.some(n=>{if(!n.transceiver||t!=n.transceiver.mid)return!1;let r=0;if(e.rtp.some(e=>e.codec.toUpperCase()===n.codec.toUpperCase()?(r=e.payload,!0):!1),r===0)return!0;let i=!1;for(let t of e.fmtp)if(t.payload===r){t.config=t.config.split(`;`).filter(e=>!e.includes(`maxaveragebitrate`)).join(`;`),n.maxbr>0&&(t.config+=`;maxaveragebitrate=${n.maxbr*1e3}`),i=!0;break}return i||n.maxbr>0&&e.fmtp.push({payload:r,config:`maxaveragebitrate=${n.maxbr*1e3}`}),!0})}),n=Od.write(t)}return yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach(e=>{this.pc.addIceCandidate(e)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type===`answer`&&(this.emit(Md.NegotiationComplete),e.sdp&&Od.parse(e.sdp).media.forEach(e=>{e.type===`video`&&this.emit(Md.RTPVideoPayloadTypes,e.rtp)})),!0})}createInitialOffer(){return F(this,void 0,void 0,function*(){let e=yield this.offerLock.lock();try{if(this.pc.signalingState!==`stable`){this.log.warn(`signaling state is not stable, cannot create initial offer`,this.logContext);return}let e=this.latestOfferId+1;this.latestOfferId=e;let t=yield this.pc.createOffer();this.pendingInitialOffer={sdp:t.sdp,type:t.type};let n=Od.parse(t.sdp??``);return n.media.forEach(e=>{Id(e)}),t.sdp=Od.write(n),{offer:t,offerId:e}}finally{e()}})}createAndSendOffer(e){return F(this,void 0,void 0,function*(){let t=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.log.debug(`restarting ICE`,this.logContext),this.restartingIce=!0),this._pc&&(this._pc.signalingState===`have-local-offer`||this.pendingInitialOffer)){let t=this._pc.remoteDescription;if(e?.iceRestart&&t)yield this._pc.setRemoteDescription(t);else{this.renegotiate=!0,this.log.debug(`requesting renegotiation`,Object.assign({},this.logContext));return}}else if(!this._pc||this._pc.signalingState===`closed`){this.log.warn(`could not createOffer with closed peer connection`,this.logContext);return}this.log.debug(`starting to negotiate`,this.logContext);let t=this.latestOfferId+1;this.latestOfferId=t;let n=yield this.pc.createOffer(e);this.log.debug(`original offer`,Object.assign({sdp:n.sdp},this.logContext));let r=Od.parse(n.sdp??``);if(r.media.forEach(e=>{Id(e),e.type===`audio`?Pd(e,[`all`],[]):e.type===`video`&&this.trackBitrates.some(t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let n=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()?(n=e.payload,!0):!1),n===0||(El(t.codec)&&!jl()&&this.ensureVideoDDExtensionForSVC(e,r),!El(t.codec)))return!0;let i=Math.round(t.maxbr*Ad);for(let t of e.fmtp)if(t.payload===n){t.config.includes(`x-google-start-bitrate`)||(t.config+=`;x-google-start-bitrate=${i}`);break}return!0})}),this.latestOfferId>t){this.log.warn(`latestOfferId mismatch`,Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:t}));return}yield this.setMungedSDP(n,Od.write(r)),this.onOffer(n,this.latestOfferId)}finally{t()}})}createAndSetAnswer(){return F(this,void 0,void 0,function*(){let e=yield this.pc.createAnswer(),t=Od.parse(e.sdp??``);return t.media.forEach(e=>{Id(e),e.type===`audio`&&Pd(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(e,Od.write(t)),e})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new Mc(`PC closed, cannot add track`);return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){if(!this._pc)throw new Mc(`PC closed, cannot configure`);return this._pc?.setConfiguration(e)}canRemoveTrack(){return!!this._pc?.removeTrack}removeTrack(e){return this._pc?.removeTrack(e)}getConnectionState(){return this._pc?.connectionState??`closed`}getICEConnectionState(){return this._pc?.iceConnectionState??`closed`}getSignallingState(){return this._pc?.signalingState??`closed`}getTransceivers(){return this._pc?.getTransceivers()??[]}getSenders(){return this._pc?.getSenders()??[]}getLocalDescription(){return this._pc?.localDescription}getRemoteDescription(){return this.pc?.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return F(this,void 0,void 0,function*(){if(!this._pc)return;let e=``,t=new Map,n=new Map;if((yield this._pc.getStats()).forEach(r=>{switch(r.type){case`transport`:e=r.selectedCandidatePairId;break;case`candidate-pair`:e===``&&r.selected&&(e=r.id),t.set(r.id,r);break;case`remote-candidate`:n.set(r.id,`${r.address}:${r.port}`);break}}),e===``)return;let r=t.get(e)?.remoteCandidateId;if(r!==void 0)return n.get(r)})}setMungedSDP(e,t,n){return F(this,void 0,void 0,function*(){if(t){let r=e.sdp;e.sdp=t;try{this.log.debug(`setting munged ${n?`remote`:`local`} description`,this.logContext),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(n){this.log.warn(`not able to set ${e.type}, falling back to unmodified sdp`,Object.assign(Object.assign({},this.logContext),{error:n,sdp:t})),e.sdp=r}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(t){let r=`unknown error`;t instanceof Error?r=t.message:typeof t==`string`&&(r=t);let i={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(i.remoteSdp=this.pc.remoteDescription),this.log.error(`unable to set ${e.type}`,Object.assign(Object.assign({},this.logContext),{fields:i})),new Nc(r)}})}ensureVideoDDExtensionForSVC(e,t){var n;if(!e.ext?.some(e=>e.uri===yl)){if(this.ddExtID===0){let e=0;t.media.forEach(t=>{var n;t.type===`video`&&((n=t.ext)==null||n.forEach(t=>{t.value>e&&(e=t.value)}))}),this.ddExtID=e+1}(n=e.ext)==null||n.push({value:this.ddExtID,uri:yl})}}};function Pd(e,t,n){let r=Ld(e.mid),i=0;e.rtp.some(e=>e.codec===`opus`?(i=e.payload,!0):!1),i>0&&(e.rtcpFb||=[],n.includes(r)&&!e.rtcpFb.some(e=>e.payload===i&&e.type===`nack`)&&e.rtcpFb.push({payload:i,type:`nack`}),(t.includes(r)||t.length===1&&t[0]===`all`)&&e.fmtp.some(e=>e.payload===i?(e.config.includes(`stereo=1`)||(e.config+=`;stereo=1`),!0):!1))}function Fd(e){let t=[],n=[],r=Od.parse(e.sdp??``),i=0;return r.media.forEach(e=>{let r=Ld(e.mid);e.type===`audio`&&(e.rtp.some(e=>e.codec===`opus`?(i=e.payload,!0):!1),e.rtcpFb?.some(e=>e.payload===i&&e.type===`nack`)&&n.push(r),e.fmtp.some(e=>e.payload===i?(e.config.includes(`sprop-stereo=1`)&&t.push(r),!0):!1))}),{stereoMids:t,nackMids:n}}function Id(e){if(e.connection){let t=e.connection.ip.indexOf(`:`)>=0;(e.connection.version===4&&t||e.connection.version===6&&!t)&&(e.connection.ip=`0.0.0.0`,e.connection.version=4)}}function Ld(e){return typeof e==`number`?e.toFixed(0):e}var Rd=`vp8`,zd={audioPreset:qc.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Xc.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Rd,backupCodec:!0,preConnectBuffer:!1},Bd={deviceId:{ideal:`default`},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Vd={deviceId:{ideal:`default`},resolution:Jc.h720.resolution},Hd={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Zo,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Ud={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3},Wd;(function(e){e[e.NEW=0]=`NEW`,e[e.CONNECTING=1]=`CONNECTING`,e[e.CONNECTED=2]=`CONNECTED`,e[e.FAILED=3]=`FAILED`,e[e.CLOSING=4]=`CLOSING`,e[e.CLOSED=5]=`CLOSED`})(Wd||={});var Gd=class{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,n){this.peerConnectionTimeout=Ud.peerConnectionTimeout,this.log=P,this.updateState=()=>{var e;let t=this.state,n=this.requiredTransports.map(e=>e.getConnectionState());n.every(e=>e===`connected`)?this.state=Wd.CONNECTED:n.some(e=>e===`failed`)?this.state=Wd.FAILED:n.some(e=>e===`connecting`)?this.state=Wd.CONNECTING:n.every(e=>e===`closed`)?this.state=Wd.CLOSED:n.some(e=>e===`closed`)?this.state=Wd.CLOSING:n.every(e=>e===`new`)&&(this.state=Wd.NEW),t!==this.state&&(this.log.debug(`pc state change: from ${Wd[t]} to ${Wd[this.state]}`,this.logContext),(e=this.onStateChange)==null||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber?.getConnectionState()))},this.log=qo(t.loggerName??Ko.PCManager),this.loggerOptions=t,this.isPublisherConnectionRequired=e!==`subscriber-primary`,this.isSubscriberConnectionRequired=e===`subscriber-primary`,this.publisher=new Nd(n,t),this._mode=e,e!==`publisher-only`&&(this.subscriber=new Nd(n,t),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=e=>{var t;(t=this.onIceCandidate)==null||t.call(this,e,ka.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;(t=this.onDataChannel)==null||t.call(this,e)},this.subscriber.onTrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;(t=this.onIceCandidate)==null||t.call(this,e,ka.PUBLISHER)},this.publisher.onTrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var n;(n=this.onPublisherOffer)==null||n.call(this,e,t)},this.state=Wd.NEW,this.connectionLock=new kn,this.remoteOfferLock=new kn}get logContext(){var e;return Object.assign({},(e=this.loggerOptions).loggerContextCb?.call(e))}requirePublisher(){this.isPublisherConnectionRequired=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return F(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!==`closed`){let e=this.publisher;for(let t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn(`could not removeTrack`,Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),this.subscriber?.close()]),this.updateState()})}triggerIceRestart(){return F(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return F(this,void 0,void 0,function*(){t===ka.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber?.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return F(this,void 0,void 0,function*(){this.log.debug(`received server offer`,Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber?.getSignallingState().toString()}));let n=yield this.remoteOfferLock.lock();try{return(yield this.subscriber?.setRemoteDescription(e,t))?yield this.subscriber?.createAndSetAnswer():void 0}finally{n()}})}updateConfiguration(e,t){var n;this.publisher.setConfiguration(e),(n=this.subscriber)==null||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return F(this,void 0,void 0,function*(){let n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!==`connected`&&this.publisher.getConnectionState()!==`connecting`&&(this.log.debug(`negotiation required, start negotiating`,this.logContext),this.publisher.negotiate()),yield Promise.all(this.requiredTransports?.map(n=>this.ensureTransportConnected(n,e,t)))}finally{n()}})}negotiate(e){return F(this,void 0,void 0,function*(){return new yc((t,n)=>F(this,void 0,void 0,function*(){let r=setTimeout(()=>{n(new Nc(`negotiation timed out`))},this.peerConnectionTimeout),i=()=>{clearTimeout(r),this.publisher.off(Md.NegotiationStarted,o),e.signal.removeEventListener(`abort`,a)},a=()=>{i(),n(new Nc(`negotiation aborted`))},o=()=>{e.signal.aborted||(clearTimeout(r),r=setTimeout(()=>{i(),n(new Nc(`negotiation timed out`))},this.peerConnectionTimeout))};e.signal.addEventListener(`abort`,a),this.publisher.on(Md.NegotiationStarted,o),this.publisher.once(Md.NegotiationComplete,()=>{i(),t()}),yield this.publisher.negotiate(e=>{i(),e instanceof Error?n(e):n(Error(String(e)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){return(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(t=>t.receiver===e)?.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===ka.PUBLISHER||e===ka.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){let e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return F(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(e.getConnectionState()!==`connected`)return new Promise((e,i)=>F(n,void 0,void 0,function*(){let n=()=>{this.log.warn(`abort transport connection`,this.logContext),Bc.clearTimeout(a),i(L.cancelled(`room connection has been cancelled`))};t?.signal.aborted&&n(),t?.signal.addEventListener(`abort`,n);let a=Bc.setTimeout(()=>{t?.signal.removeEventListener(`abort`,n),i(L.internal(`could not establish pc connection`))},r);for(;this.state!==Wd.CONNECTED;)if(yield xl(50),t?.signal.aborted){i(L.cancelled(`room connection has been cancelled`));return}Bc.clearTimeout(a),t?.signal.removeEventListener(`abort`,n),e()}))}()})}},Kd=5e3,qd=3e4,Jd=class e{static fetchRegionSettings(t,n,r){return F(this,void 0,void 0,function*(){let i=yield e.fetchLock.lock();try{let e=yield fetch(`${Yd(t)}/regions`,{headers:{authorization:`Bearer ${n}`},signal:r});if(e.ok){let t=xu(e.headers),n=t?t*1e3:Kd;return{regionSettings:yield e.json(),updatedAtInMs:Date.now(),maxAgeInMs:n}}else if(e.status===401)throw L.notAllowed(`Could not fetch region settings: ${e.statusText}`,e.status);else throw L.internal(`Could not fetch region settings: ${e.statusText}`)}catch(e){throw e instanceof L?e:r?.aborted?L.cancelled(`Region fetching was aborted`):L.serverUnreachable(`Could not fetch region settings, ${e instanceof Error?`${e.name}: ${e.message}`:e}`)}finally{i()}})}static scheduleRefetch(t,n,r){return F(this,void 0,void 0,function*(){let i=e.settingsTimeouts.get(t.hostname);clearTimeout(i),e.settingsTimeouts.set(t.hostname,setTimeout(()=>F(this,void 0,void 0,function*(){try{let r=yield e.fetchRegionSettings(t,n);e.updateCachedRegionSettings(t,n,r)}catch(i){if(i instanceof L&&i.reason===I.NotAllowed){P.debug(`token is not valid, cancelling auto region refresh`);return}P.debug(`auto refetching of region settings failed`,{error:i}),e.scheduleRefetch(t,n,r)}}),r))})}static updateCachedRegionSettings(t,n,r){e.cache.set(t.hostname,r),e.scheduleRefetch(t,n,r.maxAgeInMs)}static stopRefetch(t){let n=e.settingsTimeouts.get(t);n&&(clearTimeout(n),e.settingsTimeouts.delete(t))}static scheduleCleanup(t){let n=e.connectionTrackers.get(t);n&&(n.cleanupTimeout&&clearTimeout(n.cleanupTimeout),n.cleanupTimeout=setTimeout(()=>{let n=e.connectionTrackers.get(t);n&&n.connectionCount===0&&(P.debug(`stopping region refetch after disconnect delay`,{hostname:t}),e.stopRefetch(t)),n&&(n.cleanupTimeout=void 0)},qd))}static cancelCleanup(t){let n=e.connectionTrackers.get(t);n?.cleanupTimeout&&(clearTimeout(n.cleanupTimeout),n.cleanupTimeout=void 0)}notifyConnected(){let t=this.serverUrl.hostname,n=e.connectionTrackers.get(t);n||(n={connectionCount:0},e.connectionTrackers.set(t,n)),n.connectionCount++,e.cancelCleanup(t)}notifyDisconnected(){let t=this.serverUrl.hostname,n=e.connectionTrackers.get(t);n&&(n.connectionCount=Math.max(0,n.connectionCount-1),n.connectionCount===0&&e.scheduleCleanup(t))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return zl(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(t){return F(this,void 0,void 0,function*(){return e.fetchRegionSettings(this.serverUrl,this.token,t)})}getNextBestRegionUrl(t){return F(this,void 0,void 0,function*(){if(!this.isCloud())throw Error(`region availability is only supported for LiveKit Cloud domains`);let n=e.cache.get(this.serverUrl.hostname);(!n||Date.now()-n.updatedAtInMs>n.maxAgeInMs)&&(n=yield this.fetchRegionSettings(t),e.updateCachedRegionSettings(this.serverUrl,this.token,n));let r=n.regionSettings.regions.filter(e=>!this.attemptedRegions.find(t=>t.url===e.url));if(r.length>0){let e=r[0];return this.attemptedRegions.push(e),P.debug(`next region: ${e.region}`),e.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(t){e.updateCachedRegionSettings(this.serverUrl,this.token,t)}};Jd.cache=new Map,Jd.settingsTimeouts=new Map,Jd.connectionTrackers=new Map,Jd.fetchLock=new kn;function Yd(e){return`${e.protocol.replace(`ws`,`http`)}//${e.host}/settings`}var Xd=class e extends Error{constructor(t,n,r){super(n),this.code=t,this.message=$d(n,e.MAX_MESSAGE_BYTES),this.data=r?$d(r,e.MAX_DATA_BYTES):void 0}static fromProto(t){return new e(t.code,t.message,t.data)}toProto(){return new fa({code:this.code,message:this.message,data:this.data})}static builtIn(t,n){return new e(e.ErrorCode[t],e.ErrorMessage[t],n)}};Xd.MAX_MESSAGE_BYTES=256,Xd.MAX_DATA_BYTES=15360,Xd.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},Xd.ErrorMessage={APPLICATION_ERROR:`Application error in method handler`,CONNECTION_TIMEOUT:`Connection timeout`,RESPONSE_TIMEOUT:`Response timeout`,RECIPIENT_DISCONNECTED:`Recipient disconnected`,RESPONSE_PAYLOAD_TOO_LARGE:`Response payload too large`,SEND_FAILED:`Failed to send`,UNSUPPORTED_METHOD:`Method not supported at destination`,RECIPIENT_NOT_FOUND:`Recipient not found`,REQUEST_PAYLOAD_TOO_LARGE:`Request payload too large`,UNSUPPORTED_SERVER:`RPC not supported by server`,UNSUPPORTED_VERSION:`Unsupported RPC version`};var Zd=15360;function Qd(e){return new TextEncoder().encode(e).length}function $d(e,t){if(Qd(e)<=t)return e;let n=0,r=e.length,i=new TextEncoder;for(;n<r;){let a=Math.floor((n+r+1)/2);i.encode(e.slice(0,a)).length<=t?n=a:r=a-1}return e.slice(0,n)}var ef=2e3;function tf(e,t){if(!t)return 0;let n,r;return`bytesReceived`in e?(n=e.bytesReceived,r=t.bytesReceived):`bytesSent`in e&&(n=e.bytesSent,r=t.bytesSent),n===void 0||r===void 0||e.timestamp===void 0||t.timestamp===void 0?0:(n-r)*8*1e3/(e.timestamp-t.timestamp)}var nf=typeof MediaRecorder<`u`,rf=nf?MediaRecorder:class{constructor(){throw Error(`MediaRecorder is not available in this environment`)}},af=class extends rf{constructor(e,t){if(!nf)throw Error(`MediaRecorder is not available in this environment`);super(new MediaStream([e.mediaStreamTrack]),t);let n,r,i=()=>r===void 0,a=()=>{this.removeEventListener(`dataavailable`,n),this.removeEventListener(`stop`,a),this.removeEventListener(`error`,o),r?.close(),r=void 0},o=e=>{r?.error(e),this.removeEventListener(`dataavailable`,n),this.removeEventListener(`stop`,a),this.removeEventListener(`error`,o),r=void 0};this.byteStream=new ReadableStream({start:e=>{r=e,n=t=>F(this,void 0,void 0,function*(){let n;if(t.data.arrayBuffer){let e=yield t.data.arrayBuffer();n=new Uint8Array(e)}else if(t.data.byteArray)n=t.data.byteArray;else throw Error(`no data available!`);i()||e.enqueue(n)}),this.addEventListener(`dataavailable`,n)},cancel:()=>{a()}}),this.addEventListener(`stop`,a),this.addEventListener(`error`,o)}};function of(){return nf}var sf=1e3,cf=1e4,lf=class extends W{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,i=arguments.length>4?arguments[4]:void 0;super(e,t,i),this.manuallyStopped=!1,this.pendingDeviceChange=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug(`track mute bounce got cancelled by an unmute event`,this.logContext)),this.debouncedTrackMuteHandler=kd(()=>F(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>F(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel(`unmute`),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent),this.emit(V.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new kn,this.pauseUpstreamLock=new kn,this.trackChangeLock=new kn,this.trackChangeLock.lock().then(t=>F(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==W.Kind.Video)return;let{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){return this.processor?.processedTrack??this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t,n){return F(this,void 0,void 0,function*(){if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{_l(this._mediaStreamTrack,e)}),this.debouncedTrackMuteHandler.cancel(`new-track`),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener(`ended`,this.handleEnded),e.addEventListener(`mute`,this.handleTrackMuteEvent),e.addEventListener(`unmute`,this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let r;if(this.processor&&e){if(this.log.debug(`restarting processor`,this.logContext),this.kind===`unknown`)throw TypeError(`cannot set processor on track of unknown kind`);this.processorElement&&(gl(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}this.sender&&this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=n?!0:!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{gl(r??e,t)}))})}waitForDimensions(){return F(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:sf;return function*(){if(e.kind===W.Kind.Audio)throw Error(`cannot get dimensions for audio tracks`);Sc()?.os===`iOS`&&(yield xl(10));let n=Date.now();for(;Date.now()-n<t;){let t=e.dimensions;if(t)return t;yield xl(50)}throw new Ac(`unable to get track dimensions after timeout`)}()})}setDeviceId(e){return F(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===ru(e)?!0:(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),ru(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return F(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===W.Source.ScreenShare)return;let{deviceId:n,groupId:r}=e._mediaStreamTrack.getSettings(),i=e.kind===W.Kind.Audio?`audioinput`:`videoinput`;return t?Gu.getInstance().normalizeDeviceId(i,n,r):n}()})}mute(){return F(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return F(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return F(this,void 0,void 0,function*(){let n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Ac(`unable to replace an unpublished track`);let n,r;return typeof t==`boolean`?n=t:t!==void 0&&(n=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=n??!0,this.log.debug(`replace MediaStreamTrack`,this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor()),this}finally{n()}})}restart(e,t){return F(this,void 0,void 0,function*(){this.manuallyStopped=!1;let n=yield this.trackChangeLock.lock();try{e||=this._constraints;let{deviceId:n,facingMode:r}=e,i=Qo(e,[`deviceId`,`facingMode`]);this.log.debug(`restarting track with constraints`,Object.assign(Object.assign({},this.logContext),{constraints:e}));let a={audio:!1,video:!1};this.kind===W.Kind.Video?a.video=n||r?{deviceId:n,facingMode:r}:!0:a.audio=n?Object.assign({deviceId:n},i):!0,this.attachedElements.forEach(e=>{_l(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.stop();let o=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===W.Kind.Video&&(yield o.applyConstraints(i)),o.addEventListener(`ended`,this.handleEnded),this.log.debug(`re-acquired MediaStreamTrack`,this.logContext),yield this.setMediaStreamTrack(o,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit(V.Restarted,this),this.manuallyStopped&&(this.log.warn(`track was stopped during a restart, stopping restarted track`,this.logContext),this.stop()),this}finally{n()}})}setTrackMuted(e){this.log.debug(`setting ${this.kind} track ${e?`muted`:`unmuted`}`,this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?V.Muted:V.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!==`live`||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return F(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Fl()&&(this.log.debug(`visibility changed, is in Background: ${this.isInBackground}`,this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug(`track needs to be reacquired, restarting ${this.source}`,this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent),(e=this.processor)==null||e.destroy(),this.processor=void 0}pauseUpstream(){return F(this,void 0,void 0,function*(){let e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn(`unable to pause upstream for an unpublished track`,this.logContext);return}this._isUpstreamPaused=!0,this.emit(V.UpstreamPaused,this);let e=Sc();if(e?.name===`Safari`&&Wl(e.version,`12.0`)<0)throw new kc(`pauseUpstream is not supported on Safari < 12.`);this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(null))}finally{e()}})}resumeUpstream(){return F(this,void 0,void 0,function*(){let e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn(`unable to resume upstream for an unpublished track`,this.logContext);return}this._isUpstreamPaused=!1,this.emit(V.UpstreamResumed,this),this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{e()}})}getRTCStatsReport(){return F(this,void 0,void 0,function*(){if(this.sender?.getStats)return yield this.sender.getStats()})}setProcessor(e){return F(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){let r=yield t.trackChangeLock.lock();try{t.log.debug(`setting up processor`,t.logContext);let r=document.createElement(t.kind),i={kind:t.kind,track:t._mediaStreamTrack,element:r,audioContext:t.audioContext};if(yield e.init(i),t.log.debug(`processor initialized`,t.logContext),t.processor&&(yield t.internalStopProcessor()),t.kind===`unknown`)throw TypeError(`cannot set processor on track of unknown kind`);if(gl(t._mediaStreamTrack,r),r.muted=!0,r.play().catch(e=>{e instanceof DOMException&&e.name===`AbortError`?(t.log.warn(`failed to play processor element, retrying`,Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout(()=>{r.play().catch(e=>{t.log.error(`failed to play processor element`,Object.assign(Object.assign({},t.logContext),{err:e}))})},100)):t.log.error(`failed to play processor element`,Object.assign(Object.assign({},t.logContext),{error:e}))}),t.processor=e,t.processorElement=r,t.processor.processedTrack){for(let e of t.attachedElements)e!==t.processorElement&&n&&(_l(t._mediaStreamTrack,e),gl(t.processor.processedTrack,e));yield t.sender?.replaceTrack(t.processor.processedTrack)}t.emit(V.TrackProcessorUpdate,t.processor)}finally{r()}}()})}getProcessor(){return this.processor}stopProcessor(){return F(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){let n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}}()})}internalStopProcessor(){return F(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,r;e.processor&&(e.log.debug(`stopping processor`,e.logContext),(n=e.processor.processedTrack)==null||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||((r=e.processorElement)==null||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(V.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!of()){this.log.warn(`MediaRecorder is not available, cannot start preconnect buffer`,this.logContext);return}if(this.localTrackRecorder){this.log.warn(`preconnect buffer already started`);return}else{let e=`audio/webm;codecs=opus`;MediaRecorder.isTypeSupported(e)||(e=`video/mp4`),this.localTrackRecorder=new af(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn(`preconnect buffer timed out, stopping recording automatically`,this.logContext),this.stopPreConnectBuffer()},cf)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&=(this.localTrackRecorder.stop(),void 0)}getPreConnectBuffer(){return this.localTrackRecorder?.byteStream}getPreConnectBufferMimeType(){return this.localTrackRecorder?.mimeType}},uf=class extends lf{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0;super(e,W.Kind.Audio,t,n,i),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>F(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let e;try{e=yield this.getSenderStats()}catch(e){this.log.error(`could not get audio sender stats`,Object.assign(Object.assign({},this.logContext),{error:e}));return}e&&this.prevStats&&(this._currentBitrate=tf(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug(`Krisp noise filter enabled`,this.logContext),this.emit(V.AudioTrackFeatureUpdate,this,Ri.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug(`Krisp noise filter disabled`,this.logContext),this.emit(V.AudioTrackFeatureUpdate,this,Ri.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return F(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug(`Track already muted`,this.logContext),this):(this.source===W.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug(`stopping mic track`,this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return F(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===W.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState===`ended`||this.pendingDeviceChange)&&!this.isUserProvided&&(this.log.debug(`reacquiring mic track`,this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug(`Track already unmuted`,this.logContext),this)}finally{t()}})}restartTrack(e){return F(this,void 0,void 0,function*(){let t;if(e){let n=$c({audio:e});typeof n.audio!=`boolean`&&(t=n.audio)}yield this.restart(t)})}restart(e,t){let n=Object.create(null,{restart:{get:()=>super.restart}});return F(this,void 0,void 0,function*(){let r=yield n.restart.call(this,e,t);return this.checkForSilence(),r})}startMonitor(){Ll()&&(this.monitorInterval||=setInterval(()=>{this.monitorSender()},ef))}setProcessor(e){return F(this,void 0,void 0,function*(){let t=yield this.trackChangeLock.lock();try{if(!Rl()&&!this.audioContext)throw Error(`Audio context needs to be set on LocalAudioTrack in order to enable processors`);this.processor&&(yield this.internalStopProcessor());let t={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug(`setting up audio processor ${e.name}`,this.logContext),yield e.init(t),this.processor=e,this.processor.processedTrack&&(yield this.sender?.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener(`enable-lk-krisp-noise-filter`,this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener(`disable-lk-krisp-noise-filter`,this.handleKrispNoiseFilterDisable)),this.emit(V.TrackProcessorUpdate,this.processor)}finally{t()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return F(this,void 0,void 0,function*(){if(!this.sender?.getStats)return;let e=yield this.sender.getStats(),t;return e.forEach(e=>{e.type===`outbound-rtp`&&(t={type:`audio`,streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})}),t})}checkForSilence(){return F(this,void 0,void 0,function*(){let e=yield el(this);return e&&(this.isMuted||this.log.debug(`silence detected on local audio track`,this.logContext),this.emit(V.AudioSilenceDetected)),e})}};function df(e,t,n){switch(e.kind){case`audio`:return new uf(e,t,!1,void 0,n);case`video`:return new kf(e,t,!1,n);default:throw new Ac(`unsupported track type: ${e.kind}`)}}var ff=Object.values(Jc),pf=Object.values(Yc),mf=Object.values(Xc),hf=[Jc.h180,Jc.h360],gf=[Yc.h180,Yc.h360],_f=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map(t=>new H(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(t.scaleResolutionDownBy**2*((e.encoding.maxFramerate??30)/(t.fps??30))))),t.fps,e.encoding.priority)),vf=[`q`,`h`,`f`];function yf(e,t,n,r){let i=r?.videoEncoding;e&&(i=r?.screenShareEncoding);let a=r?.simulcast,o=r?.scalabilityMode,s=r?.videoCodec;if(!i&&!a&&!o||!t||!n)return[{}];i||(i=xf(e,t,n,s),P.debug(`using video encoding`,i));let c=i.maxFramerate,l=new H(t,n,i.maxBitrate,i.maxFramerate,i.priority);if(o&&El(s)){let e=new Ef(o),t=[];if(e.spatial>3)throw Error(`unsupported scalabilityMode: ${o}`);let n=Sc();if(Ml()||Rl()||n?.name===`Chrome`&&Wl(n?.version,`113`)<0){let r=e.suffix==`h`?2:3,a=Pl(n);for(let n=0;n<e.spatial;n+=1)t.push({rid:vf[2-n],maxBitrate:i.maxBitrate/r**+n,maxFramerate:l.encoding.maxFramerate,scaleResolutionDownBy:a?2**n:void 0});t[0].scalabilityMode=o}else t.push({maxBitrate:i.maxBitrate,maxFramerate:l.encoding.maxFramerate,scalabilityMode:o});return l.encoding.priority&&(t[0].priority=l.encoding.priority,t[0].networkPriority=l.encoding.priority),P.debug(`using svc encoding`,{encodings:t}),t}if(!a)return[i];let u=[];u=e?Tf(r?.screenShareSimulcastLayers)??Cf(e,l):Tf(r?.videoSimulcastLayers)??Cf(e,l);let d;if(u.length>0){let e=u[0];u.length>1&&([,d]=u);let r=Math.max(t,n);if(r>=960&&d)return wf(t,n,[e,d,l],c);if(r>=480)return wf(t,n,[e,l],c)}return wf(t,n,[l])}function bf(e,t,n){if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&P.warn(`requested a different codec than specified as backup`,{serverRequested:t,backup:n.backupCodec.codec}),n.videoCodec=t,n.videoEncoding=n.backupCodec.encoding;let r=e.mediaStreamTrack.getSettings(),i=r.width??e.dimensions?.width,a=r.height??e.dimensions?.height;return e.source===W.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),yf(e.source===W.Source.ScreenShare,i,a,n)}function xf(e,t,n,r){let i=Sf(e,t,n),{encoding:a}=i[0],o=Math.max(t,n);for(let e=0;e<i.length;e+=1){let t=i[e];if(a=t.encoding,t.width>=o)break}if(r)switch(r){case`av1`:case`h265`:a=Object.assign({},a),a.maxBitrate*=.7;break;case`vp9`:a=Object.assign({},a),a.maxBitrate*=.85;break}return a}function Sf(e,t,n){if(e)return mf;let r=t>n?t/n:n/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?ff:pf}function Cf(e,t){if(e)return _f(t);let{width:n,height:r}=t,i=n>r?n/r:r/n;return Math.abs(i-16/9)<Math.abs(i-4/3)?hf:gf}function wf(e,t,n,r){let i=[];if(n.forEach((n,a)=>{if(a>=vf.length)return;let o=Math.min(e,t),s={rid:vf[a],scaleResolutionDownBy:Math.max(1,o/Math.min(n.width,n.height)),maxBitrate:n.encoding.maxBitrate},c=r&&n.encoding.maxFramerate?Math.min(r,n.encoding.maxFramerate):n.encoding.maxFramerate;c&&(s.maxFramerate=c);let l=kl()||a===0;n.encoding.priority&&l&&(s.priority=n.encoding.priority,s.networkPriority=n.encoding.priority),i.push(s)}),Rl()&&Hl()===`ios`){let e;i.forEach(t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate});let t=!0;i.forEach(n=>{n.maxFramerate!=e&&(t&&(t=!1,P.info(`Simulcast on iOS React-Native requires all encodings to share the same framerate.`)),P.info(`Setting framerate of encoding "${n.rid??``}" to ${e}`),n.maxFramerate=e)})}return i}function Tf(e){if(e)return e.sort((e,t)=>{let{encoding:n}=e,{encoding:r}=t;return n.maxBitrate>r.maxBitrate?1:n.maxBitrate<r.maxBitrate?-1:n.maxBitrate===r.maxBitrate&&n.maxFramerate&&r.maxFramerate?n.maxFramerate>r.maxFramerate?1:-1:0})}var Ef=class{constructor(e){let t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw Error(`invalid scalability mode`);if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case`h`:case`_KEY`:case`_KEY_SHIFT`:this.suffix=t[3]}}toString(){return`L${this.spatial}T${this.temporal}${this.suffix??``}`}};function Df(e){return e.source===W.Source.ScreenShare||e.constraints.height&&ru(e.constraints.height)>=1080?`maintain-resolution`:`balanced`}var Of=5e3,kf=class extends lf{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,W.Kind.Video,t,n,r),this.simulcastCodecs=new Map,this.degradationPreference=`balanced`,this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>F(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let e;try{e=yield this.getSenderStats()}catch(e){this.log.error(`could not get video sender stats`,Object.assign(Object.assign({},this.logContext),{error:e}));return}let t=new Map(e.map(e=>[e.rid,e])),n=e.some(e=>e.qualityLimitationReason===`cpu`);if(n!==this.isCpuConstrained&&(this.isCpuConstrained=n,this.isCpuConstrained&&this.emit(V.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,n)=>{let r=this.prevStats?.get(n);e+=tf(t,r)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new kn}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){if(this.signalClient=e,!Ll())return;let t=this.sender?.getParameters();t&&(this.encodings=t.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},ef))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){let e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return F(this,void 0,void 0,function*(){var t,n,r,i;yield e.pauseUpstream.call(this);try{for(var a=!0,o=rs(this.simulcastCodecs.values()),s;s=yield o.next(),t=s.done,!t;a=!0)i=s.value,a=!1,yield i.sender?.replaceTrack(null)}catch(e){n={error:e}}finally{try{!a&&!t&&(r=o.return)&&(yield r.call(o))}finally{if(n)throw n.error}}})}resumeUpstream(){let e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return F(this,void 0,void 0,function*(){var t,n,r,i;yield e.resumeUpstream.call(this);try{for(var a=!0,o=rs(this.simulcastCodecs.values()),s;s=yield o.next(),t=s.done,!t;a=!0){i=s.value,a=!1;let e=i;yield e.sender?.replaceTrack(e.mediaStreamTrack)}}catch(e){n={error:e}}finally{try{!a&&!t&&(r=o.return)&&(yield r.call(o))}finally{if(n)throw n.error}}})}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return F(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug(`Track already muted`,this.logContext),this):(this.source===W.Source.Camera&&!this.isUserProvided&&(this.log.debug(`stopping camera track`,this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return F(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===W.Source.Camera&&!this.isUserProvided&&(this.log.debug(`reacquiring camera track`,this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug(`Track already unmuted`,this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(let t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return F(this,void 0,void 0,function*(){if(!this.sender?.getStats)return[];let e=[],t=yield this.sender.getStats();return t.forEach(n=>{if(n.type===`outbound-rtp`){let r={type:`video`,streamId:n.id,frameHeight:n.frameHeight,frameWidth:n.frameWidth,framesPerSecond:n.framesPerSecond,framesSent:n.framesSent,firCount:n.firCount,pliCount:n.pliCount,nackCount:n.nackCount,packetsSent:n.packetsSent,bytesSent:n.bytesSent,qualityLimitationReason:n.qualityLimitationReason,qualityLimitationDurations:n.qualityLimitationDurations,qualityLimitationResolutionChanges:n.qualityLimitationResolutionChanges,rid:n.rid??n.id,retransmittedPacketsSent:n.retransmittedPacketsSent,targetBitrate:n.targetBitrate,timestamp:n.timestamp},i=t.get(n.remoteId);i&&(r.jitter=i.jitter,r.packetsLost=i.packetsLost,r.roundTripTime=i.roundTripTime),e.push(r)}}),e.sort((e,t)=>(t.frameWidth??0)-(e.frameWidth??0)),e})}setPublishingQuality(e){let t=[];for(let n=hl.LOW;n<=hl.HIGH;n+=1)t.push(new mo({quality:n,enabled:n<=e}));this.log.debug(`setting publishing quality. max quality ${e}`,this.logContext),this.setPublishingLayers(El(this.codec),t)}restartTrack(e){return F(this,void 0,void 0,function*(){var t,n,r,i;let a;if(e){let t=$c({video:e});typeof t.video!=`boolean`&&(a=t.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var o=!0,s=rs(this.simulcastCodecs.values()),c;c=yield s.next(),t=c.done,!t;o=!0){i=c.value,o=!1;let e=i;e.sender&&e.sender.transport?.state!==`closed`&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){n={error:e}}finally{try{!o&&!t&&(r=s.return)&&(yield r.call(s))}finally{if(n)throw n.error}}})}setProcessor(e){let t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return F(this,arguments,void 0,function(e){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var i,a,o,s;if(yield t.setProcessor.call(n,e,r),n.processor?.processedTrack)try{for(var c=!0,l=rs(n.simulcastCodecs.values()),u;u=yield l.next(),i=u.done,!i;c=!0)s=u.value,c=!1,yield s.sender?.replaceTrack(n.processor.processedTrack)}catch(e){a={error:e}}finally{try{!c&&!i&&(o=l.return)&&(yield o.call(l))}finally{if(a)throw a.error}}}()})}setDegradationPreference(e){return F(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug(`setting degradationPreference to ${e}`,this.logContext);let t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn(`failed to set degradationPreference`,Object.assign({error:e},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error(`${e} already added, skipping adding simulcast codec`,this.logContext);return}let n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){let n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Of))}setPublishingCodecs(e){return F(this,void 0,void 0,function*(){var t,n,r,i,a,o,s;if(this.log.debug(`setting publishing codecs`,Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(El(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;let c=[];try{for(t=!0,n=rs(e);r=yield n.next(),i=r.done,!i;t=!0){s=r.value,t=!1;let e=s;if(!this.codec||this.codec===e.codec)yield this.setPublishingLayers(El(e.codec),e.qualities);else{let t=this.simulcastCodecs.get(e.codec);if(this.log.debug(`try setPublishingCodec for ${e.codec}`,Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),!t||!t.sender){for(let t of e.qualities)if(t.enabled){c.push(e.codec);break}}else t.encodings&&(this.log.debug(`try setPublishingLayersForSender ${e.codec}`,this.logContext),yield Af(t.sender,t.encodings,e.qualities,this.senderLock,El(e.codec),this.log,this.logContext))}}}catch(e){a={error:e}}finally{try{!t&&!i&&(o=n.return)&&(yield o.call(n))}finally{if(a)throw a.error}}return c})}setPublishingLayers(e,t){return F(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info(`skipping setPublishingLayers due to optimized publishing performance`,Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug(`setting publishing layers`,Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield Af(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return F(this,void 0,void 0,function*(){if(!this.sender)throw Error(`sender not found`);let e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;let e=this.sender.getParameters();e.encodings=e.encodings.map((e,t)=>Object.assign(Object.assign({},e),{active:t===0,scaleResolutionDownBy:Math.max(1,Math.ceil((this.mediaStreamTrack.getSettings().height??360)/360)),scalabilityMode:t===0&&El(this.codec)?`L1T3`:void 0,maxFramerate:t===0?15:0,maxBitrate:t===0?e.maxBitrate:0})),this.log.debug(`setting performance optimised encodings`,Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error(`failed to set performance optimised encodings`,Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return F(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Fl()&&this.isInBackground&&this.source===W.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}};function Af(e,t,n,r,i,a,o){return F(this,void 0,void 0,function*(){let s=yield r.lock();a.debug(`setPublishingLayersForSender`,Object.assign(Object.assign({},o),{sender:e,qualities:n,senderEncodings:t}));try{let r=e.getParameters(),{encodings:s}=r;if(!s)return;if(s.length!==t.length){a.warn(`cannot set publishing layers, encodings mismatch`,Object.assign(Object.assign({},o),{encodings:s,senderEncodings:t}));return}let c=!1;i&&n.some(e=>e.enabled)&&n.forEach(e=>e.enabled=!0),s.forEach((e,r)=>{let i=e.rid??``;i===``&&(i=`q`);let s=jf(i),l=n.find(e=>e.quality===s);l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,a.debug(`setting layer ${l.quality} to ${e.active?`enabled`:`disabled`}`,o),kl()&&(l.enabled?(e.scaleResolutionDownBy=t[r].scaleResolutionDownBy,e.maxBitrate=t[r].maxBitrate,e.maxFrameRate=t[r].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}),c&&(r.encodings=s,a.debug(`setting encodings`,Object.assign(Object.assign({},o),{encodings:r.encodings})),yield e.setParameters(r))}finally{s()}})}function jf(e){switch(e){case`f`:return hl.HIGH;case`h`:return hl.MEDIUM;case`q`:return hl.LOW;default:return hl.HIGH}}function Mf(e,t,n,r){if(!n)return[new Xi({quality:hl.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(r){let r=n[0].scalabilityMode,i=new Ef(r),a=[],o=i.suffix==`h`?1.5:2,s=i.suffix==`h`?2:3;for(let r=0;r<i.spatial;r+=1)a.push(new Xi({quality:Math.min(hl.HIGH,i.spatial-1)-r,width:Math.ceil(e/o**+r),height:Math.ceil(t/o**+r),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/s**+r):0,ssrc:0}));return a}return n.map(n=>{let r=n.scaleResolutionDownBy??1;return new Xi({quality:jf(n.rid??``),width:Math.ceil(e/r),height:Math.ceil(t/r),bitrate:n.maxBitrate??0,ssrc:0})})}var Nf=`_lossy`,Pf=`_reliable`,Ff=`_data_track`,If=2*1e3,Lf=`leave-reconnect`,Rf=3e4,zf=8*1024,Bf=256*1024,Vf=3,Hf=3,Uf;(function(e){e[e.New=0]=`New`,e[e.Connected=1]=`Connected`,e[e.Disconnected=2]=`Disconnected`,e[e.Reconnecting=3]=`Reconnecting`,e[e.Closed=4]=`Closed`})(Uf||={});var K;(function(e){e[e.RELIABLE=0]=`RELIABLE`,e[e.LOSSY=1]=`LOSSY`,e[e.DATA_TRACK_LOSSY=2]=`DATA_TRACK_LOSSY`})(K||={});var Wf=class extends ss.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Ud.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Uf.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=P,this.reliableDataSequence=1,this.reliableMessageBuffer=new md,this.reliableReceivedState=new hd(Rf),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>F(this,[e],void 0,function(e){var t=this;let{channel:n}=e;return function*(){if(!n)return;let e;if(n.label===Pf)t.reliableDCSub=n,e=t.handleDataMessage;else if(n.label===Nf)t.lossyDCSub=n,e=t.handleDataMessage;else if(n.label===Ff)t.dataTrackDCSub=n,e=t.handleDataTrackMessage;else return;t.log.debug(`on data channel ${n.id}, ${n.label}`,t.logContext),n.onmessage=e}()}),this.handleDataMessage=e=>F(this,void 0,void 0,function*(){let t=yield this.dataProcessLock.lock();try{let t;if(e.data instanceof ArrayBuffer)t=e.data;else if(e.data instanceof Blob)t=yield e.data.arrayBuffer();else{this.log.error(`unsupported data type`,Object.assign(Object.assign({},this.logContext),{data:e.data}));return}let n=Qi.fromBinary(new Uint8Array(t));if(n.sequence>0&&n.participantSid!==``){let e=this.reliableReceivedState.get(n.participantSid);if(e&&n.sequence<=e)return;this.reliableReceivedState.set(n.participantSid,n.sequence)}if(n.value?.case===`speaker`)this.emit(B.ActiveSpeakersUpdate,n.value.value.speakers);else if(n.value?.case===`encryptedPacket`){if(!this.e2eeManager){this.log.error(`Received encrypted packet but E2EE not set up`,this.logContext);return}let e=yield this.e2eeManager?.handleEncryptedData(n.value.value.encryptedValue,n.value.value.iv,n.participantIdentity,n.value.value.keyIndex),t=new Qi({value:ta.fromBinary(e.payload).value,participantIdentity:n.participantIdentity,participantSid:n.participantSid});t.value?.case===`user`&&Gf(t,t.value.value),this.emit(B.DataPacketReceived,t,n.value.value.encryptionType)}else n.value?.case===`user`&&Gf(n,n.value.value),this.emit(B.DataPacketReceived,n,N.NONE)}finally{t()}}),this.handleDataTrackMessage=e=>F(this,void 0,void 0,function*(){let t;if(e.data instanceof ArrayBuffer)t=e.data;else if(e.data instanceof Blob)t=yield e.data.arrayBuffer();else{this.log.error(`unsupported data type`,Object.assign(Object.assign({},this.logContext),{data:e.data}));return}this.emit(`dataTrackPacketReceived`,new Uint8Array(t))}),this.handleDataError=e=>{let t=e.currentTarget.maxRetransmits===0?`lossy`:`reliable`;if(e instanceof ErrorEvent&&e.error){let{error:n}=e.error;this.log.error(`DataChannel error on ${t}: ${e.message}`,Object.assign(Object.assign({},this.logContext),{error:n}))}else this.log.error(`Unknown DataChannel error on ${t}`,Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{this.updateAndEmitDCBufferStatus(e)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn(`${e} disconnected`,this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());let n=e=>{this.log.warn(`could not recover connection after ${this.reconnectAttempts} attempts, ${e}ms. giving up`,this.logContext),this.emit(B.Disconnected),this.close()},r=Date.now()-this.reconnectStart,i=this.getNextRetryDelay({elapsedMs:r,retryCount:this.reconnectAttempts});if(i===null){n(r);return}e===Lf&&(i=0),this.log.debug(`reconnecting in ${i}ms`,this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Bc.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),i)},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===Uf.Connected&&e();let n=()=>{this.off(B.Disconnected,r),e()},r=()=>{this.off(B.Restarted,n),t()};this.once(B.Restarted,n),this.once(B.Disconnected,r)}),this.updateAndEmitDCBufferStatus=e=>{if(e===K.RELIABLE){let t=this.dataChannelForKind(e);t&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount)}let t=this.isBufferStatusLow(e);t!==void 0&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(B.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{let t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>F(this,void 0,void 0,function*(){this.url&&(yield fetch(au(this.url),{method:`HEAD`}).then(e=>e.ok).catch(()=>!1))&&(this.log.info(`detected network reconnected`),(this.client.currentState===G.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===G.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Ii.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>F(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(au(this.url),{method:`HEAD`}),xl(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info(`detected network interruption`),this.isWaitingForNetworkReconnect=!0)}}),this.log=qo(e.loggerName??Ko.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new ld(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new kn,this.dataProcessLock=new kn,this.dcBufferStatus=new Map([[K.RELIABLE,!0],[K.LOSSY,!0],[K.DATA_TRACK_LOSSY,!0]]),this.client.onParticipantUpdate=e=>this.emit(B.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(B.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(B.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(B.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(B.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(B.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(B.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(B.SignalRequestResponse,e),this.client.onParticipantUpdate=e=>this.emit(B.ParticipantUpdate,e),this.client.onJoined=e=>this.emit(B.Joined,e)}get logContext(){return{room:this.latestJoinResponse?.room?.name,roomID:this.latestJoinResponse?.room?.sid,participant:this.latestJoinResponse?.participant?.identity,participantID:this.participantSid}}join(e,t,n,r){return F(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return function*(){var o;i._isNewlyCreated=!1,i.url=e,i.token=t,i.signalOpts=n,i.maxJoinAttempts=n.maxRetries;try{i.joinAttempts+=1,i.setupSignalClientCallbacks();let s;if(!a&&Su()){i.pcManager||(yield i.configure(),i.createDataChannels(),i.addMediaSections(Vf,Hf));let e=yield i.pcManager?.publisher.createInitialOffer();e&&(s=dd(e.offer,e.offerId))}if(r?.aborted)throw L.cancelled(`Connection aborted`);let c=yield i.client.join(e,t,n,r,a,s);return i._isClosed=!1,i.latestJoinResponse=c,i.participantSid=c.participant?.sid,i.subscriberPrimary=c.subscriberPrimary,!a&&Su()?(o=i.pcManager)==null||o.updateConfiguration(i.makeRTCConfiguration(c)):(i.pcManager||(yield i.configure(c,!a)),(!i.subscriberPrimary||c.fastPublish)&&i.negotiate().catch(e=>{P.error(e,i.logContext)})),i.registerOnLineListener(),i.clientConfiguration=c.clientConfiguration,i.emit(B.SignalConnected,c),c}catch(o){if(o instanceof L){if(o.reason===I.ServerUnreachable){if(i.log.warn(`Couldn't connect to server, attempt ${i.joinAttempts} of ${i.maxJoinAttempts}`,i.logContext),i.joinAttempts<i.maxJoinAttempts)return i.join(e,t,n,r,a)}else if(o.reason===I.ServiceNotFound)return i.log.warn(`Initial connection failed: ${o.message} – Retrying`),i.join(e,t,n,r,!0)}throw o}}()})}close(){return F(this,void 0,void 0,function*(){let e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(B.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return F(this,void 0,void 0,function*(){yield this.pcManager?.close(),this.pcManager=void 0;let e=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};e(this.lossyDC),e(this.lossyDCSub),e(this.reliableDC),e(this.reliableDCSub),e(this.dataTrackDC),e(this.dataTrackDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.dataTrackDC=void 0,this.dataTrackDCSub=void 0,this.reliableMessageBuffer=new md,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&=(clearInterval(this.lossyDataStatInterval),void 0),this.lossyDataDropCount=0}cleanupClient(){return F(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Ac(`a track with the same ID has already been published`);return new Promise((t,n)=>{let r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(L.timeout(`publication of local track timed out, no response from server`))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(r),t(e)},reject:()=>{clearTimeout(r),n(Error(`Cancelled publication by calling unpublish`))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){let{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn(`failed to remove track`,Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){return this.reliableDCSub?.readyState}getConnectedServerAddress(){return F(this,void 0,void 0,function*(){return this.pcManager?.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e,t){return F(this,void 0,void 0,function*(){if(!(this.pcManager&&this.pcManager.currentState!==Wd.NEW)){if(e){this.participantSid=e.participant?.sid;let n=this.makeRTCConfiguration(e);this.pcManager=new Gd(t?`publisher-only`:e.subscriberPrimary?`subscriber-primary`:`publisher-primary`,this.loggerOptions,n)}else{let e=this.makeRTCConfiguration();this.pcManager=new Gd(`publisher-only`,this.loggerOptions,e)}this.emit(B.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=(e,t)=>{this.client.sendOffer(e,t)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(e,t,n)=>F(this,void 0,void 0,function*(){if(this.log.debug(`primary PC state changed ${e}`,this.logContext),[`closed`,`disconnected`,`failed`].includes(t)&&(this.publisherConnectionPromise=void 0),e===Wd.CONNECTED){let e=this.pcState===Uf.New;this.pcState=Uf.Connected,e&&this.emit(B.Connected,this.latestJoinResponse)}else e===Wd.FAILED&&(this.pcState===Uf.Connected||this.pcState===Uf.Reconnecting)&&(this.pcState=Uf.Disconnected,this.handleDisconnect(`peerconnection failed`,n===`failed`?Ii.RR_SUBSCRIBER_FAILED:Ii.RR_PUBLISHER_FAILED));let r=this.client.isDisconnected||this.client.currentState===G.RECONNECTING,i=[Wd.FAILED,Wd.CLOSING,Wd.CLOSED].includes(e);r&&i&&!this._isClosed&&this.emit(B.Offline)}),this.pcManager.onTrack=e=>{e.streams.length!==0&&this.emit(B.MediaTrackAdded,e.track,e.streams[0],e.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>F(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug(`received server answer`,Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:n})),this.midToTrackId=n,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug(`got ICE candidate from peer`,Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,n)=>F(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;let r=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);r&&this.client.sendAnswer(r,t)}),this.client.onLocalTrackPublished=e=>{if(this.log.debug(`received trackPublishedResponse`,Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:e.track?.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error(`missing track resolver for ${e.cid}`,Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}let{resolve:t}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],t(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(B.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(B.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,(t=this.regionUrlProvider)==null||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(B.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(B.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{this.participantSid=e.participant?.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(B.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(B.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(B.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(B.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect(`signal`,Ii.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug(`client leave request`,Object.assign(Object.assign({},this.logContext),{reason:e?.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug(`updating regions`,this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:Kd,regionSettings:e.regions})),e.action){case ro.DISCONNECT:this.emit(B.Disconnected,e?.reason),this.close();break;case ro.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Lf);break;case ro.RESUME:this.handleDisconnect(Lf)}}}makeRTCConfiguration(e){let t=Object.assign({},this.rtcConfig);if(this.signalOpts?.e2eeEnabled&&(this.log.debug(`E2EE - setting up transports with insertable streams`,this.logContext),t.encodedInsertableStreams=!0),t.sdpSemantics=`unified-plan`,t.continualGatheringPolicy=`gather_continually`,!e)return t;if(e.iceServers&&!t.iceServers){let n=[];e.iceServers.forEach(e=>{let t={urls:e.urls};e.username&&(t.username=e.username),e.credential&&(t.credential=e.credential),n.push(t)}),t.iceServers=n}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Pi.ENABLED&&(t.iceTransportPolicy=`relay`),t}addMediaSections(e,t){var n,r;let i={direction:`recvonly`};for(let t=0;t<e;t++)(n=this.pcManager)==null||n.addPublisherTransceiverOfKind(`audio`,i);for(let e=0;e<t;e++)(r=this.pcManager)==null||r.addPublisherTransceiverOfKind(`video`,i)}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.dataTrackDC&&(this.dataTrackDC.onmessage=null,this.dataTrackDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Nf,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Pf,{ordered:!0}),this.dataTrackDC=this.pcManager.createPublisherDataChannel(Ff,{ordered:!1,maxRetransmits:0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.dataTrackDC.onmessage=this.handleDataTrackMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.dataTrackDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.dataTrackDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(K.LOSSY),this.reliableDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(K.RELIABLE),this.dataTrackDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(K.DATA_TRACK_LOSSY),this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;let e=this.dataChannelForKind(K.LOSSY);if(e){let t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,zf),Bf)}},1e3))}createSender(e,t,n){return F(this,void 0,void 0,function*(){if(Sl())return yield this.createTransceiverRTCRtpSender(e,t,n);if(Cl())return this.log.warn(`using add-track fallback`,this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Mc(`Required webRTC APIs not supported on this device`)})}createSimulcastSender(e,t,n,r){return F(this,void 0,void 0,function*(){if(Sl())return this.createSimulcastTransceiverSender(e,t,n,r);if(Cl())return this.log.debug(`using add-track fallback`,this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Mc(`Cannot stream on this device`)})}createTransceiverRTCRtpSender(e,t,n){return F(this,void 0,void 0,function*(){if(!this.pcManager)throw new Mc(`publisher is closed`);let r=[];e.mediaStream&&r.push(e.mediaStream),pu(e)&&(e.codec=t.videoCodec);let i={direction:`sendonly`,streams:r};return n&&(i.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,i)).sender})}createSimulcastTransceiverSender(e,t,n,r){return F(this,void 0,void 0,function*(){if(!this.pcManager)throw new Mc(`publisher is closed`);let i={direction:`sendonly`};r&&(i.sendEncodings=r);let a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,i);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return F(this,void 0,void 0,function*(){if(!this.pcManager)throw new Mc(`publisher is closed`);return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return F(this,void 0,void 0,function*(){if(!this._isClosed){if(this.attemptingReconnect){P.warn(`already attempting reconnect, returning early`,this.logContext);return}(this.clientConfiguration?.resumeConnection===Pi.DISABLED||(this.pcManager?.currentState??Wd.NEW)===Wd.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(e){this.reconnectAttempts+=1;let t=!0;e instanceof Mc?(this.log.debug(`received unrecoverable error`,Object.assign(Object.assign({},this.logContext),{error:e})),t=!1):e instanceof Rc||(this.fullReconnectOnNext=!0),t?this.handleDisconnect(`reconnect`,Ii.RR_UNKNOWN):(this.log.info(`could not recover connection after ${this.reconnectAttempts} attempts, ${Date.now()-this.reconnectStart}ms. giving up`,this.logContext),this.emit(B.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn(`encountered error in reconnect policy`,Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(e){return F(this,void 0,void 0,function*(){var t,n;try{if(!this.url||!this.token)throw new Mc(`could not reconnect, url or token not saved`);this.log.info(`reconnecting, attempt: ${this.reconnectAttempts}`,this.logContext),this.emit(B.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let n;try{if(!this.signalOpts)throw this.log.warn(`attempted connection restart, without signal options present`,this.logContext),new Rc;n=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(e){throw e instanceof L&&e.reason===I.NotAllowed?new Mc(`could not reconnect, token might be expired`):new Rc}if(this.shouldFailNext)throw this.shouldFailNext=!1,Error(`simulated failure`);if(this.client.setReconnected(),this.emit(B.SignalRestarted,n),yield this.waitForPCReconnected(),this.client.currentState!==G.CONNECTED)throw new Rc(`Signal connection got severed during reconnect`);(t=this.regionUrlProvider)==null||t.resetAttempts(),this.emit(B.Restarted)}catch(e){let t=yield this.regionUrlProvider?.getNextBestRegionUrl();if(t){yield this.restartConnection(t);return}else throw(n=this.regionUrlProvider)==null||n.resetAttempts(),e}})}resumeConnection(e){return F(this,void 0,void 0,function*(){if(!this.url||!this.token)throw new Mc(`could not reconnect, url or token not saved`);if(!this.pcManager)throw new Mc(`publisher and subscriber connections unset`);this.log.info(`resuming signal connection, attempt ${this.reconnectAttempts}`,this.logContext),this.emit(B.Resuming);let t;try{this.setupSignalClientCallbacks(),t=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(e){let t=``;throw e instanceof Error&&(t=e.message,this.log.error(e.message,Object.assign(Object.assign({},this.logContext),{error:e}))),e instanceof L&&e.reason===I.NotAllowed?new Mc(`could not reconnect, token might be expired`):e instanceof L&&e.reason===I.LeaveRequest?e:new Rc(t)}if(this.emit(B.SignalResumed),t){let e=this.makeRTCConfiguration(t);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=t.serverInfo)}else this.log.warn(`Did not receive reconnect response`,this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,Error(`simulated failure`);if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==G.CONNECTED)throw new Rc(`Signal connection got severed during reconnect`);this.client.setReconnected(),this.reliableDC?.readyState===`open`&&this.reliableDC.id===null&&this.createDataChannels(),t?.lastMessageSeq&&this.resendReliableMessagesForResume(t.lastMessageSeq),this.emit(B.Resumed)})}waitForPCInitialConnection(e,t){return F(this,void 0,void 0,function*(){if(!this.pcManager)throw new Mc(`PC manager is closed`);yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return F(this,void 0,void 0,function*(){this.pcState=Uf.Reconnecting,this.log.debug(`waiting for peer connection to reconnect`,this.logContext);try{if(yield xl(If),!this.pcManager)throw new Mc(`PC manager is closed`);yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Uf.Connected}catch(e){throw this.pcState=Uf.Disconnected,L.internal(`could not establish PC connection, ${e.message}`)}})}publishRpcResponse(e,t,n,r){return F(this,void 0,void 0,function*(){let i=new Qi({destinationIdentities:[e],kind:$i.RELIABLE,value:{case:`rpcResponse`,value:new da({requestId:t,value:r?{case:`error`,value:r.toProto()}:{case:`payload`,value:n??``}})}});yield this.sendDataPacket(i,K.RELIABLE)})}publishRpcAck(e,t){return F(this,void 0,void 0,function*(){let n=new Qi({destinationIdentities:[e],kind:$i.RELIABLE,value:{case:`rpcAck`,value:new ua({requestId:t})}});yield this.sendDataPacket(n,K.RELIABLE)})}sendDataPacket(e,t){return F(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){let t=Ru(e);if(t){let n=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:`encryptedPacket`,value:new ea({encryptedValue:n.payload,iv:n.iv,keyIndex:n.keyIndex})}}}t===K.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);let n=e.toBinary();switch(t){case K.LOSSY:case K.DATA_TRACK_LOSSY:return this.sendLossyBytes(n,t);case K.RELIABLE:let r=this.dataChannelForKind(t);if(r){if(yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:n,sequence:e.sequence}),this.attemptingReconnect)return;r.send(n)}this.updateAndEmitDCBufferStatus(t);break}})}sendLossyBytes(e,t){return F(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`drop`;return function*(){yield n.ensurePublisherConnected(t);let i=n.dataChannelForKind(t);if(i){if(!n.isBufferStatusLow(t))switch(r){case`wait`:yield n.waitForBufferStatusLow(t);break;case`drop`:n.lossyDataDropCount+=1,n.lossyDataDropCount%100==0&&n.log.warn(`dropping lossy data channel messages, total dropped: ${n.lossyDataDropCount}`,n.logContext);return}if(n.lossyDataStatCurrentBytes+=e.byteLength,n.attemptingReconnect)return;i.send(e)}n.updateAndEmitDCBufferStatus(t)}()})}resendReliableMessagesForResume(e){return F(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(K.RELIABLE);let t=this.dataChannelForKind(K.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(e=>{t.send(e.data)})),this.updateAndEmitDCBufferStatus(K.RELIABLE)})}waitForBufferStatusLow(e){return new yc((t,n)=>F(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{let r=()=>n(new Mc(`engine closed`));for(this.once(B.Closing,r);!this.dcBufferStatus.get(e);)yield xl(10);this.off(B.Closing,r),t()}}))}ensureDataTransportConnected(e){return F(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){if(!t.pcManager)throw new Mc(`PC manager is closed`);let r=n?t.pcManager.subscriber:t.pcManager.publisher,i=n?`Subscriber`:`Publisher`;if(!r)throw L.internal(`${i} connection not set`);let a=!1;if(!n&&!t.dataChannelForKind(e,n)&&(t.createDataChannels(),a=!0),!a&&!n&&!t.pcManager.publisher.isICEConnected&&t.pcManager.publisher.getICEConnectionState()!==`checking`&&(a=!0),a&&t.negotiate().catch(e=>{P.error(e,t.logContext)}),t.dataChannelForKind(e,n)?.readyState===`open`)return;let o=new Date().getTime()+t.peerConnectionTimeout;for(;new Date().getTime()<o;){if(r.isICEConnected&&t.dataChannelForKind(e,n)?.readyState===`open`)return;yield xl(50)}throw L.internal(`could not establish ${i} connection, state: ${r.getICEConnectionState()}`)}()})}ensurePublisherConnected(e){return F(this,void 0,void 0,function*(){this.publisherConnectionPromise||=this.ensureDataTransportConnected(e,!1),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||![Wd.CONNECTING,Wd.CONNECTED].includes(this.pcManager.currentState)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return F(this,void 0,void 0,function*(){return new yc((e,t)=>F(this,void 0,void 0,function*(){if(!this.pcManager){t(new Nc(`PC manager is closed`));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&!this.dataTrackDC&&this.createDataChannels();let n=new AbortController,r=()=>{n.abort(),this.log.debug(`engine disconnected while negotiation was ongoing`,this.logContext),e()};this.isClosed&&t(new Nc(`cannot negotiate on closed engine`)),this.on(B.Closing,r),this.on(B.Restarting,r),this.pcManager.publisher.once(Md.RTPVideoPayloadTypes,e=>{let t=new Map;e.forEach(e=>{let n=e.codec.toLowerCase();nu(n)&&t.set(e.payload,n)}),this.emit(B.RTPVideoMapUpdate,t)});try{yield this.pcManager.negotiate(n),e()}catch(r){if(n.signal.aborted){e();return}r instanceof Nc&&(this.fullReconnectOnNext=!0),this.handleDisconnect(`negotiation`,Ii.RR_UNKNOWN),r instanceof Error?t(r):t(Error(String(r)))}finally{this.off(B.Closing,r),this.off(B.Restarting,r)}}))})}dataChannelForKind(e,t){switch(e){case K.RELIABLE:return t?this.reliableDCSub:this.reliableDC;case K.LOSSY:return t?this.lossyDCSub:this.lossyDC;case K.DATA_TRACK_LOSSY:return t?this.dataTrackDCSub:this.dataTrackDC}}sendSyncState(e,t,n){if(!this.pcManager){this.log.warn(`sync state cannot be sent without peer connection setup`,this.logContext);return}let r=this.pcManager.publisher.getLocalDescription(),i=this.pcManager.publisher.getRemoteDescription(),a=this.pcManager.subscriber?.getRemoteDescription(),o=this.pcManager.subscriber?.getLocalDescription(),s=this.signalOpts?.autoSubscribe??!0,c=[],l=[];e.forEach(e=>{e.isDesired!==s&&c.push(e.trackSid),e.isEnabled||l.push(e.trackSid)}),this.client.sendSyncState(new So({answer:this.pcManager.mode===`publisher-only`?i?dd({sdp:i.sdp,type:i.type}):void 0:o?dd({sdp:o.sdp,type:o.type}):void 0,offer:this.pcManager.mode===`publisher-only`?r?dd({sdp:r.sdp,type:r.type}):void 0:a?dd({sdp:a.sdp,type:a.type}):void 0,subscription:new Xa({trackSids:c,subscribe:!s,participantTracks:[]}),publishTracks:ol(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new Co({publisherSid:t,lastSeq:e})),publishDataTracks:n.map(e=>new La({info:nd.toProtobuf(e)}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){let e=[],t=(t,n)=>{t?.id!==void 0&&t.id!==null&&e.push(new wo({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(K.LOSSY),ka.PUBLISHER),t(this.dataChannelForKind(K.RELIABLE),ka.PUBLISHER),t(this.dataChannelForKind(K.LOSSY,!0),ka.SUBSCRIBER),t(this.dataChannelForKind(K.RELIABLE,!0),ka.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Bc.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Ll()&&(window.addEventListener(`online`,this.handleBrowserOnLine),window.addEventListener(`offline`,this.handleBrowserOffline))}deregisterOnLineListener(){Ll()&&(window.removeEventListener(`online`,this.handleBrowserOnLine),window.removeEventListener(`offline`,this.handleBrowserOffline))}getTrackIdForReceiver(e){let t=this.pcManager?.getMidForReceiver(e);if(t){let e=Object.entries(this.midToTrackId).find(e=>{let[n]=e;return n===t});if(e)return e[1]}}};function Gf(e,t){let n=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=n,t.participantIdentity=n;let r=e.destinationIdentities.length===0?t.destinationIdentities:e.destinationIdentities;e.destinationIdentities=r,t.destinationIdentities=r}var Kf=class{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!=`number`||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new Lc(`Not enough chunk(s) received - expected ${this.totalByteSize} bytes of data total, only received ${this.bytesReceived} bytes`,Ic.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Lc(`Extra chunk(s) received - expected ${this.totalByteSize} bytes of data total, received ${this.bytesReceived} bytes`,Ic.LengthExceeded)}}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}},qf=class extends Kf{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)==null||t.call(this,n)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>F(this,void 0,void 0,function*(){try{let t=this.signal;if(t?.aborted)throw t.reason;let n=yield new Promise((n,r)=>{if(t){let i=()=>r(t.reason);t.addEventListener(`abort`,i,{once:!0}),e.read().then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})}else e.read().then(n,r)});return n.done?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(n.value),{done:!1,value:n.value.content})}catch(e){throw t(),e}}),return(){return F(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return F(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,r,i,a;let o=new Set,s=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=rs(s),u;u=yield l.next(),n=u.done,!n;c=!0){a=u.value,c=!1;let e=a;o.add(e)}}catch(e){r={error:e}}finally{try{!c&&!n&&(i=l.return)&&(yield i.call(l))}finally{if(r)throw r.error}}return Array.from(o)}()})}},Jf=class extends Kf{constructor(e,t,n){super(e,t,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;let n=lu(e.chunkIndex),r=this.receivedChunks.get(n);if(r&&r.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)==null||t.call(this,i)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=new TextDecoder(`utf-8`,{fatal:!0}),n=this.signal,r=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>F(this,void 0,void 0,function*(){try{if(n?.aborted)throw n.reason;let r=yield new Promise((t,r)=>{if(n){let i=()=>r(n.reason);n.addEventListener(`abort`,i,{once:!0}),e.read().then(t,r).finally(()=>{n.removeEventListener(`abort`,i)})}else e.read().then(t,r)});if(r.done)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(r.value);let e;try{e=t.decode(r.value.content)}catch(e){throw new Lc(`Cannot decode datastream chunk ${r.value.chunkIndex} as text: ${e}`,Ic.DecodeFailed)}return{done:!1,value:e}}}catch(e){throw r(),e}}),return(){return F(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return F(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,r,i,a;let o=``,s=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=rs(s),u;u=yield l.next(),n=u.done,!n;c=!0)a=u.value,c=!1,o+=a}catch(e){r={error:e}}finally{try{!c&&!n&&(i=l.return)&&(yield i.call(l))}finally{if(r)throw r.error}}return o}()})}},Yf=class{constructor(){this.log=P,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new Lc(`A text stream handler for topic "${e}" has already been set.`,Ic.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Lc(`A byte stream handler for topic "${e}" has already been set.`,Ic.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){let t=Array.from(this.textStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e),n=Array.from(this.byteStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e);if(t.length>0||n.length>0){let r=new Lc(`Participant ${e} unexpectedly disconnected in the middle of sending data`,Ic.AbnormalEnd);for(let[e,t]of n)t.controller.error(r),this.byteStreamControllers.delete(e);for(let[e,n]of t)n.controller.error(r),this.textStreamControllers.delete(e)}}handleDataStreamPacket(e,t){return F(this,void 0,void 0,function*(){switch(e.value.case){case`streamHeader`:return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case`streamChunk`:return this.handleStreamChunk(e.value.value,t);case`streamTrailer`:return this.handleStreamTrailer(e.value.value,t);default:throw Error(`DataPacket of value "${e.value.case}" is not data stream related!`)}})}handleStreamHeader(e,t,n){return F(this,void 0,void 0,function*(){if(e.contentHeader.case===`byteHeader`){let r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug(`ignoring incoming byte stream due to no handler for topic`,e.topic);return}let i,a={id:e.streamId,name:e.contentHeader.value.name??`unknown`,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:lu(e.timestamp),attributes:e.attributes,encryptionType:n};r(new qf(a,new ReadableStream({start:n=>{if(i=n,this.textStreamControllers.has(e.streamId))throw new Lc(`A data stream read is already in progress for a stream with id ${e.streamId}.`,Ic.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:i,startTime:Date.now(),sendingParticipantIdentity:t})}}),lu(e.totalLength)),{identity:t})}else if(e.contentHeader.case===`textHeader`){let r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug(`ignoring incoming text stream due to no handler for topic`,e.topic);return}let i,a={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:n,attachedStreamIds:e.contentHeader.value.attachedStreamIds};r(new Jf(a,new ReadableStream({start:n=>{if(i=n,this.textStreamControllers.has(e.streamId))throw new Lc(`A data stream read is already in progress for a stream with id ${e.streamId}.`,Ic.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:a,controller:i,startTime:Date.now(),sendingParticipantIdentity:t})}}),lu(e.totalLength)),{identity:t})}})}handleStreamChunk(e,t){let n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType===t?e.content.length>0&&n.controller.enqueue(e):(n.controller.error(new Lc(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${n.info.encryptionType}`,Ic.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)));let r=this.textStreamControllers.get(e.streamId);r&&(r.info.encryptionType===t?e.content.length>0&&r.controller.enqueue(e):(r.controller.error(new Lc(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${r.info.encryptionType}`,Ic.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)))}handleStreamTrailer(e,t){let n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType===t?(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.textStreamControllers.delete(e.streamId)):n.controller.error(new Lc(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${n.info.encryptionType}`,Ic.EncryptionTypeMismatch)));let r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType===t?(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close()):r.controller.error(new Lc(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${r.info.encryptionType}`,Ic.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId))}},Xf=class{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return F(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)==null||e.call(this)})}},Zf=class extends Xf{},Qf=class extends Xf{},$f=15e3,ep=class{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return F(this,void 0,void 0,function*(){let n=crypto.randomUUID(),r=new TextEncoder().encode(e).byteLength,i=(t?.attachments)?.map(()=>crypto.randomUUID()),a=Array(i?i.length+1:1).fill(0),o=(e,n)=>{var r;a[n]=e;let i=a.reduce((e,t)=>e+t,0);(r=t?.onProgress)==null||r.call(t,i)},s=yield this.streamText({streamId:n,totalSize:r,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:i,attributes:t?.attributes});return yield s.write(e),o(1,0),yield s.close(),t?.attachments&&i&&(yield Promise.all(t.attachments.map((e,n)=>F(this,void 0,void 0,function*(){return this._sendFile(i[n],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{o(e,n+1)}})})))),s.info})}streamText(e){return F(this,void 0,void 0,function*(){let t=e?.streamId??crypto.randomUUID(),n={id:t,mimeType:`text/plain`,timestamp:Date.now(),topic:e?.topic??``,size:e?.totalSize,attributes:e?.attributes,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?N.GCM:N.NONE,attachedStreamIds:e?.attachedStreamIds},r=new Ta({streamId:t,mimeType:n.mimeType,topic:n.topic,timestamp:uu(n.timestamp),totalLength:uu(n.size),attributes:n.attributes,contentHeader:{case:`textHeader`,value:new Ca({version:e?.version,attachedStreamIds:n.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type===`update`?Sa.UPDATE:Sa.CREATE})}}),i=e?.destinationIdentities,a=new Qi({destinationIdentities:i,value:{case:`streamHeader`,value:r}});yield this.engine.sendDataPacket(a,K.RELIABLE);let o=0,s=this.engine,c=new WritableStream({write(e){return F(this,void 0,void 0,function*(){for(let n of bu(e,$f)){let e=new Qi({destinationIdentities:i,value:{case:`streamChunk`,value:new Ea({content:n,streamId:t,chunkIndex:uu(o)})}});yield s.sendDataPacket(e,K.RELIABLE),o+=1}})},close(){return F(this,void 0,void 0,function*(){let e=new Qi({destinationIdentities:i,value:{case:`streamTrailer`,value:new Da({streamId:t})}});yield s.sendDataPacket(e,K.RELIABLE)})},abort(e){console.log(`Sink error:`,e)}}),l=()=>F(this,void 0,void 0,function*(){yield u.close()});s.once(B.Closing,l);let u=new Zf(c,n,()=>this.engine.off(B.Closing,l));return u})}sendFile(e,t){return F(this,void 0,void 0,function*(){let n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return F(this,void 0,void 0,function*(){let r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:n?.mimeType??t.type,topic:n?.topic,destinationIdentities:n?.destinationIdentities}),i=t.stream().getReader();for(;;){let{done:e,value:t}=yield i.read();if(e)break;yield r.write(t)}return yield r.close(),r.info})}streamBytes(e){return F(this,void 0,void 0,function*(){let t=e?.streamId??crypto.randomUUID(),n=e?.destinationIdentities,r={id:t,mimeType:e?.mimeType??`application/octet-stream`,topic:e?.topic??``,timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:e?.name??`unknown`,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?N.GCM:N.NONE},i=new Qi({destinationIdentities:n,value:{case:`streamHeader`,value:new Ta({totalLength:uu(r.size),mimeType:r.mimeType,streamId:t,topic:r.topic,timestamp:uu(Date.now()),attributes:r.attributes,contentHeader:{case:`byteHeader`,value:new wa({name:r.name})}})}});yield this.engine.sendDataPacket(i,K.RELIABLE);let a=0,o=new kn,s=this.engine,c=this.log;return new Qf(new WritableStream({write(e){return F(this,void 0,void 0,function*(){let r=yield o.lock(),i=0;try{for(;i<e.byteLength;){let r=e.slice(i,i+$f),o=new Qi({destinationIdentities:n,value:{case:`streamChunk`,value:new Ea({content:r,streamId:t,chunkIndex:uu(a)})}});yield s.sendDataPacket(o,K.RELIABLE),a+=1,i+=r.byteLength}}finally{r()}})},close(){return F(this,void 0,void 0,function*(){let e=new Qi({destinationIdentities:n,value:{case:`streamTrailer`,value:new Da({streamId:t})}});yield s.sendDataPacket(e,K.RELIABLE)})},abort(e){c.error(`Sink error:`,e)}}),r)})}};function tp(e){if(e.length===0)return new AbortController().signal;if(e.length===1)return e[0];for(let t of e)if(t.aborted)return t;let t=new AbortController,n=Array(e.length),r=()=>{for(let e of n)e()};return e.forEach((e,i)=>{let a=()=>{t.abort(e.reason),r()};e.addEventListener(`abort`,a),n[i]=()=>e.removeEventListener(`abort`,a)}),t.signal}function np(e){let t=new AbortController;return setTimeout(()=>{t.abort(new DOMException(`signal timed out after ${e} ms`,`TimeoutError`))},e),t.signal}var rp=1,ip=2,ap=4,op=8,sp=0,cp=12,lp=5,up=7,dp=3,fp=3,pp=2,mp=1,hp=0,gp=3,_p=2,vp=2,yp=1,bp=0,xp;(function(e){e[e.TooShort=0]=`TooShort`,e[e.HeaderOverrun=1]=`HeaderOverrun`,e[e.MissingExtWords=2]=`MissingExtWords`,e[e.UnsupportedVersion=3]=`UnsupportedVersion`,e[e.InvalidHandle=4]=`InvalidHandle`,e[e.MalformedExt=5]=`MalformedExt`})(xp||={});var Sp=class e extends Oc{constructor(e,t,n){super(19,e,n),this.name=`DataTrackDeserializeError`,this.reason=t,this.reasonName=xp[t]}static tooShort(){return new e(`Too short to contain a valid header`,xp.TooShort)}static headerOverrun(){return new e(`Header exceeds total packet length`,xp.HeaderOverrun)}static missingExtWords(){return new e(`Extension word indicator is missing`,xp.MissingExtWords)}static unsupportedVersion(t){return new e(`Unsupported version ${t}`,xp.UnsupportedVersion)}static invalidHandle(t){return new e(`invalid track handle: ${t.message}`,xp.InvalidHandle,{cause:t})}static malformedExt(t){return new e(`Extension with tag ${t} is malformed`,xp.MalformedExt)}},Cp;(function(e){e[e.TooSmallForHeader=0]=`TooSmallForHeader`,e[e.TooSmallForPayload=1]=`TooSmallForPayload`})(Cp||={});var wp=class e extends Oc{constructor(e,t,n){super(19,e,n),this.name=`DataTrackSerializeError`,this.reason=t,this.reasonName=Cp[t]}static tooSmallForHeader(){return new e(`Buffer cannot fit header`,Cp.TooSmallForHeader)}static tooSmallForPayload(){return new e(`Buffer cannot fit payload`,Cp.TooSmallForPayload)}},Tp=class{toBinary(){let e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),n=new DataView(t),r=this.toBinaryInto(n);if(e!==r)throw Error(`${this.constructor.name}.toBinary: written bytes (${r} bytes) not equal to allocated array buffer length (${e} bytes).`);return new Uint8Array(t)}},Ep;(function(e){e[e.UserTimestamp=2]=`UserTimestamp`,e[e.E2ee=1]=`E2ee`})(Ep||={});var Dp=class extends Tp{},Op=class e extends Dp{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return rp+rp+e.lengthBytes}toBinaryInto(t){let n=0;t.setUint8(n,e.tag),n+=rp,t.setUint8(n,e.lengthBytes),n+=rp,t.setBigUint64(n,this.timestamp),n+=op;let r=this.toBinaryLengthBytes();if(n!==r)throw Error(`DataTrackUserTimestampExtension.toBinaryInto: Wrote ${n} bytes but expected length was ${r} bytes`);return n}toJSON(){return{tag:e.tag,lengthBytes:e.lengthBytes,timestamp:this.timestamp}}};Op.tag=Ep.UserTimestamp,Op.lengthBytes=8;var kp=class e extends Dp{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return rp+rp+e.lengthBytes}toBinaryInto(t){let n=0;t.setUint8(n,e.tag),n+=rp,t.setUint8(n,e.lengthBytes),n+=rp,t.setUint8(n,this.keyIndex),n+=rp;for(let e=0;e<this.iv.length;e+=1)t.setUint8(n,this.iv[e]),n+=rp;let r=this.toBinaryLengthBytes();if(n!==r)throw Error(`DataTrackE2eeExtension.toBinaryInto: Wrote ${n} bytes but expected length was ${r} bytes`);return n}toJSON(){return{tag:e.tag,lengthBytes:e.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}};kp.tag=Ep.E2ee,kp.lengthBytes=13;var Ap=class e extends Tp{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){let n=this.e2ee.toBinaryInto(e);t+=n}if(this.userTimestamp){let n=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=n}let n=this.toBinaryLengthBytes();if(t!==n)throw Error(`DataTrackExtensions.toBinaryInto: Wrote ${t} bytes but expected length was ${n} bytes`);return t}static fromBinary(t){let n=Zu(t),r,i,a=0;for(;n.byteLength-a>=rp+rp;){let e=n.getUint8(a);a+=rp;let t=n.getUint8(a);if(a+=rp,e!==bp)switch(e){case Ep.UserTimestamp:if(n.byteLength-a<Op.lengthBytes)throw Sp.malformedExt(e);r=new Op(n.getBigUint64(a)),a+=t;break;case Ep.E2ee:if(n.byteLength-a<kp.lengthBytes)throw Sp.malformedExt(e);let o=n.getUint8(a),s=new Uint8Array(12);for(let e=0;e<s.length;e+=1){let t=a;t+=rp,t+=e*rp,s[e]=n.getUint8(t)}i=new kp(o,s),a+=t;break;default:if(n.byteLength-a<t)throw Sp.malformedExt(e);a+=t;break}}return[new e({userTimestamp:r,e2ee:i}),n.byteLength]}toJSON(){return{userTimestamp:this.userTimestamp?.toJSON()??null,e2ee:this.e2ee?.toJSON()??null}}},jp={from(e){return{payload:e.payload,extensions:new Ap({userTimestamp:e.userTimestamp?new Op(e.userTimestamp):void 0})}},lossyIntoFrame(e){return{payload:e.payload,userTimestamp:e.extensions.userTimestamp?.timestamp}}},Mp=Symbol.for(`lk.track`),Np=Symbol.for(`lk.data-track`),Pp=class{constructor(e,t,n){this.trackSymbol=Mp,this.isLocal=!1,this.typeSymbol=Np,this.info=e,this.manager=t,this.publisherIdentity=n.publisherIdentity}subscribe(e){try{let[t]=this.manager.openSubscriptionStream(this.info.sid,e?.signal,e?.bufferSize);return t}catch(e){throw e}}},Fp=class e extends Tp{constructor(e){super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=e.extensions??new Ap}extensionsMetrics(){let e=this.extensions.toBinaryLengthBytes(),t=Math.ceil(e/4);return{lengthBytes:e,lengthWords:t,paddingLengthBytes:t*4-e}}toBinaryLengthBytes(){let{lengthBytes:e,paddingLengthBytes:t}=this.extensionsMetrics(),n=cp;return e>0&&(n+=_p+e+t),n}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw wp.tooSmallForHeader();let t=sp<<lp,n;switch(this.marker){case Ip.Inter:n=hp;break;case Ip.Final:n=mp;break;case Ip.Start:n=pp;break;case Ip.Single:n=gp;break}t|=n<<dp;let{lengthBytes:r,lengthWords:i,paddingLengthBytes:a}=this.extensionsMetrics();r>0&&(t|=1<<vp);let o=0;if(e.setUint8(o,t),o+=rp,e.setUint8(o,0),o+=rp,e.setUint16(o,this.trackHandle),o+=ip,e.setUint16(o,this.sequence.value),o+=ip,e.setUint16(o,this.frameNumber.value),o+=ip,e.setUint32(o,this.timestamp.asTicks()),o+=ap,r>0){let t=i-1;e.setUint16(o,t),o+=ip;let n=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+o));o+=n;for(let t=0;t<a;t+=1)e.setUint8(o,0),o+=rp}let s=this.toBinaryLengthBytes();if(o!==s)throw Error(`DataTrackPacketHeader.toBinaryInto: Wrote ${o} bytes but expected length was ${s} bytes`);return s}static fromBinary(t){let n=Zu(t);if(n.byteLength<cp)throw Sp.tooShort();let r=0,i=n.getUint8(r);r+=rp;let a=i>>lp&up;if(a>sp)throw Sp.unsupportedVersion(a);let o;switch(i>>dp&fp){case pp:o=Ip.Start;break;case mp:o=Ip.Final;break;case gp:o=Ip.Single;break;case hp:default:o=Ip.Inter;break}let s=(i>>vp&yp)>0;r+=rp;let c;try{c=ed.fromNumber(n.getUint16(r))}catch(e){throw e instanceof $u&&(e.isReason(Qu.Reserved)||e.isReason(Qu.TooLarge))?Sp.invalidHandle(e):e}r+=ip;let l=Ju.u16(n.getUint16(r));r+=ip;let u=Ju.u16(n.getUint16(r));r+=ip;let d=Yu.fromRtpTicks(n.getUint32(r));r+=ap;let f=new Ap;if(s){if(n.byteLength-r<ip)throw Sp.missingExtWords();let e=n.getUint16(r);r+=ip;let t=4*(e+1);if(r+t>n.byteLength)throw Sp.headerOverrun();let i=new DataView(n.buffer,n.byteOffset+r,t),[a,o]=Ap.fromBinary(i);f=a,r+=o}return[new e({marker:o,trackHandle:c,sequence:l,frameNumber:u,timestamp:d,extensions:f}),r]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}},Ip;(function(e){e[e.Start=0]=`Start`,e[e.Inter=1]=`Inter`,e[e.Final=2]=`Final`,e[e.Single=3]=`Single`})(Ip||={});var Lp=class e extends Tp{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0,n=this.header.toBinaryInto(e);if(t+=n,e.byteLength-t<this.payload.byteLength)throw wp.tooSmallForPayload();for(let n=0;n<this.payload.length;n+=1)e.setUint8(t,this.payload[n]),t+=rp;let r=this.toBinaryLengthBytes();if(t!==r)throw Error(`DataTrackPacket.toBinaryInto: Wrote ${t} bytes but expected length was ${r} bytes`);return r}static fromBinary(t){let n=Zu(t),[r,i]=Fp.fromBinary(n),a=n.buffer.slice(n.byteOffset+i,n.byteOffset+n.byteLength);return[new e(r,new Uint8Array(a)),n.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}},Rp=qo(Ko.DataTracks),zp=class e extends Oc{constructor(e,t,n,r){super(19,`Frame ${n} dropped: ${e}`,r),this.name=`DataTrackDepacketizerDropError`,this.reason=t,this.reasonName=Bp[t],this.frameNumber=n}static interrupted(t,n){return new e(`Interrupted by the start of a new frame ${n}`,Bp.Interrupted,t)}static unknownFrame(t){return new e(`Initial packet was never received.`,Bp.UnknownFrame,t)}static bufferFull(t){return new e(`Reorder buffer is full.`,Bp.BufferFull,t)}static incomplete(t,n,r){return new e(`Not all packets received before final packet. Received ${n} packets, expected ${r} packets.`,Bp.Incomplete,t)}},Bp;(function(e){e[e.Interrupted=0]=`Interrupted`,e[e.UnknownFrame=1]=`UnknownFrame`,e[e.BufferFull=2]=`BufferFull`,e[e.Incomplete=3]=`Incomplete`})(Bp||={});var Vp=class e{constructor(){this.partial=null}push(e,t){switch(e.header.marker){case Ip.Single:return this.frameFromSingle(e,t);case Ip.Start:return this.beginPartial(e,t);case Ip.Inter:case Ip.Final:return this.pushToPartial(e)}}reset(){this.partial=null}frameFromSingle(e,t){if(e.header.marker!==Ip.Single)throw Error(`Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ${e.header.marker}.`);if(this.partial)if(t?.errorOnPartialFrames){let t=this.partial.frameNumber;throw this.reset(),zp.interrupted(t,e.header.frameNumber.value)}else Rp.warn(`Data track frame ${this.partial.frameNumber} was interrupted by the start of a new frame, dropping.`);return this.reset(),{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){if(e.header.marker!==Ip.Start)throw Error(`Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ${e.header.marker}.`);if(this.partial)if(t?.errorOnPartialFrames){let t=this.partial.frameNumber;throw this.reset(),zp.interrupted(t,e.header.frameNumber.value)}else Rp.warn(`Data track frame ${this.partial.frameNumber} was interrupted by the start of a new frame ${e.header.frameNumber.value}, dropping.`);this.reset();let n=e.header.sequence;return this.partial={frameNumber:e.header.frameNumber.value,startSequence:n,extensions:e.header.extensions,payloads:new Map([[n.value,e.payload]])},null}pushToPartial(t){if(t.header.marker!==Ip.Inter&&t.header.marker!==Ip.Final)throw Error(`Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ${t.header.marker}.`);if(!this.partial)throw this.reset(),zp.unknownFrame(t.header.frameNumber.value);if(t.header.frameNumber.value!==this.partial.frameNumber){let e=this.partial.frameNumber;throw this.reset(),zp.interrupted(e,t.header.frameNumber.value)}if(this.partial.payloads.size>=e.MAX_BUFFER_PACKETS){let e=this.partial.frameNumber;throw this.reset(),zp.bufferFull(e)}return this.partial.payloads.has(t.header.sequence.value)&&Rp.warn(`Data track frame ${this.partial.frameNumber} received duplicate packet for sequence ${t.header.sequence.value}, so replacing with newly received packet.`),this.partial.payloads.set(t.header.sequence.value,t.payload),t.header.marker===Ip.Final?this.finalize(this.partial,t.header.sequence.value):null}finalize(e,t){let n=e.payloads.size,r=0;for(let t of e.payloads.values())r+=t.length;let i=new Uint8Array(r),a=e.startSequence.clone(),o=0;for(;;){let n=e.payloads.get(a.value);if(!n)break;e.payloads.delete(a.value);let r=i.length-o;if(n.length>r)throw Error(`Depacketizer.finalize: Expected at least ${n.length} more bytes left in the payload buffer, only got ${r} bytes.`);if(i.set(n,o),o+=n.length,a.value!=t){a.increment();continue}return this.reset(),{payload:i,extensions:e.extensions}}throw this.reset(),zp.incomplete(e.frameNumber,n,t-e.startSequence.value+1)}};Vp.MAX_BUFFER_PACKETS=128;var Hp;(function(e){e[e.Unpublished=0]=`Unpublished`,e[e.Timeout=1]=`Timeout`,e[e.Disconnected=2]=`Disconnected`,e[e.Cancelled=4]=`Cancelled`})(Hp||={});var Up=class e extends Oc{constructor(e,t,n){super(22,e,n),this.name=`DataTrackSubscribeError`,this.reason=t,this.reasonName=Hp[t]}static unpublished(){return new e(`The track has been unpublished and is no longer available`,Hp.Unpublished)}static timeout(){return new e(`Request to subscribe to data track timed-out`,Hp.Timeout)}static disconnected(){return new e(`Cannot subscribe to data track when disconnected`,Hp.Disconnected)}static cancelled(){return new e(`Subscription to data track cancelled by caller`,Hp.Cancelled)}},Wp=qo(Ko.DataTracks),Gp=class{constructor(e){let t=e.e2eeManager!==null;if(e.info.usesE2ee!==t)throw Error(`IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider`);let n=new Vp;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=e.e2eeManager??null,this.depacketizer=n}updateE2eeManager(e){this.e2eeManager=e}processPacket(e){return F(this,void 0,void 0,function*(){let t=this.depacketize(e);return t&&(yield this.decryptIfNeeded(t))||null})}depacketize(e){let t;try{t=this.depacketizer.push(e)}catch(e){return Wp.warn(`Data frame depacketize error: ${e}`),null}return t}decryptIfNeeded(e){return F(this,void 0,void 0,function*(){let t=this.e2eeManager;if(!t)return e;let n=e.extensions?.e2ee??null;if(!n)return Wp.error(`Missing E2EE meta`),null;let r;try{r=yield t.handleEncryptedData(e.payload,n.iv,this.publisherIdentity,n.keyIndex)}catch(e){return Wp.error(`Error decrypting packet: ${e}`),null}return e.payload=r.payload,e})}},Kp=qo(Ko.DataTracks),qp=1e4,Jp=16,Yp=class extends ss.EventEmitter{constructor(e){super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=e?.e2eeManager??null}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.subscription.type===`active`&&t.subscription.pipeline.updateE2eeManager(e)}openSubscriptionStream(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Jp,r=null,i=new tu;return[new ReadableStream({start:n=>{r=n;let a=()=>{var e;n.error(Up.cancelled()),(e=i.reject)==null||e.call(i,Up.cancelled())};this.subscribeRequest(e,t).then(()=>F(this,void 0,void 0,function*(){var r;t?.addEventListener(`abort`,a);let o=this.descriptors.get(e);if(!o){Kp.error(`Unknown track ${e}`);return}if(o.subscription.type!==`active`){Kp.error(`Subscription for track ${e} is not active`);return}o.subscription.streamControllers.add(n),(r=i.resolve)==null||r.call(i)})).catch(e=>{var t;n.error(e),(t=i.reject)==null||t.call(i,e)}).finally(()=>{t?.removeEventListener(`abort`,a)})},cancel:()=>{if(!r){Kp.warn(`ReadableStream subscribed to ${e} was not started.`);return}let t=this.descriptors.get(e);if(!t){Kp.warn(`Unknown track ${e}, skipping cancel...`);return}if(t.subscription.type!==`active`){Kp.warn(`Subscription for track ${e} is not active, skipping cancel...`);return}t.subscription.streamControllers.delete(r),t.subscription.streamControllers.size===0&&this.unSubscribeRequest(t.info.sid)}},new CountQueuingStrategy({highWaterMark:n})),i.promise]}subscribeRequest(e,t){return F(this,void 0,void 0,function*(){let n=this.descriptors.get(e);if(!n)throw Error(`Cannot subscribe to unknown track`);let r=(t,n,r)=>F(this,void 0,void 0,function*(){if(t.subscription.type===`active`)return;if(t.subscription.type!==`pending`)throw Error(`Descriptor for track ${e} is not pending, found ${t.subscription.type}`);let i=tp([n,r].filter(e=>e!==void 0)),a=new tu;t.subscription.completionFuture.promise.then(()=>a.resolve?.call(a)).catch(e=>a.reject?.call(a,e));let o=()=>{var e;if(t.subscription.type===`pending`){if(--t.subscription.pendingRequestCount,r?.aborted){t.subscription.cancel();return}if(t.subscription.pendingRequestCount<=0){t.subscription.cancel();return}(e=a.reject)==null||e.call(a,Up.cancelled())}};i.aborted&&o(),i.addEventListener(`abort`,o),yield a.promise,i.removeEventListener(`abort`,o)});switch(n.subscription.type){case`none`:{n.subscription={type:`pending`,completionFuture:new tu,pendingRequestCount:1,cancel:()=>{var t,r;let a=n.subscription;n.subscription={type:`none`},this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!1}),a.type===`pending`&&((r=(t=a.completionFuture).reject)==null||r.call(t,i.aborted?Up.timeout():Up.cancelled()))}},this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!0});let i=np(qp);yield r(n,t,i);return}case`pending`:n.subscription.pendingRequestCount+=1,yield r(n,t);return;case`active`:return}})}querySubscribed(){return F(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).filter(e=>e.subscription.type===`active`).map(e=>[e.info,e.publisherIdentity])})}unSubscribeRequest(e){let t=this.descriptors.get(e);if(!t)throw Error(`Cannot subscribe to unknown track`);if(t.subscription.type!==`active`){Kp.warn(`Unexpected descriptor state in unSubscribeRequest, expected active, found ${t.subscription?.type}`);return}for(let e of t.subscription.streamControllers)e.close();let n=t.subscription;t.subscription={type:`none`},this.subscriptionHandles.delete(n.subcriptionHandle),this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!1})}receiveSfuPublicationUpdates(e){return F(this,void 0,void 0,function*(){if(e.size===0)return;let t=new Map;for(let[n,r]of e.entries()){let e=new Set;for(let t of r)e.add(t.sid),!this.descriptors.has(t.sid)&&(yield this.handleTrackPublished(n,t));t.set(n,e)}for(let[e,n]of t.entries()){let t=Array.from(this.descriptors.entries()).filter(t=>{let[n,r]=t;return r.publisherIdentity===e}).map(e=>{let[t]=e;return t}).filter(e=>!n.has(e));for(let e of t)this.handleTrackUnpublished(e)}})}queryPublications(){return F(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return F(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){Kp.error(`Existing descriptor for track ${t.sid}`);return}let n={info:t,publisherIdentity:e,subscription:{type:`none`}};this.descriptors.set(n.info.sid,n);let r=new Pp(n.info,this,{publisherIdentity:e});this.emit(`trackPublished`,{track:r})})}handleTrackUnpublished(e){let t=this.descriptors.get(e);if(!t){Kp.error(`Unknown track ${e}`);return}this.descriptors.delete(e),t.subscription.type===`active`&&this.subscriptionHandles.delete(t.subscription.subcriptionHandle),this.emit(`trackUnpublished`,{sid:e,publisherIdentity:t.publisherIdentity})}receivedSfuSubscriberHandles(e){for(let[t,n]of e.entries())this.registerSubscriberHandle(t,n)}registerSubscriberHandle(e,t){var n,r;let i=this.descriptors.get(t);if(!i){Kp.error(`Unknown track ${t}`);return}switch(i.subscription.type){case`none`:Kp.warn(`No subscription for ${t}`);return;case`active`:i.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return;case`pending`:{let a=new Gp({info:i.info,publisherIdentity:i.publisherIdentity,e2eeManager:this.e2eeManager}),o=i.subscription;i.subscription={type:`active`,subcriptionHandle:e,pipeline:a,streamControllers:new Set},this.subscriptionHandles.set(e,t),(r=(n=o.completionFuture).resolve)==null||r.call(n)}}}packetReceived(e){return F(this,void 0,void 0,function*(){let t;try{[t]=Lp.fromBinary(e)}catch(e){Kp.error(`Failed to deserialize packet: ${e}`);return}let n=this.subscriptionHandles.get(t.header.trackHandle);if(!n){Kp.warn(`Unknown subscriber handle ${t.header.trackHandle}`);return}let r=this.descriptors.get(n);if(!r){Kp.error(`Missing descriptor for track ${n}`);return}if(r.subscription.type!==`active`){Kp.warn(`Received packet for track ${n} without active subscription`);return}let i=yield r.subscription.pipeline.processPacket(t);if(i)for(let e of r.subscription.streamControllers){if(e.desiredSize!==null&&e.desiredSize<=0){Kp.warn(`Cannot send frame to subscribers: readable stream is full (desiredSize is ${e.desiredSize}). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe().`);continue}let t=jp.lossyIntoFrame(i);e.enqueue(t)}})}resendSubscriptionUpdates(){for(let[e,t]of this.descriptors)t.subscription.type!==`none`&&this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!0})}handleRemoteParticipantDisconnected(e){var t,n;for(let r of this.descriptors.values())if(r.publisherIdentity===e)switch(r.subscription.type){case`none`:break;case`pending`:(n=(t=r.subscription.completionFuture).reject)==null||n.call(t,Up.disconnected());break;case`active`:this.unSubscribeRequest(r.info.sid);break}}shutdown(){var e,t;for(let n of this.descriptors.values())this.emit(`trackUnpublished`,{sid:n.info.sid,publisherIdentity:n.publisherIdentity}),n.subscription.type===`pending`&&((t=(e=n.subscription.completionFuture).reject)==null||t.call(e,Up.disconnected()));this.descriptors.clear()}},Xp=class e extends Oc{constructor(e,t,n){super(19,e,n),this.name=`DataTrackPacketizerError`,this.reason=t,this.reasonName=Zp[t]}static mtuTooShort(){return new e(`MTU is too short to send frame`,Zp.MtuTooShort)}},Zp;(function(e){e[e.MtuTooShort=0]=`MtuTooShort`})(Zp||={});var Qp=class e{constructor(e,t){this.sequence=Ju.u16(0),this.frameNumber=Ju.u16(0),this.clock=Xu.rtpStartingNow(Yu.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?Ip.Single:e===0?Ip.Start:e===t-1?Ip.Final:Ip.Inter}*packetize(t,n){let r=this.frameNumber.getThenIncrement(),i={marker:Ip.Inter,trackHandle:this.handle,sequence:Ju.u16(0),frameNumber:r,timestamp:n?.now??this.clock.now(),extensions:t.extensions},a=new Fp(i).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw Xp.mtuTooShort();let o=this.mtuSizeBytes-a,s=Math.ceil(t.payload.byteLength/o);for(let n=0,r=0;r<t.payload.byteLength;[n,r]=[n+1,r+o]){let a=this.sequence.getThenIncrement(),c=new Fp(Object.assign(Object.assign({},i),{marker:e.computeFrameMarker(n,s),sequence:a})),l=Math.min(o,t.payload.byteLength-r);yield new Lp(c,new Uint8Array(t.payload.buffer,t.payload.byteOffset+r,l))}}},$p;(function(e){e[e.NotAllowed=0]=`NotAllowed`,e[e.DuplicateName=1]=`DuplicateName`,e[e.Timeout=2]=`Timeout`,e[e.LimitReached=3]=`LimitReached`,e[e.Disconnected=4]=`Disconnected`,e[e.Cancelled=5]=`Cancelled`,e[e.InvalidName=6]=`InvalidName`,e[e.Unknown=7]=`Unknown`})($p||={});var em=class e extends Oc{constructor(e,t,n){super(21,e,n),this.name=`DataTrackPublishError`,this.reason=t,this.reasonName=$p[t],this.rawMessage=n?.rawMessage}static notAllowed(t){return new e(`Data track publishing unauthorized`,$p.NotAllowed,{rawMessage:t})}static duplicateName(t){return new e(`Track name already taken`,$p.DuplicateName,{rawMessage:t})}static invalidName(t){return new e(`Track name is invalid`,$p.InvalidName,{rawMessage:t})}static timeout(){return new e(`Publish data track timed-out. Does the LiveKit server support data tracks?`,$p.Timeout)}static limitReached(t){return new e(`Data track publication limit reached`,$p.LimitReached,{rawMessage:t})}static unknown(t,n){return new e(`Received RequestResponse for publishDataTrack, but reason was unrecognised (${t}, ${n})`,$p.Unknown)}static disconnected(){return new e(`Room disconnected`,$p.Disconnected)}static cancelled(){return new e(`Publish data track cancelled by caller`,$p.Cancelled)}},tm;(function(e){e[e.TrackUnpublished=0]=`TrackUnpublished`,e[e.Dropped=1]=`Dropped`})(tm||={});var nm=class e extends Oc{constructor(e,t,n){super(22,e,n),this.name=`DataTrackPushFrameError`,this.reason=t,this.reasonName=tm[t]}static trackUnpublished(){return new e(`Track is no longer published`,tm.TrackUnpublished)}static dropped(t){return new e(`Frame was dropped`,tm.Dropped,{cause:t})}},rm;(function(e){e[e.Packetizer=0]=`Packetizer`,e[e.Encryption=1]=`Encryption`})(rm||={});var im=class e extends Oc{constructor(e,t,n){super(21,e,n),this.name=`DataTrackOutgoingPipelineError`,this.reason=t,this.reasonName=rm[t]}static packetizer(t){return new e(`Error packetizing frame`,rm.Packetizer,{cause:t})}static encryption(t){return new e(`Error encrypting frame`,rm.Encryption,{cause:t})}},am=class e{constructor(e,t){this.trackSymbol=Mp,this.isLocal=!0,this.typeSymbol=Np,this.handle=null,this.log=P,this.options=e,this.manager=t,this.log=qo(Ko.DataTracks)}static withExplicitHandle(t,n,r){let i=new e(t,n);return i.handle=r,i}get info(){let e=this.descriptor;if(e?.type===`active`)return e.info}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return F(this,void 0,void 0,function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(e){throw e}})}isPublished(){return this.descriptor?.type===`active`&&this.descriptor.publishState!==`unpublished`}tryPush(e){if(!this.handle)throw nm.trackUnpublished();let t=jp.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(e){throw e}}unpublish(){return F(this,void 0,void 0,function*(){if(!this.handle){P.warn(`Data track "${this.options.name}" is not published, so unpublishing has no effect.`);return}try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}})}},om=class e{constructor(t){this.e2eeManager=t.e2eeManager,this.packetizer=new Qp(t.info.pubHandle,e.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return ts(this,arguments,function*(){let t=yield es(this.encryptIfNeeded(e));try{yield es(yield*ns(rs(this.packetizer.packetize(t))))}catch(e){throw e instanceof Xp?im.packetizer(e):e}})}encryptIfNeeded(e){return F(this,void 0,void 0,function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(e){throw im.encryption(e)}return e.payload=t.payload,e.extensions.e2ee=new kp(t.keyIndex,t.iv),e})}};om.TRANSPORT_MTU_BYTES=16e3;var sm=qo(Ko.DataTracks),cm={pending(){return{type:`pending`,completionFuture:new tu}},active(e,t){return{type:`active`,info:e,publishState:`published`,pipeline:new om({info:e,e2eeManager:t}),unpublishingFuture:new tu}}},lm=1e4,um=class e extends ss.EventEmitter{constructor(e){super(),this.handleAllocator=new td,this.descriptors=new Map,this.e2eeManager=e?.e2eeManager??null}static withDescriptors(t){let n=new e;return n.descriptors=t,n}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.type===`active`&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){return this.descriptors.get(e)??null}tryProcessAndSend(e,t){return F(this,void 0,void 0,function*(){var n,r,i,a;let o=this.getDescriptor(e);if(o?.type!==`active`||o.publishState===`unpublished`)throw nm.trackUnpublished();if(o.publishState===`republishing`)throw nm.dropped(`Data track republishing`);try{try{for(var s=!0,c=rs(o.pipeline.processFrame(t)),l;l=yield c.next(),n=l.done,!n;s=!0){a=l.value,s=!1;let e=a;this.emit(`packetAvailable`,{bytes:e.toBinary()})}}catch(e){r={error:e}}finally{try{!s&&!n&&(i=c.return)&&(yield i.call(c))}finally{if(r)throw r.error}}}catch(e){throw nm.dropped(e)}})}publishRequest(e,t){return F(this,void 0,void 0,function*(){let n=this.handleAllocator.get();if(!n)throw em.limitReached();let r=np(lm),i=t?tp([t,r]):r;if(this.descriptors.has(n))throw Error(`Descriptor for handle already exists`);let a=cm.pending();this.descriptors.set(n,a);let o=()=>{var e,t;let i=this.descriptors.get(n);if(!i){sm.warn(`No descriptor for ${n}`);return}this.descriptors.delete(n),this.emit(`sfuUnpublishRequest`,{handle:n}),i.type===`pending`&&((t=(e=i.completionFuture).reject)==null||t.call(e,r.aborted?em.timeout():em.cancelled()))};return i.aborted?(o(),a.completionFuture.promise.then(()=>n)):(i.addEventListener(`abort`,o),this.emit(`sfuPublishRequest`,{handle:n,name:e.name,usesE2ee:this.e2eeManager!==null}),yield a.completionFuture.promise,i.removeEventListener(`abort`,o),this.emit(`trackPublished`,{track:am.withExplicitHandle(e,this,n)}),n)})}queryPublished(){return Array.from(this.descriptors.values()).filter(e=>e.type===`active`).map(e=>e.info)}unpublishRequest(e){return F(this,void 0,void 0,function*(){let t=this.descriptors.get(e);if(!t){sm.warn(`No descriptor for ${e}`);return}if(t.type!==`active`){sm.warn(`Track ${e} not active`);return}this.emit(`sfuUnpublishRequest`,{handle:e}),yield t.unpublishingFuture.promise,this.emit(`trackUnpublished`,{sid:t.info.sid})})}receivedSfuPublishResponse(e,t){var n,r,i,a;let o=this.descriptors.get(e);if(!o){sm.warn(`No descriptor for ${e}`);return}switch(this.descriptors.delete(e),o.type){case`pending`:if(t.type===`ok`){let e=t.data,i=e.usesE2ee?this.e2eeManager:null;this.descriptors.set(e.pubHandle,cm.active(e,i)),(r=(n=o.completionFuture).resolve)==null||r.call(n)}else (a=(i=o.completionFuture).reject)==null||a.call(i,t.error);return;case`active`:if(o.publishState!==`republishing`){sm.warn(`Track ${e} already active`);return}if(t.type===`error`){sm.warn(`Republish failed for track ${e}`);return}sm.debug(`Track ${e} republished`),o.info.sid=t.data.sid,o.publishState=`published`,this.descriptors.set(o.info.pubHandle,o)}}receivedSfuUnpublishResponse(e){var t,n;let r=this.descriptors.get(e);if(!r){sm.warn(`No descriptor for ${e}`);return}if(this.descriptors.delete(e),r.type!==`active`){sm.warn(`Track ${e} not active`);return}r.publishState=`unpublished`,(n=(t=r.unpublishingFuture).resolve)==null||n.call(t)}sfuWillRepublishTracks(){var e,t;for(let[n,r]of this.descriptors.entries())switch(r.type){case`pending`:this.descriptors.delete(n),(t=(e=r.completionFuture).reject)==null||t.call(e,em.disconnected());break;case`active`:r.publishState=`republishing`,this.emit(`sfuPublishRequest`,{handle:r.info.pubHandle,name:r.info.name,usesE2ee:r.info.usesE2ee})}}shutdown(){return F(this,void 0,void 0,function*(){var e,t,n,r;for(let i of this.descriptors.values())switch(i.type){case`pending`:(t=(e=i.completionFuture).reject)==null||t.call(e,em.disconnected());break;case`active`:(r=(n=i.unpublishingFuture).resolve)==null||r.call(n),yield this.unpublishRequest(i.info.pubHandle);break}this.descriptors.clear()})}},dm=class extends W{constructor(e,t,n,r,i){super(e,n,i),this.sid=t,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?V.Muted:V.Unmuted,this))}setMediaStream(e){this.mediaStream=e;let t=n=>{n.track===this._mediaStreamTrack&&(e.removeEventListener(`removetrack`,t),this.receiver&&`playoutDelayHint`in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(V.Ended,this))};e.addEventListener(`removetrack`,t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return F(this,void 0,void 0,function*(){if(this.receiver?.getStats)return yield this.receiver.getStats()})}setPlayoutDelay(e){this.receiver?`playoutDelayHint`in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn(`Playout delay not supported in this browser`):this.log.warn(`Cannot set playout delay, track already ended`)}getPlayoutDelay(){if(this.receiver){if(`playoutDelayHint`in this.receiver)return this.receiver.playoutDelayHint;this.log.warn(`Playout delay not supported in this browser`)}else this.log.warn(`Cannot get playout delay, track already ended`);return 0}startMonitor(){this.monitorInterval||=setInterval(()=>this.monitorReceiver(),ef),sl()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){let e=()=>{this.timeSyncHandle=requestAnimationFrame(()=>e());let t=this.receiver?.getSynchronizationSources()[0];if(t){let{timestamp:e,rtpTimestamp:n}=t;n&&this.rtpTimestamp!==n&&(this.emit(V.TimeSyncUpdate,{timestamp:e,rtpTimestamp:n}),this.rtpTimestamp=n)}};e()}},fm=class extends dm{constructor(e,t,n,r,i,a){super(e,t,W.Kind.Audio,n,a),this.monitorReceiver=()=>F(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=tf(e,this.prevStats)),this.prevStats=e}),this.audioContext=r,this.webAudioPluginNodes=[],i&&(this.sinkId=i.deviceId)}setVolume(e){var t;for(let n of this.attachedElements)this.audioContext?(t=this.gainNode)==null||t.gain.setTargetAtTime(e,0,.1):n.volume=e;Rl()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Rl())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return F(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(Dl(t))return t.setSinkId(e)}))})}attach(e){let t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Dl(e)&&e.setSinkId(this.sinkId).catch(e=>{this.log.error(`Failed to set sink id on remote audio track`,e,this.logContext)}),this.audioContext&&t&&(this.log.debug(`using audio context mapping`,this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{n.connect(e),n=e}),this.gainNode=e.createGain(),n.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!==`running`&&e.resume().then(()=>{e.state!==`running`&&this.emit(V.AudioPlaybackFailed,Error(`Audio Context couldn't be started automatically`))}).catch(e=>{this.emit(V.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;(e=this.gainNode)==null||e.disconnect(),(t=this.sourceNode)==null||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return F(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t;return e.forEach(e=>{e.type===`inbound-rtp`&&(t={type:`audio`,streamId:e.id,timestamp:e.timestamp,jitter:e.jitter,bytesReceived:e.bytesReceived,concealedSamples:e.concealedSamples,concealmentEvents:e.concealmentEvents,silentConcealedSamples:e.silentConcealedSamples,silentConcealmentEvents:e.silentConcealmentEvents,totalAudioEnergy:e.totalAudioEnergy,totalSamplesDuration:e.totalSamplesDuration})}),t})}},pm=100,mm=class extends dm{constructor(e,t,n,r,i){super(e,t,W.Kind.Video,n,i),this.elementInfos=[],this.monitorReceiver=()=>F(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=tf(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=kd(()=>{this.updateDimensions()},pm),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug(`setStreamState`,e),this.isAdaptiveStream&&e===W.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?_l(this._mediaStreamTrack,t):gl(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){let t=new hm(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn(`visibility resize observer not triggered`,this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn(`stopObservingElementInfo ignored`,this.logContext);return}let t=this.elementInfos.filter(t=>t===e);for(let e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter(t=>t!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(let e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){return this.prevStats?.decoderImplementation}getReceiverStats(){return F(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t,n=``,r=new Map;return e.forEach(e=>{e.type===`inbound-rtp`?(n=e.codecId,t={type:`video`,streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):e.type===`codec`&&r.set(e.id,e)}),t&&n!==``&&r.get(n)&&(t.mimeType=r.get(n).mimeType),t})}stopObservingElement(e){let t=this.elementInfos.filter(t=>t.element===e);for(let e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return F(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){let t=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),n=this.adaptiveStreamSettings?.pauseVideoInBackground??!0?this.isInBackground:!1,r=this.elementInfos.some(e=>e.pictureInPicture),i=this.elementInfos.some(e=>e.visible)&&!n||r;if(!(this.lastVisible===i&&!e)){if(!i&&Date.now()-t<pm){Bc.setTimeout(()=>{this.updateVisibility()},pm);return}this.lastVisible=i,this.emit(V.VisibilityChanged,i,this)}}updateDimensions(){let e=0,t=0,n=this.getPixelDensity();for(let r of this.elementInfos){let i=r.width()*n,a=r.height()*n;i+a>e+t&&(e=i,t=a)}this.lastDimensions?.width===e&&this.lastDimensions?.height===t||(this.lastDimensions={width:e,height:t},this.emit(V.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){let e=this.adaptiveStreamSettings?.pixelDensity;return e===`screen`?Ul():e||(Ul()>2?2:1)}},hm=class{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;let{target:n,isIntersecting:r}=e;n===this.element&&(this.isIntersecting=r,this.isPiP=gm(this.element),this.visibilityChangedAt=Date.now(),(t=this.handleVisibilityChanged)==null||t.call(this))},this.onEnterPiP=()=>{var e,t;(e=window.documentPictureInPicture?.window)==null||e.addEventListener(`pagehide`,this.onLeavePiP),this.isPiP=gm(this.element),(t=this.handleVisibilityChanged)==null||t.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=gm(this.element),(e=this.handleVisibilityChanged)==null||e.call(this)},this.element=e,this.isIntersecting=t??_m(e),this.isPiP=Ll()&&gm(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t;this.isIntersecting=_m(this.element),this.isPiP=gm(this.element),this.element.handleResize=()=>{var e;(e=this.handleResize)==null||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Xl().observe(this.element),Jl().observe(this.element),this.element.addEventListener(`enterpictureinpicture`,this.onEnterPiP),this.element.addEventListener(`leavepictureinpicture`,this.onLeavePiP),(e=window.documentPictureInPicture)==null||e.addEventListener(`enter`,this.onEnterPiP),(t=window.documentPictureInPicture?.window)==null||t.addEventListener(`pagehide`,this.onLeavePiP)}stopObserving(){var e,t,n,r;(e=Xl())==null||e.unobserve(this.element),(t=Jl())==null||t.unobserve(this.element),this.element.removeEventListener(`enterpictureinpicture`,this.onEnterPiP),this.element.removeEventListener(`leavepictureinpicture`,this.onLeavePiP),(n=window.documentPictureInPicture)==null||n.removeEventListener(`enter`,this.onEnterPiP),(r=window.documentPictureInPicture?.window)==null||r.removeEventListener(`pagehide`,this.onLeavePiP)}};function gm(e){return document.pictureInPictureElement===e?!0:window.documentPictureInPicture?.window?_m(e,window.documentPictureInPicture?.window):!1}function _m(e,t){let n=t||window,r=e.offsetTop,i=e.offsetLeft,a=e.offsetWidth,o=e.offsetHeight,{hidden:s}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)e=e.offsetParent,r+=e.offsetTop,i+=e.offsetLeft;return r<n.pageYOffset+n.innerHeight&&i<n.pageXOffset+n.innerWidth&&r+o>n.pageYOffset&&i+a>n.pageXOffset&&!s&&c!==`none`}var vm=class extends ss.EventEmitter{constructor(e,t,n,r){super(),this.metadataMuted=!1,this.encryption=N.NONE,this.log=P,this.handleMuted=()=>{this.emit(V.Muted)},this.handleUnmuted=()=>{this.emit(V.Unmuted)},this.log=qo(r?.loggerName??Ko.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=W.Source.Unknown}setTrack(e){this.track&&(this.track.off(V.Muted,this.handleMuted),this.track.off(V.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(V.Muted,this.handleMuted),e.on(V.Unmuted,this.handleUnmuted))}get logContext(){return Object.assign(Object.assign({},this.loggerContextCb?.call(this)),U(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==N.NONE}get audioTrack(){if(fu(this.track))return this.track}get videoTrack(){if(pu(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=W.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===W.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug(`update publication info`,Object.assign(Object.assign({},this.logContext),{info:e}))}};(function(e){(function(e){e.Desired=`desired`,e.Subscribed=`subscribed`,e.Unsubscribed=`unsubscribed`})(e.SubscriptionStatus||={}),(function(e){e.Allowed=`allowed`,e.NotAllowed=`not_allowed`})(e.PermissionStatus||={})})(vm||={});var ym=class extends vm{get isUpstreamPaused(){return this.track?.isUpstreamPaused}constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(V.Ended)},this.handleCpuConstrained=()=>{this.track&&pu(this.track)&&this.emit(V.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(V.Ended,this.handleTrackEnded),this.track.off(V.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(V.Ended,this.handleTrackEnded),e.on(V.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return F(this,void 0,void 0,function*(){return this.track?.mute()})}unmute(){return F(this,void 0,void 0,function*(){return this.track?.unmute()})}pauseUpstream(){return F(this,void 0,void 0,function*(){yield this.track?.pauseUpstream()})}resumeUpstream(){return F(this,void 0,void 0,function*(){yield this.track?.resumeUpstream()})}getTrackFeatures(){if(fu(this.track)){let e=this.track.getSourceTrackSettings(),t=new Set;return e.autoGainControl&&t.add(Ri.TF_AUTO_GAIN_CONTROL),e.echoCancellation&&t.add(Ri.TF_ECHO_CANCELLATION),e.noiseSuppression&&t.add(Ri.TF_NOISE_SUPPRESSION),e.channelCount&&e.channelCount>1&&t.add(Ri.TF_STEREO),this.options?.dtx||t.add(Ri.TF_NO_DTX),this.track.enhancedNoiseCancellation&&t.add(Ri.TF_ENHANCED_NOISE_CANCELLATION),Array.from(t.values())}else return[]}};function bm(e,t){return F(this,void 0,void 0,function*(){e??={};let n=!1,{audioProcessor:r,videoProcessor:i,optionsWithoutProcessor:a}=ll(e),o=a.audio,s=a.video;if(r&&typeof a.audio==`object`&&(a.audio.processor=r),i&&typeof a.video==`object`&&(a.video.processor=i),e.audio&&typeof a.audio==`object`&&typeof a.audio.deviceId==`string`){let e=a.audio.deviceId;a.audio.deviceId={exact:e},n=!0,o=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:e}})}if(a.video&&typeof a.video==`object`&&typeof a.video.deviceId==`string`){let e=a.video.deviceId;a.video.deviceId={exact:e},n=!0,s=Object.assign(Object.assign({},a.video),{deviceId:{ideal:e}})}a.audio===!0?a.audio={deviceId:`default`}:typeof a.audio==`object`&&a.audio!==null&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||`default`})),a.video===!0?a.video={deviceId:`default`}:typeof a.video==`object`&&!a.video.deviceId&&(a.video.deviceId=`default`);let c=Zc(a,Bd,Vd),l=$c(c),u=navigator.mediaDevices.getUserMedia(l);a.audio&&(Gu.userMediaPromiseMap.set(`audioinput`,u),u.catch(()=>Gu.userMediaPromiseMap.delete(`audioinput`))),a.video&&(Gu.userMediaPromiseMap.set(`videoinput`,u),u.catch(()=>Gu.userMediaPromiseMap.delete(`videoinput`)));try{let e=yield u;return yield Promise.all(e.getTracks().map(n=>F(this,void 0,void 0,function*(){let a=n.kind===`audio`,o=a?c.audio:c.video;(typeof o==`boolean`||!o)&&(o={});let s,u=a?l.audio:l.video;typeof u!=`boolean`&&(s=u);let d=n.getSettings().deviceId;s?.deviceId&&ru(s.deviceId)!==d?s.deviceId=d:s||={deviceId:d};let f=df(n,s,t);return f.kind===W.Kind.Video?f.source=W.Source.Camera:f.kind===W.Kind.Audio&&(f.source=W.Source.Microphone),f.mediaStream=e,fu(f)&&r?yield f.setProcessor(r):pu(f)&&i&&(yield f.setProcessor(i)),f})))}catch(r){if(!n)throw r;return bm(Object.assign(Object.assign({},e),{audio:o,video:s}),t)}})}function xm(e){return F(this,void 0,void 0,function*(){return(yield bm({audio:e??!0,video:!1}))[0]})}var Sm;(function(e){e.Excellent=`excellent`,e.Good=`good`,e.Poor=`poor`,e.Lost=`lost`,e.Unknown=`unknown`})(Sm||={});function Cm(e){switch(e){case Ni.EXCELLENT:return Sm.Excellent;case Ni.GOOD:return Sm.Good;case Ni.POOR:return Sm.Poor;case Ni.LOST:return Sm.Lost;default:return Sm.Unknown}}var wm=class extends ss.EventEmitter{get logContext(){var e;return Object.assign({},((e=this.loggerOptions)?.loggerContextCb)?.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){return this.permissions?.agent||this.kind===Wi.AGENT}get isActive(){return this.participantInfo?.state===Ui.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,r,i,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Wi.STANDARD;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Sm.Unknown,this.log=P,this.log=qo(a?.loggerName??Ko.Participant),this.loggerOptions=a,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=i??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(let[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(let[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new tu,this.once(z.Active,()=>{var e,t;(t=(e=this.activeFuture)?.resolve)==null||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){return!(this.getTrackPublication(W.Source.Camera)?.isMuted??!0)}get isMicrophoneEnabled(){return!(this.getTrackPublication(W.Source.Microphone)?.isMuted??!0)}get isScreenShareEnabled(){return!!this.getTrackPublication(W.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===Ui.ACTIVE&&this.participantInfo?.state!==Ui.ACTIVE&&this.emit(z.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){let t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(z.ParticipantMetadataChanged,n)}_setName(e){let t=this.name!==e;this.name=e,t&&this.emit(z.ParticipantNameChanged,e)}_setAttributes(e){let t=cl(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(z.AttributesChanged,t)}setPermissions(e){let t=this.permissions,n=e.canPublish!==this.permissions?.canPublish||e.canSubscribe!==this.permissions?.canSubscribe||e.canPublishData!==this.permissions?.canPublishData||e.hidden!==this.permissions?.hidden||e.recorder!==this.permissions?.recorder||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>e!==this.permissions?.canPublishSources[t])||e.canSubscribeMetrics!==this.permissions?.canSubscribeMetrics;return this.permissions=e,n&&this.emit(z.ParticipantPermissionsChanged,t),n}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(z.IsSpeakingChanged,e))}setConnectionQuality(e){let t=this._connectionQuality;this._connectionQuality=Cm(e),t!==this._connectionQuality&&this.emit(z.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&=((t=(e=this.activeFuture).reject)==null||t.call(e,Error(`Participant disconnected`)),void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>fu(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(V.Muted,()=>{this.emit(z.TrackMuted,e)}),e.on(V.Unmuted,()=>{this.emit(z.TrackUnmuted,e)});let t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case W.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case W.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}};function Tm(e){if(!e.participantSid&&!e.participantIdentity)throw Error(`Invalid track permission, must provide at least one of participantIdentity and participantSid`);return new vo({participantIdentity:e.participantIdentity??``,participantSid:e.participantSid??``,allTracks:e.allowAll??!1,trackSids:e.allowedTrackSids||[]})}var Em=class extends wm{constructor(e,t,n,r,i,a,o){super(e,t,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=N.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||=new tu},this.handleReconnected=()=>{var e,t;(t=(e=this.reconnectFuture)?.resolve)==null||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,n,r,i,a;this.reconnectFuture&&=(this.reconnectFuture.promise.catch(e=>this.log.warn(e.message,this.logContext)),(t=(e=this.reconnectFuture)?.reject)==null||t.call(e,Error(`Got disconnected during reconnection attempt`)),void 0),this.signalConnectedFuture&&=((r=(n=this.signalConnectedFuture).reject)==null||r.call(n,Error(`Got disconnected without signal connected`)),void 0),(a=(i=this.activeAgentFuture)?.reject)==null||a.call(i,Error(`Got disconnected without active agent present`)),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,n;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||=new tu,(n=(t=this.signalConnectedFuture).resolve)==null||n.call(t)},this.handleSignalRequestResponse=e=>{let{requestId:t,reason:n,message:r}=e,i=this.pendingSignalRequests.get(t);switch(i&&(n!==Mo.OK&&i.reject(new Fc(r,n)),this.pendingSignalRequests.delete(t)),e.request.case){case`publishDataTrack`:{let t;switch(e.reason){case Mo.NOT_ALLOWED:t=em.notAllowed(e.message);break;case Mo.DUPLICATE_NAME:t=em.duplicateName(e.message);break;case Mo.INVALID_NAME:t=em.invalidName(e.message);break;case Mo.LIMIT_EXCEEDED:t=em.limitReached(e.message);break;default:t=em.unknown(e.reason,e.message);return}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(e.request.value.pubHandle,{type:`error`,error:t});break}}},this.handleDataPacket=e=>{switch(e.value.case){case`rpcResponse`:let t=e.value.value,n=null,r=null;t.value.case===`payload`?n=t.value.value:t.value.case===`error`&&(r=Xd.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,n,r);break;case`rpcAck`:let i=e.value.value;this.handleIncomingRpcAck(i.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug(`updating track subscription permissions`,Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(e=>Tm(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{if(t===void 0&&(t=!0),!e.sid){this.log.error(`could not update mute status for unpublished track`,Object.assign(Object.assign({},this.logContext),U(e)));return}this.engine.updateMuteStatus(e.sid,t)},this.onTrackUpstreamPaused=e=>{this.log.debug(`upstream paused`,Object.assign(Object.assign({},this.logContext),U(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug(`upstream resumed`,Object.assign(Object.assign({},this.logContext),U(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{let t=this.audioTrackPublications.get(e.sid);if(!t){this.log.warn(`Could not update local audio track settings, missing publication for track ${e.sid}`,this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures())},this.onTrackCpuConstrained=(e,t)=>{this.log.debug(`track cpu constrained`,Object.assign(Object.assign({},this.logContext),U(t))),this.emit(z.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>F(this,void 0,void 0,function*(){var t,n,r,i;if(!this.roomOptions?.dynacast)return;let a=this.videoTrackPublications.get(e.trackSid);if(!a){this.log.warn(`received subscribed quality update for unknown track`,Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));return}if(!a.videoTrack)return;let o=yield a.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var s=!0,c=rs(o),l;l=yield c.next(),t=l.done,!t;s=!0){i=l.value,s=!1;let e=i;Gc(e)&&(this.log.debug(`publish ${e} for ${a.videoTrack.sid}`,Object.assign(Object.assign({},this.logContext),U(a))),yield this.publishAdditionalCodecForTrack(a.videoTrack,e,a.options))}}catch(e){n={error:e}}finally{try{!s&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(n)throw n.error}}}),this.handleLocalTrackUnpublished=e=>{let t=this.trackPublications.get(e.trackSid);if(!t){this.log.warn(`received unpublished event for unknown track`,Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));return}this.unpublishTrack(t.track)},this.handleTrackEnded=e=>F(this,void 0,void 0,function*(){if(e.source===W.Source.ScreenShare||e.source===W.Source.ScreenShareAudio)this.log.debug(`unpublishing local track due to TrackEnded`,Object.assign(Object.assign({},this.logContext),U(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(hu(e)||mu(e))try{if(Ll())try{let t=yield navigator==null?void 0:navigator.permissions.query({name:e.source===W.Source.Camera?`camera`:`microphone`});if(t&&t.state===`denied`)throw this.log.warn(`user has revoked access to ${e.source}`,Object.assign(Object.assign({},this.logContext),U(e))),t.onchange=()=>{t.state!==`denied`&&(e.isMuted||e.restartTrack(),t.onchange=null)},Error(`GetUserMedia Permission denied`)}catch{}e.isMuted||(this.log.debug(`track ended, attempting to use a different device`,Object.assign(Object.assign({},this.logContext),U(e))),hu(e)?yield e.restartTrack({deviceId:`default`}):yield e.restartTrack())}catch{this.log.warn(`could not restart track, muting instead`,Object.assign(Object.assign({},this.logContext),U(e))),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=r,this.setupEngine(n),this.activeDeviceMap=new Map([[`audioinput`,`default`],[`videoinput`,`default`],[`audiooutput`,`default`]]),this.pendingSignalRequests=new Map,this.rpcHandlers=i,this.roomOutgoingDataStreamManager=a,this.roomOutgoingDataTrackManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==N.NONE}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.on(B.RemoteMute,(e,t)=>{let n=this.trackPublications.get(e);!n||!n.track||(t?n.mute():n.unmute())}),this.signalConnectedFuture?.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(B.Connected,this.handleReconnected).on(B.SignalConnected,this.handleSignalConnected).on(B.SignalRestarted,this.handleReconnected).on(B.SignalResumed,this.handleReconnected).on(B.Restarting,this.handleReconnecting).on(B.Resuming,this.handleReconnecting).on(B.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(B.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(B.Closing,this.handleClosing).on(B.SignalRequestResponse,this.handleSignalRequestResponse).on(B.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return F(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return F(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return F(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return F(this,arguments,void 0,function(e){var t=this;let{metadata:n,name:r,attributes:i}=e;return function*(){return new yc((e,a)=>F(t,void 0,void 0,function*(){try{let t=!1,o=yield this.engine.client.sendUpdateLocalMetadata(n??this.metadata??``,r??this.name??``,i),s=performance.now();for(this.pendingSignalRequests.set(o,{resolve:e,reject:e=>{a(e),t=!0},values:{name:r,metadata:n,attributes:i}});performance.now()-s<5e3&&!t;){if((!r||this.name===r)&&(!n||this.metadata===n)&&(!i||Object.entries(i).every(e=>{let[t,n]=e;return this.attributes[t]===n||n===``&&!this.attributes[t]}))){this.pendingSignalRequests.delete(o),e();return}yield xl(50)}a(new Fc(`Request to update local metadata timed out`,`TimeoutError`))}catch(e){e instanceof Error?a(e):a(Error(String(e)))}}))}()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(W.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(W.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(W.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return F(this,void 0,void 0,function*(){this.encryptionType=e?N.GCM:N.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,r){return F(this,void 0,void 0,function*(){this.log.debug(`setTrackEnabled`,Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let i=this.getTrackPublication(e);if(t)if(i)yield i.unmute();else{let t;if(this.pendingPublishing.has(e)){let t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info(`waiting for pending publication promise timed out`,Object.assign(Object.assign({},this.logContext),{source:e})),yield t?.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case W.Source.Camera:t=yield this.createTracks({video:n??!0});break;case W.Source.Microphone:t=yield this.createTracks({audio:n??!0});break;case W.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},n));break;default:throw new Ac(e)}}catch(n){throw t?.forEach(e=>{e.stop()}),n instanceof Error&&this.emit(z.MediaDevicesError,n,rl(e)),this.pendingPublishing.delete(e),n}for(let r of t){let t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===W.Source.Microphone&&fu(r)&&t.preConnectBuffer&&(this.log.info(`starting preconnect buffer for microphone`,Object.assign({},this.logContext)),r.startPreConnectBuffer())}try{let e=[];for(let n of t)this.log.info(`publishing track`,Object.assign(Object.assign({},this.logContext),U(n))),e.push(this.publishTrack(n,r));let n=yield Promise.all(e);[i]=n}catch(e){throw t?.forEach(e=>{e.stop()}),e}finally{this.pendingPublishing.delete(e)}}else if(!i?.track&&this.pendingPublishing.has(e)&&(i=yield this.waitForPendingPublicationOfSource(e),i||this.log.info(`waiting for pending publication promise timed out`,Object.assign(Object.assign({},this.logContext),{source:e}))),i&&i.track)if(e===W.Source.ScreenShare){i=yield this.unpublishTrack(i.track);let e=this.getTrackPublication(W.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield i.mute();return i})}enableCameraAndMicrophone(){return F(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(W.Source.Camera)||this.pendingPublishing.has(W.Source.Microphone))){this.pendingPublishing.add(W.Source.Camera),this.pendingPublishing.add(W.Source.Microphone);try{let e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete(W.Source.Camera),this.pendingPublishing.delete(W.Source.Microphone)}}})}createTracks(e){return F(this,void 0,void 0,function*(){e??={};let t=Zc(e,this.roomOptions?.audioCaptureDefaults,this.roomOptions?.videoCaptureDefaults);try{return(yield bm(t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(e=>(fu(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=W.Source.Microphone,this.emit(z.AudioStreamAcquired)),pu(e)&&(this.cameraError=void 0,e.source=W.Source.Camera),e))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}})}createScreenTracks(e){return F(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new kc(`getDisplayMedia not supported`);e.resolution===void 0&&!Nl()&&(e.resolution=Xc.h1080fps30.resolution);let t=il(e),n=yield navigator.mediaDevices.getDisplayMedia(t),r=n.getVideoTracks();if(r.length===0)throw new Ac(`no video track found`);let i=new kf(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});i.source=W.Source.ScreenShare,e.contentHint&&(i.mediaStreamTrack.contentHint=e.contentHint);let a=[i];if(n.getAudioTracks().length>0){this.emit(z.AudioStreamAcquired);let e=new uf(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=W.Source.ScreenShareAudio,a.push(e)}return a})}publishTrack(e,t){return F(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return F(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){hu(e)&&e.setAudioContext(n.audioContext),yield n.reconnectFuture?.promise,n.republishPromise&&!r&&(yield n.republishPromise),du(e)&&n.pendingPublishPromises.has(e)&&(yield n.pendingPublishPromises.get(e));let i;if(e instanceof MediaStreamTrack)i=e.getConstraints();else{i=e.constraints;let t;switch(e.source){case W.Source.Microphone:t=`audioinput`;break;case W.Source.Camera:t=`videoinput`}t&&n.activeDeviceMap.has(t)&&(i=Object.assign(Object.assign({},i),{deviceId:n.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case`audio`:e=new uf(e,i,!0,n.audioContext,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;case`video`:e=new kf(e,i,!0,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;default:throw new Ac(`unsupported MediaStreamTrack kind ${e.kind}`)}else e.updateLoggerOptions({loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});let a;if(n.trackPublications.forEach(t=>{t.track&&t.track===e&&(a=t)}),a)return n.log.warn(`track has already been published, skipping`,Object.assign(Object.assign({},n.logContext),U(a))),a;let o=Object.assign(Object.assign({},n.roomOptions.publishDefaults),t),s=`channelCount`in e.mediaStreamTrack.getSettings()&&e.mediaStreamTrack.getSettings().channelCount===2||e.mediaStreamTrack.getConstraints().channelCount===2,c=o.forceStereo??s;c&&(o.dtx===void 0&&n.log.info(`Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.`,Object.assign(Object.assign({},n.logContext),U(e))),o.red===void 0&&n.log.info(`Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work.`),o.dtx??=!1,o.red??=!1),!Il()&&n.roomOptions.e2ee&&(n.log.info(`End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2`,Object.assign({},n.logContext)),o.simulcast=!1),o.source&&(e.source=o.source);let l=new Promise((t,r)=>F(n,void 0,void 0,function*(){try{if(this.engine.client.currentState!==G.CONNECTED){this.log.debug(`deferring track publication until signal is connected`,Object.assign(Object.assign({},this.logContext),{track:U(e)}));let n=!1,i=setTimeout(()=>{n=!0,e.stop(),r(new Pc(`publishing rejected as engine not connected within timeout`,408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(i),n)return;t(yield this.publish(e,o,c))}else try{t(yield this.publish(e,o,c))}catch(e){r(e)}}catch(e){r(e)}}));n.pendingPublishPromises.set(e,l);try{return yield l}catch(e){throw e}finally{n.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||=new tu,this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn(`no permissions present for publishing track`,Object.assign(Object.assign({},this.logContext),U(e))),!1;let{canPublish:t,canPublishSources:n}=this.permissions;return t&&(n.length===0||n.map(e=>ul(e)).includes(e.source))?!0:(this.log.warn(`insufficient permissions to publish`,Object.assign(Object.assign({},this.logContext),U(e))),!1)}publish(e,t,n){return F(this,void 0,void 0,function*(){if(!this.hasPermissionsToPublish(e))throw new Pc(`failed to publish track, insufficient permissions`,403);Array.from(this.trackPublications.values()).find(t=>du(e)&&t.source===e.source)&&e.source!==W.Source.Unknown&&this.log.info(`publishing a second track with the same source: ${e.source}`,Object.assign(Object.assign({},this.logContext),U(e))),t.stopMicTrackOnMute&&fu(e)&&(e.stopOnMute=!0),e.source===W.Source.ScreenShare&&kl()&&(t.simulcast=!1),t.videoCodec===`av1`&&!wl()&&(t.videoCodec=void 0),t.videoCodec===`vp9`&&!Tl()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Rd),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(e=>t.videoCodec===al(e.mime))||(t.videoCodec=al(this.enabledPublishVideoCodecs[0].mime)));let r=t.videoCodec;e.on(V.Muted,this.onTrackMuted),e.on(V.Unmuted,this.onTrackUnmuted),e.on(V.Ended,this.handleTrackEnded),e.on(V.UpstreamPaused,this.onTrackUpstreamPaused),e.on(V.UpstreamResumed,this.onTrackUpstreamResumed),e.on(V.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);let i=[],a=!(t.dtx??!0),o=e.getSourceTrackSettings();o.autoGainControl&&i.push(Ri.TF_AUTO_GAIN_CONTROL),o.echoCancellation&&i.push(Ri.TF_ECHO_CANCELLATION),o.noiseSuppression&&i.push(Ri.TF_NOISE_SUPPRESSION),o.channelCount&&o.channelCount>1&&i.push(Ri.TF_STEREO),a&&i.push(Ri.TF_NO_DTX),hu(e)&&e.hasPreConnectBuffer&&i.push(Ri.TF_PRECONNECT_BUFFER);let s=new Fa({cid:e.mediaStreamTrack.id,name:t.name,type:W.kindToProto(e.kind),muted:e.isMuted,source:W.sourceToProto(e.source),disableDtx:a,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(t.red??!0),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:i}),c;if(e.kind===W.Kind.Video){let n={width:0,height:0};try{n=yield e.waitForDimensions()}catch{let t=this.roomOptions.videoCaptureDefaults?.resolution??Jc.h720.resolution;n={width:t.width,height:t.height},this.log.error(`could not determine track dimensions, using defaults`,Object.assign(Object.assign(Object.assign({},this.logContext),U(e)),{dims:n}))}s.width=n.width,s.height=n.height,mu(e)&&(El(r)&&(e.source===W.Source.ScreenShare&&(t.scalabilityMode=`L1T3`,`contentHint`in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint=`motion`,this.log.info(`forcing contentHint to motion for screenshare with SVC codecs`,Object.assign(Object.assign({},this.logContext),U(e))))),t.scalabilityMode=t.scalabilityMode??`L3T3_KEY`),s.simulcastCodecs=[new Pa({codec:r,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Rd}),t.backupCodec&&r!==t.backupCodec.codec&&s.encryption===N.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),s.simulcastCodecs.push(new Pa({codec:t.backupCodec.codec,cid:``})))),c=yf(e.source===W.Source.ScreenShare,s.width,s.height,t),s.layers=Mf(s.width,s.height,c,El(t.videoCodec))}else e.kind===W.Kind.Audio&&(c=[{maxBitrate:t.audioPreset?.maxBitrate,priority:t.audioPreset?.priority??`high`,networkPriority:t.audioPreset?.priority??`high`}]);if(!this.engine||this.engine.isClosed)throw new Mc(`cannot publish track when not connected`);let l=()=>F(this,void 0,void 0,function*(){if(!this.engine.pcManager)throw new Mc(`pcManager is not ready`);if(e.sender=yield this.engine.createSender(e,t,c),this.emit(z.LocalSenderCreated,e.sender,e),mu(e)&&(t.degradationPreference??=Df(e),e.setDegradationPreference(t.degradationPreference)),c)if(kl()&&e.kind===W.Kind.Audio){let t;for(let n of this.engine.pcManager.publisher.getTransceivers())if(n.sender===e.sender){t=n;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:`opus`,maxbr:c[0]?.maxBitrate?c[0].maxBitrate/1e3:0})}else e.codec&&El(e.codec)&&c[0]?.maxBitrate&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:s.cid,codec:e.codec,maxbr:c[0].maxBitrate/1e3});yield this.engine.negotiate()}),u,d=new Promise((t,n)=>F(this,void 0,void 0,function*(){try{u=yield this.engine.addTrack(s),t(u)}catch(t){e.sender&&this.engine.pcManager?.publisher&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(t=>{this.log.error(`failed to negotiate after removing track due to failed add track request`,Object.assign(Object.assign(Object.assign({},this.logContext),U(e)),{error:t}))})),n(t)}}));if(this.enabledPublishVideoCodecs.length>0)u=(yield Promise.all([d,l()]))[0];else{u=yield d;let n;if(u.codecs.forEach(e=>{n===void 0&&(n=e.mimeType)}),n&&e.kind===W.Kind.Video){let i=al(n);i!==r&&(this.log.debug(`falling back to server selected codec`,Object.assign(Object.assign(Object.assign({},this.logContext),U(e)),{codec:i})),t.videoCodec=i,c=yf(e.source===W.Source.ScreenShare,s.width,s.height,t))}yield l()}let f=new ym(e.kind,u,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(f.on(V.CpuConstrained,e=>this.onTrackCpuConstrained(e,f)),f.options=t,e.sid=u.sid,this.log.debug(`publishing ${e.kind} with encodings`,Object.assign(Object.assign({},this.logContext),{encodings:c,trackInfo:u})),mu(e)?e.startMonitor(this.engine.client):hu(e)&&e.startMonitor(),this.addTrackPublication(f),this.emit(z.LocalTrackPublished,f),hu(e)&&u.audioFeatures.includes(Ri.TF_PRECONNECT_BUFFER)){let t=e.getPreConnectBuffer(),n=e.getPreConnectBufferMimeType();this.on(z.LocalTrackSubscribed,t=>{if(t.trackSid===u.sid){if(!e.hasPreConnectBuffer){this.log.warn(`subscribe event came to late, buffer already closed`,this.logContext);return}this.log.debug(`finished recording preconnect buffer`,Object.assign(Object.assign({},this.logContext),U(e))),e.stopPreConnectBuffer()}}),t&&new Promise((r,i)=>F(this,void 0,void 0,function*(){var a,s,c,l;try{this.log.debug(`waiting for agent`,Object.assign(Object.assign({},this.logContext),U(e)));let m=setTimeout(()=>{i(Error(`agent not active within 10 seconds`))},1e4),h=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug(`sending preconnect buffer`,Object.assign(Object.assign({},this.logContext),U(e)));let g=yield this.streamBytes({name:`preconnect-buffer`,mimeType:n,topic:`lk.agent.pre-connect-audio-buffer`,destinationIdentities:[h.identity],attributes:{trackId:f.trackSid,sampleRate:String(o.sampleRate??`48000`),channels:String(o.channelCount??`1`)}});try{for(var u=!0,d=rs(t),p;p=yield d.next(),a=p.done,!a;u=!0){l=p.value,u=!1;let e=l;yield g.write(e)}}catch(e){s={error:e}}finally{try{!u&&!a&&(c=d.return)&&(yield c.call(d))}finally{if(s)throw s.error}}yield g.close(),r()}catch(e){i(e)}})).then(()=>{this.log.debug(`preconnect buffer sent successfully`,Object.assign(Object.assign({},this.logContext),U(e)))}).catch(t=>{this.log.error(`error sending preconnect buffer`,Object.assign(Object.assign(Object.assign({},this.logContext),U(e)),{error:t}))})}return f})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return F(this,void 0,void 0,function*(){if(this.encryptionType!==N.NONE)return;let r;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(r=t)}),!r)throw new Ac(`track is not published`);if(!mu(e))throw new Ac(`track is not a video track`);let i=Object.assign(Object.assign({},this.roomOptions?.publishDefaults),n),a=bf(e,t,i);if(!a){this.log.info(`backup codec has been disabled, ignoring request to add additional codec for track`,Object.assign(Object.assign({},this.logContext),U(e)));return}let o=e.addSimulcastTrack(t,a);if(!o)return;let s=new Fa({cid:o.mediaStreamTrack.id,type:W.kindToProto(e.kind),muted:e.isMuted,source:W.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:i.videoCodec,cid:o.mediaStreamTrack.id}]});if(s.layers=Mf(s.width,s.height,a),!this.engine||this.engine.isClosed)throw new Mc(`cannot publish track when not connected`);let c=(yield Promise.all([this.engine.addTrack(s),F(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,o,i,a),yield this.engine.negotiate()})]))[0];this.log.debug(`published ${t} for track ${e.sid}`,Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:c}))})}unpublishTrack(e,t){return F(this,void 0,void 0,function*(){if(du(e)){let t=this.pendingPublishPromises.get(e);t&&(this.log.info(`awaiting publish promise before attempting to unpublish`,Object.assign(Object.assign({},this.logContext),U(e))),yield t)}let n=this.getPublicationForTrack(e),r=n?U(n):void 0;if(this.log.debug(`unpublishing track`,Object.assign(Object.assign({},this.logContext),r)),!n||!n.track){this.log.warn(`track was not unpublished because no publication was found`,Object.assign(Object.assign({},this.logContext),r));return}e=n.track,e.off(V.Muted,this.onTrackMuted),e.off(V.Unmuted,this.onTrackUnmuted),e.off(V.Ended,this.handleTrackEnded),e.off(V.UpstreamPaused,this.onTrackUpstreamPaused),e.off(V.UpstreamResumed,this.onTrackUpstreamResumed),e.off(V.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=this.roomOptions?.stopLocalTrackOnUnpublish??!0),t?e.stop():e.stopMonitor();let i=!1,a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Wd.FAILED&&a)try{for(let e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction=`inactive`,i=!0);if(this.engine.removeTrack(a)&&(i=!0),mu(e)){for(let[,t]of e.simulcastCodecs)t.sender&&=(this.engine.removeTrack(t.sender)&&(i=!0),void 0);e.simulcastCodecs.clear()}}catch(e){this.log.warn(`failed to unpublish track`,Object.assign(Object.assign(Object.assign({},this.logContext),r),{error:e}))}switch(this.trackPublications.delete(n.trackSid),n.kind){case W.Kind.Audio:this.audioTrackPublications.delete(n.trackSid);break;case W.Kind.Video:this.videoTrackPublications.delete(n.trackSid);break}return this.emit(z.LocalTrackUnpublished,n),n.setTrack(void 0),i&&(yield this.engine.negotiate()),n})}unpublishTracks(e){return F(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return F(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new yc((r,i)=>F(t,void 0,void 0,function*(){try{let t=[];this.trackPublications.forEach(n=>{n.track&&(e&&(n.options=Object.assign(Object.assign({},n.options),e)),t.push(n))}),yield Promise.all(t.map(e=>F(this,void 0,void 0,function*(){let t=e.track;yield this.unpublishTrack(t,!1),n&&!t.isMuted&&t.source!==W.Source.ScreenShare&&t.source!==W.Source.ScreenShareAudio&&(hu(t)||mu(t))&&!t.isUserProvided&&(this.log.debug(`restarting existing track`,Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))),r()}catch(e){e instanceof Error?i(e):i(Error(String(e)))}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return F(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){let r=n.reliable?K.RELIABLE:K.LOSSY,i=n.reliable?$i.RELIABLE:$i.LOSSY,a=n.destinationIdentities,o=n.topic,s=new Qi({kind:i,value:{case:`user`,value:new ia({participantIdentity:t.identity,payload:e,destinationIdentities:a,topic:o})}});yield t.engine.sendDataPacket(s,r)}()})}publishDtmf(e,t){return F(this,void 0,void 0,function*(){let n=new Qi({kind:$i.RELIABLE,value:{case:`sipDtmf`,value:new aa({code:e,digit:t})}});yield this.engine.sendDataPacket(n,K.RELIABLE)})}sendChatMessage(e,t){return F(this,void 0,void 0,function*(){let n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},r=new Qi({value:{case:`chatMessage`,value:new ca(Object.assign(Object.assign({},n),{timestamp:or.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(r,K.RELIABLE),this.emit(z.ChatMessage,n),n})}editChatMessage(e,t){return F(this,void 0,void 0,function*(){let n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new Qi({value:{case:`chatMessage`,value:new ca(Object.assign(Object.assign({},n),{timestamp:or.parse(n.timestamp),editTimestamp:or.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,K.RELIABLE),this.emit(z.ChatMessage,n),n})}sendText(e,t){return F(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return F(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return F(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return F(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:n,payload:r,responseTimeout:i=15e3}=e,a=7e3;return a+1e3,new yc((e,o)=>F(this,void 0,void 0,function*(){if(Qd(r)>Zd){o(Xd.builtIn(`REQUEST_PAYLOAD_TOO_LARGE`));return}if(this.engine.latestJoinResponse?.serverInfo?.version&&Wl(this.engine.latestJoinResponse?.serverInfo?.version,`1.8.0`)<0){o(Xd.builtIn(`UNSUPPORTED_SERVER`));return}let s=Math.max(i,8e3),c=crypto.randomUUID();yield this.publishRpcRequest(t,c,n,r,s);let l=setTimeout(()=>{this.pendingAcks.delete(c),o(Xd.builtIn(`CONNECTION_TIMEOUT`)),this.pendingResponses.delete(c),clearTimeout(u)},a);this.pendingAcks.set(c,{resolve:()=>{clearTimeout(l)},participantIdentity:t});let u=setTimeout(()=>{this.pendingResponses.delete(c),o(Xd.builtIn(`RESPONSE_TIMEOUT`))},i);this.pendingResponses.set(c,{resolve:(t,n)=>{clearTimeout(u),this.pendingAcks.has(c)&&(this.log.warn(`RPC response received before ack`,c),this.pendingAcks.delete(c),clearTimeout(l)),n?o(n):e(t??``)},participantIdentity:t})}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn(`you're overriding the RPC handler for method ${e}, in the future this will throw an error`),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){this.participantTrackPermissions=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){let t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error(`Ack received for unexpected RPC request`,e)}handleIncomingRpcResponse(e,t,n){let r=this.pendingResponses.get(e);r?(r.resolve(t,n),this.pendingResponses.delete(e)):console.error(`Response received for unexpected RPC request`,e)}publishRpcRequest(e,t,n,r,i){return F(this,void 0,void 0,function*(){let a=new Qi({destinationIdentities:[e],kind:$i.RELIABLE,value:{case:`rpcRequest`,value:new la({id:t,method:n,payload:r,responseTimeoutMs:i,version:1})}});yield this.engine.sendDataPacket(a,K.RELIABLE)})}handleParticipantDisconnected(e){for(let[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(let[t,{participantIdentity:n,resolve:r}]of this.pendingResponses)n===e&&(r(null,Xd.builtIn(`RECIPIENT_DISCONNECTED`)),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(e=>e.mime.split(`/`)[0].toLowerCase()===`video`)}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(e=>{let t=this.trackPublications.get(e.sid);if(t){let n=t.isMuted||(t.track?.isUpstreamPaused??!1);n!==e.muted&&(this.log.debug(`updating server mute state after reconcile`,Object.assign(Object.assign(Object.assign({},this.logContext),U(t)),{mutedOnServer:n})),this.engine.client.sendMuteTrack(e.sid,n))}}),!0):!1}setActiveAgent(e){var t,n,r,i;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(n=(t=this.activeAgentFuture)?.resolve)==null||n.call(t,e):(i=(r=this.activeAgentFuture)?.reject)==null||i.call(r,Error(`Agent disconnected`)),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||=new tu,this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{let r=n.track;r&&(e instanceof MediaStreamTrack?(hu(r)||mu(r))&&r.mediaStreamTrack===e&&(t=n):e===r&&(t=n))}),t}waitForPendingPublicationOfSource(e){return F(this,void 0,void 0,function*(){let t=Date.now();for(;Date.now()<t+1e4;){let t=Array.from(this.pendingPublishPromises.entries()).find(t=>{let[n]=t;return n.source===e});if(t)return t[1];yield xl(20)}})}publishDataTrack(e){return F(this,void 0,void 0,function*(){let t=new am(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}},Dm=class extends DOMException{constructor(e,t){super(e,`AbortError`),this.reason=t}},Om=class extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var n;super.set(e,t);let r=this.pending.get(e);if(r){for(let e of r)e.isResolved||(n=e.resolve)==null||n.call(e,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return`WaitableMap`}getDeferred(e,t){return F(this,void 0,void 0,function*(){let n=this.get(e);if(n!==void 0)return n;if(t?.aborted)throw new Dm(`The operation was aborted.`,t.reason);let r=new tu(void 0,()=>{let t=this.pending.get(e);if(!t)return;let n=t.indexOf(r);n!==-1&&t.splice(n,1),t.length===0&&this.pending.delete(e)}),i=this.pending.get(e);if(i?i.push(r):this.pending.set(e,[r]),t){let e=()=>{var e;r.isResolved||(e=r.reject)==null||e.call(r,new Dm(`The operation was aborted.`,t.reason))};t.addEventListener(`abort`,e,{once:!0}),r.promise.finally(()=>{t.removeEventListener(`abort`,e)})}return r.promise})}},km=class extends vm{constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(V.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug(`adaptivestream video visibility ${this.trackSid}, visible=${e}`,this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug(`adaptivestream video dimensions ${e.width}x${e.height}`,this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);let r=new Xa({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new pa({participantSid:``,trackSids:[this.trackSid]})]});this.emit(V.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?vm.SubscriptionStatus.Unsubscribed:super.isSubscribed?vm.SubscriptionStatus.Subscribed:vm.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?vm.PermissionStatus.Allowed:vm.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled===void 0?this.isAdaptiveStream?this.visible:!0:!this.requestedDisabled}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){this.isManualOperationAllowed()&&(this.requestedVideoDimensions?.width===e.width&&this.requestedVideoDimensions?.height===e.height||(vu(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&vu(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.requestedMaxQuality??hl.HIGH}setTrack(e){let t=this.subscriptionStatus,n=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(V.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(V.VisibilityChanged,this.handleVisibilityChange),r.off(V.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(V.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(V.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(V.VisibilityChanged,this.handleVisibilityChange),e.on(V.Ended,this.handleEnded),this.emit(V.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(V.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);let t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?V.Muted:V.Unmuted)}emitSubscriptionUpdateIfChanged(e){let t=this.subscriptionStatus;e!==t&&this.emit(V.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(V.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn(`cannot update track settings when not subscribed`,this.logContext),!1)}get isAdaptiveStream(){return vu(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new $a({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===W.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)dl(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug(`using adaptive stream dimensions instead of requested`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){let e=fl(this.trackInfo,this.requestedMaxQuality);e&&dl(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug(`using adaptive stream dimensions instead of max quality layer`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug(`using adaptive stream dimensions`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality===void 0?(this.log.debug(`using default quality`,Object.assign(Object.assign({},this.logContext),{quality:hl.HIGH})),e.quality=hl.HIGH):(this.log.debug(`using requested max quality`,Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality)}this.emit(V.UpdateSettings,e)}},Am=class e extends wm{static fromParticipantInfo(t,n,r){return new e(t,n.sid,n.identity,n.name,n.metadata,n.attributes,r,n.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,r,i,a,o){let s=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Wi.STANDARD;super(t,n||``,r,i,a,o,s),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new Om,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(V.UpdateSettings,t=>{this.log.debug(`send update settings`,Object.assign(Object.assign(Object.assign({},this.logContext),U(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(V.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(V.SubscriptionPermissionChanged,t=>{this.emit(z.TrackSubscriptionPermissionChanged,e,t)}),e.on(V.SubscriptionStatusChanged,t=>{this.emit(z.TrackSubscriptionStatusChanged,e,t)}),e.on(V.Subscribed,t=>{this.emit(z.TrackSubscribed,t,e)}),e.on(V.Unsubscribed,t=>{this.emit(z.TrackUnsubscribed,t,e)}),e.on(V.SubscriptionFailed,t=>{this.emit(z.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:W.Source.Microphone;this.volumeMap.set(t,e);let n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:W.Source.Microphone,t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,r,i,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith(`TR`)||this.trackPublications.forEach(t=>{!o&&e.kind===t.kind.toString()&&(o=t)}),!o){if(a===0){this.log.error(`could not find published track`,Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(z.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,r,i,a-1)},150);return}if(e.readyState===`ended`){this.log.error(`unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()`,Object.assign(Object.assign({},this.logContext),U(o))),this.emit(z.TrackSubscriptionFailed,t);return}let s=e.kind===`video`,c;return c=s?new mm(e,t,r,i):new fm(e,t,r,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(n),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&gu(c)&&fu(c)&&c.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;let t=new Map,n=new Map;return e.tracks.forEach(e=>{let r=this.getTrackPublicationBySid(e.sid);if(r)r.updateInfo(e);else{let t=W.kindFromProto(e.type);if(!t)return;r=new km(t,e,this.signalClient.connectOptions?.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:this.loggerOptions?.loggerName}),r.updateInfo(e),n.set(e.sid,r);let i=Array.from(this.trackPublications.values()).find(e=>e.source===r?.source);i&&r.source!==W.Source.Unknown&&this.log.debug(`received a second track publication for ${this.identity} with the same source: ${r.source}`,Object.assign(Object.assign({},this.logContext),{oldTrack:U(i),newTrack:U(r)})),this.addTrackPublication(r)}t.set(e.sid,r)}),this.trackPublications.forEach(e=>{t.has(e.trackSid)||(this.log.trace(`detected removed track on remote participant, unpublishing`,Object.assign(Object.assign({},this.logContext),U(e))),this.unpublishTrack(e.trackSid,!0))}),n.forEach(e=>{this.emit(z.TrackPublished,e)}),!0}unpublishTrack(e,t){let n=this.trackPublications.get(e);if(!n)return;let{track:r}=n;switch(r&&(r.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case W.Kind.Audio:this.audioTrackPublications.delete(e);break;case W.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(z.TrackUnpublished,n)}setAudioOutput(e){return F(this,void 0,void 0,function*(){this.audioOutput=e;let t=[];this.audioTrackPublications.forEach(n=>{fu(n.track)&&gu(n.track)&&t.push(n.track.setSinkId(e.deviceId??`default`))}),yield Promise.all(t)})}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(let[t,n]of this.dataTracks.entries())e===n.info.sid&&this.dataTracks.delete(t)}emit(e){var t=[...arguments].slice(1);return this.log.trace(`participant event`,Object.assign(Object.assign({},this.logContext),{event:e,args:t})),super.emit(e,...t)}},q;(function(e){e.Disconnected=`disconnected`,e.Connecting=`connecting`,e.Connected=`connected`,e.Reconnecting=`reconnecting`,e.SignalReconnecting=`signalReconnecting`})(q||={});var jm=4*1e3,Mm=class e extends ss.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(t){var n,r,i;if(super(),n=this,this.state=q.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=P,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(e,t,n)=>F(this,void 0,void 0,function*(){if(!Ol())throw Rl()?Error(`WebRTC isn't detected, have you called registerGlobals?`):Error(`LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.`);let r=yield this.disconnectLock.lock();if(this.state===q.Connected)return this.log.info(`already connected to room ${this.name}`,this.logContext),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(q.Connecting),this.regionUrlProvider?.getServerUrl().toString()!==Eu(e)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),zl(new URL(e))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Jd(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;(t=this.regionUrlProvider)==null||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn(`could not fetch region settings`,Object.assign(Object.assign({},this.logContext),{error:e}))}));let i=(a,o,s)=>F(this,void 0,void 0,function*(){this.abortController&&this.abortController.abort();let c=new AbortController;this.abortController=c,r?.();try{if(yield Uu.getInstance().getBackOffPromise(e),c.signal.aborted)throw L.cancelled(`Connection attempt aborted`);yield this.attemptConnection(s??e,t,n,c),this.abortController=void 0,a()}catch(t){if(this.regionUrlProvider&&t instanceof L&&t.reason!==I.Cancelled&&t.reason!==I.NotAllowed){let n=null;try{this.log.debug(`Fetching next region`),n=yield this.regionUrlProvider.getNextBestRegionUrl(this.abortController?.signal)}catch(e){if(e instanceof L&&(e.status===401||e.reason===I.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),o(e);return}}[I.InternalError,I.ServerUnreachable,I.Timeout].includes(t.reason)&&(this.log.debug(`Adding failed connection attempt to back off`),Uu.getInstance().addFailedConnectionAttempt(e)),n&&!this.abortController?.signal.aborted?(this.log.info(`Initial connection failed with ConnectionError: ${t.message}. Retrying with another region: ${n}`,this.logContext),this.recreateEngine(!0),yield i(a,o,n)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,cu(t)),o(t))}else{let e=Fi.UNKNOWN_REASON;t instanceof L&&(e=cu(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),o(t)}}}),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new tu((e,t)=>{i(e,t,a)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,n,r,i,a)=>F(this,void 0,void 0,function*(){let o=yield n.join(e,t,{autoSubscribe:r.autoSubscribe,adaptiveStream:typeof i.adaptiveStream==`object`?!0:i.adaptiveStream,maxRetries:r.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:r.websocketTimeout},a.signal,!i.singlePeerConnection),s=o.serverInfo;if(s||={version:o.serverVersion,region:o.serverRegion},this.serverInfo=s,this.log.debug(`connected to Livekit Server ${Object.entries(s).map(e=>{let[t,n]=e;return`${t}: ${n}`}).join(`, `)}`,{room:o.room?.name,roomSid:o.room?.sid,identity:o.participant?.identity}),!s.version)throw new jc(`unknown server version`);return s.version===`0.15.1`&&this.options.dynacast&&(this.log.debug(`disabling dynacast due to server version`,this.logContext),i.dynacast=!1),o}),this.applyJoinResponse=e=>{let t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:`Could not set SifTrailer`,Object.assign(Object.assign({},this.logContext),{error:e}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,n,r)=>F(this,void 0,void 0,function*(){this.state===q.Reconnecting||this.isResuming||this.engine?.pendingReconnect?(this.log.info(`Reconnection attempt replaced by new connection attempt`,this.logContext),this.recreateEngine(!0)):this.maybeCreateEngine(),this.regionUrlProvider?.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Ud),n),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{let n=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,r);this.applyJoinResponse(n),this.setupLocalParticipantEvents(),this.emit(R.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();let t=r.signal.aborted?L.cancelled(`Signal connection aborted`):L.serverUnreachable(`could not establish signal connection`);throw e instanceof Error&&(t.message=`${t.message}: ${e.message}`),e instanceof L&&(t.reason=e.reason,t.status=e.status),this.log.debug(`error trying to establish signal connection`,Object.assign(Object.assign({},this.logContext),{error:e})),t}if(r.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),L.cancelled(`Connection attempt aborted`);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,r)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}Ll()&&this.options.disconnectOnPageLeave&&(window.addEventListener(`pagehide`,this.onPageLeave),window.addEventListener(`beforeunload`,this.onPageLeave)),Ll()&&window.addEventListener(`freeze`,this.onPageLeave),this.setAndEmitConnectionState(q.Connected),this.emit(R.Connected),Uu.getInstance().resetFailedConnectionAttempts(e),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){return F(n,[...[...arguments]],void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,r,i;let a=yield e.disconnectLock.lock();try{if(e.state===q.Disconnected){e.log.debug(`already disconnected`,e.logContext);return}if(e.log.info(`disconnect from room`,Object.assign({},e.logContext)),e.state===q.Connecting||e.state===q.Reconnecting||e.isResuming){let t=`Abort connection attempt due to user initiated disconnect`;e.log.warn(t,e.logContext),(n=e.abortController)==null||n.abort(t),(i=(r=e.connectFuture)?.reject)==null||i.call(r,L.cancelled(`Client initiated disconnect`)),e.connectFuture=void 0}e.engine&&(e.engine.client.isDisconnected||(yield e.engine.client.sendLeave()),yield e.engine.close()),e.handleDisconnect(t,Fi.CLIENT_INITIATED),e.engine=void 0}finally{a()}}()})},this.onPageLeave=()=>F(this,void 0,void 0,function*(){this.log.info(`Page leave detected, disconnecting`,this.logContext),yield this.disconnect()}),this.startAudio=()=>F(this,void 0,void 0,function*(){let e=[],t=Sc();if(t&&t.os===`iOS`){let t=`livekit-dummy-audio-el`,n=document.getElementById(t);if(!n){n=document.createElement(`audio`),n.id=t,n.autoplay=!0,n.hidden=!0;let e=eu();e.enabled=!0;let r=new MediaStream([e]);n.srcObject=r,document.addEventListener(`visibilitychange`,()=>{n&&(n.srcObject=document.hidden?null:r,document.hidden||(this.log.debug(`page visible again, triggering startAudio to resume playback and update playback status`,this.logContext),this.startAudio()))}),document.body.append(n),this.once(R.Disconnected,()=>{n?.remove(),n=null})}e.push(n)}this.remoteParticipants.forEach(t=>{t.audioTrackPublications.forEach(t=>{t.track&&t.track.attachedElements.forEach(t=>{e.push(t)})})});try{yield Promise.all([this.acquireAudioContext(),...e.map(e=>(e.muted=!1,e.play()))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}),this.startVideo=()=>F(this,void 0,void 0,function*(){let e=[];for(let t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var n;(n=t.track)==null||n.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{e.name===`NotAllowedError`?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(let e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(q.Reconnecting)&&this.emit(R.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=e=>F(this,void 0,void 0,function*(){this.log.debug(`signal reconnected to server, region ${e.serverRegion}`,Object.assign(Object.assign({},this.logContext),{region:e.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error(`error trying to re-publish tracks after reconnection`,Object.assign(Object.assign({},this.logContext),{error:e}))}try{yield this.engine.waitForRestarted(),this.log.debug(`fully reconnected to server`,Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch{return}this.setAndEmitConnectionState(q.Connected),this.emit(R.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{for(let t of e){if(t.identity===this.localParticipant.identity){this.localParticipant.updateInfo(t);continue}t.identity===``&&(t.identity=this.sidToIdentity.get(t.sid)??``);let e=this.remoteParticipants.get(t.identity);t.state===Ui.DISCONNECTED?this.handleParticipantDisconnected(t.identity,e):e=this.getOrCreateParticipant(t.identity,t)}let t=new Map(e.filter(e=>e.identity!==this.localParticipant.identity).map(e=>[e.identity,e.dataTracks.map(e=>nd.from(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)},this.handleActiveSpeakersUpdate=e=>{let t=[],n={};e.forEach(e=>{if(n[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{let n=this.getRemoteParticipantBySid(e.sid);n&&(n.audioLevel=e.level,n.setIsSpeaking(!0),t.push(n))}}),n[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(e=>{n[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(R.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{let t=new Map;this.activeSpeakers.forEach(e=>{let n=this.remoteParticipants.get(e.identity);n&&n.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let n=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(n=this.localParticipant),n&&(n.audioLevel=e.level,n.setIsSpeaking(e.active),e.active?t.set(e.sid,n):t.delete(e.sid))});let n=Array.from(t.values());n.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=n,this.emitWhenConnected(R.ActiveSpeakersChanged,n)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);if(!n||!n.track)return;let r=W.streamStateFromProto(e.state);n.track.setStreamState(r),r!==n.track.streamState&&(t.emit(z.TrackStreamStateChanged,n,n.track.streamState),this.emitWhenConnected(R.TrackStreamStateChanged,n,n.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);n&&n.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{let t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);n&&n.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{let n=this.remoteParticipants.get(e.participantIdentity);if(e.value.case===`user`)this.handleUserPacket(n,e.value.value,e.kind,t);else if(e.value.case===`transcription`)this.handleTranscription(n,e.value.value);else if(e.value.case===`sipDtmf`)this.handleSipDtmf(n,e.value.value);else if(e.value.case===`chatMessage`)this.handleChatMessage(n,e.value.value);else if(e.value.case===`metrics`)this.handleMetrics(e.value.value,n);else if(e.value.case===`streamHeader`||e.value.case===`streamChunk`||e.value.case===`streamTrailer`)this.handleDataStream(e,t);else if(e.value.case===`rpcRequest`){let t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,n,r)=>{this.emit(R.DataReceived,t.payload,e,n,t.topic,r),e?.emit(z.DataReceived,t.payload,n,r)},this.handleSipDtmf=(e,t)=>{this.emit(R.SipDTMFReceived,t,e),e?.emit(z.SipDTMFReceived,t)},this.handleTranscription=(e,t)=>{let n=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),r=n?.trackPublications.get(t.trackId),i=ou(t,this.transcriptionReceivedTimes);r?.emit(V.TranscriptionReceived,i),n?.emit(z.TranscriptionReceived,i,r),this.emit(R.TranscriptionReceived,i,n,r)},this.handleChatMessage=(e,t)=>{let n=su(t);this.emit(R.ChatMessage,n,e)},this.handleMetrics=(e,t)=>{this.emit(R.MetricsReceived,e,t)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(R.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn(`could not playback audio`,Object.assign(Object.assign({},this.logContext),{error:e})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(R.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(R.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(R.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>F(this,void 0,void 0,function*(){Sc()?.os!==`iOS`&&(yield this.selectDefaultDevices()),this.emit(R.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{let t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(R.RoomMetadataChanged,e.metadata),t?.activeRecording!==e.activeRecording&&this.emitWhenConnected(R.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach(e=>{if(e.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(e.quality);return}let t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)})},this.onLocalParticipantMetadataChanged=e=>{this.emit(R.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(R.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(R.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(R.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(R.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;(t=e?.onPublish)==null||t.call(e,this)},this.onLocalTrackPublished=e=>F(this,void 0,void 0,function*(){var t,n,r,i;(t=e.track)==null||t.on(V.TrackProcessorUpdate,this.onTrackProcessorUpdate),(n=e.track)==null||n.on(V.Restarted,this.onLocalTrackRestarted),(i=(r=e.track?.getProcessor())?.onPublish)==null||i.call(r,this),this.emit(R.LocalTrackPublished,e,this.localParticipant),hu(e.track)&&(yield e.track.checkForSilence())&&this.emit(R.LocalAudioSilenceDetected,e);let a=yield e.track?.getDeviceId(!1),o=rl(e.source);o&&a&&a!==this.localParticipant.activeDeviceMap.get(o)&&(this.localParticipant.activeDeviceMap.set(o,a),this.emit(R.ActiveDeviceChanged,o,a))}),this.onLocalTrackUnpublished=e=>{var t,n;(t=e.track)==null||t.off(V.TrackProcessorUpdate,this.onTrackProcessorUpdate),(n=e.track)==null||n.off(V.Restarted,this.onLocalTrackRestarted),this.emit(R.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>F(this,void 0,void 0,function*(){let t=yield e.getDeviceId(!1),n=rl(e.source);n&&t&&t!==this.localParticipant.activeDeviceMap.get(n)&&(this.log.debug(`local track restarted, setting ${n} ${t} active`,this.logContext),this.localParticipant.activeDeviceMap.set(n,t),this.emit(R.ActiveDeviceChanged,n,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(R.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(R.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(R.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(R.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Hd),t),this.log=qo(this.options.loggerName??Ko.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Bd),t?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Vd),t?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},zd),t?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Yf,this.outgoingDataStreamManager=new ep(this.engine,this.log),this.incomingDataTrackManager=new Yp({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on(`sfuUpdateSubscription`,e=>{this.engine.client.sendUpdateDataSubscription(e.sid,e.subscribe)}).on(`trackPublished`,e=>{var t;e.track.publisherIdentity!==this.localParticipant.identity&&(this.emit(R.DataTrackPublished,e.track),(t=this.remoteParticipants.get(e.track.publisherIdentity))==null||t.addRemoteDataTrack(e.track))}).on(`trackUnpublished`,e=>{var t;e.publisherIdentity!==this.localParticipant.identity&&(this.emit(R.DataTrackUnpublished,e.sid),(t=this.remoteParticipants.get(e.publisherIdentity))==null||t.removeRemoteDataTrack(e.sid))}),this.outgoingDataTrackManager=new um({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on(`sfuPublishRequest`,e=>{this.engine.client.sendPublishDataTrackRequest(e.handle,e.name,e.usesE2ee)}).on(`sfuUnpublishRequest`,e=>{this.engine.client.sendUnPublishDataTrackRequest(e.handle)}).on(`trackPublished`,e=>{this.emit(R.LocalDataTrackPublished,e.track)}).on(`trackUnpublished`,e=>{this.emit(R.LocalDataTrackUnpublished,e.sid)}).on(`packetAvailable`,e=>{let{bytes:t}=e;this.engine.sendLossyBytes(t,K.DATA_TRACK_LOSSY,`wait`)}),this.disconnectLock=new kn,this.localParticipant=new Em(``,``,this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager,this.outgoingDataTrackManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager(this.e2eeManager??null),this.outgoingDataTrackManager.updateE2eeManager(this.e2eeManager??null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set(`videoinput`,ru(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set(`audioinput`,ru(this.options.audioCaptureDefaults.deviceId)),this.options.audioOutput?.deviceId&&this.switchActiveDevice(`audiooutput`,ru(this.options.audioOutput.deviceId)).catch(e=>this.log.warn(`Could not set audio output: ${e.message}`,this.logContext)),Ll()){let t=new AbortController;(i=(r=navigator.mediaDevices)?.addEventListener)==null||i.call(r,`devicechange`,this.handleDeviceChange,{signal:t.signal}),e.cleanupRegistry&&e.cleanupRegistry.register(this,()=>{t.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error(`RPC handler already registered for method ${e}, unregisterRpcMethod before trying to register again`);this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return F(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==``&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error(`e2ee not configured, please set e2ee settings within the room options`)})}setupE2EE(){var e;let t=!!this.options.encryption,n=this.options.encryption||this.options.e2ee;n&&(`e2eeManager`in n?(this.e2eeManager=n.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new Bu(n,t),this.e2eeManager.on(Nu.ParticipantEncryptionStatusChanged,(e,t)=>{yu(t)&&(this.isE2EEEnabled=e),this.emit(R.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(Nu.EncryptionError,(e,t)=>{let n=t?this.getParticipantByIdentity(t):void 0;this.emit(R.EncryptionError,e,n)}),(e=this.e2eeManager)==null||e.setup(this))}get logContext(){return{room:this.name,roomID:this.roomInfo?.sid,participant:this.localParticipant.identity,participantID:this.localParticipant.sid}}get isRecording(){return this.roomInfo?.activeRecording??!1}getSid(){return this.state===q.Disconnected?yc.resolve(``):this.roomInfo&&this.roomInfo.sid!==``?yc.resolve(this.roomInfo.sid):new yc((e,t)=>{let n=t=>{t.sid!==``&&(this.engine.off(B.RoomUpdate,n),e(t.sid))};this.engine.on(B.RoomUpdate,n),this.once(R.Disconnected,()=>{this.engine.off(B.RoomUpdate,n),t(new Mc(`Room disconnected before room server id was available`))})})}get name(){return this.roomInfo?.name??``}get metadata(){return this.roomInfo?.metadata}get numParticipants(){return this.roomInfo?.numParticipants??0}get numPublishers(){return this.roomInfo?.numPublishers??0}maybeCreateEngine(){this.engine&&(this.engine.isNewlyCreated||!this.engine.isClosed)||(this.engine=new Wf(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(B.ParticipantUpdate,this.handleParticipantUpdates).on(B.RoomUpdate,this.handleRoomUpdate).on(B.SpeakersChanged,this.handleSpeakersChanged).on(B.StreamStateChanged,this.handleStreamStateUpdate).on(B.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(B.SubscriptionError,this.handleSubscriptionError).on(B.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(B.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(B.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(B.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(B.DataPacketReceived,this.handleDataPacket).on(B.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info(`Resuming signal connection`,this.logContext),this.setAndEmitConnectionState(q.SignalReconnecting)&&this.emit(R.SignalReconnecting)}).on(B.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info(`Resumed signal connection`,this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(q.Connected)&&this.emit(R.Reconnected)}).on(B.SignalResumed,()=>{this.bufferedEvents=[],(this.state===q.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(B.Restarting,this.handleRestarting).on(B.Restarted,this.handleRestarted).on(B.SignalRestarted,this.handleSignalRestarted).on(B.Offline,()=>{this.setAndEmitConnectionState(q.Reconnecting)&&this.emit(R.Reconnecting)}).on(B.DCBufferStatusChanged,(e,t)=>{this.emit(R.DCBufferStatusChanged,e,t)}).on(B.LocalTrackSubscribed,e=>{let t=this.localParticipant.getTrackPublications().find(t=>{let{trackSid:n}=t;return n===e});if(!t){this.log.warn(`could not find local track subscription for subscribed event`,this.logContext);return}this.localParticipant.emit(z.LocalTrackSubscribed,t),this.emitWhenConnected(R.LocalTrackSubscribed,t,this.localParticipant)}).on(B.RoomMoved,e=>{this.log.debug(`room moved`,e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((e,t)=>{this.handleParticipantDisconnected(t,e)}),this.emit(R.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(B.PublishDataTrackResponse,e=>{if(!e.info){this.log.warn(`received PublishDataTrackResponse, but event.info was ${e.info}, so skipping.`,this.logContext);return}this.outgoingDataTrackManager.receivedSfuPublishResponse(e.info.pubHandle,{type:`ok`,data:{sid:e.info.sid,pubHandle:e.info.pubHandle,name:e.info.name,usesE2ee:e.info.encryption!==N.NONE}})}).on(B.UnPublishDataTrackResponse,e=>{if(!e.info){this.log.warn(`received UnPublishDataTrackResponse, but event.info was ${e.info}, so skipping.`,this.logContext);return}this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle)}).on(B.DataTrackSubscriberHandles,e=>{let t=new Map(Object.entries(e.subHandles).map(e=>{let[t,n]=e;return[parseInt(t,10),n.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(B.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(e){throw e}}).on(B.Joined,e=>{let t=new Map(e.otherParticipants.map(e=>[e.identity,e.dataTracks.map(e=>nd.from(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Gu.getInstance().getDevices(e,t)}prepareConnection(e,t){return F(this,void 0,void 0,function*(){if(this.state===q.Disconnected){this.log.debug(`prepareConnection to ${e}`,this.logContext);try{if(zl(new URL(e))&&t){this.regionUrlProvider=new Jd(e,t);let n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===q.Disconnected&&(this.regionUrl=n,yield fetch(au(n),{method:`HEAD`}),this.log.debug(`prepared connection to ${n}`,this.logContext))}else yield fetch(au(e),{method:`HEAD`})}catch(e){this.log.warn(`could not prepare connection`,Object.assign(Object.assign({},this.logContext),{error:e}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return F(this,void 0,void 0,function*(){let n=()=>F(this,void 0,void 0,function*(){}),r;switch(e){case`signal-reconnect`:yield this.engine.client.handleOnClose(`simulate disconnect`);break;case`speaker`:r=new To({scenario:{case:`speakerUpdate`,value:3}});break;case`node-failure`:r=new To({scenario:{case:`nodeFailure`,value:!0}});break;case`server-leave`:r=new To({scenario:{case:`serverLeave`,value:!0}});break;case`migration`:r=new To({scenario:{case:`migration`,value:!0}});break;case`resume-reconnect`:this.engine.failNext(),yield this.engine.client.handleOnClose(`simulate resume-disconnect`);break;case`disconnect-signal-on-resume`:n=()=>F(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose(`simulate resume-disconnect`)}),r=new To({scenario:{case:`disconnectSignalOnResume`,value:!0}});break;case`disconnect-signal-on-resume-no-messages`:n=()=>F(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose(`simulate resume-disconnect`)}),r=new To({scenario:{case:`disconnectSignalOnResumeNoMessages`,value:!0}});break;case`full-reconnect`:this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose(`simulate full-reconnect`);break;case`force-tcp`:case`force-tls`:r=new To({scenario:{case:`switchCandidateProtocol`,value:e===`force-tls`?2:1}}),n=()=>F(this,void 0,void 0,function*(){let e=this.engine.client.onLeave;e&&e(new no({reason:Fi.CLIENT_INITIATED,action:ro.RECONNECT}))});break;case`subscriber-bandwidth`:if(t===void 0||typeof t!=`number`)throw Error(`subscriber-bandwidth requires a number as argument`);r=new To({scenario:{case:`subscriberBandwidth`,value:uu(t)}});break;case`leave-full-reconnect`:r=new To({scenario:{case:`leaveRequestFullReconnect`,value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return F(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var i,a;let o=!0,s=!1,c=r?{exact:t}:t;if(e===`audioinput`){s=n.localParticipant.audioTrackPublications.size===0;let t=n.getActiveDevice(e)??n.options.audioCaptureDefaults.deviceId;n.options.audioCaptureDefaults.deviceId=c;let r=Array.from(n.localParticipant.audioTrackPublications.values()).filter(e=>e.source===W.Source.Microphone);try{o=(yield Promise.all(r.map(e=>e.audioTrack?.setDeviceId(c)))).every(e=>e===!0)}catch(e){throw n.options.audioCaptureDefaults.deviceId=t,e}let i=r.some(e=>e.track?.isMuted??!1);o&&i&&(s=!0)}else if(e===`videoinput`){s=n.localParticipant.videoTrackPublications.size===0;let t=n.getActiveDevice(e)??n.options.videoCaptureDefaults.deviceId;n.options.videoCaptureDefaults.deviceId=c;let r=Array.from(n.localParticipant.videoTrackPublications.values()).filter(e=>e.source===W.Source.Camera);try{o=(yield Promise.all(r.map(e=>e.videoTrack?.setDeviceId(c)))).every(e=>e===!0)}catch(e){throw n.options.videoCaptureDefaults.deviceId=t,e}let i=r.some(e=>e.track?.isMuted??!1);o&&i&&(s=!0)}else if(e===`audiooutput`){if(s=!0,!Dl()&&!n.options.webAudioMix||n.options.webAudioMix&&n.audioContext&&!(`setSinkId`in n.audioContext))throw Error(`cannot switch audio output, the current browser does not support it`);n.options.webAudioMix&&(t=(yield Gu.getInstance().normalizeDeviceId(`audiooutput`,t))??``),(a=n.options).audioOutput??(a.audioOutput={});let r=n.getActiveDevice(e)??n.options.audioOutput.deviceId;n.options.audioOutput.deviceId=t;try{n.options.webAudioMix&&((i=n.audioContext)==null||i.setSinkId(t)),yield Promise.all(Array.from(n.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(e){throw n.options.audioOutput.deviceId=r,e}}return s&&(n.localParticipant.activeDeviceMap.set(e,t),n.emit(R.ActiveDeviceChanged,e,t)),o}()})}setupLocalParticipantEvents(){this.localParticipant.on(z.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(z.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(z.AttributesChanged,this.onLocalAttributesChanged).on(z.TrackMuted,this.onLocalTrackMuted).on(z.TrackUnmuted,this.onLocalTrackUnmuted).on(z.LocalTrackPublished,this.onLocalTrackPublished).on(z.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(z.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(z.MediaDevicesError,this.onMediaDevicesError).on(z.AudioStreamAcquired,this.startAudio).on(z.ChatMessage,this.onLocalChatMessageSent).on(z.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){let t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally(()=>t.close()):t?.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===q.Connecting||this.state===q.Reconnecting){let r=()=>{this.log.debug(`deferring on track for later`,{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(e=>e.id)}),this.onTrackAdded(e,t,n),i()},i=()=>{this.off(R.Reconnected,r),this.off(R.Connected,r),this.off(R.Disconnected,i)};this.once(R.Reconnected,r),this.once(R.Connected,r),this.once(R.Disconnected,i);return}if(this.state===q.Disconnected){this.log.warn(`skipping incoming track after Room disconnected`,this.logContext);return}if(e.readyState===`ended`){this.log.info(`skipping incoming track as it already ended`,this.logContext);return}let r=bl(t.id),i=r[0],a=r[1],o=e.id;if(a&&a.startsWith(`TR`)&&(o=a),i===this.localParticipant.sid){this.log.warn(`tried to create RemoteParticipant for local participant`,this.logContext);return}let s=Array.from(this.remoteParticipants.values()).find(e=>e.sid===i);if(!s){i.startsWith(`PA`)&&this.log.error(`Tried to add a track for a participant, that's not present. Sid: ${i}`,this.logContext);return}if(!o.startsWith(`TR`)){let e=this.engine.getTrackIdForReceiver(n);if(!e){this.log.error(`Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ${i}`,this.logContext);return}o=e}o.startsWith(`TR`)||this.log.warn(`Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ${i}, streamId: ${a}, trackId: ${o}`,Object.assign(Object.assign({},this.logContext),{remoteParticipantID:i,streamId:a,trackId:o}));let c;this.options.adaptiveStream&&(c=typeof this.options.adaptiveStream==`object`?this.options.adaptiveStream:{});let l=s.addSubscribedMediaTrack(e,o,t,n,c);l?.isEncrypted&&!this.e2eeManager&&this.emit(R.EncryptionError,Error(`Encrypted ${l.source} track received from participant ${s.sid}, but room does not have encryption enabled!`))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n,r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==q.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{e.unpublishTrack(t.trackSid)})}),this.localParticipant.trackPublications.forEach(t=>{var n,r,i;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?((n=t.track)==null||n.detach(),(r=t.track)==null||r.stop()):(i=t.track)==null||i.stopMonitor()}),this.localParticipant.off(z.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(z.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(z.AttributesChanged,this.onLocalAttributesChanged).off(z.TrackMuted,this.onLocalTrackMuted).off(z.TrackUnmuted,this.onLocalTrackUnmuted).off(z.LocalTrackPublished,this.onLocalTrackPublished).off(z.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(z.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(z.MediaDevicesError,this.onMediaDevicesError).off(z.AudioStreamAcquired,this.startAudio).off(z.ChatMessage,this.onLocalChatMessageSent).off(z.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix==`boolean`&&(this.audioContext.close(),this.audioContext=void 0),Ll()&&(window.removeEventListener(`beforeunload`,this.onPageLeave),window.removeEventListener(`pagehide`,this.onPageLeave),window.removeEventListener(`freeze`,this.onPageLeave),(r=(n=navigator.mediaDevices)?.removeEventListener)==null||r.call(n,`devicechange`,this.handleDeviceChange))}finally{this.setAndEmitConnectionState(q.Disconnected),this.emit(R.Disconnected,t)}}}handleParticipantDisconnected(e,t){var n;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(R.ParticipantDisconnected,t),t.setDisconnected(),(n=this.localParticipant)==null||n.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,n,r,i,a){return F(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),a!==1){yield this.engine.publishRpcResponse(e,t,null,Xd.builtIn(`UNSUPPORTED_VERSION`));return}let o=this.rpcHandlers.get(n);if(!o){yield this.engine.publishRpcResponse(e,t,null,Xd.builtIn(`UNSUPPORTED_METHOD`));return}let s=null,c=null;try{let a=yield o({requestId:t,callerIdentity:e,payload:r,responseTimeout:i});Qd(a)>Zd?(s=Xd.builtIn(`RESPONSE_PAYLOAD_TOO_LARGE`),this.log.warn(`RPC Response payload too large for ${n}`)):c=a}catch(e){e instanceof Xd?s=e:(this.log.warn(`Uncaught error returned by RPC handler for ${n}. Returning APPLICATION_ERROR instead.`,e),s=Xd.builtIn(`APPLICATION_ERROR`))}yield this.engine.publishRpcResponse(e,t,c,s)})}selectDefaultDevices(){return F(this,void 0,void 0,function*(){let e=Gu.getInstance().previousDevices,t=yield Gu.getInstance().getDevices(void 0,!1),n=Sc();if(n?.name===`Chrome`&&n.os!==`iOS`)for(let n of t){let t=e.find(e=>e.deviceId===n.deviceId);t&&t.label!==``&&t.kind===n.kind&&t.label!==n.label&&this.getActiveDevice(n.kind)===`default`&&this.emit(R.ActiveDeviceChanged,n.kind,n.deviceId)}for(let n of[`audiooutput`,`audioinput`,`videoinput`]){let r=nl(n),i=this.localParticipant.getTrackPublication(r);if(i&&i.track?.isUserProvided)continue;let a=t.filter(e=>e.kind===n),o=this.getActiveDevice(n);if(o===e.filter(e=>e.kind===n)[0]?.deviceId&&a.length>0&&a[0]?.deviceId!==o){yield this.switchActiveDevice(n,a[0].deviceId);continue}n===`audioinput`&&!Ml()||n===`videoinput`||a.length>0&&!a.find(e=>e.deviceId===this.getActiveDevice(n))&&(n!==`audiooutput`||!Ml())&&(yield this.switchActiveDevice(n,a[0].deviceId))}})}acquireAudioContext(){return F(this,void 0,void 0,function*(){if(typeof this.options.webAudioMix!=`boolean`&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state===`closed`)&&(this.audioContext=tl()??void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state===`suspended`)try{yield Promise.race([this.audioContext.resume(),xl(200)])}catch(e){this.log.warn(`Could not resume audio context`,Object.assign(Object.assign({},this.logContext),{error:e}))}let e=this.audioContext?.state===`running`;e!==this.canPlaybackAudio&&(this.audioEnabled=e,this.emit(R.AudioPlaybackStatusChanged,e))})}createParticipant(e,t){let n;return n=t?Am.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new Am(this.engine.client,``,e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),this.options.audioOutput?.deviceId&&n.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn(`Could not set audio output: ${e.message}`,this.logContext)),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){let n=this.remoteParticipants.get(e);return t&&n.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),n}let n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(R.ParticipantConnected,n),n.on(z.TrackPublished,e=>{this.emitWhenConnected(R.TrackPublished,e,n)}).on(z.TrackSubscribed,(e,t)=>{e.kind===W.Kind.Audio?(e.on(V.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(V.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===W.Kind.Video&&(e.on(V.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(V.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(R.TrackSubscribed,e,t,n)}).on(z.TrackUnpublished,e=>{this.emit(R.TrackUnpublished,e,n)}).on(z.TrackUnsubscribed,(e,t)=>{this.emit(R.TrackUnsubscribed,e,t,n)}).on(z.TrackMuted,e=>{this.emitWhenConnected(R.TrackMuted,e,n)}).on(z.TrackUnmuted,e=>{this.emitWhenConnected(R.TrackUnmuted,e,n)}).on(z.ParticipantMetadataChanged,e=>{this.emitWhenConnected(R.ParticipantMetadataChanged,e,n)}).on(z.ParticipantNameChanged,e=>{this.emitWhenConnected(R.ParticipantNameChanged,e,n)}).on(z.AttributesChanged,e=>{this.emitWhenConnected(R.ParticipantAttributesChanged,e,n)}).on(z.ConnectionQualityChanged,e=>{this.emitWhenConnected(R.ConnectionQualityChanged,e,n)}).on(z.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(R.ParticipantPermissionsChanged,e,n)}).on(z.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(R.TrackSubscriptionStatusChanged,e,t,n)}).on(z.TrackSubscriptionFailed,(e,t)=>{this.emit(R.TrackSubscriptionFailed,e,n,t)}).on(z.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(R.TrackSubscriptionPermissionChanged,e,t,n)}).on(z.Active,()=>{this.emitWhenConnected(R.ParticipantActive,n),n.kind===Wi.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){let e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications(),n=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,n)}updateSubscriptions(){for(let e of this.remoteParticipants.values())for(let t of e.videoTrackPublications.values())t.isSubscribed&&_u(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){let t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Bc.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn(`detected connection state mismatch`,Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Fi.STATE_MISMATCH))):e=0},jm)}clearConnectionReconcile(){this.connectionReconcileInterval&&Bc.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(R.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){var t=[...arguments].slice(1);if(this.state===q.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,t]);else if(this.state===q.Connected)return this.emit(e,...t);return!1}simulateParticipants(e){return F(this,void 0,void 0,function*(){let t=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),n=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new zi({sid:`RM_SIMULATED`,name:`simulated-room`,emptyTimeout:0,maxParticipants:0,creationTime:or.parse(new Date().getTime()),metadata:``,numParticipants:1,numPublishers:1,turnPassword:``,enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Hi({identity:`simulated-local`,name:`local-name`})),this.setupLocalParticipantEvents(),this.emit(R.SignalConnected),this.emit(R.Connected),this.setAndEmitConnectionState(q.Connected),t.video){let e=new ym(W.Kind.Video,new qi({source:ji.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Ai.AUDIO,name:`video-dummy`}),new kf(t.useRealTracks&&window.navigator.mediaDevices?.getUserMedia?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Ql(160*(n.aspectRatios[0]??1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(z.LocalTrackPublished,e)}if(t.audio){let e=new ym(W.Kind.Audio,new qi({source:ji.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Ai.AUDIO}),new uf(t.useRealTracks&&navigator.mediaDevices?.getUserMedia?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:eu(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(z.LocalTrackPublished,e)}for(let e=0;e<n.count-1;e+=1){let t=new Hi({sid:Math.floor(Math.random()*1e4).toString(),identity:`simulated-${e}`,state:Ui.ACTIVE,tracks:[],joinedAt:or.parse(Date.now())}),r=this.getOrCreateParticipant(t.identity,t);if(n.video){let i=Ql(160*(n.aspectRatios[e%n.aspectRatios.length]??1),160,!1,!0),a=new qi({source:ji.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Ai.AUDIO});r.addSubscribedMediaTrack(i,a.sid,new MediaStream([i]),new RTCRtpReceiver),t.tracks=[...t.tracks,a]}if(n.audio){let e=eu(),n=new qi({source:ji.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Ai.AUDIO});r.addSubscribedMediaTrack(e,n.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,n]}r.updateInfo(t)}})}emit(e){var t=[...arguments].slice(1);if(e!==R.ActiveSpeakersChanged&&e!==R.TranscriptionReceived){let n=Nm(t).filter(e=>e!==void 0);(e===R.TrackSubscribed||e===R.TrackUnsubscribed)&&this.log.trace(`subscribe trace: ${e}`,Object.assign(Object.assign({},this.logContext),{event:e,args:n})),this.log.debug(`room event ${e}`,Object.assign(Object.assign({},this.logContext),{event:e,args:n}))}return super.emit(e,...t)}};Mm.cleanupRegistry=typeof FinalizationRegistry<`u`&&new FinalizationRegistry(e=>{e()});function Nm(e){return e.map(e=>{if(e)return Array.isArray(e)?Nm(e):typeof e==`object`?`logContext`in e?e.logContext:void 0:e})}var Pm;(function(e){e[e.IDLE=0]=`IDLE`,e[e.RUNNING=1]=`RUNNING`,e[e.SKIPPED=2]=`SKIPPED`,e[e.SUCCESS=3]=`SUCCESS`,e[e.FAILED=4]=`FAILED`})(Pm||={}),ss.EventEmitter,ss.EventEmitter;function J(e,t,n){return(t=Im(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Fm(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Im(e){var t=Fm(e,`string`);return typeof t==`symbol`?t:t+``}new TextEncoder,new TextDecoder;var Lm=class extends Error{constructor(e,t){var n;super(e,t),J(this,`code`,`ERR_JOSE_GENERIC`),this.name=this.constructor.name,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}};J(Lm,`code`,`ERR_JOSE_GENERIC`),J(class extends Lm{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),J(this,`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),J(this,`claim`,void 0),J(this,`reason`,void 0),J(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}},`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),J(class extends Lm{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),J(this,`code`,`ERR_JWT_EXPIRED`),J(this,`claim`,void 0),J(this,`reason`,void 0),J(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}},`code`,`ERR_JWT_EXPIRED`),J(class extends Lm{constructor(){super(...arguments),J(this,`code`,`ERR_JOSE_ALG_NOT_ALLOWED`)}},`code`,`ERR_JOSE_ALG_NOT_ALLOWED`),J(class extends Lm{constructor(){super(...arguments),J(this,`code`,`ERR_JOSE_NOT_SUPPORTED`)}},`code`,`ERR_JOSE_NOT_SUPPORTED`),J(class extends Lm{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`decryption operation failed`,t=arguments.length>1?arguments[1]:void 0;super(e,t),J(this,`code`,`ERR_JWE_DECRYPTION_FAILED`)}},`code`,`ERR_JWE_DECRYPTION_FAILED`),J(class extends Lm{constructor(){super(...arguments),J(this,`code`,`ERR_JWE_INVALID`)}},`code`,`ERR_JWE_INVALID`),J(class extends Lm{constructor(){super(...arguments),J(this,`code`,`ERR_JWS_INVALID`)}},`code`,`ERR_JWS_INVALID`),J(class extends Lm{constructor(){super(...arguments),J(this,`code`,`ERR_JWT_INVALID`)}},`code`,`ERR_JWT_INVALID`),J(class extends Lm{constructor(){super(...arguments),J(this,`code`,`ERR_JWK_INVALID`)}},`code`,`ERR_JWK_INVALID`),J(class extends Lm{constructor(){super(...arguments),J(this,`code`,`ERR_JWKS_INVALID`)}},`code`,`ERR_JWKS_INVALID`),J(class extends Lm{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`no applicable key found in the JSON Web Key Set`,t=arguments.length>1?arguments[1]:void 0;super(e,t),J(this,`code`,`ERR_JWKS_NO_MATCHING_KEY`)}},`code`,`ERR_JWKS_NO_MATCHING_KEY`),J(class extends Lm{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`multiple matching keys found in the JSON Web Key Set`,t=arguments.length>1?arguments[1]:void 0;super(e,t),J(this,Symbol.asyncIterator,void 0),J(this,`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`)}},`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`),J(class extends Lm{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`request timed out`,t=arguments.length>1?arguments[1]:void 0;super(e,t),J(this,`code`,`ERR_JWKS_TIMEOUT`)}},`code`,`ERR_JWKS_TIMEOUT`),J(class extends Lm{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`signature verification failed`,t=arguments.length>1?arguments[1]:void 0;super(e,t),J(this,`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`)}},`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`);function Rm(){return Rm=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Rm.apply(null,arguments)}var zm=new Uint8Array,Bm=class{static getFullOptions(e){return Rm({clientTools:{},onConnect:()=>{},onDebug:()=>{},onDisconnect:()=>{},onError:()=>{},onMessage:()=>{},onAudio:()=>{},onModeChange:()=>{},onStatusChange:()=>{},onCanSendFeedbackChange:()=>{},onInterruption:()=>{}},e)}constructor(e,t){var n=this;this.options=void 0,this.connection=void 0,this.lastInterruptTimestamp=0,this.mode=`listening`,this.status=`connecting`,this.volume=1,this.currentEventId=1,this.lastFeedbackEventId=0,this.canSendFeedback=!1,this.endSessionWithDetails=async function(e){n.status!==`connected`&&n.status!==`connecting`||(n.updateStatus(`disconnecting`),await n.handleEndSession(),n.updateStatus(`disconnected`),n.options.onDisconnect&&n.options.onDisconnect(e))},this.onMessage=async function(e){switch(e.type){case`interruption`:n.handleInterruption(e);return;case`agent_response`:n.handleAgentResponse(e);return;case`user_transcript`:n.handleUserTranscript(e);return;case`internal_tentative_agent_response`:n.handleTentativeAgentResponse(e);return;case`client_tool_call`:try{await n.handleClientToolCall(e)}catch(t){n.onError(`Unexpected error in client tool call handling: ${t instanceof Error?t.message:String(t)}`,{clientToolName:e.client_tool_call.tool_name,toolCallId:e.client_tool_call.tool_call_id})}return;case`audio`:n.handleAudio(e);return;case`vad_score`:n.handleVadScore(e);return;case`ping`:n.connection.sendMessage({type:`pong`,event_id:e.ping_event.event_id});return;case`mcp_tool_call`:n.handleMCPToolCall(e);return;case`mcp_connection_status`:n.handleMCPConnectionStatus(e);return;case`agent_tool_request`:n.handleAgentToolRequest(e);return;case`agent_tool_response`:n.handleAgentToolResponse(e);return;case`conversation_initiation_metadata`:n.handleConversationMetadata(e);return;case`asr_initiation_metadata`:n.handleAsrInitiationMetadata(e);return;case`agent_chat_response_part`:n.handleAgentChatResponsePart(e);return;case`error`:n.handleErrorEvent(e);return;default:n.options.onDebug&&n.options.onDebug(e);return}},this.setVolume=({volume:e})=>{this.volume=e},this.options=e,this.connection=t,this.options.onConnect&&this.options.onConnect({conversationId:t.conversationId}),this.connection.onMessage(this.onMessage),this.connection.onDisconnect(this.endSessionWithDetails),this.connection.onModeChange(e=>this.updateMode(e)),this.updateStatus(`connected`)}endSession(){return this.endSessionWithDetails({reason:`user`})}async handleEndSession(){this.connection.close()}updateMode(e){e!==this.mode&&(this.mode=e,this.options.onModeChange&&this.options.onModeChange({mode:e}))}updateStatus(e){e!==this.status&&(this.status=e,this.options.onStatusChange&&this.options.onStatusChange({status:e}))}updateCanSendFeedback(){let e=this.currentEventId!==this.lastFeedbackEventId;this.canSendFeedback!==e&&(this.canSendFeedback=e,this.options.onCanSendFeedbackChange&&this.options.onCanSendFeedbackChange({canSendFeedback:e}))}handleInterruption(e){e.interruption_event&&(this.lastInterruptTimestamp=e.interruption_event.event_id,this.options.onInterruption&&this.options.onInterruption({event_id:e.interruption_event.event_id}))}handleAgentResponse(e){this.options.onMessage&&this.options.onMessage({source:`ai`,role:`agent`,message:e.agent_response_event.agent_response})}handleUserTranscript(e){this.options.onMessage&&this.options.onMessage({source:`user`,role:`user`,message:e.user_transcription_event.user_transcript})}handleTentativeAgentResponse(e){this.options.onDebug&&this.options.onDebug({type:`tentative_agent_response`,response:e.tentative_agent_response_internal_event.tentative_agent_response})}handleVadScore(e){this.options.onVadScore&&this.options.onVadScore({vadScore:e.vad_score_event.vad_score})}async handleClientToolCall(e){if(Object.prototype.hasOwnProperty.call(this.options.clientTools,e.client_tool_call.tool_name))try{let t=await this.options.clientTools[e.client_tool_call.tool_name](e.client_tool_call.parameters)??`Client tool execution successful.`,n=typeof t==`object`?JSON.stringify(t):String(t);this.connection.sendMessage({type:`client_tool_result`,tool_call_id:e.client_tool_call.tool_call_id,result:n,is_error:!1})}catch(t){this.onError(`Client tool execution failed with following error: ${t?.message}`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:`client_tool_result`,tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool execution failed: ${t?.message}`,is_error:!0})}else{if(this.options.onUnhandledClientToolCall)return void this.options.onUnhandledClientToolCall(e.client_tool_call);this.onError(`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:`client_tool_result`,tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,is_error:!0})}}handleAudio(e){}handleMCPToolCall(e){this.options.onMCPToolCall&&this.options.onMCPToolCall(e.mcp_tool_call)}handleMCPConnectionStatus(e){this.options.onMCPConnectionStatus&&this.options.onMCPConnectionStatus(e.mcp_connection_status)}handleAgentToolRequest(e){this.options.onAgentToolRequest&&this.options.onAgentToolRequest(e.agent_tool_request)}handleAgentToolResponse(e){e.agent_tool_response.tool_name===`end_call`&&this.endSessionWithDetails({reason:`agent`,context:new CloseEvent(`end_call`,{reason:`Agent ended the call`})}),this.options.onAgentToolResponse&&this.options.onAgentToolResponse(e.agent_tool_response)}handleConversationMetadata(e){this.options.onConversationMetadata&&this.options.onConversationMetadata(e.conversation_initiation_metadata_event)}handleAsrInitiationMetadata(e){this.options.onAsrInitiationMetadata&&this.options.onAsrInitiationMetadata(e.asr_initiation_metadata_event)}handleAgentChatResponsePart(e){this.options.onAgentChatResponsePart&&this.options.onAgentChatResponsePart(e.text_response_part)}handleErrorEvent(e){let t=e.error_event.error_type,n=e.error_event.message||e.error_event.reason||`Unknown error`;t===`max_duration_exceeded`?this.endSessionWithDetails({reason:`error`,message:n,context:new Event(`max_duration_exceeded`)}):this.onError(`Server error: ${n}`,{errorType:t,code:e.error_event.code,debugMessage:e.error_event.debug_message,details:e.error_event.details})}onError(e,t){console.error(e,t),this.options.onError&&this.options.onError(e,t)}getId(){return this.connection.conversationId}isOpen(){return this.status===`connected`}setMicMuted(e){this.connection.setMicMuted(e)}getInputByteFrequencyData(){return zm}getOutputByteFrequencyData(){return zm}getInputVolume(){return 0}getOutputVolume(){return 0}sendFeedback(e){this.canSendFeedback?(this.connection.sendMessage({type:`feedback`,score:e?`like`:`dislike`,event_id:this.currentEventId}),this.lastFeedbackEventId=this.currentEventId,this.updateCanSendFeedback()):console.warn(this.lastFeedbackEventId===0?`Cannot send feedback: the conversation has not started yet.`:`Cannot send feedback: feedback has already been sent for the current response.`)}sendContextualUpdate(e){this.connection.sendMessage({type:`contextual_update`,text:e})}sendUserMessage(e){this.connection.sendMessage({type:`user_message`,text:e})}sendUserActivity(){this.connection.sendMessage({type:`user_activity`})}sendMCPToolApprovalResult(e,t){this.connection.sendMessage({type:`mcp_tool_approval_result`,tool_call_id:e,is_approved:t})}},Vm=class{constructor(e={}){this.queue=[],this.disconnectionDetails=null,this.onDisconnectCallback=null,this.onMessageCallback=null,this.onModeChangeCallback=null,this.onDebug=void 0,this.onDebug=e.onDebug}debug(e){this.onDebug&&this.onDebug(e)}onMessage(e){this.onMessageCallback=e;let t=this.queue;this.queue=[],t.length>0&&queueMicrotask(()=>{t.forEach(e)})}onDisconnect(e){this.onDisconnectCallback=e;let t=this.disconnectionDetails;t&&queueMicrotask(()=>{e(t)})}onModeChange(e){this.onModeChangeCallback=e}updateMode(e){var t;(t=this.onModeChangeCallback)==null||t.call(this,e)}disconnect(e){var t;this.disconnectionDetails||(this.disconnectionDetails=e,(t=this.onDisconnectCallback)==null||t.call(this,e))}handleMessage(e){this.onMessageCallback?this.onMessageCallback(e):this.queue.push(e)}};function Hm(e){let[t,n]=e.split(`_`);if(![`pcm`,`ulaw`].includes(t))throw Error(`Invalid format: ${e}`);let r=Number.parseInt(n);if(Number.isNaN(r))throw Error(`Invalid sample rate: ${n}`);return{format:t,sampleRate:r}}var Um=`0.12.2`;function Wm(e){return!!e.type}var Gm=`conversation_initiation_client_data`;function Km(e){var t;let n={type:Gm};return e.overrides&&(n.conversation_config_override={agent:{prompt:e.overrides.agent?.prompt,first_message:e.overrides.agent?.firstMessage,language:e.overrides.agent?.language},tts:{voice_id:e.overrides.tts?.voiceId,speed:e.overrides.tts?.speed},conversation:{text_only:e.overrides.conversation?.textOnly}}),e.customLlmExtraBody&&(n.custom_llm_extra_body=e.customLlmExtraBody),e.dynamicVariables&&(n.dynamic_variables=e.dynamicVariables),e.userId&&(n.user_id=e.userId),(t=e.overrides)!=null&&t.client&&(n.source_info={source:e.overrides.client.source,version:e.overrides.client.version}),n}var qm=class e extends Vm{constructor(e,t,n,r){super(),this.socket=void 0,this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.socket=e,this.conversationId=t,this.inputFormat=n,this.outputFormat=r,this.socket.addEventListener(`error`,e=>{setTimeout(()=>this.disconnect({reason:`error`,message:`The connection was closed due to a socket error.`,context:e}),0)}),this.socket.addEventListener(`close`,e=>{this.disconnect(e.code===1e3?{reason:`agent`,context:e}:{reason:`error`,message:e.reason||`The connection was closed by the server.`,context:e})}),this.socket.addEventListener(`message`,e=>{try{let t=JSON.parse(e.data);if(!Wm(t))return void this.debug({type:`invalid_event`,message:`Received invalid socket event`,data:e.data});this.handleMessage(t)}catch(t){this.debug({type:`parsing_error`,message:`Failed to parse socket message`,error:t instanceof Error?t.message:String(t),data:e.data})}})}static async create(t){let n=null;try{var r,i;let a=t.origin??`wss://api.elevenlabs.io`,o,s=((r=t.overrides)==null||(r=r.client)==null?void 0:r.version)||Um,c=((i=t.overrides)==null||(i=i.client)==null?void 0:i.source)||`js_sdk`;if(t.signedUrl){let e=t.signedUrl.includes(`?`)?`&`:`?`;o=`${t.signedUrl}${e}source=${c}&version=${s}`}else o=`${a}/v1/convai/conversation?agent_id=${t.agentId}&source=${c}&version=${s}`;let l=[`convai`];t.authorization&&l.push(`bearer.${t.authorization}`),n=new WebSocket(o,l);let{conversation_id:u,agent_output_audio_format:d,user_input_audio_format:f}=await new Promise((e,r)=>{n.addEventListener(`open`,()=>{var e;let r=Km(t);(e=n)==null||e.send(JSON.stringify(r))},{once:!0}),n.addEventListener(`error`,e=>{setTimeout(()=>r(e),0)}),n.addEventListener(`close`,r),n.addEventListener(`message`,t=>{let n=JSON.parse(t.data);Wm(n)&&(n.type===`conversation_initiation_metadata`?e(n.conversation_initiation_metadata_event):console.warn(`First received message is not conversation metadata.`))},{once:!0})}),p=Hm(f??`pcm_16000`),m=Hm(d);return new e(n,u,p,m)}catch(e){var a;throw(a=n)==null||a.close(),e}}close(){this.socket.close(1e3,`User ended conversation`)}sendMessage(e){this.socket.send(JSON.stringify(e))}async setMicMuted(e){console.warn(`WebSocket connection setMicMuted called with ${e}, but this is handled by VoiceConversation`)}};function Jm(e){let t=new Uint8Array(e);return window.btoa(String.fromCharCode(...t))}function Ym(e){let t=window.atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return r.buffer}var Xm=new Map;function Zm(e,t){return async(n,r)=>{let i=Xm.get(e);if(i)return n.addModule(i);if(r)try{await n.addModule(r),Xm.set(e,r);return}catch(t){throw Error(`Failed to load the ${e} worklet module from path: ${r}. Error: ${t}`)}let a=new Blob([t],{type:`application/javascript`}),o=URL.createObjectURL(a);try{await n.addModule(o),Xm.set(e,o);return}catch{URL.revokeObjectURL(o)}try{let r=`data:application/javascript;base64,${btoa(t)}`;await n.addModule(r),Xm.set(e,r)}catch{throw Error(`Failed to load the ${e} worklet module. Make sure the browser supports AudioWorklets. If you are using a strict CSP, you may need to self-host the worklet files.`)}}}var Qm=Zm(`rawAudioProcessor`,`/*
|
|
62
|
+
`},SC}var TC;function EC(){if(TC)return hC;TC=1;var e=xC(),t=wC();return hC.grammar=yC(),hC.write=t,hC.parse=e.parse,hC.parseParams=e.parseParams,hC.parseFmtpConfig=e.parseFmtpConfig,hC.parsePayloads=e.parsePayloads,hC.parseRemoteCandidates=e.parseRemoteCandidates,hC.parseImageAttributes=e.parseImageAttributes,hC.parseSimulcastStreamList=e.parseSimulcastStreamList,hC}var DC=EC();function OC(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:50,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r,i=n.isImmediate??!1,a=n.callback??!1,o=n.maxWait,s=Date.now(),c=[];function l(){if(o!==void 0){let e=Date.now()-s;if(e+t>=o)return o-e}return t}let u=function(){for(var t=arguments.length,n=Array(t),o=0;o<t;o++)n[o]=arguments[o];let u=this;return new Promise((t,o)=>{let d=function(){if(r=void 0,s=Date.now(),!i){let t=e.apply(u,n);a&&a(t),c.forEach(e=>{let{resolve:n}=e;return n(t)}),c=[]}},f=i&&r===void 0;if(r!==void 0&&Rb.clearTimeout(r),r=Rb.setTimeout(d,l()),f){let r=e.apply(u,n);return a&&a(r),t(r)}c.push({resolve:t,reject:o})})};return u.cancel=function(e){r!==void 0&&Rb.clearTimeout(r),c.forEach(t=>{let{reject:n}=t;return n(e)}),c=[]},u}var kC=.7,AC=20,jC={NegotiationStarted:`negotiationStarted`,NegotiationComplete:`negotiationComplete`,RTPVideoPayloadTypes:`rtpVideoPayloadTypes`},MC=class extends iy.EventEmitter{get pc(){return this._pc||=this.createPC(),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),this.log=R,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=OC(e=>z(this,void 0,void 0,function*(){this.emit(jC.NegotiationStarted);try{yield this.createAndSendOffer()}catch(t){if(e)e(t);else throw t}}),AC),this.close=()=>{this._pc&&=(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,null)},this.log=Wv(t.loggerName??Uv.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new Dm}createPC(){let e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&((t=this.onIceCandidate)==null||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;(t=this.onIceCandidateError)==null||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)==null||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)==null||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)==null||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;(t=this.onDataChannel)==null||t.call(this,e)},e.ontrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)},e}get logContext(){var e;return Object.assign({},(e=this.loggerOptions).loggerContextCb?.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState===`connected`||this.pc.iceConnectionState===`completed`)}addIceCandidate(e){return z(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return z(this,void 0,void 0,function*(){if(e.type===`answer`&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn(`ignoring answer for old offer`,Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let n;if(e.type===`offer`){let{stereoMids:t,nackMids:n}=PC(e);this.remoteStereoMids=t,this.remoteNackMids=n}else if(e.type===`answer`){if(this.pendingInitialOffer){let e=this.pendingInitialOffer;this.pendingInitialOffer=void 0;let t=DC.parse(e.sdp??``);t.media.forEach(e=>{FC(e)}),this.log.debug(`setting pending initial offer before processing answer`,this.logContext),yield this.setMungedSDP(e,DC.write(t))}let t=DC.parse(e.sdp??``);t.media.forEach(e=>{let t=IC(e.mid);e.type===`audio`&&this.trackBitrates.some(n=>{if(!n.transceiver||t!=n.transceiver.mid)return!1;let r=0;if(e.rtp.some(e=>e.codec.toUpperCase()===n.codec.toUpperCase()?(r=e.payload,!0):!1),r===0)return!0;let i=!1;for(let t of e.fmtp)if(t.payload===r){t.config=t.config.split(`;`).filter(e=>!e.includes(`maxaveragebitrate`)).join(`;`),n.maxbr>0&&(t.config+=`;maxaveragebitrate=${n.maxbr*1e3}`),i=!0;break}return i||n.maxbr>0&&e.fmtp.push({payload:r,config:`maxaveragebitrate=${n.maxbr*1e3}`}),!0})}),n=DC.write(t)}return yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach(e=>{this.pc.addIceCandidate(e)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type===`answer`&&(this.emit(jC.NegotiationComplete),e.sdp&&DC.parse(e.sdp).media.forEach(e=>{e.type===`video`&&this.emit(jC.RTPVideoPayloadTypes,e.rtp)})),!0})}createInitialOffer(){return z(this,void 0,void 0,function*(){let e=yield this.offerLock.lock();try{if(this.pc.signalingState!==`stable`){this.log.warn(`signaling state is not stable, cannot create initial offer`,this.logContext);return}let e=this.latestOfferId+1;this.latestOfferId=e;let t=yield this.pc.createOffer();this.pendingInitialOffer={sdp:t.sdp,type:t.type};let n=DC.parse(t.sdp??``);return n.media.forEach(e=>{FC(e)}),t.sdp=DC.write(n),{offer:t,offerId:e}}finally{e()}})}createAndSendOffer(e){return z(this,void 0,void 0,function*(){let t=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.log.debug(`restarting ICE`,this.logContext),this.restartingIce=!0),this._pc&&(this._pc.signalingState===`have-local-offer`||this.pendingInitialOffer)){let t=this._pc.remoteDescription;if(e?.iceRestart&&t)yield this._pc.setRemoteDescription(t);else{this.renegotiate=!0,this.log.debug(`requesting renegotiation`,Object.assign({},this.logContext));return}}else if(!this._pc||this._pc.signalingState===`closed`){this.log.warn(`could not createOffer with closed peer connection`,this.logContext);return}this.log.debug(`starting to negotiate`,this.logContext);let t=this.latestOfferId+1;this.latestOfferId=t;let n=yield this.pc.createOffer(e);this.log.debug(`original offer`,Object.assign({sdp:n.sdp},this.logContext));let r=DC.parse(n.sdp??``);if(r.media.forEach(e=>{FC(e),e.type===`audio`?NC(e,[`all`],[]):e.type===`video`&&this.trackBitrates.some(t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let n=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()?(n=e.payload,!0):!1),n===0||(wx(t.codec)&&!kx()&&this.ensureVideoDDExtensionForSVC(e,r),!wx(t.codec)))return!0;let i=Math.round(t.maxbr*kC);for(let t of e.fmtp)if(t.payload===n){t.config.includes(`x-google-start-bitrate`)||(t.config+=`;x-google-start-bitrate=${i}`);break}return!0})}),this.latestOfferId>t){this.log.warn(`latestOfferId mismatch`,Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:t}));return}yield this.setMungedSDP(n,DC.write(r)),this.onOffer(n,this.latestOfferId)}finally{t()}})}createAndSetAnswer(){return z(this,void 0,void 0,function*(){let e=yield this.pc.createAnswer(),t=DC.parse(e.sdp??``);return t.media.forEach(e=>{FC(e),e.type===`audio`&&NC(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(e,DC.write(t)),e})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new Ab(`PC closed, cannot add track`);return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){if(!this._pc)throw new Ab(`PC closed, cannot configure`);return this._pc?.setConfiguration(e)}canRemoveTrack(){return!!this._pc?.removeTrack}removeTrack(e){return this._pc?.removeTrack(e)}getConnectionState(){return this._pc?.connectionState??`closed`}getICEConnectionState(){return this._pc?.iceConnectionState??`closed`}getSignallingState(){return this._pc?.signalingState??`closed`}getTransceivers(){return this._pc?.getTransceivers()??[]}getSenders(){return this._pc?.getSenders()??[]}getLocalDescription(){return this._pc?.localDescription}getRemoteDescription(){return this.pc?.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return z(this,void 0,void 0,function*(){if(!this._pc)return;let e=``,t=new Map,n=new Map;if((yield this._pc.getStats()).forEach(r=>{switch(r.type){case`transport`:e=r.selectedCandidatePairId;break;case`candidate-pair`:e===``&&r.selected&&(e=r.id),t.set(r.id,r);break;case`remote-candidate`:n.set(r.id,`${r.address}:${r.port}`);break}}),e===``)return;let r=t.get(e)?.remoteCandidateId;if(r!==void 0)return n.get(r)})}setMungedSDP(e,t,n){return z(this,void 0,void 0,function*(){if(t){let r=e.sdp;e.sdp=t;try{this.log.debug(`setting munged ${n?`remote`:`local`} description`,this.logContext),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(n){this.log.warn(`not able to set ${e.type}, falling back to unmodified sdp`,Object.assign(Object.assign({},this.logContext),{error:n,sdp:t})),e.sdp=r}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(t){let r=`unknown error`;t instanceof Error?r=t.message:typeof t==`string`&&(r=t);let i={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(i.remoteSdp=this.pc.remoteDescription),this.log.error(`unable to set ${e.type}`,Object.assign(Object.assign({},this.logContext),{fields:i})),new jb(r)}})}ensureVideoDDExtensionForSVC(e,t){var n;if(!e.ext?.some(e=>e.uri===_x)){if(this.ddExtID===0){let e=0;t.media.forEach(t=>{var n;t.type===`video`&&((n=t.ext)==null||n.forEach(t=>{t.value>e&&(e=t.value)}))}),this.ddExtID=e+1}(n=e.ext)==null||n.push({value:this.ddExtID,uri:_x})}}};function NC(e,t,n){let r=IC(e.mid),i=0;e.rtp.some(e=>e.codec===`opus`?(i=e.payload,!0):!1),i>0&&(e.rtcpFb||=[],n.includes(r)&&!e.rtcpFb.some(e=>e.payload===i&&e.type===`nack`)&&e.rtcpFb.push({payload:i,type:`nack`}),(t.includes(r)||t.length===1&&t[0]===`all`)&&e.fmtp.some(e=>e.payload===i?(e.config.includes(`stereo=1`)||(e.config+=`;stereo=1`),!0):!1))}function PC(e){let t=[],n=[],r=DC.parse(e.sdp??``),i=0;return r.media.forEach(e=>{let r=IC(e.mid);e.type===`audio`&&(e.rtp.some(e=>e.codec===`opus`?(i=e.payload,!0):!1),e.rtcpFb?.some(e=>e.payload===i&&e.type===`nack`)&&n.push(r),e.fmtp.some(e=>e.payload===i?(e.config.includes(`sprop-stereo=1`)&&t.push(r),!0):!1))}),{stereoMids:t,nackMids:n}}function FC(e){if(e.connection){let t=e.connection.ip.indexOf(`:`)>=0;(e.connection.version===4&&t||e.connection.version===6&&!t)&&(e.connection.ip=`0.0.0.0`,e.connection.version=4)}}function IC(e){return typeof e==`number`?e.toFixed(0):e}var LC=`vp8`,RC={audioPreset:Gb.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Jb.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:LC,backupCodec:!0,preConnectBuffer:!1},zC={deviceId:{ideal:`default`},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},BC={deviceId:{ideal:`default`},resolution:Kb.h720.resolution},VC={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Jv,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},HC={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3},UC;(function(e){e[e.NEW=0]=`NEW`,e[e.CONNECTING=1]=`CONNECTING`,e[e.CONNECTED=2]=`CONNECTED`,e[e.FAILED=3]=`FAILED`,e[e.CLOSING=4]=`CLOSING`,e[e.CLOSED=5]=`CLOSED`})(UC||={});var WC=class{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,n){this.peerConnectionTimeout=HC.peerConnectionTimeout,this.log=R,this.updateState=()=>{var e;let t=this.state,n=this.requiredTransports.map(e=>e.getConnectionState());n.every(e=>e===`connected`)?this.state=UC.CONNECTED:n.some(e=>e===`failed`)?this.state=UC.FAILED:n.some(e=>e===`connecting`)?this.state=UC.CONNECTING:n.every(e=>e===`closed`)?this.state=UC.CLOSED:n.some(e=>e===`closed`)?this.state=UC.CLOSING:n.every(e=>e===`new`)&&(this.state=UC.NEW),t!==this.state&&(this.log.debug(`pc state change: from ${UC[t]} to ${UC[this.state]}`,this.logContext),(e=this.onStateChange)==null||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber?.getConnectionState()))},this.log=Wv(t.loggerName??Uv.PCManager),this.loggerOptions=t,this.isPublisherConnectionRequired=e!==`subscriber-primary`,this.isSubscriberConnectionRequired=e===`subscriber-primary`,this.publisher=new MC(n,t),this._mode=e,e!==`publisher-only`&&(this.subscriber=new MC(n,t),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=e=>{var t;(t=this.onIceCandidate)==null||t.call(this,e,D_.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;(t=this.onDataChannel)==null||t.call(this,e)},this.subscriber.onTrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;(t=this.onIceCandidate)==null||t.call(this,e,D_.PUBLISHER)},this.publisher.onTrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var n;(n=this.onPublisherOffer)==null||n.call(this,e,t)},this.state=UC.NEW,this.connectionLock=new Dm,this.remoteOfferLock=new Dm}get logContext(){var e;return Object.assign({},(e=this.loggerOptions).loggerContextCb?.call(e))}requirePublisher(){this.isPublisherConnectionRequired=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return z(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!==`closed`){let e=this.publisher;for(let t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn(`could not removeTrack`,Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),this.subscriber?.close()]),this.updateState()})}triggerIceRestart(){return z(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return z(this,void 0,void 0,function*(){t===D_.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber?.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return z(this,void 0,void 0,function*(){this.log.debug(`received server offer`,Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber?.getSignallingState().toString()}));let n=yield this.remoteOfferLock.lock();try{return(yield this.subscriber?.setRemoteDescription(e,t))?yield this.subscriber?.createAndSetAnswer():void 0}finally{n()}})}updateConfiguration(e,t){var n;this.publisher.setConfiguration(e),(n=this.subscriber)==null||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return z(this,void 0,void 0,function*(){let n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!==`connected`&&this.publisher.getConnectionState()!==`connecting`&&(this.log.debug(`negotiation required, start negotiating`,this.logContext),this.publisher.negotiate()),yield Promise.all(this.requiredTransports?.map(n=>this.ensureTransportConnected(n,e,t)))}finally{n()}})}negotiate(e){return z(this,void 0,void 0,function*(){return new gb((t,n)=>z(this,void 0,void 0,function*(){let r=setTimeout(()=>{n(new jb(`negotiation timed out`))},this.peerConnectionTimeout),i=()=>{clearTimeout(r),this.publisher.off(jC.NegotiationStarted,o),e.signal.removeEventListener(`abort`,a)},a=()=>{i(),n(new jb(`negotiation aborted`))},o=()=>{e.signal.aborted||(clearTimeout(r),r=setTimeout(()=>{i(),n(new jb(`negotiation timed out`))},this.peerConnectionTimeout))};e.signal.addEventListener(`abort`,a),this.publisher.on(jC.NegotiationStarted,o),this.publisher.once(jC.NegotiationComplete,()=>{i(),t()}),yield this.publisher.negotiate(e=>{i(),e instanceof Error?n(e):n(Error(String(e)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){return(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(t=>t.receiver===e)?.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===D_.PUBLISHER||e===D_.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){let e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return z(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(e.getConnectionState()!==`connected`)return new Promise((e,i)=>z(n,void 0,void 0,function*(){let n=()=>{this.log.warn(`abort transport connection`,this.logContext),Rb.clearTimeout(a),i(B.cancelled(`room connection has been cancelled`))};t?.signal.aborted&&n(),t?.signal.addEventListener(`abort`,n);let a=Rb.setTimeout(()=>{t?.signal.removeEventListener(`abort`,n),i(B.internal(`could not establish pc connection`))},r);for(;this.state!==UC.CONNECTED;)if(yield yx(50),t?.signal.aborted){i(B.cancelled(`room connection has been cancelled`));return}Rb.clearTimeout(a),t?.signal.removeEventListener(`abort`,n),e()}))}()})}},GC=5e3,KC=3e4,qC=class e{static fetchRegionSettings(t,n,r){return z(this,void 0,void 0,function*(){let i=yield e.fetchLock.lock();try{let e=yield fetch(`${JC(t)}/regions`,{headers:{authorization:`Bearer ${n}`},signal:r});if(e.ok){let t=yS(e.headers),n=t?t*1e3:GC;return{regionSettings:yield e.json(),updatedAtInMs:Date.now(),maxAgeInMs:n}}else if(e.status===401)throw B.notAllowed(`Could not fetch region settings: ${e.statusText}`,e.status);else throw B.internal(`Could not fetch region settings: ${e.statusText}`)}catch(e){throw e instanceof B?e:r?.aborted?B.cancelled(`Region fetching was aborted`):B.serverUnreachable(`Could not fetch region settings, ${e instanceof Error?`${e.name}: ${e.message}`:e}`)}finally{i()}})}static scheduleRefetch(t,n,r){return z(this,void 0,void 0,function*(){let i=e.settingsTimeouts.get(t.hostname);clearTimeout(i),e.settingsTimeouts.set(t.hostname,setTimeout(()=>z(this,void 0,void 0,function*(){try{let r=yield e.fetchRegionSettings(t,n);e.updateCachedRegionSettings(t,n,r)}catch(i){if(i instanceof B&&i.reason===Eb.NotAllowed){R.debug(`token is not valid, cancelling auto region refresh`);return}R.debug(`auto refetching of region settings failed`,{error:i}),e.scheduleRefetch(t,n,r)}}),r))})}static updateCachedRegionSettings(t,n,r){e.cache.set(t.hostname,r),e.scheduleRefetch(t,n,r.maxAgeInMs)}static stopRefetch(t){let n=e.settingsTimeouts.get(t);n&&(clearTimeout(n),e.settingsTimeouts.delete(t))}static scheduleCleanup(t){let n=e.connectionTrackers.get(t);n&&(n.cleanupTimeout&&clearTimeout(n.cleanupTimeout),n.cleanupTimeout=setTimeout(()=>{let n=e.connectionTrackers.get(t);n&&n.connectionCount===0&&(R.debug(`stopping region refetch after disconnect delay`,{hostname:t}),e.stopRefetch(t)),n&&(n.cleanupTimeout=void 0)},KC))}static cancelCleanup(t){let n=e.connectionTrackers.get(t);n?.cleanupTimeout&&(clearTimeout(n.cleanupTimeout),n.cleanupTimeout=void 0)}notifyConnected(){let t=this.serverUrl.hostname,n=e.connectionTrackers.get(t);n||(n={connectionCount:0},e.connectionTrackers.set(t,n)),n.connectionCount++,e.cancelCleanup(t)}notifyDisconnected(){let t=this.serverUrl.hostname,n=e.connectionTrackers.get(t);n&&(n.connectionCount=Math.max(0,n.connectionCount-1),n.connectionCount===0&&e.scheduleCleanup(t))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Lx(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(t){return z(this,void 0,void 0,function*(){return e.fetchRegionSettings(this.serverUrl,this.token,t)})}getNextBestRegionUrl(t){return z(this,void 0,void 0,function*(){if(!this.isCloud())throw Error(`region availability is only supported for LiveKit Cloud domains`);let n=e.cache.get(this.serverUrl.hostname);(!n||Date.now()-n.updatedAtInMs>n.maxAgeInMs)&&(n=yield this.fetchRegionSettings(t),e.updateCachedRegionSettings(this.serverUrl,this.token,n));let r=n.regionSettings.regions.filter(e=>!this.attemptedRegions.find(t=>t.url===e.url));if(r.length>0){let e=r[0];return this.attemptedRegions.push(e),R.debug(`next region: ${e.region}`),e.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(t){e.updateCachedRegionSettings(this.serverUrl,this.token,t)}};qC.cache=new Map,qC.settingsTimeouts=new Map,qC.connectionTrackers=new Map,qC.fetchLock=new Dm;function JC(e){return`${e.protocol.replace(`ws`,`http`)}//${e.host}/settings`}var YC=class e extends Error{constructor(t,n,r){super(n),this.code=t,this.message=QC(n,e.MAX_MESSAGE_BYTES),this.data=r?QC(r,e.MAX_DATA_BYTES):void 0}static fromProto(t){return new e(t.code,t.message,t.data)}toProto(){return new u_({code:this.code,message:this.message,data:this.data})}static builtIn(t,n){return new e(e.ErrorCode[t],e.ErrorMessage[t],n)}};YC.MAX_MESSAGE_BYTES=256,YC.MAX_DATA_BYTES=15360,YC.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},YC.ErrorMessage={APPLICATION_ERROR:`Application error in method handler`,CONNECTION_TIMEOUT:`Connection timeout`,RESPONSE_TIMEOUT:`Response timeout`,RECIPIENT_DISCONNECTED:`Recipient disconnected`,RESPONSE_PAYLOAD_TOO_LARGE:`Response payload too large`,SEND_FAILED:`Failed to send`,UNSUPPORTED_METHOD:`Method not supported at destination`,RECIPIENT_NOT_FOUND:`Recipient not found`,REQUEST_PAYLOAD_TOO_LARGE:`Request payload too large`,UNSUPPORTED_SERVER:`RPC not supported by server`,UNSUPPORTED_VERSION:`Unsupported RPC version`};var XC=15360;function ZC(e){return new TextEncoder().encode(e).length}function QC(e,t){if(ZC(e)<=t)return e;let n=0,r=e.length,i=new TextEncoder;for(;n<r;){let a=Math.floor((n+r+1)/2);i.encode(e.slice(0,a)).length<=t?n=a:r=a-1}return e.slice(0,n)}var $C=2e3;function ew(e,t){if(!t)return 0;let n,r;return`bytesReceived`in e?(n=e.bytesReceived,r=t.bytesReceived):`bytesSent`in e&&(n=e.bytesSent,r=t.bytesSent),n===void 0||r===void 0||e.timestamp===void 0||t.timestamp===void 0?0:(n-r)*8*1e3/(e.timestamp-t.timestamp)}var tw=typeof MediaRecorder<`u`,nw=tw?MediaRecorder:class{constructor(){throw Error(`MediaRecorder is not available in this environment`)}},rw=class extends nw{constructor(e,t){if(!tw)throw Error(`MediaRecorder is not available in this environment`);super(new MediaStream([e.mediaStreamTrack]),t);let n,r,i=()=>r===void 0,a=()=>{this.removeEventListener(`dataavailable`,n),this.removeEventListener(`stop`,a),this.removeEventListener(`error`,o),r?.close(),r=void 0},o=e=>{r?.error(e),this.removeEventListener(`dataavailable`,n),this.removeEventListener(`stop`,a),this.removeEventListener(`error`,o),r=void 0};this.byteStream=new ReadableStream({start:e=>{r=e,n=t=>z(this,void 0,void 0,function*(){let n;if(t.data.arrayBuffer){let e=yield t.data.arrayBuffer();n=new Uint8Array(e)}else if(t.data.byteArray)n=t.data.byteArray;else throw Error(`no data available!`);i()||e.enqueue(n)}),this.addEventListener(`dataavailable`,n)},cancel:()=>{a()}}),this.addEventListener(`stop`,a),this.addEventListener(`error`,o)}};function iw(){return tw}var aw=1e3,ow=1e4,sw=class extends q{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,i=arguments.length>4?arguments[4]:void 0;super(e,t,i),this.manuallyStopped=!1,this.pendingDeviceChange=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug(`track mute bounce got cancelled by an unmute event`,this.logContext)),this.debouncedTrackMuteHandler=OC(()=>z(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>z(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel(`unmute`),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent),this.emit(W.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new Dm,this.pauseUpstreamLock=new Dm,this.trackChangeLock=new Dm,this.trackChangeLock.lock().then(t=>z(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==q.Kind.Video)return;let{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){return this.processor?.processedTrack??this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t,n){return z(this,void 0,void 0,function*(){if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{hx(this._mediaStreamTrack,e)}),this.debouncedTrackMuteHandler.cancel(`new-track`),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener(`ended`,this.handleEnded),e.addEventListener(`mute`,this.handleTrackMuteEvent),e.addEventListener(`unmute`,this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let r;if(this.processor&&e){if(this.log.debug(`restarting processor`,this.logContext),this.kind===`unknown`)throw TypeError(`cannot set processor on track of unknown kind`);this.processorElement&&(mx(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}this.sender&&this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=n?!0:!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{mx(r??e,t)}))})}waitForDimensions(){return z(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:aw;return function*(){if(e.kind===q.Kind.Audio)throw Error(`cannot get dimensions for audio tracks`);yb()?.os===`iOS`&&(yield yx(10));let n=Date.now();for(;Date.now()-n<t;){let t=e.dimensions;if(t)return t;yield yx(50)}throw new Ob(`unable to get track dimensions after timeout`)}()})}setDeviceId(e){return z(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===tS(e)?!0:(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),tS(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return z(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===q.Source.ScreenShare)return;let{deviceId:n,groupId:r}=e._mediaStreamTrack.getSettings(),i=e.kind===q.Kind.Audio?`audioinput`:`videoinput`;return t?US.getInstance().normalizeDeviceId(i,n,r):n}()})}mute(){return z(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return z(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return z(this,void 0,void 0,function*(){let n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Ob(`unable to replace an unpublished track`);let n,r;return typeof t==`boolean`?n=t:t!==void 0&&(n=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=n??!0,this.log.debug(`replace MediaStreamTrack`,this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor()),this}finally{n()}})}restart(e,t){return z(this,void 0,void 0,function*(){this.manuallyStopped=!1;let n=yield this.trackChangeLock.lock();try{e||=this._constraints;let{deviceId:n,facingMode:r}=e,i=Yv(e,[`deviceId`,`facingMode`]);this.log.debug(`restarting track with constraints`,Object.assign(Object.assign({},this.logContext),{constraints:e}));let a={audio:!1,video:!1};this.kind===q.Kind.Video?a.video=n||r?{deviceId:n,facingMode:r}:!0:a.audio=n?Object.assign({deviceId:n},i):!0,this.attachedElements.forEach(e=>{hx(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.stop();let o=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===q.Kind.Video&&(yield o.applyConstraints(i)),o.addEventListener(`ended`,this.handleEnded),this.log.debug(`re-acquired MediaStreamTrack`,this.logContext),yield this.setMediaStreamTrack(o,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit(W.Restarted,this),this.manuallyStopped&&(this.log.warn(`track was stopped during a restart, stopping restarted track`,this.logContext),this.stop()),this}finally{n()}})}setTrackMuted(e){this.log.debug(`setting ${this.kind} track ${e?`muted`:`unmuted`}`,this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?W.Muted:W.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!==`live`||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return z(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Nx()&&(this.log.debug(`visibility changed, is in Background: ${this.isInBackground}`,this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug(`track needs to be reacquired, restarting ${this.source}`,this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent),(e=this.processor)==null||e.destroy(),this.processor=void 0}pauseUpstream(){return z(this,void 0,void 0,function*(){let e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn(`unable to pause upstream for an unpublished track`,this.logContext);return}this._isUpstreamPaused=!0,this.emit(W.UpstreamPaused,this);let e=yb();if(e?.name===`Safari`&&Hx(e.version,`12.0`)<0)throw new Db(`pauseUpstream is not supported on Safari < 12.`);this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(null))}finally{e()}})}resumeUpstream(){return z(this,void 0,void 0,function*(){let e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn(`unable to resume upstream for an unpublished track`,this.logContext);return}this._isUpstreamPaused=!1,this.emit(W.UpstreamResumed,this),this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{e()}})}getRTCStatsReport(){return z(this,void 0,void 0,function*(){if(this.sender?.getStats)return yield this.sender.getStats()})}setProcessor(e){return z(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){let r=yield t.trackChangeLock.lock();try{t.log.debug(`setting up processor`,t.logContext);let r=document.createElement(t.kind),i={kind:t.kind,track:t._mediaStreamTrack,element:r,audioContext:t.audioContext};if(yield e.init(i),t.log.debug(`processor initialized`,t.logContext),t.processor&&(yield t.internalStopProcessor()),t.kind===`unknown`)throw TypeError(`cannot set processor on track of unknown kind`);if(mx(t._mediaStreamTrack,r),r.muted=!0,r.play().catch(e=>{e instanceof DOMException&&e.name===`AbortError`?(t.log.warn(`failed to play processor element, retrying`,Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout(()=>{r.play().catch(e=>{t.log.error(`failed to play processor element`,Object.assign(Object.assign({},t.logContext),{err:e}))})},100)):t.log.error(`failed to play processor element`,Object.assign(Object.assign({},t.logContext),{error:e}))}),t.processor=e,t.processorElement=r,t.processor.processedTrack){for(let e of t.attachedElements)e!==t.processorElement&&n&&(hx(t._mediaStreamTrack,e),mx(t.processor.processedTrack,e));yield t.sender?.replaceTrack(t.processor.processedTrack)}t.emit(W.TrackProcessorUpdate,t.processor)}finally{r()}}()})}getProcessor(){return this.processor}stopProcessor(){return z(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){let n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}}()})}internalStopProcessor(){return z(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,r;e.processor&&(e.log.debug(`stopping processor`,e.logContext),(n=e.processor.processedTrack)==null||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||((r=e.processorElement)==null||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(W.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!iw()){this.log.warn(`MediaRecorder is not available, cannot start preconnect buffer`,this.logContext);return}if(this.localTrackRecorder){this.log.warn(`preconnect buffer already started`);return}else{let e=`audio/webm;codecs=opus`;MediaRecorder.isTypeSupported(e)||(e=`video/mp4`),this.localTrackRecorder=new rw(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn(`preconnect buffer timed out, stopping recording automatically`,this.logContext),this.stopPreConnectBuffer()},ow)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&=(this.localTrackRecorder.stop(),void 0)}getPreConnectBuffer(){return this.localTrackRecorder?.byteStream}getPreConnectBufferMimeType(){return this.localTrackRecorder?.mimeType}},cw=class extends sw{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0;super(e,q.Kind.Audio,t,n,i),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>z(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let e;try{e=yield this.getSenderStats()}catch(e){this.log.error(`could not get audio sender stats`,Object.assign(Object.assign({},this.logContext),{error:e}));return}e&&this.prevStats&&(this._currentBitrate=ew(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug(`Krisp noise filter enabled`,this.logContext),this.emit(W.AudioTrackFeatureUpdate,this,Ig.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug(`Krisp noise filter disabled`,this.logContext),this.emit(W.AudioTrackFeatureUpdate,this,Ig.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return z(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug(`Track already muted`,this.logContext),this):(this.source===q.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug(`stopping mic track`,this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return z(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===q.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState===`ended`||this.pendingDeviceChange)&&!this.isUserProvided&&(this.log.debug(`reacquiring mic track`,this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug(`Track already unmuted`,this.logContext),this)}finally{t()}})}restartTrack(e){return z(this,void 0,void 0,function*(){let t;if(e){let n=Zb({audio:e});typeof n.audio!=`boolean`&&(t=n.audio)}yield this.restart(t)})}restart(e,t){let n=Object.create(null,{restart:{get:()=>super.restart}});return z(this,void 0,void 0,function*(){let r=yield n.restart.call(this,e,t);return this.checkForSilence(),r})}startMonitor(){Fx()&&(this.monitorInterval||=setInterval(()=>{this.monitorSender()},$C))}setProcessor(e){return z(this,void 0,void 0,function*(){let t=yield this.trackChangeLock.lock();try{if(!Ix()&&!this.audioContext)throw Error(`Audio context needs to be set on LocalAudioTrack in order to enable processors`);this.processor&&(yield this.internalStopProcessor());let t={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug(`setting up audio processor ${e.name}`,this.logContext),yield e.init(t),this.processor=e,this.processor.processedTrack&&(yield this.sender?.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener(`enable-lk-krisp-noise-filter`,this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener(`disable-lk-krisp-noise-filter`,this.handleKrispNoiseFilterDisable)),this.emit(W.TrackProcessorUpdate,this.processor)}finally{t()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return z(this,void 0,void 0,function*(){if(!this.sender?.getStats)return;let e=yield this.sender.getStats(),t;return e.forEach(e=>{e.type===`outbound-rtp`&&(t={type:`audio`,streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})}),t})}checkForSilence(){return z(this,void 0,void 0,function*(){let e=yield Qb(this);return e&&(this.isMuted||this.log.debug(`silence detected on local audio track`,this.logContext),this.emit(W.AudioSilenceDetected)),e})}};function lw(e,t,n){switch(e.kind){case`audio`:return new cw(e,t,!1,void 0,n);case`video`:return new Dw(e,t,!1,n);default:throw new Ob(`unsupported track type: ${e.kind}`)}}var uw=Object.values(Kb),dw=Object.values(qb),fw=Object.values(Jb),pw=[Kb.h180,Kb.h360],mw=[qb.h180,qb.h360],hw=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map(t=>new G(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(t.scaleResolutionDownBy**2*((e.encoding.maxFramerate??30)/(t.fps??30))))),t.fps,e.encoding.priority)),gw=[`q`,`h`,`f`];function _w(e,t,n,r){let i=r?.videoEncoding;e&&(i=r?.screenShareEncoding);let a=r?.simulcast,o=r?.scalabilityMode,s=r?.videoCodec;if(!i&&!a&&!o||!t||!n)return[{}];i||(i=yw(e,t,n,s),R.debug(`using video encoding`,i));let c=i.maxFramerate,l=new G(t,n,i.maxBitrate,i.maxFramerate,i.priority);if(o&&wx(s)){let e=new ww(o),t=[];if(e.spatial>3)throw Error(`unsupported scalabilityMode: ${o}`);let n=yb();if(Ax()||Ix()||n?.name===`Chrome`&&Hx(n?.version,`113`)<0){let r=e.suffix==`h`?2:3,a=Mx(n);for(let n=0;n<e.spatial;n+=1)t.push({rid:gw[2-n],maxBitrate:i.maxBitrate/r**+n,maxFramerate:l.encoding.maxFramerate,scaleResolutionDownBy:a?2**n:void 0});t[0].scalabilityMode=o}else t.push({maxBitrate:i.maxBitrate,maxFramerate:l.encoding.maxFramerate,scalabilityMode:o});return l.encoding.priority&&(t[0].priority=l.encoding.priority,t[0].networkPriority=l.encoding.priority),R.debug(`using svc encoding`,{encodings:t}),t}if(!a)return[i];let u=[];u=e?Cw(r?.screenShareSimulcastLayers)??xw(e,l):Cw(r?.videoSimulcastLayers)??xw(e,l);let d;if(u.length>0){let e=u[0];u.length>1&&([,d]=u);let r=Math.max(t,n);if(r>=960&&d)return Sw(t,n,[e,d,l],c);if(r>=480)return Sw(t,n,[e,l],c)}return Sw(t,n,[l])}function vw(e,t,n){if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&R.warn(`requested a different codec than specified as backup`,{serverRequested:t,backup:n.backupCodec.codec}),n.videoCodec=t,n.videoEncoding=n.backupCodec.encoding;let r=e.mediaStreamTrack.getSettings(),i=r.width??e.dimensions?.width,a=r.height??e.dimensions?.height;return e.source===q.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),_w(e.source===q.Source.ScreenShare,i,a,n)}function yw(e,t,n,r){let i=bw(e,t,n),{encoding:a}=i[0],o=Math.max(t,n);for(let e=0;e<i.length;e+=1){let t=i[e];if(a=t.encoding,t.width>=o)break}if(r)switch(r){case`av1`:case`h265`:a=Object.assign({},a),a.maxBitrate*=.7;break;case`vp9`:a=Object.assign({},a),a.maxBitrate*=.85;break}return a}function bw(e,t,n){if(e)return fw;let r=t>n?t/n:n/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?uw:dw}function xw(e,t){if(e)return hw(t);let{width:n,height:r}=t,i=n>r?n/r:r/n;return Math.abs(i-16/9)<Math.abs(i-4/3)?pw:mw}function Sw(e,t,n,r){let i=[];if(n.forEach((n,a)=>{if(a>=gw.length)return;let o=Math.min(e,t),s={rid:gw[a],scaleResolutionDownBy:Math.max(1,o/Math.min(n.width,n.height)),maxBitrate:n.encoding.maxBitrate},c=r&&n.encoding.maxFramerate?Math.min(r,n.encoding.maxFramerate):n.encoding.maxFramerate;c&&(s.maxFramerate=c);let l=Dx()||a===0;n.encoding.priority&&l&&(s.priority=n.encoding.priority,s.networkPriority=n.encoding.priority),i.push(s)}),Ix()&&Bx()===`ios`){let e;i.forEach(t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate});let t=!0;i.forEach(n=>{n.maxFramerate!=e&&(t&&(t=!1,R.info(`Simulcast on iOS React-Native requires all encodings to share the same framerate.`)),R.info(`Setting framerate of encoding "${n.rid??``}" to ${e}`),n.maxFramerate=e)})}return i}function Cw(e){if(e)return e.sort((e,t)=>{let{encoding:n}=e,{encoding:r}=t;return n.maxBitrate>r.maxBitrate?1:n.maxBitrate<r.maxBitrate?-1:n.maxBitrate===r.maxBitrate&&n.maxFramerate&&r.maxFramerate?n.maxFramerate>r.maxFramerate?1:-1:0})}var ww=class{constructor(e){let t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw Error(`invalid scalability mode`);if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case`h`:case`_KEY`:case`_KEY_SHIFT`:this.suffix=t[3]}}toString(){return`L${this.spatial}T${this.temporal}${this.suffix??``}`}};function Tw(e){return e.source===q.Source.ScreenShare||e.constraints.height&&tS(e.constraints.height)>=1080?`maintain-resolution`:`balanced`}var Ew=5e3,Dw=class extends sw{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,q.Kind.Video,t,n,r),this.simulcastCodecs=new Map,this.degradationPreference=`balanced`,this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>z(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let e;try{e=yield this.getSenderStats()}catch(e){this.log.error(`could not get video sender stats`,Object.assign(Object.assign({},this.logContext),{error:e}));return}let t=new Map(e.map(e=>[e.rid,e])),n=e.some(e=>e.qualityLimitationReason===`cpu`);if(n!==this.isCpuConstrained&&(this.isCpuConstrained=n,this.isCpuConstrained&&this.emit(W.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,n)=>{let r=this.prevStats?.get(n);e+=ew(t,r)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new Dm}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){if(this.signalClient=e,!Fx())return;let t=this.sender?.getParameters();t&&(this.encodings=t.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},$C))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){let e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return z(this,void 0,void 0,function*(){var t,n,r,i;yield e.pauseUpstream.call(this);try{for(var a=!0,o=ey(this.simulcastCodecs.values()),s;s=yield o.next(),t=s.done,!t;a=!0)i=s.value,a=!1,yield i.sender?.replaceTrack(null)}catch(e){n={error:e}}finally{try{!a&&!t&&(r=o.return)&&(yield r.call(o))}finally{if(n)throw n.error}}})}resumeUpstream(){let e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return z(this,void 0,void 0,function*(){var t,n,r,i;yield e.resumeUpstream.call(this);try{for(var a=!0,o=ey(this.simulcastCodecs.values()),s;s=yield o.next(),t=s.done,!t;a=!0){i=s.value,a=!1;let e=i;yield e.sender?.replaceTrack(e.mediaStreamTrack)}}catch(e){n={error:e}}finally{try{!a&&!t&&(r=o.return)&&(yield r.call(o))}finally{if(n)throw n.error}}})}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return z(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug(`Track already muted`,this.logContext),this):(this.source===q.Source.Camera&&!this.isUserProvided&&(this.log.debug(`stopping camera track`,this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return z(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===q.Source.Camera&&!this.isUserProvided&&(this.log.debug(`reacquiring camera track`,this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug(`Track already unmuted`,this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(let t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return z(this,void 0,void 0,function*(){if(!this.sender?.getStats)return[];let e=[],t=yield this.sender.getStats();return t.forEach(n=>{if(n.type===`outbound-rtp`){let r={type:`video`,streamId:n.id,frameHeight:n.frameHeight,frameWidth:n.frameWidth,framesPerSecond:n.framesPerSecond,framesSent:n.framesSent,firCount:n.firCount,pliCount:n.pliCount,nackCount:n.nackCount,packetsSent:n.packetsSent,bytesSent:n.bytesSent,qualityLimitationReason:n.qualityLimitationReason,qualityLimitationDurations:n.qualityLimitationDurations,qualityLimitationResolutionChanges:n.qualityLimitationResolutionChanges,rid:n.rid??n.id,retransmittedPacketsSent:n.retransmittedPacketsSent,targetBitrate:n.targetBitrate,timestamp:n.timestamp},i=t.get(n.remoteId);i&&(r.jitter=i.jitter,r.packetsLost=i.packetsLost,r.roundTripTime=i.roundTripTime),e.push(r)}}),e.sort((e,t)=>(t.frameWidth??0)-(e.frameWidth??0)),e})}setPublishingQuality(e){let t=[];for(let n=px.LOW;n<=px.HIGH;n+=1)t.push(new dv({quality:n,enabled:n<=e}));this.log.debug(`setting publishing quality. max quality ${e}`,this.logContext),this.setPublishingLayers(wx(this.codec),t)}restartTrack(e){return z(this,void 0,void 0,function*(){var t,n,r,i;let a;if(e){let t=Zb({video:e});typeof t.video!=`boolean`&&(a=t.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var o=!0,s=ey(this.simulcastCodecs.values()),c;c=yield s.next(),t=c.done,!t;o=!0){i=c.value,o=!1;let e=i;e.sender&&e.sender.transport?.state!==`closed`&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){n={error:e}}finally{try{!o&&!t&&(r=s.return)&&(yield r.call(s))}finally{if(n)throw n.error}}})}setProcessor(e){let t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return z(this,arguments,void 0,function(e){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var i,a,o,s;if(yield t.setProcessor.call(n,e,r),n.processor?.processedTrack)try{for(var c=!0,l=ey(n.simulcastCodecs.values()),u;u=yield l.next(),i=u.done,!i;c=!0)s=u.value,c=!1,yield s.sender?.replaceTrack(n.processor.processedTrack)}catch(e){a={error:e}}finally{try{!c&&!i&&(o=l.return)&&(yield o.call(l))}finally{if(a)throw a.error}}}()})}setDegradationPreference(e){return z(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug(`setting degradationPreference to ${e}`,this.logContext);let t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn(`failed to set degradationPreference`,Object.assign({error:e},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error(`${e} already added, skipping adding simulcast codec`,this.logContext);return}let n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){let n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Ew))}setPublishingCodecs(e){return z(this,void 0,void 0,function*(){var t,n,r,i,a,o,s;if(this.log.debug(`setting publishing codecs`,Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(wx(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;let c=[];try{for(t=!0,n=ey(e);r=yield n.next(),i=r.done,!i;t=!0){s=r.value,t=!1;let e=s;if(!this.codec||this.codec===e.codec)yield this.setPublishingLayers(wx(e.codec),e.qualities);else{let t=this.simulcastCodecs.get(e.codec);if(this.log.debug(`try setPublishingCodec for ${e.codec}`,Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),!t||!t.sender){for(let t of e.qualities)if(t.enabled){c.push(e.codec);break}}else t.encodings&&(this.log.debug(`try setPublishingLayersForSender ${e.codec}`,this.logContext),yield Ow(t.sender,t.encodings,e.qualities,this.senderLock,wx(e.codec),this.log,this.logContext))}}}catch(e){a={error:e}}finally{try{!t&&!i&&(o=n.return)&&(yield o.call(n))}finally{if(a)throw a.error}}return c})}setPublishingLayers(e,t){return z(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info(`skipping setPublishingLayers due to optimized publishing performance`,Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug(`setting publishing layers`,Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield Ow(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return z(this,void 0,void 0,function*(){if(!this.sender)throw Error(`sender not found`);let e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;let e=this.sender.getParameters();e.encodings=e.encodings.map((e,t)=>Object.assign(Object.assign({},e),{active:t===0,scaleResolutionDownBy:Math.max(1,Math.ceil((this.mediaStreamTrack.getSettings().height??360)/360)),scalabilityMode:t===0&&wx(this.codec)?`L1T3`:void 0,maxFramerate:t===0?15:0,maxBitrate:t===0?e.maxBitrate:0})),this.log.debug(`setting performance optimised encodings`,Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error(`failed to set performance optimised encodings`,Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return z(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Nx()&&this.isInBackground&&this.source===q.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}};function Ow(e,t,n,r,i,a,o){return z(this,void 0,void 0,function*(){let s=yield r.lock();a.debug(`setPublishingLayersForSender`,Object.assign(Object.assign({},o),{sender:e,qualities:n,senderEncodings:t}));try{let r=e.getParameters(),{encodings:s}=r;if(!s)return;if(s.length!==t.length){a.warn(`cannot set publishing layers, encodings mismatch`,Object.assign(Object.assign({},o),{encodings:s,senderEncodings:t}));return}let c=!1;i&&n.some(e=>e.enabled)&&n.forEach(e=>e.enabled=!0),s.forEach((e,r)=>{let i=e.rid??``;i===``&&(i=`q`);let s=kw(i),l=n.find(e=>e.quality===s);l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,a.debug(`setting layer ${l.quality} to ${e.active?`enabled`:`disabled`}`,o),Dx()&&(l.enabled?(e.scaleResolutionDownBy=t[r].scaleResolutionDownBy,e.maxBitrate=t[r].maxBitrate,e.maxFrameRate=t[r].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}),c&&(r.encodings=s,a.debug(`setting encodings`,Object.assign(Object.assign({},o),{encodings:r.encodings})),yield e.setParameters(r))}finally{s()}})}function kw(e){switch(e){case`f`:return px.HIGH;case`h`:return px.MEDIUM;case`q`:return px.LOW;default:return px.HIGH}}function Aw(e,t,n,r){if(!n)return[new Jg({quality:px.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(r){let r=n[0].scalabilityMode,i=new ww(r),a=[],o=i.suffix==`h`?1.5:2,s=i.suffix==`h`?2:3;for(let r=0;r<i.spatial;r+=1)a.push(new Jg({quality:Math.min(px.HIGH,i.spatial-1)-r,width:Math.ceil(e/o**+r),height:Math.ceil(t/o**+r),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/s**+r):0,ssrc:0}));return a}return n.map(n=>{let r=n.scaleResolutionDownBy??1;return new Jg({quality:kw(n.rid??``),width:Math.ceil(e/r),height:Math.ceil(t/r),bitrate:n.maxBitrate??0,ssrc:0})})}var jw=`_lossy`,Mw=`_reliable`,Nw=`_data_track`,Pw=2*1e3,Fw=`leave-reconnect`,Iw=3e4,Lw=8*1024,Rw=256*1024,zw=3,Bw=3,Vw;(function(e){e[e.New=0]=`New`,e[e.Connected=1]=`Connected`,e[e.Disconnected=2]=`Disconnected`,e[e.Reconnecting=3]=`Reconnecting`,e[e.Closed=4]=`Closed`})(Vw||={});var J;(function(e){e[e.RELIABLE=0]=`RELIABLE`,e[e.LOSSY=1]=`LOSSY`,e[e.DATA_TRACK_LOSSY=2]=`DATA_TRACK_LOSSY`})(J||={});var Hw=class extends iy.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=HC.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Vw.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=R,this.reliableDataSequence=1,this.reliableMessageBuffer=new pC,this.reliableReceivedState=new mC(Iw),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>z(this,[e],void 0,function(e){var t=this;let{channel:n}=e;return function*(){if(!n)return;let e;if(n.label===Mw)t.reliableDCSub=n,e=t.handleDataMessage;else if(n.label===jw)t.lossyDCSub=n,e=t.handleDataMessage;else if(n.label===Nw)t.dataTrackDCSub=n,e=t.handleDataTrackMessage;else return;t.log.debug(`on data channel ${n.id}, ${n.label}`,t.logContext),n.onmessage=e}()}),this.handleDataMessage=e=>z(this,void 0,void 0,function*(){let t=yield this.dataProcessLock.lock();try{let t;if(e.data instanceof ArrayBuffer)t=e.data;else if(e.data instanceof Blob)t=yield e.data.arrayBuffer();else{this.log.error(`unsupported data type`,Object.assign(Object.assign({},this.logContext),{data:e.data}));return}let n=Xg.fromBinary(new Uint8Array(t));if(n.sequence>0&&n.participantSid!==``){let e=this.reliableReceivedState.get(n.participantSid);if(e&&n.sequence<=e)return;this.reliableReceivedState.set(n.participantSid,n.sequence)}if(n.value?.case===`speaker`)this.emit(U.ActiveSpeakersUpdate,n.value.value.speakers);else if(n.value?.case===`encryptedPacket`){if(!this.e2eeManager){this.log.error(`Received encrypted packet but E2EE not set up`,this.logContext);return}let e=yield this.e2eeManager?.handleEncryptedData(n.value.value.encryptedValue,n.value.value.iv,n.participantIdentity,n.value.value.keyIndex),t=new Xg({value:$g.fromBinary(e.payload).value,participantIdentity:n.participantIdentity,participantSid:n.participantSid});t.value?.case===`user`&&Uw(t,t.value.value),this.emit(U.DataPacketReceived,t,n.value.value.encryptionType)}else n.value?.case===`user`&&Uw(n,n.value.value),this.emit(U.DataPacketReceived,n,L.NONE)}finally{t()}}),this.handleDataTrackMessage=e=>z(this,void 0,void 0,function*(){let t;if(e.data instanceof ArrayBuffer)t=e.data;else if(e.data instanceof Blob)t=yield e.data.arrayBuffer();else{this.log.error(`unsupported data type`,Object.assign(Object.assign({},this.logContext),{data:e.data}));return}this.emit(`dataTrackPacketReceived`,new Uint8Array(t))}),this.handleDataError=e=>{let t=e.currentTarget.maxRetransmits===0?`lossy`:`reliable`;if(e instanceof ErrorEvent&&e.error){let{error:n}=e.error;this.log.error(`DataChannel error on ${t}: ${e.message}`,Object.assign(Object.assign({},this.logContext),{error:n}))}else this.log.error(`Unknown DataChannel error on ${t}`,Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{this.updateAndEmitDCBufferStatus(e)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn(`${e} disconnected`,this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());let n=e=>{this.log.warn(`could not recover connection after ${this.reconnectAttempts} attempts, ${e}ms. giving up`,this.logContext),this.emit(U.Disconnected),this.close()},r=Date.now()-this.reconnectStart,i=this.getNextRetryDelay({elapsedMs:r,retryCount:this.reconnectAttempts});if(i===null){n(r);return}e===Fw&&(i=0),this.log.debug(`reconnecting in ${i}ms`,this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Rb.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),i)},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===Vw.Connected&&e();let n=()=>{this.off(U.Disconnected,r),e()},r=()=>{this.off(U.Restarted,n),t()};this.once(U.Restarted,n),this.once(U.Disconnected,r)}),this.updateAndEmitDCBufferStatus=e=>{if(e===J.RELIABLE){let t=this.dataChannelForKind(e);t&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount)}let t=this.isBufferStatusLow(e);t!==void 0&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(U.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{let t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>z(this,void 0,void 0,function*(){this.url&&(yield fetch(rS(this.url),{method:`HEAD`}).then(e=>e.ok).catch(()=>!1))&&(this.log.info(`detected network reconnected`),(this.client.currentState===oC.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===oC.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Pg.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>z(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(rS(this.url),{method:`HEAD`}),yx(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info(`detected network interruption`),this.isWaitingForNetworkReconnect=!0)}}),this.log=Wv(e.loggerName??Uv.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new cC(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new Dm,this.dataProcessLock=new Dm,this.dcBufferStatus=new Map([[J.RELIABLE,!0],[J.LOSSY,!0],[J.DATA_TRACK_LOSSY,!0]]),this.client.onParticipantUpdate=e=>this.emit(U.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(U.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(U.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(U.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(U.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(U.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(U.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(U.SignalRequestResponse,e),this.client.onParticipantUpdate=e=>this.emit(U.ParticipantUpdate,e),this.client.onJoined=e=>this.emit(U.Joined,e)}get logContext(){return{room:this.latestJoinResponse?.room?.name,roomID:this.latestJoinResponse?.room?.sid,participant:this.latestJoinResponse?.participant?.identity,participantID:this.participantSid}}join(e,t,n,r){return z(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return function*(){var o;i._isNewlyCreated=!1,i.url=e,i.token=t,i.signalOpts=n,i.maxJoinAttempts=n.maxRetries;try{i.joinAttempts+=1,i.setupSignalClientCallbacks();let s;if(!a&&bS()){i.pcManager||(yield i.configure(),i.createDataChannels(),i.addMediaSections(zw,Bw));let e=yield i.pcManager?.publisher.createInitialOffer();e&&(s=uC(e.offer,e.offerId))}if(r?.aborted)throw B.cancelled(`Connection aborted`);let c=yield i.client.join(e,t,n,r,a,s);return i._isClosed=!1,i.latestJoinResponse=c,i.participantSid=c.participant?.sid,i.subscriberPrimary=c.subscriberPrimary,!a&&bS()?(o=i.pcManager)==null||o.updateConfiguration(i.makeRTCConfiguration(c)):(i.pcManager||(yield i.configure(c,!a)),(!i.subscriberPrimary||c.fastPublish)&&i.negotiate().catch(e=>{R.error(e,i.logContext)})),i.registerOnLineListener(),i.clientConfiguration=c.clientConfiguration,i.emit(U.SignalConnected,c),c}catch(o){if(o instanceof B){if(o.reason===Eb.ServerUnreachable){if(i.log.warn(`Couldn't connect to server, attempt ${i.joinAttempts} of ${i.maxJoinAttempts}`,i.logContext),i.joinAttempts<i.maxJoinAttempts)return i.join(e,t,n,r,a)}else if(o.reason===Eb.ServiceNotFound)return i.log.warn(`Initial connection failed: ${o.message} – Retrying`),i.join(e,t,n,r,!0)}throw o}}()})}close(){return z(this,void 0,void 0,function*(){let e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(U.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return z(this,void 0,void 0,function*(){yield this.pcManager?.close(),this.pcManager=void 0;let e=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};e(this.lossyDC),e(this.lossyDCSub),e(this.reliableDC),e(this.reliableDCSub),e(this.dataTrackDC),e(this.dataTrackDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.dataTrackDC=void 0,this.dataTrackDCSub=void 0,this.reliableMessageBuffer=new pC,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&=(clearInterval(this.lossyDataStatInterval),void 0),this.lossyDataDropCount=0}cleanupClient(){return z(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Ob(`a track with the same ID has already been published`);return new Promise((t,n)=>{let r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(B.timeout(`publication of local track timed out, no response from server`))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(r),t(e)},reject:()=>{clearTimeout(r),n(Error(`Cancelled publication by calling unpublish`))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){let{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn(`failed to remove track`,Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){return this.reliableDCSub?.readyState}getConnectedServerAddress(){return z(this,void 0,void 0,function*(){return this.pcManager?.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e,t){return z(this,void 0,void 0,function*(){if(!(this.pcManager&&this.pcManager.currentState!==UC.NEW)){if(e){this.participantSid=e.participant?.sid;let n=this.makeRTCConfiguration(e);this.pcManager=new WC(t?`publisher-only`:e.subscriberPrimary?`subscriber-primary`:`publisher-primary`,this.loggerOptions,n)}else{let e=this.makeRTCConfiguration();this.pcManager=new WC(`publisher-only`,this.loggerOptions,e)}this.emit(U.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=(e,t)=>{this.client.sendOffer(e,t)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(e,t,n)=>z(this,void 0,void 0,function*(){if(this.log.debug(`primary PC state changed ${e}`,this.logContext),[`closed`,`disconnected`,`failed`].includes(t)&&(this.publisherConnectionPromise=void 0),e===UC.CONNECTED){let e=this.pcState===Vw.New;this.pcState=Vw.Connected,e&&this.emit(U.Connected,this.latestJoinResponse)}else e===UC.FAILED&&(this.pcState===Vw.Connected||this.pcState===Vw.Reconnecting)&&(this.pcState=Vw.Disconnected,this.handleDisconnect(`peerconnection failed`,n===`failed`?Pg.RR_SUBSCRIBER_FAILED:Pg.RR_PUBLISHER_FAILED));let r=this.client.isDisconnected||this.client.currentState===oC.RECONNECTING,i=[UC.FAILED,UC.CLOSING,UC.CLOSED].includes(e);r&&i&&!this._isClosed&&this.emit(U.Offline)}),this.pcManager.onTrack=e=>{e.streams.length!==0&&this.emit(U.MediaTrackAdded,e.track,e.streams[0],e.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>z(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug(`received server answer`,Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:n})),this.midToTrackId=n,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug(`got ICE candidate from peer`,Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,n)=>z(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;let r=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);r&&this.client.sendAnswer(r,t)}),this.client.onLocalTrackPublished=e=>{if(this.log.debug(`received trackPublishedResponse`,Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:e.track?.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error(`missing track resolver for ${e.cid}`,Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}let{resolve:t}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],t(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(U.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(U.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,(t=this.regionUrlProvider)==null||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(U.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(U.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{this.participantSid=e.participant?.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(U.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(U.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(U.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(U.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect(`signal`,Pg.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug(`client leave request`,Object.assign(Object.assign({},this.logContext),{reason:e?.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug(`updating regions`,this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:GC,regionSettings:e.regions})),e.action){case tv.DISCONNECT:this.emit(U.Disconnected,e?.reason),this.close();break;case tv.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Fw);break;case tv.RESUME:this.handleDisconnect(Fw)}}}makeRTCConfiguration(e){let t=Object.assign({},this.rtcConfig);if(this.signalOpts?.e2eeEnabled&&(this.log.debug(`E2EE - setting up transports with insertable streams`,this.logContext),t.encodedInsertableStreams=!0),t.sdpSemantics=`unified-plan`,t.continualGatheringPolicy=`gather_continually`,!e)return t;if(e.iceServers&&!t.iceServers){let n=[];e.iceServers.forEach(e=>{let t={urls:e.urls};e.username&&(t.username=e.username),e.credential&&(t.credential=e.credential),n.push(t)}),t.iceServers=n}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Mg.ENABLED&&(t.iceTransportPolicy=`relay`),t}addMediaSections(e,t){var n,r;let i={direction:`recvonly`};for(let t=0;t<e;t++)(n=this.pcManager)==null||n.addPublisherTransceiverOfKind(`audio`,i);for(let e=0;e<t;e++)(r=this.pcManager)==null||r.addPublisherTransceiverOfKind(`video`,i)}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.dataTrackDC&&(this.dataTrackDC.onmessage=null,this.dataTrackDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(jw,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Mw,{ordered:!0}),this.dataTrackDC=this.pcManager.createPublisherDataChannel(Nw,{ordered:!1,maxRetransmits:0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.dataTrackDC.onmessage=this.handleDataTrackMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.dataTrackDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.dataTrackDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(J.LOSSY),this.reliableDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(J.RELIABLE),this.dataTrackDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(J.DATA_TRACK_LOSSY),this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;let e=this.dataChannelForKind(J.LOSSY);if(e){let t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,Lw),Rw)}},1e3))}createSender(e,t,n){return z(this,void 0,void 0,function*(){if(bx())return yield this.createTransceiverRTCRtpSender(e,t,n);if(xx())return this.log.warn(`using add-track fallback`,this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Ab(`Required webRTC APIs not supported on this device`)})}createSimulcastSender(e,t,n,r){return z(this,void 0,void 0,function*(){if(bx())return this.createSimulcastTransceiverSender(e,t,n,r);if(xx())return this.log.debug(`using add-track fallback`,this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Ab(`Cannot stream on this device`)})}createTransceiverRTCRtpSender(e,t,n){return z(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ab(`publisher is closed`);let r=[];e.mediaStream&&r.push(e.mediaStream),dS(e)&&(e.codec=t.videoCodec);let i={direction:`sendonly`,streams:r};return n&&(i.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,i)).sender})}createSimulcastTransceiverSender(e,t,n,r){return z(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ab(`publisher is closed`);let i={direction:`sendonly`};r&&(i.sendEncodings=r);let a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,i);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return z(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ab(`publisher is closed`);return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return z(this,void 0,void 0,function*(){if(!this._isClosed){if(this.attemptingReconnect){R.warn(`already attempting reconnect, returning early`,this.logContext);return}(this.clientConfiguration?.resumeConnection===Mg.DISABLED||(this.pcManager?.currentState??UC.NEW)===UC.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(e){this.reconnectAttempts+=1;let t=!0;e instanceof Ab?(this.log.debug(`received unrecoverable error`,Object.assign(Object.assign({},this.logContext),{error:e})),t=!1):e instanceof Ib||(this.fullReconnectOnNext=!0),t?this.handleDisconnect(`reconnect`,Pg.RR_UNKNOWN):(this.log.info(`could not recover connection after ${this.reconnectAttempts} attempts, ${Date.now()-this.reconnectStart}ms. giving up`,this.logContext),this.emit(U.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn(`encountered error in reconnect policy`,Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(e){return z(this,void 0,void 0,function*(){var t,n;try{if(!this.url||!this.token)throw new Ab(`could not reconnect, url or token not saved`);this.log.info(`reconnecting, attempt: ${this.reconnectAttempts}`,this.logContext),this.emit(U.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let n;try{if(!this.signalOpts)throw this.log.warn(`attempted connection restart, without signal options present`,this.logContext),new Ib;n=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(e){throw e instanceof B&&e.reason===Eb.NotAllowed?new Ab(`could not reconnect, token might be expired`):new Ib}if(this.shouldFailNext)throw this.shouldFailNext=!1,Error(`simulated failure`);if(this.client.setReconnected(),this.emit(U.SignalRestarted,n),yield this.waitForPCReconnected(),this.client.currentState!==oC.CONNECTED)throw new Ib(`Signal connection got severed during reconnect`);(t=this.regionUrlProvider)==null||t.resetAttempts(),this.emit(U.Restarted)}catch(e){let t=yield this.regionUrlProvider?.getNextBestRegionUrl();if(t){yield this.restartConnection(t);return}else throw(n=this.regionUrlProvider)==null||n.resetAttempts(),e}})}resumeConnection(e){return z(this,void 0,void 0,function*(){if(!this.url||!this.token)throw new Ab(`could not reconnect, url or token not saved`);if(!this.pcManager)throw new Ab(`publisher and subscriber connections unset`);this.log.info(`resuming signal connection, attempt ${this.reconnectAttempts}`,this.logContext),this.emit(U.Resuming);let t;try{this.setupSignalClientCallbacks(),t=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(e){let t=``;throw e instanceof Error&&(t=e.message,this.log.error(e.message,Object.assign(Object.assign({},this.logContext),{error:e}))),e instanceof B&&e.reason===Eb.NotAllowed?new Ab(`could not reconnect, token might be expired`):e instanceof B&&e.reason===Eb.LeaveRequest?e:new Ib(t)}if(this.emit(U.SignalResumed),t){let e=this.makeRTCConfiguration(t);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=t.serverInfo)}else this.log.warn(`Did not receive reconnect response`,this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,Error(`simulated failure`);if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==oC.CONNECTED)throw new Ib(`Signal connection got severed during reconnect`);this.client.setReconnected(),this.reliableDC?.readyState===`open`&&this.reliableDC.id===null&&this.createDataChannels(),t?.lastMessageSeq&&this.resendReliableMessagesForResume(t.lastMessageSeq),this.emit(U.Resumed)})}waitForPCInitialConnection(e,t){return z(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ab(`PC manager is closed`);yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return z(this,void 0,void 0,function*(){this.pcState=Vw.Reconnecting,this.log.debug(`waiting for peer connection to reconnect`,this.logContext);try{if(yield yx(Pw),!this.pcManager)throw new Ab(`PC manager is closed`);yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Vw.Connected}catch(e){throw this.pcState=Vw.Disconnected,B.internal(`could not establish PC connection, ${e.message}`)}})}publishRpcResponse(e,t,n,r){return z(this,void 0,void 0,function*(){let i=new Xg({destinationIdentities:[e],kind:Zg.RELIABLE,value:{case:`rpcResponse`,value:new l_({requestId:t,value:r?{case:`error`,value:r.toProto()}:{case:`payload`,value:n??``}})}});yield this.sendDataPacket(i,J.RELIABLE)})}publishRpcAck(e,t){return z(this,void 0,void 0,function*(){let n=new Xg({destinationIdentities:[e],kind:Zg.RELIABLE,value:{case:`rpcAck`,value:new c_({requestId:t})}});yield this.sendDataPacket(n,J.RELIABLE)})}sendDataPacket(e,t){return z(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){let t=IS(e);if(t){let n=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:`encryptedPacket`,value:new Qg({encryptedValue:n.payload,iv:n.iv,keyIndex:n.keyIndex})}}}t===J.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);let n=e.toBinary();switch(t){case J.LOSSY:case J.DATA_TRACK_LOSSY:return this.sendLossyBytes(n,t);case J.RELIABLE:let r=this.dataChannelForKind(t);if(r){if(yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:n,sequence:e.sequence}),this.attemptingReconnect)return;r.send(n)}this.updateAndEmitDCBufferStatus(t);break}})}sendLossyBytes(e,t){return z(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`drop`;return function*(){yield n.ensurePublisherConnected(t);let i=n.dataChannelForKind(t);if(i){if(!n.isBufferStatusLow(t))switch(r){case`wait`:yield n.waitForBufferStatusLow(t);break;case`drop`:n.lossyDataDropCount+=1,n.lossyDataDropCount%100==0&&n.log.warn(`dropping lossy data channel messages, total dropped: ${n.lossyDataDropCount}`,n.logContext);return}if(n.lossyDataStatCurrentBytes+=e.byteLength,n.attemptingReconnect)return;i.send(e)}n.updateAndEmitDCBufferStatus(t)}()})}resendReliableMessagesForResume(e){return z(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(J.RELIABLE);let t=this.dataChannelForKind(J.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(e=>{t.send(e.data)})),this.updateAndEmitDCBufferStatus(J.RELIABLE)})}waitForBufferStatusLow(e){return new gb((t,n)=>z(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{let r=()=>n(new Ab(`engine closed`));for(this.once(U.Closing,r);!this.dcBufferStatus.get(e);)yield yx(10);this.off(U.Closing,r),t()}}))}ensureDataTransportConnected(e){return z(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){if(!t.pcManager)throw new Ab(`PC manager is closed`);let r=n?t.pcManager.subscriber:t.pcManager.publisher,i=n?`Subscriber`:`Publisher`;if(!r)throw B.internal(`${i} connection not set`);let a=!1;if(!n&&!t.dataChannelForKind(e,n)&&(t.createDataChannels(),a=!0),!a&&!n&&!t.pcManager.publisher.isICEConnected&&t.pcManager.publisher.getICEConnectionState()!==`checking`&&(a=!0),a&&t.negotiate().catch(e=>{R.error(e,t.logContext)}),t.dataChannelForKind(e,n)?.readyState===`open`)return;let o=new Date().getTime()+t.peerConnectionTimeout;for(;new Date().getTime()<o;){if(r.isICEConnected&&t.dataChannelForKind(e,n)?.readyState===`open`)return;yield yx(50)}throw B.internal(`could not establish ${i} connection, state: ${r.getICEConnectionState()}`)}()})}ensurePublisherConnected(e){return z(this,void 0,void 0,function*(){this.publisherConnectionPromise||=this.ensureDataTransportConnected(e,!1),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||![UC.CONNECTING,UC.CONNECTED].includes(this.pcManager.currentState)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return z(this,void 0,void 0,function*(){return new gb((e,t)=>z(this,void 0,void 0,function*(){if(!this.pcManager){t(new jb(`PC manager is closed`));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&!this.dataTrackDC&&this.createDataChannels();let n=new AbortController,r=()=>{n.abort(),this.log.debug(`engine disconnected while negotiation was ongoing`,this.logContext),e()};this.isClosed&&t(new jb(`cannot negotiate on closed engine`)),this.on(U.Closing,r),this.on(U.Restarting,r),this.pcManager.publisher.once(jC.RTPVideoPayloadTypes,e=>{let t=new Map;e.forEach(e=>{let n=e.codec.toLowerCase();eS(n)&&t.set(e.payload,n)}),this.emit(U.RTPVideoMapUpdate,t)});try{yield this.pcManager.negotiate(n),e()}catch(r){if(n.signal.aborted){e();return}r instanceof jb&&(this.fullReconnectOnNext=!0),this.handleDisconnect(`negotiation`,Pg.RR_UNKNOWN),r instanceof Error?t(r):t(Error(String(r)))}finally{this.off(U.Closing,r),this.off(U.Restarting,r)}}))})}dataChannelForKind(e,t){switch(e){case J.RELIABLE:return t?this.reliableDCSub:this.reliableDC;case J.LOSSY:return t?this.lossyDCSub:this.lossyDC;case J.DATA_TRACK_LOSSY:return t?this.dataTrackDCSub:this.dataTrackDC}}sendSyncState(e,t,n){if(!this.pcManager){this.log.warn(`sync state cannot be sent without peer connection setup`,this.logContext);return}let r=this.pcManager.publisher.getLocalDescription(),i=this.pcManager.publisher.getRemoteDescription(),a=this.pcManager.subscriber?.getRemoteDescription(),o=this.pcManager.subscriber?.getLocalDescription(),s=this.signalOpts?.autoSubscribe??!0,c=[],l=[];e.forEach(e=>{e.isDesired!==s&&c.push(e.trackSid),e.isEnabled||l.push(e.trackSid)}),this.client.sendSyncState(new yv({answer:this.pcManager.mode===`publisher-only`?i?uC({sdp:i.sdp,type:i.type}):void 0:o?uC({sdp:o.sdp,type:o.type}):void 0,offer:this.pcManager.mode===`publisher-only`?r?uC({sdp:r.sdp,type:r.type}):void 0:a?uC({sdp:a.sdp,type:a.type}):void 0,subscription:new J_({trackSids:c,subscribe:!s,participantTracks:[]}),publishTracks:ix(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new bv({publisherSid:t,lastSeq:e})),publishDataTracks:n.map(e=>new F_({info:eC.toProtobuf(e)}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){let e=[],t=(t,n)=>{t?.id!==void 0&&t.id!==null&&e.push(new xv({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(J.LOSSY),D_.PUBLISHER),t(this.dataChannelForKind(J.RELIABLE),D_.PUBLISHER),t(this.dataChannelForKind(J.LOSSY,!0),D_.SUBSCRIBER),t(this.dataChannelForKind(J.RELIABLE,!0),D_.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Rb.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Fx()&&(window.addEventListener(`online`,this.handleBrowserOnLine),window.addEventListener(`offline`,this.handleBrowserOffline))}deregisterOnLineListener(){Fx()&&(window.removeEventListener(`online`,this.handleBrowserOnLine),window.removeEventListener(`offline`,this.handleBrowserOffline))}getTrackIdForReceiver(e){let t=this.pcManager?.getMidForReceiver(e);if(t){let e=Object.entries(this.midToTrackId).find(e=>{let[n]=e;return n===t});if(e)return e[1]}}};function Uw(e,t){let n=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=n,t.participantIdentity=n;let r=e.destinationIdentities.length===0?t.destinationIdentities:e.destinationIdentities;e.destinationIdentities=r,t.destinationIdentities=r}var Ww=class{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!=`number`||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new Fb(`Not enough chunk(s) received - expected ${this.totalByteSize} bytes of data total, only received ${this.bytesReceived} bytes`,Pb.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Fb(`Extra chunk(s) received - expected ${this.totalByteSize} bytes of data total, received ${this.bytesReceived} bytes`,Pb.LengthExceeded)}}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}},Gw=class extends Ww{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)==null||t.call(this,n)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>z(this,void 0,void 0,function*(){try{let t=this.signal;if(t?.aborted)throw t.reason;let n=yield new Promise((n,r)=>{if(t){let i=()=>r(t.reason);t.addEventListener(`abort`,i,{once:!0}),e.read().then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})}else e.read().then(n,r)});return n.done?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(n.value),{done:!1,value:n.value.content})}catch(e){throw t(),e}}),return(){return z(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return z(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,r,i,a;let o=new Set,s=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=ey(s),u;u=yield l.next(),n=u.done,!n;c=!0){a=u.value,c=!1;let e=a;o.add(e)}}catch(e){r={error:e}}finally{try{!c&&!n&&(i=l.return)&&(yield i.call(l))}finally{if(r)throw r.error}}return Array.from(o)}()})}},Kw=class extends Ww{constructor(e,t,n){super(e,t,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;let n=sS(e.chunkIndex),r=this.receivedChunks.get(n);if(r&&r.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)==null||t.call(this,i)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=new TextDecoder(`utf-8`,{fatal:!0}),n=this.signal,r=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>z(this,void 0,void 0,function*(){try{if(n?.aborted)throw n.reason;let r=yield new Promise((t,r)=>{if(n){let i=()=>r(n.reason);n.addEventListener(`abort`,i,{once:!0}),e.read().then(t,r).finally(()=>{n.removeEventListener(`abort`,i)})}else e.read().then(t,r)});if(r.done)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(r.value);let e;try{e=t.decode(r.value.content)}catch(e){throw new Fb(`Cannot decode datastream chunk ${r.value.chunkIndex} as text: ${e}`,Pb.DecodeFailed)}return{done:!1,value:e}}}catch(e){throw r(),e}}),return(){return z(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return z(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,r,i,a;let o=``,s=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=ey(s),u;u=yield l.next(),n=u.done,!n;c=!0)a=u.value,c=!1,o+=a}catch(e){r={error:e}}finally{try{!c&&!n&&(i=l.return)&&(yield i.call(l))}finally{if(r)throw r.error}}return o}()})}},qw=class{constructor(){this.log=R,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new Fb(`A text stream handler for topic "${e}" has already been set.`,Pb.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Fb(`A byte stream handler for topic "${e}" has already been set.`,Pb.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){let t=Array.from(this.textStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e),n=Array.from(this.byteStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e);if(t.length>0||n.length>0){let r=new Fb(`Participant ${e} unexpectedly disconnected in the middle of sending data`,Pb.AbnormalEnd);for(let[e,t]of n)t.controller.error(r),this.byteStreamControllers.delete(e);for(let[e,n]of t)n.controller.error(r),this.textStreamControllers.delete(e)}}handleDataStreamPacket(e,t){return z(this,void 0,void 0,function*(){switch(e.value.case){case`streamHeader`:return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case`streamChunk`:return this.handleStreamChunk(e.value.value,t);case`streamTrailer`:return this.handleStreamTrailer(e.value.value,t);default:throw Error(`DataPacket of value "${e.value.case}" is not data stream related!`)}})}handleStreamHeader(e,t,n){return z(this,void 0,void 0,function*(){if(e.contentHeader.case===`byteHeader`){let r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug(`ignoring incoming byte stream due to no handler for topic`,e.topic);return}let i,a={id:e.streamId,name:e.contentHeader.value.name??`unknown`,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:sS(e.timestamp),attributes:e.attributes,encryptionType:n};r(new Gw(a,new ReadableStream({start:n=>{if(i=n,this.textStreamControllers.has(e.streamId))throw new Fb(`A data stream read is already in progress for a stream with id ${e.streamId}.`,Pb.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:i,startTime:Date.now(),sendingParticipantIdentity:t})}}),sS(e.totalLength)),{identity:t})}else if(e.contentHeader.case===`textHeader`){let r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug(`ignoring incoming text stream due to no handler for topic`,e.topic);return}let i,a={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:n,attachedStreamIds:e.contentHeader.value.attachedStreamIds};r(new Kw(a,new ReadableStream({start:n=>{if(i=n,this.textStreamControllers.has(e.streamId))throw new Fb(`A data stream read is already in progress for a stream with id ${e.streamId}.`,Pb.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:a,controller:i,startTime:Date.now(),sendingParticipantIdentity:t})}}),sS(e.totalLength)),{identity:t})}})}handleStreamChunk(e,t){let n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType===t?e.content.length>0&&n.controller.enqueue(e):(n.controller.error(new Fb(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${n.info.encryptionType}`,Pb.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)));let r=this.textStreamControllers.get(e.streamId);r&&(r.info.encryptionType===t?e.content.length>0&&r.controller.enqueue(e):(r.controller.error(new Fb(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${r.info.encryptionType}`,Pb.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)))}handleStreamTrailer(e,t){let n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType===t?(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.textStreamControllers.delete(e.streamId)):n.controller.error(new Fb(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${n.info.encryptionType}`,Pb.EncryptionTypeMismatch)));let r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType===t?(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close()):r.controller.error(new Fb(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${r.info.encryptionType}`,Pb.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId))}},Jw=class{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return z(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)==null||e.call(this)})}},Yw=class extends Jw{},Xw=class extends Jw{},Zw=15e3,Qw=class{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return z(this,void 0,void 0,function*(){let n=crypto.randomUUID(),r=new TextEncoder().encode(e).byteLength,i=(t?.attachments)?.map(()=>crypto.randomUUID()),a=Array(i?i.length+1:1).fill(0),o=(e,n)=>{var r;a[n]=e;let i=a.reduce((e,t)=>e+t,0);(r=t?.onProgress)==null||r.call(t,i)},s=yield this.streamText({streamId:n,totalSize:r,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:i,attributes:t?.attributes});return yield s.write(e),o(1,0),yield s.close(),t?.attachments&&i&&(yield Promise.all(t.attachments.map((e,n)=>z(this,void 0,void 0,function*(){return this._sendFile(i[n],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{o(e,n+1)}})})))),s.info})}streamText(e){return z(this,void 0,void 0,function*(){let t=e?.streamId??crypto.randomUUID(),n={id:t,mimeType:`text/plain`,timestamp:Date.now(),topic:e?.topic??``,size:e?.totalSize,attributes:e?.attributes,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?L.GCM:L.NONE,attachedStreamIds:e?.attachedStreamIds},r=new C_({streamId:t,mimeType:n.mimeType,topic:n.topic,timestamp:cS(n.timestamp),totalLength:cS(n.size),attributes:n.attributes,contentHeader:{case:`textHeader`,value:new x_({version:e?.version,attachedStreamIds:n.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type===`update`?b_.UPDATE:b_.CREATE})}}),i=e?.destinationIdentities,a=new Xg({destinationIdentities:i,value:{case:`streamHeader`,value:r}});yield this.engine.sendDataPacket(a,J.RELIABLE);let o=0,s=this.engine,c=new WritableStream({write(e){return z(this,void 0,void 0,function*(){for(let n of vS(e,Zw)){let e=new Xg({destinationIdentities:i,value:{case:`streamChunk`,value:new w_({content:n,streamId:t,chunkIndex:cS(o)})}});yield s.sendDataPacket(e,J.RELIABLE),o+=1}})},close(){return z(this,void 0,void 0,function*(){let e=new Xg({destinationIdentities:i,value:{case:`streamTrailer`,value:new T_({streamId:t})}});yield s.sendDataPacket(e,J.RELIABLE)})},abort(e){console.log(`Sink error:`,e)}}),l=()=>z(this,void 0,void 0,function*(){yield u.close()});s.once(U.Closing,l);let u=new Yw(c,n,()=>this.engine.off(U.Closing,l));return u})}sendFile(e,t){return z(this,void 0,void 0,function*(){let n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return z(this,void 0,void 0,function*(){let r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:n?.mimeType??t.type,topic:n?.topic,destinationIdentities:n?.destinationIdentities}),i=t.stream().getReader();for(;;){let{done:e,value:t}=yield i.read();if(e)break;yield r.write(t)}return yield r.close(),r.info})}streamBytes(e){return z(this,void 0,void 0,function*(){let t=e?.streamId??crypto.randomUUID(),n=e?.destinationIdentities,r={id:t,mimeType:e?.mimeType??`application/octet-stream`,topic:e?.topic??``,timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:e?.name??`unknown`,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?L.GCM:L.NONE},i=new Xg({destinationIdentities:n,value:{case:`streamHeader`,value:new C_({totalLength:cS(r.size),mimeType:r.mimeType,streamId:t,topic:r.topic,timestamp:cS(Date.now()),attributes:r.attributes,contentHeader:{case:`byteHeader`,value:new S_({name:r.name})}})}});yield this.engine.sendDataPacket(i,J.RELIABLE);let a=0,o=new Dm,s=this.engine,c=this.log;return new Xw(new WritableStream({write(e){return z(this,void 0,void 0,function*(){let r=yield o.lock(),i=0;try{for(;i<e.byteLength;){let r=e.slice(i,i+Zw),o=new Xg({destinationIdentities:n,value:{case:`streamChunk`,value:new w_({content:r,streamId:t,chunkIndex:cS(a)})}});yield s.sendDataPacket(o,J.RELIABLE),a+=1,i+=r.byteLength}}finally{r()}})},close(){return z(this,void 0,void 0,function*(){let e=new Xg({destinationIdentities:n,value:{case:`streamTrailer`,value:new T_({streamId:t})}});yield s.sendDataPacket(e,J.RELIABLE)})},abort(e){c.error(`Sink error:`,e)}}),r)})}};function $w(e){if(e.length===0)return new AbortController().signal;if(e.length===1)return e[0];for(let t of e)if(t.aborted)return t;let t=new AbortController,n=Array(e.length),r=()=>{for(let e of n)e()};return e.forEach((e,i)=>{let a=()=>{t.abort(e.reason),r()};e.addEventListener(`abort`,a),n[i]=()=>e.removeEventListener(`abort`,a)}),t.signal}function eT(e){let t=new AbortController;return setTimeout(()=>{t.abort(new DOMException(`signal timed out after ${e} ms`,`TimeoutError`))},e),t.signal}var tT=1,nT=2,rT=4,iT=8,aT=0,oT=12,sT=5,cT=7,lT=3,uT=3,dT=2,fT=1,pT=0,mT=3,hT=2,gT=2,_T=1,vT=0,yT;(function(e){e[e.TooShort=0]=`TooShort`,e[e.HeaderOverrun=1]=`HeaderOverrun`,e[e.MissingExtWords=2]=`MissingExtWords`,e[e.UnsupportedVersion=3]=`UnsupportedVersion`,e[e.InvalidHandle=4]=`InvalidHandle`,e[e.MalformedExt=5]=`MalformedExt`})(yT||={});var bT=class e extends Tb{constructor(e,t,n){super(19,e,n),this.name=`DataTrackDeserializeError`,this.reason=t,this.reasonName=yT[t]}static tooShort(){return new e(`Too short to contain a valid header`,yT.TooShort)}static headerOverrun(){return new e(`Header exceeds total packet length`,yT.HeaderOverrun)}static missingExtWords(){return new e(`Extension word indicator is missing`,yT.MissingExtWords)}static unsupportedVersion(t){return new e(`Unsupported version ${t}`,yT.UnsupportedVersion)}static invalidHandle(t){return new e(`invalid track handle: ${t.message}`,yT.InvalidHandle,{cause:t})}static malformedExt(t){return new e(`Extension with tag ${t} is malformed`,yT.MalformedExt)}},xT;(function(e){e[e.TooSmallForHeader=0]=`TooSmallForHeader`,e[e.TooSmallForPayload=1]=`TooSmallForPayload`})(xT||={});var ST=class e extends Tb{constructor(e,t,n){super(19,e,n),this.name=`DataTrackSerializeError`,this.reason=t,this.reasonName=xT[t]}static tooSmallForHeader(){return new e(`Buffer cannot fit header`,xT.TooSmallForHeader)}static tooSmallForPayload(){return new e(`Buffer cannot fit payload`,xT.TooSmallForPayload)}},CT=class{toBinary(){let e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),n=new DataView(t),r=this.toBinaryInto(n);if(e!==r)throw Error(`${this.constructor.name}.toBinary: written bytes (${r} bytes) not equal to allocated array buffer length (${e} bytes).`);return new Uint8Array(t)}},wT;(function(e){e[e.UserTimestamp=2]=`UserTimestamp`,e[e.E2ee=1]=`E2ee`})(wT||={});var TT=class extends CT{},ET=class e extends TT{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return tT+tT+e.lengthBytes}toBinaryInto(t){let n=0;t.setUint8(n,e.tag),n+=tT,t.setUint8(n,e.lengthBytes),n+=tT,t.setBigUint64(n,this.timestamp),n+=iT;let r=this.toBinaryLengthBytes();if(n!==r)throw Error(`DataTrackUserTimestampExtension.toBinaryInto: Wrote ${n} bytes but expected length was ${r} bytes`);return n}toJSON(){return{tag:e.tag,lengthBytes:e.lengthBytes,timestamp:this.timestamp}}};ET.tag=wT.UserTimestamp,ET.lengthBytes=8;var DT=class e extends TT{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return tT+tT+e.lengthBytes}toBinaryInto(t){let n=0;t.setUint8(n,e.tag),n+=tT,t.setUint8(n,e.lengthBytes),n+=tT,t.setUint8(n,this.keyIndex),n+=tT;for(let e=0;e<this.iv.length;e+=1)t.setUint8(n,this.iv[e]),n+=tT;let r=this.toBinaryLengthBytes();if(n!==r)throw Error(`DataTrackE2eeExtension.toBinaryInto: Wrote ${n} bytes but expected length was ${r} bytes`);return n}toJSON(){return{tag:e.tag,lengthBytes:e.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}};DT.tag=wT.E2ee,DT.lengthBytes=13;var OT=class e extends CT{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){let n=this.e2ee.toBinaryInto(e);t+=n}if(this.userTimestamp){let n=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=n}let n=this.toBinaryLengthBytes();if(t!==n)throw Error(`DataTrackExtensions.toBinaryInto: Wrote ${t} bytes but expected length was ${n} bytes`);return t}static fromBinary(t){let n=YS(t),r,i,a=0;for(;n.byteLength-a>=tT+tT;){let e=n.getUint8(a);a+=tT;let t=n.getUint8(a);if(a+=tT,e!==vT)switch(e){case wT.UserTimestamp:if(n.byteLength-a<ET.lengthBytes)throw bT.malformedExt(e);r=new ET(n.getBigUint64(a)),a+=t;break;case wT.E2ee:if(n.byteLength-a<DT.lengthBytes)throw bT.malformedExt(e);let o=n.getUint8(a),s=new Uint8Array(12);for(let e=0;e<s.length;e+=1){let t=a;t+=tT,t+=e*tT,s[e]=n.getUint8(t)}i=new DT(o,s),a+=t;break;default:if(n.byteLength-a<t)throw bT.malformedExt(e);a+=t;break}}return[new e({userTimestamp:r,e2ee:i}),n.byteLength]}toJSON(){return{userTimestamp:this.userTimestamp?.toJSON()??null,e2ee:this.e2ee?.toJSON()??null}}},kT={from(e){return{payload:e.payload,extensions:new OT({userTimestamp:e.userTimestamp?new ET(e.userTimestamp):void 0})}},lossyIntoFrame(e){return{payload:e.payload,userTimestamp:e.extensions.userTimestamp?.timestamp}}},AT=Symbol.for(`lk.track`),jT=Symbol.for(`lk.data-track`),MT=class{constructor(e,t,n){this.trackSymbol=AT,this.isLocal=!1,this.typeSymbol=jT,this.info=e,this.manager=t,this.publisherIdentity=n.publisherIdentity}subscribe(e){try{let[t]=this.manager.openSubscriptionStream(this.info.sid,e?.signal,e?.bufferSize);return t}catch(e){throw e}}},NT=class e extends CT{constructor(e){super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=e.extensions??new OT}extensionsMetrics(){let e=this.extensions.toBinaryLengthBytes(),t=Math.ceil(e/4);return{lengthBytes:e,lengthWords:t,paddingLengthBytes:t*4-e}}toBinaryLengthBytes(){let{lengthBytes:e,paddingLengthBytes:t}=this.extensionsMetrics(),n=oT;return e>0&&(n+=hT+e+t),n}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw ST.tooSmallForHeader();let t=aT<<sT,n;switch(this.marker){case PT.Inter:n=pT;break;case PT.Final:n=fT;break;case PT.Start:n=dT;break;case PT.Single:n=mT;break}t|=n<<lT;let{lengthBytes:r,lengthWords:i,paddingLengthBytes:a}=this.extensionsMetrics();r>0&&(t|=1<<gT);let o=0;if(e.setUint8(o,t),o+=tT,e.setUint8(o,0),o+=tT,e.setUint16(o,this.trackHandle),o+=nT,e.setUint16(o,this.sequence.value),o+=nT,e.setUint16(o,this.frameNumber.value),o+=nT,e.setUint32(o,this.timestamp.asTicks()),o+=rT,r>0){let t=i-1;e.setUint16(o,t),o+=nT;let n=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+o));o+=n;for(let t=0;t<a;t+=1)e.setUint8(o,0),o+=tT}let s=this.toBinaryLengthBytes();if(o!==s)throw Error(`DataTrackPacketHeader.toBinaryInto: Wrote ${o} bytes but expected length was ${s} bytes`);return s}static fromBinary(t){let n=YS(t);if(n.byteLength<oT)throw bT.tooShort();let r=0,i=n.getUint8(r);r+=tT;let a=i>>sT&cT;if(a>aT)throw bT.unsupportedVersion(a);let o;switch(i>>lT&uT){case dT:o=PT.Start;break;case fT:o=PT.Final;break;case mT:o=PT.Single;break;case pT:default:o=PT.Inter;break}let s=(i>>gT&_T)>0;r+=tT;let c;try{c=QS.fromNumber(n.getUint16(r))}catch(e){throw e instanceof ZS&&(e.isReason(XS.Reserved)||e.isReason(XS.TooLarge))?bT.invalidHandle(e):e}r+=nT;let l=KS.u16(n.getUint16(r));r+=nT;let u=KS.u16(n.getUint16(r));r+=nT;let d=qS.fromRtpTicks(n.getUint32(r));r+=rT;let f=new OT;if(s){if(n.byteLength-r<nT)throw bT.missingExtWords();let e=n.getUint16(r);r+=nT;let t=4*(e+1);if(r+t>n.byteLength)throw bT.headerOverrun();let i=new DataView(n.buffer,n.byteOffset+r,t),[a,o]=OT.fromBinary(i);f=a,r+=o}return[new e({marker:o,trackHandle:c,sequence:l,frameNumber:u,timestamp:d,extensions:f}),r]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}},PT;(function(e){e[e.Start=0]=`Start`,e[e.Inter=1]=`Inter`,e[e.Final=2]=`Final`,e[e.Single=3]=`Single`})(PT||={});var FT=class e extends CT{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0,n=this.header.toBinaryInto(e);if(t+=n,e.byteLength-t<this.payload.byteLength)throw ST.tooSmallForPayload();for(let n=0;n<this.payload.length;n+=1)e.setUint8(t,this.payload[n]),t+=tT;let r=this.toBinaryLengthBytes();if(t!==r)throw Error(`DataTrackPacket.toBinaryInto: Wrote ${t} bytes but expected length was ${r} bytes`);return r}static fromBinary(t){let n=YS(t),[r,i]=NT.fromBinary(n),a=n.buffer.slice(n.byteOffset+i,n.byteOffset+n.byteLength);return[new e(r,new Uint8Array(a)),n.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}},IT=Wv(Uv.DataTracks),LT=class e extends Tb{constructor(e,t,n,r){super(19,`Frame ${n} dropped: ${e}`,r),this.name=`DataTrackDepacketizerDropError`,this.reason=t,this.reasonName=RT[t],this.frameNumber=n}static interrupted(t,n){return new e(`Interrupted by the start of a new frame ${n}`,RT.Interrupted,t)}static unknownFrame(t){return new e(`Initial packet was never received.`,RT.UnknownFrame,t)}static bufferFull(t){return new e(`Reorder buffer is full.`,RT.BufferFull,t)}static incomplete(t,n,r){return new e(`Not all packets received before final packet. Received ${n} packets, expected ${r} packets.`,RT.Incomplete,t)}},RT;(function(e){e[e.Interrupted=0]=`Interrupted`,e[e.UnknownFrame=1]=`UnknownFrame`,e[e.BufferFull=2]=`BufferFull`,e[e.Incomplete=3]=`Incomplete`})(RT||={});var zT=class e{constructor(){this.partial=null}push(e,t){switch(e.header.marker){case PT.Single:return this.frameFromSingle(e,t);case PT.Start:return this.beginPartial(e,t);case PT.Inter:case PT.Final:return this.pushToPartial(e)}}reset(){this.partial=null}frameFromSingle(e,t){if(e.header.marker!==PT.Single)throw Error(`Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ${e.header.marker}.`);if(this.partial)if(t?.errorOnPartialFrames){let t=this.partial.frameNumber;throw this.reset(),LT.interrupted(t,e.header.frameNumber.value)}else IT.warn(`Data track frame ${this.partial.frameNumber} was interrupted by the start of a new frame, dropping.`);return this.reset(),{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){if(e.header.marker!==PT.Start)throw Error(`Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ${e.header.marker}.`);if(this.partial)if(t?.errorOnPartialFrames){let t=this.partial.frameNumber;throw this.reset(),LT.interrupted(t,e.header.frameNumber.value)}else IT.warn(`Data track frame ${this.partial.frameNumber} was interrupted by the start of a new frame ${e.header.frameNumber.value}, dropping.`);this.reset();let n=e.header.sequence;return this.partial={frameNumber:e.header.frameNumber.value,startSequence:n,extensions:e.header.extensions,payloads:new Map([[n.value,e.payload]])},null}pushToPartial(t){if(t.header.marker!==PT.Inter&&t.header.marker!==PT.Final)throw Error(`Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ${t.header.marker}.`);if(!this.partial)throw this.reset(),LT.unknownFrame(t.header.frameNumber.value);if(t.header.frameNumber.value!==this.partial.frameNumber){let e=this.partial.frameNumber;throw this.reset(),LT.interrupted(e,t.header.frameNumber.value)}if(this.partial.payloads.size>=e.MAX_BUFFER_PACKETS){let e=this.partial.frameNumber;throw this.reset(),LT.bufferFull(e)}return this.partial.payloads.has(t.header.sequence.value)&&IT.warn(`Data track frame ${this.partial.frameNumber} received duplicate packet for sequence ${t.header.sequence.value}, so replacing with newly received packet.`),this.partial.payloads.set(t.header.sequence.value,t.payload),t.header.marker===PT.Final?this.finalize(this.partial,t.header.sequence.value):null}finalize(e,t){let n=e.payloads.size,r=0;for(let t of e.payloads.values())r+=t.length;let i=new Uint8Array(r),a=e.startSequence.clone(),o=0;for(;;){let n=e.payloads.get(a.value);if(!n)break;e.payloads.delete(a.value);let r=i.length-o;if(n.length>r)throw Error(`Depacketizer.finalize: Expected at least ${n.length} more bytes left in the payload buffer, only got ${r} bytes.`);if(i.set(n,o),o+=n.length,a.value!=t){a.increment();continue}return this.reset(),{payload:i,extensions:e.extensions}}throw this.reset(),LT.incomplete(e.frameNumber,n,t-e.startSequence.value+1)}};zT.MAX_BUFFER_PACKETS=128;var BT;(function(e){e[e.Unpublished=0]=`Unpublished`,e[e.Timeout=1]=`Timeout`,e[e.Disconnected=2]=`Disconnected`,e[e.Cancelled=4]=`Cancelled`})(BT||={});var VT=class e extends Tb{constructor(e,t,n){super(22,e,n),this.name=`DataTrackSubscribeError`,this.reason=t,this.reasonName=BT[t]}static unpublished(){return new e(`The track has been unpublished and is no longer available`,BT.Unpublished)}static timeout(){return new e(`Request to subscribe to data track timed-out`,BT.Timeout)}static disconnected(){return new e(`Cannot subscribe to data track when disconnected`,BT.Disconnected)}static cancelled(){return new e(`Subscription to data track cancelled by caller`,BT.Cancelled)}},HT=Wv(Uv.DataTracks),UT=class{constructor(e){let t=e.e2eeManager!==null;if(e.info.usesE2ee!==t)throw Error(`IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider`);let n=new zT;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=e.e2eeManager??null,this.depacketizer=n}updateE2eeManager(e){this.e2eeManager=e}processPacket(e){return z(this,void 0,void 0,function*(){let t=this.depacketize(e);return t&&(yield this.decryptIfNeeded(t))||null})}depacketize(e){let t;try{t=this.depacketizer.push(e)}catch(e){return HT.warn(`Data frame depacketize error: ${e}`),null}return t}decryptIfNeeded(e){return z(this,void 0,void 0,function*(){let t=this.e2eeManager;if(!t)return e;let n=e.extensions?.e2ee??null;if(!n)return HT.error(`Missing E2EE meta`),null;let r;try{r=yield t.handleEncryptedData(e.payload,n.iv,this.publisherIdentity,n.keyIndex)}catch(e){return HT.error(`Error decrypting packet: ${e}`),null}return e.payload=r.payload,e})}},WT=Wv(Uv.DataTracks),GT=1e4,KT=16,qT=class extends iy.EventEmitter{constructor(e){super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=e?.e2eeManager??null}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.subscription.type===`active`&&t.subscription.pipeline.updateE2eeManager(e)}openSubscriptionStream(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:KT,r=null,i=new $x;return[new ReadableStream({start:n=>{r=n;let a=()=>{var e;n.error(VT.cancelled()),(e=i.reject)==null||e.call(i,VT.cancelled())};this.subscribeRequest(e,t).then(()=>z(this,void 0,void 0,function*(){var r;t?.addEventListener(`abort`,a);let o=this.descriptors.get(e);if(!o){WT.error(`Unknown track ${e}`);return}if(o.subscription.type!==`active`){WT.error(`Subscription for track ${e} is not active`);return}o.subscription.streamControllers.add(n),(r=i.resolve)==null||r.call(i)})).catch(e=>{var t;n.error(e),(t=i.reject)==null||t.call(i,e)}).finally(()=>{t?.removeEventListener(`abort`,a)})},cancel:()=>{if(!r){WT.warn(`ReadableStream subscribed to ${e} was not started.`);return}let t=this.descriptors.get(e);if(!t){WT.warn(`Unknown track ${e}, skipping cancel...`);return}if(t.subscription.type!==`active`){WT.warn(`Subscription for track ${e} is not active, skipping cancel...`);return}t.subscription.streamControllers.delete(r),t.subscription.streamControllers.size===0&&this.unSubscribeRequest(t.info.sid)}},new CountQueuingStrategy({highWaterMark:n})),i.promise]}subscribeRequest(e,t){return z(this,void 0,void 0,function*(){let n=this.descriptors.get(e);if(!n)throw Error(`Cannot subscribe to unknown track`);let r=(t,n,r)=>z(this,void 0,void 0,function*(){if(t.subscription.type===`active`)return;if(t.subscription.type!==`pending`)throw Error(`Descriptor for track ${e} is not pending, found ${t.subscription.type}`);let i=$w([n,r].filter(e=>e!==void 0)),a=new $x;t.subscription.completionFuture.promise.then(()=>a.resolve?.call(a)).catch(e=>a.reject?.call(a,e));let o=()=>{var e;if(t.subscription.type===`pending`){if(--t.subscription.pendingRequestCount,r?.aborted){t.subscription.cancel();return}if(t.subscription.pendingRequestCount<=0){t.subscription.cancel();return}(e=a.reject)==null||e.call(a,VT.cancelled())}};i.aborted&&o(),i.addEventListener(`abort`,o),yield a.promise,i.removeEventListener(`abort`,o)});switch(n.subscription.type){case`none`:{n.subscription={type:`pending`,completionFuture:new $x,pendingRequestCount:1,cancel:()=>{var t,r;let a=n.subscription;n.subscription={type:`none`},this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!1}),a.type===`pending`&&((r=(t=a.completionFuture).reject)==null||r.call(t,i.aborted?VT.timeout():VT.cancelled()))}},this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!0});let i=eT(GT);yield r(n,t,i);return}case`pending`:n.subscription.pendingRequestCount+=1,yield r(n,t);return;case`active`:return}})}querySubscribed(){return z(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).filter(e=>e.subscription.type===`active`).map(e=>[e.info,e.publisherIdentity])})}unSubscribeRequest(e){let t=this.descriptors.get(e);if(!t)throw Error(`Cannot subscribe to unknown track`);if(t.subscription.type!==`active`){WT.warn(`Unexpected descriptor state in unSubscribeRequest, expected active, found ${t.subscription?.type}`);return}for(let e of t.subscription.streamControllers)e.close();let n=t.subscription;t.subscription={type:`none`},this.subscriptionHandles.delete(n.subcriptionHandle),this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!1})}receiveSfuPublicationUpdates(e){return z(this,void 0,void 0,function*(){if(e.size===0)return;let t=new Map;for(let[n,r]of e.entries()){let e=new Set;for(let t of r)e.add(t.sid),!this.descriptors.has(t.sid)&&(yield this.handleTrackPublished(n,t));t.set(n,e)}for(let[e,n]of t.entries()){let t=Array.from(this.descriptors.entries()).filter(t=>{let[n,r]=t;return r.publisherIdentity===e}).map(e=>{let[t]=e;return t}).filter(e=>!n.has(e));for(let e of t)this.handleTrackUnpublished(e)}})}queryPublications(){return z(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return z(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){WT.error(`Existing descriptor for track ${t.sid}`);return}let n={info:t,publisherIdentity:e,subscription:{type:`none`}};this.descriptors.set(n.info.sid,n);let r=new MT(n.info,this,{publisherIdentity:e});this.emit(`trackPublished`,{track:r})})}handleTrackUnpublished(e){let t=this.descriptors.get(e);if(!t){WT.error(`Unknown track ${e}`);return}this.descriptors.delete(e),t.subscription.type===`active`&&this.subscriptionHandles.delete(t.subscription.subcriptionHandle),this.emit(`trackUnpublished`,{sid:e,publisherIdentity:t.publisherIdentity})}receivedSfuSubscriberHandles(e){for(let[t,n]of e.entries())this.registerSubscriberHandle(t,n)}registerSubscriberHandle(e,t){var n,r;let i=this.descriptors.get(t);if(!i){WT.error(`Unknown track ${t}`);return}switch(i.subscription.type){case`none`:WT.warn(`No subscription for ${t}`);return;case`active`:i.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return;case`pending`:{let a=new UT({info:i.info,publisherIdentity:i.publisherIdentity,e2eeManager:this.e2eeManager}),o=i.subscription;i.subscription={type:`active`,subcriptionHandle:e,pipeline:a,streamControllers:new Set},this.subscriptionHandles.set(e,t),(r=(n=o.completionFuture).resolve)==null||r.call(n)}}}packetReceived(e){return z(this,void 0,void 0,function*(){let t;try{[t]=FT.fromBinary(e)}catch(e){WT.error(`Failed to deserialize packet: ${e}`);return}let n=this.subscriptionHandles.get(t.header.trackHandle);if(!n){WT.warn(`Unknown subscriber handle ${t.header.trackHandle}`);return}let r=this.descriptors.get(n);if(!r){WT.error(`Missing descriptor for track ${n}`);return}if(r.subscription.type!==`active`){WT.warn(`Received packet for track ${n} without active subscription`);return}let i=yield r.subscription.pipeline.processPacket(t);if(i)for(let e of r.subscription.streamControllers){if(e.desiredSize!==null&&e.desiredSize<=0){WT.warn(`Cannot send frame to subscribers: readable stream is full (desiredSize is ${e.desiredSize}). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe().`);continue}let t=kT.lossyIntoFrame(i);e.enqueue(t)}})}resendSubscriptionUpdates(){for(let[e,t]of this.descriptors)t.subscription.type!==`none`&&this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!0})}handleRemoteParticipantDisconnected(e){var t,n;for(let r of this.descriptors.values())if(r.publisherIdentity===e)switch(r.subscription.type){case`none`:break;case`pending`:(n=(t=r.subscription.completionFuture).reject)==null||n.call(t,VT.disconnected());break;case`active`:this.unSubscribeRequest(r.info.sid);break}}shutdown(){var e,t;for(let n of this.descriptors.values())this.emit(`trackUnpublished`,{sid:n.info.sid,publisherIdentity:n.publisherIdentity}),n.subscription.type===`pending`&&((t=(e=n.subscription.completionFuture).reject)==null||t.call(e,VT.disconnected()));this.descriptors.clear()}},JT=class e extends Tb{constructor(e,t,n){super(19,e,n),this.name=`DataTrackPacketizerError`,this.reason=t,this.reasonName=YT[t]}static mtuTooShort(){return new e(`MTU is too short to send frame`,YT.MtuTooShort)}},YT;(function(e){e[e.MtuTooShort=0]=`MtuTooShort`})(YT||={});var XT=class e{constructor(e,t){this.sequence=KS.u16(0),this.frameNumber=KS.u16(0),this.clock=JS.rtpStartingNow(qS.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?PT.Single:e===0?PT.Start:e===t-1?PT.Final:PT.Inter}*packetize(t,n){let r=this.frameNumber.getThenIncrement(),i={marker:PT.Inter,trackHandle:this.handle,sequence:KS.u16(0),frameNumber:r,timestamp:n?.now??this.clock.now(),extensions:t.extensions},a=new NT(i).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw JT.mtuTooShort();let o=this.mtuSizeBytes-a,s=Math.ceil(t.payload.byteLength/o);for(let n=0,r=0;r<t.payload.byteLength;[n,r]=[n+1,r+o]){let a=this.sequence.getThenIncrement(),c=new NT(Object.assign(Object.assign({},i),{marker:e.computeFrameMarker(n,s),sequence:a})),l=Math.min(o,t.payload.byteLength-r);yield new FT(c,new Uint8Array(t.payload.buffer,t.payload.byteOffset+r,l))}}},ZT;(function(e){e[e.NotAllowed=0]=`NotAllowed`,e[e.DuplicateName=1]=`DuplicateName`,e[e.Timeout=2]=`Timeout`,e[e.LimitReached=3]=`LimitReached`,e[e.Disconnected=4]=`Disconnected`,e[e.Cancelled=5]=`Cancelled`,e[e.InvalidName=6]=`InvalidName`,e[e.Unknown=7]=`Unknown`})(ZT||={});var QT=class e extends Tb{constructor(e,t,n){super(21,e,n),this.name=`DataTrackPublishError`,this.reason=t,this.reasonName=ZT[t],this.rawMessage=n?.rawMessage}static notAllowed(t){return new e(`Data track publishing unauthorized`,ZT.NotAllowed,{rawMessage:t})}static duplicateName(t){return new e(`Track name already taken`,ZT.DuplicateName,{rawMessage:t})}static invalidName(t){return new e(`Track name is invalid`,ZT.InvalidName,{rawMessage:t})}static timeout(){return new e(`Publish data track timed-out. Does the LiveKit server support data tracks?`,ZT.Timeout)}static limitReached(t){return new e(`Data track publication limit reached`,ZT.LimitReached,{rawMessage:t})}static unknown(t,n){return new e(`Received RequestResponse for publishDataTrack, but reason was unrecognised (${t}, ${n})`,ZT.Unknown)}static disconnected(){return new e(`Room disconnected`,ZT.Disconnected)}static cancelled(){return new e(`Publish data track cancelled by caller`,ZT.Cancelled)}},$T;(function(e){e[e.TrackUnpublished=0]=`TrackUnpublished`,e[e.Dropped=1]=`Dropped`})($T||={});var eE=class e extends Tb{constructor(e,t,n){super(22,e,n),this.name=`DataTrackPushFrameError`,this.reason=t,this.reasonName=$T[t]}static trackUnpublished(){return new e(`Track is no longer published`,$T.TrackUnpublished)}static dropped(t){return new e(`Frame was dropped`,$T.Dropped,{cause:t})}},tE;(function(e){e[e.Packetizer=0]=`Packetizer`,e[e.Encryption=1]=`Encryption`})(tE||={});var nE=class e extends Tb{constructor(e,t,n){super(21,e,n),this.name=`DataTrackOutgoingPipelineError`,this.reason=t,this.reasonName=tE[t]}static packetizer(t){return new e(`Error packetizing frame`,tE.Packetizer,{cause:t})}static encryption(t){return new e(`Error encrypting frame`,tE.Encryption,{cause:t})}},rE=class e{constructor(e,t){this.trackSymbol=AT,this.isLocal=!0,this.typeSymbol=jT,this.handle=null,this.log=R,this.options=e,this.manager=t,this.log=Wv(Uv.DataTracks)}static withExplicitHandle(t,n,r){let i=new e(t,n);return i.handle=r,i}get info(){let e=this.descriptor;if(e?.type===`active`)return e.info}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return z(this,void 0,void 0,function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(e){throw e}})}isPublished(){return this.descriptor?.type===`active`&&this.descriptor.publishState!==`unpublished`}tryPush(e){if(!this.handle)throw eE.trackUnpublished();let t=kT.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(e){throw e}}unpublish(){return z(this,void 0,void 0,function*(){if(!this.handle){R.warn(`Data track "${this.options.name}" is not published, so unpublishing has no effect.`);return}try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}})}},iE=class e{constructor(t){this.e2eeManager=t.e2eeManager,this.packetizer=new XT(t.info.pubHandle,e.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return Qv(this,arguments,function*(){let t=yield Zv(this.encryptIfNeeded(e));try{yield Zv(yield*$v(ey(this.packetizer.packetize(t))))}catch(e){throw e instanceof JT?nE.packetizer(e):e}})}encryptIfNeeded(e){return z(this,void 0,void 0,function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(e){throw nE.encryption(e)}return e.payload=t.payload,e.extensions.e2ee=new DT(t.keyIndex,t.iv),e})}};iE.TRANSPORT_MTU_BYTES=16e3;var aE=Wv(Uv.DataTracks),oE={pending(){return{type:`pending`,completionFuture:new $x}},active(e,t){return{type:`active`,info:e,publishState:`published`,pipeline:new iE({info:e,e2eeManager:t}),unpublishingFuture:new $x}}},sE=1e4,cE=class e extends iy.EventEmitter{constructor(e){super(),this.handleAllocator=new $S,this.descriptors=new Map,this.e2eeManager=e?.e2eeManager??null}static withDescriptors(t){let n=new e;return n.descriptors=t,n}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.type===`active`&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){return this.descriptors.get(e)??null}tryProcessAndSend(e,t){return z(this,void 0,void 0,function*(){var n,r,i,a;let o=this.getDescriptor(e);if(o?.type!==`active`||o.publishState===`unpublished`)throw eE.trackUnpublished();if(o.publishState===`republishing`)throw eE.dropped(`Data track republishing`);try{try{for(var s=!0,c=ey(o.pipeline.processFrame(t)),l;l=yield c.next(),n=l.done,!n;s=!0){a=l.value,s=!1;let e=a;this.emit(`packetAvailable`,{bytes:e.toBinary()})}}catch(e){r={error:e}}finally{try{!s&&!n&&(i=c.return)&&(yield i.call(c))}finally{if(r)throw r.error}}}catch(e){throw eE.dropped(e)}})}publishRequest(e,t){return z(this,void 0,void 0,function*(){let n=this.handleAllocator.get();if(!n)throw QT.limitReached();let r=eT(sE),i=t?$w([t,r]):r;if(this.descriptors.has(n))throw Error(`Descriptor for handle already exists`);let a=oE.pending();this.descriptors.set(n,a);let o=()=>{var e,t;let i=this.descriptors.get(n);if(!i){aE.warn(`No descriptor for ${n}`);return}this.descriptors.delete(n),this.emit(`sfuUnpublishRequest`,{handle:n}),i.type===`pending`&&((t=(e=i.completionFuture).reject)==null||t.call(e,r.aborted?QT.timeout():QT.cancelled()))};return i.aborted?(o(),a.completionFuture.promise.then(()=>n)):(i.addEventListener(`abort`,o),this.emit(`sfuPublishRequest`,{handle:n,name:e.name,usesE2ee:this.e2eeManager!==null}),yield a.completionFuture.promise,i.removeEventListener(`abort`,o),this.emit(`trackPublished`,{track:rE.withExplicitHandle(e,this,n)}),n)})}queryPublished(){return Array.from(this.descriptors.values()).filter(e=>e.type===`active`).map(e=>e.info)}unpublishRequest(e){return z(this,void 0,void 0,function*(){let t=this.descriptors.get(e);if(!t){aE.warn(`No descriptor for ${e}`);return}if(t.type!==`active`){aE.warn(`Track ${e} not active`);return}this.emit(`sfuUnpublishRequest`,{handle:e}),yield t.unpublishingFuture.promise,this.emit(`trackUnpublished`,{sid:t.info.sid})})}receivedSfuPublishResponse(e,t){var n,r,i,a;let o=this.descriptors.get(e);if(!o){aE.warn(`No descriptor for ${e}`);return}switch(this.descriptors.delete(e),o.type){case`pending`:if(t.type===`ok`){let e=t.data,i=e.usesE2ee?this.e2eeManager:null;this.descriptors.set(e.pubHandle,oE.active(e,i)),(r=(n=o.completionFuture).resolve)==null||r.call(n)}else (a=(i=o.completionFuture).reject)==null||a.call(i,t.error);return;case`active`:if(o.publishState!==`republishing`){aE.warn(`Track ${e} already active`);return}if(t.type===`error`){aE.warn(`Republish failed for track ${e}`);return}aE.debug(`Track ${e} republished`),o.info.sid=t.data.sid,o.publishState=`published`,this.descriptors.set(o.info.pubHandle,o)}}receivedSfuUnpublishResponse(e){var t,n;let r=this.descriptors.get(e);if(!r){aE.warn(`No descriptor for ${e}`);return}if(this.descriptors.delete(e),r.type!==`active`){aE.warn(`Track ${e} not active`);return}r.publishState=`unpublished`,(n=(t=r.unpublishingFuture).resolve)==null||n.call(t)}sfuWillRepublishTracks(){var e,t;for(let[n,r]of this.descriptors.entries())switch(r.type){case`pending`:this.descriptors.delete(n),(t=(e=r.completionFuture).reject)==null||t.call(e,QT.disconnected());break;case`active`:r.publishState=`republishing`,this.emit(`sfuPublishRequest`,{handle:r.info.pubHandle,name:r.info.name,usesE2ee:r.info.usesE2ee})}}shutdown(){return z(this,void 0,void 0,function*(){var e,t,n,r;for(let i of this.descriptors.values())switch(i.type){case`pending`:(t=(e=i.completionFuture).reject)==null||t.call(e,QT.disconnected());break;case`active`:(r=(n=i.unpublishingFuture).resolve)==null||r.call(n),yield this.unpublishRequest(i.info.pubHandle);break}this.descriptors.clear()})}},lE=class extends q{constructor(e,t,n,r,i){super(e,n,i),this.sid=t,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?W.Muted:W.Unmuted,this))}setMediaStream(e){this.mediaStream=e;let t=n=>{n.track===this._mediaStreamTrack&&(e.removeEventListener(`removetrack`,t),this.receiver&&`playoutDelayHint`in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(W.Ended,this))};e.addEventListener(`removetrack`,t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return z(this,void 0,void 0,function*(){if(this.receiver?.getStats)return yield this.receiver.getStats()})}setPlayoutDelay(e){this.receiver?`playoutDelayHint`in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn(`Playout delay not supported in this browser`):this.log.warn(`Cannot set playout delay, track already ended`)}getPlayoutDelay(){if(this.receiver){if(`playoutDelayHint`in this.receiver)return this.receiver.playoutDelayHint;this.log.warn(`Playout delay not supported in this browser`)}else this.log.warn(`Cannot get playout delay, track already ended`);return 0}startMonitor(){this.monitorInterval||=setInterval(()=>this.monitorReceiver(),$C),ax()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){let e=()=>{this.timeSyncHandle=requestAnimationFrame(()=>e());let t=this.receiver?.getSynchronizationSources()[0];if(t){let{timestamp:e,rtpTimestamp:n}=t;n&&this.rtpTimestamp!==n&&(this.emit(W.TimeSyncUpdate,{timestamp:e,rtpTimestamp:n}),this.rtpTimestamp=n)}};e()}},uE=class extends lE{constructor(e,t,n,r,i,a){super(e,t,q.Kind.Audio,n,a),this.monitorReceiver=()=>z(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=ew(e,this.prevStats)),this.prevStats=e}),this.audioContext=r,this.webAudioPluginNodes=[],i&&(this.sinkId=i.deviceId)}setVolume(e){var t;for(let n of this.attachedElements)this.audioContext?(t=this.gainNode)==null||t.gain.setTargetAtTime(e,0,.1):n.volume=e;Ix()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Ix())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return z(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(Tx(t))return t.setSinkId(e)}))})}attach(e){let t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Tx(e)&&e.setSinkId(this.sinkId).catch(e=>{this.log.error(`Failed to set sink id on remote audio track`,e,this.logContext)}),this.audioContext&&t&&(this.log.debug(`using audio context mapping`,this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{n.connect(e),n=e}),this.gainNode=e.createGain(),n.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!==`running`&&e.resume().then(()=>{e.state!==`running`&&this.emit(W.AudioPlaybackFailed,Error(`Audio Context couldn't be started automatically`))}).catch(e=>{this.emit(W.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;(e=this.gainNode)==null||e.disconnect(),(t=this.sourceNode)==null||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return z(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t;return e.forEach(e=>{e.type===`inbound-rtp`&&(t={type:`audio`,streamId:e.id,timestamp:e.timestamp,jitter:e.jitter,bytesReceived:e.bytesReceived,concealedSamples:e.concealedSamples,concealmentEvents:e.concealmentEvents,silentConcealedSamples:e.silentConcealedSamples,silentConcealmentEvents:e.silentConcealmentEvents,totalAudioEnergy:e.totalAudioEnergy,totalSamplesDuration:e.totalSamplesDuration})}),t})}},dE=100,fE=class extends lE{constructor(e,t,n,r,i){super(e,t,q.Kind.Video,n,i),this.elementInfos=[],this.monitorReceiver=()=>z(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=ew(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=OC(()=>{this.updateDimensions()},dE),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug(`setStreamState`,e),this.isAdaptiveStream&&e===q.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?hx(this._mediaStreamTrack,t):mx(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){let t=new pE(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn(`visibility resize observer not triggered`,this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn(`stopObservingElementInfo ignored`,this.logContext);return}let t=this.elementInfos.filter(t=>t===e);for(let e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter(t=>t!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(let e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){return this.prevStats?.decoderImplementation}getReceiverStats(){return z(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t,n=``,r=new Map;return e.forEach(e=>{e.type===`inbound-rtp`?(n=e.codecId,t={type:`video`,streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):e.type===`codec`&&r.set(e.id,e)}),t&&n!==``&&r.get(n)&&(t.mimeType=r.get(n).mimeType),t})}stopObservingElement(e){let t=this.elementInfos.filter(t=>t.element===e);for(let e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return z(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){let t=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),n=this.adaptiveStreamSettings?.pauseVideoInBackground??!0?this.isInBackground:!1,r=this.elementInfos.some(e=>e.pictureInPicture),i=this.elementInfos.some(e=>e.visible)&&!n||r;if(!(this.lastVisible===i&&!e)){if(!i&&Date.now()-t<dE){Rb.setTimeout(()=>{this.updateVisibility()},dE);return}this.lastVisible=i,this.emit(W.VisibilityChanged,i,this)}}updateDimensions(){let e=0,t=0,n=this.getPixelDensity();for(let r of this.elementInfos){let i=r.width()*n,a=r.height()*n;i+a>e+t&&(e=i,t=a)}this.lastDimensions?.width===e&&this.lastDimensions?.height===t||(this.lastDimensions={width:e,height:t},this.emit(W.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){let e=this.adaptiveStreamSettings?.pixelDensity;return e===`screen`?Vx():e||(Vx()>2?2:1)}},pE=class{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;let{target:n,isIntersecting:r}=e;n===this.element&&(this.isIntersecting=r,this.isPiP=mE(this.element),this.visibilityChangedAt=Date.now(),(t=this.handleVisibilityChanged)==null||t.call(this))},this.onEnterPiP=()=>{var e,t;(e=window.documentPictureInPicture?.window)==null||e.addEventListener(`pagehide`,this.onLeavePiP),this.isPiP=mE(this.element),(t=this.handleVisibilityChanged)==null||t.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=mE(this.element),(e=this.handleVisibilityChanged)==null||e.call(this)},this.element=e,this.isIntersecting=t??hE(e),this.isPiP=Fx()&&mE(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t;this.isIntersecting=hE(this.element),this.isPiP=mE(this.element),this.element.handleResize=()=>{var e;(e=this.handleResize)==null||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Jx().observe(this.element),Kx().observe(this.element),this.element.addEventListener(`enterpictureinpicture`,this.onEnterPiP),this.element.addEventListener(`leavepictureinpicture`,this.onLeavePiP),(e=window.documentPictureInPicture)==null||e.addEventListener(`enter`,this.onEnterPiP),(t=window.documentPictureInPicture?.window)==null||t.addEventListener(`pagehide`,this.onLeavePiP)}stopObserving(){var e,t,n,r;(e=Jx())==null||e.unobserve(this.element),(t=Kx())==null||t.unobserve(this.element),this.element.removeEventListener(`enterpictureinpicture`,this.onEnterPiP),this.element.removeEventListener(`leavepictureinpicture`,this.onLeavePiP),(n=window.documentPictureInPicture)==null||n.removeEventListener(`enter`,this.onEnterPiP),(r=window.documentPictureInPicture?.window)==null||r.removeEventListener(`pagehide`,this.onLeavePiP)}};function mE(e){return document.pictureInPictureElement===e?!0:window.documentPictureInPicture?.window?hE(e,window.documentPictureInPicture?.window):!1}function hE(e,t){let n=t||window,r=e.offsetTop,i=e.offsetLeft,a=e.offsetWidth,o=e.offsetHeight,{hidden:s}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)e=e.offsetParent,r+=e.offsetTop,i+=e.offsetLeft;return r<n.pageYOffset+n.innerHeight&&i<n.pageXOffset+n.innerWidth&&r+o>n.pageYOffset&&i+a>n.pageXOffset&&!s&&c!==`none`}var gE=class extends iy.EventEmitter{constructor(e,t,n,r){super(),this.metadataMuted=!1,this.encryption=L.NONE,this.log=R,this.handleMuted=()=>{this.emit(W.Muted)},this.handleUnmuted=()=>{this.emit(W.Unmuted)},this.log=Wv(r?.loggerName??Uv.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=q.Source.Unknown}setTrack(e){this.track&&(this.track.off(W.Muted,this.handleMuted),this.track.off(W.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(W.Muted,this.handleMuted),e.on(W.Unmuted,this.handleUnmuted))}get logContext(){return Object.assign(Object.assign({},this.loggerContextCb?.call(this)),K(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==L.NONE}get audioTrack(){if(uS(this.track))return this.track}get videoTrack(){if(dS(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=q.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===q.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug(`update publication info`,Object.assign(Object.assign({},this.logContext),{info:e}))}};(function(e){(function(e){e.Desired=`desired`,e.Subscribed=`subscribed`,e.Unsubscribed=`unsubscribed`})(e.SubscriptionStatus||={}),(function(e){e.Allowed=`allowed`,e.NotAllowed=`not_allowed`})(e.PermissionStatus||={})})(gE||={});var _E=class extends gE{get isUpstreamPaused(){return this.track?.isUpstreamPaused}constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(W.Ended)},this.handleCpuConstrained=()=>{this.track&&dS(this.track)&&this.emit(W.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(W.Ended,this.handleTrackEnded),this.track.off(W.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(W.Ended,this.handleTrackEnded),e.on(W.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return z(this,void 0,void 0,function*(){return this.track?.mute()})}unmute(){return z(this,void 0,void 0,function*(){return this.track?.unmute()})}pauseUpstream(){return z(this,void 0,void 0,function*(){yield this.track?.pauseUpstream()})}resumeUpstream(){return z(this,void 0,void 0,function*(){yield this.track?.resumeUpstream()})}getTrackFeatures(){if(uS(this.track)){let e=this.track.getSourceTrackSettings(),t=new Set;return e.autoGainControl&&t.add(Ig.TF_AUTO_GAIN_CONTROL),e.echoCancellation&&t.add(Ig.TF_ECHO_CANCELLATION),e.noiseSuppression&&t.add(Ig.TF_NOISE_SUPPRESSION),e.channelCount&&e.channelCount>1&&t.add(Ig.TF_STEREO),this.options?.dtx||t.add(Ig.TF_NO_DTX),this.track.enhancedNoiseCancellation&&t.add(Ig.TF_ENHANCED_NOISE_CANCELLATION),Array.from(t.values())}else return[]}};function vE(e,t){return z(this,void 0,void 0,function*(){e??={};let n=!1,{audioProcessor:r,videoProcessor:i,optionsWithoutProcessor:a}=sx(e),o=a.audio,s=a.video;if(r&&typeof a.audio==`object`&&(a.audio.processor=r),i&&typeof a.video==`object`&&(a.video.processor=i),e.audio&&typeof a.audio==`object`&&typeof a.audio.deviceId==`string`){let e=a.audio.deviceId;a.audio.deviceId={exact:e},n=!0,o=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:e}})}if(a.video&&typeof a.video==`object`&&typeof a.video.deviceId==`string`){let e=a.video.deviceId;a.video.deviceId={exact:e},n=!0,s=Object.assign(Object.assign({},a.video),{deviceId:{ideal:e}})}a.audio===!0?a.audio={deviceId:`default`}:typeof a.audio==`object`&&a.audio!==null&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||`default`})),a.video===!0?a.video={deviceId:`default`}:typeof a.video==`object`&&!a.video.deviceId&&(a.video.deviceId=`default`);let c=Yb(a,zC,BC),l=Zb(c),u=navigator.mediaDevices.getUserMedia(l);a.audio&&(US.userMediaPromiseMap.set(`audioinput`,u),u.catch(()=>US.userMediaPromiseMap.delete(`audioinput`))),a.video&&(US.userMediaPromiseMap.set(`videoinput`,u),u.catch(()=>US.userMediaPromiseMap.delete(`videoinput`)));try{let e=yield u;return yield Promise.all(e.getTracks().map(n=>z(this,void 0,void 0,function*(){let a=n.kind===`audio`,o=a?c.audio:c.video;(typeof o==`boolean`||!o)&&(o={});let s,u=a?l.audio:l.video;typeof u!=`boolean`&&(s=u);let d=n.getSettings().deviceId;s?.deviceId&&tS(s.deviceId)!==d?s.deviceId=d:s||={deviceId:d};let f=lw(n,s,t);return f.kind===q.Kind.Video?f.source=q.Source.Camera:f.kind===q.Kind.Audio&&(f.source=q.Source.Microphone),f.mediaStream=e,uS(f)&&r?yield f.setProcessor(r):dS(f)&&i&&(yield f.setProcessor(i)),f})))}catch(r){if(!n)throw r;return vE(Object.assign(Object.assign({},e),{audio:o,video:s}),t)}})}function yE(e){return z(this,void 0,void 0,function*(){return(yield vE({audio:e??!0,video:!1}))[0]})}var bE;(function(e){e.Excellent=`excellent`,e.Good=`good`,e.Poor=`poor`,e.Lost=`lost`,e.Unknown=`unknown`})(bE||={});function xE(e){switch(e){case jg.EXCELLENT:return bE.Excellent;case jg.GOOD:return bE.Good;case jg.POOR:return bE.Poor;case jg.LOST:return bE.Lost;default:return bE.Unknown}}var SE=class extends iy.EventEmitter{get logContext(){var e;return Object.assign({},((e=this.loggerOptions)?.loggerContextCb)?.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){return this.permissions?.agent||this.kind===Hg.AGENT}get isActive(){return this.participantInfo?.state===Vg.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,r,i,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Hg.STANDARD;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=bE.Unknown,this.log=R,this.log=Wv(a?.loggerName??Uv.Participant),this.loggerOptions=a,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=i??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(let[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(let[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new $x,this.once(H.Active,()=>{var e,t;(t=(e=this.activeFuture)?.resolve)==null||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){return!(this.getTrackPublication(q.Source.Camera)?.isMuted??!0)}get isMicrophoneEnabled(){return!(this.getTrackPublication(q.Source.Microphone)?.isMuted??!0)}get isScreenShareEnabled(){return!!this.getTrackPublication(q.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===Vg.ACTIVE&&this.participantInfo?.state!==Vg.ACTIVE&&this.emit(H.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){let t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(H.ParticipantMetadataChanged,n)}_setName(e){let t=this.name!==e;this.name=e,t&&this.emit(H.ParticipantNameChanged,e)}_setAttributes(e){let t=ox(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(H.AttributesChanged,t)}setPermissions(e){let t=this.permissions,n=e.canPublish!==this.permissions?.canPublish||e.canSubscribe!==this.permissions?.canSubscribe||e.canPublishData!==this.permissions?.canPublishData||e.hidden!==this.permissions?.hidden||e.recorder!==this.permissions?.recorder||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>e!==this.permissions?.canPublishSources[t])||e.canSubscribeMetrics!==this.permissions?.canSubscribeMetrics;return this.permissions=e,n&&this.emit(H.ParticipantPermissionsChanged,t),n}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(H.IsSpeakingChanged,e))}setConnectionQuality(e){let t=this._connectionQuality;this._connectionQuality=xE(e),t!==this._connectionQuality&&this.emit(H.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&=((t=(e=this.activeFuture).reject)==null||t.call(e,Error(`Participant disconnected`)),void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>uS(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(W.Muted,()=>{this.emit(H.TrackMuted,e)}),e.on(W.Unmuted,()=>{this.emit(H.TrackUnmuted,e)});let t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case q.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case q.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}};function CE(e){if(!e.participantSid&&!e.participantIdentity)throw Error(`Invalid track permission, must provide at least one of participantIdentity and participantSid`);return new hv({participantIdentity:e.participantIdentity??``,participantSid:e.participantSid??``,allTracks:e.allowAll??!1,trackSids:e.allowedTrackSids||[]})}var wE=class extends SE{constructor(e,t,n,r,i,a,o){super(e,t,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=L.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||=new $x},this.handleReconnected=()=>{var e,t;(t=(e=this.reconnectFuture)?.resolve)==null||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,n,r,i,a;this.reconnectFuture&&=(this.reconnectFuture.promise.catch(e=>this.log.warn(e.message,this.logContext)),(t=(e=this.reconnectFuture)?.reject)==null||t.call(e,Error(`Got disconnected during reconnection attempt`)),void 0),this.signalConnectedFuture&&=((r=(n=this.signalConnectedFuture).reject)==null||r.call(n,Error(`Got disconnected without signal connected`)),void 0),(a=(i=this.activeAgentFuture)?.reject)==null||a.call(i,Error(`Got disconnected without active agent present`)),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,n;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||=new $x,(n=(t=this.signalConnectedFuture).resolve)==null||n.call(t)},this.handleSignalRequestResponse=e=>{let{requestId:t,reason:n,message:r}=e,i=this.pendingSignalRequests.get(t);switch(i&&(n!==kv.OK&&i.reject(new Nb(r,n)),this.pendingSignalRequests.delete(t)),e.request.case){case`publishDataTrack`:{let t;switch(e.reason){case kv.NOT_ALLOWED:t=QT.notAllowed(e.message);break;case kv.DUPLICATE_NAME:t=QT.duplicateName(e.message);break;case kv.INVALID_NAME:t=QT.invalidName(e.message);break;case kv.LIMIT_EXCEEDED:t=QT.limitReached(e.message);break;default:t=QT.unknown(e.reason,e.message);return}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(e.request.value.pubHandle,{type:`error`,error:t});break}}},this.handleDataPacket=e=>{switch(e.value.case){case`rpcResponse`:let t=e.value.value,n=null,r=null;t.value.case===`payload`?n=t.value.value:t.value.case===`error`&&(r=YC.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,n,r);break;case`rpcAck`:let i=e.value.value;this.handleIncomingRpcAck(i.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug(`updating track subscription permissions`,Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(e=>CE(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{if(t===void 0&&(t=!0),!e.sid){this.log.error(`could not update mute status for unpublished track`,Object.assign(Object.assign({},this.logContext),K(e)));return}this.engine.updateMuteStatus(e.sid,t)},this.onTrackUpstreamPaused=e=>{this.log.debug(`upstream paused`,Object.assign(Object.assign({},this.logContext),K(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug(`upstream resumed`,Object.assign(Object.assign({},this.logContext),K(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{let t=this.audioTrackPublications.get(e.sid);if(!t){this.log.warn(`Could not update local audio track settings, missing publication for track ${e.sid}`,this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures())},this.onTrackCpuConstrained=(e,t)=>{this.log.debug(`track cpu constrained`,Object.assign(Object.assign({},this.logContext),K(t))),this.emit(H.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>z(this,void 0,void 0,function*(){var t,n,r,i;if(!this.roomOptions?.dynacast)return;let a=this.videoTrackPublications.get(e.trackSid);if(!a){this.log.warn(`received subscribed quality update for unknown track`,Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));return}if(!a.videoTrack)return;let o=yield a.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var s=!0,c=ey(o),l;l=yield c.next(),t=l.done,!t;s=!0){i=l.value,s=!1;let e=i;Ub(e)&&(this.log.debug(`publish ${e} for ${a.videoTrack.sid}`,Object.assign(Object.assign({},this.logContext),K(a))),yield this.publishAdditionalCodecForTrack(a.videoTrack,e,a.options))}}catch(e){n={error:e}}finally{try{!s&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(n)throw n.error}}}),this.handleLocalTrackUnpublished=e=>{let t=this.trackPublications.get(e.trackSid);if(!t){this.log.warn(`received unpublished event for unknown track`,Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));return}this.unpublishTrack(t.track)},this.handleTrackEnded=e=>z(this,void 0,void 0,function*(){if(e.source===q.Source.ScreenShare||e.source===q.Source.ScreenShareAudio)this.log.debug(`unpublishing local track due to TrackEnded`,Object.assign(Object.assign({},this.logContext),K(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(pS(e)||fS(e))try{if(Fx())try{let t=yield navigator==null?void 0:navigator.permissions.query({name:e.source===q.Source.Camera?`camera`:`microphone`});if(t&&t.state===`denied`)throw this.log.warn(`user has revoked access to ${e.source}`,Object.assign(Object.assign({},this.logContext),K(e))),t.onchange=()=>{t.state!==`denied`&&(e.isMuted||e.restartTrack(),t.onchange=null)},Error(`GetUserMedia Permission denied`)}catch{}e.isMuted||(this.log.debug(`track ended, attempting to use a different device`,Object.assign(Object.assign({},this.logContext),K(e))),pS(e)?yield e.restartTrack({deviceId:`default`}):yield e.restartTrack())}catch{this.log.warn(`could not restart track, muting instead`,Object.assign(Object.assign({},this.logContext),K(e))),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=r,this.setupEngine(n),this.activeDeviceMap=new Map([[`audioinput`,`default`],[`videoinput`,`default`],[`audiooutput`,`default`]]),this.pendingSignalRequests=new Map,this.rpcHandlers=i,this.roomOutgoingDataStreamManager=a,this.roomOutgoingDataTrackManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==L.NONE}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.on(U.RemoteMute,(e,t)=>{let n=this.trackPublications.get(e);!n||!n.track||(t?n.mute():n.unmute())}),this.signalConnectedFuture?.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(U.Connected,this.handleReconnected).on(U.SignalConnected,this.handleSignalConnected).on(U.SignalRestarted,this.handleReconnected).on(U.SignalResumed,this.handleReconnected).on(U.Restarting,this.handleReconnecting).on(U.Resuming,this.handleReconnecting).on(U.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(U.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(U.Closing,this.handleClosing).on(U.SignalRequestResponse,this.handleSignalRequestResponse).on(U.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return z(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return z(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return z(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return z(this,arguments,void 0,function(e){var t=this;let{metadata:n,name:r,attributes:i}=e;return function*(){return new gb((e,a)=>z(t,void 0,void 0,function*(){try{let t=!1,o=yield this.engine.client.sendUpdateLocalMetadata(n??this.metadata??``,r??this.name??``,i),s=performance.now();for(this.pendingSignalRequests.set(o,{resolve:e,reject:e=>{a(e),t=!0},values:{name:r,metadata:n,attributes:i}});performance.now()-s<5e3&&!t;){if((!r||this.name===r)&&(!n||this.metadata===n)&&(!i||Object.entries(i).every(e=>{let[t,n]=e;return this.attributes[t]===n||n===``&&!this.attributes[t]}))){this.pendingSignalRequests.delete(o),e();return}yield yx(50)}a(new Nb(`Request to update local metadata timed out`,`TimeoutError`))}catch(e){e instanceof Error?a(e):a(Error(String(e)))}}))}()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(q.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(q.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(q.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return z(this,void 0,void 0,function*(){this.encryptionType=e?L.GCM:L.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,r){return z(this,void 0,void 0,function*(){this.log.debug(`setTrackEnabled`,Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let i=this.getTrackPublication(e);if(t)if(i)yield i.unmute();else{let t;if(this.pendingPublishing.has(e)){let t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info(`waiting for pending publication promise timed out`,Object.assign(Object.assign({},this.logContext),{source:e})),yield t?.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case q.Source.Camera:t=yield this.createTracks({video:n??!0});break;case q.Source.Microphone:t=yield this.createTracks({audio:n??!0});break;case q.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},n));break;default:throw new Ob(e)}}catch(n){throw t?.forEach(e=>{e.stop()}),n instanceof Error&&this.emit(H.MediaDevicesError,n,tx(e)),this.pendingPublishing.delete(e),n}for(let r of t){let t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===q.Source.Microphone&&uS(r)&&t.preConnectBuffer&&(this.log.info(`starting preconnect buffer for microphone`,Object.assign({},this.logContext)),r.startPreConnectBuffer())}try{let e=[];for(let n of t)this.log.info(`publishing track`,Object.assign(Object.assign({},this.logContext),K(n))),e.push(this.publishTrack(n,r));let n=yield Promise.all(e);[i]=n}catch(e){throw t?.forEach(e=>{e.stop()}),e}finally{this.pendingPublishing.delete(e)}}else if(!i?.track&&this.pendingPublishing.has(e)&&(i=yield this.waitForPendingPublicationOfSource(e),i||this.log.info(`waiting for pending publication promise timed out`,Object.assign(Object.assign({},this.logContext),{source:e}))),i&&i.track)if(e===q.Source.ScreenShare){i=yield this.unpublishTrack(i.track);let e=this.getTrackPublication(q.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield i.mute();return i})}enableCameraAndMicrophone(){return z(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(q.Source.Camera)||this.pendingPublishing.has(q.Source.Microphone))){this.pendingPublishing.add(q.Source.Camera),this.pendingPublishing.add(q.Source.Microphone);try{let e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete(q.Source.Camera),this.pendingPublishing.delete(q.Source.Microphone)}}})}createTracks(e){return z(this,void 0,void 0,function*(){e??={};let t=Yb(e,this.roomOptions?.audioCaptureDefaults,this.roomOptions?.videoCaptureDefaults);try{return(yield vE(t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(e=>(uS(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=q.Source.Microphone,this.emit(H.AudioStreamAcquired)),dS(e)&&(this.cameraError=void 0,e.source=q.Source.Camera),e))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}})}createScreenTracks(e){return z(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Db(`getDisplayMedia not supported`);e.resolution===void 0&&!jx()&&(e.resolution=Jb.h1080fps30.resolution);let t=nx(e),n=yield navigator.mediaDevices.getDisplayMedia(t),r=n.getVideoTracks();if(r.length===0)throw new Ob(`no video track found`);let i=new Dw(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});i.source=q.Source.ScreenShare,e.contentHint&&(i.mediaStreamTrack.contentHint=e.contentHint);let a=[i];if(n.getAudioTracks().length>0){this.emit(H.AudioStreamAcquired);let e=new cw(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=q.Source.ScreenShareAudio,a.push(e)}return a})}publishTrack(e,t){return z(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return z(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){pS(e)&&e.setAudioContext(n.audioContext),yield n.reconnectFuture?.promise,n.republishPromise&&!r&&(yield n.republishPromise),lS(e)&&n.pendingPublishPromises.has(e)&&(yield n.pendingPublishPromises.get(e));let i;if(e instanceof MediaStreamTrack)i=e.getConstraints();else{i=e.constraints;let t;switch(e.source){case q.Source.Microphone:t=`audioinput`;break;case q.Source.Camera:t=`videoinput`}t&&n.activeDeviceMap.has(t)&&(i=Object.assign(Object.assign({},i),{deviceId:n.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case`audio`:e=new cw(e,i,!0,n.audioContext,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;case`video`:e=new Dw(e,i,!0,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;default:throw new Ob(`unsupported MediaStreamTrack kind ${e.kind}`)}else e.updateLoggerOptions({loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});let a;if(n.trackPublications.forEach(t=>{t.track&&t.track===e&&(a=t)}),a)return n.log.warn(`track has already been published, skipping`,Object.assign(Object.assign({},n.logContext),K(a))),a;let o=Object.assign(Object.assign({},n.roomOptions.publishDefaults),t),s=`channelCount`in e.mediaStreamTrack.getSettings()&&e.mediaStreamTrack.getSettings().channelCount===2||e.mediaStreamTrack.getConstraints().channelCount===2,c=o.forceStereo??s;c&&(o.dtx===void 0&&n.log.info(`Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.`,Object.assign(Object.assign({},n.logContext),K(e))),o.red===void 0&&n.log.info(`Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work.`),o.dtx??=!1,o.red??=!1),!Px()&&n.roomOptions.e2ee&&(n.log.info(`End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2`,Object.assign({},n.logContext)),o.simulcast=!1),o.source&&(e.source=o.source);let l=new Promise((t,r)=>z(n,void 0,void 0,function*(){try{if(this.engine.client.currentState!==oC.CONNECTED){this.log.debug(`deferring track publication until signal is connected`,Object.assign(Object.assign({},this.logContext),{track:K(e)}));let n=!1,i=setTimeout(()=>{n=!0,e.stop(),r(new Mb(`publishing rejected as engine not connected within timeout`,408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(i),n)return;t(yield this.publish(e,o,c))}else try{t(yield this.publish(e,o,c))}catch(e){r(e)}}catch(e){r(e)}}));n.pendingPublishPromises.set(e,l);try{return yield l}catch(e){throw e}finally{n.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||=new $x,this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn(`no permissions present for publishing track`,Object.assign(Object.assign({},this.logContext),K(e))),!1;let{canPublish:t,canPublishSources:n}=this.permissions;return t&&(n.length===0||n.map(e=>cx(e)).includes(e.source))?!0:(this.log.warn(`insufficient permissions to publish`,Object.assign(Object.assign({},this.logContext),K(e))),!1)}publish(e,t,n){return z(this,void 0,void 0,function*(){if(!this.hasPermissionsToPublish(e))throw new Mb(`failed to publish track, insufficient permissions`,403);Array.from(this.trackPublications.values()).find(t=>lS(e)&&t.source===e.source)&&e.source!==q.Source.Unknown&&this.log.info(`publishing a second track with the same source: ${e.source}`,Object.assign(Object.assign({},this.logContext),K(e))),t.stopMicTrackOnMute&&uS(e)&&(e.stopOnMute=!0),e.source===q.Source.ScreenShare&&Dx()&&(t.simulcast=!1),t.videoCodec===`av1`&&!Sx()&&(t.videoCodec=void 0),t.videoCodec===`vp9`&&!Cx()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=LC),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(e=>t.videoCodec===rx(e.mime))||(t.videoCodec=rx(this.enabledPublishVideoCodecs[0].mime)));let r=t.videoCodec;e.on(W.Muted,this.onTrackMuted),e.on(W.Unmuted,this.onTrackUnmuted),e.on(W.Ended,this.handleTrackEnded),e.on(W.UpstreamPaused,this.onTrackUpstreamPaused),e.on(W.UpstreamResumed,this.onTrackUpstreamResumed),e.on(W.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);let i=[],a=!(t.dtx??!0),o=e.getSourceTrackSettings();o.autoGainControl&&i.push(Ig.TF_AUTO_GAIN_CONTROL),o.echoCancellation&&i.push(Ig.TF_ECHO_CANCELLATION),o.noiseSuppression&&i.push(Ig.TF_NOISE_SUPPRESSION),o.channelCount&&o.channelCount>1&&i.push(Ig.TF_STEREO),a&&i.push(Ig.TF_NO_DTX),pS(e)&&e.hasPreConnectBuffer&&i.push(Ig.TF_PRECONNECT_BUFFER);let s=new N_({cid:e.mediaStreamTrack.id,name:t.name,type:q.kindToProto(e.kind),muted:e.isMuted,source:q.sourceToProto(e.source),disableDtx:a,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(t.red??!0),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:i}),c;if(e.kind===q.Kind.Video){let n={width:0,height:0};try{n=yield e.waitForDimensions()}catch{let t=this.roomOptions.videoCaptureDefaults?.resolution??Kb.h720.resolution;n={width:t.width,height:t.height},this.log.error(`could not determine track dimensions, using defaults`,Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{dims:n}))}s.width=n.width,s.height=n.height,fS(e)&&(wx(r)&&(e.source===q.Source.ScreenShare&&(t.scalabilityMode=`L1T3`,`contentHint`in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint=`motion`,this.log.info(`forcing contentHint to motion for screenshare with SVC codecs`,Object.assign(Object.assign({},this.logContext),K(e))))),t.scalabilityMode=t.scalabilityMode??`L3T3_KEY`),s.simulcastCodecs=[new M_({codec:r,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:LC}),t.backupCodec&&r!==t.backupCodec.codec&&s.encryption===L.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),s.simulcastCodecs.push(new M_({codec:t.backupCodec.codec,cid:``})))),c=_w(e.source===q.Source.ScreenShare,s.width,s.height,t),s.layers=Aw(s.width,s.height,c,wx(t.videoCodec))}else e.kind===q.Kind.Audio&&(c=[{maxBitrate:t.audioPreset?.maxBitrate,priority:t.audioPreset?.priority??`high`,networkPriority:t.audioPreset?.priority??`high`}]);if(!this.engine||this.engine.isClosed)throw new Ab(`cannot publish track when not connected`);let l=()=>z(this,void 0,void 0,function*(){if(!this.engine.pcManager)throw new Ab(`pcManager is not ready`);if(e.sender=yield this.engine.createSender(e,t,c),this.emit(H.LocalSenderCreated,e.sender,e),fS(e)&&(t.degradationPreference??=Tw(e),e.setDegradationPreference(t.degradationPreference)),c)if(Dx()&&e.kind===q.Kind.Audio){let t;for(let n of this.engine.pcManager.publisher.getTransceivers())if(n.sender===e.sender){t=n;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:`opus`,maxbr:c[0]?.maxBitrate?c[0].maxBitrate/1e3:0})}else e.codec&&wx(e.codec)&&c[0]?.maxBitrate&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:s.cid,codec:e.codec,maxbr:c[0].maxBitrate/1e3});yield this.engine.negotiate()}),u,d=new Promise((t,n)=>z(this,void 0,void 0,function*(){try{u=yield this.engine.addTrack(s),t(u)}catch(t){e.sender&&this.engine.pcManager?.publisher&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(t=>{this.log.error(`failed to negotiate after removing track due to failed add track request`,Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{error:t}))})),n(t)}}));if(this.enabledPublishVideoCodecs.length>0)u=(yield Promise.all([d,l()]))[0];else{u=yield d;let n;if(u.codecs.forEach(e=>{n===void 0&&(n=e.mimeType)}),n&&e.kind===q.Kind.Video){let i=rx(n);i!==r&&(this.log.debug(`falling back to server selected codec`,Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{codec:i})),t.videoCodec=i,c=_w(e.source===q.Source.ScreenShare,s.width,s.height,t))}yield l()}let f=new _E(e.kind,u,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(f.on(W.CpuConstrained,e=>this.onTrackCpuConstrained(e,f)),f.options=t,e.sid=u.sid,this.log.debug(`publishing ${e.kind} with encodings`,Object.assign(Object.assign({},this.logContext),{encodings:c,trackInfo:u})),fS(e)?e.startMonitor(this.engine.client):pS(e)&&e.startMonitor(),this.addTrackPublication(f),this.emit(H.LocalTrackPublished,f),pS(e)&&u.audioFeatures.includes(Ig.TF_PRECONNECT_BUFFER)){let t=e.getPreConnectBuffer(),n=e.getPreConnectBufferMimeType();this.on(H.LocalTrackSubscribed,t=>{if(t.trackSid===u.sid){if(!e.hasPreConnectBuffer){this.log.warn(`subscribe event came to late, buffer already closed`,this.logContext);return}this.log.debug(`finished recording preconnect buffer`,Object.assign(Object.assign({},this.logContext),K(e))),e.stopPreConnectBuffer()}}),t&&new Promise((r,i)=>z(this,void 0,void 0,function*(){var a,s,c,l;try{this.log.debug(`waiting for agent`,Object.assign(Object.assign({},this.logContext),K(e)));let m=setTimeout(()=>{i(Error(`agent not active within 10 seconds`))},1e4),h=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug(`sending preconnect buffer`,Object.assign(Object.assign({},this.logContext),K(e)));let g=yield this.streamBytes({name:`preconnect-buffer`,mimeType:n,topic:`lk.agent.pre-connect-audio-buffer`,destinationIdentities:[h.identity],attributes:{trackId:f.trackSid,sampleRate:String(o.sampleRate??`48000`),channels:String(o.channelCount??`1`)}});try{for(var u=!0,d=ey(t),p;p=yield d.next(),a=p.done,!a;u=!0){l=p.value,u=!1;let e=l;yield g.write(e)}}catch(e){s={error:e}}finally{try{!u&&!a&&(c=d.return)&&(yield c.call(d))}finally{if(s)throw s.error}}yield g.close(),r()}catch(e){i(e)}})).then(()=>{this.log.debug(`preconnect buffer sent successfully`,Object.assign(Object.assign({},this.logContext),K(e)))}).catch(t=>{this.log.error(`error sending preconnect buffer`,Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{error:t}))})}return f})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return z(this,void 0,void 0,function*(){if(this.encryptionType!==L.NONE)return;let r;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(r=t)}),!r)throw new Ob(`track is not published`);if(!fS(e))throw new Ob(`track is not a video track`);let i=Object.assign(Object.assign({},this.roomOptions?.publishDefaults),n),a=vw(e,t,i);if(!a){this.log.info(`backup codec has been disabled, ignoring request to add additional codec for track`,Object.assign(Object.assign({},this.logContext),K(e)));return}let o=e.addSimulcastTrack(t,a);if(!o)return;let s=new N_({cid:o.mediaStreamTrack.id,type:q.kindToProto(e.kind),muted:e.isMuted,source:q.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:i.videoCodec,cid:o.mediaStreamTrack.id}]});if(s.layers=Aw(s.width,s.height,a),!this.engine||this.engine.isClosed)throw new Ab(`cannot publish track when not connected`);let c=(yield Promise.all([this.engine.addTrack(s),z(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,o,i,a),yield this.engine.negotiate()})]))[0];this.log.debug(`published ${t} for track ${e.sid}`,Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:c}))})}unpublishTrack(e,t){return z(this,void 0,void 0,function*(){if(lS(e)){let t=this.pendingPublishPromises.get(e);t&&(this.log.info(`awaiting publish promise before attempting to unpublish`,Object.assign(Object.assign({},this.logContext),K(e))),yield t)}let n=this.getPublicationForTrack(e),r=n?K(n):void 0;if(this.log.debug(`unpublishing track`,Object.assign(Object.assign({},this.logContext),r)),!n||!n.track){this.log.warn(`track was not unpublished because no publication was found`,Object.assign(Object.assign({},this.logContext),r));return}e=n.track,e.off(W.Muted,this.onTrackMuted),e.off(W.Unmuted,this.onTrackUnmuted),e.off(W.Ended,this.handleTrackEnded),e.off(W.UpstreamPaused,this.onTrackUpstreamPaused),e.off(W.UpstreamResumed,this.onTrackUpstreamResumed),e.off(W.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=this.roomOptions?.stopLocalTrackOnUnpublish??!0),t?e.stop():e.stopMonitor();let i=!1,a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<UC.FAILED&&a)try{for(let e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction=`inactive`,i=!0);if(this.engine.removeTrack(a)&&(i=!0),fS(e)){for(let[,t]of e.simulcastCodecs)t.sender&&=(this.engine.removeTrack(t.sender)&&(i=!0),void 0);e.simulcastCodecs.clear()}}catch(e){this.log.warn(`failed to unpublish track`,Object.assign(Object.assign(Object.assign({},this.logContext),r),{error:e}))}switch(this.trackPublications.delete(n.trackSid),n.kind){case q.Kind.Audio:this.audioTrackPublications.delete(n.trackSid);break;case q.Kind.Video:this.videoTrackPublications.delete(n.trackSid);break}return this.emit(H.LocalTrackUnpublished,n),n.setTrack(void 0),i&&(yield this.engine.negotiate()),n})}unpublishTracks(e){return z(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return z(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new gb((r,i)=>z(t,void 0,void 0,function*(){try{let t=[];this.trackPublications.forEach(n=>{n.track&&(e&&(n.options=Object.assign(Object.assign({},n.options),e)),t.push(n))}),yield Promise.all(t.map(e=>z(this,void 0,void 0,function*(){let t=e.track;yield this.unpublishTrack(t,!1),n&&!t.isMuted&&t.source!==q.Source.ScreenShare&&t.source!==q.Source.ScreenShareAudio&&(pS(t)||fS(t))&&!t.isUserProvided&&(this.log.debug(`restarting existing track`,Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))),r()}catch(e){e instanceof Error?i(e):i(Error(String(e)))}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return z(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){let r=n.reliable?J.RELIABLE:J.LOSSY,i=n.reliable?Zg.RELIABLE:Zg.LOSSY,a=n.destinationIdentities,o=n.topic,s=new Xg({kind:i,value:{case:`user`,value:new n_({participantIdentity:t.identity,payload:e,destinationIdentities:a,topic:o})}});yield t.engine.sendDataPacket(s,r)}()})}publishDtmf(e,t){return z(this,void 0,void 0,function*(){let n=new Xg({kind:Zg.RELIABLE,value:{case:`sipDtmf`,value:new r_({code:e,digit:t})}});yield this.engine.sendDataPacket(n,J.RELIABLE)})}sendChatMessage(e,t){return z(this,void 0,void 0,function*(){let n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},r=new Xg({value:{case:`chatMessage`,value:new o_(Object.assign(Object.assign({},n),{timestamp:ih.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(r,J.RELIABLE),this.emit(H.ChatMessage,n),n})}editChatMessage(e,t){return z(this,void 0,void 0,function*(){let n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new Xg({value:{case:`chatMessage`,value:new o_(Object.assign(Object.assign({},n),{timestamp:ih.parse(n.timestamp),editTimestamp:ih.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,J.RELIABLE),this.emit(H.ChatMessage,n),n})}sendText(e,t){return z(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return z(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return z(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return z(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:n,payload:r,responseTimeout:i=15e3}=e,a=7e3;return a+1e3,new gb((e,o)=>z(this,void 0,void 0,function*(){if(ZC(r)>XC){o(YC.builtIn(`REQUEST_PAYLOAD_TOO_LARGE`));return}if(this.engine.latestJoinResponse?.serverInfo?.version&&Hx(this.engine.latestJoinResponse?.serverInfo?.version,`1.8.0`)<0){o(YC.builtIn(`UNSUPPORTED_SERVER`));return}let s=Math.max(i,8e3),c=crypto.randomUUID();yield this.publishRpcRequest(t,c,n,r,s);let l=setTimeout(()=>{this.pendingAcks.delete(c),o(YC.builtIn(`CONNECTION_TIMEOUT`)),this.pendingResponses.delete(c),clearTimeout(u)},a);this.pendingAcks.set(c,{resolve:()=>{clearTimeout(l)},participantIdentity:t});let u=setTimeout(()=>{this.pendingResponses.delete(c),o(YC.builtIn(`RESPONSE_TIMEOUT`))},i);this.pendingResponses.set(c,{resolve:(t,n)=>{clearTimeout(u),this.pendingAcks.has(c)&&(this.log.warn(`RPC response received before ack`,c),this.pendingAcks.delete(c),clearTimeout(l)),n?o(n):e(t??``)},participantIdentity:t})}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn(`you're overriding the RPC handler for method ${e}, in the future this will throw an error`),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){this.participantTrackPermissions=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){let t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error(`Ack received for unexpected RPC request`,e)}handleIncomingRpcResponse(e,t,n){let r=this.pendingResponses.get(e);r?(r.resolve(t,n),this.pendingResponses.delete(e)):console.error(`Response received for unexpected RPC request`,e)}publishRpcRequest(e,t,n,r,i){return z(this,void 0,void 0,function*(){let a=new Xg({destinationIdentities:[e],kind:Zg.RELIABLE,value:{case:`rpcRequest`,value:new s_({id:t,method:n,payload:r,responseTimeoutMs:i,version:1})}});yield this.engine.sendDataPacket(a,J.RELIABLE)})}handleParticipantDisconnected(e){for(let[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(let[t,{participantIdentity:n,resolve:r}]of this.pendingResponses)n===e&&(r(null,YC.builtIn(`RECIPIENT_DISCONNECTED`)),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(e=>e.mime.split(`/`)[0].toLowerCase()===`video`)}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(e=>{let t=this.trackPublications.get(e.sid);if(t){let n=t.isMuted||(t.track?.isUpstreamPaused??!1);n!==e.muted&&(this.log.debug(`updating server mute state after reconcile`,Object.assign(Object.assign(Object.assign({},this.logContext),K(t)),{mutedOnServer:n})),this.engine.client.sendMuteTrack(e.sid,n))}}),!0):!1}setActiveAgent(e){var t,n,r,i;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(n=(t=this.activeAgentFuture)?.resolve)==null||n.call(t,e):(i=(r=this.activeAgentFuture)?.reject)==null||i.call(r,Error(`Agent disconnected`)),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||=new $x,this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{let r=n.track;r&&(e instanceof MediaStreamTrack?(pS(r)||fS(r))&&r.mediaStreamTrack===e&&(t=n):e===r&&(t=n))}),t}waitForPendingPublicationOfSource(e){return z(this,void 0,void 0,function*(){let t=Date.now();for(;Date.now()<t+1e4;){let t=Array.from(this.pendingPublishPromises.entries()).find(t=>{let[n]=t;return n.source===e});if(t)return t[1];yield yx(20)}})}publishDataTrack(e){return z(this,void 0,void 0,function*(){let t=new rE(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}},TE=class extends DOMException{constructor(e,t){super(e,`AbortError`),this.reason=t}},EE=class extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var n;super.set(e,t);let r=this.pending.get(e);if(r){for(let e of r)e.isResolved||(n=e.resolve)==null||n.call(e,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return`WaitableMap`}getDeferred(e,t){return z(this,void 0,void 0,function*(){let n=this.get(e);if(n!==void 0)return n;if(t?.aborted)throw new TE(`The operation was aborted.`,t.reason);let r=new $x(void 0,()=>{let t=this.pending.get(e);if(!t)return;let n=t.indexOf(r);n!==-1&&t.splice(n,1),t.length===0&&this.pending.delete(e)}),i=this.pending.get(e);if(i?i.push(r):this.pending.set(e,[r]),t){let e=()=>{var e;r.isResolved||(e=r.reject)==null||e.call(r,new TE(`The operation was aborted.`,t.reason))};t.addEventListener(`abort`,e,{once:!0}),r.promise.finally(()=>{t.removeEventListener(`abort`,e)})}return r.promise})}},DE=class extends gE{constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(W.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug(`adaptivestream video visibility ${this.trackSid}, visible=${e}`,this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug(`adaptivestream video dimensions ${e.width}x${e.height}`,this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);let r=new J_({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new d_({participantSid:``,trackSids:[this.trackSid]})]});this.emit(W.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?gE.SubscriptionStatus.Unsubscribed:super.isSubscribed?gE.SubscriptionStatus.Subscribed:gE.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?gE.PermissionStatus.Allowed:gE.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled===void 0?this.isAdaptiveStream?this.visible:!0:!this.requestedDisabled}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){this.isManualOperationAllowed()&&(this.requestedVideoDimensions?.width===e.width&&this.requestedVideoDimensions?.height===e.height||(gS(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&gS(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.requestedMaxQuality??px.HIGH}setTrack(e){let t=this.subscriptionStatus,n=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(W.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(W.VisibilityChanged,this.handleVisibilityChange),r.off(W.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(W.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(W.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(W.VisibilityChanged,this.handleVisibilityChange),e.on(W.Ended,this.handleEnded),this.emit(W.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(W.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);let t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?W.Muted:W.Unmuted)}emitSubscriptionUpdateIfChanged(e){let t=this.subscriptionStatus;e!==t&&this.emit(W.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(W.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn(`cannot update track settings when not subscribed`,this.logContext),!1)}get isAdaptiveStream(){return gS(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new Z_({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===q.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)lx(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug(`using adaptive stream dimensions instead of requested`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){let e=ux(this.trackInfo,this.requestedMaxQuality);e&&lx(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug(`using adaptive stream dimensions instead of max quality layer`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug(`using adaptive stream dimensions`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality===void 0?(this.log.debug(`using default quality`,Object.assign(Object.assign({},this.logContext),{quality:px.HIGH})),e.quality=px.HIGH):(this.log.debug(`using requested max quality`,Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality)}this.emit(W.UpdateSettings,e)}},OE=class e extends SE{static fromParticipantInfo(t,n,r){return new e(t,n.sid,n.identity,n.name,n.metadata,n.attributes,r,n.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,r,i,a,o){let s=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Hg.STANDARD;super(t,n||``,r,i,a,o,s),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new EE,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(W.UpdateSettings,t=>{this.log.debug(`send update settings`,Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(W.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(W.SubscriptionPermissionChanged,t=>{this.emit(H.TrackSubscriptionPermissionChanged,e,t)}),e.on(W.SubscriptionStatusChanged,t=>{this.emit(H.TrackSubscriptionStatusChanged,e,t)}),e.on(W.Subscribed,t=>{this.emit(H.TrackSubscribed,t,e)}),e.on(W.Unsubscribed,t=>{this.emit(H.TrackUnsubscribed,t,e)}),e.on(W.SubscriptionFailed,t=>{this.emit(H.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:q.Source.Microphone;this.volumeMap.set(t,e);let n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:q.Source.Microphone,t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,r,i,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith(`TR`)||this.trackPublications.forEach(t=>{!o&&e.kind===t.kind.toString()&&(o=t)}),!o){if(a===0){this.log.error(`could not find published track`,Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(H.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,r,i,a-1)},150);return}if(e.readyState===`ended`){this.log.error(`unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()`,Object.assign(Object.assign({},this.logContext),K(o))),this.emit(H.TrackSubscriptionFailed,t);return}let s=e.kind===`video`,c;return c=s?new fE(e,t,r,i):new uE(e,t,r,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(n),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&mS(c)&&uS(c)&&c.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;let t=new Map,n=new Map;return e.tracks.forEach(e=>{let r=this.getTrackPublicationBySid(e.sid);if(r)r.updateInfo(e);else{let t=q.kindFromProto(e.type);if(!t)return;r=new DE(t,e,this.signalClient.connectOptions?.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:this.loggerOptions?.loggerName}),r.updateInfo(e),n.set(e.sid,r);let i=Array.from(this.trackPublications.values()).find(e=>e.source===r?.source);i&&r.source!==q.Source.Unknown&&this.log.debug(`received a second track publication for ${this.identity} with the same source: ${r.source}`,Object.assign(Object.assign({},this.logContext),{oldTrack:K(i),newTrack:K(r)})),this.addTrackPublication(r)}t.set(e.sid,r)}),this.trackPublications.forEach(e=>{t.has(e.trackSid)||(this.log.trace(`detected removed track on remote participant, unpublishing`,Object.assign(Object.assign({},this.logContext),K(e))),this.unpublishTrack(e.trackSid,!0))}),n.forEach(e=>{this.emit(H.TrackPublished,e)}),!0}unpublishTrack(e,t){let n=this.trackPublications.get(e);if(!n)return;let{track:r}=n;switch(r&&(r.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case q.Kind.Audio:this.audioTrackPublications.delete(e);break;case q.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(H.TrackUnpublished,n)}setAudioOutput(e){return z(this,void 0,void 0,function*(){this.audioOutput=e;let t=[];this.audioTrackPublications.forEach(n=>{uS(n.track)&&mS(n.track)&&t.push(n.track.setSinkId(e.deviceId??`default`))}),yield Promise.all(t)})}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(let[t,n]of this.dataTracks.entries())e===n.info.sid&&this.dataTracks.delete(t)}emit(e){var t=[...arguments].slice(1);return this.log.trace(`participant event`,Object.assign(Object.assign({},this.logContext),{event:e,args:t})),super.emit(e,...t)}},Y;(function(e){e.Disconnected=`disconnected`,e.Connecting=`connecting`,e.Connected=`connected`,e.Reconnecting=`reconnecting`,e.SignalReconnecting=`signalReconnecting`})(Y||={});var kE=4*1e3,AE=class e extends iy.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(t){var n,r,i;if(super(),n=this,this.state=Y.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=R,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(e,t,n)=>z(this,void 0,void 0,function*(){if(!Ex())throw Ix()?Error(`WebRTC isn't detected, have you called registerGlobals?`):Error(`LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.`);let r=yield this.disconnectLock.lock();if(this.state===Y.Connected)return this.log.info(`already connected to room ${this.name}`,this.logContext),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(Y.Connecting),this.regionUrlProvider?.getServerUrl().toString()!==wS(e)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Lx(new URL(e))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new qC(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;(t=this.regionUrlProvider)==null||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn(`could not fetch region settings`,Object.assign(Object.assign({},this.logContext),{error:e}))}));let i=(a,o,s)=>z(this,void 0,void 0,function*(){this.abortController&&this.abortController.abort();let c=new AbortController;this.abortController=c,r?.();try{if(yield VS.getInstance().getBackOffPromise(e),c.signal.aborted)throw B.cancelled(`Connection attempt aborted`);yield this.attemptConnection(s??e,t,n,c),this.abortController=void 0,a()}catch(t){if(this.regionUrlProvider&&t instanceof B&&t.reason!==Eb.Cancelled&&t.reason!==Eb.NotAllowed){let n=null;try{this.log.debug(`Fetching next region`),n=yield this.regionUrlProvider.getNextBestRegionUrl(this.abortController?.signal)}catch(e){if(e instanceof B&&(e.status===401||e.reason===Eb.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),o(e);return}}[Eb.InternalError,Eb.ServerUnreachable,Eb.Timeout].includes(t.reason)&&(this.log.debug(`Adding failed connection attempt to back off`),VS.getInstance().addFailedConnectionAttempt(e)),n&&!this.abortController?.signal.aborted?(this.log.info(`Initial connection failed with ConnectionError: ${t.message}. Retrying with another region: ${n}`,this.logContext),this.recreateEngine(!0),yield i(a,o,n)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,oS(t)),o(t))}else{let e=Ng.UNKNOWN_REASON;t instanceof B&&(e=oS(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),o(t)}}}),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new $x((e,t)=>{i(e,t,a)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,n,r,i,a)=>z(this,void 0,void 0,function*(){let o=yield n.join(e,t,{autoSubscribe:r.autoSubscribe,adaptiveStream:typeof i.adaptiveStream==`object`?!0:i.adaptiveStream,maxRetries:r.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:r.websocketTimeout},a.signal,!i.singlePeerConnection),s=o.serverInfo;if(s||={version:o.serverVersion,region:o.serverRegion},this.serverInfo=s,this.log.debug(`connected to Livekit Server ${Object.entries(s).map(e=>{let[t,n]=e;return`${t}: ${n}`}).join(`, `)}`,{room:o.room?.name,roomSid:o.room?.sid,identity:o.participant?.identity}),!s.version)throw new kb(`unknown server version`);return s.version===`0.15.1`&&this.options.dynacast&&(this.log.debug(`disabling dynacast due to server version`,this.logContext),i.dynacast=!1),o}),this.applyJoinResponse=e=>{let t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:`Could not set SifTrailer`,Object.assign(Object.assign({},this.logContext),{error:e}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,n,r)=>z(this,void 0,void 0,function*(){this.state===Y.Reconnecting||this.isResuming||this.engine?.pendingReconnect?(this.log.info(`Reconnection attempt replaced by new connection attempt`,this.logContext),this.recreateEngine(!0)):this.maybeCreateEngine(),this.regionUrlProvider?.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},HC),n),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{let n=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,r);this.applyJoinResponse(n),this.setupLocalParticipantEvents(),this.emit(V.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();let t=r.signal.aborted?B.cancelled(`Signal connection aborted`):B.serverUnreachable(`could not establish signal connection`);throw e instanceof Error&&(t.message=`${t.message}: ${e.message}`),e instanceof B&&(t.reason=e.reason,t.status=e.status),this.log.debug(`error trying to establish signal connection`,Object.assign(Object.assign({},this.logContext),{error:e})),t}if(r.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),B.cancelled(`Connection attempt aborted`);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,r)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}Fx()&&this.options.disconnectOnPageLeave&&(window.addEventListener(`pagehide`,this.onPageLeave),window.addEventListener(`beforeunload`,this.onPageLeave)),Fx()&&window.addEventListener(`freeze`,this.onPageLeave),this.setAndEmitConnectionState(Y.Connected),this.emit(V.Connected),VS.getInstance().resetFailedConnectionAttempts(e),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){return z(n,[...[...arguments]],void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,r,i;let a=yield e.disconnectLock.lock();try{if(e.state===Y.Disconnected){e.log.debug(`already disconnected`,e.logContext);return}if(e.log.info(`disconnect from room`,Object.assign({},e.logContext)),e.state===Y.Connecting||e.state===Y.Reconnecting||e.isResuming){let t=`Abort connection attempt due to user initiated disconnect`;e.log.warn(t,e.logContext),(n=e.abortController)==null||n.abort(t),(i=(r=e.connectFuture)?.reject)==null||i.call(r,B.cancelled(`Client initiated disconnect`)),e.connectFuture=void 0}e.engine&&(e.engine.client.isDisconnected||(yield e.engine.client.sendLeave()),yield e.engine.close()),e.handleDisconnect(t,Ng.CLIENT_INITIATED),e.engine=void 0}finally{a()}}()})},this.onPageLeave=()=>z(this,void 0,void 0,function*(){this.log.info(`Page leave detected, disconnecting`,this.logContext),yield this.disconnect()}),this.startAudio=()=>z(this,void 0,void 0,function*(){let e=[],t=yb();if(t&&t.os===`iOS`){let t=`livekit-dummy-audio-el`,n=document.getElementById(t);if(!n){n=document.createElement(`audio`),n.id=t,n.autoplay=!0,n.hidden=!0;let e=Qx();e.enabled=!0;let r=new MediaStream([e]);n.srcObject=r,document.addEventListener(`visibilitychange`,()=>{n&&(n.srcObject=document.hidden?null:r,document.hidden||(this.log.debug(`page visible again, triggering startAudio to resume playback and update playback status`,this.logContext),this.startAudio()))}),document.body.append(n),this.once(V.Disconnected,()=>{n?.remove(),n=null})}e.push(n)}this.remoteParticipants.forEach(t=>{t.audioTrackPublications.forEach(t=>{t.track&&t.track.attachedElements.forEach(t=>{e.push(t)})})});try{yield Promise.all([this.acquireAudioContext(),...e.map(e=>(e.muted=!1,e.play()))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}),this.startVideo=()=>z(this,void 0,void 0,function*(){let e=[];for(let t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var n;(n=t.track)==null||n.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{e.name===`NotAllowedError`?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(let e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(Y.Reconnecting)&&this.emit(V.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=e=>z(this,void 0,void 0,function*(){this.log.debug(`signal reconnected to server, region ${e.serverRegion}`,Object.assign(Object.assign({},this.logContext),{region:e.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error(`error trying to re-publish tracks after reconnection`,Object.assign(Object.assign({},this.logContext),{error:e}))}try{yield this.engine.waitForRestarted(),this.log.debug(`fully reconnected to server`,Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch{return}this.setAndEmitConnectionState(Y.Connected),this.emit(V.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{for(let t of e){if(t.identity===this.localParticipant.identity){this.localParticipant.updateInfo(t);continue}t.identity===``&&(t.identity=this.sidToIdentity.get(t.sid)??``);let e=this.remoteParticipants.get(t.identity);t.state===Vg.DISCONNECTED?this.handleParticipantDisconnected(t.identity,e):e=this.getOrCreateParticipant(t.identity,t)}let t=new Map(e.filter(e=>e.identity!==this.localParticipant.identity).map(e=>[e.identity,e.dataTracks.map(e=>eC.from(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)},this.handleActiveSpeakersUpdate=e=>{let t=[],n={};e.forEach(e=>{if(n[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{let n=this.getRemoteParticipantBySid(e.sid);n&&(n.audioLevel=e.level,n.setIsSpeaking(!0),t.push(n))}}),n[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(e=>{n[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(V.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{let t=new Map;this.activeSpeakers.forEach(e=>{let n=this.remoteParticipants.get(e.identity);n&&n.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let n=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(n=this.localParticipant),n&&(n.audioLevel=e.level,n.setIsSpeaking(e.active),e.active?t.set(e.sid,n):t.delete(e.sid))});let n=Array.from(t.values());n.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=n,this.emitWhenConnected(V.ActiveSpeakersChanged,n)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);if(!n||!n.track)return;let r=q.streamStateFromProto(e.state);n.track.setStreamState(r),r!==n.track.streamState&&(t.emit(H.TrackStreamStateChanged,n,n.track.streamState),this.emitWhenConnected(V.TrackStreamStateChanged,n,n.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);n&&n.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{let t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);n&&n.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{let n=this.remoteParticipants.get(e.participantIdentity);if(e.value.case===`user`)this.handleUserPacket(n,e.value.value,e.kind,t);else if(e.value.case===`transcription`)this.handleTranscription(n,e.value.value);else if(e.value.case===`sipDtmf`)this.handleSipDtmf(n,e.value.value);else if(e.value.case===`chatMessage`)this.handleChatMessage(n,e.value.value);else if(e.value.case===`metrics`)this.handleMetrics(e.value.value,n);else if(e.value.case===`streamHeader`||e.value.case===`streamChunk`||e.value.case===`streamTrailer`)this.handleDataStream(e,t);else if(e.value.case===`rpcRequest`){let t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,n,r)=>{this.emit(V.DataReceived,t.payload,e,n,t.topic,r),e?.emit(H.DataReceived,t.payload,n,r)},this.handleSipDtmf=(e,t)=>{this.emit(V.SipDTMFReceived,t,e),e?.emit(H.SipDTMFReceived,t)},this.handleTranscription=(e,t)=>{let n=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),r=n?.trackPublications.get(t.trackId),i=iS(t,this.transcriptionReceivedTimes);r?.emit(W.TranscriptionReceived,i),n?.emit(H.TranscriptionReceived,i,r),this.emit(V.TranscriptionReceived,i,n,r)},this.handleChatMessage=(e,t)=>{let n=aS(t);this.emit(V.ChatMessage,n,e)},this.handleMetrics=(e,t)=>{this.emit(V.MetricsReceived,e,t)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(V.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn(`could not playback audio`,Object.assign(Object.assign({},this.logContext),{error:e})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(V.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(V.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(V.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>z(this,void 0,void 0,function*(){yb()?.os!==`iOS`&&(yield this.selectDefaultDevices()),this.emit(V.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{let t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(V.RoomMetadataChanged,e.metadata),t?.activeRecording!==e.activeRecording&&this.emitWhenConnected(V.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach(e=>{if(e.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(e.quality);return}let t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)})},this.onLocalParticipantMetadataChanged=e=>{this.emit(V.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(V.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(V.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(V.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(V.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;(t=e?.onPublish)==null||t.call(e,this)},this.onLocalTrackPublished=e=>z(this,void 0,void 0,function*(){var t,n,r,i;(t=e.track)==null||t.on(W.TrackProcessorUpdate,this.onTrackProcessorUpdate),(n=e.track)==null||n.on(W.Restarted,this.onLocalTrackRestarted),(i=(r=e.track?.getProcessor())?.onPublish)==null||i.call(r,this),this.emit(V.LocalTrackPublished,e,this.localParticipant),pS(e.track)&&(yield e.track.checkForSilence())&&this.emit(V.LocalAudioSilenceDetected,e);let a=yield e.track?.getDeviceId(!1),o=tx(e.source);o&&a&&a!==this.localParticipant.activeDeviceMap.get(o)&&(this.localParticipant.activeDeviceMap.set(o,a),this.emit(V.ActiveDeviceChanged,o,a))}),this.onLocalTrackUnpublished=e=>{var t,n;(t=e.track)==null||t.off(W.TrackProcessorUpdate,this.onTrackProcessorUpdate),(n=e.track)==null||n.off(W.Restarted,this.onLocalTrackRestarted),this.emit(V.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>z(this,void 0,void 0,function*(){let t=yield e.getDeviceId(!1),n=tx(e.source);n&&t&&t!==this.localParticipant.activeDeviceMap.get(n)&&(this.log.debug(`local track restarted, setting ${n} ${t} active`,this.logContext),this.localParticipant.activeDeviceMap.set(n,t),this.emit(V.ActiveDeviceChanged,n,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(V.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(V.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(V.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(V.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},VC),t),this.log=Wv(this.options.loggerName??Uv.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},zC),t?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},BC),t?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},RC),t?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new qw,this.outgoingDataStreamManager=new Qw(this.engine,this.log),this.incomingDataTrackManager=new qT({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on(`sfuUpdateSubscription`,e=>{this.engine.client.sendUpdateDataSubscription(e.sid,e.subscribe)}).on(`trackPublished`,e=>{var t;e.track.publisherIdentity!==this.localParticipant.identity&&(this.emit(V.DataTrackPublished,e.track),(t=this.remoteParticipants.get(e.track.publisherIdentity))==null||t.addRemoteDataTrack(e.track))}).on(`trackUnpublished`,e=>{var t;e.publisherIdentity!==this.localParticipant.identity&&(this.emit(V.DataTrackUnpublished,e.sid),(t=this.remoteParticipants.get(e.publisherIdentity))==null||t.removeRemoteDataTrack(e.sid))}),this.outgoingDataTrackManager=new cE({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on(`sfuPublishRequest`,e=>{this.engine.client.sendPublishDataTrackRequest(e.handle,e.name,e.usesE2ee)}).on(`sfuUnpublishRequest`,e=>{this.engine.client.sendUnPublishDataTrackRequest(e.handle)}).on(`trackPublished`,e=>{this.emit(V.LocalDataTrackPublished,e.track)}).on(`trackUnpublished`,e=>{this.emit(V.LocalDataTrackUnpublished,e.sid)}).on(`packetAvailable`,e=>{let{bytes:t}=e;this.engine.sendLossyBytes(t,J.DATA_TRACK_LOSSY,`wait`)}),this.disconnectLock=new Dm,this.localParticipant=new wE(``,``,this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager,this.outgoingDataTrackManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager(this.e2eeManager??null),this.outgoingDataTrackManager.updateE2eeManager(this.e2eeManager??null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set(`videoinput`,tS(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set(`audioinput`,tS(this.options.audioCaptureDefaults.deviceId)),this.options.audioOutput?.deviceId&&this.switchActiveDevice(`audiooutput`,tS(this.options.audioOutput.deviceId)).catch(e=>this.log.warn(`Could not set audio output: ${e.message}`,this.logContext)),Fx()){let t=new AbortController;(i=(r=navigator.mediaDevices)?.addEventListener)==null||i.call(r,`devicechange`,this.handleDeviceChange,{signal:t.signal}),e.cleanupRegistry&&e.cleanupRegistry.register(this,()=>{t.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error(`RPC handler already registered for method ${e}, unregisterRpcMethod before trying to register again`);this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return z(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==``&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error(`e2ee not configured, please set e2ee settings within the room options`)})}setupE2EE(){var e;let t=!!this.options.encryption,n=this.options.encryption||this.options.e2ee;n&&(`e2eeManager`in n?(this.e2eeManager=n.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new RS(n,t),this.e2eeManager.on(jS.ParticipantEncryptionStatusChanged,(e,t)=>{_S(t)&&(this.isE2EEEnabled=e),this.emit(V.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(jS.EncryptionError,(e,t)=>{let n=t?this.getParticipantByIdentity(t):void 0;this.emit(V.EncryptionError,e,n)}),(e=this.e2eeManager)==null||e.setup(this))}get logContext(){return{room:this.name,roomID:this.roomInfo?.sid,participant:this.localParticipant.identity,participantID:this.localParticipant.sid}}get isRecording(){return this.roomInfo?.activeRecording??!1}getSid(){return this.state===Y.Disconnected?gb.resolve(``):this.roomInfo&&this.roomInfo.sid!==``?gb.resolve(this.roomInfo.sid):new gb((e,t)=>{let n=t=>{t.sid!==``&&(this.engine.off(U.RoomUpdate,n),e(t.sid))};this.engine.on(U.RoomUpdate,n),this.once(V.Disconnected,()=>{this.engine.off(U.RoomUpdate,n),t(new Ab(`Room disconnected before room server id was available`))})})}get name(){return this.roomInfo?.name??``}get metadata(){return this.roomInfo?.metadata}get numParticipants(){return this.roomInfo?.numParticipants??0}get numPublishers(){return this.roomInfo?.numPublishers??0}maybeCreateEngine(){this.engine&&(this.engine.isNewlyCreated||!this.engine.isClosed)||(this.engine=new Hw(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(U.ParticipantUpdate,this.handleParticipantUpdates).on(U.RoomUpdate,this.handleRoomUpdate).on(U.SpeakersChanged,this.handleSpeakersChanged).on(U.StreamStateChanged,this.handleStreamStateUpdate).on(U.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(U.SubscriptionError,this.handleSubscriptionError).on(U.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(U.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(U.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(U.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(U.DataPacketReceived,this.handleDataPacket).on(U.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info(`Resuming signal connection`,this.logContext),this.setAndEmitConnectionState(Y.SignalReconnecting)&&this.emit(V.SignalReconnecting)}).on(U.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info(`Resumed signal connection`,this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Y.Connected)&&this.emit(V.Reconnected)}).on(U.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Y.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(U.Restarting,this.handleRestarting).on(U.Restarted,this.handleRestarted).on(U.SignalRestarted,this.handleSignalRestarted).on(U.Offline,()=>{this.setAndEmitConnectionState(Y.Reconnecting)&&this.emit(V.Reconnecting)}).on(U.DCBufferStatusChanged,(e,t)=>{this.emit(V.DCBufferStatusChanged,e,t)}).on(U.LocalTrackSubscribed,e=>{let t=this.localParticipant.getTrackPublications().find(t=>{let{trackSid:n}=t;return n===e});if(!t){this.log.warn(`could not find local track subscription for subscribed event`,this.logContext);return}this.localParticipant.emit(H.LocalTrackSubscribed,t),this.emitWhenConnected(V.LocalTrackSubscribed,t,this.localParticipant)}).on(U.RoomMoved,e=>{this.log.debug(`room moved`,e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((e,t)=>{this.handleParticipantDisconnected(t,e)}),this.emit(V.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(U.PublishDataTrackResponse,e=>{if(!e.info){this.log.warn(`received PublishDataTrackResponse, but event.info was ${e.info}, so skipping.`,this.logContext);return}this.outgoingDataTrackManager.receivedSfuPublishResponse(e.info.pubHandle,{type:`ok`,data:{sid:e.info.sid,pubHandle:e.info.pubHandle,name:e.info.name,usesE2ee:e.info.encryption!==L.NONE}})}).on(U.UnPublishDataTrackResponse,e=>{if(!e.info){this.log.warn(`received UnPublishDataTrackResponse, but event.info was ${e.info}, so skipping.`,this.logContext);return}this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle)}).on(U.DataTrackSubscriberHandles,e=>{let t=new Map(Object.entries(e.subHandles).map(e=>{let[t,n]=e;return[parseInt(t,10),n.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(U.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(e){throw e}}).on(U.Joined,e=>{let t=new Map(e.otherParticipants.map(e=>[e.identity,e.dataTracks.map(e=>eC.from(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return US.getInstance().getDevices(e,t)}prepareConnection(e,t){return z(this,void 0,void 0,function*(){if(this.state===Y.Disconnected){this.log.debug(`prepareConnection to ${e}`,this.logContext);try{if(Lx(new URL(e))&&t){this.regionUrlProvider=new qC(e,t);let n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===Y.Disconnected&&(this.regionUrl=n,yield fetch(rS(n),{method:`HEAD`}),this.log.debug(`prepared connection to ${n}`,this.logContext))}else yield fetch(rS(e),{method:`HEAD`})}catch(e){this.log.warn(`could not prepare connection`,Object.assign(Object.assign({},this.logContext),{error:e}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return z(this,void 0,void 0,function*(){let n=()=>z(this,void 0,void 0,function*(){}),r;switch(e){case`signal-reconnect`:yield this.engine.client.handleOnClose(`simulate disconnect`);break;case`speaker`:r=new Sv({scenario:{case:`speakerUpdate`,value:3}});break;case`node-failure`:r=new Sv({scenario:{case:`nodeFailure`,value:!0}});break;case`server-leave`:r=new Sv({scenario:{case:`serverLeave`,value:!0}});break;case`migration`:r=new Sv({scenario:{case:`migration`,value:!0}});break;case`resume-reconnect`:this.engine.failNext(),yield this.engine.client.handleOnClose(`simulate resume-disconnect`);break;case`disconnect-signal-on-resume`:n=()=>z(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose(`simulate resume-disconnect`)}),r=new Sv({scenario:{case:`disconnectSignalOnResume`,value:!0}});break;case`disconnect-signal-on-resume-no-messages`:n=()=>z(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose(`simulate resume-disconnect`)}),r=new Sv({scenario:{case:`disconnectSignalOnResumeNoMessages`,value:!0}});break;case`full-reconnect`:this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose(`simulate full-reconnect`);break;case`force-tcp`:case`force-tls`:r=new Sv({scenario:{case:`switchCandidateProtocol`,value:e===`force-tls`?2:1}}),n=()=>z(this,void 0,void 0,function*(){let e=this.engine.client.onLeave;e&&e(new ev({reason:Ng.CLIENT_INITIATED,action:tv.RECONNECT}))});break;case`subscriber-bandwidth`:if(t===void 0||typeof t!=`number`)throw Error(`subscriber-bandwidth requires a number as argument`);r=new Sv({scenario:{case:`subscriberBandwidth`,value:cS(t)}});break;case`leave-full-reconnect`:r=new Sv({scenario:{case:`leaveRequestFullReconnect`,value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return z(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var i,a;let o=!0,s=!1,c=r?{exact:t}:t;if(e===`audioinput`){s=n.localParticipant.audioTrackPublications.size===0;let t=n.getActiveDevice(e)??n.options.audioCaptureDefaults.deviceId;n.options.audioCaptureDefaults.deviceId=c;let r=Array.from(n.localParticipant.audioTrackPublications.values()).filter(e=>e.source===q.Source.Microphone);try{o=(yield Promise.all(r.map(e=>e.audioTrack?.setDeviceId(c)))).every(e=>e===!0)}catch(e){throw n.options.audioCaptureDefaults.deviceId=t,e}let i=r.some(e=>e.track?.isMuted??!1);o&&i&&(s=!0)}else if(e===`videoinput`){s=n.localParticipant.videoTrackPublications.size===0;let t=n.getActiveDevice(e)??n.options.videoCaptureDefaults.deviceId;n.options.videoCaptureDefaults.deviceId=c;let r=Array.from(n.localParticipant.videoTrackPublications.values()).filter(e=>e.source===q.Source.Camera);try{o=(yield Promise.all(r.map(e=>e.videoTrack?.setDeviceId(c)))).every(e=>e===!0)}catch(e){throw n.options.videoCaptureDefaults.deviceId=t,e}let i=r.some(e=>e.track?.isMuted??!1);o&&i&&(s=!0)}else if(e===`audiooutput`){if(s=!0,!Tx()&&!n.options.webAudioMix||n.options.webAudioMix&&n.audioContext&&!(`setSinkId`in n.audioContext))throw Error(`cannot switch audio output, the current browser does not support it`);n.options.webAudioMix&&(t=(yield US.getInstance().normalizeDeviceId(`audiooutput`,t))??``),(a=n.options).audioOutput??(a.audioOutput={});let r=n.getActiveDevice(e)??n.options.audioOutput.deviceId;n.options.audioOutput.deviceId=t;try{n.options.webAudioMix&&((i=n.audioContext)==null||i.setSinkId(t)),yield Promise.all(Array.from(n.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(e){throw n.options.audioOutput.deviceId=r,e}}return s&&(n.localParticipant.activeDeviceMap.set(e,t),n.emit(V.ActiveDeviceChanged,e,t)),o}()})}setupLocalParticipantEvents(){this.localParticipant.on(H.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(H.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(H.AttributesChanged,this.onLocalAttributesChanged).on(H.TrackMuted,this.onLocalTrackMuted).on(H.TrackUnmuted,this.onLocalTrackUnmuted).on(H.LocalTrackPublished,this.onLocalTrackPublished).on(H.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(H.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(H.MediaDevicesError,this.onMediaDevicesError).on(H.AudioStreamAcquired,this.startAudio).on(H.ChatMessage,this.onLocalChatMessageSent).on(H.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){let t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally(()=>t.close()):t?.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===Y.Connecting||this.state===Y.Reconnecting){let r=()=>{this.log.debug(`deferring on track for later`,{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(e=>e.id)}),this.onTrackAdded(e,t,n),i()},i=()=>{this.off(V.Reconnected,r),this.off(V.Connected,r),this.off(V.Disconnected,i)};this.once(V.Reconnected,r),this.once(V.Connected,r),this.once(V.Disconnected,i);return}if(this.state===Y.Disconnected){this.log.warn(`skipping incoming track after Room disconnected`,this.logContext);return}if(e.readyState===`ended`){this.log.info(`skipping incoming track as it already ended`,this.logContext);return}let r=vx(t.id),i=r[0],a=r[1],o=e.id;if(a&&a.startsWith(`TR`)&&(o=a),i===this.localParticipant.sid){this.log.warn(`tried to create RemoteParticipant for local participant`,this.logContext);return}let s=Array.from(this.remoteParticipants.values()).find(e=>e.sid===i);if(!s){i.startsWith(`PA`)&&this.log.error(`Tried to add a track for a participant, that's not present. Sid: ${i}`,this.logContext);return}if(!o.startsWith(`TR`)){let e=this.engine.getTrackIdForReceiver(n);if(!e){this.log.error(`Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ${i}`,this.logContext);return}o=e}o.startsWith(`TR`)||this.log.warn(`Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ${i}, streamId: ${a}, trackId: ${o}`,Object.assign(Object.assign({},this.logContext),{remoteParticipantID:i,streamId:a,trackId:o}));let c;this.options.adaptiveStream&&(c=typeof this.options.adaptiveStream==`object`?this.options.adaptiveStream:{});let l=s.addSubscribedMediaTrack(e,o,t,n,c);l?.isEncrypted&&!this.e2eeManager&&this.emit(V.EncryptionError,Error(`Encrypted ${l.source} track received from participant ${s.sid}, but room does not have encryption enabled!`))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n,r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==Y.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{e.unpublishTrack(t.trackSid)})}),this.localParticipant.trackPublications.forEach(t=>{var n,r,i;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?((n=t.track)==null||n.detach(),(r=t.track)==null||r.stop()):(i=t.track)==null||i.stopMonitor()}),this.localParticipant.off(H.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(H.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(H.AttributesChanged,this.onLocalAttributesChanged).off(H.TrackMuted,this.onLocalTrackMuted).off(H.TrackUnmuted,this.onLocalTrackUnmuted).off(H.LocalTrackPublished,this.onLocalTrackPublished).off(H.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(H.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(H.MediaDevicesError,this.onMediaDevicesError).off(H.AudioStreamAcquired,this.startAudio).off(H.ChatMessage,this.onLocalChatMessageSent).off(H.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix==`boolean`&&(this.audioContext.close(),this.audioContext=void 0),Fx()&&(window.removeEventListener(`beforeunload`,this.onPageLeave),window.removeEventListener(`pagehide`,this.onPageLeave),window.removeEventListener(`freeze`,this.onPageLeave),(r=(n=navigator.mediaDevices)?.removeEventListener)==null||r.call(n,`devicechange`,this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Y.Disconnected),this.emit(V.Disconnected,t)}}}handleParticipantDisconnected(e,t){var n;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(V.ParticipantDisconnected,t),t.setDisconnected(),(n=this.localParticipant)==null||n.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,n,r,i,a){return z(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),a!==1){yield this.engine.publishRpcResponse(e,t,null,YC.builtIn(`UNSUPPORTED_VERSION`));return}let o=this.rpcHandlers.get(n);if(!o){yield this.engine.publishRpcResponse(e,t,null,YC.builtIn(`UNSUPPORTED_METHOD`));return}let s=null,c=null;try{let a=yield o({requestId:t,callerIdentity:e,payload:r,responseTimeout:i});ZC(a)>XC?(s=YC.builtIn(`RESPONSE_PAYLOAD_TOO_LARGE`),this.log.warn(`RPC Response payload too large for ${n}`)):c=a}catch(e){e instanceof YC?s=e:(this.log.warn(`Uncaught error returned by RPC handler for ${n}. Returning APPLICATION_ERROR instead.`,e),s=YC.builtIn(`APPLICATION_ERROR`))}yield this.engine.publishRpcResponse(e,t,c,s)})}selectDefaultDevices(){return z(this,void 0,void 0,function*(){let e=US.getInstance().previousDevices,t=yield US.getInstance().getDevices(void 0,!1),n=yb();if(n?.name===`Chrome`&&n.os!==`iOS`)for(let n of t){let t=e.find(e=>e.deviceId===n.deviceId);t&&t.label!==``&&t.kind===n.kind&&t.label!==n.label&&this.getActiveDevice(n.kind)===`default`&&this.emit(V.ActiveDeviceChanged,n.kind,n.deviceId)}for(let n of[`audiooutput`,`audioinput`,`videoinput`]){let r=ex(n),i=this.localParticipant.getTrackPublication(r);if(i&&i.track?.isUserProvided)continue;let a=t.filter(e=>e.kind===n),o=this.getActiveDevice(n);if(o===e.filter(e=>e.kind===n)[0]?.deviceId&&a.length>0&&a[0]?.deviceId!==o){yield this.switchActiveDevice(n,a[0].deviceId);continue}n===`audioinput`&&!Ax()||n===`videoinput`||a.length>0&&!a.find(e=>e.deviceId===this.getActiveDevice(n))&&(n!==`audiooutput`||!Ax())&&(yield this.switchActiveDevice(n,a[0].deviceId))}})}acquireAudioContext(){return z(this,void 0,void 0,function*(){if(typeof this.options.webAudioMix!=`boolean`&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state===`closed`)&&(this.audioContext=$b()??void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state===`suspended`)try{yield Promise.race([this.audioContext.resume(),yx(200)])}catch(e){this.log.warn(`Could not resume audio context`,Object.assign(Object.assign({},this.logContext),{error:e}))}let e=this.audioContext?.state===`running`;e!==this.canPlaybackAudio&&(this.audioEnabled=e,this.emit(V.AudioPlaybackStatusChanged,e))})}createParticipant(e,t){let n;return n=t?OE.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new OE(this.engine.client,``,e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),this.options.audioOutput?.deviceId&&n.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn(`Could not set audio output: ${e.message}`,this.logContext)),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){let n=this.remoteParticipants.get(e);return t&&n.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),n}let n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(V.ParticipantConnected,n),n.on(H.TrackPublished,e=>{this.emitWhenConnected(V.TrackPublished,e,n)}).on(H.TrackSubscribed,(e,t)=>{e.kind===q.Kind.Audio?(e.on(W.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(W.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===q.Kind.Video&&(e.on(W.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(W.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(V.TrackSubscribed,e,t,n)}).on(H.TrackUnpublished,e=>{this.emit(V.TrackUnpublished,e,n)}).on(H.TrackUnsubscribed,(e,t)=>{this.emit(V.TrackUnsubscribed,e,t,n)}).on(H.TrackMuted,e=>{this.emitWhenConnected(V.TrackMuted,e,n)}).on(H.TrackUnmuted,e=>{this.emitWhenConnected(V.TrackUnmuted,e,n)}).on(H.ParticipantMetadataChanged,e=>{this.emitWhenConnected(V.ParticipantMetadataChanged,e,n)}).on(H.ParticipantNameChanged,e=>{this.emitWhenConnected(V.ParticipantNameChanged,e,n)}).on(H.AttributesChanged,e=>{this.emitWhenConnected(V.ParticipantAttributesChanged,e,n)}).on(H.ConnectionQualityChanged,e=>{this.emitWhenConnected(V.ConnectionQualityChanged,e,n)}).on(H.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(V.ParticipantPermissionsChanged,e,n)}).on(H.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(V.TrackSubscriptionStatusChanged,e,t,n)}).on(H.TrackSubscriptionFailed,(e,t)=>{this.emit(V.TrackSubscriptionFailed,e,n,t)}).on(H.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(V.TrackSubscriptionPermissionChanged,e,t,n)}).on(H.Active,()=>{this.emitWhenConnected(V.ParticipantActive,n),n.kind===Hg.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){let e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications(),n=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,n)}updateSubscriptions(){for(let e of this.remoteParticipants.values())for(let t of e.videoTrackPublications.values())t.isSubscribed&&hS(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){let t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Rb.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn(`detected connection state mismatch`,Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Ng.STATE_MISMATCH))):e=0},kE)}clearConnectionReconcile(){this.connectionReconcileInterval&&Rb.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(V.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){var t=[...arguments].slice(1);if(this.state===Y.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,t]);else if(this.state===Y.Connected)return this.emit(e,...t);return!1}simulateParticipants(e){return z(this,void 0,void 0,function*(){let t=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),n=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Lg({sid:`RM_SIMULATED`,name:`simulated-room`,emptyTimeout:0,maxParticipants:0,creationTime:ih.parse(new Date().getTime()),metadata:``,numParticipants:1,numPublishers:1,turnPassword:``,enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Bg({identity:`simulated-local`,name:`local-name`})),this.setupLocalParticipantEvents(),this.emit(V.SignalConnected),this.emit(V.Connected),this.setAndEmitConnectionState(Y.Connected),t.video){let e=new _E(q.Kind.Video,new Gg({source:kg.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Og.AUDIO,name:`video-dummy`}),new Dw(t.useRealTracks&&window.navigator.mediaDevices?.getUserMedia?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Xx(160*(n.aspectRatios[0]??1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(H.LocalTrackPublished,e)}if(t.audio){let e=new _E(q.Kind.Audio,new Gg({source:kg.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Og.AUDIO}),new cw(t.useRealTracks&&navigator.mediaDevices?.getUserMedia?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Qx(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(H.LocalTrackPublished,e)}for(let e=0;e<n.count-1;e+=1){let t=new Bg({sid:Math.floor(Math.random()*1e4).toString(),identity:`simulated-${e}`,state:Vg.ACTIVE,tracks:[],joinedAt:ih.parse(Date.now())}),r=this.getOrCreateParticipant(t.identity,t);if(n.video){let i=Xx(160*(n.aspectRatios[e%n.aspectRatios.length]??1),160,!1,!0),a=new Gg({source:kg.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Og.AUDIO});r.addSubscribedMediaTrack(i,a.sid,new MediaStream([i]),new RTCRtpReceiver),t.tracks=[...t.tracks,a]}if(n.audio){let e=Qx(),n=new Gg({source:kg.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Og.AUDIO});r.addSubscribedMediaTrack(e,n.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,n]}r.updateInfo(t)}})}emit(e){var t=[...arguments].slice(1);if(e!==V.ActiveSpeakersChanged&&e!==V.TranscriptionReceived){let n=jE(t).filter(e=>e!==void 0);(e===V.TrackSubscribed||e===V.TrackUnsubscribed)&&this.log.trace(`subscribe trace: ${e}`,Object.assign(Object.assign({},this.logContext),{event:e,args:n})),this.log.debug(`room event ${e}`,Object.assign(Object.assign({},this.logContext),{event:e,args:n}))}return super.emit(e,...t)}};AE.cleanupRegistry=typeof FinalizationRegistry<`u`&&new FinalizationRegistry(e=>{e()});function jE(e){return e.map(e=>{if(e)return Array.isArray(e)?jE(e):typeof e==`object`?`logContext`in e?e.logContext:void 0:e})}var ME;(function(e){e[e.IDLE=0]=`IDLE`,e[e.RUNNING=1]=`RUNNING`,e[e.SKIPPED=2]=`SKIPPED`,e[e.SUCCESS=3]=`SUCCESS`,e[e.FAILED=4]=`FAILED`})(ME||={}),iy.EventEmitter,iy.EventEmitter;function X(e,t,n){return(t=PE(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function NE(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function PE(e){var t=NE(e,`string`);return typeof t==`symbol`?t:t+``}new TextEncoder,new TextDecoder;var FE=class extends Error{constructor(e,t){var n;super(e,t),X(this,`code`,`ERR_JOSE_GENERIC`),this.name=this.constructor.name,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}};X(FE,`code`,`ERR_JOSE_GENERIC`),X(class extends FE{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),X(this,`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),X(this,`claim`,void 0),X(this,`reason`,void 0),X(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}},`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),X(class extends FE{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),X(this,`code`,`ERR_JWT_EXPIRED`),X(this,`claim`,void 0),X(this,`reason`,void 0),X(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}},`code`,`ERR_JWT_EXPIRED`),X(class extends FE{constructor(){super(...arguments),X(this,`code`,`ERR_JOSE_ALG_NOT_ALLOWED`)}},`code`,`ERR_JOSE_ALG_NOT_ALLOWED`),X(class extends FE{constructor(){super(...arguments),X(this,`code`,`ERR_JOSE_NOT_SUPPORTED`)}},`code`,`ERR_JOSE_NOT_SUPPORTED`),X(class extends FE{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`decryption operation failed`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,`code`,`ERR_JWE_DECRYPTION_FAILED`)}},`code`,`ERR_JWE_DECRYPTION_FAILED`),X(class extends FE{constructor(){super(...arguments),X(this,`code`,`ERR_JWE_INVALID`)}},`code`,`ERR_JWE_INVALID`),X(class extends FE{constructor(){super(...arguments),X(this,`code`,`ERR_JWS_INVALID`)}},`code`,`ERR_JWS_INVALID`),X(class extends FE{constructor(){super(...arguments),X(this,`code`,`ERR_JWT_INVALID`)}},`code`,`ERR_JWT_INVALID`),X(class extends FE{constructor(){super(...arguments),X(this,`code`,`ERR_JWK_INVALID`)}},`code`,`ERR_JWK_INVALID`),X(class extends FE{constructor(){super(...arguments),X(this,`code`,`ERR_JWKS_INVALID`)}},`code`,`ERR_JWKS_INVALID`),X(class extends FE{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`no applicable key found in the JSON Web Key Set`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,`code`,`ERR_JWKS_NO_MATCHING_KEY`)}},`code`,`ERR_JWKS_NO_MATCHING_KEY`),X(class extends FE{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`multiple matching keys found in the JSON Web Key Set`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,Symbol.asyncIterator,void 0),X(this,`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`)}},`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`),X(class extends FE{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`request timed out`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,`code`,`ERR_JWKS_TIMEOUT`)}},`code`,`ERR_JWKS_TIMEOUT`),X(class extends FE{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`signature verification failed`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`)}},`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`);function IE(){return IE=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},IE.apply(null,arguments)}var LE=new Uint8Array,RE=class{static getFullOptions(e){return IE({clientTools:{},onConnect:()=>{},onDebug:()=>{},onDisconnect:()=>{},onError:()=>{},onMessage:()=>{},onAudio:()=>{},onModeChange:()=>{},onStatusChange:()=>{},onCanSendFeedbackChange:()=>{},onInterruption:()=>{}},e)}constructor(e,t){var n=this;this.options=void 0,this.connection=void 0,this.lastInterruptTimestamp=0,this.mode=`listening`,this.status=`connecting`,this.volume=1,this.currentEventId=1,this.lastFeedbackEventId=0,this.canSendFeedback=!1,this.endSessionWithDetails=async function(e){n.status!==`connected`&&n.status!==`connecting`||(n.updateStatus(`disconnecting`),await n.handleEndSession(),n.updateStatus(`disconnected`),n.options.onDisconnect&&n.options.onDisconnect(e))},this.onMessage=async function(e){switch(e.type){case`interruption`:n.handleInterruption(e);return;case`agent_response`:n.handleAgentResponse(e);return;case`user_transcript`:n.handleUserTranscript(e);return;case`internal_tentative_agent_response`:n.handleTentativeAgentResponse(e);return;case`client_tool_call`:try{await n.handleClientToolCall(e)}catch(t){n.onError(`Unexpected error in client tool call handling: ${t instanceof Error?t.message:String(t)}`,{clientToolName:e.client_tool_call.tool_name,toolCallId:e.client_tool_call.tool_call_id})}return;case`audio`:n.handleAudio(e);return;case`vad_score`:n.handleVadScore(e);return;case`ping`:n.connection.sendMessage({type:`pong`,event_id:e.ping_event.event_id});return;case`mcp_tool_call`:n.handleMCPToolCall(e);return;case`mcp_connection_status`:n.handleMCPConnectionStatus(e);return;case`agent_tool_request`:n.handleAgentToolRequest(e);return;case`agent_tool_response`:n.handleAgentToolResponse(e);return;case`conversation_initiation_metadata`:n.handleConversationMetadata(e);return;case`asr_initiation_metadata`:n.handleAsrInitiationMetadata(e);return;case`agent_chat_response_part`:n.handleAgentChatResponsePart(e);return;case`error`:n.handleErrorEvent(e);return;default:n.options.onDebug&&n.options.onDebug(e);return}},this.setVolume=({volume:e})=>{this.volume=e},this.options=e,this.connection=t,this.options.onConnect&&this.options.onConnect({conversationId:t.conversationId}),this.connection.onMessage(this.onMessage),this.connection.onDisconnect(this.endSessionWithDetails),this.connection.onModeChange(e=>this.updateMode(e)),this.updateStatus(`connected`)}endSession(){return this.endSessionWithDetails({reason:`user`})}async handleEndSession(){this.connection.close()}updateMode(e){e!==this.mode&&(this.mode=e,this.options.onModeChange&&this.options.onModeChange({mode:e}))}updateStatus(e){e!==this.status&&(this.status=e,this.options.onStatusChange&&this.options.onStatusChange({status:e}))}updateCanSendFeedback(){let e=this.currentEventId!==this.lastFeedbackEventId;this.canSendFeedback!==e&&(this.canSendFeedback=e,this.options.onCanSendFeedbackChange&&this.options.onCanSendFeedbackChange({canSendFeedback:e}))}handleInterruption(e){e.interruption_event&&(this.lastInterruptTimestamp=e.interruption_event.event_id,this.options.onInterruption&&this.options.onInterruption({event_id:e.interruption_event.event_id}))}handleAgentResponse(e){this.options.onMessage&&this.options.onMessage({source:`ai`,role:`agent`,message:e.agent_response_event.agent_response})}handleUserTranscript(e){this.options.onMessage&&this.options.onMessage({source:`user`,role:`user`,message:e.user_transcription_event.user_transcript})}handleTentativeAgentResponse(e){this.options.onDebug&&this.options.onDebug({type:`tentative_agent_response`,response:e.tentative_agent_response_internal_event.tentative_agent_response})}handleVadScore(e){this.options.onVadScore&&this.options.onVadScore({vadScore:e.vad_score_event.vad_score})}async handleClientToolCall(e){if(Object.prototype.hasOwnProperty.call(this.options.clientTools,e.client_tool_call.tool_name))try{let t=await this.options.clientTools[e.client_tool_call.tool_name](e.client_tool_call.parameters)??`Client tool execution successful.`,n=typeof t==`object`?JSON.stringify(t):String(t);this.connection.sendMessage({type:`client_tool_result`,tool_call_id:e.client_tool_call.tool_call_id,result:n,is_error:!1})}catch(t){this.onError(`Client tool execution failed with following error: ${t?.message}`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:`client_tool_result`,tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool execution failed: ${t?.message}`,is_error:!0})}else{if(this.options.onUnhandledClientToolCall)return void this.options.onUnhandledClientToolCall(e.client_tool_call);this.onError(`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:`client_tool_result`,tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,is_error:!0})}}handleAudio(e){}handleMCPToolCall(e){this.options.onMCPToolCall&&this.options.onMCPToolCall(e.mcp_tool_call)}handleMCPConnectionStatus(e){this.options.onMCPConnectionStatus&&this.options.onMCPConnectionStatus(e.mcp_connection_status)}handleAgentToolRequest(e){this.options.onAgentToolRequest&&this.options.onAgentToolRequest(e.agent_tool_request)}handleAgentToolResponse(e){e.agent_tool_response.tool_name===`end_call`&&this.endSessionWithDetails({reason:`agent`,context:new CloseEvent(`end_call`,{reason:`Agent ended the call`})}),this.options.onAgentToolResponse&&this.options.onAgentToolResponse(e.agent_tool_response)}handleConversationMetadata(e){this.options.onConversationMetadata&&this.options.onConversationMetadata(e.conversation_initiation_metadata_event)}handleAsrInitiationMetadata(e){this.options.onAsrInitiationMetadata&&this.options.onAsrInitiationMetadata(e.asr_initiation_metadata_event)}handleAgentChatResponsePart(e){this.options.onAgentChatResponsePart&&this.options.onAgentChatResponsePart(e.text_response_part)}handleErrorEvent(e){let t=e.error_event.error_type,n=e.error_event.message||e.error_event.reason||`Unknown error`;t===`max_duration_exceeded`?this.endSessionWithDetails({reason:`error`,message:n,context:new Event(`max_duration_exceeded`)}):this.onError(`Server error: ${n}`,{errorType:t,code:e.error_event.code,debugMessage:e.error_event.debug_message,details:e.error_event.details})}onError(e,t){console.error(e,t),this.options.onError&&this.options.onError(e,t)}getId(){return this.connection.conversationId}isOpen(){return this.status===`connected`}setMicMuted(e){this.connection.setMicMuted(e)}getInputByteFrequencyData(){return LE}getOutputByteFrequencyData(){return LE}getInputVolume(){return 0}getOutputVolume(){return 0}sendFeedback(e){this.canSendFeedback?(this.connection.sendMessage({type:`feedback`,score:e?`like`:`dislike`,event_id:this.currentEventId}),this.lastFeedbackEventId=this.currentEventId,this.updateCanSendFeedback()):console.warn(this.lastFeedbackEventId===0?`Cannot send feedback: the conversation has not started yet.`:`Cannot send feedback: feedback has already been sent for the current response.`)}sendContextualUpdate(e){this.connection.sendMessage({type:`contextual_update`,text:e})}sendUserMessage(e){this.connection.sendMessage({type:`user_message`,text:e})}sendUserActivity(){this.connection.sendMessage({type:`user_activity`})}sendMCPToolApprovalResult(e,t){this.connection.sendMessage({type:`mcp_tool_approval_result`,tool_call_id:e,is_approved:t})}},zE=class{constructor(e={}){this.queue=[],this.disconnectionDetails=null,this.onDisconnectCallback=null,this.onMessageCallback=null,this.onModeChangeCallback=null,this.onDebug=void 0,this.onDebug=e.onDebug}debug(e){this.onDebug&&this.onDebug(e)}onMessage(e){this.onMessageCallback=e;let t=this.queue;this.queue=[],t.length>0&&queueMicrotask(()=>{t.forEach(e)})}onDisconnect(e){this.onDisconnectCallback=e;let t=this.disconnectionDetails;t&&queueMicrotask(()=>{e(t)})}onModeChange(e){this.onModeChangeCallback=e}updateMode(e){var t;(t=this.onModeChangeCallback)==null||t.call(this,e)}disconnect(e){var t;this.disconnectionDetails||(this.disconnectionDetails=e,(t=this.onDisconnectCallback)==null||t.call(this,e))}handleMessage(e){this.onMessageCallback?this.onMessageCallback(e):this.queue.push(e)}};function BE(e){let[t,n]=e.split(`_`);if(![`pcm`,`ulaw`].includes(t))throw Error(`Invalid format: ${e}`);let r=Number.parseInt(n);if(Number.isNaN(r))throw Error(`Invalid sample rate: ${n}`);return{format:t,sampleRate:r}}var VE=`0.12.2`;function HE(e){return!!e.type}var UE=`conversation_initiation_client_data`;function WE(e){var t;let n={type:UE};return e.overrides&&(n.conversation_config_override={agent:{prompt:e.overrides.agent?.prompt,first_message:e.overrides.agent?.firstMessage,language:e.overrides.agent?.language},tts:{voice_id:e.overrides.tts?.voiceId,speed:e.overrides.tts?.speed},conversation:{text_only:e.overrides.conversation?.textOnly}}),e.customLlmExtraBody&&(n.custom_llm_extra_body=e.customLlmExtraBody),e.dynamicVariables&&(n.dynamic_variables=e.dynamicVariables),e.userId&&(n.user_id=e.userId),(t=e.overrides)!=null&&t.client&&(n.source_info={source:e.overrides.client.source,version:e.overrides.client.version}),n}var GE=class e extends zE{constructor(e,t,n,r){super(),this.socket=void 0,this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.socket=e,this.conversationId=t,this.inputFormat=n,this.outputFormat=r,this.socket.addEventListener(`error`,e=>{setTimeout(()=>this.disconnect({reason:`error`,message:`The connection was closed due to a socket error.`,context:e}),0)}),this.socket.addEventListener(`close`,e=>{this.disconnect(e.code===1e3?{reason:`agent`,context:e}:{reason:`error`,message:e.reason||`The connection was closed by the server.`,context:e})}),this.socket.addEventListener(`message`,e=>{try{let t=JSON.parse(e.data);if(!HE(t))return void this.debug({type:`invalid_event`,message:`Received invalid socket event`,data:e.data});this.handleMessage(t)}catch(t){this.debug({type:`parsing_error`,message:`Failed to parse socket message`,error:t instanceof Error?t.message:String(t),data:e.data})}})}static async create(t){let n=null;try{var r,i;let a=t.origin??`wss://api.elevenlabs.io`,o,s=((r=t.overrides)==null||(r=r.client)==null?void 0:r.version)||VE,c=((i=t.overrides)==null||(i=i.client)==null?void 0:i.source)||`js_sdk`;if(t.signedUrl){let e=t.signedUrl.includes(`?`)?`&`:`?`;o=`${t.signedUrl}${e}source=${c}&version=${s}`}else o=`${a}/v1/convai/conversation?agent_id=${t.agentId}&source=${c}&version=${s}`;let l=[`convai`];t.authorization&&l.push(`bearer.${t.authorization}`),n=new WebSocket(o,l);let{conversation_id:u,agent_output_audio_format:d,user_input_audio_format:f}=await new Promise((e,r)=>{n.addEventListener(`open`,()=>{var e;let r=WE(t);(e=n)==null||e.send(JSON.stringify(r))},{once:!0}),n.addEventListener(`error`,e=>{setTimeout(()=>r(e),0)}),n.addEventListener(`close`,r),n.addEventListener(`message`,t=>{let n=JSON.parse(t.data);HE(n)&&(n.type===`conversation_initiation_metadata`?e(n.conversation_initiation_metadata_event):console.warn(`First received message is not conversation metadata.`))},{once:!0})}),p=BE(f??`pcm_16000`),m=BE(d);return new e(n,u,p,m)}catch(e){var a;throw(a=n)==null||a.close(),e}}close(){this.socket.close(1e3,`User ended conversation`)}sendMessage(e){this.socket.send(JSON.stringify(e))}async setMicMuted(e){console.warn(`WebSocket connection setMicMuted called with ${e}, but this is handled by VoiceConversation`)}};function KE(e){let t=new Uint8Array(e);return window.btoa(String.fromCharCode(...t))}function qE(e){let t=window.atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return r.buffer}var JE=new Map;function YE(e,t){return async(n,r)=>{let i=JE.get(e);if(i)return n.addModule(i);if(r)try{await n.addModule(r),JE.set(e,r);return}catch(t){throw Error(`Failed to load the ${e} worklet module from path: ${r}. Error: ${t}`)}let a=new Blob([t],{type:`application/javascript`}),o=URL.createObjectURL(a);try{await n.addModule(o),JE.set(e,o);return}catch{URL.revokeObjectURL(o)}try{let r=`data:application/javascript;base64,${btoa(t)}`;await n.addModule(r),JE.set(e,r)}catch{throw Error(`Failed to load the ${e} worklet module. Make sure the browser supports AudioWorklets. If you are using a strict CSP, you may need to self-host the worklet files.`)}}}var XE=YE(`rawAudioProcessor`,`/*
|
|
39
63
|
* ulaw encoding logic taken from the wavefile library
|
|
40
64
|
* https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js
|
|
41
65
|
* USED BY @elevenlabs/client
|
|
@@ -159,7 +183,7 @@ class RawAudioProcessor extends AudioWorkletProcessor {
|
|
|
159
183
|
}
|
|
160
184
|
}
|
|
161
185
|
registerProcessor("rawAudioProcessor", RawAudioProcessor);
|
|
162
|
-
`),$m=class e extends Vm{constructor(e,t,n,r,i={}){super(i),this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.room=void 0,this.isConnected=!1,this.audioEventId=1,this.audioCaptureContext=null,this.audioElements=[],this.outputDeviceId=null,this.outputAnalyser=null,this.outputFrequencyData=null,this.room=e,this.conversationId=t,this.inputFormat=n,this.outputFormat=r,this.setupRoomEventListeners()}static async create(t){let n;if(`conversationToken`in t&&t.conversationToken)n=t.conversationToken;else{if(!(`agentId`in t)||!t.agentId)throw Error(`Either conversationToken or agentId is required for WebRTC connection`);try{var r,i;let e=((r=t.overrides)==null||(r=r.client)==null?void 0:r.version)||Um,o=((i=t.overrides)==null||(i=i.client)==null?void 0:i.source)||`js_sdk`,s=`${a=t.origin??`https://api.elevenlabs.io`,a.replace(/^wss:\/\//,`https://`)}/v1/convai/conversation/token?agent_id=${t.agentId}&source=${o}&version=${e}`,c=await fetch(s);if(!c.ok)throw Error(`ElevenLabs API returned ${c.status} ${c.statusText}`);if(n=(await c.json()).token,!n)throw Error(`No conversation token received from API`)}catch(e){let n=e instanceof Error?e.message:String(e);throw e instanceof Error&&e.message.includes(`401`)&&(n=`Your agent has authentication enabled, but no signed URL or conversation token was provided.`),Error(`Failed to fetch conversation token for agent ${t.agentId}: ${n}`)}}var a;let o=new Mm;try{let r=new e(o,`room_${Date.now()}`,Hm(`pcm_48000`),Hm(`pcm_48000`),t),i=t.livekitUrl||`wss://livekit.rtc.elevenlabs.io`;await o.connect(i,n),await new Promise(e=>{if(r.isConnected)e();else{let t=()=>{o.off(R.Connected,t),e()};o.on(R.Connected,t)}}),o.name&&(r.conversationId=o.name.match(/(conv_[a-zA-Z0-9]+)/)?.[0]||o.name),await o.localParticipant.setMicrophoneEnabled(!0);let a=Km(t);return r.debug({type:Gm,message:a}),await r.sendMessage(a),r}catch(e){throw await o.disconnect(),e}}setupRoomEventListeners(){var e=this;this.room.on(R.Connected,async function(){e.isConnected=!0,console.info(`WebRTC room connected`)}),this.room.on(R.Disconnected,e=>{this.isConnected=!1,this.disconnect({reason:`agent`,context:new CloseEvent(`close`,{reason:e?.toString()})})}),this.room.on(R.ConnectionStateChanged,e=>{e===q.Disconnected&&(this.isConnected=!1,this.disconnect({reason:`error`,message:`LiveKit connection state changed to ${e}`,context:new Event(`connection_state_changed`)}))}),this.room.on(R.DataReceived,(e,t)=>{try{let t=JSON.parse(new TextDecoder().decode(e));if(t.type===`audio`)return;Wm(t)?this.handleMessage(t):console.warn(`Invalid socket event received:`,t)}catch(t){console.warn(`Failed to parse incoming data message:`,t),console.warn(`Raw payload:`,new TextDecoder().decode(e))}}),this.room.on(R.TrackSubscribed,async function(t,n,r){if(t.kind===W.Kind.Audio&&r.identity.includes(`agent`)){let n=t,r=n.attach();if(r.autoplay=!0,r.controls=!1,e.outputDeviceId&&r.setSinkId)try{await r.setSinkId(e.outputDeviceId)}catch(e){console.warn(`Failed to set output device for new audio element:`,e)}r.style.display=`none`,document.body.appendChild(r),e.audioElements.push(r),e.audioElements.length===1&&(e.onDebug==null||e.onDebug({type:`audio_element_ready`})),await e.setupAudioCapture(n)}}),this.room.on(R.ActiveSpeakersChanged,async function(t){e.updateMode(t.length>0&&t[0].identity.startsWith(`agent`)?`speaking`:`listening`)}),this.room.on(R.ParticipantDisconnected,e=>{var t;(t=e.identity)!=null&&t.startsWith(`agent`)&&this.disconnect({reason:`agent`,context:new CloseEvent(`close`,{reason:`agent disconnected`})})})}close(){if(this.isConnected){try{this.room.localParticipant.audioTrackPublications.forEach(e=>{e.track&&e.track.stop()})}catch(e){console.warn(`Error stopping local tracks:`,e)}this.audioCaptureContext&&=(this.audioCaptureContext.close().catch(e=>{console.warn(`Error closing audio capture context:`,e)}),null),this.audioElements.forEach(e=>{e.parentNode&&e.parentNode.removeChild(e)}),this.audioElements=[],this.room.disconnect()}}async sendMessage(e){if(this.isConnected&&this.room.localParticipant){if(!(`user_audio_chunk`in e))try{let t=new TextEncoder().encode(JSON.stringify(e));await this.room.localParticipant.publishData(t,{reliable:!0})}catch(t){this.debug({type:`send_message_error`,message:{message:e,error:t}}),console.error(`Failed to send message via WebRTC:`,t)}}else console.warn(`Cannot send message: room not connected or no local participant`)}getRoom(){return this.room}async setMicMuted(e){if(!this.isConnected||!this.room.localParticipant)return void console.warn(`Cannot set microphone muted: room not connected or no local participant`);let t=this.room.localParticipant.getTrackPublication(W.Source.Microphone);if(t!=null&&t.track)try{e?await t.track.mute():await t.track.unmute()}catch{await this.room.localParticipant.setMicrophoneEnabled(!e)}else await this.room.localParticipant.setMicrophoneEnabled(!e)}async setupAudioCapture(e){try{let t=new AudioContext;this.audioCaptureContext=t,this.outputAnalyser=t.createAnalyser(),this.outputAnalyser.fftSize=2048,this.outputAnalyser.smoothingTimeConstant=.8;let n=new MediaStream([e.mediaStreamTrack]),r=t.createMediaStreamSource(n);r.connect(this.outputAnalyser),await Qm(t.audioWorklet);let i=new AudioWorkletNode(t,`rawAudioProcessor`);this.outputAnalyser.connect(i),i.port.postMessage({type:`setFormat`,format:this.outputFormat.format,sampleRate:this.outputFormat.sampleRate}),i.port.onmessage=e=>{let[t,n]=e.data;if(n>.01){let e=Jm(t.buffer),n=this.audioEventId++;this.handleMessage({type:`audio`,audio_event:{audio_base_64:e,event_id:n}})}},r.connect(i)}catch(e){console.warn(`Failed to set up audio capture:`,e)}}setAudioVolume(e){this.audioElements.forEach(t=>{t.volume=e})}async setAudioOutputDevice(e){if(!(`setSinkId`in HTMLAudioElement.prototype))throw Error(`setSinkId is not supported in this browser`);let t=this.audioElements.map(async function(t){try{await t.setSinkId(e)}catch(e){throw console.error(`Failed to set sink ID for audio element:`,e),e}});await Promise.all(t),this.outputDeviceId=e}async setAudioInputDevice(e){if(!this.isConnected||!this.room.localParticipant)throw Error(`Cannot change input device: room not connected or no local participant`);try{let t=this.room.localParticipant.getTrackPublication(W.Source.Microphone);t!=null&&t.track&&(await t.track.stop(),await this.room.localParticipant.unpublishTrack(t.track));let n=await xm({deviceId:{exact:e},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}});await this.room.localParticipant.publishTrack(n,{name:`microphone`,source:W.Source.Microphone})}catch(e){console.error(`Failed to change input device:`,e);try{await this.room.localParticipant.setMicrophoneEnabled(!0)}catch(e){console.error(`Failed to recover microphone after device switch error:`,e)}throw e}}getOutputByteFrequencyData(){return this.outputAnalyser?(this.outputFrequencyData??=new Uint8Array(this.outputAnalyser.frequencyBinCount),this.outputAnalyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData):null}};async function eh(e){let t=function(e){return e.connectionType?e.connectionType:`conversationToken`in e&&e.conversationToken?`webrtc`:`websocket`}(e);switch(t){case`websocket`:return qm.create(e);case`webrtc`:return $m.create(e);default:throw Error(`Unknown connection type: ${t}`)}}function th(){return[`iPad Simulator`,`iPhone Simulator`,`iPod Simulator`,`iPad`,`iPhone`,`iPod`].includes(navigator.platform)||navigator.userAgent.includes(`Mac`)&&`ontouchend`in document}async function nh(e={default:0,android:3e3}){let t=e.default;/android/i.test(navigator.userAgent)?t=e.android??t:th()&&(t=e.ios??t),t>0&&await new Promise(e=>setTimeout(e,t))}var rh=class e extends Bm{static async startSession(t){let n=Bm.getFullOptions(t);n.onStatusChange&&n.onStatusChange({status:`connecting`}),n.onCanSendFeedbackChange&&n.onCanSendFeedbackChange({canSendFeedback:!1}),n.onModeChange&&n.onModeChange({mode:`listening`}),n.onCanSendFeedbackChange&&n.onCanSendFeedbackChange({canSendFeedback:!1});let r=null;try{return await nh(n.connectionDelay),r=await eh(t),new e(n,r)}catch(e){var i;throw n.onStatusChange&&n.onStatusChange({status:`disconnected`}),(i=r)==null||i.close(),e}}},ih={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}},ah=class e{static async create({sampleRate:t,format:n,preferHeadphonesForIosDevices:r,inputDeviceId:i,workletPaths:a,libsampleratePath:o}){let s=null,c=null;try{let l=Rm({sampleRate:{ideal:t}},ih);if(th()&&r){let e=(await window.navigator.mediaDevices.enumerateDevices()).find(e=>e.kind===`audioinput`&&[`airpod`,`headphone`,`earphone`].find(t=>e.label.toLowerCase().includes(t)));e&&(l.deviceId={ideal:e.deviceId})}i&&(l.deviceId=e.getDeviceIdConstraint(i));let u=navigator.mediaDevices.getSupportedConstraints().sampleRate;s=new window.AudioContext(u?{sampleRate:t}:{});let d=s.createAnalyser();if(!u){let e=o||`https://cdn.jsdelivr.net/npm/@alexanderolsen/libsamplerate-js@2.1.2/dist/libsamplerate.worklet.js`;await s.audioWorklet.addModule(e)}await Qm(s.audioWorklet,a?.rawAudioProcessor);let f=Rm({voiceIsolation:!0},l);c=await navigator.mediaDevices.getUserMedia({audio:f});let p=s.createMediaStreamSource(c),m=new AudioWorkletNode(s,`rawAudioProcessor`);return m.port.postMessage({type:`setFormat`,format:n,sampleRate:t}),p.connect(d),d.connect(m),await s.resume(),new e(s,d,m,c,p)}catch(e){var l,u;throw(l=c)==null||l.getTracks().forEach(e=>{e.stop()}),(u=s)==null||u.close(),e}}static getDeviceIdConstraint(e){if(e)return th()?{ideal:e}:{exact:e}}constructor(e,t,n,r,i){this.context=void 0,this.analyser=void 0,this.worklet=void 0,this.inputStream=void 0,this.mediaStreamSource=void 0,this.context=e,this.analyser=t,this.worklet=n,this.inputStream=r,this.mediaStreamSource=i}async close(){this.inputStream.getTracks().forEach(e=>{e.stop()}),this.mediaStreamSource.disconnect(),await this.context.close()}setMuted(e){this.worklet.port.postMessage({type:`setMuted`,isMuted:e})}async setInputDevice(t){try{let n=Rm({},ih);t&&(n.deviceId=e.getDeviceIdConstraint(t));let r=Rm({voiceIsolation:!0},n),i=await navigator.mediaDevices.getUserMedia({audio:r});this.inputStream.getTracks().forEach(e=>{e.stop()}),this.mediaStreamSource.disconnect(),this.inputStream=i,this.mediaStreamSource=this.context.createMediaStreamSource(i),this.mediaStreamSource.connect(this.analyser)}catch(e){throw console.error(`Failed to switch input device:`,e),e}}},oh=Zm(`audioConcatProcessor`,`/*
|
|
186
|
+
`),ZE=class e extends zE{constructor(e,t,n,r,i={}){super(i),this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.room=void 0,this.isConnected=!1,this.audioEventId=1,this.audioCaptureContext=null,this.audioElements=[],this.outputDeviceId=null,this.outputAnalyser=null,this.outputFrequencyData=null,this.room=e,this.conversationId=t,this.inputFormat=n,this.outputFormat=r,this.setupRoomEventListeners()}static async create(t){let n;if(`conversationToken`in t&&t.conversationToken)n=t.conversationToken;else{if(!(`agentId`in t)||!t.agentId)throw Error(`Either conversationToken or agentId is required for WebRTC connection`);try{var r,i;let e=((r=t.overrides)==null||(r=r.client)==null?void 0:r.version)||VE,o=((i=t.overrides)==null||(i=i.client)==null?void 0:i.source)||`js_sdk`,s=`${a=t.origin??`https://api.elevenlabs.io`,a.replace(/^wss:\/\//,`https://`)}/v1/convai/conversation/token?agent_id=${t.agentId}&source=${o}&version=${e}`,c=await fetch(s);if(!c.ok)throw Error(`ElevenLabs API returned ${c.status} ${c.statusText}`);if(n=(await c.json()).token,!n)throw Error(`No conversation token received from API`)}catch(e){let n=e instanceof Error?e.message:String(e);throw e instanceof Error&&e.message.includes(`401`)&&(n=`Your agent has authentication enabled, but no signed URL or conversation token was provided.`),Error(`Failed to fetch conversation token for agent ${t.agentId}: ${n}`)}}var a;let o=new AE;try{let r=new e(o,`room_${Date.now()}`,BE(`pcm_48000`),BE(`pcm_48000`),t),i=t.livekitUrl||`wss://livekit.rtc.elevenlabs.io`;await o.connect(i,n),await new Promise(e=>{if(r.isConnected)e();else{let t=()=>{o.off(V.Connected,t),e()};o.on(V.Connected,t)}}),o.name&&(r.conversationId=o.name.match(/(conv_[a-zA-Z0-9]+)/)?.[0]||o.name),await o.localParticipant.setMicrophoneEnabled(!0);let a=WE(t);return r.debug({type:UE,message:a}),await r.sendMessage(a),r}catch(e){throw await o.disconnect(),e}}setupRoomEventListeners(){var e=this;this.room.on(V.Connected,async function(){e.isConnected=!0,console.info(`WebRTC room connected`)}),this.room.on(V.Disconnected,e=>{this.isConnected=!1,this.disconnect({reason:`agent`,context:new CloseEvent(`close`,{reason:e?.toString()})})}),this.room.on(V.ConnectionStateChanged,e=>{e===Y.Disconnected&&(this.isConnected=!1,this.disconnect({reason:`error`,message:`LiveKit connection state changed to ${e}`,context:new Event(`connection_state_changed`)}))}),this.room.on(V.DataReceived,(e,t)=>{try{let t=JSON.parse(new TextDecoder().decode(e));if(t.type===`audio`)return;HE(t)?this.handleMessage(t):console.warn(`Invalid socket event received:`,t)}catch(t){console.warn(`Failed to parse incoming data message:`,t),console.warn(`Raw payload:`,new TextDecoder().decode(e))}}),this.room.on(V.TrackSubscribed,async function(t,n,r){if(t.kind===q.Kind.Audio&&r.identity.includes(`agent`)){let n=t,r=n.attach();if(r.autoplay=!0,r.controls=!1,e.outputDeviceId&&r.setSinkId)try{await r.setSinkId(e.outputDeviceId)}catch(e){console.warn(`Failed to set output device for new audio element:`,e)}r.style.display=`none`,document.body.appendChild(r),e.audioElements.push(r),e.audioElements.length===1&&(e.onDebug==null||e.onDebug({type:`audio_element_ready`})),await e.setupAudioCapture(n)}}),this.room.on(V.ActiveSpeakersChanged,async function(t){e.updateMode(t.length>0&&t[0].identity.startsWith(`agent`)?`speaking`:`listening`)}),this.room.on(V.ParticipantDisconnected,e=>{var t;(t=e.identity)!=null&&t.startsWith(`agent`)&&this.disconnect({reason:`agent`,context:new CloseEvent(`close`,{reason:`agent disconnected`})})})}close(){if(this.isConnected){try{this.room.localParticipant.audioTrackPublications.forEach(e=>{e.track&&e.track.stop()})}catch(e){console.warn(`Error stopping local tracks:`,e)}this.audioCaptureContext&&=(this.audioCaptureContext.close().catch(e=>{console.warn(`Error closing audio capture context:`,e)}),null),this.audioElements.forEach(e=>{e.parentNode&&e.parentNode.removeChild(e)}),this.audioElements=[],this.room.disconnect()}}async sendMessage(e){if(this.isConnected&&this.room.localParticipant){if(!(`user_audio_chunk`in e))try{let t=new TextEncoder().encode(JSON.stringify(e));await this.room.localParticipant.publishData(t,{reliable:!0})}catch(t){this.debug({type:`send_message_error`,message:{message:e,error:t}}),console.error(`Failed to send message via WebRTC:`,t)}}else console.warn(`Cannot send message: room not connected or no local participant`)}getRoom(){return this.room}async setMicMuted(e){if(!this.isConnected||!this.room.localParticipant)return void console.warn(`Cannot set microphone muted: room not connected or no local participant`);let t=this.room.localParticipant.getTrackPublication(q.Source.Microphone);if(t!=null&&t.track)try{e?await t.track.mute():await t.track.unmute()}catch{await this.room.localParticipant.setMicrophoneEnabled(!e)}else await this.room.localParticipant.setMicrophoneEnabled(!e)}async setupAudioCapture(e){try{let t=new AudioContext;this.audioCaptureContext=t,this.outputAnalyser=t.createAnalyser(),this.outputAnalyser.fftSize=2048,this.outputAnalyser.smoothingTimeConstant=.8;let n=new MediaStream([e.mediaStreamTrack]),r=t.createMediaStreamSource(n);r.connect(this.outputAnalyser),await XE(t.audioWorklet);let i=new AudioWorkletNode(t,`rawAudioProcessor`);this.outputAnalyser.connect(i),i.port.postMessage({type:`setFormat`,format:this.outputFormat.format,sampleRate:this.outputFormat.sampleRate}),i.port.onmessage=e=>{let[t,n]=e.data;if(n>.01){let e=KE(t.buffer),n=this.audioEventId++;this.handleMessage({type:`audio`,audio_event:{audio_base_64:e,event_id:n}})}},r.connect(i)}catch(e){console.warn(`Failed to set up audio capture:`,e)}}setAudioVolume(e){this.audioElements.forEach(t=>{t.volume=e})}async setAudioOutputDevice(e){if(!(`setSinkId`in HTMLAudioElement.prototype))throw Error(`setSinkId is not supported in this browser`);let t=this.audioElements.map(async function(t){try{await t.setSinkId(e)}catch(e){throw console.error(`Failed to set sink ID for audio element:`,e),e}});await Promise.all(t),this.outputDeviceId=e}async setAudioInputDevice(e){if(!this.isConnected||!this.room.localParticipant)throw Error(`Cannot change input device: room not connected or no local participant`);try{let t=this.room.localParticipant.getTrackPublication(q.Source.Microphone);t!=null&&t.track&&(await t.track.stop(),await this.room.localParticipant.unpublishTrack(t.track));let n=await yE({deviceId:{exact:e},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}});await this.room.localParticipant.publishTrack(n,{name:`microphone`,source:q.Source.Microphone})}catch(e){console.error(`Failed to change input device:`,e);try{await this.room.localParticipant.setMicrophoneEnabled(!0)}catch(e){console.error(`Failed to recover microphone after device switch error:`,e)}throw e}}getOutputByteFrequencyData(){return this.outputAnalyser?(this.outputFrequencyData??=new Uint8Array(this.outputAnalyser.frequencyBinCount),this.outputAnalyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData):null}};async function QE(e){let t=function(e){return e.connectionType?e.connectionType:`conversationToken`in e&&e.conversationToken?`webrtc`:`websocket`}(e);switch(t){case`websocket`:return GE.create(e);case`webrtc`:return ZE.create(e);default:throw Error(`Unknown connection type: ${t}`)}}function $E(){return[`iPad Simulator`,`iPhone Simulator`,`iPod Simulator`,`iPad`,`iPhone`,`iPod`].includes(navigator.platform)||navigator.userAgent.includes(`Mac`)&&`ontouchend`in document}async function eD(e={default:0,android:3e3}){let t=e.default;/android/i.test(navigator.userAgent)?t=e.android??t:$E()&&(t=e.ios??t),t>0&&await new Promise(e=>setTimeout(e,t))}var tD=class e extends RE{static async startSession(t){let n=RE.getFullOptions(t);n.onStatusChange&&n.onStatusChange({status:`connecting`}),n.onCanSendFeedbackChange&&n.onCanSendFeedbackChange({canSendFeedback:!1}),n.onModeChange&&n.onModeChange({mode:`listening`}),n.onCanSendFeedbackChange&&n.onCanSendFeedbackChange({canSendFeedback:!1});let r=null;try{return await eD(n.connectionDelay),r=await QE(t),new e(n,r)}catch(e){var i;throw n.onStatusChange&&n.onStatusChange({status:`disconnected`}),(i=r)==null||i.close(),e}}},nD={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}},rD=class e{static async create({sampleRate:t,format:n,preferHeadphonesForIosDevices:r,inputDeviceId:i,workletPaths:a,libsampleratePath:o}){let s=null,c=null;try{let l=IE({sampleRate:{ideal:t}},nD);if($E()&&r){let e=(await window.navigator.mediaDevices.enumerateDevices()).find(e=>e.kind===`audioinput`&&[`airpod`,`headphone`,`earphone`].find(t=>e.label.toLowerCase().includes(t)));e&&(l.deviceId={ideal:e.deviceId})}i&&(l.deviceId=e.getDeviceIdConstraint(i));let u=navigator.mediaDevices.getSupportedConstraints().sampleRate;s=new window.AudioContext(u?{sampleRate:t}:{});let d=s.createAnalyser();if(!u){let e=o||`https://cdn.jsdelivr.net/npm/@alexanderolsen/libsamplerate-js@2.1.2/dist/libsamplerate.worklet.js`;await s.audioWorklet.addModule(e)}await XE(s.audioWorklet,a?.rawAudioProcessor);let f=IE({voiceIsolation:!0},l);c=await navigator.mediaDevices.getUserMedia({audio:f});let p=s.createMediaStreamSource(c),m=new AudioWorkletNode(s,`rawAudioProcessor`);return m.port.postMessage({type:`setFormat`,format:n,sampleRate:t}),p.connect(d),d.connect(m),await s.resume(),new e(s,d,m,c,p)}catch(e){var l,u;throw(l=c)==null||l.getTracks().forEach(e=>{e.stop()}),(u=s)==null||u.close(),e}}static getDeviceIdConstraint(e){if(e)return $E()?{ideal:e}:{exact:e}}constructor(e,t,n,r,i){this.context=void 0,this.analyser=void 0,this.worklet=void 0,this.inputStream=void 0,this.mediaStreamSource=void 0,this.context=e,this.analyser=t,this.worklet=n,this.inputStream=r,this.mediaStreamSource=i}async close(){this.inputStream.getTracks().forEach(e=>{e.stop()}),this.mediaStreamSource.disconnect(),await this.context.close()}setMuted(e){this.worklet.port.postMessage({type:`setMuted`,isMuted:e})}async setInputDevice(t){try{let n=IE({},nD);t&&(n.deviceId=e.getDeviceIdConstraint(t));let r=IE({voiceIsolation:!0},n),i=await navigator.mediaDevices.getUserMedia({audio:r});this.inputStream.getTracks().forEach(e=>{e.stop()}),this.mediaStreamSource.disconnect(),this.inputStream=i,this.mediaStreamSource=this.context.createMediaStreamSource(i),this.mediaStreamSource.connect(this.analyser)}catch(e){throw console.error(`Failed to switch input device:`,e),e}}},iD=YE(`audioConcatProcessor`,`/*
|
|
163
187
|
* ulaw decoding logic taken from the wavefile library
|
|
164
188
|
* https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js
|
|
165
189
|
* USED BY @elevenlabs/client
|
|
@@ -251,7 +275,7 @@ class AudioConcatProcessor extends AudioWorkletProcessor {
|
|
|
251
275
|
}
|
|
252
276
|
|
|
253
277
|
registerProcessor("audioConcatProcessor", AudioConcatProcessor);
|
|
254
|
-
`),sh=class e{static async create({sampleRate:t,format:n,outputDeviceId:r,workletPaths:i}){let a=null,o=null;try{a=new AudioContext({sampleRate:t});let s=a.createAnalyser(),c=a.createGain();o=new Audio,o.src=``,o.load(),o.autoplay=!0,o.style.display=`none`,document.body.appendChild(o);let l=a.createMediaStreamDestination();o.srcObject=l.stream,c.connect(s),s.connect(l),await oh(a.audioWorklet,i?.audioConcatProcessor);let u=new AudioWorkletNode(a,`audioConcatProcessor`);return u.port.postMessage({type:`setFormat`,format:n}),u.connect(c),await a.resume(),r&&o.setSinkId&&await o.setSinkId(r),new e(a,s,c,u,o)}catch(e){var s,c;throw(s=o)!=null&&s.parentNode&&o.parentNode.removeChild(o),(c=o)==null||c.pause(),a&&a.state!==`closed`&&await a.close(),e}}constructor(e,t,n,r,i){this.context=void 0,this.analyser=void 0,this.gain=void 0,this.worklet=void 0,this.audioElement=void 0,this.context=e,this.analyser=t,this.gain=n,this.worklet=r,this.audioElement=i}async setOutputDevice(e){if(!(`setSinkId`in HTMLAudioElement.prototype))throw Error(`setSinkId is not supported in this browser`);await this.audioElement.setSinkId(e||``)}async close(){this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement),this.audioElement.pause(),await this.context.close()}},ch=class e extends Bm{static async startSession(t){var n;let r=Bm.getFullOptions(t);r.onStatusChange&&r.onStatusChange({status:`connecting`}),r.onCanSendFeedbackChange&&r.onCanSendFeedbackChange({canSendFeedback:!1});let i=null,a=null,o=null,s=null,c=null;if((n=t.useWakeLock)==null||n)try{c=await navigator.wakeLock.request(`screen`)}catch{}try{var l;return s=await navigator.mediaDevices.getUserMedia({audio:!0}),await nh(r.connectionDelay),a=await eh(t),[i,o]=await Promise.all([ah.create(Rm({},a.inputFormat,{preferHeadphonesForIosDevices:t.preferHeadphonesForIosDevices,inputDeviceId:t.inputDeviceId,workletPaths:t.workletPaths,libsampleratePath:t.libsampleratePath})),sh.create(Rm({},a.outputFormat,{outputDeviceId:t.outputDeviceId,workletPaths:t.workletPaths}))]),(l=s)==null||l.getTracks().forEach(e=>{e.stop()}),s=null,new e(r,a,i,o,c)}catch(e){var u,d;r.onStatusChange&&r.onStatusChange({status:`disconnected`}),(u=s)==null||u.getTracks().forEach(e=>{e.stop()}),(d=a)==null||d.close(),await i?.close(),await o?.close();try{await c?.release(),c=null}catch{}throw e}}constructor(e,t,n,r,i){super(e,t),this.input=void 0,this.output=void 0,this.wakeLock=void 0,this.inputFrequencyData=void 0,this.outputFrequencyData=void 0,this.onInputWorkletMessage=e=>{this.status===`connected`&&this.connection.sendMessage({user_audio_chunk:Jm(e.data[0].buffer)})},this.onOutputWorkletMessage=({data:e})=>{e.type===`process`&&this.updateMode(e.finished?`listening`:`speaking`)},this.addAudioBase64Chunk=e=>{this.output.gain.gain.cancelScheduledValues(this.output.context.currentTime),this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:`clearInterrupted`}),this.output.worklet.port.postMessage({type:`buffer`,buffer:Ym(e)})},this.fadeOutAudio=()=>{this.updateMode(`listening`),this.output.worklet.port.postMessage({type:`interrupt`}),this.output.gain.gain.exponentialRampToValueAtTime(1e-4,this.output.context.currentTime+2),setTimeout(()=>{this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:`clearInterrupted`})},2e3)},this.calculateVolume=e=>{if(e.length===0)return 0;let t=0;for(let n=0;n<e.length;n++)t+=e[n]/255;return t/=e.length,t<0?0:t>1?1:t},this.setVolume=({volume:e})=>{let t=Number.isFinite(e)?Math.min(1,Math.max(0,e)):1;this.volume=t,this.connection instanceof $m?this.connection.setAudioVolume(t):this.output.gain.gain.value=t},this.input=n,this.output=r,this.wakeLock=i,this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.output.worklet.port.onmessage=this.onOutputWorkletMessage}async handleEndSession(){await super.handleEndSession();try{await this.wakeLock?.release(),this.wakeLock=null}catch{}await this.input.close(),await this.output.close()}handleInterruption(e){super.handleInterruption(e),this.fadeOutAudio()}handleAudio(e){var t,n;this.lastInterruptTimestamp<=e.audio_event.event_id&&((t=(n=this.options).onAudio)==null||t.call(n,e.audio_event.audio_base_64),this.connection instanceof $m||this.addAudioBase64Chunk(e.audio_event.audio_base_64),this.currentEventId=e.audio_event.event_id,this.updateCanSendFeedback(),this.updateMode(`speaking`))}setMicMuted(e){this.connection instanceof $m?this.connection.setMicMuted(e):this.input.setMuted(e)}getInputByteFrequencyData(){return this.inputFrequencyData??=new Uint8Array(this.input.analyser.frequencyBinCount),this.input.analyser.getByteFrequencyData(this.inputFrequencyData),this.inputFrequencyData}getOutputByteFrequencyData(){return this.connection instanceof $m?this.connection.getOutputByteFrequencyData()||new Uint8Array(1024):(this.outputFrequencyData??=new Uint8Array(this.output.analyser.frequencyBinCount),this.output.analyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData)}getInputVolume(){return this.calculateVolume(this.getInputByteFrequencyData())}getOutputVolume(){return this.calculateVolume(this.getOutputByteFrequencyData())}async changeInputDevice({sampleRate:e,format:t,preferHeadphonesForIosDevices:n,inputDeviceId:r}){try{if(this.connection instanceof qm)try{return await this.input.setInputDevice(r),this.input}catch(e){console.warn(`Failed to change device on existing input, recreating:`,e)}return this.connection instanceof $m&&await this.connection.setAudioInputDevice(r||``),await this.input.close(),this.input=await ah.create({sampleRate:e??this.connection.inputFormat.sampleRate,format:t??this.connection.inputFormat.format,preferHeadphonesForIosDevices:n,inputDeviceId:r,workletPaths:this.options.workletPaths,libsampleratePath:this.options.libsampleratePath}),this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.input}catch(e){throw console.error(`Error changing input device`,e),e}}async changeOutputDevice({sampleRate:e,format:t,outputDeviceId:n}){try{if(this.connection instanceof qm)try{return await this.output.setOutputDevice(n),this.output}catch(e){console.warn(`Failed to change device on existing output, recreating:`,e)}return this.connection instanceof $m&&await this.connection.setAudioOutputDevice(n||``),await this.output.close(),this.output=await sh.create({sampleRate:e??this.connection.outputFormat.sampleRate,format:t??this.connection.outputFormat.format,outputDeviceId:n,workletPaths:this.options.workletPaths}),this.output}catch(e){throw console.error(`Error changing output device`,e),e}}},lh=class{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);let n=this.listeners.get(e);n&&n.add(t)}off(e,t){let n=this.listeners.get(e);n&&n.delete(t)}emit(e,...t){let n=this.listeners.get(e);n&&n.forEach(e=>{e(...t)})}},Y;(function(e){e.SESSION_STARTED=`session_started`,e.PARTIAL_TRANSCRIPT=`partial_transcript`,e.COMMITTED_TRANSCRIPT=`committed_transcript`,e.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS=`committed_transcript_with_timestamps`,e.AUTH_ERROR=`auth_error`,e.ERROR=`error`,e.OPEN=`open`,e.CLOSE=`close`,e.QUOTA_EXCEEDED=`quota_exceeded`,e.COMMIT_THROTTLED=`commit_throttled`,e.TRANSCRIBER_ERROR=`transcriber_error`,e.UNACCEPTED_TERMS=`unaccepted_terms`,e.RATE_LIMITED=`rate_limited`,e.INPUT_ERROR=`input_error`,e.QUEUE_OVERFLOW=`queue_overflow`,e.RESOURCE_EXHAUSTED=`resource_exhausted`,e.SESSION_TIME_LIMIT_EXCEEDED=`session_time_limit_exceeded`,e.CHUNK_SIZE_EXCEEDED=`chunk_size_exceeded`,e.INSUFFICIENT_AUDIO_ACTIVITY=`insufficient_audio_activity`})(Y||={});var uh=class{constructor(e){this.websocket=null,this.eventEmitter=new lh,this.currentSampleRate=16e3,this._audioCleanup=void 0,this.currentSampleRate=e}setWebSocket(e){this.websocket=e,this.websocket.readyState===WebSocket.OPEN?this.eventEmitter.emit(Y.OPEN):this.websocket.addEventListener(`open`,()=>{this.eventEmitter.emit(Y.OPEN)}),this.websocket.addEventListener(`message`,e=>{try{let t=JSON.parse(e.data);switch(t.message_type){case`session_started`:this.eventEmitter.emit(Y.SESSION_STARTED,t);break;case`partial_transcript`:this.eventEmitter.emit(Y.PARTIAL_TRANSCRIPT,t);break;case`committed_transcript`:this.eventEmitter.emit(Y.COMMITTED_TRANSCRIPT,t);break;case`committed_transcript_with_timestamps`:this.eventEmitter.emit(Y.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS,t);break;case`auth_error`:this.eventEmitter.emit(Y.AUTH_ERROR,t),this.eventEmitter.emit(Y.ERROR,t);break;case`quota_exceeded`:this.eventEmitter.emit(Y.QUOTA_EXCEEDED,t),this.eventEmitter.emit(Y.ERROR,t);break;case`commit_throttled`:this.eventEmitter.emit(Y.COMMIT_THROTTLED,t),this.eventEmitter.emit(Y.ERROR,t);break;case`transcriber_error`:this.eventEmitter.emit(Y.TRANSCRIBER_ERROR,t),this.eventEmitter.emit(Y.ERROR,t);break;case`unaccepted_terms`:this.eventEmitter.emit(Y.UNACCEPTED_TERMS,t),this.eventEmitter.emit(Y.ERROR,t);break;case`rate_limited`:this.eventEmitter.emit(Y.RATE_LIMITED,t),this.eventEmitter.emit(Y.ERROR,t);break;case`input_error`:this.eventEmitter.emit(Y.INPUT_ERROR,t),this.eventEmitter.emit(Y.ERROR,t);break;case`queue_overflow`:this.eventEmitter.emit(Y.QUEUE_OVERFLOW,t),this.eventEmitter.emit(Y.ERROR,t);break;case`resource_exhausted`:this.eventEmitter.emit(Y.RESOURCE_EXHAUSTED,t),this.eventEmitter.emit(Y.ERROR,t);break;case`session_time_limit_exceeded`:this.eventEmitter.emit(Y.SESSION_TIME_LIMIT_EXCEEDED,t),this.eventEmitter.emit(Y.ERROR,t);break;case`chunk_size_exceeded`:this.eventEmitter.emit(Y.CHUNK_SIZE_EXCEEDED,t),this.eventEmitter.emit(Y.ERROR,t);break;case`insufficient_audio_activity`:this.eventEmitter.emit(Y.INSUFFICIENT_AUDIO_ACTIVITY,t),this.eventEmitter.emit(Y.ERROR,t);break;case`error`:this.eventEmitter.emit(Y.ERROR,t);break;default:console.warn(`Unknown message type:`,t)}}catch(t){console.error(`Failed to parse WebSocket message:`,t,e.data),this.eventEmitter.emit(Y.ERROR,Error(`Failed to parse message: ${t}`))}}),this.websocket.addEventListener(`error`,e=>{console.error(`WebSocket error:`,e),this.eventEmitter.emit(Y.ERROR,e)}),this.websocket.addEventListener(`close`,e=>{if(console.log(`WebSocket closed: code=${e.code}, reason="${e.reason}", wasClean=${e.wasClean}`),!e.wasClean||e.code!==1e3&&e.code!==1005){let t=`WebSocket closed unexpectedly: ${e.code} - ${e.reason||`No reason provided`}`;console.error(t),this.eventEmitter.emit(Y.ERROR,Error(t))}this.eventEmitter.emit(Y.CLOSE,e)})}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}send(e){var t;if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw Error(`WebSocket is not connected`);let n={message_type:`input_audio_chunk`,audio_base_64:e.audioBase64,commit:(t=e.commit)!=null&&t,sample_rate:e.sampleRate??this.currentSampleRate,previous_text:e.previousText};this.websocket.send(JSON.stringify(n))}commit(){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw Error(`WebSocket is not connected`);this.websocket.send(JSON.stringify({message_type:`input_audio_chunk`,audio_base_64:``,commit:!0,sample_rate:this.currentSampleRate}))}close(){this._audioCleanup&&this._audioCleanup(),this.websocket&&this.websocket.close(1e3,`User ended session`)}},dh=Zm(`scribeAudioProcessor`,`/*
|
|
278
|
+
`),aD=class e{static async create({sampleRate:t,format:n,outputDeviceId:r,workletPaths:i}){let a=null,o=null;try{a=new AudioContext({sampleRate:t});let s=a.createAnalyser(),c=a.createGain();o=new Audio,o.src=``,o.load(),o.autoplay=!0,o.style.display=`none`,document.body.appendChild(o);let l=a.createMediaStreamDestination();o.srcObject=l.stream,c.connect(s),s.connect(l),await iD(a.audioWorklet,i?.audioConcatProcessor);let u=new AudioWorkletNode(a,`audioConcatProcessor`);return u.port.postMessage({type:`setFormat`,format:n}),u.connect(c),await a.resume(),r&&o.setSinkId&&await o.setSinkId(r),new e(a,s,c,u,o)}catch(e){var s,c;throw(s=o)!=null&&s.parentNode&&o.parentNode.removeChild(o),(c=o)==null||c.pause(),a&&a.state!==`closed`&&await a.close(),e}}constructor(e,t,n,r,i){this.context=void 0,this.analyser=void 0,this.gain=void 0,this.worklet=void 0,this.audioElement=void 0,this.context=e,this.analyser=t,this.gain=n,this.worklet=r,this.audioElement=i}async setOutputDevice(e){if(!(`setSinkId`in HTMLAudioElement.prototype))throw Error(`setSinkId is not supported in this browser`);await this.audioElement.setSinkId(e||``)}async close(){this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement),this.audioElement.pause(),await this.context.close()}},oD=class e extends RE{static async startSession(t){var n;let r=RE.getFullOptions(t);r.onStatusChange&&r.onStatusChange({status:`connecting`}),r.onCanSendFeedbackChange&&r.onCanSendFeedbackChange({canSendFeedback:!1});let i=null,a=null,o=null,s=null,c=null;if((n=t.useWakeLock)==null||n)try{c=await navigator.wakeLock.request(`screen`)}catch{}try{var l;return s=await navigator.mediaDevices.getUserMedia({audio:!0}),await eD(r.connectionDelay),a=await QE(t),[i,o]=await Promise.all([rD.create(IE({},a.inputFormat,{preferHeadphonesForIosDevices:t.preferHeadphonesForIosDevices,inputDeviceId:t.inputDeviceId,workletPaths:t.workletPaths,libsampleratePath:t.libsampleratePath})),aD.create(IE({},a.outputFormat,{outputDeviceId:t.outputDeviceId,workletPaths:t.workletPaths}))]),(l=s)==null||l.getTracks().forEach(e=>{e.stop()}),s=null,new e(r,a,i,o,c)}catch(e){var u,d;r.onStatusChange&&r.onStatusChange({status:`disconnected`}),(u=s)==null||u.getTracks().forEach(e=>{e.stop()}),(d=a)==null||d.close(),await i?.close(),await o?.close();try{await c?.release(),c=null}catch{}throw e}}constructor(e,t,n,r,i){super(e,t),this.input=void 0,this.output=void 0,this.wakeLock=void 0,this.inputFrequencyData=void 0,this.outputFrequencyData=void 0,this.onInputWorkletMessage=e=>{this.status===`connected`&&this.connection.sendMessage({user_audio_chunk:KE(e.data[0].buffer)})},this.onOutputWorkletMessage=({data:e})=>{e.type===`process`&&this.updateMode(e.finished?`listening`:`speaking`)},this.addAudioBase64Chunk=e=>{this.output.gain.gain.cancelScheduledValues(this.output.context.currentTime),this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:`clearInterrupted`}),this.output.worklet.port.postMessage({type:`buffer`,buffer:qE(e)})},this.fadeOutAudio=()=>{this.updateMode(`listening`),this.output.worklet.port.postMessage({type:`interrupt`}),this.output.gain.gain.exponentialRampToValueAtTime(1e-4,this.output.context.currentTime+2),setTimeout(()=>{this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:`clearInterrupted`})},2e3)},this.calculateVolume=e=>{if(e.length===0)return 0;let t=0;for(let n=0;n<e.length;n++)t+=e[n]/255;return t/=e.length,t<0?0:t>1?1:t},this.setVolume=({volume:e})=>{let t=Number.isFinite(e)?Math.min(1,Math.max(0,e)):1;this.volume=t,this.connection instanceof ZE?this.connection.setAudioVolume(t):this.output.gain.gain.value=t},this.input=n,this.output=r,this.wakeLock=i,this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.output.worklet.port.onmessage=this.onOutputWorkletMessage}async handleEndSession(){await super.handleEndSession();try{await this.wakeLock?.release(),this.wakeLock=null}catch{}await this.input.close(),await this.output.close()}handleInterruption(e){super.handleInterruption(e),this.fadeOutAudio()}handleAudio(e){var t,n;this.lastInterruptTimestamp<=e.audio_event.event_id&&((t=(n=this.options).onAudio)==null||t.call(n,e.audio_event.audio_base_64),this.connection instanceof ZE||this.addAudioBase64Chunk(e.audio_event.audio_base_64),this.currentEventId=e.audio_event.event_id,this.updateCanSendFeedback(),this.updateMode(`speaking`))}setMicMuted(e){this.connection instanceof ZE?this.connection.setMicMuted(e):this.input.setMuted(e)}getInputByteFrequencyData(){return this.inputFrequencyData??=new Uint8Array(this.input.analyser.frequencyBinCount),this.input.analyser.getByteFrequencyData(this.inputFrequencyData),this.inputFrequencyData}getOutputByteFrequencyData(){return this.connection instanceof ZE?this.connection.getOutputByteFrequencyData()||new Uint8Array(1024):(this.outputFrequencyData??=new Uint8Array(this.output.analyser.frequencyBinCount),this.output.analyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData)}getInputVolume(){return this.calculateVolume(this.getInputByteFrequencyData())}getOutputVolume(){return this.calculateVolume(this.getOutputByteFrequencyData())}async changeInputDevice({sampleRate:e,format:t,preferHeadphonesForIosDevices:n,inputDeviceId:r}){try{if(this.connection instanceof GE)try{return await this.input.setInputDevice(r),this.input}catch(e){console.warn(`Failed to change device on existing input, recreating:`,e)}return this.connection instanceof ZE&&await this.connection.setAudioInputDevice(r||``),await this.input.close(),this.input=await rD.create({sampleRate:e??this.connection.inputFormat.sampleRate,format:t??this.connection.inputFormat.format,preferHeadphonesForIosDevices:n,inputDeviceId:r,workletPaths:this.options.workletPaths,libsampleratePath:this.options.libsampleratePath}),this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.input}catch(e){throw console.error(`Error changing input device`,e),e}}async changeOutputDevice({sampleRate:e,format:t,outputDeviceId:n}){try{if(this.connection instanceof GE)try{return await this.output.setOutputDevice(n),this.output}catch(e){console.warn(`Failed to change device on existing output, recreating:`,e)}return this.connection instanceof ZE&&await this.connection.setAudioOutputDevice(n||``),await this.output.close(),this.output=await aD.create({sampleRate:e??this.connection.outputFormat.sampleRate,format:t??this.connection.outputFormat.format,outputDeviceId:n,workletPaths:this.options.workletPaths}),this.output}catch(e){throw console.error(`Error changing output device`,e),e}}},sD=class{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);let n=this.listeners.get(e);n&&n.add(t)}off(e,t){let n=this.listeners.get(e);n&&n.delete(t)}emit(e,...t){let n=this.listeners.get(e);n&&n.forEach(e=>{e(...t)})}},Z;(function(e){e.SESSION_STARTED=`session_started`,e.PARTIAL_TRANSCRIPT=`partial_transcript`,e.COMMITTED_TRANSCRIPT=`committed_transcript`,e.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS=`committed_transcript_with_timestamps`,e.AUTH_ERROR=`auth_error`,e.ERROR=`error`,e.OPEN=`open`,e.CLOSE=`close`,e.QUOTA_EXCEEDED=`quota_exceeded`,e.COMMIT_THROTTLED=`commit_throttled`,e.TRANSCRIBER_ERROR=`transcriber_error`,e.UNACCEPTED_TERMS=`unaccepted_terms`,e.RATE_LIMITED=`rate_limited`,e.INPUT_ERROR=`input_error`,e.QUEUE_OVERFLOW=`queue_overflow`,e.RESOURCE_EXHAUSTED=`resource_exhausted`,e.SESSION_TIME_LIMIT_EXCEEDED=`session_time_limit_exceeded`,e.CHUNK_SIZE_EXCEEDED=`chunk_size_exceeded`,e.INSUFFICIENT_AUDIO_ACTIVITY=`insufficient_audio_activity`})(Z||={});var cD=class{constructor(e){this.websocket=null,this.eventEmitter=new sD,this.currentSampleRate=16e3,this._audioCleanup=void 0,this.currentSampleRate=e}setWebSocket(e){this.websocket=e,this.websocket.readyState===WebSocket.OPEN?this.eventEmitter.emit(Z.OPEN):this.websocket.addEventListener(`open`,()=>{this.eventEmitter.emit(Z.OPEN)}),this.websocket.addEventListener(`message`,e=>{try{let t=JSON.parse(e.data);switch(t.message_type){case`session_started`:this.eventEmitter.emit(Z.SESSION_STARTED,t);break;case`partial_transcript`:this.eventEmitter.emit(Z.PARTIAL_TRANSCRIPT,t);break;case`committed_transcript`:this.eventEmitter.emit(Z.COMMITTED_TRANSCRIPT,t);break;case`committed_transcript_with_timestamps`:this.eventEmitter.emit(Z.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS,t);break;case`auth_error`:this.eventEmitter.emit(Z.AUTH_ERROR,t),this.eventEmitter.emit(Z.ERROR,t);break;case`quota_exceeded`:this.eventEmitter.emit(Z.QUOTA_EXCEEDED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`commit_throttled`:this.eventEmitter.emit(Z.COMMIT_THROTTLED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`transcriber_error`:this.eventEmitter.emit(Z.TRANSCRIBER_ERROR,t),this.eventEmitter.emit(Z.ERROR,t);break;case`unaccepted_terms`:this.eventEmitter.emit(Z.UNACCEPTED_TERMS,t),this.eventEmitter.emit(Z.ERROR,t);break;case`rate_limited`:this.eventEmitter.emit(Z.RATE_LIMITED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`input_error`:this.eventEmitter.emit(Z.INPUT_ERROR,t),this.eventEmitter.emit(Z.ERROR,t);break;case`queue_overflow`:this.eventEmitter.emit(Z.QUEUE_OVERFLOW,t),this.eventEmitter.emit(Z.ERROR,t);break;case`resource_exhausted`:this.eventEmitter.emit(Z.RESOURCE_EXHAUSTED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`session_time_limit_exceeded`:this.eventEmitter.emit(Z.SESSION_TIME_LIMIT_EXCEEDED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`chunk_size_exceeded`:this.eventEmitter.emit(Z.CHUNK_SIZE_EXCEEDED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`insufficient_audio_activity`:this.eventEmitter.emit(Z.INSUFFICIENT_AUDIO_ACTIVITY,t),this.eventEmitter.emit(Z.ERROR,t);break;case`error`:this.eventEmitter.emit(Z.ERROR,t);break;default:console.warn(`Unknown message type:`,t)}}catch(t){console.error(`Failed to parse WebSocket message:`,t,e.data),this.eventEmitter.emit(Z.ERROR,Error(`Failed to parse message: ${t}`))}}),this.websocket.addEventListener(`error`,e=>{console.error(`WebSocket error:`,e),this.eventEmitter.emit(Z.ERROR,e)}),this.websocket.addEventListener(`close`,e=>{if(console.log(`WebSocket closed: code=${e.code}, reason="${e.reason}", wasClean=${e.wasClean}`),!e.wasClean||e.code!==1e3&&e.code!==1005){let t=`WebSocket closed unexpectedly: ${e.code} - ${e.reason||`No reason provided`}`;console.error(t),this.eventEmitter.emit(Z.ERROR,Error(t))}this.eventEmitter.emit(Z.CLOSE,e)})}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}send(e){var t;if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw Error(`WebSocket is not connected`);let n={message_type:`input_audio_chunk`,audio_base_64:e.audioBase64,commit:(t=e.commit)!=null&&t,sample_rate:e.sampleRate??this.currentSampleRate,previous_text:e.previousText};this.websocket.send(JSON.stringify(n))}commit(){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw Error(`WebSocket is not connected`);this.websocket.send(JSON.stringify({message_type:`input_audio_chunk`,audio_base_64:``,commit:!0,sample_rate:this.currentSampleRate}))}close(){this._audioCleanup&&this._audioCleanup(),this.websocket&&this.websocket.close(1e3,`User ended session`)}},lD=YE(`scribeAudioProcessor`,`/*
|
|
255
279
|
* Scribe Audio Processor for converting microphone audio to PCM16 format
|
|
256
280
|
* USED BY @elevenlabs/client
|
|
257
281
|
*/
|
|
@@ -303,194 +327,18 @@ class ScribeAudioProcessor extends AudioWorkletProcessor {
|
|
|
303
327
|
|
|
304
328
|
registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
|
|
305
329
|
|
|
306
|
-
`),
|
|
307
|
-
.fe-highlight-section {
|
|
308
|
-
outline: 3px solid #7c3aed !important;
|
|
309
|
-
box-shadow: 0 0 15px rgba(124, 58, 237, 0.6) !important;
|
|
310
|
-
transition: outline-color 0.3s ease, box-shadow 0.3s ease !important;
|
|
311
|
-
border-radius: 8px !important;
|
|
312
|
-
position: relative;
|
|
313
|
-
}
|
|
314
|
-
/* Smooth fade-in for the speaking highlight */
|
|
315
|
-
.fe-highlight-section.fe-highlight-speaking {
|
|
316
|
-
outline-color: #6366f1 !important;
|
|
317
|
-
box-shadow: 0 0 20px rgba(99, 102, 241, 0.45), 0 0 4px rgba(99, 102, 241, 0.3) !important;
|
|
318
|
-
animation: fe-hl-pulse 2s ease-in-out infinite !important;
|
|
319
|
-
}
|
|
320
|
-
@keyframes fe-hl-pulse {
|
|
321
|
-
0%, 100% { box-shadow: 0 0 15px rgba(99, 102, 241, 0.40), 0 0 4px rgba(99, 102, 241, 0.25); }
|
|
322
|
-
50% { box-shadow: 0 0 25px rgba(99, 102, 241, 0.55), 0 0 8px rgba(99, 102, 241, 0.35); }
|
|
323
|
-
}
|
|
324
|
-
/* Exit transition — the old highlight fades out */
|
|
325
|
-
.fe-highlight-exiting {
|
|
326
|
-
outline: 3px solid transparent !important;
|
|
327
|
-
box-shadow: none !important;
|
|
328
|
-
transition: outline-color 0.25s ease, box-shadow 0.25s ease !important;
|
|
329
|
-
}
|
|
330
|
-
`,document.head.appendChild(e)};function Yh(e,t){if(typeof document>`u`)return null;if(e){let n=document.getElementById(e)||document.querySelector(`[data-section="${e}"]`);if(n)return n;t||=e.replace(/[-_]+/g,` `).trim()}if(!t)return null;let n=t.toLowerCase().trim(),r=n.split(/\s+/).filter(e=>e.length>2),i=Array.from(document.querySelectorAll(`h1.h2.h3.h4.h5.h6.[data-section].section[id].[id].main li.article li.[role='main'] li.[class*='card'].[class*='Card'].[class*='feature'].[class*='Feature'].[class*='tier'].[class*='Tier'].[class*='plan'].[class*='Plan'].[class*='pricing'].[class*='Pricing'].[class*='testimonial'].[class*='Testimonial'].[class*='team'].[class*='Team'].[class*='service'].[class*='Service'].[class*='block'].[role='listitem'].[role='article'].[role='region'].dt.dd`.split(`.`).join(`, `))).filter(e=>{if(_h(e))return!1;let t=e.textContent.trim();return!(t.length<3||t.length>5e3||e.closest(`nav, footer, header, aside, .nav, .footer, .header`))});for(let e of i)if(e.textContent.replace(/\s+/g,` `).toLowerCase().trim()===n)return e;for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.startsWith(n)||t.endsWith(n))return e}let a=[];for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();t.includes(n)&&a.push({el:e,len:t.length})}if(a.length)return a.sort((e,t)=>e.len-t.len),a[0].el;for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.length>3&&n.includes(t))return e}if(r.length>0){let e=null,t=0;for(let n of i){let i=n.textContent.replace(/\s+/g,` `).toLowerCase(),a=0;for(let e of r)i.includes(e)&&a++;let o=a/r.length;o>t&&o>=.6&&(t=o,e=n)}if(e)return e}let o=Array.from(document.querySelectorAll(`main [role='group']`)).filter(e=>!_h(e)),s=[];for(let e of o){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();t.length<15||t.length>8e3||t.includes(n)&&s.push({el:e,len:t.length})}if(s.length)return s.sort((e,t)=>e.len-t.len),s[0].el;if(r.length>0){let e=Array.from(document.querySelectorAll(`main a[href], article a[href], .views-row a[href], h2 a[href], h3 a[href], .card a[href], [class*='teaser'] a[href]`)).filter(e=>{if(_h(e))return!1;try{let t=e.getAttribute(`href`)||``;if(!t||t===`#`||t.startsWith(`javascript:`))return!1}catch{return!1}let t=e.textContent.replace(/\s+/g,` `).trim();return t.length>=3&&t.length<=220}),t=null,n=0;for(let i of e){let e=i.textContent.replace(/\s+/g,` `).toLowerCase(),a=0;for(let t of r)e.includes(t)&&a++;let o=a/r.length;o>n&&o>=.5&&(n=o,t=i)}if(t)return t.closest(`article`)||t.closest(`.views-row`)||t}let c=document.querySelectorAll(`section, article, .card, [class*='feature'], [class*='service']`);for(let e of c){if(_h(e))continue;let t=e.querySelector(`h1, h2, h3, h4, h5, h6`);if(t){let r=t.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(r.includes(n)||n.includes(r))return e}}let l=document.querySelectorAll(`li, strong, blockquote, dt`);for(let e of l){if(_h(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e.tagName===`STRONG`&&e.parentElement?.tagName===`LI`?e.parentElement:e}let u=Array.from(document.querySelectorAll(`a[href]`)).filter(e=>!_h(e));u.sort((e,t)=>(e.textContent||``).trim().length-(t.textContent||``).trim().length);for(let e of u){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e}let d=document.querySelectorAll(`p`);for(let e of d){if(_h(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<800)return e}return null}function Xh(e,{speaking:t=!1,scroll:n=!0}={}){if(!e||typeof document>`u`)return;Jh();let r=document.querySelectorAll(`.fe-highlight-section`);for(let t of r)t!==e&&(t.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`),t.classList.add(`fe-highlight-exiting`),setTimeout(()=>t.classList.remove(`fe-highlight-exiting`),300));if(e.classList.remove(`fe-highlight-exiting`),e.classList.add(`fe-highlight-section`),t?e.classList.add(`fe-highlight-speaking`):e.classList.remove(`fe-highlight-speaking`),n)try{e.scrollIntoView({behavior:`smooth`,block:`center`})}catch{try{e.scrollIntoView(!0)}catch{}}}function Zh(){typeof document>`u`||document.querySelectorAll(`.fe-highlight-section, .fe-highlight-exiting`).forEach(e=>e.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`,`fe-highlight-exiting`))}function Qh(e){if(typeof window>`u`)return e;try{let t=new URL(String(e).trim(),window.location.href);return!/^https?:$/i.test(t.protocol)||t.origin===window.location.origin?t.href:new URL(t.pathname+t.search+t.hash,window.location.origin).href}catch{return e}}async function $h(e){if(typeof window>`u`)return!1;try{let t=new URL(String(e).trim(),window.location.href),n=t.origin===window.location.origin?t.href:new URL(t.pathname+t.search+t.hash,window.location.origin).href;return(await fetch(n,{method:`HEAD`,mode:`same-origin`,cache:`no-store`})).ok}catch{return!1}}async function eg(e,{siteId:t,apiBaseUrl:n}){if(!e)return!1;if(!t||!n)return console.warn(`[FlowEngage] shouldProceedWithNavigation: missing siteId or apiBaseUrl`),$h(e);let r=String(n).replace(/\/$/,``),i=new URLSearchParams({siteId:String(t),url:String(e).trim()});try{let t=await(await fetch(`${r}/api/widget/navigate-allowed?${i.toString()}`)).json().catch(()=>({}));return t.success&&t.allowed?!0:$h(e)}catch(t){return console.warn(`[FlowEngage] navigate-allowed check failed:`,t?.message),$h(e)}}function tg(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(yh,JSON.stringify({sectionText:e,ts:Date.now()}))}catch{}}async function ng(e,{skipPushState:t=!1,isBack:n=!1}={}){if(typeof window>`u`||typeof document>`u`)return!1;try{if(new URL(e,window.location.href).origin!==window.location.origin)return!1}catch{return!1}Gh();let r=new AbortController,i=setTimeout(()=>r.abort(),8e3);try{let a=await fetch(e,{credentials:`same-origin`,cache:`no-store`,signal:r.signal});if(clearTimeout(i),!a.ok)return Kh(),!1;let o=await a.text(),s=new DOMParser().parseFromString(o,`text/html`),c=document.getElementById(`flowengage-root`);if(!c)return Kh(),!1;try{typeof window.Drupal?.detachBehaviors==`function`&&window.Drupal.detachBehaviors(document.body,window.drupalSettings)}catch{}document.querySelectorAll(`script`).forEach(e=>{e.setAttribute(`data-fe-original`,`true`)}),Array.from(document.body.children).forEach(e=>{if(e===c)return;let t=e.tagName?.toUpperCase();t===`AUDIO`||t===`VIDEO`||e.remove()}),Ih();let l=new Set(Array.from(document.querySelectorAll(`link[rel='stylesheet']`)).map(e=>{try{return new URL(e.getAttribute(`href`)||``,window.location.href).href}catch{return``}}));for(let t of Array.from(s.head.querySelectorAll(`link[rel='stylesheet']`))){let n=t.getAttribute(`href`);if(!n)continue;let r;try{r=new URL(n,e).href}catch{continue}if(l.has(r))continue;let i=document.createElement(`link`);i.rel=`stylesheet`,i.href=r,i.setAttribute(Fh,`true`),t.media&&(i.media=t.media),document.head.appendChild(i)}for(let e of Array.from(s.head.querySelectorAll(`style`))){if(!e.textContent.trim())continue;let t=e.textContent.trim().slice(0,120);if(Array.from(document.head.querySelectorAll(`style:not([data-fe-swap-css])`)).some(e=>e.textContent.trim().slice(0,120)===t))continue;let n=document.createElement(`style`);n.textContent=e.textContent,n.setAttribute(Fh,`true`),document.head.appendChild(n)}Array.from(s.body.children).forEach(e=>{e.tagName?.toUpperCase()!==`SCRIPT`&&document.body.insertBefore(document.importNode(e,!0),c)});let u=document.querySelectorAll(`script:not([data-fe-replayed])`);for(let e of u){if(e.closest(`#flowengage-root, .flowengage-shell`)||e.hasAttribute(`data-fe-original`)||e.hasAttribute(`data-fe-replayed`))continue;let t=e.getAttribute(`src`),n=e.getAttribute(`type`)||``;if(!(n&&n!==`text/javascript`&&n!==``&&!n.includes(`drupal-ajax`))){if(n.includes(`drupal-ajax`)){e.setAttribute(`data-fe-replayed`,`true`);try{let t=JSON.parse(e.textContent);if(Array.isArray(t))for(let e of t){if((e.command===`insert`||e.command===`insert_new_content`)&&e.selector&&e.data){let t=document.querySelector(e.selector);t&&(e.method===`replaceWith`?t.outerHTML=e.data:e.method===`html`||e.method===`replace`?t.innerHTML=e.data:e.method===`append`?t.insertAdjacentHTML(`beforeend`,e.data):e.method===`prepend`?t.insertAdjacentHTML(`afterbegin`,e.data):t.innerHTML=e.data,vh(`trySpaNavigate: BigPipe replacement →`,e.selector))}if(e.command===`settings`&&e.settings)try{window.drupalSettings&&typeof window.drupalSettings==`object`&&Object.assign(window.drupalSettings,e.settings)}catch{}}}catch(e){vh(`trySpaNavigate: BigPipe parse error:`,e.message)}continue}if(!t&&e.textContent.trim()){let t=e.textContent;if(/window\.location\s*[.=]|location\s*\.\s*(href|assign|replace|reload)\s*[=(]/i.test(t)){e.setAttribute(`data-fe-replayed`,`true`);continue}let n=document.createElement(`script`);n.textContent=t,n.setAttribute(`data-fe-replayed`,`true`),e.parentNode.replaceChild(n,e)}}}try{for(let e of Array.from(s.querySelectorAll(`script`))){let t=(e.textContent||``).match(/drupalSettings\s*[,=]\s*(\{[\s\S]*?\})\s*[;)]/);if(t){try{let e=JSON.parse(t[1]);window.drupalSettings&&typeof window.drupalSettings==`object`?Object.assign(window.drupalSettings,e):window.drupalSettings=e,vh(`trySpaNavigate: updated drupalSettings from new page`)}catch{}break}}}catch{}let d=window.location.assign.bind(window.location),f=window.location.replace.bind(window.location),p=!0;window.location.assign=e=>{if(p){vh(`trySpaNavigate: blocked location.assign from replayed script:`,e);return}return d(e)},window.location.replace=e=>{if(p){vh(`trySpaNavigate: blocked location.replace from replayed script:`,e);return}return f(e)};function m(e){let t=e.toLowerCase();return!!(/\/jquery[.\-\/]/.test(t)||/\/jquery\.min\.js/.test(t)||/\/jquery-once/.test(t)||/\/jquery\.once/.test(t)||/\/jquery\.ui[\./]/.test(t)||/\/jqueryui/.test(t)||/\/core\/misc\//.test(t)||/\/core\/modules\//.test(t)||/\/misc\/drupal\.js/.test(t)||/\/lodash[.\-\/]/.test(t)||/\/underscore[.\-\/]/.test(t)||/\/backbone[.\-\/]/.test(t)||/\/modernizr[.\-\/]/.test(t)||/\/popper[.\-\/]/.test(t)||/\/bootstrap\.min\.js/.test(t)||/\/bootstrap\.bundle/.test(t))}let h=new Set(Array.from(document.querySelectorAll(`script[src]`)).map(e=>{try{return new URL(e.getAttribute(`src`)||``,window.location.href).href}catch{return``}}));function g(t,n){let r=t.getAttribute(`src`)||``;if(r.includes(`flowengage`))return;let i=document.createElement(`script`);if(r){let n;try{n=new URL(r,e).href}catch{return}if(h.has(n)){if(m(n))return;vh(`trySpaNavigate: re-running theme/custom script:`,n)}h.add(n),i.src=n,i.async=t.async,i.defer=t.defer}else if(t.textContent.trim()){let e=t.textContent;if(/window\.location\s*[.=]|location\s*\.\s*(href|assign|replace|reload)\s*[=(]/i.test(e)){vh(`trySpaNavigate: skipping inline script with navigation:`,e.slice(0,120));return}if(/^\s*\(?\s*(?:window\.)?drupalSettings\s*[,=]/.test(e))return;i.textContent=e}else return;let a=t.getAttribute(`type`);a&&a!==`text/javascript`&&a!==``&&(i.type=a),n.parentNode.insertBefore(i,n)}for(let e of Array.from(s.head.querySelectorAll(`script`)))g(e,c);for(let e of Array.from(s.body.querySelectorAll(`script`)))g(e,c);try{typeof window.Drupal?.attachBehaviors==`function`&&window.Drupal.attachBehaviors(document.body,window.drupalSettings)}catch{}try{typeof window.jQuery==`function`&&(window.jQuery(document).trigger(`ready`),window.dispatchEvent(new Event(`resize`)))}catch{}try{document.dispatchEvent(new Event(`DOMContentLoaded`,{bubbles:!0,cancelable:!1}))}catch{}try{window.dispatchEvent(new Event(`load`))}catch{}try{let e=document.querySelectorAll(`iframe:not([data-fe-skip-reload])`);for(let t of e){if(t.closest(`#flowengage-root, .flowengage-shell`))continue;let e=t.getAttribute(`src`)||t.src;e&&e!==`about:blank`&&!e.startsWith(`javascript:`)&&(vh(`trySpaNavigate: reloading iframe:`,e),t.src=e)}}catch{}try{let e=document.querySelectorAll(`.g-recaptcha, [data-sitekey]`);if(e.length>0){if(typeof window.grecaptcha?.render==`function`){for(let t of e)if(!t.closest(`#flowengage-root`)){t.innerHTML=``;try{window.grecaptcha.render(t,{sitekey:t.getAttribute(`data-sitekey`)||``}),vh(`trySpaNavigate: re-rendered reCAPTCHA`)}catch{}}}else if(!document.querySelector(`script[src*='recaptcha']`)){let e=document.createElement(`script`);e.src=`https://www.google.com/recaptcha/api.js?render=explicit`,e.async=!0,document.head.appendChild(e),vh(`trySpaNavigate: injected reCAPTCHA script`)}}}catch{}if(setTimeout(()=>{p=!1,window.location.assign=d,window.location.replace=f},2e3),s.title&&(document.title=s.title),!t)try{history.pushState({flowengageSpa:!0},``,e)}catch{}if(kh(),jh(),n){try{zh()}catch{}try{Hh()}catch{}}else window.scrollTo(0,0);Kh(),Uh(e);try{sessionStorage.removeItem(yh)}catch{}try{sessionStorage.removeItem(xh)}catch{}try{Oh=new URL(e,window.location.origin).pathname}catch{}return vh(`trySpaNavigate: succeeded →`,e),!0}catch{return clearTimeout(i),Kh(),!1}}function rg(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(xh,JSON.stringify({voiceWasActive:!0,targetUrl:String(e),ts:Date.now()}))}catch{}}function ig(){if(!(typeof sessionStorage>`u`))try{sessionStorage.removeItem(xh)}catch{}}function ag(){if(typeof window>`u`||typeof sessionStorage>`u`)return{shouldResumeVoice:!1,targetUrl:null};let e;try{e=JSON.parse(sessionStorage.getItem(xh)||`null`)}catch{return{shouldResumeVoice:!1,targetUrl:null}}if(!e)return{shouldResumeVoice:!1,targetUrl:null};try{sessionStorage.removeItem(xh)}catch{}return e.voiceWasActive?Date.now()-e.ts>Sh?(vh(`initVoiceNavResume: state expired, skipping`),{shouldResumeVoice:!1,targetUrl:null}):(vh(`initVoiceNavResume: voice was active during navigation to`,e.targetUrl),{shouldResumeVoice:!0,targetUrl:e.targetUrl||null}):{shouldResumeVoice:!1,targetUrl:null}}async function og(e,t={}){if(typeof window>`u`)return!1;let{sectionText:n,voiceActive:r=!1}=t;try{let t=Qh(e),i=new URL(t,window.location.origin);if(i.hash&&i.pathname===window.location.pathname){let e=document.getElementById(i.hash.slice(1));if(e)return e.scrollIntoView({behavior:`smooth`,block:`start`}),!0}if(i.pathname===window.location.pathname&&i.search===window.location.search&&!i.hash)return!1;let a=i.pathname+i.search+i.hash,o=window.next?.router;if(o?.push)return new Promise(e=>{let t=()=>{o.events?.off(`routeChangeComplete`,t),e(!0)};o.events?.on(`routeChangeComplete`,t),o.push(a),setTimeout(t,5e3)});if(window.__NEXT_ROUTER__?.push)return window.__NEXT_ROUTER__.push(a),!0;if(Ph()){n&&tg(n);try{window.history.pushState({},``,i.href),window.dispatchEvent(new PopStateEvent(`popstate`,{state:{}}))}catch{}return!0}return n&&tg(n),r||Oe(),window.location.assign(i.href),!0}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t),n&&tg(n);try{window.location.href=Qh(e)}catch{window.location.href=e}return!0}}var sg=!1,cg=null;function lg(e){cg=e,typeof window<`u`&&(window.__fe_triggerVoiceNavHooks=()=>{try{e.onBeforeNavigate()}catch{}}),!sg&&(sg=!0,!(typeof document>`u`)&&(document.addEventListener(`click`,e=>{if(!cg)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&&!r.hash)){vh(`voice-link-hook: saving state before navigation →`,r.href);try{cg.onBeforeNavigate()}catch{}}},!0),document.addEventListener(`submit`,e=>{if(cg&&!e.target?.closest?.(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)){vh(`voice-form-hook: saving state before form submit`);try{cg.onBeforeNavigate()}catch{}}},!0)))}function ug(){cg=null,vh(`voice-nav-hooks: deactivated`)}function dg(e,t={}){let n=t.maxChars??4500;if(!Array.isArray(e)||e.length===0)return``;let r=[];for(let t of e){if(!t||t.isPending)continue;let e=String(t.sender||``).toLowerCase(),n=null;if(e===`user`?n=`Visitor`:(e===`bot`||e===`ai`||e===`agent`)&&(n=`Assistant`),!n)continue;let i=String(t.message||``).replace(/<[^>]+>/g,` `).replace(/\s+/g,` `).trim().slice(0,1200);i&&r.push(`${n}: ${i}`)}if(r.length===0)return``;let i=r.join(`
|
|
331
|
-
`);return i.length>n&&(i=`…(earlier messages omitted)
|
|
332
|
-
`+i.slice(-n)),i}var fg=80;function pg(e){requestAnimationFrame(()=>{let t=e.getBoundingClientRect(),n=t.top+t.height/2,r=fg+(window.innerHeight-fg)/2,i=window.pageYOffset+n-r;window.scrollTo({top:Math.max(0,i),behavior:`smooth`})})}function mg(e){e&&(e.hasAttribute(`data-fe-highlighted`)||(hg(),e.classList?.remove(`fe-highlight-section`,`fe-highlight-speaking`,`fe-highlight-exiting`),pg(e),e.setAttribute(`data-fe-orig-style`,e.style.cssText),e.setAttribute(`data-fe-highlighted`,`true`),e.style.outline=`3px solid #2563eb`,e.style.outlineOffset=`8px`,e.style.background=`rgba(37, 99, 235, 0.08)`,e.style.borderRadius=`8px`,e.style.padding=`12px 16px`,e.style.transition=`all 0.4s ease`))}function hg(){let e=document.querySelector(`[data-fe-highlighted]`);e&&(e.style.cssText=e.getAttribute(`data-fe-orig-style`)||``,e.removeAttribute(`data-fe-highlighted`),e.removeAttribute(`data-fe-orig-style`))}var X=`fe-vv`;function gg(){if(typeof document>`u`||document.getElementById(`${X}-styles`))return;let e=`
|
|
333
|
-
/* ── Action toast ───────────────────────────────────────────────────────────── */
|
|
334
|
-
#${X}-toast {
|
|
335
|
-
position: fixed;
|
|
336
|
-
top: 16px;
|
|
337
|
-
left: 50%;
|
|
338
|
-
transform: translateX(-50%) translateY(-160%);
|
|
339
|
-
background: rgba(10, 10, 20, 0.88);
|
|
340
|
-
color: #f1f5f9;
|
|
341
|
-
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
|
342
|
-
font-size: 13px;
|
|
343
|
-
font-weight: 500;
|
|
344
|
-
line-height: 1.4;
|
|
345
|
-
padding: 9px 18px 9px 14px;
|
|
346
|
-
border-radius: 999px;
|
|
347
|
-
z-index: 2147483640;
|
|
348
|
-
pointer-events: none;
|
|
349
|
-
opacity: 0;
|
|
350
|
-
transition: transform 0.28s cubic-bezier(0.34, 1.56, 0.64, 1), opacity 0.2s ease;
|
|
351
|
-
white-space: nowrap;
|
|
352
|
-
display: flex;
|
|
353
|
-
align-items: center;
|
|
354
|
-
gap: 9px;
|
|
355
|
-
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.35), 0 1px 4px rgba(0, 0, 0, 0.2);
|
|
356
|
-
backdrop-filter: blur(12px);
|
|
357
|
-
-webkit-backdrop-filter: blur(12px);
|
|
358
|
-
border: 1px solid rgba(255,255,255,0.08);
|
|
359
|
-
max-width: 90vw;
|
|
360
|
-
overflow: hidden;
|
|
361
|
-
text-overflow: ellipsis;
|
|
362
|
-
}
|
|
363
|
-
#${X}-toast.${X}-show {
|
|
364
|
-
transform: translateX(-50%) translateY(0);
|
|
365
|
-
opacity: 1;
|
|
366
|
-
}
|
|
367
|
-
#${X}-toast .${X}-spin {
|
|
368
|
-
width: 13px;
|
|
369
|
-
height: 13px;
|
|
370
|
-
border: 2px solid rgba(255,255,255,0.25);
|
|
371
|
-
border-top-color: #a78bfa;
|
|
372
|
-
border-radius: 50%;
|
|
373
|
-
animation: ${X}-spin 0.65s linear infinite;
|
|
374
|
-
flex-shrink: 0;
|
|
375
|
-
}
|
|
376
|
-
#${X}-toast .${X}-icon {
|
|
377
|
-
font-size: 14px;
|
|
378
|
-
flex-shrink: 0;
|
|
379
|
-
line-height: 1;
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
/* ── Navigation progress bar ────────────────────────────────────────────────── */
|
|
383
|
-
#${X}-bar {
|
|
384
|
-
position: fixed;
|
|
385
|
-
top: 0;
|
|
386
|
-
left: 0;
|
|
387
|
-
width: 0%;
|
|
388
|
-
height: 3px;
|
|
389
|
-
background: linear-gradient(90deg, #7c3aed, #06b6d4, #7c3aed);
|
|
390
|
-
background-size: 200% 100%;
|
|
391
|
-
z-index: 2147483647;
|
|
392
|
-
pointer-events: none;
|
|
393
|
-
opacity: 0;
|
|
394
|
-
transition: width 0.35s ease, opacity 0.25s ease;
|
|
395
|
-
box-shadow: 0 0 12px #7c3aed88;
|
|
396
|
-
animation: ${X}-bar-shimmer 1.5s linear infinite;
|
|
397
|
-
}
|
|
398
|
-
#${X}-bar.${X}-bar-active {
|
|
399
|
-
opacity: 1;
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
/* ── Field active highlight (about to fill) ─────────────────────────────────── */
|
|
403
|
-
.${X}-field-active {
|
|
404
|
-
outline: 2.5px solid #7c3aed !important;
|
|
405
|
-
outline-offset: 3px !important;
|
|
406
|
-
box-shadow: 0 0 0 5px rgba(124, 58, 237, 0.14), 0 0 20px rgba(124, 58, 237, 0.28) !important;
|
|
407
|
-
border-radius: 5px !important;
|
|
408
|
-
transition: outline 0.18s ease, box-shadow 0.18s ease !important;
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
/* ── Field filled confirmation (green flash) ────────────────────────────────── */
|
|
412
|
-
.${X}-field-filled {
|
|
413
|
-
outline: 2px solid #10b981 !important;
|
|
414
|
-
outline-offset: 3px !important;
|
|
415
|
-
box-shadow: 0 0 0 4px rgba(16, 185, 129, 0.12), 0 0 16px rgba(16, 185, 129, 0.22) !important;
|
|
416
|
-
border-radius: 5px !important;
|
|
417
|
-
animation: ${X}-fill-flash 0.45s ease forwards !important;
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
/* ── Ghost cursor ────────────────────────────────────────────────────────────── */
|
|
421
|
-
#${X}-cursor {
|
|
422
|
-
position: fixed;
|
|
423
|
-
width: 22px;
|
|
424
|
-
height: 22px;
|
|
425
|
-
pointer-events: none;
|
|
426
|
-
z-index: 2147483645;
|
|
427
|
-
opacity: 0;
|
|
428
|
-
transition:
|
|
429
|
-
left 0.32s cubic-bezier(0.25, 0.46, 0.45, 0.94),
|
|
430
|
-
top 0.32s cubic-bezier(0.25, 0.46, 0.45, 0.94),
|
|
431
|
-
opacity 0.2s ease;
|
|
432
|
-
transform: translate(-4px, -4px);
|
|
433
|
-
}
|
|
434
|
-
#${X}-cursor.${X}-cursor-visible {
|
|
435
|
-
opacity: 1;
|
|
436
|
-
}
|
|
437
|
-
#${X}-cursor.${X}-cursor-click {
|
|
438
|
-
animation: ${X}-cursor-click 0.25s ease;
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
/* ── Click ripple ────────────────────────────────────────────────────────────── */
|
|
442
|
-
.${X}-ripple {
|
|
443
|
-
position: absolute;
|
|
444
|
-
border-radius: 50%;
|
|
445
|
-
transform: scale(0);
|
|
446
|
-
background: rgba(124, 58, 237, 0.35);
|
|
447
|
-
animation: ${X}-ripple-anim 0.55s linear forwards;
|
|
448
|
-
pointer-events: none;
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
/* ── Keyframes ───────────────────────────────────────────────────────────────── */
|
|
452
|
-
@keyframes ${X}-spin {
|
|
453
|
-
to { transform: rotate(360deg); }
|
|
454
|
-
}
|
|
455
|
-
@keyframes ${X}-bar-shimmer {
|
|
456
|
-
0% { background-position: 0% 0%; }
|
|
457
|
-
100% { background-position: 200% 0%; }
|
|
458
|
-
}
|
|
459
|
-
@keyframes ${X}-fill-flash {
|
|
460
|
-
0% { background-color: rgba(16, 185, 129, 0.10); }
|
|
461
|
-
40% { background-color: rgba(16, 185, 129, 0.22); }
|
|
462
|
-
100% { background-color: transparent; }
|
|
463
|
-
}
|
|
464
|
-
@keyframes ${X}-ripple-anim {
|
|
465
|
-
to { transform: scale(3.5); opacity: 0; }
|
|
466
|
-
}
|
|
467
|
-
@keyframes ${X}-cursor-click {
|
|
468
|
-
0% { transform: translate(-4px,-4px) scale(1); }
|
|
469
|
-
50% { transform: translate(-4px,-4px) scale(0.82); }
|
|
470
|
-
100% { transform: translate(-4px,-4px) scale(1); }
|
|
471
|
-
}
|
|
472
|
-
`,t=document.createElement(`style`);t.id=`${X}-styles`,t.textContent=e,(document.head||document.documentElement).appendChild(t)}var _g=null,vg=null;function yg(){return(!_g||!_g.isConnected)&&(_g=document.createElement(`div`),_g.id=`${X}-toast`,document.body.appendChild(_g)),_g}function bg(e,{spinner:t=!0,icon:n=null,duration:r=0}={}){if(typeof document>`u`)return;gg(),vg&&=(clearTimeout(vg),null);let i=yg();if(i.innerHTML=``,n){let e=document.createElement(`span`);e.className=`${X}-icon`,e.textContent=n,i.appendChild(e)}else if(t){let e=document.createElement(`span`);e.className=`${X}-spin`,i.appendChild(e)}let a=document.createElement(`span`);a.textContent=e,i.appendChild(a),i.classList.remove(`${X}-show`),i.offsetHeight,i.classList.add(`${X}-show`),r>0&&(vg=setTimeout(()=>xg(),r))}function xg(e=0){_g&&(e>0?vg=setTimeout(()=>{_g&&_g.classList.remove(`${X}-show`)},e):_g&&_g.classList.remove(`${X}-show`))}var Sg=null,Cg=[];function wg(){return(!Sg||!Sg.isConnected)&&(Sg=document.createElement(`div`),Sg.id=`${X}-bar`,document.body.appendChild(Sg)),Sg}function Tg(){if(typeof document>`u`)return;gg(),Cg.forEach(clearTimeout),Cg=[];let e=wg();e.style.transition=`none`,e.style.width=`0%`,e.classList.add(`${X}-bar-active`),e.offsetHeight,e.style.transition=`width 0.35s ease, opacity 0.25s ease`;let t=[[80,`width 0.6s ease`],[92,`width 1.2s ease`]],n=50;for(let[e,r]of t){let t=n,i=e,a=r;Cg.push(setTimeout(()=>{Sg&&(Sg.style.transition=a,Sg.style.width=`${i}%`)},t)),n+=800}}function Eg(){Sg&&(Cg.forEach(clearTimeout),Cg=[],Sg.style.transition=`width 0.2s ease`,Sg.style.width=`100%`,Cg.push(setTimeout(()=>{Sg&&(Sg.style.transition=`opacity 0.35s ease`,Sg.style.opacity=`0`,Cg.push(setTimeout(()=>{Sg&&(Sg.style.width=`0%`,Sg.classList.remove(`${X}-bar-active`))},380)))},220)))}function Dg(){typeof document>`u`||document.querySelectorAll(`.${X}-field-active, .${X}-field-filled`).forEach(e=>e.classList.remove(`${X}-field-active`,`${X}-field-filled`))}function Og(e){!e||typeof document>`u`||(gg(),Dg(),e.classList.add(`${X}-field-active`))}function kg(e){e&&(e.classList.remove(`${X}-field-active`),e.classList.add(`${X}-field-filled`),setTimeout(()=>{e.isConnected&&e.classList.remove(`${X}-field-filled`)},1400))}var Ag=`<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 22 22" fill="none">
|
|
473
|
-
<filter id="${X}-csh">
|
|
474
|
-
<feDropShadow dx="1" dy="2" stdDeviation="1.5" flood-color="#00000060"/>
|
|
475
|
-
</filter>
|
|
476
|
-
<path d="M4 2L19 10.5L11 12.8L8 20L4 2Z"
|
|
477
|
-
fill="white" stroke="#1e1b4b" stroke-width="1.6" stroke-linejoin="round"
|
|
478
|
-
filter="url(#${X}-csh)"/>
|
|
479
|
-
</svg>`,jg=null,Mg=!1;function Ng(){return(!jg||!jg.isConnected)&&(jg=document.createElement(`div`),jg.id=`${X}-cursor`,jg.innerHTML=Ag,document.body.appendChild(jg),Mg=!1),jg}async function Pg(e){if(typeof document>`u`||!e)return;gg();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=Ng();Mg||=(i.style.transition=`none`,i.style.left=`${window.innerWidth/2}px`,i.style.top=`${window.innerHeight*.4}px`,i.classList.add(`${X}-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 Rg(360)}function Fg(e=!1){jg&&(e?(jg.classList.remove(`${X}-cursor-visible`),Mg=!1):(jg.classList.remove(`${X}-cursor-visible`),setTimeout(()=>{Mg=!1},250)))}async function Ig(e){jg&&(jg.classList.add(`${X}-cursor-click`),await Rg(280),jg.classList.remove(`${X}-cursor-click`))}function Lg(e){if(!e||typeof document>`u`)return;gg();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=`${X}-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 Rg(e){return new Promise(t=>setTimeout(t,e))}function Z(...e){gh()&&console.log(`[FlowEngage:voice-tools]`,...e)}function zg(e){return new Promise(t=>setTimeout(t,e))}var Bg=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function Vg(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(Bg)}catch{return!1}}function Hg(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function Ug(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(!Vg(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function Wg(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function Gg(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 Wg(r.join(` `))}if(e.labels&&e.labels.length)return Wg(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return Wg(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return Wg(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return Wg(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=Wg(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 Wg(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return Wg(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?Wg(o):null}function Kg(){let e=[];return Ug(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(Vg(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=Hg(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function qg(){return Kg().map((e,t)=>{let n={formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:Gg(e),placeholder:e.placeholder||null};return e.tagName===`SELECT`&&(n.options=Array.from(e.options).filter(e=>e.value!==``&&!e.disabled).map(e=>({value:e.value,text:e.text.trim()})),n.currentValue=e.value||null),n})}function Jg(){let e=[];return Ug(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(Vg(e)||e.disabled)return!1;try{let t=Hg(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 Yg(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function Xg(e){let t=Yg(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function Zg(e,t){let n=Xg(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,Gg(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>Yg(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 Qg=28;function $g(e,t){let n=null,r=0;for(let i of e){let e=Zg(i,t);e>r&&(r=e,n=i)}return!n||r<Qg?null:n}function e_(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,Gg(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 t_(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function n_(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 r_(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 i_(e){if(!r_(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,Gg(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 a_(e,t,n){let r=String(t??``),i=String(n??``),a=c_(e,r)||$g(e,r)||e_(e,r,i);if(!a)return[];let o=new Set([a]);if(t_(i)&&n_(r))for(let t of e)t!==a&&i_(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 o_(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 s_(e){if(!e||typeof e!=`string`)return null;let t=null;return Ug(n=>{try{let r=n.getElementById(e);r&&!Vg(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function c_(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=s_(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=s_(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 l_(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 u_(e,t){let n=[];Ug(e=>{let t=Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"], a[href]`));n.push(...t.filter(e=>{if(Vg(e)||e.disabled)return!1;try{let t=Hg(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:l_(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=o_(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function d_(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 f_(e){let t=d_(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 p_(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 m_(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 h_(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 g_(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 __(){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 v_(){let e=e=>Array.from(e).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),t=e((document.querySelector(`main, [role='main']`)||document.body).querySelectorAll(`h1, h2, h3`));return t.length||(t=e(document.body.querySelectorAll(`h1, h2, h3`))),t.length||(t=e(document.body.querySelectorAll(`h4, h5`))),[...new Set(t)].slice(0,15)}function y_(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={"fwh-navigate-mvp":async n=>{Z(`fwh-navigate-mvp ▶ raw parameters:`,n);let i=d_(n),a=h_(i);if(Z(`fwh-navigate-mvp · coerced:`,{url:a,sectionText:i.section_text??i.sectionText??i.section,expectedLandmarks:Array.isArray(i.expected_landmarks)?i.expected_landmarks:Array.isArray(i.expectedLandmarks)?i.expectedLandmarks:[]}),!a){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return Z(`fwh-navigate-mvp ✖`,e),e}if(typeof window<`u`)try{let e=new URL(a,window.location.href);if(e.origin!==window.location.origin&&/^https?:$/i.test(e.protocol)){let t=e.hostname;return Z(`fwh-navigate-mvp ✖ external URL blocked:`,e.href),`EXTERNAL_LINK_BLOCKED: The URL "${a}" points to an external site (${t}) that opens in a new tab. I cannot open new tabs or navigate to external sites. Tell the visitor exactly this: "That link opens an external app — I'm not able to open it for you, but you can click the link directly in the navigation header."`}}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 Z(`fwh-navigate-mvp ✖ 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{}let e=window.__fe_user_nav_during_speech;if(e&&Date.now()-e.ts<3e4)try{if(new URL(a,window.location.href).pathname===e.fromPath)return Z(`flowengage_navigate ✖ blocked — would navigate back to page visitor just left`,e),`NAV_BLOCKED: The visitor just left "${e.fromPageName}" and is now on "${e.toPageName}". Do NOT navigate them back. If they said "continue", resume verbally from where you left off — no navigation needed. If they want to return, they will navigate themselves.`}catch{}}if(!await eg(a,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`Page "${a}" could not be verified. Try a different URL from your known site pages, or ask the visitor to clarify which page they want.`;return Z(`fwh-navigate-mvp ✖ blocked`,e),e}try{bg(`Navigating to ${a}...`,{spinner:!0}),Tg(),hg();try{let e=r?r():``;if(e&&t){let n=dg([{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`&&w(t,window.location.href,e),rg(e),Z(`fwh-navigate-mvp → real navigation`,a);let n=typeof window<`u`&&!!Ph();if(typeof window<`u`&&window.__fe_triggerVoiceNavHooks&&window.__fe_triggerVoiceNavHooks(),n&&Th(12e3),og(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`;Z(`fwh-navigate-mvp → SPA nav complete. target:`,e,`actual:`,n);try{typeof window<`u`&&window.scrollTo(0,0)}catch{}let s=[],c=Date.now()+12e3;for(;Date.now()<c&&(await new Promise(e=>setTimeout(e,300)),s=v_(),!(s.length>=1)););__(),Z(`fwh-navigate-mvp → page headings collected:`,s);let l=s.length?s.join(` | `):`none`,u=s.length?`Use ONLY these exact heading strings for fwh-highlight-mvp — never invent or abbreviate.`:`No headings collected yet — call fwh-get-current-page-mvp immediately (no speech) to get the live headings before speaking or highlighting.`;return i?(ig(),`OK_NAVIGATE_SPA. Visitor is now on: ${r} (page: "${o}") | Section headings: ${l}. ${u} Speak 2-3 sentences about this page from your knowledge. Then ask: "Would you like to know about a specific section, or should I give you a complete overview?" Then STOP — wait for their reply. Do NOT auto-highlight any sections.`):(ig(),`OK_NAVIGATE_SPA. CURRENT PAGE IS: ${r} (page: "${o}") | Section headings: ${l}. ${u} Speak 2-3 sentences about this page from your knowledge. Then ask: "Would you like to know about a specific section, or should I give you a complete overview?" Then STOP — wait for their reply. Do NOT auto-highlight any sections.`)}catch{}return`OK_NAVIGATE_RELOADING. Navigating to the page now; the voice session will resume automatically on the new page. When the session resumes, speak 2-3 sentences about the page, then ask: "Would you like to know about a specific section, or should I give you a complete overview?" Wait for the visitor's reply.`}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return Z(`fwh-navigate-mvp ✖`,t),bg(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{Eg(),xg(900)}},"fwh-highlight-mvp":async e=>{Z(`fwh-highlight-mvp ▶`,e);let t=d_(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;if(typeof window<`u`&&window.__fe_user_nav_during_speech){let e=window.__fe_user_nav_during_speech,t=window.location.pathname;if(Date.now()-e.ts>=3e4)window.__fe_user_nav_during_speech=null;else return Z(`flowengage_highlight ✖ blocked — user navigated during speech`,e),`NAV_CHANGED: The visitor navigated from "${e.fromPageName}" to "${e.toPageName}" (current path: ${t}) while you were speaking. STOP the current walkthrough immediately. DO NOT call flowengage_highlight again. Say out loud: "I see you've navigated to the ${e.toPageName} page — do you want me to continue what I was explaining, or shall I guide you through this page?" Wait for the visitor's answer before doing anything else.`}__();let i=(e=>e&&e.replace(/^\d+\.\s*/,``).replace(/^["']|["']$/g,``).trim())(r),a=Yh(n||null,i||null);if(!a&&i){let e=Date.now()+600;for(;!a&&Date.now()<e;)await new Promise(e=>setTimeout(e,50)),__(),a=Yh(null,i)}if(!a){Z(`fwh-highlight-mvp ✖ no element for:`,i||n);let e=v_(),t=e.length?`Page headings: ${e.map(e=>`"${e}"`).join(` | `)}. Use one of these EXACT strings for section_text — no numbers, no quotes around them.`:`No headings found — skip highlight and continue speaking.`;return`HIGHLIGHT_NOT_FOUND: "${i||n}" on the current page. ${t}`}return mg(a),Z(`fwh-highlight-mvp ✓`,i||n),`OK_HIGHLIGHT: "${i||n}". WALKTHROUGH: continue immediately to the next section — do NOT pause between sections.`},"fwh-read-content-mvp":async e=>{Z(`fwh-read-content-mvp ▶`,e);let t=d_(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=Yh(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(`
|
|
480
|
-
`)}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, #flowengage-root, .flowengage-shell, .flowengage-widget-root`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),Z(`fwh-read-content-mvp ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return Z(`fwh-read-content-mvp ✖`,e.message),`Could not read page content: ${e.message}`}},flowengage_search:async e=>{Z(`flowengage_search ▶`,e);let r=d_(e),i=pickSearchQuery(r);if(Z(`flowengage_search · query:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return Z(`flowengage_search ✖ missing query`),`Missing query parameter.`;if(!t)return Z(`flowengage_search ✖ no siteId`),`Site is not configured for search.`;if(!n)return Z(`flowengage_search ✖ no api base`),`API base URL is missing; cannot search.`;bg(`Searching${i?` for "${i}"`:``}…`,{spinner:!0});try{let e=`${n}/api/site-tools/search`;Z(`flowengage_search → POST`,e);let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:i,currentUrl:typeof window<`u`?window.location.href:``})}),a=await r.json();if(Z(`flowengage_search · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return Z(`flowengage_search ✖`,e),e}let o=a.results||[];return Z(`flowengage_search ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),o.length?`SEARCH_RESULTS: ${JSON.stringify(o)}. MANDATORY: Do NOT call fwh-navigate-mvp now. Speak the answer from these results in 2-3 sentences. Then ask the visitor if they want to go to a relevant page — e.g. "Would you like me to take you to that page?" Only navigate if they say yes. NAVIGATION RULE: When navigating to a specific article, case study, blog post, or detail page — always use the most specific URL from the results (e.g. /case-study/cgs-detail), never the generic listing page (e.g. /case-study). If multiple URLs are in the results, pick the one whose path most closely matches the topic.`:`SEARCH_RESULTS: No results found. Answer from your knowledge base.`}catch(e){let t=`Search error: ${e.message||`network`}`;return Z(`flowengage_search ✖`,t),t}finally{xg(600)}},"fwh-page-content-mvp":async e=>{Z(`fwh-page-content-mvp ▶`,e);let r=d_(e),i=r?.url||r?.page_url||``;if(Z(`fwh-page-content-mvp · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return Z(`fwh-page-content-mvp ✖ missing url`),`Missing url parameter.`;if(!t)return Z(`fwh-page-content-mvp ✖ no siteId`),`Site is not configured.`;if(!n)return Z(`fwh-page-content-mvp ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;Z(`fwh-page-content-mvp → 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(Z(`fwh-page-content-mvp · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return Z(`fwh-page-content-mvp ✖`,e),`${e} FALLBACK REQUIRED: This page is not in the search index. Call fwh-read-content-mvp (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 Z(`fwh-page-content-mvp ✓`,`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 Z(`fwh-page-content-mvp ✖`,t),t}},"fwh-search-mvp":async e=>{Z(`fwh-search-mvp ▶`,e);let r=d_(e).query;if(!r)return Z(`fwh-search-mvp ✖ missing query`),`Missing query parameter.`;if(!t)return Z(`fwh-search-mvp ✖ no siteId`),`Search unavailable (no siteId configured).`;if(!n)return Z(`fwh-search-mvp ✖ no api base`),`Search unavailable (no API base URL).`;try{let e=`${n}/api/site-tools/search`;Z(`fwh-search-mvp → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r})}),a=await i.json();if(Z(`fwh-search-mvp · HTTP`,i.status,`success:`,a.success),!a.success||!a.results?.length)return`No results found for that query. Try rephrasing, or use fwh-read-content-mvp to read the current page.`;let o=a.results.slice(0,5).map((e,t)=>`${t+1}. ${e.title||e.url} (${e.url})${e.snippet?` — ${e.snippet}`:``}`).join(`
|
|
481
|
-
`);return Z(`fwh-search-mvp ✓`,`${a.results.length} result(s)`),`SEARCH_RESULTS:\n${o}`}catch(e){return Z(`fwh-search-mvp ✖`,e.message),`Search failed. Use fwh-read-content-mvp to read the current page instead.`}},"fwh-list-nav-links-mvp":async()=>{if(Z(`fwh-list-nav-links-mvp ▶`),typeof window>`u`)return`Cannot read navigation (no browser context).`;let e=new Map,t=[],n=[`nav a`,`[role='navigation'] a`,`header a`,`.navbar a`,`.nav a`,`.menu a`,`.navigation a`,`.header a`,`[class*='nav'] a`,`[class*='menu'] a`,`[class*='header'] a`];if(Ug(t=>{for(let r of n)try{t.querySelectorAll(r).forEach(t=>{if(Vg(t))return;let n=t.getAttribute(`href`),r=(t.textContent||``).replace(/\s+/g,` `).trim();if(!r||!n||n===`#`||n.startsWith(`javascript:`))return;try{let e=t.parentElement;if(e&&Hg(e).display===`none`&&!e.closest(`nav, [role='navigation'], header, [class*='nav'], [class*='menu']`))return}catch{}let i=r.toLowerCase()+`|`+n;e.has(i)||e.set(i,{text:r,href:n})})}catch{}t.querySelectorAll(`select`).forEach(t=>{if(Vg(t))return;let n=Gg(t);/nav|menu|page|section|go to/i.test(n||t.name||t.id||``)&&Array.from(t.options).forEach(r=>{if(!r.value||r.disabled)return;let i=r.text.trim();if(!i)return;let a=i.toLowerCase()+`|`+r.value;e.has(a)||e.set(a,{text:i,href:r.value,isSelectOption:!0,selectLabel:n||t.name||`dropdown`})})})}),e.forEach(e=>t.push(e)),!t.length)return`NAV_LINKS: No navigation links found on this page. Use fwh-read-content-mvp to read page content or fwh-search-mvp to search the site.`;let r=t.slice(0,50).map((e,t)=>`${t+1}. "${e.text}"${e.isSelectOption?` (dropdown option in "${e.selectLabel}")`:``} → ${e.href}`).join(`
|
|
482
|
-
`);return Z(`fwh-list-nav-links-mvp ✓`,`${t.length} links`),`NAV_LINKS (${t.length} total, showing up to 50):\n${r}\n\nIMPORTANT: Use the EXACT text shown above when reading link names to the visitor. Do NOT rename, abbreviate, or invent options not listed here. To navigate, call fwh-navigate-mvp with the href value.`},"fwh-end-session-mvp":async()=>(Z(`fwh-end-session-mvp ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),"fwh-get-current-page-mvp":async()=>{if(Z(`fwh-get-current-page-mvp ▶`),typeof window>`u`)return`Cannot determine current page (no browser context).`;let e=window.location.href,t=window.location.pathname,n=document.title||``,r=v_();if(Z(`fwh-get-current-page-mvp ✓`,{url:e,path:t,title:n}),Z(`fwh-get-current-page-mvp → page headings collected:`,r),!r.length)return`CURRENT_PAGE. URL: ${e} | Title: ${n} | No headings found on this page. Describe the page from your knowledge without calling this tool again.`;let i=r.map(e=>`"${e}"`).join(` | `);return`CURRENT_PAGE. URL: ${e} | Title: ${n} | Page sections (${r.length} total): ${i}. *** IMPORTANT: For fwh-highlight-mvp, pass the heading text EXACTLY as shown above — no numbers, no extra punctuation, no paraphrasing. DO NOT call this tool again. If the visitor requested a walkthrough: START IT NOW. For every section: speak a short transition sentence, INVOKE the fwh-highlight-mvp tool with the exact heading text (do not speak the tool name — call it silently as a tool), then speak 3-4 sentences about that section. Cover ALL ${r.length} sections without pausing between them. ***`},"fwh-list-forms-mvp":async()=>{let e=qg(),t=Jg();Z(`fwh-list-forms-mvp ✓`,`${e.length} field(s)`,`${t.length} button(s)`);let n=e.map(e=>({...e,inputCategory:e.tag===`SELECT`?`dropdown_select`:`text_input`}));return JSON.stringify({fields:n,buttons:t,hint:`field_key: use the label/placeholder/name shown above. CRITICAL: fields with inputCategory='dropdown_select' are SELECT elements — their field_key must match the SELECT's own label (e.g. 'Company Size'), NOT the option text (e.g. 'Small Business') and NOT a nearby text input label. Never fill a SELECT option value into a text input.`})},"fwh-fill-form-mvp":async e=>{try{Z(`fwh-fill-form-mvp ▶ raw:`,e),Dg();let t=f_(e);if(!t.length&&r){let e=r(),n=p_(e);n.length?Z(`fwh-fill-form-mvp · inferred URL from last user utterance (model omitted usable fields):`,n):(n=m_(e),n.length&&Z(`fwh-fill-form-mvp · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if(Z(`fwh-fill-form-mvp · normalized fields:`,t),!t.length)return`No fields provided. Call fwh-list-forms-mvp for field_key strings, then fwh-fill-form-mvp 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;bg(`Filling ${String(t)}...`,{spinner:!0});let a=Kg(),o=(()=>{let e=Yg(r);Yg(String(t));let n=null,i=0;for(let r of a){if(r.tagName!==`SELECT`||!Array.from(r.options).find(t=>Yg(t.text)===e||Yg(t.value)===e))continue;let a=Zg(r,String(t));a>=i&&(i=a,n=r)}return n&&i>=0?n:null})();if(o){Z(`fwh-fill-form-mvp · SELECT pre-pass matched dropdown:`,o.name||o.id||o.getAttribute(`aria-label`)),Og(o),await Pg(o),g_(o,r),kg(o),await zg(120),i=[o],n.push(String(t));continue}let s=a_(a,String(t),r);if(s.length){for(let[e,t]of s.entries())Og(t),await Pg(t),g_(t,r,{skipScroll:e>0}),kg(t),await zg(120);i=s,n.push(String(t));continue}let c=c_(a,String(t));c||=$g(a,String(t)),c||=e_(a,String(t),r),c&&(Og(c),await Pg(c),g_(c,r),kg(c),await zg(120),i=[c],n.push(String(t)))}if(!n.length)return Z(`fwh-fill-form-mvp ✖ no matches`),`Could not match any fields. Call fwh-list-forms-mvp 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 Z(`fwh-fill-form-mvp ✓`,a),bg(`Form filled`,{spinner:!1,icon:`✅`,duration:1100}),a}catch(e){let t=`FORM_ERROR: ${e?.message||String(e)}`;return Z(`fwh-fill-form-mvp ✖`,t),bg(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{Fg(),Dg(),xg(700)}},"fwh-click-button-mvp":async e=>{let t=d_(e),n=(t.button_text??t.buttonText??t.text??``).trim();if(Z(`fwh-click-button-mvp ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=u_(n,i);if(!r)return Z(`fwh-click-button-mvp ✖ no match`),`Could not find a button matching "${n}". Call fwh-list-forms-mvp to see button texts.`;try{bg(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await Pg(r),r.focus?.(),await Ig(r),Lg(r),r.click();let e=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return Z(`fwh-click-button-mvp ✓`,t),bg(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return Z(`fwh-click-button-mvp ✖`,t),bg(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{Fg(),xg(700)}}};return{...a,highlightOnPage:a[`fwh-highlight-mvp`],getPageContent:a[`fwh-page-content-mvp`],endVoiceSession:a[`fwh-end-session-mvp`],listPageForms:a[`fwh-list-forms-mvp`],fillFormFields:a[`fwh-fill-form-mvp`],clickPageButton:a[`fwh-click-button-mvp`]}}var b_=(0,d.createContext)(null),x_=()=>{let e=(0,d.useContext)(b_);if(!e)throw Error(`useFlowEngage must be used inside FlowEngageProvider`);return e},S_=e=>!e||typeof e!=`string`?e:e.replace(/<human_assistance_request[^>]*>/gi,``).replace(/<\/human_assistance_request>/gi,``).replace(/<navigate[^>]*\/>/gi,``).replace(/<navigate[^>]*>[\s\S]*?<\/navigate>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*>[\s\S]*?<\/[a-z]+(?:_[a-z]+)+>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*\/>/gi,``).trim(),C_=(e=[])=>e.filter(e=>e.type!==`call_recording`&&!(typeof e.message==`string`&&e.message.includes(`AI chat recording`))).map(e=>({...e,message:S_(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`}));function w_(e){if(!e||typeof e!=`string`)return null;let t=e.match(/<navigate([^>]*?)(?:\/>|>[\s\S]*?<\/navigate>)/i);if(!t)return null;let n=t[1],r=n.match(/url=["']([^"']+)["']/i);if(!r)return null;let i=n.match(/section=["']([^"']+)["']/i)||n.match(/highlight=["']([^"']+)["']/i);return{url:r[1].trim(),section:i?.[1]?.trim()||null}}var T_=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,E_=(e={})=>{if(!e?.candidate)return null;if(typeof e.candidate==`object`)return e.candidate;let t=e.sdpMid!==void 0&&e.sdpMid!==null&&e.sdpMid!==``,n=e.sdpMLineIndex!==void 0&&e.sdpMLineIndex!==null;return!t&&!n?null:{candidate:e.candidate,...t?{sdpMid:e.sdpMid}:{},...n?{sdpMLineIndex:e.sdpMLineIndex}:{}}},D_=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t},O_=(e=[],t,n=6)=>!t?.message||e.slice(-n).some(e=>e.sender===`system`&&e.message===t.message)?e:[...e,t];function k_({siteId:e,config:t,children:n,language:r=`en`}){let i=(0,d.useMemo)(()=>e?{...t||{},siteId:e}:t||null,[e,t]),[a,o]=(0,d.useState)(0),[s,c]=(0,d.useState)(`booting`),[l,u]=(0,d.useState)(null),[m,h]=(0,d.useState)(null),[g,_]=(0,d.useState)(``),[x,S]=(0,d.useState)([]),[re,C]=(0,d.useState)(le().isOpen),[ie,ae]=(0,d.useState)(le().activeScreen),[pe,me]=(0,d.useState)(le().isHumanHandled),[he,_e]=(0,d.useState)(le().agentName),[ve,ye]=(0,d.useState)(le().agentHeadshot),[be,xe]=(0,d.useState)(()=>de(i?.siteId)),[Se,Ce]=(0,d.useState)(!1),[we,Ee]=(0,d.useState)(!1),[De,Oe]=(0,d.useState)(`idle`),[ke,Ae]=(0,d.useState)(!1),[je,w]=(0,d.useState)(!1),[Me,Ne]=(0,d.useState)(``),[Pe,Re]=(0,d.useState)(!1),[ze,Be]=(0,d.useState)(0),[Ve,He]=(0,d.useState)(0),[Ue,We]=(0,d.useState)(!1),[T,Ge]=(0,d.useState)(null),[Ke,qe]=(0,d.useState)(null),[Je,Ye]=(0,d.useState)(`idle`),[Xe,Ze]=(0,d.useState)(null),[Qe,$e]=(0,d.useState)(!1),[et,tt]=(0,d.useState)(``),[nt,rt]=(0,d.useState)(!1),it=(0,d.useRef)(null),E=(0,d.useRef)(null),D=(0,d.useRef)(``),at=(0,d.useRef)(!1),ot=(0,d.useRef)(null),O=(0,d.useRef)(null),st=(0,d.useRef)(null),ct=(0,d.useRef)(null),lt=(0,d.useRef)(null),k=(0,d.useRef)(null),ut=(0,d.useRef)(null),dt=(0,d.useRef)(!1),ft=(0,d.useRef)([]),pt=(0,d.useRef)(null),mt=(0,d.useRef)(null),ht=(0,d.useRef)(null),gt=(0,d.useRef)(!1),_t=(0,d.useRef)(!1),vt=(0,d.useRef)(``),yt=(0,d.useRef)(null),bt=(0,d.useRef)(null),xt=(0,d.useRef)([]),St=(0,d.useRef)(0),Ct=(0,d.useRef)(he),wt=(0,d.useRef)([]),Tt=(0,d.useRef)(!1),Et=(0,d.useRef)(!1),Dt=(0,d.useRef)(i),Ot=(0,d.useRef)(null),kt=(0,d.useRef)(null),At=(0,d.useRef)(!1),jt=(0,d.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),Mt=(0,d.useCallback)((e={})=>{let t=!!e.is_human_handled;return me(t),t?(ae(`agent`),e.agent_info?.name&&_e(e.agent_info.name),e.agent_info?.headshot&&ye(e.agent_info.headshot),t):(ae(`ai`),t)},[]),Nt=(0,d.useMemo)(()=>{let e=m?.widgetSettings?.call?.maxDurationSeconds??i?.widgetSettings?.call?.maxDurationSeconds??i?.callMaxDurationSeconds,t=Number(e);return Number.isFinite(t)&&t>0?t:y},[i,m]);(0,d.useEffect)(()=>{O.current=T},[T]),(0,d.useEffect)(()=>{Ct.current=he},[he]),(0,d.useEffect)(()=>{Et.current=Pe},[Pe]),(0,d.useEffect)(()=>{Dt.current=i},[i]);let Pt=()=>{tt(``)},Ft=(0,d.useCallback)(()=>{ht.current&&=(window.clearTimeout(ht.current),null)},[]),It=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return xe(t),fe(t,i?.siteId),t};(0,d.useEffect)(()=>{let e=i?.siteId;e&&xe(de(e))},[i?.siteId]);let Lt=(e=`unspecified`)=>{let t=pt.current||k.current?.callId,n=St.current,r=yt.current;if(yt.current=null,St.current=0,r&&r.state!==`inactive`){r.onstop=()=>{let e=xt.current;if(xt.current=[],e.length>0&&t&&E.current){let r=new Blob(e,{type:e[0].type}),i=n>0?Math.round((Date.now()-n)/1e3):0;E.current.uploadRecording(t,r,i).then(e=>console.log(`[FlowEngageCall] recording upload success`,e)).catch(e=>console.warn(`[FlowEngageCall] recording upload failed`,e))}};try{r.stop()}catch{r.onstop=null,xt.current=[]}}else if(r&&r.state===`inactive`){let e=xt.current;if(xt.current=[],e.length>0&&t&&E.current){let r=new Blob(e,{type:e[0].type}),i=n>0?Math.round((Date.now()-n)/1e3):0;E.current.uploadRecording(t,r,i).then(e=>console.log(`[FlowEngageCall] recording upload success`,e)).catch(e=>console.warn(`[FlowEngageCall] recording upload failed`,e))}}else xt.current=[];if(bt.current){try{bt.current.close()}catch{}bt.current=null}st.current&&=(st.current.close(),null),ct.current&&=(ct.current.getTracks().forEach(e=>e.stop()),null),lt.current&&=(lt.current.srcObject=null,lt.current.remove(),null),Ft(),k.current=null,ft.current=[],pt.current=null,mt.current=null,gt.current=!1,$e(!1),Ge(null),qe(null),Ye(`idle`),Ze(null)},Rt=(e=new Date().toISOString())=>{let t=it.current,n=pt.current||k.current?.callId;if(!(!t?.connected||!n||gt.current)){gt.current=!0,t.emit(`call:connected`,{callId:n,chatId:D.current,connectedAt:e});try{let e=ct.current,t=lt.current?.srcObject;if(e&&t&&!yt.current){xt.current=[];let n=new(window.AudioContext||window.webkitAudioContext);bt.current=n;let r=n.createMediaStreamDestination();n.createMediaStreamSource(e).connect(r),n.createMediaStreamSource(t).connect(r);let i=window.MediaRecorder.isTypeSupported(`audio/webm`)?`audio/webm`:`audio/mp4`,a=new window.MediaRecorder(r.stream,{mimeType:i});a.ondataavailable=e=>{e.data&&e.data.size>0&&xt.current.push(e.data)},yt.current=a,St.current=Date.now(),a.start(1e3),setTimeout(()=>{try{if(!window.speechSynthesis)return;let e=new SpeechSynthesisUtterance(`This call is being recorded for quality and training purposes.`);if(e.rate=.95,e.pitch=1,e.volume=1,window.MediaStreamTrackGenerator||window.AudioContext)try{let t=n.createMediaStreamDestination();e.onstart=()=>{try{let i=document.createElement(`audio`);i.style.display=`none`,i.srcObject=t.stream,document.body.appendChild(i),i.play().catch(()=>{});let a=n.createMediaStreamSource(t.stream);a.connect(r),e.onend=()=>{try{a.disconnect()}catch{}try{i.remove()}catch{}}}catch{}}}catch{}window.speechSynthesis.speak(e)}catch{}},200)}}catch{}}},zt=(e={})=>{if(!e.callId)return;let t=mt.current===e.callId,n=pt.current===e.callId,r=O.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(Ft(),Ge(null),t||n){pt.current=e.callId,qe(e.callId),Ye(e=>e===`connected`?e:`connecting`),C(!0);return}Ye(`idle`)}},Bt=(e={})=>{if(!e.callId)return;let t=mt.current===e.callId,n=pt.current===e.callId,r=O.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(Ft(),n){Lt();return}mt.current=null,k.current=null,ft.current=[],Ge(null),Ye(`idle`)}},Vt=async(e={})=>{let t=st.current,n=it.current,r=e.sdpOffer||e.offer?.sdp;if(!t||!n?.connected||!r||!e.callId){console.log(`[FlowEngageProvider] deferring remote offer until peer/socket ready`,{callId:e.callId,chatId:D.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),k.current=e;return}if(await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),ft.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:D.current,queuedCount:ft.current.length});for(let e of ft.current)await t.addIceCandidate(new RTCIceCandidate(e));ft.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:D.current})};(0,d.useEffect)(()=>{ue({isOpen:re,activeScreen:ie,isHumanHandled:pe,agentName:he,agentHeadshot:ve})},[re,ie,pe,he,ve]),(0,d.useEffect)(()=>{let e=!0;return(async()=>{rt(!0);try{if(i?.standalone){let e=i.siteId||`standalone`,t=oe(e)||ne();ce(e,t),D.current=t,h({siteId:e,apiBaseUrl:i.apiBaseUrl||null,widgetSettings:i.widgetSettings||{},siteType:i.siteType||`spa`,standalone:!0}),_(t),c(`ready`);return}let t=p(i),n=await Ie(t);if(!e)return;let a=t.siteId,o=oe(a),s=ge(a),l=``;try{let e=at.current,r=ot.current;if(at.current=!1,ot.current=null,l=(await Fe({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:a,priorChatId:e||r?null:o||ee(),forceNew:e,resumeChatId:r,visitorId:s}))?.data?.chatId,!l)throw Error(`resolve-session returned no chatId`);te(),ce(a,l)}catch(e){console.warn(`[FlowEngageProvider] resolve-session failed, reusing persisted or ephemeral chat id`,e?.message||e),l=o||ne(),ce(a,l)}D.current=l;let u=Le({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId,visitorId:s});E.current=u,h({...n,apiBaseUrl:t.apiBaseUrl}),_(l);let d=n?.widgetSettings?.branding?.fallbackAgentName||`Agent`,f=Cn({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:l,siteId:t.siteId});it.current=f,f.on(`connect`,()=>{Oe(`connected`)}),f.on(`disconnect`,()=>{Oe(`disconnected`)}),f.on(`aiTyping`,()=>{Ee(!0)}),f.on(`ai:typing`,()=>{Ee(!0)}),f.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:S_(t.message)};Ee(!1),Ce(!1),!(n.type===`call_recording`||typeof n.message==`string`&&n.message.includes(`AI chat recording`))&&S(e=>[...e.filter(e=>!e.isPending),{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}])}),f.on(`conversationStarted`,e=>{e?.message&&S(t=>[...t,{id:`system-start-${Date.now()}`,sender:`system`,message:e.message,timestamp:new Date().toISOString(),isPending:!1}])}),f.on(`message:new`,e=>{let t=e.message||e,n={...t,message:S_(t.message)};Ee(!1),!(n.type===`call_recording`||typeof n.message==`string`&&n.message.includes(`AI chat recording`))&&((n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&Ce(!1),S(e=>n.sender===`bot`||n.sender===`ai`?[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]:e.some(e=>e.id===n.messageId||e.sender===n.sender&&e.message===n.message&&e.isPending)?e.map(e=>e.sender===n.sender&&e.message===n.message&&e.isPending?{...n,isPending:!1,id:n.messageId||e.id}:e):[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]),(n.sender===`agent`||n.agent_name)&&(me(!0),ae(`agent`),_e(D_([n.agent_name,n.agentName,n.metadata?.agentName],d)),n.sender_headshot&&ye(n.sender_headshot),C(!0),Be(e=>e+1)))});let m=(e={})=>{let t=D_([e.agent?.name,e.agentName,e.agent_name,Ct.current],d);me(!0),ae(`agent`),_e(t),ye(e.agent?.headshot||null),C(!0),Be(e=>e+1),S(e=>O_(e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}))},g=(e={})=>{let t=D_([e.agent?.name,e.agentName,e.agent_name,Ct.current],d);me(!1),ae(`ai`),S(e=>O_(e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}))};f.on(`agent:joined`,m),f.on(`agentJoined`,m),f.on(`agent:left`,g),f.on(`agentLeft`,g),f.on(`conversationEnded`,e=>{We(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;S(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),f.on(`chat:history_update`,e=>{let t=C_(e.chat_history||[]);S(t),t.length===0&&(We(!1),me(!1),ae(`ai`),Ee(!1),Ce(!1))}),f.on(`conversation:reset`,()=>{S([]),We(!1),me(!1),ae(`ai`),Ee(!1),Ce(!1)}),f.on(`voice:end_session`,(e={})=>{console.log(`[FlowEngageProvider] voice:end_session received — ending ElevenLabs session`),He(e=>e+1),C(!0),Be(e=>e+1)}),f.on(`typing:start`,e=>{e.sender===`agent`&&Ce(!0)}),f.on(`typing:stop`,e=>{e.sender===`agent`&&Ce(!1)}),f.on(`call:incoming`,(e={})=>{let t=D_([e.agentName,e.ownerName,e.agent?.name,Ct.current],`Agent`);Pt(),Ft(),gt.current=!1,Ge({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),_e(e=>D_([t,e],`Agent`)),Ye(`incoming`),Ze(null),C(!0)}),f.on(`call:offer`,async(e={})=>{k.current=e;try{await Vt(e)}catch(e){console.error(`[FlowEngageProvider] failed to apply remote offer`,e)}}),f.on(`call:ice-candidate-from-agent`,async(e={})=>{if(e.candidate)try{let t=E_(e);if(!t){console.warn(`[FlowEngageProvider] ignoring invalid ICE candidate payload`,e);return}if(!st.current||!st.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||D.current,queueSize:ft.current.length+1}),ft.current.push(t);return}await st.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),f.on(`call:ended`,()=>{Pt(),Lt(`socket:call_ended`)}),f.on(`call:accepted`,(e={})=>{zt(e)}),f.on(`call:accepted_by_other`,(e={})=>{zt(e)}),f.on(`call:rejected`,(e={})=>{Bt(e)}),f.on(`call:missed`,(e={})=>{Bt(e)}),f.on(`call:failed`,(e={})=>{Bt(e)}),f.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=mt.current===e.callId,n=pt.current===e.callId,r=k.current?.callId===e.callId,i=O.current?.callId===e.callId;if(!t&&!n&&!r){i&&(Ge(null),Ye(`idle`));return}gt.current=!0,mt.current=null,pt.current=e.callId,qe(e.callId),Ge(null),Ye(`connected`),Ze(e.connectedAt||new Date().toISOString()),C(!0)}),f.on(`call:unavailable`,(e={})=>{Lt(`socket:call_unavailable`),tt(T_(e,`This visitor is not available for a call right now.`)),C(!0)}),f.on(`call:error`,(e={})=>{Lt(`socket:call_error`),tt(T_(e,`We couldn't connect the call right now.`)),C(!0)}),f.on(`visitor:navigate`,async({url:e,section:n,highlight:r}={})=>{e&&await eg(e,{siteId:t.siteId,apiBaseUrl:t.apiBaseUrl})&&og(e,{voiceActive:Et.current}).then(e=>{let t=n||r;t&&setTimeout(()=>{let e=Yh(null,t);e&&Xh(e)},e?300:150)})}),f.on(`visitor:highlight`,({sectionId:e,sectionText:t}={})=>{if(!e&&!t)return;let n=Yh(e||null,t||null);n&&Xh(n)}),f.on(`visitor:clear_highlight`,()=>{Zh()}),jt.current=wn({socket:f,chatId:l});let v=await u.loadHistory(l,r);if(!e)return;S(C_(v.chat_history||[])),me(!!v.is_human_handled),ae(v.is_human_handled?`agent`:ie);let y=v?.visitor_email||v?.visitorEmail;if(y&&String(y).trim()&&It(String(y).trim()),await new Promise(e=>setTimeout(e,500)),!e)return;c(`ready`)}catch(t){if(!e)return;u(t),c(`error`)}finally{e&&rt(!1)}})(),()=>{e=!1,jt.current?.cleanup?.(),Lt(),it.current?.disconnect();try{Ot.current?.endSession?.()}catch{}Ot.current=null,kt.current=null}},[i,r,a]),(0,d.useEffect)(()=>()=>{if(Pe&&!Tt.current&&wt.current.length>0){let e=D.current,t=wt.current,n=E.current;n&&e&&t.length>0&&(console.log(`[FlowEngageProvider] safety-net: syncing voice transcript on unmount`),n.beaconSyncVoice(e,t)||n.syncVoice(e,t).catch(()=>{}),Tt.current=!0)}},[Pe,m]);let Ht=(0,d.useRef)(null),Ut=(0,d.useRef)(!1);(0,d.useEffect)(()=>{let e=E.current;!e||!g||Ht.current!==re&&(re&&Ht.current!==null?(e.updateChatStatus(g,`open`).catch(()=>{}),Ut.current=!0):Ht.current===!0&&e.updateChatStatus(g,`widget_closed`).catch(()=>{}),Ht.current=re)},[re,g]),(0,d.useEffect)(()=>{let e=()=>{let e=D.current,t=E.current;!e||!t||typeof navigator>`u`||t.beaconWidgetClosed?.(e)||t.updateChatStatus(e,`widget_closed`).catch(()=>{})};return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[]),(0,d.useEffect)(()=>{if(!E.current||!g||s!==`ready`)return;let e=window.setInterval(async()=>{try{let e=await E.current.checkHumanHandled(g);me(!!e.is_human_handled),e.is_human_handled&&(ae(`agent`),e.agent_info?.name&&_e(D_([e.agent_info.name],`Agent`)),e.agent_info?.headshot&&ye(e.agent_info.headshot)),Mt(e)}catch{}},1e4);return()=>window.clearInterval(e)},[g,s,Mt]);let Wt=async()=>{if(!(!T?.callId||!E.current||!it.current||!g)){Pt(),mt.current=T.callId,Ft();try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});ct.current=e;let t=[{urls:`stun:stun.l.google.com:19302`}];try{let e=await E.current.getIceServersConfig();e?.data?.iceServers?.length&&(t=e.data.iceServers)}catch(e){console.warn(`[FlowEngageProvider] ice-config fetch failed, using STUN default`,e)}let n=new RTCPeerConnection({iceServers:t});st.current=n,n.onconnectionstatechange=()=>{let e=n.connectionState;if(e===`connected`){let e=new Date().toISOString();Ye(`connected`),Ze(t=>t||e),Rt(e);return}if(e===`connecting`){Ye(e=>e===`connected`?e:`connecting`);return}(e===`failed`||e===`closed`)&&Lt(`peer:connection_${e}`)},n.oniceconnectionstatechange=()=>{let e=n.iceConnectionState;if(e===`connected`||e===`completed`){let e=new Date().toISOString();Ye(`connected`),Ze(t=>t||e),Rt(e);return}if(e===`checking`||e===`new`){Ye(e=>e===`connected`?e:`connecting`);return}(e===`failed`||e===`closed`)&&Lt(`peer:ice_${e}`)},n.onsignalingstatechange=()=>{},n.onicegatheringstatechange=()=>{},e.getTracks().forEach(t=>{n.addTrack(t,e)}),n.onicecandidate=e=>{if(!e.candidate||!it.current?.connected)return;let t=e.candidate;it.current.emit(`call:ice-candidate`,{callId:T.callId,candidate:t.candidate,sdpMid:t.sdpMid,sdpMLineIndex:t.sdpMLineIndex,chatId:g,from:`customer`})},n.ontrack=e=>{let[t]=e.streams||[],[n]=t?.getAudioTracks?.()||[];if(!lt.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,e.playsInline=!0,e.onplay=()=>{},e.onpause=()=>{},e.onended=()=>{},e.onerror=e=>{},lt.current=e,document.body.appendChild(e)}lt.current.srcObject=e.streams[0];let r=T?.callId,i=r&&(mt.current===r||pt.current===r);if(!gt.current&&i){let e=new Date().toISOString();Ye(`connected`),Ze(t=>t||e),pt.current=r,qe(r),Rt(e)}lt.current.srcObject=t||null;let a=lt.current.play?.();a?.catch&&a.catch(e=>{})};let r=k.current;r&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:r.callId||T.callId,chatId:g}),await Vt({...r,callId:r.callId||T.callId})),await E.current.acceptCall(T.callId,g),it.current?.emit(`call:accepted`,{callId:T.callId,chatId:g}),pt.current=T.callId,qe(T.callId),Ye(e=>e===`connected`||gt.current?`connected`:`connecting`),Ge(null),C(!0)}catch(e){if(mt.current=null,Lt(`accept_call_failed`),e?.status===404||e?.status===409||e?.status===422){tt(T_(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await E.current.rejectCall(T.callId,g)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}tt(`Microphone access was denied. Please allow microphone access to accept the call.`);return}tt(`We couldn't connect the call right now. Please try again.`)}}},Gt=async()=>{if(!T?.callId||!E.current||!g){Lt(`reject_call_without_server_context`);return}let e=T.callId;Ft(),Pt(),it.current?.emit(`call:rejected`,{callId:e,chatId:g,reason:`visitor_declined`});try{await E.current.rejectCall(e,g)}catch(e){tt(T_(e,`We couldn't decline the call cleanly.`))}finally{Lt(`reject_call_finally`)}},Kt=(0,d.useRef)(Gt);Kt.current=Gt,(0,d.useEffect)(()=>{if(!T?.callId||Ke){Ft();return}let e=T.callId;return Ft(),ht.current=window.setTimeout(()=>{O.current?.callId===e&&mt.current!==e&&pt.current!==e&&Kt.current()},b),()=>{ht.current&&=(window.clearTimeout(ht.current),null)}},[Ke,Ft,T?.callId]);let qt=async()=>{if(!Ke||!E.current||!g){Lt(`end_call_without_server_context`);return}Pt();try{await E.current.endWebRTCCall(Ke,g)}catch(e){tt(T_(e,`The call ended locally, but the server could not be updated.`))}finally{Lt(`end_call_finally`)}},Jt=()=>{let e=ct.current?.getAudioTracks?.()||[],t=st.current?.getSenders?.().map(e=>e.track).filter(e=>e?.kind===`audio`)||[],n=[...e,...t].filter(Boolean);if(n.length===0)return;let r=!Qe;n.forEach(e=>{e.enabled=!r}),$e(r)},Yt=async(e={})=>{let t=e.notifyChatInitiated===!0;if(Ut.current=!0,C(!0),!(!t||!E.current||!g||typeof window>`u`)){try{await E.current.trackVisitor({chatId:g,currentPagePath:window.location.pathname||`/`})}catch{}try{await E.current.updateChatStatus(g,`open`)}catch{}}},Xt=async e=>{let t=It(e);if(!t||!E.current||!D.current)return t;try{await E.current.trackVisitor({chatId:D.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},Zt=()=>{!g||!it.current?.connected||_t.current||(_t.current=!0,it.current.emit(`typing:start`,{chatId:g,sender:`user`}))},Qt=()=>{!g||!it.current?.connected||!_t.current||(_t.current=!1,it.current.emit(`typing:stop`,{chatId:g,sender:`user`}))},$t=(e=``)=>{let t=typeof e==`string`?e:``;!g||!it.current?.connected||t!==``&&vt.current===t||(vt.current=t,it.current.emit(`typing:update`,{chatId:g,sender:`user`,text:t}))},en=(0,d.useCallback)(async()=>{if(Ot.current)return Ot.current;if(kt.current)return kt.current;let e=Dt.current||{},t=e.widgetSettings||{},n=t.elevenLabsAgentId;if(!n)return null;let r={...y_({siteId:e.siteId||null,apiBaseUrl:e.apiBaseUrl||null,getLastUserVoiceText:()=>``}),...t.voiceClientTools||{}};return At.current=!0,kt.current=hh.startSession({agentId:n,textOnly:!0,connectionType:`websocket`,clientTools:r,onMessage:e=>{if(!e||e.role===`user`)return;let t=e.message||e.text||e.content||``;if(t){if(At.current){At.current=!1;return}Ee(!1),S(e=>[...e,{id:`ai-${Date.now()}-${Math.random().toString(36).slice(2)}`,sender:`ai`,message:t,timestamp:new Date().toISOString(),isPending:!1,type:`text`}])}},onError:e=>{console.warn(`[FlowEngage] text session error:`,e),Ee(!1)},onDisconnect:()=>{Ot.current=null}}).then(e=>(Ot.current=e,kt.current=null,e)).catch(e=>(console.warn(`[FlowEngage] text session failed to start:`,e),kt.current=null,null)),kt.current},[]),tn=async(e,t=``,n=null,a={})=>{let o=typeof e==`string`?e.trim():``;if(Dt.current?.standalone){if(!o||Ue)return;S(t=>[...t,{id:`user-${Date.now()}`,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!1,type:a?.type||`text`,...n||{}}]),Ee(!0);let t=await en();if(!t){Ee(!1),S(e=>[...e,{id:`ai-err-${Date.now()}`,sender:`ai`,message:`Sorry, the assistant isn't available right now.`,timestamp:new Date().toISOString(),isPending:!1,type:`text`}]);return}try{t.sendUserMessage(o)}catch(e){console.warn(`[FlowEngage] sendUserMessage failed:`,e),Ee(!1)}return}if(!o||!E.current||!g||s!==`ready`||Ue)return;Qt();let c=/^\s*(yes|yeah|sure|ok|okay|go ahead|take me(?: there)?(?!\s+\w)|navigate(?!\s+(?:me\s+)?to\s+\w)|yep|absolutely|please do|do it|let'?s go|go there|show me(?!\s+(?:the|a|an)\s+\w)|go to it|bring me there|navigate me there)\b/i,l=/^\s*(?:yes|yeah|sure|ok|okay|yep|absolutely)\s+(?!(?:please|do\s+it|let'?s|that|this|there|it|thanks|go|cool|great|perfect|sounds|alright|proceed)\b)\w/i,d=/\b(take me|navigate|go to|show me|bring me|open|go there|navigate to|take me to|let'?s go to)\b/i;if(ut.current&&c.test(o)&&!l.test(o)){let{url:e,section:t}=ut.current;ut.current=null,dt.current=!0,console.log(`[FWH Nav] Client-side nav firing →`,e),og(e,{voiceActive:Et.current}).then(e=>{!t||!Et.current||setTimeout(()=>{let e=Yh(null,t);e&&Xh(e)},e?300:150)})}else c.test(o)||(ut.current=null);let f=`pending-user-${Date.now()}`,p={id:f,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,type:a?.type||`text`,metadata:a?.metadata||void 0,...n||{}};S(e=>[...e,p]);let m=pe;if(m)try{m=Mt(await E.current.checkHumanHandled(g))}catch{}if(m&&it.current?.connected){it.current.emit(`customer:message`,{chatId:g,content:e,sender:`user`,email:be||void 0,type:a?.type||`text`,metadata:a?.metadata||{},...n||{}});return}Ae(!0);try{let s=await E.current.sendAiMessage(g,e,r,t,{...n||{},...be?{email:be}:{}},{...a,currentPageUrl:typeof window<`u`?window.location.href:void 0,currentPageTitle:typeof window<`u`?document.title:void 0,currentPagePath:typeof window<`u`?window.location.pathname:void 0}),c=s.chat_history||[];if(console.log(`[FWH Nav Debug] API response fields:`,{has_navigate:!!s.navigate,navigate:s.navigate,has_pending_navigate:!!s.pending_navigate,pending_navigate:s.pending_navigate,last_bot_msg:[...c].reverse().find(e=>e.sender===`bot`)?.message?.substring(0,80)}),s.pending_navigate?.url){let e={url:s.pending_navigate.url,section:s.pending_navigate.section||null};d.test(o)?(console.log(`[FWH Nav] Auto-navigating (intent detected) →`,e.url),eg(e.url,{siteId:i?.siteId,apiBaseUrl:i?.apiBaseUrl}).then(t=>{t&&og(e.url,{voiceActive:Et.current}).then(t=>{e.section&&setTimeout(()=>{let t=Yh(null,e.section);t&&Xh(t)},t?300:150)})})):(ut.current=e,console.log(`[FWH Nav] Stored pending nav →`,ut.current))}if(s.navigate?.url)if(dt.current)dt.current=!1;else{let{url:e,section:t}=s.navigate;og(e,{voiceActive:Et.current}).then(e=>{!t||!Et.current||setTimeout(()=>{let e=Yh(null,t);e&&Xh(e)},e?300:150)})}else{let e=[...c].reverse().find(e=>e.sender===`bot`||e.sender===`assistant`);if(e?.message){let t=w_(e.message);t&&eg(t.url,{siteId:Dt.current?.siteId,apiBaseUrl:Dt.current?.apiBaseUrl}).then(e=>{e&&og(t.url,{voiceActive:Et.current}).then(e=>{!t.section||!Et.current||setTimeout(()=>{let e=Yh(null,t.section);e&&Xh(e)},e?300:150)})})}}S(C_(c)),me(!!s.is_human_handled),ae(s.is_human_handled?`agent`:`ai`),Ee(!1),Ae(!1),await E.current.updateChatStatus(g,`messageSent`)}catch(e){S(e=>e.filter(e=>e.id!==f)),Ee(!1),Ae(!1),e.status===429?(w(!0),Ne(e.message),window.setTimeout(()=>{w(!1),Ne(``)},v)):u(e)}},nn=async e=>{if(!E.current||!e)throw Error(`Upload is unavailable right now.`);return E.current.uploadChatFile(e)},rn=async e=>{if(!(!E.current||!g)){try{let t=e?`voice`:`text`;await E.current.setChatMode(g,t)}catch{}Re(e),e&&(Tt.current=!1)}},an=async e=>{if(Tt.current)return;if(Tt.current=!0,!E.current||!g||!e?.length){Re(!1);return}let t=()=>{let t=C_(e);S(e=>{if(!e.length)return t;let n=e[e.length-1],r=t[0];return n&&r&&n.sender===r.sender&&n.message===r.message?e:[...e,...t]})};try{let n=await E.current.syncVoice(g,e);if(n?.chat_history?.length)S(C_(n.chat_history));else if(n?.success)try{let e=await E.current.loadHistory(g,r);e?.chat_history?.length?S(C_(e.chat_history)):t()}catch{t()}else t()}catch{t()}finally{Re(!1)}},on=async()=>{if(!(!E.current||!g)){Pe&&!Tt.current&&wt.current.length>0&&await an(wt.current);try{await E.current.endConversation(g)}catch{try{await E.current.updateChatStatus(g,`ended`)}catch{}}We(!0),S(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:`This conversation has ended. Thank you for reaching out!`,timestamp:new Date().toISOString(),isPending:!1}])}};(0,d.useEffect)(()=>{if(Je!==`connected`||!Ke||!g||!Xe||!Nt)return;let e=new Date(Xe).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,Nt*1e3-t),r=window.setTimeout(()=>{tt(`The call ended because it reached the time limit.`),qt()},n);return()=>window.clearTimeout(r)},[Ke,Xe,Je,g,qt,Nt]),(0,d.useEffect)(()=>{let e=()=>{let e=D.current,t=E.current;if(!t||!e)return;if(Et.current&&wt.current.length>0&&Te(),!Tt.current&&wt.current.length>0&&(t.beaconSyncVoice(e,wt.current)||t.syncVoice(e,wt.current).catch(()=>{}),Tt.current=!0),pt.current){t.beaconEndWebRTCCall(pt.current,e);return}let n=mt.current||O.current?.callId;n&&t.beaconCustomerUnavailable(n,e)};return window.addEventListener(`pagehide`,e),window.addEventListener(`beforeunload`,e),()=>{window.removeEventListener(`pagehide`,e),window.removeEventListener(`beforeunload`,e)}},[]);let A=(0,d.useCallback)(()=>{let e=i?.siteId;se(e),at.current=!0,ot.current=null,it.current?.disconnect(),S([]),_(``),D.current=``,We(!1),me(!1),_e(null),ye(null),rt(!0),o(e=>e+1)},[i?.siteId]),sn=(0,d.useCallback)(e=>{i?.siteId,at.current=!1,ot.current=e,it.current?.disconnect(),S([]),_(``),D.current=``,We(!1),me(!1),_e(null),ye(null),rt(!0),o(e=>e+1)},[i?.siteId]),cn=(0,d.useMemo)(()=>({status:s,error:l,runtimeConfig:m,resolvedConfig:i,chatId:g,chatHistory:x,isOpen:re,activeScreen:ie,isHumanHandled:pe,agentName:he,agentHeadshot:ve,visitorEmail:be,isAgentTyping:Se,isAiTyping:we,connectionStatus:De,isLoading:ke,isVoiceMode:Pe,isRateLimited:je,rateLimitMessage:Me,isConversationEnded:Ue,isSessionRestoring:nt,openToChatCounter:ze,voiceEndCounter:Ve,incomingCall:T,activeCallId:Ke,callConnectionState:Je,callConnectedAt:Xe,isCallMuted:Qe,webRTCError:et,language:r,historyRef:wt,hasSyncedRef:Tt,dismissCallError:Pt,captureVisitorEmail:Xt,startTyping:Zt,stopTyping:Qt,updateTypingDraft:$t,notifyRouteChange:()=>jt.current?.notifyRouteChange?.(),openWidget:Yt,closeWidget:()=>C(!1),toggleWidget:()=>{if(re){C(!1);return}Yt({notifyChatInitiated:!0})},sendMessage:tn,uploadChatFile:nn,setVoiceMode:rn,onMessageSync:an,endConversation:on,startNewChat:A,resumeChat:sn,getVisitorChatHistory:()=>E.current?.getVisitorChatHistory?.(),getVisitorChatThread:e=>E.current?.getVisitorChatThread?.(e),acceptCall:Wt,rejectCall:Gt,endWebRTCCall:qt,toggleCallMute:Jt}),[s,l,m,i,g,x,re,ie,pe,he,ve,be,Se,we,De,ke,Pe,je,Me,Ue,nt,ze,Ve,T,Ke,Je,Xe,Qe,et,r,Xt,Zt,Qt,$t,Wt,Gt,qt,Jt,Yt,tn,nn,rn,an,on,A,Pt]);return(0,f.jsx)(b_.Provider,{value:cn,children:n})}var A_=(0,d.createContext)({});function j_(e){let t=(0,d.useRef)(null);return t.current===null&&(t.current=e()),t.current}var M_=typeof window<`u`?d.useLayoutEffect:d.useEffect,N_=(0,d.createContext)(null);function P_(e,t){e.indexOf(t)===-1&&e.push(t)}function F_(e,t){let n=e.indexOf(t);n>-1&&e.splice(n,1)}var I_=(e,t,n)=>n>t?t:n<e?e:n;function L_(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}var R_=()=>{},z_=()=>{};typeof process<`u`&&process.env.NODE_ENV!==`production`&&(R_=(e,t,n)=>{!e&&typeof console<`u`&&console.warn(L_(t,n))},z_=(e,t,n)=>{if(!e)throw Error(L_(t,n))});var B_={},V_=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function H_(e){return typeof e==`object`&&!!e}var U_=e=>/^0[^.\s]+$/u.test(e);function W_(e){let t;return()=>(t===void 0&&(t=e()),t)}var G_=e=>e,K_=(e,t)=>n=>t(e(n)),q_=(...e)=>e.reduce(K_),J_=(e,t,n)=>{let r=t-e;return r===0?1:(n-e)/r},Y_=class{constructor(){this.subscriptions=[]}add(e){return P_(this.subscriptions,e),()=>F_(this.subscriptions,e)}notify(e,t,n){let r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](e,t,n);else for(let i=0;i<r;i++){let r=this.subscriptions[i];r&&r(e,t,n)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}},X_=e=>e*1e3,Z_=e=>e/1e3;function Q_(e,t){return t?1e3/t*e:0}var $_=new Set;function ev(e,t,n){e||$_.has(t)||(console.warn(L_(t,n)),$_.add(t))}var tv=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,nv=1e-7,rv=12;function iv(e,t,n,r,i){let a,o,s=0;do o=t+(n-t)/2,a=tv(o,r,i)-e,a>0?n=o:t=o;while(Math.abs(a)>nv&&++s<rv);return o}function av(e,t,n,r){if(e===t&&n===r)return G_;let i=t=>iv(t,0,1,e,n);return e=>e===0||e===1?e:tv(i(e),t,r)}var ov=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,sv=e=>t=>1-e(1-t),cv=av(.33,1.53,.69,.99),lv=sv(cv),uv=ov(lv),dv=e=>e>=1?1:(e*=2)<1?.5*lv(e):.5*(2-2**(-10*(e-1))),fv=e=>1-Math.sin(Math.acos(e)),pv=sv(fv),mv=ov(fv),hv=av(.42,0,1,1),gv=av(0,0,.58,1),_v=av(.42,0,.58,1),vv=e=>Array.isArray(e)&&typeof e[0]!=`number`,yv=e=>Array.isArray(e)&&typeof e[0]==`number`,bv={linear:G_,easeIn:hv,easeInOut:_v,easeOut:gv,circIn:fv,circInOut:mv,circOut:pv,backIn:lv,backInOut:uv,backOut:cv,anticipate:dv},xv=e=>typeof e==`string`,Sv=e=>{if(yv(e)){z_(e.length===4,`Cubic bezier arrays must contain four numerical values.`,`cubic-bezier-length`);let[t,n,r,i]=e;return av(t,n,r,i)}else if(xv(e))return z_(bv[e]!==void 0,`Invalid easing type '${e}'`,`invalid-easing-type`),bv[e];return e},Cv=[`setup`,`read`,`resolveKeyframes`,`preUpdate`,`update`,`preRender`,`render`,`postRender`],wv={value:null,addProjectionMetrics:null};function Tv(e,t){let n=new Set,r=new Set,i=!1,a=!1,o=new WeakSet,s={delta:0,timestamp:0,isProcessing:!1},c=0;function l(t){o.has(t)&&(u.schedule(t),e()),c++,t(s)}let u={schedule:(e,t=!1,a=!1)=>{let s=a&&i?n:r;return t&&o.add(e),s.add(e),e},cancel:e=>{r.delete(e),o.delete(e)},process:e=>{if(s=e,i){a=!0;return}i=!0;let o=n;n=r,r=o,n.forEach(l),t&&wv.value&&wv.value.frameloop[t].push(c),c=0,n.clear(),i=!1,a&&(a=!1,u.process(e))}};return u}var Ev=40;function Dv(e,t){let n=!1,r=!0,i={delta:0,timestamp:0,isProcessing:!1},a=()=>n=!0,o=Cv.reduce((e,n)=>(e[n]=Tv(a,t?n:void 0),e),{}),{setup:s,read:c,resolveKeyframes:l,preUpdate:u,update:d,preRender:f,render:p,postRender:m}=o,h=()=>{let a=B_.useManualTiming,o=a?i.timestamp:performance.now();n=!1,a||(i.delta=r?1e3/60:Math.max(Math.min(o-i.timestamp,Ev),1)),i.timestamp=o,i.isProcessing=!0,s.process(i),c.process(i),l.process(i),u.process(i),d.process(i),f.process(i),p.process(i),m.process(i),i.isProcessing=!1,n&&t&&(r=!1,e(h))},g=()=>{n=!0,r=!0,i.isProcessing||e(h)};return{schedule:Cv.reduce((e,t)=>{let r=o[t];return e[t]=(e,t=!1,i=!1)=>(n||g(),r.schedule(e,t,i)),e},{}),cancel:e=>{for(let t=0;t<Cv.length;t++)o[Cv[t]].cancel(e)},state:i,steps:o}}var{schedule:Q,cancel:Ov,state:kv,steps:Av}=Dv(typeof requestAnimationFrame<`u`?requestAnimationFrame:G_,!0),jv;function Mv(){jv=void 0}var Nv={now:()=>(jv===void 0&&Nv.set(kv.isProcessing||B_.useManualTiming?kv.timestamp:performance.now()),jv),set:e=>{jv=e,queueMicrotask(Mv)}},Pv={layout:0,mainThread:0,waapi:0},Fv=e=>t=>typeof t==`string`&&t.startsWith(e),Iv=Fv(`--`),Lv=Fv(`var(--`),Rv=e=>Lv(e)?zv.test(e.split(`/*`)[0].trim()):!1,zv=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function Bv(e){return typeof e==`string`?e.split(`/*`)[0].includes(`var(--`):!1}var Vv={test:e=>typeof e==`number`,parse:parseFloat,transform:e=>e},Hv={...Vv,transform:e=>I_(0,1,e)},Uv={...Vv,default:1},Wv=e=>Math.round(e*1e5)/1e5,Gv=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Kv(e){return e==null}var qv=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Jv=(e,t)=>n=>!!(typeof n==`string`&&qv.test(n)&&n.startsWith(e)||t&&!Kv(n)&&Object.prototype.hasOwnProperty.call(n,t)),Yv=(e,t,n)=>r=>{if(typeof r!=`string`)return r;let[i,a,o,s]=r.match(Gv);return{[e]:parseFloat(i),[t]:parseFloat(a),[n]:parseFloat(o),alpha:s===void 0?1:parseFloat(s)}},Xv=e=>I_(0,255,e),Zv={...Vv,transform:e=>Math.round(Xv(e))},Qv={test:Jv(`rgb`,`red`),parse:Yv(`red`,`green`,`blue`),transform:({red:e,green:t,blue:n,alpha:r=1})=>`rgba(`+Zv.transform(e)+`, `+Zv.transform(t)+`, `+Zv.transform(n)+`, `+Wv(Hv.transform(r))+`)`};function $v(e){let t=``,n=``,r=``,i=``;return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),r=e.substring(5,7),i=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),r=e.substring(3,4),i=e.substring(4,5),t+=t,n+=n,r+=r,i+=i),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(r,16),alpha:i?parseInt(i,16)/255:1}}var ey={test:Jv(`#`),parse:$v,transform:Qv.transform},ty=e=>({test:t=>typeof t==`string`&&t.endsWith(e)&&t.split(` `).length===1,parse:parseFloat,transform:t=>`${t}${e}`}),ny=ty(`deg`),ry=ty(`%`),$=ty(`px`),iy=ty(`vh`),ay=ty(`vw`),oy={...ry,parse:e=>ry.parse(e)/100,transform:e=>ry.transform(e*100)},sy={test:Jv(`hsl`,`hue`),parse:Yv(`hue`,`saturation`,`lightness`),transform:({hue:e,saturation:t,lightness:n,alpha:r=1})=>`hsla(`+Math.round(e)+`, `+ry.transform(Wv(t))+`, `+ry.transform(Wv(n))+`, `+Wv(Hv.transform(r))+`)`},cy={test:e=>Qv.test(e)||ey.test(e)||sy.test(e),parse:e=>Qv.test(e)?Qv.parse(e):sy.test(e)?sy.parse(e):ey.parse(e),transform:e=>typeof e==`string`?e:e.hasOwnProperty(`red`)?Qv.transform(e):sy.transform(e),getAnimatableNone:e=>{let t=cy.parse(e);return t.alpha=0,cy.transform(t)}},ly=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function uy(e){return isNaN(e)&&typeof e==`string`&&(e.match(Gv)?.length||0)+(e.match(ly)?.length||0)>0}var dy=`number`,fy=`color`,py=`var`,my=`var(`,hy="${}",gy=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function _y(e){let t=e.toString(),n=[],r={color:[],number:[],var:[]},i=[],a=0;return{values:n,split:t.replace(gy,e=>(cy.test(e)?(r.color.push(a),i.push(fy),n.push(cy.parse(e))):e.startsWith(my)?(r.var.push(a),i.push(py),n.push(e)):(r.number.push(a),i.push(dy),n.push(parseFloat(e))),++a,hy)).split(hy),indexes:r,types:i}}function vy(e){return _y(e).values}function yy({split:e,types:t}){let n=e.length;return r=>{let i=``;for(let a=0;a<n;a++)if(i+=e[a],r[a]!==void 0){let e=t[a];e===dy?i+=Wv(r[a]):e===fy?i+=cy.transform(r[a]):i+=r[a]}return i}}function by(e){return yy(_y(e))}var xy=e=>typeof e==`number`?0:cy.test(e)?cy.getAnimatableNone(e):e,Sy=(e,t)=>typeof e==`number`?t?.trim().endsWith(`/`)?e:0:xy(e);function Cy(e){let t=_y(e);return yy(t)(t.values.map((e,n)=>Sy(e,t.split[n])))}var wy={test:uy,parse:vy,createTransformer:by,getAnimatableNone:Cy};function Ty(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function Ey({hue:e,saturation:t,lightness:n,alpha:r}){e/=360,t/=100,n/=100;let i=0,a=0,o=0;if(!t)i=a=o=n;else{let r=n<.5?n*(1+t):n+t-n*t,s=2*n-r;i=Ty(s,r,e+1/3),a=Ty(s,r,e),o=Ty(s,r,e-1/3)}return{red:Math.round(i*255),green:Math.round(a*255),blue:Math.round(o*255),alpha:r}}function Dy(e,t){return n=>n>0?t:e}var Oy=(e,t,n)=>e+(t-e)*n,ky=(e,t,n)=>{let r=e*e,i=n*(t*t-r)+r;return i<0?0:Math.sqrt(i)},Ay=[ey,Qv,sy],jy=e=>Ay.find(t=>t.test(e));function My(e){let t=jy(e);if(R_(!!t,`'${e}' is not an animatable color. Use the equivalent color code instead.`,`color-not-animatable`),!t)return!1;let n=t.parse(e);return t===sy&&(n=Ey(n)),n}var Ny=(e,t)=>{let n=My(e),r=My(t);if(!n||!r)return Dy(e,t);let i={...n};return e=>(i.red=ky(n.red,r.red,e),i.green=ky(n.green,r.green,e),i.blue=ky(n.blue,r.blue,e),i.alpha=Oy(n.alpha,r.alpha,e),Qv.transform(i))},Py=new Set([`none`,`hidden`]);function Fy(e,t){return Py.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function Iy(e,t){return n=>Oy(e,t,n)}function Ly(e){return typeof e==`number`?Iy:typeof e==`string`?Rv(e)?Dy:cy.test(e)?Ny:Vy:Array.isArray(e)?Ry:typeof e==`object`?cy.test(e)?Ny:zy:Dy}function Ry(e,t){let n=[...e],r=n.length,i=e.map((e,n)=>Ly(e)(e,t[n]));return e=>{for(let t=0;t<r;t++)n[t]=i[t](e);return n}}function zy(e,t){let n={...e,...t},r={};for(let i in n)e[i]!==void 0&&t[i]!==void 0&&(r[i]=Ly(e[i])(e[i],t[i]));return e=>{for(let t in r)n[t]=r[t](e);return n}}function By(e,t){let n=[],r={color:0,var:0,number:0};for(let i=0;i<t.values.length;i++){let a=t.types[i],o=e.indexes[a][r[a]];n[i]=e.values[o]??0,r[a]++}return n}var Vy=(e,t)=>{let n=wy.createTransformer(t),r=_y(e),i=_y(t);return r.indexes.var.length===i.indexes.var.length&&r.indexes.color.length===i.indexes.color.length&&r.indexes.number.length>=i.indexes.number.length?Py.has(e)&&!i.values.length||Py.has(t)&&!r.values.length?Fy(e,t):q_(Ry(By(r,i),i.values),n):(R_(!0,`Complex values '${e}' and '${t}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,`complex-values-different`),Dy(e,t))};function Hy(e,t,n){return typeof e==`number`&&typeof t==`number`&&typeof n==`number`?Oy(e,t,n):Ly(e)(e,t)}var Uy=e=>{let t=({timestamp:t})=>e(t);return{start:(e=!0)=>Q.update(t,e),stop:()=>Ov(t),now:()=>kv.isProcessing?kv.timestamp:Nv.now()}},Wy=(e,t,n=10)=>{let r=``,i=Math.max(Math.round(t/n),2);for(let t=0;t<i;t++)r+=Math.round(e(t/(i-1))*1e4)/1e4+`, `;return`linear(${r.substring(0,r.length-2)})`},Gy=2e4;function Ky(e){let t=0,n=e.next(t);for(;!n.done&&t<2e4;)t+=50,n=e.next(t);return t>=2e4?1/0:t}function qy(e,t=100,n){let r=n({...e,keyframes:[0,t]}),i=Math.min(Ky(r),Gy);return{type:`keyframes`,ease:e=>r.next(i*e).value/t,duration:Z_(i)}}var Jy={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1};function Yy(e,t){return e*Math.sqrt(1-t*t)}var Xy=12;function Zy(e,t,n){let r=n;for(let n=1;n<Xy;n++)r-=e(r)/t(r);return r}var Qy=.001;function $y({duration:e=Jy.duration,bounce:t=Jy.bounce,velocity:n=Jy.velocity,mass:r=Jy.mass}){let i,a;R_(e<=X_(Jy.maxDuration),`Spring duration must be 10 seconds or less`,`spring-duration-limit`);let o=1-t;o=I_(Jy.minDamping,Jy.maxDamping,o),e=I_(Jy.minDuration,Jy.maxDuration,Z_(e)),o<1?(i=t=>{let r=t*o,i=r*e,a=r-n,s=Yy(t,o),c=Math.exp(-i);return Qy-a/s*c},a=t=>{let r=t*o*e,a=r*n+n,s=o**2*t**2*e,c=Math.exp(-r),l=Yy(t**2,o);return(-i(t)+Qy>0?-1:1)*((a-s)*c)/l}):(i=t=>{let r=Math.exp(-t*e),i=(t-n)*e+1;return-Qy+r*i},a=t=>Math.exp(-t*e)*((n-t)*(e*e)));let s=5/e,c=Zy(i,a,s);if(e=X_(e),isNaN(c))return{stiffness:Jy.stiffness,damping:Jy.damping,duration:e};{let t=c**2*r;return{stiffness:t,damping:o*2*Math.sqrt(r*t),duration:e}}}var eb=[`duration`,`bounce`],tb=[`stiffness`,`damping`,`mass`];function nb(e,t){return t.some(t=>e[t]!==void 0)}function rb(e){let t={velocity:Jy.velocity,stiffness:Jy.stiffness,damping:Jy.damping,mass:Jy.mass,isResolvedFromDuration:!1,...e};if(!nb(e,tb)&&nb(e,eb))if(t.velocity=0,e.visualDuration){let n=e.visualDuration,r=2*Math.PI/(n*1.2),i=r*r,a=2*I_(.05,1,1-(e.bounce||0))*Math.sqrt(i);t={...t,mass:Jy.mass,stiffness:i,damping:a}}else{let n=$y({...e,velocity:0});t={...t,...n,mass:Jy.mass},t.isResolvedFromDuration=!0}return t}function ib(e=Jy.visualDuration,t=Jy.bounce){let n=typeof e==`object`?e:{visualDuration:e,keyframes:[0,1],bounce:t},{restSpeed:r,restDelta:i}=n,a=n.keyframes[0],o=n.keyframes[n.keyframes.length-1],s={done:!1,value:a},{stiffness:c,damping:l,mass:u,duration:d,velocity:f,isResolvedFromDuration:p}=rb({...n,velocity:-Z_(n.velocity||0)}),m=f||0,h=l/(2*Math.sqrt(c*u)),g=o-a,_=Z_(Math.sqrt(c/u)),v=Math.abs(g)<5;r||=v?Jy.restSpeed.granular:Jy.restSpeed.default,i||=v?Jy.restDelta.granular:Jy.restDelta.default;let y,b,x,S,ee,te;if(h<1)x=Yy(_,h),S=(m+h*_*g)/x,y=e=>o-Math.exp(-h*_*e)*(S*Math.sin(x*e)+g*Math.cos(x*e)),ee=h*_*S+g*x,te=h*_*g-S*x,b=e=>Math.exp(-h*_*e)*(ee*Math.sin(x*e)+te*Math.cos(x*e));else if(h===1){y=e=>o-Math.exp(-_*e)*(g+(m+_*g)*e);let e=m+_*g;b=t=>Math.exp(-_*t)*(_*e*t-m)}else{let e=_*Math.sqrt(h*h-1);y=t=>{let n=Math.exp(-h*_*t),r=Math.min(e*t,300);return o-n*((m+h*_*g)*Math.sinh(r)+e*g*Math.cosh(r))/e};let t=(m+h*_*g)/e,n=h*_*t-g*e,r=h*_*g-t*e;b=t=>{let i=Math.exp(-h*_*t),a=Math.min(e*t,300);return i*(n*Math.sinh(a)+r*Math.cosh(a))}}let ne={calculatedDuration:p&&d||null,velocity:e=>X_(b(e)),next:e=>{if(!p&&h<1){let t=Math.exp(-h*_*e),n=Math.sin(x*e),a=Math.cos(x*e),c=o-t*(S*n+g*a),l=X_(t*(ee*n+te*a));return s.done=Math.abs(l)<=r&&Math.abs(o-c)<=i,s.value=s.done?o:c,s}let t=y(e);if(p)s.done=e>=d;else{let n=X_(b(e));s.done=Math.abs(n)<=r&&Math.abs(o-t)<=i}return s.value=s.done?o:t,s},toString:()=>{let e=Math.min(Ky(ne),Gy),t=Wy(t=>ne.next(e*t).value,e,30);return e+`ms `+t},toTransition:()=>{}};return ne}ib.applyToOptions=e=>{let t=qy(e,100,ib);return e.ease=t.ease,e.duration=X_(t.duration),e.type=`keyframes`,e};var ab=5;function ob(e,t,n){let r=Math.max(t-ab,0);return Q_(n-e(r),t-r)}function sb({keyframes:e,velocity:t=0,power:n=.8,timeConstant:r=325,bounceDamping:i=10,bounceStiffness:a=500,modifyTarget:o,min:s,max:c,restDelta:l=.5,restSpeed:u}){let d=e[0],f={done:!1,value:d},p=e=>s!==void 0&&e<s||c!==void 0&&e>c,m=e=>s===void 0?c:c===void 0||Math.abs(s-e)<Math.abs(c-e)?s:c,h=n*t,g=d+h,_=o===void 0?g:o(g);_!==g&&(h=_-d);let v=e=>-h*Math.exp(-e/r),y=e=>_+v(e),b=e=>{let t=v(e),n=y(e);f.done=Math.abs(t)<=l,f.value=f.done?_:n},x,S,ee=e=>{p(f.value)&&(x=e,S=ib({keyframes:[f.value,m(f.value)],velocity:ob(y,e,f.value),damping:i,stiffness:a,restDelta:l,restSpeed:u}))};return ee(0),{calculatedDuration:null,next:e=>{let t=!1;return!S&&x===void 0&&(t=!0,b(e),ee(e)),x!==void 0&&e>=x?S.next(e-x):(!t&&b(e),f)}}}function cb(e,t,n){let r=[],i=n||B_.mix||Hy,a=e.length-1;for(let n=0;n<a;n++){let a=i(e[n],e[n+1]);t&&(a=q_(Array.isArray(t)?t[n]||G_:t,a)),r.push(a)}return r}function lb(e,t,{clamp:n=!0,ease:r,mixer:i}={}){let a=e.length;if(z_(a===t.length,`Both input and output ranges must be the same length`,`range-length`),a===1)return()=>t[0];if(a===2&&t[0]===t[1])return()=>t[1];let o=e[0]===e[1];e[0]>e[a-1]&&(e=[...e].reverse(),t=[...t].reverse());let s=cb(t,r,i),c=s.length,l=n=>{if(o&&n<e[0])return t[0];let r=0;if(c>1)for(;r<e.length-2&&!(n<e[r+1]);r++);let i=J_(e[r],e[r+1],n);return s[r](i)};return n?t=>l(I_(e[0],e[a-1],t)):l}function ub(e,t){let n=e[e.length-1];for(let r=1;r<=t;r++){let i=J_(0,t,r);e.push(Oy(n,1,i))}}function db(e){let t=[0];return ub(t,e.length-1),t}function fb(e,t){return e.map(e=>e*t)}function pb(e,t){return e.map(()=>t||_v).splice(0,e.length-1)}function mb({duration:e=300,keyframes:t,times:n,ease:r=`easeInOut`}){let i=vv(r)?r.map(Sv):Sv(r),a={done:!1,value:t[0]},o=lb(fb(n&&n.length===t.length?n:db(t),e),t,{ease:Array.isArray(i)?i:pb(t,i)});return{calculatedDuration:e,next:t=>(a.value=o(t),a.done=t>=e,a)}}var hb=e=>e!==null;function gb(e,{repeat:t,repeatType:n=`loop`},r,i=1){let a=e.filter(hb),o=i<0||t&&n!==`loop`&&t%2==1?0:a.length-1;return!o||r===void 0?a[o]:r}var _b={decay:sb,inertia:sb,tween:mb,keyframes:mb,spring:ib};function vb(e){typeof e.type==`string`&&(e.type=_b[e.type])}var yb=class{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,t){return this.finished.then(e,t)}},bb=e=>e/100,xb=class extends yb{constructor(e){super(),this.state=`idle`,this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.delayState={done:!1,value:void 0},this.stop=()=>{let{motionValue:e}=this.options;e&&e.updatedAt!==Nv.now()&&this.tick(Nv.now()),this.isStopped=!0,this.state!==`idle`&&(this.teardown(),this.options.onStop?.())},Pv.mainThread++,this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){let{options:e}=this;vb(e);let{type:t=mb,repeat:n=0,repeatDelay:r=0,repeatType:i,velocity:a=0}=e,{keyframes:o}=e,s=t||mb;process.env.NODE_ENV!==`production`&&s!==mb&&z_(o.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${o}`,`spring-two-frames`),s!==mb&&typeof o[0]!=`number`&&(this.mixKeyframes=q_(bb,Hy(o[0],o[1])),o=[0,100]);let c=s({...e,keyframes:o});i===`mirror`&&(this.mirroredGenerator=s({...e,keyframes:[...o].reverse(),velocity:-a})),c.calculatedDuration===null&&(c.calculatedDuration=Ky(c));let{calculatedDuration:l}=c;this.calculatedDuration=l,this.resolvedDuration=l+r,this.totalDuration=this.resolvedDuration*(n+1)-r,this.generator=c}updateTime(e){let t=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime===null?this.currentTime=t:this.currentTime=this.holdTime}tick(e,t=!1){let{generator:n,totalDuration:r,mixKeyframes:i,mirroredGenerator:a,resolvedDuration:o,calculatedDuration:s}=this;if(this.startTime===null)return n.next(0);let{delay:c=0,keyframes:l,repeat:u,repeatType:d,repeatDelay:f,type:p,onUpdate:m,finalKeyframe:h}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-r/this.speed,this.startTime)),t?this.currentTime=e:this.updateTime(e);let g=this.currentTime-c*(this.playbackSpeed>=0?1:-1),_=this.playbackSpeed>=0?g<0:g>r;this.currentTime=Math.max(g,0),this.state===`finished`&&this.holdTime===null&&(this.currentTime=r);let v=this.currentTime,y=n;if(u){let e=Math.min(this.currentTime,r)/o,t=Math.floor(e),n=e%1;!n&&e>=1&&(n=1),n===1&&t--,t=Math.min(t,u+1),t%2&&(d===`reverse`?(n=1-n,f&&(n-=f/o)):d===`mirror`&&(y=a)),v=I_(0,1,n)*o}let b;_?(this.delayState.value=l[0],b=this.delayState):b=y.next(v),i&&!_&&(b.value=i(b.value));let{done:x}=b;!_&&s!==null&&(x=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);let S=this.holdTime===null&&(this.state===`finished`||this.state===`running`&&x);return S&&p!==sb&&(b.value=gb(l,this.options,h,this.speed)),m&&m(b.value),S&&this.finish(),b}then(e,t){return this.finished.then(e,t)}get duration(){return Z_(this.calculatedDuration)}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+Z_(e)}get time(){return Z_(this.currentTime)}set time(e){e=X_(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),this.driver?this.driver.start(!1):(this.startTime=0,this.state=`paused`,this.holdTime=e,this.tick(e))}getGeneratorVelocity(){let e=this.currentTime;if(e<=0)return this.options.velocity||0;if(this.generator.velocity)return this.generator.velocity(e);let t=this.generator.next(e).value;return ob(e=>this.generator.next(e).value,e,t)}get speed(){return this.playbackSpeed}set speed(e){let t=this.playbackSpeed!==e;t&&this.driver&&this.updateTime(Nv.now()),this.playbackSpeed=e,t&&this.driver&&(this.time=Z_(this.currentTime))}play(){if(this.isStopped)return;let{driver:e=Uy,startTime:t}=this.options;this.driver||=e(e=>this.tick(e)),this.options.onPlay?.();let n=this.driver.now();this.state===`finished`?(this.updateFinished(),this.startTime=n):this.holdTime===null?this.startTime||=t??n:this.startTime=n-this.holdTime,this.state===`finished`&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state=`running`,this.driver.start()}pause(){this.state=`paused`,this.updateTime(Nv.now()),this.holdTime=this.currentTime}complete(){this.state!==`running`&&this.play(),this.state=`finished`,this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state=`finished`,this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state=`idle`,this.stopDriver(),this.startTime=this.holdTime=null,Pv.mainThread--}stopDriver(){this.driver&&=(this.driver.stop(),void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){return this.options.allowFlatten&&(this.options.type=`keyframes`,this.options.ease=`linear`,this.initAnimation()),this.driver?.stop(),e.observe(this)}};function Sb(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}var Cb=e=>e*180/Math.PI,wb=e=>Eb(Cb(Math.atan2(e[1],e[0]))),Tb={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:wb,rotateZ:wb,skewX:e=>Cb(Math.atan(e[1])),skewY:e=>Cb(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Eb=e=>(e%=360,e<0&&(e+=360),e),Db=wb,Ob=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),kb=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),Ab={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Ob,scaleY:kb,scale:e=>(Ob(e)+kb(e))/2,rotateX:e=>Eb(Cb(Math.atan2(e[6],e[5]))),rotateY:e=>Eb(Cb(Math.atan2(-e[2],e[0]))),rotateZ:Db,rotate:Db,skewX:e=>Cb(Math.atan(e[4])),skewY:e=>Cb(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function jb(e){return e.includes(`scale`)?1:0}function Mb(e,t){if(!e||e===`none`)return jb(t);let n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u),r,i;if(n)r=Ab,i=n;else{let t=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=Tb,i=t}if(!i)return jb(t);let a=r[t],o=i[1].split(`,`).map(Pb);return typeof a==`function`?a(o):o[a]}var Nb=(e,t)=>{let{transform:n=`none`}=getComputedStyle(e);return Mb(n,t)};function Pb(e){return parseFloat(e.trim())}var Fb=[`transformPerspective`,`x`,`y`,`z`,`translateX`,`translateY`,`translateZ`,`scale`,`scaleX`,`scaleY`,`rotate`,`rotateX`,`rotateY`,`rotateZ`,`skew`,`skewX`,`skewY`],Ib=new Set(Fb),Lb=e=>e===Vv||e===$,Rb=new Set([`x`,`y`,`z`]),zb=Fb.filter(e=>!Rb.has(e));function Bb(e){let t=[];return zb.forEach(n=>{let r=e.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith(`scale`)?1:0))}),t}var Vb={width:({x:e},{paddingLeft:t=`0`,paddingRight:n=`0`,boxSizing:r})=>{let i=e.max-e.min;return r===`border-box`?i:i-parseFloat(t)-parseFloat(n)},height:({y:e},{paddingTop:t=`0`,paddingBottom:n=`0`,boxSizing:r})=>{let i=e.max-e.min;return r===`border-box`?i:i-parseFloat(t)-parseFloat(n)},top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:(e,{transform:t})=>Mb(t,`x`),y:(e,{transform:t})=>Mb(t,`y`)};Vb.translateX=Vb.x,Vb.translateY=Vb.y;var Hb=new Set,Ub=!1,Wb=!1,Gb=!1;function Kb(){if(Wb){let e=Array.from(Hb).filter(e=>e.needsMeasurement),t=new Set(e.map(e=>e.element)),n=new Map;t.forEach(e=>{let t=Bb(e);t.length&&(n.set(e,t),e.render())}),e.forEach(e=>e.measureInitialState()),t.forEach(e=>{e.render();let t=n.get(e);t&&t.forEach(([t,n])=>{e.getValue(t)?.set(n)})}),e.forEach(e=>e.measureEndState()),e.forEach(e=>{e.suspendedScrollY!==void 0&&window.scrollTo(0,e.suspendedScrollY)})}Wb=!1,Ub=!1,Hb.forEach(e=>e.complete(Gb)),Hb.clear()}function qb(){Hb.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(Wb=!0)})}function Jb(){Gb=!0,qb(),Kb(),Gb=!1}var Yb=class{constructor(e,t,n,r,i,a=!1){this.state=`pending`,this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=t,this.name=n,this.motionValue=r,this.element=i,this.isAsync=a}scheduleResolve(){this.state=`scheduled`,this.isAsync?(Hb.add(this),Ub||(Ub=!0,Q.read(qb),Q.resolveKeyframes(Kb))):(this.readKeyframes(),this.complete())}readKeyframes(){let{unresolvedKeyframes:e,name:t,element:n,motionValue:r}=this;if(e[0]===null){let i=r?.get(),a=e[e.length-1];if(i!==void 0)e[0]=i;else if(n&&t){let r=n.readValue(t,a);r!=null&&(e[0]=r)}e[0]===void 0&&(e[0]=a),r&&i===void 0&&r.set(e[0])}Sb(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state=`complete`,this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Hb.delete(this)}cancel(){this.state===`scheduled`&&(Hb.delete(this),this.state=`pending`)}resume(){this.state===`pending`&&this.scheduleResolve()}},Xb=e=>e.startsWith(`--`);function Zb(e,t,n){Xb(t)?e.style.setProperty(t,n):e.style[t]=n}var Qb={};function $b(e,t){let n=W_(e);return()=>Qb[t]??n()}var ex=$b(()=>window.ScrollTimeline!==void 0,`scrollTimeline`),tx=$b(()=>{try{document.createElement(`div`).animate({opacity:0},{easing:`linear(0, 1)`})}catch{return!1}return!0},`linearEasing`),nx=([e,t,n,r])=>`cubic-bezier(${e}, ${t}, ${n}, ${r})`,rx={linear:`linear`,ease:`ease`,easeIn:`ease-in`,easeOut:`ease-out`,easeInOut:`ease-in-out`,circIn:nx([0,.65,.55,1]),circOut:nx([.55,0,1,.45]),backIn:nx([.31,.01,.66,-.59]),backOut:nx([.33,1.53,.69,.99])};function ix(e,t){if(e)return typeof e==`function`?tx()?Wy(e,t):`ease-out`:yv(e)?nx(e):Array.isArray(e)?e.map(e=>ix(e,t)||rx.easeOut):rx[e]}function ax(e,t,n,{delay:r=0,duration:i=300,repeat:a=0,repeatType:o=`loop`,ease:s=`easeOut`,times:c}={},l=void 0){let u={[t]:n};c&&(u.offset=c);let d=ix(s,i);Array.isArray(d)&&(u.easing=d),wv.value&&Pv.waapi++;let f={delay:r,duration:i,easing:Array.isArray(d)?`linear`:d,fill:`both`,iterations:a+1,direction:o===`reverse`?`alternate`:`normal`};l&&(f.pseudoElement=l);let p=e.animate(u,f);return wv.value&&p.finished.finally(()=>{Pv.waapi--}),p}function ox(e){return typeof e==`function`&&`applyToOptions`in e}function sx({type:e,...t}){return ox(e)&&tx()?e.applyToOptions(t):(t.duration??=300,t.ease??=`easeOut`,t)}var cx=class extends yb{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!e)return;let{element:t,name:n,keyframes:r,pseudoElement:i,allowFlatten:a=!1,finalKeyframe:o,onComplete:s}=e;this.isPseudoElement=!!i,this.allowFlatten=a,this.options=e,z_(typeof e.type!=`string`,`Mini animate() doesn't support "type" as a string.`,`mini-spring`);let c=sx(e);this.animation=ax(t,n,r,c,i),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){let e=gb(r,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(e),Zb(t,n,e),this.animation.cancel()}s?.(),this.notifyFinished()}}play(){this.isStopped||(this.manualStartTime=null,this.animation.play(),this.state===`finished`&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;let{state:e}=this;e===`idle`||e===`finished`||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){let e=this.options?.element;!this.isPseudoElement&&e?.isConnected&&this.animation.commitStyles?.()}get duration(){let e=this.animation.effect?.getComputedTiming?.().duration||0;return Z_(Number(e))}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+Z_(e)}get time(){return Z_(Number(this.animation.currentTime)||0)}set time(e){let t=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=X_(e),t&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime===null?this.animation.playState:`finished`}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(e){this.manualStartTime=this.animation.startTime=e}attachTimeline({timeline:e,rangeStart:t,rangeEnd:n,observe:r}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:`linear`}),this.animation.onfinish=null,e&&ex()?(this.animation.timeline=e,t&&(this.animation.rangeStart=t),n&&(this.animation.rangeEnd=n),G_):r(this)}},lx={anticipate:dv,backInOut:uv,circInOut:mv};function ux(e){return e in lx}function dx(e){typeof e.ease==`string`&&ux(e.ease)&&(e.ease=lx[e.ease])}var fx=10,px=class extends cx{constructor(e){dx(e),vb(e),super(e),e.startTime!==void 0&&e.autoplay!==!1&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){let{motionValue:t,onUpdate:n,onComplete:r,element:i,...a}=this.options;if(!t)return;if(e!==void 0){t.set(e);return}let o=new xb({...a,autoplay:!1}),s=Math.max(fx,Nv.now()-this.startTime),c=I_(0,fx,s-fx),l=o.sample(s).value,{name:u}=this.options;i&&u&&Zb(i,u,l),t.setWithVelocity(o.sample(Math.max(0,s-c)).value,l,c),o.stop()}},mx=(e,t)=>t===`zIndex`?!1:!!(typeof e==`number`||Array.isArray(e)||typeof e==`string`&&(wy.test(e)||e===`0`)&&!e.startsWith(`url(`));function hx(e){let t=e[0];if(e.length===1)return!0;for(let n=0;n<e.length;n++)if(e[n]!==t)return!0}function gx(e,t,n,r){let i=e[0];if(i===null)return!1;if(t===`display`||t===`visibility`)return!0;let a=e[e.length-1],o=mx(i,t),s=mx(a,t);return R_(o===s,`You are trying to animate ${t} from "${i}" to "${a}". "${o?a:i}" is not an animatable value.`,`value-not-animatable`),!o||!s?!1:hx(e)||(n===`spring`||ox(n))&&r}function _x(e){e.duration=0,e.type=`keyframes`}var vx=new Set([`opacity`,`clipPath`,`filter`,`transform`]),yx=/^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;function bx(e){for(let t=0;t<e.length;t++)if(typeof e[t]==`string`&&yx.test(e[t]))return!0;return!1}var xx=new Set([`color`,`backgroundColor`,`outlineColor`,`fill`,`stroke`,`borderColor`,`borderTopColor`,`borderRightColor`,`borderBottomColor`,`borderLeftColor`]),Sx=W_(()=>Object.hasOwnProperty.call(Element.prototype,`animate`));function Cx(e){let{motionValue:t,name:n,repeatDelay:r,repeatType:i,damping:a,type:o,keyframes:s}=e;if(!(t?.owner?.current instanceof HTMLElement))return!1;let{onUpdate:c,transformTemplate:l}=t.owner.getProps();return Sx()&&n&&(vx.has(n)||xx.has(n)&&bx(s))&&(n!==`transform`||!l)&&!c&&!r&&i!==`mirror`&&a!==0&&o!==`inertia`}var wx=40,Tx=class extends yb{constructor({autoplay:e=!0,delay:t=0,type:n=`keyframes`,repeat:r=0,repeatDelay:i=0,repeatType:a=`loop`,keyframes:o,name:s,motionValue:c,element:l,...u}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=Nv.now();let d={autoplay:e,delay:t,type:n,repeat:r,repeatDelay:i,repeatType:a,name:s,motionValue:c,element:l,...u};this.keyframeResolver=new(l?.KeyframeResolver||Yb)(o,(e,t,n)=>this.onKeyframesResolved(e,t,d,!n),s,c,l),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(e,t,n,r){this.keyframeResolver=void 0;let{name:i,type:a,velocity:o,delay:s,isHandoff:c,onUpdate:l}=n;this.resolvedAt=Nv.now();let u=!0;gx(e,i,a,o)||(u=!1,(B_.instantAnimations||!s)&&l?.(gb(e,n,t)),e[0]=e[e.length-1],_x(n),n.repeat=0);let d={startTime:r?this.resolvedAt&&this.resolvedAt-this.createdAt>wx?this.resolvedAt:this.createdAt:void 0,finalKeyframe:t,...n,keyframes:e},f=u&&!c&&Cx(d),p=d.motionValue?.owner?.current,m;if(f)try{m=new px({...d,element:p})}catch{m=new xb(d)}else m=new xb(d);m.finished.then(()=>{this.notifyFinished()}).catch(G_),this.pendingTimeline&&=(this.stopTimeline=m.attachTimeline(this.pendingTimeline),void 0),this._animation=m}get finished(){return this._animation?this.animation.finished:this._finished}then(e,t){return this.finished.finally(e).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),Jb()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}};function Ex(e,t,n,r=0,i=1){let a=Array.from(e).sort((e,t)=>e.sortNodePosition(t)).indexOf(t),o=e.size,s=(o-1)*r;return typeof n==`function`?n(a,o):i===1?a*r:s-a*r}var Dx=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Ox(e){let t=Dx.exec(e);if(!t)return[,];let[,n,r,i]=t;return[`--${n??r}`,i]}var kx=4;function Ax(e,t,n=1){z_(n<=kx,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,`max-css-var-depth`);let[r,i]=Ox(e);if(!r)return;let a=window.getComputedStyle(t).getPropertyValue(r);if(a){let e=a.trim();return V_(e)?parseFloat(e):e}return Rv(i)?Ax(i,t,n+1):i}var jx={type:`spring`,stiffness:500,damping:25,restSpeed:10},Mx=e=>({type:`spring`,stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),Nx={type:`keyframes`,duration:.8},Px={type:`keyframes`,ease:[.25,.1,.35,1],duration:.3},Fx=(e,{keyframes:t})=>t.length>2?Nx:Ib.has(e)?e.startsWith(`scale`)?Mx(t[1]):jx:Px;function Ix(e,t){if(e?.inherit&&t){let{inherit:n,...r}=e;return{...t,...r}}return e}function Lx(e,t){let n=e?.[t]??e?.default??e;return n===e?n:Ix(n,e)}var Rx=new Set([`when`,`delay`,`delayChildren`,`staggerChildren`,`staggerDirection`,`repeat`,`repeatType`,`repeatDelay`,`from`,`elapsed`]);function zx(e){for(let t in e)if(!Rx.has(t))return!0;return!1}var Bx=(e,t,n,r={},i,a)=>o=>{let s=Lx(r,e)||{},c=s.delay||r.delay||0,{elapsed:l=0}=r;l-=X_(c);let u={keyframes:Array.isArray(n)?n:[null,n],ease:`easeOut`,velocity:t.getVelocity(),...s,delay:-l,onUpdate:e=>{t.set(e),s.onUpdate&&s.onUpdate(e)},onComplete:()=>{o(),s.onComplete&&s.onComplete()},name:e,motionValue:t,element:a?void 0:i};zx(s)||Object.assign(u,Fx(e,u)),u.duration&&=X_(u.duration),u.repeatDelay&&=X_(u.repeatDelay),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(_x(u),u.delay===0&&(d=!0)),(B_.instantAnimations||B_.skipAnimations||i?.shouldSkipAnimations)&&(d=!0,_x(u),u.delay=0),u.allowFlatten=!s.type&&!s.ease,d&&!a&&t.get()!==void 0){let e=gb(u.keyframes,s);if(e!==void 0){Q.update(()=>{u.onUpdate(e),u.onComplete()});return}}return s.isSync?new xb(u):new Tx(u)};function Vx(e){let t=[{},{}];return e?.values.forEach((e,n)=>{t[0][n]=e.get(),t[1][n]=e.getVelocity()}),t}function Hx(e,t,n,r){if(typeof t==`function`){let[i,a]=Vx(r);t=t(n===void 0?e.custom:n,i,a)}if(typeof t==`string`&&(t=e.variants&&e.variants[t]),typeof t==`function`){let[i,a]=Vx(r);t=t(n===void 0?e.custom:n,i,a)}return t}function Ux(e,t,n){let r=e.getProps();return Hx(r,t,n===void 0?r.custom:n,e)}var Wx=new Set([`width`,`height`,`top`,`left`,`right`,`bottom`,...Fb]),Gx=30,Kx=e=>!isNaN(parseFloat(e)),qx={current:void 0},Jx=class{constructor(e,t={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=e=>{let t=Nv.now();if(this.updatedAt!==t&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(e),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(let e of this.dependents)e.dirty()},this.hasAnimated=!1,this.setCurrent(e),this.owner=t.owner}setCurrent(e){this.current=e,this.updatedAt=Nv.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=Kx(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return process.env.NODE_ENV!==`production`&&ev(!1,`value.onChange(callback) is deprecated. Switch to value.on("change", callback).`),this.on(`change`,e)}on(e,t){this.events[e]||(this.events[e]=new Y_);let n=this.events[e].add(t);return e===`change`?()=>{n(),Q.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(let e in this.events)this.events[e].clear()}attach(e,t){this.passiveEffect=e,this.stopPassiveEffect=t}set(e){this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e)}setWithVelocity(e,t,n){this.set(t),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-n}jump(e,t=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,t&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(e){this.dependents||=new Set,this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return qx.current&&qx.current.push(this),this.current}getPrevious(){return this.prev}getVelocity(){let e=Nv.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Gx)return 0;let t=Math.min(this.updatedAt-this.prevUpdatedAt,Gx);return Q_(parseFloat(this.current)-parseFloat(this.prevFrameValue),t)}start(e){return this.stop(),new Promise(t=>{this.hasAnimated=!0,this.animation=e(t),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}};function Yx(e,t){return new Jx(e,t)}var Xx=e=>Array.isArray(e);function Zx(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,Yx(n))}function Qx(e){return Xx(e)?e[e.length-1]||0:e}function $x(e,t){let{transitionEnd:n={},transition:r={},...i}=Ux(e,t)||{};i={...i,...n};for(let t in i)Zx(e,t,Qx(i[t]))}var eS=e=>!!(e&&e.getVelocity);function tS(e){return!!(eS(e)&&e.add)}function nS(e,t){let n=e.getValue(`willChange`);if(tS(n))return n.add(t);if(!n&&B_.WillChange){let n=new B_.WillChange(`auto`);e.addValue(`willChange`,n),n.add(t)}}function rS(e){return e.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}var iS=`data-`+rS(`framerAppearId`);function aS(e){return e.props[iS]}function oS({protectedKeys:e,needsAnimating:t},n){let r=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function sS(e,t,{delay:n=0,transitionOverride:r,type:i}={}){let{transition:a,transitionEnd:o,...s}=t,c=e.getDefaultTransition();a=a?Ix(a,c):c;let l=a?.reduceMotion;r&&(a=r);let u=[],d=i&&e.animationState&&e.animationState.getState()[i];for(let t in s){let r=e.getValue(t,e.latestValues[t]??null),i=s[t];if(i===void 0||d&&oS(d,t))continue;let o={delay:n,...Lx(a||{},t)},c=r.get();if(c!==void 0&&!r.isAnimating()&&!Array.isArray(i)&&i===c&&!o.velocity){Q.update(()=>r.set(i));continue}let f=!1;if(window.MotionHandoffAnimation){let n=aS(e);if(n){let e=window.MotionHandoffAnimation(n,t,Q);e!==null&&(o.startTime=e,f=!0)}}nS(e,t);let p=l??e.shouldReduceMotion;r.start(Bx(t,r,i,p&&Wx.has(t)?{type:!1}:o,e,f));let m=r.animation;m&&u.push(m)}if(o){let t=()=>Q.update(()=>{o&&$x(e,o)});u.length?Promise.all(u).then(t):t()}return u}function cS(e,t,n={}){let r=Ux(e,t,n.type===`exit`?e.presenceContext?.custom:void 0),{transition:i=e.getDefaultTransition()||{}}=r||{};n.transitionOverride&&(i=n.transitionOverride);let a=r?()=>Promise.all(sS(e,r,n)):()=>Promise.resolve(),o=e.variantChildren&&e.variantChildren.size?(r=0)=>{let{delayChildren:a=0,staggerChildren:o,staggerDirection:s}=i;return lS(e,t,r,a,o,s,n)}:()=>Promise.resolve(),{when:s}=i;if(s){let[e,t]=s===`beforeChildren`?[a,o]:[o,a];return e().then(()=>t())}else return Promise.all([a(),o(n.delay)])}function lS(e,t,n=0,r=0,i=0,a=1,o){let s=[];for(let c of e.variantChildren)c.notify(`AnimationStart`,t),s.push(cS(c,t,{...o,delay:n+(typeof r==`function`?0:r)+Ex(e.variantChildren,c,r,i,a)}).then(()=>c.notify(`AnimationComplete`,t)));return Promise.all(s)}function uS(e,t,n={}){e.notify(`AnimationStart`,t);let r;if(Array.isArray(t)){let i=t.map(t=>cS(e,t,n));r=Promise.all(i)}else if(typeof t==`string`)r=cS(e,t,n);else{let i=typeof t==`function`?Ux(e,t,n.custom):t;r=Promise.all(sS(e,i,n))}return r.then(()=>{e.notify(`AnimationComplete`,t)})}var dS={test:e=>e===`auto`,parse:e=>e},fS=e=>t=>t.test(e),pS=[Vv,$,ry,ny,ay,iy,dS],mS=e=>pS.find(fS(e));function hS(e){return typeof e==`number`?e===0:e===null?!0:e===`none`||e===`0`||U_(e)}var gS=new Set([`brightness`,`contrast`,`saturate`,`opacity`]);function _S(e){let[t,n]=e.slice(0,-1).split(`(`);if(t===`drop-shadow`)return e;let[r]=n.match(Gv)||[];if(!r)return e;let i=n.replace(r,``),a=gS.has(t)?1:0;return r!==n&&(a*=100),t+`(`+a+i+`)`}var vS=/\b([a-z-]*)\(.*?\)/gu,yS={...wy,getAnimatableNone:e=>{let t=e.match(vS);return t?t.map(_S).join(` `):e}},bS={...wy,getAnimatableNone:e=>{let t=wy.parse(e);return wy.createTransformer(e)(t.map(e=>typeof e==`number`?0:typeof e==`object`?{...e,alpha:1}:e))}},xS={...Vv,transform:Math.round},SS={borderWidth:$,borderTopWidth:$,borderRightWidth:$,borderBottomWidth:$,borderLeftWidth:$,borderRadius:$,borderTopLeftRadius:$,borderTopRightRadius:$,borderBottomRightRadius:$,borderBottomLeftRadius:$,width:$,maxWidth:$,height:$,maxHeight:$,top:$,right:$,bottom:$,left:$,inset:$,insetBlock:$,insetBlockStart:$,insetBlockEnd:$,insetInline:$,insetInlineStart:$,insetInlineEnd:$,padding:$,paddingTop:$,paddingRight:$,paddingBottom:$,paddingLeft:$,paddingBlock:$,paddingBlockStart:$,paddingBlockEnd:$,paddingInline:$,paddingInlineStart:$,paddingInlineEnd:$,margin:$,marginTop:$,marginRight:$,marginBottom:$,marginLeft:$,marginBlock:$,marginBlockStart:$,marginBlockEnd:$,marginInline:$,marginInlineStart:$,marginInlineEnd:$,fontSize:$,backgroundPositionX:$,backgroundPositionY:$,rotate:ny,rotateX:ny,rotateY:ny,rotateZ:ny,scale:Uv,scaleX:Uv,scaleY:Uv,scaleZ:Uv,skew:ny,skewX:ny,skewY:ny,distance:$,translateX:$,translateY:$,translateZ:$,x:$,y:$,z:$,perspective:$,transformPerspective:$,opacity:Hv,originX:oy,originY:oy,originZ:$,zIndex:xS,fillOpacity:Hv,strokeOpacity:Hv,numOctaves:xS},CS={...SS,color:cy,backgroundColor:cy,outlineColor:cy,fill:cy,stroke:cy,borderColor:cy,borderTopColor:cy,borderRightColor:cy,borderBottomColor:cy,borderLeftColor:cy,filter:yS,WebkitFilter:yS,mask:bS,WebkitMask:bS},wS=e=>CS[e],TS=new Set([yS,bS]);function ES(e,t){let n=wS(e);return TS.has(n)||(n=wy),n.getAnimatableNone?n.getAnimatableNone(t):void 0}var DS=new Set([`auto`,`none`,`0`]);function OS(e,t,n){let r=0,i;for(;r<e.length&&!i;){let t=e[r];typeof t==`string`&&!DS.has(t)&&_y(t).values.length&&(i=e[r]),r++}if(i&&n)for(let r of t)e[r]=ES(n,i)}var kS=class extends Yb{constructor(e,t,n,r,i){super(e,t,n,r,i,!0)}readKeyframes(){let{unresolvedKeyframes:e,element:t,name:n}=this;if(!t||!t.current)return;super.readKeyframes();for(let n=0;n<e.length;n++){let r=e[n];if(typeof r==`string`&&(r=r.trim(),Rv(r))){let i=Ax(r,t.current);i!==void 0&&(e[n]=i),n===e.length-1&&(this.finalKeyframe=r)}}if(this.resolveNoneKeyframes(),!Wx.has(n)||e.length!==2)return;let[r,i]=e,a=mS(r),o=mS(i);if(Bv(r)!==Bv(i)&&Vb[n]){this.needsMeasurement=!0;return}if(a!==o)if(Lb(a)&&Lb(o))for(let t=0;t<e.length;t++){let n=e[t];typeof n==`string`&&(e[t]=parseFloat(n))}else Vb[n]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){let{unresolvedKeyframes:e,name:t}=this,n=[];for(let t=0;t<e.length;t++)(e[t]===null||hS(e[t]))&&n.push(t);n.length&&OS(e,n,t)}measureInitialState(){let{element:e,unresolvedKeyframes:t,name:n}=this;if(!e||!e.current)return;n===`height`&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Vb[n](e.measureViewportBox(),window.getComputedStyle(e.current)),t[0]=this.measuredOrigin;let r=t[t.length-1];r!==void 0&&e.getValue(n,r).jump(r,!1)}measureEndState(){let{element:e,name:t,unresolvedKeyframes:n}=this;if(!e||!e.current)return;let r=e.getValue(t);r&&r.jump(this.measuredOrigin,!1);let i=n.length-1,a=n[i];n[i]=Vb[t](e.measureViewportBox(),window.getComputedStyle(e.current)),a!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=a),this.removedTransforms?.length&&this.removedTransforms.forEach(([t,n])=>{e.getValue(t).set(n)}),this.resolveNoneKeyframes()}};function AS(e,t,n){if(e==null)return[];if(e instanceof EventTarget)return[e];if(typeof e==`string`){let r=document;t&&(r=t.current);let i=n?.[e]??r.querySelectorAll(e);return i?Array.from(i):[]}return Array.from(e).filter(e=>e!=null)}var jS=(e,t)=>t&&typeof e==`number`?t.transform(e):e;function MS(e){return H_(e)&&`offsetHeight`in e&&!(`ownerSVGElement`in e)}var{schedule:NS,cancel:PS}=Dv(queueMicrotask,!1),FS={x:!1,y:!1};function IS(){return FS.x||FS.y}function LS(e){return e===`x`||e===`y`?FS[e]?null:(FS[e]=!0,()=>{FS[e]=!1}):FS.x||FS.y?null:(FS.x=FS.y=!0,()=>{FS.x=FS.y=!1})}function RS(e,t){let n=AS(e),r=new AbortController;return[n,{passive:!0,...t,signal:r.signal},()=>r.abort()]}function zS(e){return!(e.pointerType===`touch`||IS())}function BS(e,t,n={}){let[r,i,a]=RS(e,n);return r.forEach(e=>{let n=!1,r=!1,a,o=()=>{e.removeEventListener(`pointerleave`,u)},s=e=>{a&&=(a(e),void 0),o()},c=e=>{n=!1,window.removeEventListener(`pointerup`,c),window.removeEventListener(`pointercancel`,c),r&&(r=!1,s(e))},l=()=>{n=!0,window.addEventListener(`pointerup`,c,i),window.addEventListener(`pointercancel`,c,i)},u=e=>{if(e.pointerType!==`touch`){if(n){r=!0;return}s(e)}};e.addEventListener(`pointerenter`,n=>{if(!zS(n))return;r=!1;let o=t(e,n);typeof o==`function`&&(a=o,e.addEventListener(`pointerleave`,u,i))},i),e.addEventListener(`pointerdown`,l,i)}),a}var VS=(e,t)=>t?e===t?!0:VS(e,t.parentElement):!1,HS=e=>e.pointerType===`mouse`?typeof e.button!=`number`||e.button<=0:e.isPrimary!==!1,US=new Set([`BUTTON`,`INPUT`,`SELECT`,`TEXTAREA`,`A`]);function WS(e){return US.has(e.tagName)||e.isContentEditable===!0}var GS=new Set([`INPUT`,`SELECT`,`TEXTAREA`]);function KS(e){return GS.has(e.tagName)||e.isContentEditable===!0}var qS=new WeakSet;function JS(e){return t=>{t.key===`Enter`&&e(t)}}function YS(e,t){e.dispatchEvent(new PointerEvent(`pointer`+t,{isPrimary:!0,bubbles:!0}))}var XS=(e,t)=>{let n=e.currentTarget;if(!n)return;let r=JS(()=>{if(qS.has(n))return;YS(n,`down`);let e=JS(()=>{YS(n,`up`)});n.addEventListener(`keyup`,e,t),n.addEventListener(`blur`,()=>YS(n,`cancel`),t)});n.addEventListener(`keydown`,r,t),n.addEventListener(`blur`,()=>n.removeEventListener(`keydown`,r),t)};function ZS(e){return HS(e)&&!IS()}var QS=new WeakSet;function $S(e,t,n={}){let[r,i,a]=RS(e,n),o=e=>{let r=e.currentTarget;if(!ZS(e)||QS.has(e))return;qS.add(r),n.stopPropagation&&QS.add(e);let a=t(r,e),o=(e,t)=>{window.removeEventListener(`pointerup`,s),window.removeEventListener(`pointercancel`,c),qS.has(r)&&qS.delete(r),ZS(e)&&typeof a==`function`&&a(e,{success:t})},s=e=>{o(e,r===window||r===document||n.useGlobalTarget||VS(r,e.target))},c=e=>{o(e,!1)};window.addEventListener(`pointerup`,s,i),window.addEventListener(`pointercancel`,c,i)};return r.forEach(e=>{(n.useGlobalTarget?window:e).addEventListener(`pointerdown`,o,i),MS(e)&&(e.addEventListener(`focus`,e=>XS(e,i)),!WS(e)&&!e.hasAttribute(`tabindex`)&&(e.tabIndex=0))}),a}function eC(e){return H_(e)&&`ownerSVGElement`in e}var tC=new WeakMap,nC,rC=(e,t,n)=>(r,i)=>i&&i[0]?i[0][e+`Size`]:eC(r)&&`getBBox`in r?r.getBBox()[t]:r[n],iC=rC(`inline`,`width`,`offsetWidth`),aC=rC(`block`,`height`,`offsetHeight`);function oC({target:e,borderBoxSize:t}){tC.get(e)?.forEach(n=>{n(e,{get width(){return iC(e,t)},get height(){return aC(e,t)}})})}function sC(e){e.forEach(oC)}function cC(){typeof ResizeObserver>`u`||(nC=new ResizeObserver(sC))}function lC(e,t){nC||cC();let n=AS(e);return n.forEach(e=>{let n=tC.get(e);n||(n=new Set,tC.set(e,n)),n.add(t),nC?.observe(e)}),()=>{n.forEach(e=>{let n=tC.get(e);n?.delete(t),n?.size||nC?.unobserve(e)})}}var uC=new Set,dC;function fC(){dC=()=>{let e={get width(){return window.innerWidth},get height(){return window.innerHeight}};uC.forEach(t=>t(e))},window.addEventListener(`resize`,dC)}function pC(e){return uC.add(e),dC||fC(),()=>{uC.delete(e),!uC.size&&typeof dC==`function`&&(window.removeEventListener(`resize`,dC),dC=void 0)}}function mC(e,t){return typeof e==`function`?pC(e):lC(e,t)}function hC(e){return eC(e)&&e.tagName===`svg`}var gC=[...pS,cy,wy],_C=e=>gC.find(fS(e)),vC=()=>({translate:0,scale:1,origin:0,originPoint:0}),yC=()=>({x:vC(),y:vC()}),bC=()=>({min:0,max:0}),xC=()=>({x:bC(),y:bC()}),SC=new WeakMap;function CC(e){return typeof e==`object`&&!!e&&typeof e.start==`function`}function wC(e){return typeof e==`string`||Array.isArray(e)}var TC=[`animate`,`whileInView`,`whileFocus`,`whileHover`,`whileTap`,`whileDrag`,`exit`],EC=[`initial`,...TC];function DC(e){return CC(e.animate)||EC.some(t=>wC(e[t]))}function OC(e){return!!(DC(e)||e.variants)}function kC(e,t,n){for(let r in t){let i=t[r],a=n[r];if(eS(i))e.addValue(r,i);else if(eS(a))e.addValue(r,Yx(i,{owner:e}));else if(a!==i)if(e.hasValue(r)){let t=e.getValue(r);t.liveStyle===!0?t.jump(i):t.hasAnimated||t.set(i)}else{let t=e.getStaticValue(r);e.addValue(r,Yx(t===void 0?i:t,{owner:e}))}}for(let r in n)t[r]===void 0&&e.removeValue(r);return t}var AC={current:null},jC={current:!1},MC=typeof window<`u`;function NC(){if(jC.current=!0,MC)if(window.matchMedia){let e=window.matchMedia(`(prefers-reduced-motion)`),t=()=>AC.current=e.matches;e.addEventListener(`change`,t),t()}else AC.current=!1}var PC=[`AnimationStart`,`AnimationComplete`,`Update`,`BeforeLayoutMeasure`,`LayoutMeasure`,`LayoutAnimationStart`,`LayoutAnimationComplete`],FC={};function IC(e){FC=e}function LC(){return FC}var RC=class{scrapeMotionValuesFromProps(e,t,n){return{}}constructor({parent:e,props:t,presenceContext:n,reducedMotionConfig:r,skipAnimations:i,blockInitialAnimation:a,visualState:o},s={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.shouldSkipAnimations=!1,this.values=new Map,this.KeyframeResolver=Yb,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify(`Update`,this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{let e=Nv.now();this.renderScheduledAt<e&&(this.renderScheduledAt=e,Q.render(this.render,!1,!0))};let{latestValues:c,renderState:l}=o;this.latestValues=c,this.baseTarget={...c},this.initialValues=t.initial?{...c}:{},this.renderState=l,this.parent=e,this.props=t,this.presenceContext=n,this.depth=e?e.depth+1:0,this.reducedMotionConfig=r,this.skipAnimationsConfig=i,this.options=s,this.blockInitialAnimation=!!a,this.isControllingVariants=DC(t),this.isVariantNode=OC(t),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);let{willChange:u,...d}=this.scrapeMotionValuesFromProps(t,{},this);for(let e in d){let t=d[e];c[e]!==void 0&&eS(t)&&t.set(c[e])}}mount(e){if(this.hasBeenMounted)for(let e in this.initialValues)this.values.get(e)?.jump(this.initialValues[e]),this.latestValues[e]=this.initialValues[e];this.current=e,SC.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((e,t)=>this.bindToMotionValue(t,e)),this.reducedMotionConfig===`never`?this.shouldReduceMotion=!1:this.reducedMotionConfig===`always`?this.shouldReduceMotion=!0:(jC.current||NC(),this.shouldReduceMotion=AC.current),process.env.NODE_ENV!==`production`&&ev(this.shouldReduceMotion!==!0,`You have Reduced Motion enabled on your device. Animations may not appear as expected.`,`reduced-motion-disabled`),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,this.parent?.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){this.projection&&this.projection.unmount(),Ov(this.notifyUpdate),Ov(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(let e in this.events)this.events[e].clear();for(let e in this.features){let t=this.features[e];t&&(t.unmount(),t.isMounted=!1)}this.current=null}addChild(e){this.children.add(e),this.enteringChildren??=new Set,this.enteringChildren.add(e)}removeChild(e){this.children.delete(e),this.enteringChildren&&this.enteringChildren.delete(e)}bindToMotionValue(e,t){if(this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)(),t.accelerate&&vx.has(e)&&this.current instanceof HTMLElement){let{factory:n,keyframes:r,times:i,ease:a,duration:o}=t.accelerate,s=new cx({element:this.current,name:e,keyframes:r,times:i,ease:a,duration:X_(o)}),c=n(s);this.valueSubscriptions.set(e,()=>{c(),s.cancel()});return}let n=Ib.has(e);n&&this.onBindTransform&&this.onBindTransform();let r=t.on(`change`,t=>{this.latestValues[e]=t,this.props.onUpdate&&Q.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()}),i;typeof window<`u`&&window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,e,t)),this.valueSubscriptions.set(e,()=>{r(),i&&i(),t.owner&&t.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e=`animation`;for(e in FC){let t=FC[e];if(!t)continue;let{isEnabled:n,Feature:r}=t;if(!this.features[e]&&r&&n(this.props)&&(this.features[e]=new r(this)),this.features[e]){let t=this.features[e];t.isMounted?t.update():(t.mount(),t.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):xC()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,t){this.latestValues[e]=t}update(e,t){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=t;for(let t=0;t<PC.length;t++){let n=PC[t];this.propEventSubscriptions[n]&&(this.propEventSubscriptions[n](),delete this.propEventSubscriptions[n]);let r=e[`on`+n];r&&(this.propEventSubscriptions[n]=this.on(n,r))}this.prevMotionValues=kC(this,this.scrapeMotionValuesFromProps(e,this.prevProps||{},this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(e){return this.props.variants?this.props.variants[e]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(e){let t=this.getClosestVariantNode();if(t)return t.variantChildren&&t.variantChildren.add(e),()=>t.variantChildren.delete(e)}addValue(e,t){let n=this.values.get(e);t!==n&&(n&&this.removeValue(e),this.bindToMotionValue(e,t),this.values.set(e,t),this.latestValues[e]=t.get())}removeValue(e){this.values.delete(e);let t=this.valueSubscriptions.get(e);t&&(t(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,t){if(this.props.values&&this.props.values[e])return this.props.values[e];let n=this.values.get(e);return n===void 0&&t!==void 0&&(n=Yx(t===null?void 0:t,{owner:this}),this.addValue(e,n)),n}readValue(e,t){let n=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return n!=null&&(typeof n==`string`&&(V_(n)||U_(n))?n=parseFloat(n):!_C(n)&&wy.test(t)&&(n=ES(e,t)),this.setBaseTarget(e,eS(n)?n.get():n)),eS(n)?n.get():n}setBaseTarget(e,t){this.baseTarget[e]=t}getBaseTarget(e){let{initial:t}=this.props,n;if(typeof t==`string`||typeof t==`object`){let r=Hx(this.props,t,this.presenceContext?.custom);r&&(n=r[e])}if(t&&n!==void 0)return n;let r=this.getBaseTargetFromProps(this.props,e);return r!==void 0&&!eS(r)?r:this.initialValues[e]!==void 0&&n===void 0?void 0:this.baseTarget[e]}on(e,t){return this.events[e]||(this.events[e]=new Y_),this.events[e].add(t)}notify(e,...t){this.events[e]&&this.events[e].notify(...t)}scheduleRenderMicrotask(){NS.render(this.render)}},zC=class extends RC{constructor(){super(...arguments),this.KeyframeResolver=kS}sortInstanceNodePosition(e,t){return e.compareDocumentPosition(t)&2?1:-1}getBaseTargetFromProps(e,t){let n=e.style;return n?n[t]:void 0}removeValueFromRenderState(e,{vars:t,style:n}){delete t[e],delete n[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);let{children:e}=this.props;eS(e)&&(this.childSubscription=e.on(`change`,e=>{this.current&&(this.current.textContent=`${e}`)}))}},BC=class{constructor(e){this.isMounted=!1,this.node=e}update(){}};function VC({top:e,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:e,max:r}}}function HC({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function UC(e,t){if(!t)return e;let n=t({x:e.left,y:e.top}),r=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:r.y,right:r.x}}function WC(e){return e===void 0||e===1}function GC({scale:e,scaleX:t,scaleY:n}){return!WC(e)||!WC(t)||!WC(n)}function KC(e){return GC(e)||qC(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function qC(e){return JC(e.x)||JC(e.y)}function JC(e){return e&&e!==`0%`}function YC(e,t,n){return n+t*(e-n)}function XC(e,t,n,r,i){return i!==void 0&&(e=YC(e,i,r)),YC(e,n,r)+t}function ZC(e,t=0,n=1,r,i){e.min=XC(e.min,t,n,r,i),e.max=XC(e.max,t,n,r,i)}function QC(e,{x:t,y:n}){ZC(e.x,t.translate,t.scale,t.originPoint),ZC(e.y,n.translate,n.scale,n.originPoint)}var $C=.999999999999,ew=1.0000000000001;function tw(e,t,n,r=!1){let i=n.length;if(!i)return;t.x=t.y=1;let a,o;for(let s=0;s<i;s++){a=n[s],o=a.projectionDelta;let{visualElement:i}=a.options;i&&i.props.style&&i.props.style.display===`contents`||(r&&a.options.layoutScroll&&a.scroll&&a!==a.root&&(nw(e.x,-a.scroll.offset.x),nw(e.y,-a.scroll.offset.y)),o&&(t.x*=o.x.scale,t.y*=o.y.scale,QC(e,o)),r&&KC(a.latestValues)&&aw(e,a.latestValues,a.layout?.layoutBox))}t.x<ew&&t.x>$C&&(t.x=1),t.y<ew&&t.y>$C&&(t.y=1)}function nw(e,t){e.min+=t,e.max+=t}function rw(e,t,n,r,i=.5){ZC(e,t,n,Oy(e.min,e.max,i),r)}function iw(e,t){return typeof e==`string`?parseFloat(e)/100*(t.max-t.min):e}function aw(e,t,n){let r=n??e;rw(e.x,iw(t.x,r.x),t.scaleX,t.scale,t.originX),rw(e.y,iw(t.y,r.y),t.scaleY,t.scale,t.originY)}function ow(e,t){return VC(UC(e.getBoundingClientRect(),t))}function sw(e,t,n){let r=ow(e,n),{scroll:i}=t;return i&&(nw(r.x,i.offset.x),nw(r.y,i.offset.y)),r}var cw={x:`translateX`,y:`translateY`,z:`translateZ`,transformPerspective:`perspective`},lw=Fb.length;function uw(e,t,n){let r=``,i=!0;for(let a=0;a<lw;a++){let o=Fb[a],s=e[o];if(s===void 0)continue;let c=!0;if(typeof s==`number`)c=s===(o.startsWith(`scale`)?1:0);else{let e=parseFloat(s);c=o.startsWith(`scale`)?e===1:e===0}if(!c||n){let e=jS(s,SS[o]);if(!c){i=!1;let t=cw[o]||o;r+=`${t}(${e}) `}n&&(t[o]=e)}}return r=r.trim(),n?r=n(t,i?``:r):i&&(r=`none`),r}function dw(e,t,n){let{style:r,vars:i,transformOrigin:a}=e,o=!1,s=!1;for(let e in t){let n=t[e];if(Ib.has(e)){o=!0;continue}else if(Iv(e)){i[e]=n;continue}else{let t=jS(n,SS[e]);e.startsWith(`origin`)?(s=!0,a[e]=t):r[e]=t}}if(t.transform||(o||n?r.transform=uw(t,e.transform,n):r.transform&&=`none`),s){let{originX:e=`50%`,originY:t=`50%`,originZ:n=0}=a;r.transformOrigin=`${e} ${t} ${n}`}}function fw(e,{style:t,vars:n},r,i){let a=e.style,o;for(o in t)a[o]=t[o];for(o in i?.applyProjectionStyles(a,r),n)a.setProperty(o,n[o])}function pw(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}var mw={correct:(e,t)=>{if(!t.target)return e;if(typeof e==`string`)if($.test(e))e=parseFloat(e);else return e;return`${pw(e,t.target.x)}% ${pw(e,t.target.y)}%`}},hw={correct:(e,{treeScale:t,projectionDelta:n})=>{let r=e,i=wy.parse(e);if(i.length>5)return r;let a=wy.createTransformer(e),o=typeof i[0]==`number`?0:1,s=n.x.scale*t.x,c=n.y.scale*t.y;i[0+o]/=s,i[1+o]/=c;let l=Oy(s,c,.5);return typeof i[2+o]==`number`&&(i[2+o]/=l),typeof i[3+o]==`number`&&(i[3+o]/=l),a(i)}},gw={borderRadius:{...mw,applyTo:[`borderTopLeftRadius`,`borderTopRightRadius`,`borderBottomLeftRadius`,`borderBottomRightRadius`]},borderTopLeftRadius:mw,borderTopRightRadius:mw,borderBottomLeftRadius:mw,borderBottomRightRadius:mw,boxShadow:hw};function _w(e,{layout:t,layoutId:n}){return Ib.has(e)||e.startsWith(`origin`)||(t||n!==void 0)&&(!!gw[e]||e===`opacity`)}function vw(e,t,n){let r=e.style,i=t?.style,a={};if(!r)return a;for(let t in r)(eS(r[t])||i&&eS(i[t])||_w(t,e)||n?.getValue(t)?.liveStyle!==void 0)&&(a[t]=r[t]);return a}function yw(e){return window.getComputedStyle(e)}var bw=class extends zC{constructor(){super(...arguments),this.type=`html`,this.renderInstance=fw}readValueFromInstance(e,t){if(Ib.has(t))return this.projection?.isProjecting?jb(t):Nb(e,t);{let n=yw(e),r=(Iv(t)?n.getPropertyValue(t):n[t])||0;return typeof r==`string`?r.trim():r}}measureInstanceViewportBox(e,{transformPagePoint:t}){return ow(e,t)}build(e,t,n){dw(e,t,n.transformTemplate)}scrapeMotionValuesFromProps(e,t,n){return vw(e,t,n)}},xw={offset:`stroke-dashoffset`,array:`stroke-dasharray`},Sw={offset:`strokeDashoffset`,array:`strokeDasharray`};function Cw(e,t,n=1,r=0,i=!0){e.pathLength=1;let a=i?xw:Sw;e[a.offset]=`${-r}`,e[a.array]=`${t} ${n}`}var ww=[`offsetDistance`,`offsetPath`,`offsetRotate`,`offsetAnchor`];function Tw(e,{attrX:t,attrY:n,attrScale:r,pathLength:i,pathSpacing:a=1,pathOffset:o=0,...s},c,l,u){if(dw(e,s,l),c){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};let{attrs:d,style:f}=e;d.transform&&(f.transform=d.transform,delete d.transform),(f.transform||d.transformOrigin)&&(f.transformOrigin=d.transformOrigin??`50% 50%`,delete d.transformOrigin),f.transform&&(f.transformBox=u?.transformBox??`fill-box`,delete d.transformBox);for(let e of ww)d[e]!==void 0&&(f[e]=d[e],delete d[e]);t!==void 0&&(d.x=t),n!==void 0&&(d.y=n),r!==void 0&&(d.scale=r),i!==void 0&&Cw(d,i,a,o,!1)}var Ew=new Set([`baseFrequency`,`diffuseConstant`,`kernelMatrix`,`kernelUnitLength`,`keySplines`,`keyTimes`,`limitingConeAngle`,`markerHeight`,`markerWidth`,`numOctaves`,`targetX`,`targetY`,`surfaceScale`,`specularConstant`,`specularExponent`,`stdDeviation`,`tableValues`,`viewBox`,`gradientTransform`,`pathLength`,`startOffset`,`textLength`,`lengthAdjust`]),Dw=e=>typeof e==`string`&&e.toLowerCase()===`svg`;function Ow(e,t,n,r){fw(e,t,void 0,r);for(let n in t.attrs)e.setAttribute(Ew.has(n)?n:rS(n),t.attrs[n])}function kw(e,t,n){let r=vw(e,t,n);for(let n in e)if(eS(e[n])||eS(t[n])){let t=Fb.indexOf(n)===-1?n:`attr`+n.charAt(0).toUpperCase()+n.substring(1);r[t]=e[n]}return r}var Aw=class extends zC{constructor(){super(...arguments),this.type=`svg`,this.isSVGTag=!1,this.measureInstanceViewportBox=xC}getBaseTargetFromProps(e,t){return e[t]}readValueFromInstance(e,t){if(Ib.has(t)){let e=wS(t);return e&&e.default||0}return t=Ew.has(t)?t:rS(t),e.getAttribute(t)}scrapeMotionValuesFromProps(e,t,n){return kw(e,t,n)}build(e,t,n){Tw(e,t,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,t,n,r){Ow(e,t,n,r)}mount(e){this.isSVGTag=Dw(e.tagName),super.mount(e)}},jw=EC.length;function Mw(e){if(!e)return;if(!e.isControllingVariants){let t=e.parent&&Mw(e.parent)||{};return e.props.initial!==void 0&&(t.initial=e.props.initial),t}let t={};for(let n=0;n<jw;n++){let r=EC[n],i=e.props[r];(wC(i)||i===!1)&&(t[r]=i)}return t}function Nw(e,t){if(!Array.isArray(t))return!1;let n=t.length;if(n!==e.length)return!1;for(let r=0;r<n;r++)if(t[r]!==e[r])return!1;return!0}var Pw=[...TC].reverse(),Fw=TC.length;function Iw(e){return t=>Promise.all(t.map(({animation:t,options:n})=>uS(e,t,n)))}function Lw(e){let t=Iw(e),n=Bw(),r=!0,i=!1,a=t=>(n,r)=>{let i=Ux(e,r,t===`exit`?e.presenceContext?.custom:void 0);if(i){let{transition:e,transitionEnd:t,...r}=i;n={...n,...r,...t}}return n};function o(n){t=n(e)}function s(o){let{props:s}=e,c=Mw(e.parent)||{},l=[],u=new Set,d={},f=1/0;for(let t=0;t<Fw;t++){let p=Pw[t],m=n[p],h=s[p]===void 0?c[p]:s[p],g=wC(h),_=p===o?m.isActive:null;_===!1&&(f=t);let v=h===c[p]&&h!==s[p]&&g;if(v&&(r||i)&&e.manuallyAnimateOnMount&&(v=!1),m.protectedKeys={...d},!m.isActive&&_===null||!h&&!m.prevProp||CC(h)||typeof h==`boolean`)continue;if(p===`exit`&&m.isActive&&_!==!0){m.prevResolvedValues&&(d={...d,...m.prevResolvedValues});continue}let y=Rw(m.prevProp,h),b=y||p===o&&m.isActive&&!v&&g||t>f&&g,x=!1,S=Array.isArray(h)?h:[h],ee=S.reduce(a(p),{});_===!1&&(ee={});let{prevResolvedValues:te={}}=m,ne={...te,...ee},re=t=>{b=!0,u.has(t)&&(x=!0,u.delete(t)),m.needsAnimating[t]=!0;let n=e.getValue(t);n&&(n.liveStyle=!1)};for(let e in ne){let t=ee[e],n=te[e];if(d.hasOwnProperty(e))continue;let r=!1;r=Xx(t)&&Xx(n)?!Nw(t,n):t!==n,r?t==null?u.add(e):re(e):t!==void 0&&u.has(e)?re(e):m.protectedKeys[e]=!0}m.prevProp=h,m.prevResolvedValues=ee,m.isActive&&(d={...d,...ee}),(r||i)&&e.blockInitialAnimation&&(b=!1);let C=v&&y;b&&(!C||x)&&l.push(...S.map(t=>{let n={type:p};if(typeof t==`string`&&(r||i)&&!C&&e.manuallyAnimateOnMount&&e.parent){let{parent:r}=e,i=Ux(r,t);if(r.enteringChildren&&i){let{delayChildren:t}=i.transition||{};n.delay=Ex(r.enteringChildren,e,t)}}return{animation:t,options:n}}))}if(u.size){let t={};if(typeof s.initial!=`boolean`){let n=Ux(e,Array.isArray(s.initial)?s.initial[0]:s.initial);n&&n.transition&&(t.transition=n.transition)}u.forEach(n=>{let r=e.getBaseTarget(n),i=e.getValue(n);i&&(i.liveStyle=!0),t[n]=r??null}),l.push({animation:t})}let p=!!l.length;return r&&(s.initial===!1||s.initial===s.animate)&&!e.manuallyAnimateOnMount&&(p=!1),r=!1,i=!1,p?t(l):Promise.resolve()}function c(t,r){if(n[t].isActive===r)return Promise.resolve();e.variantChildren?.forEach(e=>e.animationState?.setActive(t,r)),n[t].isActive=r;let i=s(t);for(let e in n)n[e].protectedKeys={};return i}return{animateChanges:s,setActive:c,setAnimateFunction:o,getState:()=>n,reset:()=>{n=Bw(),i=!0}}}function Rw(e,t){return typeof t==`string`?t!==e:Array.isArray(t)?!Nw(t,e):!1}function zw(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Bw(){return{animate:zw(!0),whileInView:zw(),whileHover:zw(),whileTap:zw(),whileDrag:zw(),whileFocus:zw(),exit:zw()}}function Vw(e,t){e.min=t.min,e.max=t.max}function Hw(e,t){Vw(e.x,t.x),Vw(e.y,t.y)}function Uw(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}var Ww=1e-4,Gw=1-Ww,Kw=1+Ww,qw=.01,Jw=0-qw,Yw=0+qw;function Xw(e){return e.max-e.min}function Zw(e,t,n){return Math.abs(e-t)<=n}function Qw(e,t,n,r=.5){e.origin=r,e.originPoint=Oy(t.min,t.max,e.origin),e.scale=Xw(n)/Xw(t),e.translate=Oy(n.min,n.max,e.origin)-e.originPoint,(e.scale>=Gw&&e.scale<=Kw||isNaN(e.scale))&&(e.scale=1),(e.translate>=Jw&&e.translate<=Yw||isNaN(e.translate))&&(e.translate=0)}function $w(e,t,n,r){Qw(e.x,t.x,n.x,r?r.originX:void 0),Qw(e.y,t.y,n.y,r?r.originY:void 0)}function eT(e,t,n,r=0){e.min=(r?Oy(n.min,n.max,r):n.min)+t.min,e.max=e.min+Xw(t)}function tT(e,t,n,r){eT(e.x,t.x,n.x,r?.x),eT(e.y,t.y,n.y,r?.y)}function nT(e,t,n,r=0){let i=r?Oy(n.min,n.max,r):n.min;e.min=t.min-i,e.max=e.min+Xw(t)}function rT(e,t,n,r){nT(e.x,t.x,n.x,r?.x),nT(e.y,t.y,n.y,r?.y)}function iT(e,t,n,r,i){return e-=t,e=YC(e,1/n,r),i!==void 0&&(e=YC(e,1/i,r)),e}function aT(e,t=0,n=1,r=.5,i,a=e,o=e){if(ry.test(t)&&(t=parseFloat(t),t=Oy(o.min,o.max,t/100)-o.min),typeof t!=`number`)return;let s=Oy(a.min,a.max,r);e===a&&(s-=t),e.min=iT(e.min,t,n,s,i),e.max=iT(e.max,t,n,s,i)}function oT(e,t,[n,r,i],a,o){aT(e,t[n],t[r],t[i],t.scale,a,o)}var sT=[`x`,`scaleX`,`originX`],cT=[`y`,`scaleY`,`originY`];function lT(e,t,n,r){oT(e.x,t,sT,n?n.x:void 0,r?r.x:void 0),oT(e.y,t,cT,n?n.y:void 0,r?r.y:void 0)}function uT(e){return e.translate===0&&e.scale===1}function dT(e){return uT(e.x)&&uT(e.y)}function fT(e,t){return e.min===t.min&&e.max===t.max}function pT(e,t){return fT(e.x,t.x)&&fT(e.y,t.y)}function mT(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function hT(e,t){return mT(e.x,t.x)&&mT(e.y,t.y)}function gT(e){return Xw(e.x)/Xw(e.y)}function _T(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}function vT(e){return[e(`x`),e(`y`)]}function yT(e,t,n){let r=``,i=e.x.translate/t.x,a=e.y.translate/t.y,o=n?.z||0;if((i||a||o)&&(r=`translate3d(${i}px, ${a}px, ${o}px) `),(t.x!==1||t.y!==1)&&(r+=`scale(${1/t.x}, ${1/t.y}) `),n){let{transformPerspective:e,rotate:t,rotateX:i,rotateY:a,skewX:o,skewY:s}=n;e&&(r=`perspective(${e}px) ${r}`),t&&(r+=`rotate(${t}deg) `),i&&(r+=`rotateX(${i}deg) `),a&&(r+=`rotateY(${a}deg) `),o&&(r+=`skewX(${o}deg) `),s&&(r+=`skewY(${s}deg) `)}let s=e.x.scale*t.x,c=e.y.scale*t.y;return(s!==1||c!==1)&&(r+=`scale(${s}, ${c})`),r||`none`}var bT=[`borderTopLeftRadius`,`borderTopRightRadius`,`borderBottomLeftRadius`,`borderBottomRightRadius`],xT=bT.length,ST=e=>typeof e==`string`?parseFloat(e):e,CT=e=>typeof e==`number`||$.test(e);function wT(e,t,n,r,i,a){i?(e.opacity=Oy(0,n.opacity??1,ET(r)),e.opacityExit=Oy(t.opacity??1,0,DT(r))):a&&(e.opacity=Oy(t.opacity??1,n.opacity??1,r));for(let i=0;i<xT;i++){let a=bT[i],o=TT(t,a),s=TT(n,a);o===void 0&&s===void 0||(o||=0,s||=0,o===0||s===0||CT(o)===CT(s)?(e[a]=Math.max(Oy(ST(o),ST(s),r),0),(ry.test(s)||ry.test(o))&&(e[a]+=`%`)):e[a]=s)}(t.rotate||n.rotate)&&(e.rotate=Oy(t.rotate||0,n.rotate||0,r))}function TT(e,t){return e[t]===void 0?e.borderRadius:e[t]}var ET=OT(0,.5,pv),DT=OT(.5,.95,G_);function OT(e,t,n){return r=>r<e?0:r>t?1:n(J_(e,t,r))}function kT(e,t,n){let r=eS(e)?e:Yx(e);return r.start(Bx(``,r,t,n)),r.animation}function AT(e,t,n,r={passive:!0}){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n)}var jT=(e,t)=>e.depth-t.depth,MT=class{constructor(){this.children=[],this.isDirty=!1}add(e){P_(this.children,e),this.isDirty=!0}remove(e){F_(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(jT),this.isDirty=!1,this.children.forEach(e)}};function NT(e,t){let n=Nv.now(),r=({timestamp:i})=>{let a=i-n;a>=t&&(Ov(r),e(a-t))};return Q.setup(r,!0),()=>Ov(r)}function PT(e){return eS(e)?e.get():e}var FT=class{constructor(){this.members=[]}add(e){P_(this.members,e);for(let t=this.members.length-1;t>=0;t--){let n=this.members[t];if(n===e||n===this.lead||n===this.prevLead)continue;let r=n.instance;(!r||r.isConnected===!1)&&!n.snapshot&&(F_(this.members,n),n.unmount())}e.scheduleRender()}remove(e){if(F_(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){let e=this.members[this.members.length-1];e&&this.promote(e)}}relegate(e){for(let t=this.members.indexOf(e)-1;t>=0;t--){let e=this.members[t];if(e.isPresent!==!1&&e.instance?.isConnected!==!1)return this.promote(e),!0}return!1}promote(e,t){let n=this.lead;if(e!==n&&(this.prevLead=n,this.lead=e,e.show(),n)){n.updateSnapshot(),e.scheduleRender();let{layoutDependency:r}=n.options,{layoutDependency:i}=e.options;(r===void 0||r!==i)&&(e.resumeFrom=n,t&&(n.preserveOpacity=!0),n.snapshot&&(e.snapshot=n.snapshot,e.snapshot.latestValues=n.animationValues||n.latestValues),e.root?.isUpdating&&(e.isLayoutDirty=!0)),e.options.crossfade===!1&&n.hide()}}exitAnimationComplete(){this.members.forEach(e=>{e.options.onExitComplete?.(),e.resumingFrom?.options.onExitComplete?.()})}scheduleRender(){this.members.forEach(e=>e.instance&&e.scheduleRender(!1))}removeLeadSnapshot(){this.lead?.snapshot&&(this.lead.snapshot=void 0)}},IT={hasAnimatedSinceResize:!0,hasEverUpdated:!1},LT={nodes:0,calculatedTargetDeltas:0,calculatedProjections:0},RT=[``,`X`,`Y`,`Z`],zT=1e3,BT=0;function VT(e,t,n,r){let{latestValues:i}=t;i[e]&&(n[e]=i[e],t.setStaticValue(e,0),r&&(r[e]=0))}function HT(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;let{visualElement:t}=e.options;if(!t)return;let n=aS(t);if(window.MotionHasOptimisedAnimation(n,`transform`)){let{layout:t,layoutId:r}=e.options;window.MotionCancelOptimisedAnimation(n,`transform`,Q,!(t||r))}let{parent:r}=e;r&&!r.hasCheckedOptimisedAppear&&HT(r)}function UT({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:i}){return class{constructor(e={},n=t?.()){this.id=BT++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.layoutVersion=0,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,wv.value&&(LT.nodes=LT.calculatedTargetDeltas=LT.calculatedProjections=0),this.nodes.forEach(KT),this.nodes.forEach(tE),this.nodes.forEach(nE),this.nodes.forEach(qT),wv.addProjectionMetrics&&wv.addProjectionMetrics(LT)},this.resolvedRelativeTargetAt=0,this.linkedParentVersion=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=e,this.root=n?n.root||n:this,this.path=n?[...n.path,n]:[],this.parent=n,this.depth=n?n.depth+1:0;for(let e=0;e<this.path.length;e++)this.path[e].shouldResetTransform=!0;this.root===this&&(this.nodes=new MT)}addEventListener(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,new Y_),this.eventHandlers.get(e).add(t)}notifyListeners(e,...t){let n=this.eventHandlers.get(e);n&&n.notify(...t)}hasListeners(e){return this.eventHandlers.has(e)}mount(t){if(this.instance)return;this.isSVG=eC(t)&&!hC(t),this.instance=t;let{layoutId:n,layout:r,visualElement:i}=this.options;if(i&&!i.current&&i.mount(t),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(r||n)&&(this.isLayoutDirty=!0),e){let n,r=0,i=()=>this.root.updateBlockedByResize=!1;Q.read(()=>{r=window.innerWidth}),e(t,()=>{let e=window.innerWidth;e!==r&&(r=e,this.root.updateBlockedByResize=!0,n&&n(),n=NT(i,250),IT.hasAnimatedSinceResize&&(IT.hasAnimatedSinceResize=!1,this.nodes.forEach(eE)))})}n&&this.root.registerSharedNode(n,this),this.options.animate!==!1&&i&&(n||r)&&this.addEventListener(`didUpdate`,({delta:e,hasLayoutChanged:t,hasRelativeLayoutChanged:n,layout:r})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}let a=this.options.transition||i.getDefaultTransition()||lE,{onLayoutAnimationStart:o,onLayoutAnimationComplete:s}=i.getProps(),c=!this.targetLayout||!hT(this.targetLayout,r),l=!t&&n;if(this.options.layoutRoot||this.resumeFrom||l||t&&(c||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);let t={...Lx(a,`layout`),onPlay:o,onComplete:s};(i.shouldReduceMotion||this.options.layoutRoot)&&(t.delay=0,t.type=!1),this.startAnimation(t),this.setAnimationOrigin(e,l)}else t||eE(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=r})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);let e=this.getStack();e&&e.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Ov(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(rE),this.animationId++)}getTransformTemplate(){let{visualElement:e}=this.options;return e&&e.getProps().transformTemplate}willUpdate(e=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&HT(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let e=0;e<this.path.length;e++){let t=this.path[e];t.shouldResetTransform=!0,(typeof t.latestValues.x==`string`||typeof t.latestValues.y==`string`)&&(t.isLayoutDirty=!0),t.updateScroll(`snapshot`),t.options.layoutRoot&&t.willUpdate(!1)}let{layoutId:t,layout:n}=this.options;if(t===void 0&&!n)return;let r=this.getTransformTemplate();this.prevTransformTemplateValue=r?r(this.latestValues,``):void 0,this.updateSnapshot(),e&&this.notifyListeners(`willUpdate`)}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){let e=this.updateBlockedByResize;this.unblockUpdate(),this.updateBlockedByResize=!1,this.clearAllSnapshots(),e&&this.nodes.forEach(XT),this.nodes.forEach(YT);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(ZT);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(QT),this.nodes.forEach($T),this.nodes.forEach(WT),this.nodes.forEach(GT)):this.nodes.forEach(ZT),this.clearAllSnapshots();let e=Nv.now();kv.delta=I_(0,1e3/60,e-kv.timestamp),kv.timestamp=e,kv.isProcessing=!0,Av.update.process(kv),Av.preRender.process(kv),Av.render.process(kv),kv.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,NS.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(JT),this.sharedNodes.forEach(iE)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,Q.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){Q.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Xw(this.snapshot.measuredBox.x)&&!Xw(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let e=0;e<this.path.length;e++)this.path[e].updateScroll();let e=this.layout;this.layout=this.measure(!1),this.layoutVersion++,this.layoutCorrected||=xC(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners(`measure`,this.layout.layoutBox);let{visualElement:t}=this.options;t&&t.notify(`LayoutMeasure`,this.layout.layoutBox,e?e.layoutBox:void 0)}updateScroll(e=`measure`){let t=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===e&&(t=!1),t&&this.instance){let t=r(this.instance);this.scroll={animationId:this.root.animationId,phase:e,isRoot:t,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:t}}}resetTransform(){if(!i)return;let e=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,t=this.projectionDelta&&!dT(this.projectionDelta),n=this.getTransformTemplate(),r=n?n(this.latestValues,``):void 0,a=r!==this.prevTransformTemplateValue;e&&this.instance&&(t||KC(this.latestValues)||a)&&(i(this.instance,r),this.shouldResetTransform=!1,this.scheduleRender())}measure(e=!0){let t=this.measurePageBox(),n=this.removeElementScroll(t);return e&&(n=this.removeTransform(n)),pE(n),{animationId:this.root.animationId,measuredBox:t,layoutBox:n,latestValues:{},source:this.id}}measurePageBox(){let{visualElement:e}=this.options;if(!e)return xC();let t=e.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(hE))){let{scroll:e}=this.root;e&&(nw(t.x,e.offset.x),nw(t.y,e.offset.y))}return t}removeElementScroll(e){let t=xC();if(Hw(t,e),this.scroll?.wasRoot)return t;for(let n=0;n<this.path.length;n++){let r=this.path[n],{scroll:i,options:a}=r;r!==this.root&&i&&a.layoutScroll&&(i.wasRoot&&Hw(t,e),nw(t.x,i.offset.x),nw(t.y,i.offset.y))}return t}applyTransform(e,t=!1,n){let r=n||xC();Hw(r,e);for(let e=0;e<this.path.length;e++){let n=this.path[e];!t&&n.options.layoutScroll&&n.scroll&&n!==n.root&&(nw(r.x,-n.scroll.offset.x),nw(r.y,-n.scroll.offset.y)),KC(n.latestValues)&&aw(r,n.latestValues,n.layout?.layoutBox)}return KC(this.latestValues)&&aw(r,this.latestValues,this.layout?.layoutBox),r}removeTransform(e){let t=xC();Hw(t,e);for(let e=0;e<this.path.length;e++){let n=this.path[e];if(!KC(n.latestValues))continue;let r;n.instance&&(GC(n.latestValues)&&n.updateSnapshot(),r=xC(),Hw(r,n.measurePageBox())),lT(t,n.latestValues,n.snapshot?.layoutBox,r)}return KC(this.latestValues)&&lT(t,this.latestValues),t}setTargetDelta(e){this.targetDelta=e,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(e){this.options={...this.options,...e,crossfade:e.crossfade===void 0?!0:e.crossfade}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==kv.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(e=!1){let t=this.getLead();this.isProjectionDirty||=t.isProjectionDirty,this.isTransformDirty||=t.isTransformDirty,this.isSharedProjectionDirty||=t.isSharedProjectionDirty;let n=!!this.resumingFrom||this!==t;if(!(e||n&&this.isSharedProjectionDirty||this.isProjectionDirty||this.parent?.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;let{layout:r,layoutId:i}=this.options;if(!this.layout||!(r||i))return;this.resolvedRelativeTargetAt=kv.timestamp;let a=this.getClosestProjectingParent();a&&this.linkedParentVersion!==a.layoutVersion&&!a.options.layoutRoot&&this.removeRelativeTarget(),!this.targetDelta&&!this.relativeTarget&&(this.options.layoutAnchor!==!1&&a&&a.layout?this.createRelativeTarget(a,this.layout.layoutBox,a.layout.layoutBox):this.removeRelativeTarget()),!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=xC(),this.targetWithTransforms=xC()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),tT(this.target,this.relativeTarget,this.relativeParent.target,this.options.layoutAnchor||void 0)):this.targetDelta?(this.resumingFrom?this.applyTransform(this.layout.layoutBox,!1,this.target):Hw(this.target,this.layout.layoutBox),QC(this.target,this.targetDelta)):Hw(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget&&(this.attemptToResolveRelativeTarget=!1,this.options.layoutAnchor!==!1&&a&&!!a.resumingFrom==!!this.resumingFrom&&!a.options.layoutScroll&&a.target&&this.animationProgress!==1?this.createRelativeTarget(a,this.target,a.target):this.relativeParent=this.relativeTarget=void 0),wv.value&<.calculatedTargetDeltas++)}getClosestProjectingParent(){if(!(!this.parent||GC(this.parent.latestValues)||qC(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}createRelativeTarget(e,t,n){this.relativeParent=e,this.linkedParentVersion=e.layoutVersion,this.forceRelativeParentToResolveTarget(),this.relativeTarget=xC(),this.relativeTargetOrigin=xC(),rT(this.relativeTargetOrigin,t,n,this.options.layoutAnchor||void 0),Hw(this.relativeTarget,this.relativeTargetOrigin)}removeRelativeTarget(){this.relativeParent=this.relativeTarget=void 0}calcProjection(){let e=this.getLead(),t=!!this.resumingFrom||this!==e,n=!0;if((this.isProjectionDirty||this.parent?.isProjectionDirty)&&(n=!1),t&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(n=!1),this.resolvedRelativeTargetAt===kv.timestamp&&(n=!1),n)return;let{layout:r,layoutId:i}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(r||i))return;Hw(this.layoutCorrected,this.layout.layoutBox);let a=this.treeScale.x,o=this.treeScale.y;tw(this.layoutCorrected,this.treeScale,this.path,t),e.layout&&!e.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(e.target=e.layout.layoutBox,e.targetWithTransforms=xC());let{target:s}=e;if(!s){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Uw(this.prevProjectionDelta.x,this.projectionDelta.x),Uw(this.prevProjectionDelta.y,this.projectionDelta.y)),$w(this.projectionDelta,this.layoutCorrected,s,this.latestValues),(this.treeScale.x!==a||this.treeScale.y!==o||!_T(this.projectionDelta.x,this.prevProjectionDelta.x)||!_T(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners(`projectionUpdate`,s)),wv.value&<.calculatedProjections++}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(e=!0){if(this.options.visualElement?.scheduleRender(),e){let e=this.getStack();e&&e.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=yC(),this.projectionDelta=yC(),this.projectionDeltaWithTransform=yC()}setAnimationOrigin(e,t=!1){let n=this.snapshot,r=n?n.latestValues:{},i={...this.latestValues},a=yC();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!t;let o=xC(),s=(n?n.source:void 0)!==(this.layout?this.layout.source:void 0),c=this.getStack(),l=!c||c.members.length<=1,u=!!(s&&!l&&this.options.crossfade===!0&&!this.path.some(cE));this.animationProgress=0;let d;this.mixTargetDelta=t=>{let n=t/1e3;aE(a.x,e.x,n),aE(a.y,e.y,n),this.setTargetDelta(a),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(rT(o,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),sE(this.relativeTarget,this.relativeTargetOrigin,o,n),d&&pT(this.relativeTarget,d)&&(this.isProjectionDirty=!1),d||=xC(),Hw(d,this.relativeTarget)),s&&(this.animationValues=i,wT(i,r,this.latestValues,n,u,l)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=n},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(e){this.notifyListeners(`animationStart`),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&=(Ov(this.pendingAnimation),void 0),this.pendingAnimation=Q.update(()=>{IT.hasAnimatedSinceResize=!0,Pv.layout++,this.motionValue||=Yx(0),this.motionValue.jump(0,!1),this.currentAnimation=kT(this.motionValue,[0,1e3],{...e,velocity:0,isSync:!0,onUpdate:t=>{this.mixTargetDelta(t),e.onUpdate&&e.onUpdate(t)},onStop:()=>{Pv.layout--},onComplete:()=>{Pv.layout--,e.onComplete&&e.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);let e=this.getStack();e&&e.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners(`animationComplete`)}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(zT),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){let e=this.getLead(),{targetWithTransforms:t,target:n,layout:r,latestValues:i}=e;if(!(!t||!n||!r)){if(this!==e&&this.layout&&r&&mE(this.options.animationType,this.layout.layoutBox,r.layoutBox)){n=this.target||xC();let t=Xw(this.layout.layoutBox.x);n.x.min=e.target.x.min,n.x.max=n.x.min+t;let r=Xw(this.layout.layoutBox.y);n.y.min=e.target.y.min,n.y.max=n.y.min+r}Hw(t,n),aw(t,i),$w(this.projectionDeltaWithTransform,this.layoutCorrected,t,i)}}registerSharedNode(e,t){this.sharedNodes.has(e)||this.sharedNodes.set(e,new FT),this.sharedNodes.get(e).add(t);let n=t.options.initialPromotionConfig;t.promote({transition:n?n.transition:void 0,preserveFollowOpacity:n&&n.shouldPreserveFollowOpacity?n.shouldPreserveFollowOpacity(t):void 0})}isLead(){let e=this.getStack();return e?e.lead===this:!0}getLead(){let{layoutId:e}=this.options;return e&&this.getStack()?.lead||this}getPrevLead(){let{layoutId:e}=this.options;return e?this.getStack()?.prevLead:void 0}getStack(){let{layoutId:e}=this.options;if(e)return this.root.sharedNodes.get(e)}promote({needsReset:e,transition:t,preserveFollowOpacity:n}={}){let r=this.getStack();r&&r.promote(this,n),e&&(this.projectionDelta=void 0,this.needsReset=!0),t&&this.setOptions({transition:t})}relegate(){let e=this.getStack();return e?e.relegate(this):!1}resetSkewAndRotation(){let{visualElement:e}=this.options;if(!e)return;let t=!1,{latestValues:n}=e;if((n.z||n.rotate||n.rotateX||n.rotateY||n.rotateZ||n.skewX||n.skewY)&&(t=!0),!t)return;let r={};n.z&&VT(`z`,e,r,this.animationValues);for(let t=0;t<RT.length;t++)VT(`rotate${RT[t]}`,e,r,this.animationValues),VT(`skew${RT[t]}`,e,r,this.animationValues);e.render();for(let t in r)e.setStaticValue(t,r[t]),this.animationValues&&(this.animationValues[t]=r[t]);e.scheduleRender()}applyProjectionStyles(e,t){if(!this.instance||this.isSVG)return;if(!this.isVisible){e.visibility=`hidden`;return}let n=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,e.visibility=``,e.opacity=``,e.pointerEvents=PT(t?.pointerEvents)||``,e.transform=n?n(this.latestValues,``):`none`;return}let r=this.getLead();if(!this.projectionDelta||!this.layout||!r.target){this.options.layoutId&&(e.opacity=this.latestValues.opacity===void 0?1:this.latestValues.opacity,e.pointerEvents=PT(t?.pointerEvents)||``),this.hasProjected&&!KC(this.latestValues)&&(e.transform=n?n({},``):`none`,this.hasProjected=!1);return}e.visibility=``;let i=r.animationValues||r.latestValues;this.applyTransformsToTarget();let a=yT(this.projectionDeltaWithTransform,this.treeScale,i);n&&(a=n(i,a)),e.transform=a;let{x:o,y:s}=this.projectionDelta;e.transformOrigin=`${o.origin*100}% ${s.origin*100}% 0`,r.animationValues?e.opacity=r===this?i.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:i.opacityExit:e.opacity=r===this?i.opacity===void 0?``:i.opacity:i.opacityExit===void 0?0:i.opacityExit;for(let t in gw){if(i[t]===void 0)continue;let{correct:n,applyTo:o,isCSSVariable:s}=gw[t],c=a===`none`?i[t]:n(i[t],r);if(o){let t=o.length;for(let n=0;n<t;n++)e[o[n]]=c}else s?this.options.visualElement.renderState.vars[t]=c:e[t]=c}this.options.layoutId&&(e.pointerEvents=r===this?PT(t?.pointerEvents)||``:`none`)}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(e=>e.currentAnimation?.stop()),this.root.nodes.forEach(YT),this.root.sharedNodes.clear()}}}function WT(e){e.updateLayout()}function GT(e){let t=e.resumeFrom?.snapshot||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners(`didUpdate`)){let{layoutBox:n,measuredBox:r}=e.layout,{animationType:i}=e.options,a=t.source!==e.layout.source;if(i===`size`)vT(e=>{let r=a?t.measuredBox[e]:t.layoutBox[e],i=Xw(r);r.min=n[e].min,r.max=r.min+i});else if(i===`x`||i===`y`){let e=i===`x`?`y`:`x`;Vw(a?t.measuredBox[e]:t.layoutBox[e],n[e])}else mE(i,t.layoutBox,n)&&vT(r=>{let i=a?t.measuredBox[r]:t.layoutBox[r],o=Xw(n[r]);i.max=i.min+o,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[r].max=e.relativeTarget[r].min+o)});let o=yC();$w(o,n,t.layoutBox);let s=yC();a?$w(s,e.applyTransform(r,!0),t.measuredBox):$w(s,n,t.layoutBox);let c=!dT(o),l=!1;if(!e.resumeFrom){let r=e.getClosestProjectingParent();if(r&&!r.resumeFrom){let{snapshot:i,layout:a}=r;if(i&&a){let o=e.options.layoutAnchor||void 0,s=xC();rT(s,t.layoutBox,i.layoutBox,o);let c=xC();rT(c,n,a.layoutBox,o),hT(s,c)||(l=!0),r.options.layoutRoot&&(e.relativeTarget=c,e.relativeTargetOrigin=s,e.relativeParent=r)}}}e.notifyListeners(`didUpdate`,{layout:n,snapshot:t,delta:s,layoutDelta:o,hasLayoutChanged:c,hasRelativeLayoutChanged:l})}else if(e.isLead()){let{onExitComplete:t}=e.options;t&&t()}e.options.transition=void 0}function KT(e){wv.value&<.nodes++,e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty),e.isTransformDirty||=e.parent.isTransformDirty)}function qT(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function JT(e){e.clearSnapshot()}function YT(e){e.clearMeasurements()}function XT(e){e.isLayoutDirty=!0,e.updateLayout()}function ZT(e){e.isLayoutDirty=!1}function QT(e){e.isAnimationBlocked&&e.layout&&!e.isLayoutDirty&&(e.snapshot=e.layout,e.isLayoutDirty=!0)}function $T(e){let{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify(`BeforeLayoutMeasure`),e.resetTransform()}function eE(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function tE(e){e.resolveTargetDelta()}function nE(e){e.calcProjection()}function rE(e){e.resetSkewAndRotation()}function iE(e){e.removeLeadSnapshot()}function aE(e,t,n){e.translate=Oy(t.translate,0,n),e.scale=Oy(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function oE(e,t,n,r){e.min=Oy(t.min,n.min,r),e.max=Oy(t.max,n.max,r)}function sE(e,t,n,r){oE(e.x,t.x,n.x,r),oE(e.y,t.y,n.y,r)}function cE(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}var lE={duration:.45,ease:[.4,0,.1,1]},uE=e=>typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),dE=uE(`applewebkit/`)&&!uE(`chrome/`)?Math.round:G_;function fE(e){e.min=dE(e.min),e.max=dE(e.max)}function pE(e){fE(e.x),fE(e.y)}function mE(e,t,n){return e===`position`||e===`preserve-aspect`&&!Zw(gT(t),gT(n),.2)}function hE(e){return e!==e.root&&e.scroll?.wasRoot}var gE=UT({attachResizeListener:(e,t)=>AT(e,`resize`,t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body?.scrollLeft||0,y:document.documentElement.scrollTop||document.body?.scrollTop||0}),checkIsScrollRoot:()=>!0}),_E={current:void 0},vE=UT({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!_E.current){let e=new gE({});e.mount(window),e.setOptions({layoutScroll:!0}),_E.current=e}return _E.current},resetTransform:(e,t)=>{e.style.transform=t===void 0?`none`:t},checkIsScrollRoot:e=>window.getComputedStyle(e).position===`fixed`}),yE=(0,d.createContext)({transformPagePoint:e=>e,isStatic:!1,reducedMotion:`never`});function bE(e=!0){let t=(0,d.useContext)(N_);if(t===null)return[!0,null];let{isPresent:n,onExitComplete:r,register:i}=t,a=(0,d.useId)();(0,d.useEffect)(()=>{if(e)return i(a)},[e]);let o=(0,d.useCallback)(()=>e&&r&&r(a),[a,r,e]);return!n&&r?[!1,o]:[!0]}var xE=(0,d.createContext)({strict:!1}),SE={animation:[`animate`,`variants`,`whileHover`,`whileTap`,`exit`,`whileInView`,`whileFocus`,`whileDrag`],exit:[`exit`],drag:[`drag`,`dragControls`],focus:[`whileFocus`],hover:[`whileHover`,`onHoverStart`,`onHoverEnd`],tap:[`whileTap`,`onTap`,`onTapStart`,`onTapCancel`],pan:[`onPan`,`onPanStart`,`onPanSessionStart`,`onPanEnd`],inView:[`whileInView`,`onViewportEnter`,`onViewportLeave`],layout:[`layout`,`layoutId`]},CE=!1;function wE(){if(CE)return;let e={};for(let t in SE)e[t]={isEnabled:e=>SE[t].some(t=>!!e[t])};IC(e),CE=!0}function TE(){return wE(),LC()}function EE(e){let t=TE();for(let n in e)t[n]={...t[n],...e[n]};IC(t)}var DE=new Set(`animate.exit.variants.initial.style.values.variants.transition.transformTemplate.custom.inherit.onBeforeLayoutMeasure.onAnimationStart.onAnimationComplete.onUpdate.onDragStart.onDrag.onDragEnd.onMeasureDragConstraints.onDirectionLock.onDragTransitionEnd._dragX._dragY.onHoverStart.onHoverEnd.onViewportEnter.onViewportLeave.globalTapTarget.propagate.ignoreStrict.viewport`.split(`.`));function OE(e){return e.startsWith(`while`)||e.startsWith(`drag`)&&e!==`draggable`||e.startsWith(`layout`)||e.startsWith(`onTap`)||e.startsWith(`onPan`)||e.startsWith(`onLayout`)||DE.has(e)}var kE=s({default:()=>AE}),AE,jE=o((()=>{throw AE={},Error(`Could not resolve "@emotion/is-prop-valid" imported by "framer-motion". Is it installed?`)})),ME=e=>!OE(e);function NE(e){typeof e==`function`&&(ME=t=>t.startsWith(`on`)?!OE(t):e(t))}try{NE((jE(),u(kE)).default)}catch{}function PE(e,t,n){let r={};for(let i in e)i===`values`&&typeof e.values==`object`||eS(e[i])||(ME(i)||n===!0&&OE(i)||!t&&!OE(i)||e.draggable&&i.startsWith(`onDrag`))&&(r[i]=e[i]);return r}var FE=(0,d.createContext)({});function IE(e,t){if(DC(e)){let{initial:t,animate:n}=e;return{initial:t===!1||wC(t)?t:void 0,animate:wC(n)?n:void 0}}return e.inherit===!1?{}:t}function LE(e){let{initial:t,animate:n}=IE(e,(0,d.useContext)(FE));return(0,d.useMemo)(()=>({initial:t,animate:n}),[RE(t),RE(n)])}function RE(e){return Array.isArray(e)?e.join(` `):e}var zE=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function BE(e,t,n){for(let r in t)!eS(t[r])&&!_w(r,n)&&(e[r]=t[r])}function VE({transformTemplate:e},t){return(0,d.useMemo)(()=>{let n=zE();return dw(n,t,e),Object.assign({},n.vars,n.style)},[t])}function HE(e,t){let n=e.style||{},r={};return BE(r,n,e),Object.assign(r,VE(e,t)),r}function UE(e,t){let n={},r=HE(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout=`none`,r.touchAction=e.drag===!0?`none`:`pan-${e.drag===`x`?`y`:`x`}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=r,n}var WE=()=>({...zE(),attrs:{}});function GE(e,t,n,r){let i=(0,d.useMemo)(()=>{let n=WE();return Tw(n,t,Dw(r),e.transformTemplate,e.style),{...n.attrs,style:{...n.style}}},[t]);if(e.style){let t={};BE(t,e.style,e),i.style={...t,...i.style}}return i}var KE=[`animate`,`circle`,`defs`,`desc`,`ellipse`,`g`,`image`,`line`,`filter`,`marker`,`mask`,`metadata`,`path`,`pattern`,`polygon`,`polyline`,`rect`,`stop`,`switch`,`symbol`,`svg`,`text`,`tspan`,`use`,`view`];function qE(e){return typeof e!=`string`||e.includes(`-`)?!1:!!(KE.indexOf(e)>-1||/[A-Z]/u.test(e))}function JE(e,t,n,{latestValues:r},i,a=!1,o){let s=(o??qE(e)?GE:UE)(t,r,i,e),c=PE(t,typeof e==`string`,a),l=e===d.Fragment?{}:{...c,...s,ref:n},{children:u}=t,f=(0,d.useMemo)(()=>eS(u)?u.get():u,[u]);return(0,d.createElement)(e,{...l,children:f})}function YE({scrapeMotionValuesFromProps:e,createRenderState:t},n,r,i){return{latestValues:XE(n,r,i,e),renderState:t()}}function XE(e,t,n,r){let i={},a=r(e,{});for(let e in a)i[e]=PT(a[e]);let{initial:o,animate:s}=e,c=DC(e),l=OC(e);t&&l&&!c&&e.inherit!==!1&&(o===void 0&&(o=t.initial),s===void 0&&(s=t.animate));let u=n?n.initial===!1:!1;u||=o===!1;let d=u?s:o;if(d&&typeof d!=`boolean`&&!CC(d)){let t=Array.isArray(d)?d:[d];for(let n=0;n<t.length;n++){let r=Hx(e,t[n]);if(r){let{transitionEnd:e,transition:t,...n}=r;for(let e in n){let t=n[e];if(Array.isArray(t)){let e=u?t.length-1:0;t=t[e]}t!==null&&(i[e]=t)}for(let t in e)i[t]=e[t]}}}return i}var ZE=e=>(t,n)=>{let r=(0,d.useContext)(FE),i=(0,d.useContext)(N_),a=()=>YE(e,t,r,i);return n?a():j_(a)},QE=ZE({scrapeMotionValuesFromProps:vw,createRenderState:zE}),$E=ZE({scrapeMotionValuesFromProps:kw,createRenderState:WE}),eD=Symbol.for(`motionComponentSymbol`);function tD(e,t,n){let r=(0,d.useRef)(n);(0,d.useInsertionEffect)(()=>{r.current=n});let i=(0,d.useRef)(null);return(0,d.useCallback)(n=>{n&&e.onMount?.(n);let a=r.current;if(typeof a==`function`)if(n){let e=a(n);typeof e==`function`&&(i.current=e)}else i.current?(i.current(),i.current=null):a(n);else a&&(a.current=n);t&&(n?t.mount(n):t.unmount())},[t])}var nD=(0,d.createContext)({});function rD(e){return e&&typeof e==`object`&&Object.prototype.hasOwnProperty.call(e,`current`)}function iD(e,t,n,r,i,a){let{visualElement:o}=(0,d.useContext)(FE),s=(0,d.useContext)(xE),c=(0,d.useContext)(N_),l=(0,d.useContext)(yE),u=l.reducedMotion,f=l.skipAnimations,p=(0,d.useRef)(null),m=(0,d.useRef)(!1);r||=s.renderer,!p.current&&r&&(p.current=r(e,{visualState:t,parent:o,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:f,isSVG:a}),m.current&&p.current&&(p.current.manuallyAnimateOnMount=!0));let h=p.current,g=(0,d.useContext)(nD);h&&!h.projection&&i&&(h.type===`html`||h.type===`svg`)&&aD(p.current,n,i,g);let _=(0,d.useRef)(!1);(0,d.useInsertionEffect)(()=>{h&&_.current&&h.update(n,c)});let v=n[iS],y=(0,d.useRef)(!!v&&typeof window<`u`&&!window.MotionHandoffIsComplete?.(v)&&window.MotionHasOptimisedAnimation?.(v));return M_(()=>{m.current=!0,h&&(_.current=!0,window.MotionIsMounted=!0,h.updateFeatures(),h.scheduleRenderMicrotask(),y.current&&h.animationState&&h.animationState.animateChanges())}),(0,d.useEffect)(()=>{h&&(!y.current&&h.animationState&&h.animationState.animateChanges(),y.current&&=(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(v)}),!1),h.enteringChildren=void 0)}),h}function aD(e,t,n,r){let{layoutId:i,layout:a,drag:o,dragConstraints:s,layoutScroll:c,layoutRoot:l,layoutAnchor:u,layoutCrossfade:d}=t;e.projection=new n(e.latestValues,t[`data-framer-portal-id`]?void 0:oD(e.parent)),e.projection.setOptions({layoutId:i,layout:a,alwaysMeasureLayout:!!o||s&&rD(s),visualElement:e,animationType:typeof a==`string`?a:`both`,initialPromotionConfig:r,crossfade:d,layoutScroll:c,layoutRoot:l,layoutAnchor:u})}function oD(e){if(e)return e.options.allowProjection===!1?oD(e.parent):e.projection}function sD(e,{forwardMotionProps:t=!1,type:n}={},r,i){r&&EE(r);let a=n?n===`svg`:qE(e),o=a?$E:QE;function s(n,s){let c,l={...(0,d.useContext)(yE),...n,layoutId:cD(n)},{isStatic:u}=l,p=LE(n),m=o(n,u);if(!u&&typeof window<`u`){lD(l,r);let t=uD(l);c=t.MeasureLayout,p.visualElement=iD(e,m,l,i,t.ProjectionNode,a)}return(0,f.jsxs)(FE.Provider,{value:p,children:[c&&p.visualElement?(0,f.jsx)(c,{visualElement:p.visualElement,...l}):null,JE(e,n,tD(m,p.visualElement,s),m,u,t,a)]})}s.displayName=`motion.${typeof e==`string`?e:`create(${e.displayName??e.name??``})`}`;let c=(0,d.forwardRef)(s);return c[eD]=e,c}function cD({layoutId:e}){let t=(0,d.useContext)(A_).id;return t&&e!==void 0?t+`-`+e:e}function lD(e,t){let n=(0,d.useContext)(xE).strict;if(process.env.NODE_ENV!==`production`&&t&&n){let t="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";e.ignoreStrict?R_(!1,t,`lazy-strict-mode`):z_(!1,t,`lazy-strict-mode`)}}function uD(e){let{drag:t,layout:n}=TE();if(!t&&!n)return{};let r={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}function dD(e,t){if(typeof Proxy>`u`)return sD;let n=new Map,r=(n,r)=>sD(n,r,e,t);return new Proxy((e,t)=>(process.env.NODE_ENV!==`production`&&ev(!1,`motion() is deprecated. Use motion.create() instead.`),r(e,t)),{get:(i,a)=>a===`create`?r:(n.has(a)||n.set(a,sD(a,void 0,e,t)),n.get(a))})}var fD=(e,t)=>t.isSVG??qE(e)?new Aw(t):new bw(t,{allowProjection:e!==d.Fragment}),pD=class extends BC{constructor(e){super(e),e.animationState||=Lw(e)}updateAnimationControlsSubscription(){let{animate:e}=this.node.getProps();CC(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){let{animate:e}=this.node.getProps(),{animate:t}=this.node.prevProps||{};e!==t&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}},mD=0,hD={animation:{Feature:pD},exit:{Feature:class extends BC{constructor(){super(...arguments),this.id=mD++,this.isExitComplete=!1}update(){if(!this.node.presenceContext)return;let{isPresent:e,onExitComplete:t}=this.node.presenceContext,{isPresent:n}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===n)return;if(e&&n===!1){if(this.isExitComplete){let{initial:e,custom:t}=this.node.getProps();if(typeof e==`string`){let n=Ux(this.node,e,t);if(n){let{transition:e,transitionEnd:t,...r}=n;for(let e in r)this.node.getValue(e)?.jump(r[e])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive(`exit`,!1);this.isExitComplete=!1;return}let r=this.node.animationState.setActive(`exit`,!e);t&&!e&&r.then(()=>{this.isExitComplete=!0,t(this.id)})}mount(){let{register:e,onExitComplete:t}=this.node.presenceContext||{};t&&t(this.id),e&&(this.unmount=e(this.id))}unmount(){}}}};function gD(e){return{point:{x:e.pageX,y:e.pageY}}}var _D=e=>t=>HS(t)&&e(t,gD(t));function vD(e,t,n,r){return AT(e,t,_D(n),r)}var yD=({current:e})=>e?e.ownerDocument.defaultView:null,bD=(e,t)=>Math.abs(e-t);function xD(e,t){let n=bD(e.x,t.x),r=bD(e.y,t.y);return Math.sqrt(n**2+r**2)}var SD=new Set([`auto`,`scroll`]),CD=class{constructor(e,t,{transformPagePoint:n,contextWindow:r=window,dragSnapToOrigin:i=!1,distanceThreshold:a=3,element:o}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=e=>{this.handleScroll(e.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=wD(this.lastRawMoveEventInfo,this.transformPagePoint));let e=ED(this.lastMoveEventInfo,this.history),t=this.startEvent!==null,n=xD(e.offset,{x:0,y:0})>=this.distanceThreshold;if(!t&&!n)return;let{point:r}=e,{timestamp:i}=kv;this.history.push({...r,timestamp:i});let{onStart:a,onMove:o}=this.handlers;t||(a&&a(this.lastMoveEvent,e),this.startEvent=this.lastMoveEvent),o&&o(this.lastMoveEvent,e)},this.handlePointerMove=(e,t)=>{this.lastMoveEvent=e,this.lastRawMoveEventInfo=t,this.lastMoveEventInfo=wD(t,this.transformPagePoint),Q.update(this.updatePoint,!0)},this.handlePointerUp=(e,t)=>{this.end();let{onEnd:n,onSessionEnd:r,resumeAnimation:i}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&i&&i(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;let a=ED(e.type===`pointercancel`?this.lastMoveEventInfo:wD(t,this.transformPagePoint),this.history);this.startEvent&&n&&n(e,a),r&&r(e,a)},!HS(e))return;this.dragSnapToOrigin=i,this.handlers=t,this.transformPagePoint=n,this.distanceThreshold=a,this.contextWindow=r||window;let s=wD(gD(e),this.transformPagePoint),{point:c}=s,{timestamp:l}=kv;this.history=[{...c,timestamp:l}];let{onSessionStart:u}=t;u&&u(e,ED(s,this.history)),this.removeListeners=q_(vD(this.contextWindow,`pointermove`,this.handlePointerMove),vD(this.contextWindow,`pointerup`,this.handlePointerUp),vD(this.contextWindow,`pointercancel`,this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(e){let t=e.parentElement;for(;t;){let e=getComputedStyle(t);(SD.has(e.overflowX)||SD.has(e.overflowY))&&this.scrollPositions.set(t,{x:t.scrollLeft,y:t.scrollTop}),t=t.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener(`scroll`,this.onElementScroll,{capture:!0}),window.addEventListener(`scroll`,this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener(`scroll`,this.onElementScroll,{capture:!0}),window.removeEventListener(`scroll`,this.onWindowScroll)}}handleScroll(e){let t=this.scrollPositions.get(e);if(!t)return;let n=e===window,r=n?{x:window.scrollX,y:window.scrollY}:{x:e.scrollLeft,y:e.scrollTop},i={x:r.x-t.x,y:r.y-t.y};i.x===0&&i.y===0||(n?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=i.x,this.lastMoveEventInfo.point.y+=i.y):this.history.length>0&&(this.history[0].x-=i.x,this.history[0].y-=i.y),this.scrollPositions.set(e,r),Q.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),Ov(this.updatePoint)}};function wD(e,t){return t?{point:t(e.point)}:e}function TD(e,t){return{x:e.x-t.x,y:e.y-t.y}}function ED({point:e},t){return{point:e,delta:TD(e,OD(t)),offset:TD(e,DD(t)),velocity:kD(t,.1)}}function DD(e){return e[0]}function OD(e){return e[e.length-1]}function kD(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,r=null,i=OD(e);for(;n>=0&&(r=e[n],!(i.timestamp-r.timestamp>X_(t)));)n--;if(!r)return{x:0,y:0};r===e[0]&&e.length>2&&i.timestamp-r.timestamp>X_(t)*2&&(r=e[1]);let a=Z_(i.timestamp-r.timestamp);if(a===0)return{x:0,y:0};let o={x:(i.x-r.x)/a,y:(i.y-r.y)/a};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}function AD(e,{min:t,max:n},r){return t!==void 0&&e<t?e=r?Oy(t,e,r.min):Math.max(e,t):n!==void 0&&e>n&&(e=r?Oy(n,e,r.max):Math.min(e,n)),e}function jD(e,t,n){return{min:t===void 0?void 0:e.min+t,max:n===void 0?void 0:e.max+n-(e.max-e.min)}}function MD(e,{top:t,left:n,bottom:r,right:i}){return{x:jD(e.x,n,i),y:jD(e.y,t,r)}}function ND(e,t){let n=t.min-e.min,r=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,r]=[r,n]),{min:n,max:r}}function PD(e,t){return{x:ND(e.x,t.x),y:ND(e.y,t.y)}}function FD(e,t){let n=.5,r=Xw(e),i=Xw(t);return i>r?n=J_(t.min,t.max-r,e.min):r>i&&(n=J_(e.min,e.max-i,t.min)),I_(0,1,n)}function ID(e,t){let n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}var LD=.35;function RD(e=LD){return e===!1?e=0:e===!0&&(e=LD),{x:zD(e,`left`,`right`),y:zD(e,`top`,`bottom`)}}function zD(e,t,n){return{min:BD(e,t),max:BD(e,n)}}function BD(e,t){return typeof e==`number`?e:e[t]||0}var VD=new WeakMap,HD=class{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=xC(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:t=!1,distanceThreshold:n}={}){let{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;let i=e=>{t&&this.snapToCursor(gD(e).point),this.stopAnimation()},a=(e,t)=>{let{drag:n,dragPropagation:r,onDragStart:i}=this.getProps();if(n&&!r&&(this.openDragLock&&this.openDragLock(),this.openDragLock=LS(n),!this.openDragLock))return;this.latestPointerEvent=e,this.latestPanInfo=t,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),vT(e=>{let t=this.getAxisMotionValue(e).get()||0;if(ry.test(t)){let{projection:n}=this.visualElement;if(n&&n.layout){let r=n.layout.layoutBox[e];r&&(t=Xw(r)*(parseFloat(t)/100))}}this.originPoint[e]=t}),i&&Q.update(()=>i(e,t),!1,!0),nS(this.visualElement,`transform`);let{animationState:a}=this.visualElement;a&&a.setActive(`whileDrag`,!0)},o=(e,t)=>{this.latestPointerEvent=e,this.latestPanInfo=t;let{dragPropagation:n,dragDirectionLock:r,onDirectionLock:i,onDrag:a}=this.getProps();if(!n&&!this.openDragLock)return;let{offset:o}=t;if(r&&this.currentDirection===null){this.currentDirection=KD(o),this.currentDirection!==null&&i&&i(this.currentDirection);return}this.updateAxis(`x`,t.point,o),this.updateAxis(`y`,t.point,o),this.visualElement.render(),a&&Q.update(()=>a(e,t),!1,!0)},s=(e,t)=>{this.latestPointerEvent=e,this.latestPanInfo=t,this.stop(e,t),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>{let{dragSnapToOrigin:e}=this.getProps();(e||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:l}=this.getProps();this.panSession=new CD(e,{onSessionStart:i,onStart:a,onMove:o,onSessionEnd:s,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:l,distanceThreshold:n,contextWindow:yD(this.visualElement),element:this.visualElement.current})}stop(e,t){let n=e||this.latestPointerEvent,r=t||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!r||!n)return;let{velocity:a}=r;this.startAnimation(a);let{onDragEnd:o}=this.getProps();o&&Q.postRender(()=>o(n,r))}cancel(){this.isDragging=!1;let{projection:e,animationState:t}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.endPanSession();let{dragPropagation:n}=this.getProps();!n&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),t&&t.setActive(`whileDrag`,!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(e,t,n){let{drag:r}=this.getProps();if(!n||!GD(e,r,this.currentDirection))return;let i=this.getAxisMotionValue(e),a=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(a=AD(a,this.constraints[e],this.elastic[e])),i.set(a)}resolveConstraints(){let{dragConstraints:e,dragElastic:t}=this.getProps(),n=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,r=this.constraints;e&&rD(e)?this.constraints||=this.resolveRefConstraints():e&&n?this.constraints=MD(n.layoutBox,e):this.constraints=!1,this.elastic=RD(t),r!==this.constraints&&!rD(e)&&n&&this.constraints&&!this.hasMutatedConstraints&&vT(e=>{this.constraints!==!1&&this.getAxisMotionValue(e)&&(this.constraints[e]=ID(n.layoutBox[e],this.constraints[e]))})}resolveRefConstraints(){let{dragConstraints:e,onMeasureDragConstraints:t}=this.getProps();if(!e||!rD(e))return!1;let n=e.current;z_(n!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.",`drag-constraints-ref`);let{projection:r}=this.visualElement;if(!r||!r.layout)return!1;let i=sw(n,r.root,this.visualElement.getTransformPagePoint()),a=PD(r.layout.layoutBox,i);if(t){let e=t(HC(a));this.hasMutatedConstraints=!!e,e&&(a=VC(e))}return a}startAnimation(e){let{drag:t,dragMomentum:n,dragElastic:r,dragTransition:i,dragSnapToOrigin:a,onDragTransitionEnd:o}=this.getProps(),s=this.constraints||{},c=vT(o=>{if(!GD(o,t,this.currentDirection))return;let c=s&&s[o]||{};(a===!0||a===o)&&(c={min:0,max:0});let l=r?200:1e6,u=r?40:1e7,d={type:`inertia`,velocity:n?e[o]:0,bounceStiffness:l,bounceDamping:u,timeConstant:750,restDelta:1,restSpeed:10,...i,...c};return this.startAxisValueAnimation(o,d)});return Promise.all(c).then(o)}startAxisValueAnimation(e,t){let n=this.getAxisMotionValue(e);return nS(this.visualElement,e),n.start(Bx(e,n,0,t,this.visualElement,!1))}stopAnimation(){vT(e=>this.getAxisMotionValue(e).stop())}getAxisMotionValue(e){let t=`_drag${e.toUpperCase()}`,n=this.visualElement.getProps();return n[t]||this.visualElement.getValue(e,(n.initial?n.initial[e]:void 0)||0)}snapToCursor(e){vT(t=>{let{drag:n}=this.getProps();if(!GD(t,n,this.currentDirection))return;let{projection:r}=this.visualElement,i=this.getAxisMotionValue(t);if(r&&r.layout){let{min:n,max:a}=r.layout.layoutBox[t],o=i.get()||0;i.set(e[t]-Oy(n,a,.5)+o)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;let{drag:e,dragConstraints:t}=this.getProps(),{projection:n}=this.visualElement;if(!rD(t)||!n||!this.constraints)return;this.stopAnimation();let r={x:0,y:0};vT(e=>{let t=this.getAxisMotionValue(e);if(t&&this.constraints!==!1){let n=t.get();r[e]=FD({min:n,max:n},this.constraints[e])}});let{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},``):`none`,n.root&&n.root.updateScroll(),n.updateLayout(),this.constraints=!1,this.resolveConstraints(),vT(t=>{if(!GD(t,e,null))return;let n=this.getAxisMotionValue(t),{min:i,max:a}=this.constraints[t];n.set(Oy(i,a,r[t]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;VD.set(this.visualElement,this);let e=this.visualElement.current,t=vD(e,`pointerdown`,t=>{let{drag:n,dragListener:r=!0}=this.getProps(),i=t.target,a=i!==e&&KS(i);n&&r&&!a&&this.start(t)}),n,r=()=>{let{dragConstraints:t}=this.getProps();rD(t)&&t.current&&(this.constraints=this.resolveRefConstraints(),n||=WD(e,t.current,()=>this.scalePositionWithinConstraints()))},{projection:i}=this.visualElement,a=i.addEventListener(`measure`,r);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),Q.read(r);let o=AT(window,`resize`,()=>this.scalePositionWithinConstraints()),s=i.addEventListener(`didUpdate`,(({delta:e,hasLayoutChanged:t})=>{this.isDragging&&t&&(vT(t=>{let n=this.getAxisMotionValue(t);n&&(this.originPoint[t]+=e[t].translate,n.set(n.get()+e[t].translate))}),this.visualElement.render())}));return()=>{o(),t(),a(),s&&s(),n&&n()}}getProps(){let e=this.visualElement.getProps(),{drag:t=!1,dragDirectionLock:n=!1,dragPropagation:r=!1,dragConstraints:i=!1,dragElastic:a=LD,dragMomentum:o=!0}=e;return{...e,drag:t,dragDirectionLock:n,dragPropagation:r,dragConstraints:i,dragElastic:a,dragMomentum:o}}};function UD(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function WD(e,t,n){let r=mC(e,UD(n)),i=mC(t,UD(n));return()=>{r(),i()}}function GD(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function KD(e,t=10){let n=null;return Math.abs(e.y)>t?n=`y`:Math.abs(e.x)>t&&(n=`x`),n}var qD=class extends BC{constructor(e){super(e),this.removeGroupControls=G_,this.removeListeners=G_,this.controls=new HD(e)}mount(){let{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||G_}update(){let{dragControls:e}=this.node.getProps(),{dragControls:t}=this.node.prevProps||{};e!==t&&(this.removeGroupControls(),e&&(this.removeGroupControls=e.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}},JD=e=>(t,n)=>{e&&Q.update(()=>e(t,n),!1,!0)},YD=class extends BC{constructor(){super(...arguments),this.removePointerDownListener=G_}onPointerDown(e){this.session=new CD(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:yD(this.node)})}createPanHandlers(){let{onPanSessionStart:e,onPanStart:t,onPan:n,onPanEnd:r}=this.node.getProps();return{onSessionStart:JD(e),onStart:JD(t),onMove:JD(n),onEnd:(e,t)=>{delete this.session,r&&Q.postRender(()=>r(e,t))}}}mount(){this.removePointerDownListener=vD(this.node.current,`pointerdown`,e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}},XD=!1,ZD=class extends d.Component{componentDidMount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:n,layoutId:r}=this.props,{projection:i}=e;i&&(t.group&&t.group.add(i),n&&n.register&&r&&n.register(i),XD&&i.root.didUpdate(),i.addEventListener(`animationComplete`,()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),IT.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){let{layoutDependency:t,visualElement:n,drag:r,isPresent:i}=this.props,{projection:a}=n;return a?(a.isPresent=i,e.layoutDependency!==t&&a.setOptions({...a.options,layoutDependency:t}),XD=!0,r||e.layoutDependency!==t||t===void 0||e.isPresent!==i?a.willUpdate():this.safeToRemove(),e.isPresent!==i&&(i?a.promote():a.relegate()||Q.postRender(()=>{let e=a.getStack();(!e||!e.members.length)&&this.safeToRemove()})),null):null}componentDidUpdate(){let{visualElement:e,layoutAnchor:t}=this.props,{projection:n}=e;n&&(n.options.layoutAnchor=t,n.root.didUpdate(),NS.postRender(()=>{!n.currentAnimation&&n.isLead()&&this.safeToRemove()}))}componentWillUnmount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:n}=this.props,{projection:r}=e;XD=!0,r&&(r.scheduleCheckAfterUnmount(),t&&t.group&&t.group.remove(r),n&&n.deregister&&n.deregister(r))}safeToRemove(){let{safeToRemove:e}=this.props;e&&e()}render(){return null}};function QD(e){let[t,n]=bE(),r=(0,d.useContext)(A_);return(0,f.jsx)(ZD,{...e,layoutGroup:r,switchLayoutGroup:(0,d.useContext)(nD),isPresent:t,safeToRemove:n})}var $D={pan:{Feature:YD},drag:{Feature:qD,ProjectionNode:vE,MeasureLayout:QD}};function eO(e,t,n){let{props:r}=e;e.animationState&&r.whileHover&&e.animationState.setActive(`whileHover`,n===`Start`);let i=r[`onHover`+n];i&&Q.postRender(()=>i(t,gD(t)))}var tO=class extends BC{mount(){let{current:e}=this.node;e&&(this.unmount=BS(e,(e,t)=>(eO(this.node,t,`Start`),e=>eO(this.node,e,`End`))))}unmount(){}},nO=class extends BC{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(`:focus-visible`)}catch{e=!0}!e||!this.node.animationState||(this.node.animationState.setActive(`whileFocus`,!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive(`whileFocus`,!1),this.isActive=!1)}mount(){this.unmount=q_(AT(this.node.current,`focus`,()=>this.onFocus()),AT(this.node.current,`blur`,()=>this.onBlur()))}unmount(){}};function rO(e,t,n){let{props:r}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&r.whileTap&&e.animationState.setActive(`whileTap`,n===`Start`);let i=r[`onTap`+(n===`End`?``:n)];i&&Q.postRender(()=>i(t,gD(t)))}var iO=class extends BC{mount(){let{current:e}=this.node;if(!e)return;let{globalTapTarget:t,propagate:n}=this.node.props;this.unmount=$S(e,(e,t)=>(rO(this.node,t,`Start`),(e,{success:t})=>rO(this.node,e,t?`End`:`Cancel`)),{useGlobalTarget:t,stopPropagation:n?.tap===!1})}unmount(){}},aO=new WeakMap,oO=new WeakMap,sO=e=>{let t=aO.get(e.target);t&&t(e)},cO=e=>{e.forEach(sO)};function lO({root:e,...t}){let n=e||document;oO.has(n)||oO.set(n,{});let r=oO.get(n),i=JSON.stringify(t);return r[i]||(r[i]=new IntersectionObserver(cO,{root:e,...t})),r[i]}function uO(e,t,n){let r=lO(t);return aO.set(e,n),r.observe(e),()=>{aO.delete(e),r.unobserve(e)}}var dO={some:0,all:1},fO=class extends BC{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.stopObserver?.();let{viewport:e={}}=this.node.getProps(),{root:t,margin:n,amount:r=`some`,once:i}=e,a={root:t?t.current:void 0,rootMargin:n,threshold:typeof r==`number`?r:dO[r]};this.stopObserver=uO(this.node.current,a,e=>{let{isIntersecting:t}=e;if(this.isInView===t||(this.isInView=t,i&&!t&&this.hasEnteredView))return;t&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive(`whileInView`,t);let{onViewportEnter:n,onViewportLeave:r}=this.node.getProps(),a=t?n:r;a&&a(e)})}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>`u`)return;let{props:e,prevProps:t}=this.node;[`amount`,`margin`,`root`].some(pO(e,t))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}};function pO({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}var mO={inView:{Feature:fO},tap:{Feature:iO},focus:{Feature:nO},hover:{Feature:tO}},hO={layout:{ProjectionNode:vE,MeasureLayout:QD}},gO=dD({...hD,...mO,...$D,...hO},fD),_O=({size:e=18,color:t=`currentColor`})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:t}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`,stroke:t,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),vO=({size:e=20})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,f.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),yO=({size:e=18})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,f.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),bO=()=>(0,f.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,f.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),xO=()=>(0,f.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`path`,{d:`M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.42 19.42 0 01-6.12-6.11A19.79 19.79 0 012 4.11 2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.37 1.91.71 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.9.34 1.85.58 2.81.71A2 2 0 0122 16.92z`})}),SO=({className:e=``})=>(0,f.jsxs)(`svg`,{className:e,width:`14`,height:`14`,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:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,f.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),CO=({size:e=14})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 8V4H8`}),(0,f.jsx)(`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`}),(0,f.jsx)(`path`,{d:`M2 14h2`}),(0,f.jsx)(`path`,{d:`M20 14h2`}),(0,f.jsx)(`path`,{d:`M15 13v2`}),(0,f.jsx)(`path`,{d:`M9 13v2`})]}),wO=({size:e=20,strokeWidth:t=2,color:n=`currentColor`})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:n,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`12`,y1:`5`,x2:`12`,y2:`19`}),(0,f.jsx)(`line`,{x1:`5`,y1:`12`,x2:`19`,y2:`12`})]}),TO=({size:e=20,color:t=`currentColor`})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`,fill:t}),(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`,fill:t}),(0,f.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`,fill:t})]}),EO=({size:e=20,color:t=`currentColor`})=>(0,f.jsxs)(`svg`,{width:`24`,height:`24`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`path`,{d:`M22 11.5667C22 16.8499 17.5222 21.1334 12 21.1334C11.3507 21.1343 10.7032 21.0742 10.0654 20.9545C9.60633 20.8682 9.37678 20.8251 9.21653 20.8496C9.05627 20.8741 8.82918 20.9948 8.37499 21.2364C7.09014 21.9197 5.59195 22.161 4.15111 21.893C4.69874 21.2194 5.07275 20.4112 5.23778 19.5448C5.33778 19.0148 5.09 18.5 4.71889 18.1231C3.03333 16.4115 2 14.1051 2 11.5667C2 6.28357 6.47778 2 12 2C17.5222 2 22 6.28357 22 11.5667Z`,stroke:`white`,"stroke-width":`1.5`,"stroke-linejoin":`round`}),(0,f.jsx)(`path`,{d:`M11.9955 12H12.0045M15.991 12H16M8 12H8.00897`,stroke:`white`,"stroke-width":`2`,"stroke-linecap":`round`,"stroke-linejoin":`round`})]}),DO=()=>(0,f.jsx)(`svg`,{width:`24`,height:`24`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,f.jsx)(`path`,{d:`M16.7133 8.59374C18.1939 8.98463 19.2229 9.47922 20.1589 10.0848C21.5432 10.9804 22.1367 12.5944 21.9737 14.1517C21.9049 14.8099 21.3744 15.1246 20.7592 14.9544L19.3705 14.57C18.2697 14.2653 17.7193 14.1129 17.3837 13.71C17.0481 13.307 17.0086 12.751 16.9296 11.6391L16.7133 8.59374ZM16.7133 8.59374C13.7164 7.80255 10.2871 7.80163 7.28669 8.59374M7.28669 8.59374C5.80606 8.98463 4.77711 9.47923 3.84113 10.0848C2.45683 10.9804 1.86334 12.5944 2.02628 14.1517C2.09514 14.8099 2.62563 15.1246 3.24078 14.9544L4.62954 14.57C5.73032 14.2653 6.28071 14.1129 6.61631 13.71C6.95191 13.307 6.9914 12.751 7.07038 11.6391L7.28669 8.59374Z`,stroke:`#E30C12`,"stroke-width":`1.5`,"stroke-linejoin":`round`})}),OO=({size:e=24})=>(0,f.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 19v3`}),(0,f.jsx)(`path`,{d:`M15 9.34V5a3 3 0 0 0-5.68-1.33`}),(0,f.jsx)(`path`,{d:`M16.95 16.95A7 7 0 0 1 5 12v-2`}),(0,f.jsx)(`path`,{d:`M18.89 13.23A7 7 0 0 0 19 12v-2`}),(0,f.jsx)(`path`,{d:`m2 2 20 20`}),(0,f.jsx)(`path`,{d:`M9 9v3a3 3 0 0 0 5.12 2.12`})]}),kO=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),AO=(e=``)=>String(e).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`),jO=new Set([`p`,`br`,`ul`,`ol`,`li`,`strong`,`em`,`b`,`i`,`a`]),MO=/^https?:\/\//i;function NO(e){let t=Array.from(e.childNodes);for(let n of t)if(n.nodeType===Node.ELEMENT_NODE){let t=n.tagName.toLowerCase();if(!jO.has(t)){e.replaceChild(document.createTextNode(n.textContent),n);continue}let r={};if(t===`a`){let e=n.getAttribute(`href`)||``;MO.test(e)&&(r.href=e),r.target=`_blank`,r.rel=`noopener noreferrer`}for(;n.attributes.length>0;)n.removeAttribute(n.attributes[0].name);for(let[e,t]of Object.entries(r))n.setAttribute(e,t);NO(n)}else n.nodeType!==Node.TEXT_NODE&&e.removeChild(n)}function PO(e){let t=document.createElement(`div`);return t.innerHTML=e,NO(t),t.innerHTML}function FO(e){let t=String(e||``).trim();if(!t)return t;let n=/^<p>\s*<strong>([\s\S]*?)<\/strong>\s*<\/p>$/i.exec(t);if(n&&!/<\/?strong\b/i.test(n[1]))return`<p>${n[1]}</p>`;let r=/^<strong>([\s\S]*?)<\/strong>$/i.exec(t);if(r&&!/<\/?strong\b/i.test(r[1])){let e=r[1].trim();return/^<(?:p|ul|ol)\b/i.test(e)?e:`<p>${e}</p>`}return e}var IO=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return FO(PO(t));let n=t.replace(/\r\n/g,`
|
|
330
|
+
`),uD,dD;(function(e){e.PCM_8000=`pcm_8000`,e.PCM_16000=`pcm_16000`,e.PCM_22050=`pcm_22050`,e.PCM_24000=`pcm_24000`,e.PCM_44100=`pcm_44100`,e.PCM_48000=`pcm_48000`,e.ULAW_8000=`ulaw_8000`})(uD||={}),function(e){e.MANUAL=`manual`,e.VAD=`vad`}(dD||={});var fD=class e{static getWebSocketUri(t=e.DEFAULT_BASE_URI){return`${t}/v1/speech-to-text/realtime`}static buildWebSocketUri(t){let n=e.getWebSocketUri(t.baseUri),r=new URLSearchParams;if(r.append(`model_id`,t.modelId),r.append(`token`,t.token),t.commitStrategy!==void 0&&r.append(`commit_strategy`,t.commitStrategy),t.audioFormat!==void 0&&r.append(`audio_format`,t.audioFormat),t.vadSilenceThresholdSecs!==void 0){if(t.vadSilenceThresholdSecs<=.3||t.vadSilenceThresholdSecs>3)throw Error(`vadSilenceThresholdSecs must be between 0.3 and 3.0`);r.append(`vad_silence_threshold_secs`,t.vadSilenceThresholdSecs.toString())}if(t.vadThreshold!==void 0){if(t.vadThreshold<.1||t.vadThreshold>.9)throw Error(`vadThreshold must be between 0.1 and 0.9`);r.append(`vad_threshold`,t.vadThreshold.toString())}if(t.minSpeechDurationMs!==void 0){if(t.minSpeechDurationMs<=50||t.minSpeechDurationMs>2e3)throw Error(`minSpeechDurationMs must be between 50 and 2000`);r.append(`min_speech_duration_ms`,t.minSpeechDurationMs.toString())}if(t.minSilenceDurationMs!==void 0){if(t.minSilenceDurationMs<=50||t.minSilenceDurationMs>2e3)throw Error(`minSilenceDurationMs must be between 50 and 2000`);r.append(`min_silence_duration_ms`,t.minSilenceDurationMs.toString())}t.languageCode!==void 0&&r.append(`language_code`,t.languageCode),t.includeTimestamps!==void 0&&r.append(`include_timestamps`,t.includeTimestamps?`true`:`false`);let i=r.toString();return i?`${n}?${i}`:n}static connect(t){if(!t.modelId)throw Error(`modelId is required`);let n=new cD(`microphone`in t&&t.microphone?16e3:t.sampleRate),r=e.buildWebSocketUri(t),i=new WebSocket(r);return`microphone`in t&&t.microphone&&i.addEventListener(`open`,()=>{e.streamFromMicrophone(t,n)}),n.setWebSocket(i),n}static async streamFromMicrophone(e,t){try{var n,r,i;let a=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e.microphone?.deviceId,echoCancellation:(n=e.microphone?.echoCancellation)==null||n,noiseSuppression:(r=e.microphone?.noiseSuppression)==null||r,autoGainControl:(i=e.microphone?.autoGainControl)==null||i,channelCount:e.microphone?.channelCount??1,sampleRate:{ideal:16e3}}}),o=new AudioContext({sampleRate:16e3});await lD(o.audioWorklet);let s=o.createMediaStreamSource(a),c=new AudioWorkletNode(o,`scribeAudioProcessor`);c.port.onmessage=e=>{let{audioData:n}=e.data,r=new Uint8Array(n),i=``;for(let e=0;e<r.length;e++)i+=String.fromCharCode(r[e]);let a=btoa(i);t.send({audioBase64:a})},s.connect(c),o.state===`suspended`&&await o.resume(),t._audioCleanup=()=>{a.getTracks().forEach(e=>{e.stop()}),s.disconnect(),c.disconnect(),o.close()}}catch(e){throw console.error(`Failed to start microphone streaming:`,e),e}}};fD.DEFAULT_BASE_URI=`wss://api.elevenlabs.io`;var pD=class extends RE{static startSession(e){return e.textOnly?tD.startSession(e):oD.startSession(e)}},mD=({size:e=18,color:t=`currentColor`})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:t}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`,stroke:t,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),hD=({size:e=20})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,f.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),gD=({size:e=18})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,f.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),_D=()=>(0,f.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,f.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),vD=()=>(0,f.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`path`,{d:`M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.42 19.42 0 01-6.12-6.11A19.79 19.79 0 012 4.11 2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.37 1.91.71 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.9.34 1.85.58 2.81.71A2 2 0 0122 16.92z`})}),yD=({className:e=``})=>(0,f.jsxs)(`svg`,{className:e,width:`14`,height:`14`,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:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,f.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),bD=({size:e=14})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 8V4H8`}),(0,f.jsx)(`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`}),(0,f.jsx)(`path`,{d:`M2 14h2`}),(0,f.jsx)(`path`,{d:`M20 14h2`}),(0,f.jsx)(`path`,{d:`M15 13v2`}),(0,f.jsx)(`path`,{d:`M9 13v2`})]}),xD=({size:e=20,strokeWidth:t=2,color:n=`currentColor`})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:n,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`12`,y1:`5`,x2:`12`,y2:`19`}),(0,f.jsx)(`line`,{x1:`5`,y1:`12`,x2:`19`,y2:`12`})]}),SD=({size:e=20,color:t=`currentColor`})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`,fill:t}),(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`,fill:t}),(0,f.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`,fill:t})]}),CD=({size:e=20,color:t=`currentColor`})=>(0,f.jsxs)(`svg`,{width:`24`,height:`24`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`path`,{d:`M22 11.5667C22 16.8499 17.5222 21.1334 12 21.1334C11.3507 21.1343 10.7032 21.0742 10.0654 20.9545C9.60633 20.8682 9.37678 20.8251 9.21653 20.8496C9.05627 20.8741 8.82918 20.9948 8.37499 21.2364C7.09014 21.9197 5.59195 22.161 4.15111 21.893C4.69874 21.2194 5.07275 20.4112 5.23778 19.5448C5.33778 19.0148 5.09 18.5 4.71889 18.1231C3.03333 16.4115 2 14.1051 2 11.5667C2 6.28357 6.47778 2 12 2C17.5222 2 22 6.28357 22 11.5667Z`,stroke:`white`,"stroke-width":`1.5`,"stroke-linejoin":`round`}),(0,f.jsx)(`path`,{d:`M11.9955 12H12.0045M15.991 12H16M8 12H8.00897`,stroke:`white`,"stroke-width":`2`,"stroke-linecap":`round`,"stroke-linejoin":`round`})]}),wD=()=>(0,f.jsx)(`svg`,{width:`24`,height:`24`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,f.jsx)(`path`,{d:`M16.7133 8.59374C18.1939 8.98463 19.2229 9.47922 20.1589 10.0848C21.5432 10.9804 22.1367 12.5944 21.9737 14.1517C21.9049 14.8099 21.3744 15.1246 20.7592 14.9544L19.3705 14.57C18.2697 14.2653 17.7193 14.1129 17.3837 13.71C17.0481 13.307 17.0086 12.751 16.9296 11.6391L16.7133 8.59374ZM16.7133 8.59374C13.7164 7.80255 10.2871 7.80163 7.28669 8.59374M7.28669 8.59374C5.80606 8.98463 4.77711 9.47923 3.84113 10.0848C2.45683 10.9804 1.86334 12.5944 2.02628 14.1517C2.09514 14.8099 2.62563 15.1246 3.24078 14.9544L4.62954 14.57C5.73032 14.2653 6.28071 14.1129 6.61631 13.71C6.95191 13.307 6.9914 12.751 7.07038 11.6391L7.28669 8.59374Z`,stroke:`#E30C12`,"stroke-width":`1.5`,"stroke-linejoin":`round`})}),TD=({size:e=24})=>(0,f.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 19v3`}),(0,f.jsx)(`path`,{d:`M15 9.34V5a3 3 0 0 0-5.68-1.33`}),(0,f.jsx)(`path`,{d:`M16.95 16.95A7 7 0 0 1 5 12v-2`}),(0,f.jsx)(`path`,{d:`M18.89 13.23A7 7 0 0 0 19 12v-2`}),(0,f.jsx)(`path`,{d:`m2 2 20 20`}),(0,f.jsx)(`path`,{d:`M9 9v3a3 3 0 0 0 5.12 2.12`})]}),ED=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),DD=(e=``)=>String(e).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`),OD=new Set([`p`,`br`,`ul`,`ol`,`li`,`strong`,`em`,`b`,`i`,`a`]),kD=/^https?:\/\//i;function AD(e){let t=Array.from(e.childNodes);for(let n of t)if(n.nodeType===Node.ELEMENT_NODE){let t=n.tagName.toLowerCase();if(!OD.has(t)){e.replaceChild(document.createTextNode(n.textContent),n);continue}let r={};if(t===`a`){let e=n.getAttribute(`href`)||``;kD.test(e)&&(r.href=e),r.target=`_blank`,r.rel=`noopener noreferrer`}for(;n.attributes.length>0;)n.removeAttribute(n.attributes[0].name);for(let[e,t]of Object.entries(r))n.setAttribute(e,t);AD(n)}else n.nodeType!==Node.TEXT_NODE&&e.removeChild(n)}function jD(e){let t=document.createElement(`div`);return t.innerHTML=e,AD(t),t.innerHTML}function MD(e){let t=String(e||``).trim();if(!t)return t;let n=/^<p>\s*<strong>([\s\S]*?)<\/strong>\s*<\/p>$/i.exec(t);if(n&&!/<\/?strong\b/i.test(n[1]))return`<p>${n[1]}</p>`;let r=/^<strong>([\s\S]*?)<\/strong>$/i.exec(t);if(r&&!/<\/?strong\b/i.test(r[1])){let e=r[1].trim();return/^<(?:p|ul|ol)\b/i.test(e)?e:`<p>${e}</p>`}return e}var ND=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return MD(jD(t));let n=t.replace(/\r\n/g,`
|
|
483
331
|
`).replace(/\n{3,}/g,`
|
|
484
332
|
|
|
485
|
-
`).split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean),r=e=>
|
|
486
|
-
`).map(e=>e.trim()).filter(Boolean),n=t.filter(e=>/^[-*]\s+/.test(e));if(n.length>=2&&n.length===t.length)return`<ul>${n.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`;let i=e.split(/\s+(?=[-*]\s+\*\*?)/).map(e=>e.trim()).filter(Boolean);return i.length>=2&&i.every(e=>/^[-*]\s+/.test(e))?`<ul>${i.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`:`<p>${r(e).replace(/\n/g,`<br />`)}</p>`}).join(``))},LO=new Set([`application/pdf`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`]),RO=new Set([`.pdf`,`.docx`,`.png`,`.jpg`,`.jpeg`]),zO=`image/png,image/jpeg,.pdf,.docx`;function BO(e){if(!e)return!1;let t=typeof e.name==`string`?e.name.toLowerCase():``,n=t.includes(`.`)?`.${t.split(`.`).pop()}`:``,r=typeof e.type==`string`?e.type.toLowerCase():``;return r===`image/png`||r===`image/jpeg`||LO.has(r)||RO.has(n)}function VO(e){return e?BO(e)?e.size>2097152?`File must be 2 MB or smaller.`:``:`Only PNG, JPEG, PDF, and DOCX files are allowed.`:`No file selected.`}function HO(e=0){if(!Number.isFinite(e)||e<=0)return``;let t=[`B`,`KB`,`MB`,`GB`],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;let i=n>=10||r===0?0:1;return`${n.toFixed(i)} ${t[r]}`}function UO(e){return e?e.name||`Attachment`:``}function WO(e){if(!e||typeof e!=`string`)return`?`;let t=e.trim();if(!t)return`?`;let n=t.split(/\s+/).filter(Boolean);return n.length>=2?`${n[0][0]}${n[n.length-1][0]}`.toUpperCase():t.slice(0,2).toUpperCase()}function GO({src:e,name:t,imgStyle:n,initialsSpanStyle:r}){let[i,a]=(0,d.useState)(null),o=typeof e==`string`?e.trim():``;return(0,d.useEffect)(()=>{if(!o){a(null);return}a(null);let e=!1,t=new window.Image;return t.onload=()=>{e||a(o)},t.onerror=()=>{e||a(null)},t.src=o,()=>{e=!0}},[o]),i?(0,f.jsx)(`img`,{src:i,alt:``,style:n,onError:()=>a(null)}):(0,f.jsx)(`span`,{style:r,children:WO(t)})}function KO({chatHistory:e,isAiTyping:t,isLoading:n,isAgentTyping:r,setReplyContext:i,primaryColor:a=`#3B82F6`,agentHeadshot:o=null,agentDisplayName:s=`Agent`,botAvatarNode:c=null}){let{resolvedConfig:l,language:u}=x_(),p=(0,d.useRef)(null),[m,h]=(0,d.useState)(null),[g,_]=(0,d.useState)(null),v=(0,d.useRef)(e.length),y=(0,d.useRef)(!0),b=(0,d.useRef)(null),x=(0,d.useCallback)(e=>{let t=e.target.closest(`a[href]`);if(!t)return;let n=t.getAttribute(`href`)||``;if(!(!n||n.startsWith(`mailto:`)||n.startsWith(`tel:`)||n.startsWith(`javascript:`)))try{let t=new URL(n,window.location.href);if(t.origin!==window.location.origin){e.preventDefault(),window.open(t.href,`_blank`,`noopener,noreferrer`);return}e.preventDefault(),eg(t.href,{siteId:l?.siteId,apiBaseUrl:l?.apiBaseUrl}).then(e=>{e&&og(t.href)})}catch{}},[l]),S=u===`de`,ee=e=>{if(!e)return S?`gerade eben`:`just now`;let t=new Date,n=new Date(e),r=Math.max(0,Math.floor((t-n)/1e3));if(r<60)return S?`gerade eben`:`just now`;let i=Math.floor(r/60);if(i<60)return S?`vor ${i} Min.`:`${i} min${i>1?`s`:``} ago`;let a=Math.floor(i/60);if(a<24)return S?`vor ${a} Std.`:`${a} hr${a>1?`s`:``} ago`;let o=Math.floor(a/24);return S?`vor ${o} ${o>1?`Tagen`:`Tag`}`:`${o} day${o>1?`s`:``} ago`};return(0,d.useEffect)(()=>{if(y.current){y.current=!1,v.current=e.length,b.current&&(b.current.scrollTop=b.current.scrollHeight);return}let n=e.length>v.current;v.current=e.length,(n||t||r)&&p.current?.scrollIntoView({behavior:`smooth`})},[e.length,t,n,r]),(0,f.jsxs)(`div`,{ref:b,style:{flex:1,overflowY:`auto`,overscrollBehavior:`contain`,padding:`10px 16px 20px`,display:`flex`,flexDirection:`column`,background:`transparent`},children:[e.map(e=>{if(e.type===`call_recording`||typeof e.message==`string`&&e.message.includes(`AI chat recording`))return null;let t=e.sender===`system`,n=e.sender===`user`,r=e.sender===`ai`||e.sender===`bot`,l=e.sender===`agent`,u=e.isPending,d=e.type===`file`&&e.metadata?.fileUrl,p=e.agent_name||e.agentName||e.metadata?.agentName||s,m=typeof e.sender_headshot==`string`&&e.sender_headshot.trim()||typeof o==`string`&&o.trim()||null,v=kO(e.replyToContent||e.replyContext?.message||``),y=e.replyToSender===`user`?`You`:e.replyToSender===`agent`?`Agent`:e.replyToSender===`ai`||e.replyToSender===`bot`?`AI Assistant`:`Message`;return t?(0,f.jsx)(`div`,{style:{display:`flex`,justifyContent:`center`,margin:`8px 0`},children:(0,f.jsx)(`div`,{style:{padding:`6px 12px`,borderRadius:`9999px`,background:`#f3f4f6`,color:`#6b7280`,fontSize:`12px`,fontWeight:500},children:e.message})},e.id):(0,f.jsxs)(`div`,{style:{display:`flex`,justifyContent:n?`flex-end`:`flex-start`,alignItems:`flex-start`,marginBottom:`16px`,gap:`8px`,flexDirection:`row`},children:[!n&&(r||l)&&(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,background:l?`#f3f4f6`:c&&r?`transparent`:`var(--flowengage-primary)`,color:l?a:`#fff`,boxShadow:l?`0 2px 8px rgba(0,0,0,0.06)`:c&&r?`none`:`0 8px 20px rgba(59,130,246,0.24)`,overflow:`hidden`,border:l?`1px solid ${a}22`:`none`,fontSize:`12px`,fontWeight:800,marginTop:!u&&(r||l)?`22px`:`0px`},children:r?c||(0,f.jsx)(CO,{size:16}):(0,f.jsx)(GO,{src:m||``,name:p,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}),(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:n?`flex-end`:`flex-start`,maxWidth:`75%`,minWidth:0},children:[!u&&l&&(0,f.jsxs)(`button`,{type:`button`,onClick:()=>i(e),style:{opacity:1,marginBottom:`4px`,display:`flex`,alignItems:`center`,gap:`4px`,fontSize:`11px`,color:`#9ca3af`,background:`transparent`,border:0,cursor:`pointer`,padding:0,marginLeft:`2px`},onMouseEnter:e=>{e.currentTarget.style.color=`#4b5563`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:[(0,f.jsx)(bO,{}),`Reply`]}),(0,f.jsxs)(`div`,{style:{padding:`8px 16px`,borderRadius:n?`20px 6px 20px 20px`:`6px 20px 20px 20px`,lineHeight:1.8,letterSpacing:0,boxShadow:`0 2px 8px rgba(0,0,0,0.06)`,background:n?`var(--flowengage-primary)`:`rgba(255,255,255,0.92)`,color:n?`#fff`:`#111827`,fontSize:`14px`,fontWeight:400,opacity:u?.55:1,transition:`opacity 0.3s ease`,wordBreak:`break-word`,width:`fit-content`},children:[v&&(0,f.jsxs)(`div`,{style:{marginBottom:`8px`,borderRadius:`14px`,borderLeft:n?`2px solid rgba(255,255,255,0.8)`:`2px solid var(--flowengage-primary)`,padding:`8px 12px`,fontSize:`12px`,background:n?`rgba(255,255,255,0.15)`:`#f9fafb`,color:n?`rgba(255,255,255,0.9)`:`#6b7280`},children:[(0,f.jsx)(`div`,{style:{marginBottom:`2px`,fontWeight:600},children:y}),(0,f.jsx)(`div`,{style:{display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,overflow:`hidden`},children:v})]}),d?(()=>{let t=e.metadata.fileType||``,r=e.metadata.fileName||e.message||`File`,i=HO(e.metadata.fileSize),a=t.startsWith(`image/`),o=`shared file: ${r}`.toLowerCase(),s=(e.message||``).trim(),c=s&&s.toLowerCase()!==o&&!s.toLowerCase().startsWith(`shared file:`),l=t===`application/pdf`?{color:`#ef4444`,label:`PDF`}:t.includes(`word`)||t.includes(`docx`)?{color:`#3b82f6`,label:`DOCX`}:t.includes(`excel`)||t.includes(`sheet`)||t===`text/csv`?{color:`#10b981`,label:`XLSX`}:{color:`#6b7280`,label:`FILE`};return(0,f.jsxs)(`div`,{style:{minWidth:`200px`,maxWidth:`240px`},children:[c&&(0,f.jsx)(`div`,{style:{marginBottom:`6px`,fontSize:`14px`,color:n?`#fff`:`#111827`,whiteSpace:`normal`,wordBreak:`break-word`},children:s}),a?(0,f.jsx)(`button`,{type:`button`,onClick:()=>h({url:e.metadata.fileUrl,name:r}),onMouseEnter:()=>_(e.id),onMouseLeave:()=>_(null),style:{display:`block`,width:`100%`,background:`transparent`,border:0,padding:0,margin:0,textAlign:`left`,cursor:`pointer`},children:(0,f.jsxs)(`div`,{style:{position:`relative`},children:[(0,f.jsx)(`img`,{src:e.metadata.fileUrl,alt:r,style:{width:`100%`,borderRadius:`10px`,display:`block`,maxHeight:`180px`,objectFit:`cover`}}),(0,f.jsx)(`div`,{style:{position:`absolute`,inset:0,borderRadius:`10px`,background:g===e.id?`rgba(17,24,39,0.32)`:`rgba(17,24,39,0)`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`#fff`,fontSize:`13px`,fontWeight:700,letterSpacing:`0.02em`,opacity:g===e.id?1:0,transition:`background 0.18s ease, opacity 0.18s ease`,pointerEvents:`none`},children:`Preview`})]})}):(0,f.jsx)(`a`,{href:e.metadata.fileUrl,target:`_blank`,rel:`noopener noreferrer`,style:{textDecoration:`none`,display:`block`},children:(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`10px`,background:n?`rgba(255,255,255,0.15)`:`#f3f4f6`,borderRadius:`12px`,padding:`10px 12px`},children:[(0,f.jsxs)(`div`,{style:{width:`38px`,height:`46px`,borderRadius:`8px`,background:n?`rgba(255,255,255,0.22)`:`#fff`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flexShrink:0,boxShadow:`0 1px 4px rgba(0,0,0,0.1)`,gap:`3px`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:n?`#fff`:l.color,strokeWidth:`1.8`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z`}),(0,f.jsx)(`polyline`,{points:`14 2 14 8 20 8`})]}),(0,f.jsx)(`span`,{style:{fontSize:`7px`,fontWeight:800,letterSpacing:`0.04em`,color:n?`#fff`:l.color,lineHeight:1},children:l.label})]}),(0,f.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(`div`,{style:{fontSize:`13px`,fontWeight:600,color:n?`#fff`:`#111827`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:r}),i&&(0,f.jsx)(`div`,{style:{fontSize:`11px`,marginTop:`3px`,color:n?`rgba(255,255,255,0.6)`:`#9ca3af`},children:i})]}),(0,f.jsxs)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,stroke:n?`rgba(255,255,255,0.65)`:`#9ca3af`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:[(0,f.jsx)(`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`}),(0,f.jsx)(`polyline`,{points:`7 10 12 15 17 10`}),(0,f.jsx)(`line`,{x1:`12`,y1:`15`,x2:`12`,y2:`3`})]})]})})]})})():r?(0,f.jsx)(`div`,{className:`flowengage-message-content fe-bot-message`,dangerouslySetInnerHTML:{__html:IO(e.message)},onClick:x}):(0,f.jsx)(`div`,{style:{whiteSpace:n||l?`normal`:`pre-wrap`},children:e.message})]}),(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`,marginTop:`4px`,padding:`0 4px`,alignSelf:n?`flex-end`:`flex-start`},children:u?(0,f.jsx)(`span`,{style:{fontSize:`10px`,color:`#9ca3af`,fontWeight:500,fontStyle:`italic`},children:`sending…`}):(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(`span`,{style:{fontSize:`10px`,color:`#9ca3af`,fontWeight:500},children:ee(e.timestamp||e.createdAt)}),(0,f.jsx)(`span`,{style:{fontSize:`10px`,fontWeight:700,color:n?`var(--flowengage-primary)`:`#9ca3af`},children:`✓`})]})})]})]},e.id)}),(t||n)&&(0,f.jsxs)(`div`,{style:{marginBottom:`16px`,display:`flex`,alignItems:`center`,gap:`8px`},children:[(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,background:c?`transparent`:`var(--flowengage-primary)`,color:`#fff`,boxShadow:c?`none`:`0 8px 20px rgba(59,130,246,0.24)`,overflow:`hidden`},children:c||(0,f.jsx)(CO,{size:16})}),(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`2px`,color:`#374151`,fontSize:`13px`,fontWeight:500,fontStyle:`italic`},children:[`Analysing`,[0,1,2].map(e=>(0,f.jsx)(`span`,{style:{animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`},children:`.`},e))]})]}),r&&(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`flex-start`,gap:`8px`,marginBottom:`12px`},children:[(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,overflow:`hidden`},children:(0,f.jsx)(GO,{src:o||``,name:s,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}),(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))})]}),(0,f.jsx)(`div`,{ref:p}),m&&(0,f.jsx)(`button`,{type:`button`,onClick:()=>h(null),style:{position:`fixed`,inset:0,zIndex:1e4,border:0,padding:`16px`,margin:0,background:`rgba(2,6,23,0.88)`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`default`},children:(0,f.jsxs)(`div`,{style:{position:`relative`,maxWidth:`min(96vw, 1100px)`,maxHeight:`96vh`,width:`100%`,display:`flex`,flexDirection:`column`,gap:`10px`,alignItems:`center`},children:[(0,f.jsx)(`img`,{src:m.url,alt:m.name,style:{width:`100%`,maxHeight:`calc(96vh - 72px)`,objectFit:`contain`,borderRadius:`16px`,boxShadow:`0 30px 80px rgba(0,0,0,0.42)`}}),(0,f.jsx)(`div`,{style:{maxWidth:`100%`,padding:`8px 14px`,borderRadius:`9999px`,background:`rgba(255,255,255,0.92)`,color:`#0f172a`,fontSize:`12px`,fontWeight:600,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:m.name})]})})]})}function qO({input:e,setInput:t,onSubmit:n,isConversationEnded:r,callUiActive:i,handleToggleVoice:a,activeScreen:o,inputDisabled:s,replyContext:c,clearReplyContext:l,requiresEmail:u,emailInput:p,setEmailInput:m,emailError:h,showVoiceToggle:g=!1,voiceEnabled:_=!0,onFileSelect:v,selectedFile:y=null,onRemoveSelectedFile:b,attachmentError:x=``,isUploadingAttachment:S=!1,inputPlaceholder:ee=`Type your message`}){let te=(0,d.useRef)(null),ne=c?.sender===`user`?`You`:c?.sender===`agent`?`Agent`:`AI Assistant`,re=u?!!p?.trim():!!e?.trim()||!!y,C=s||S||!re,ie=!u&&_&&g;return(0,f.jsxs)(`div`,{style:{padding:`0 16px`,background:`transparent`},children:[c&&(0,f.jsxs)(`div`,{style:{marginBottom:`8px`,display:`flex`,alignItems:`flex-start`,justifyContent:`space-between`,gap:`12px`,borderRadius:`16px`,border:`1px solid rgba(0,0,0,0.05)`,background:`#fff`,padding:`12px 16px`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`},children:[(0,f.jsxs)(`div`,{style:{minWidth:0,flex:1,borderLeft:`2px solid var(--flowengage-primary)`,paddingLeft:`12px`},children:[(0,f.jsxs)(`div`,{style:{fontSize:`12px`,fontWeight:600,color:`var(--flowengage-primary)`},children:[`Replying to `,ne]}),(0,f.jsx)(`div`,{style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`,fontSize:`12px`,color:`#6b7280`},children:c.replyToContent||c.message})]}),(0,f.jsx)(`button`,{type:`button`,style:{width:`28px`,height:`28px`,borderRadius:`9999px`,border:0,background:`#f3f4f6`,color:`#6b7280`,transition:`color 0.2s ease, background 0.2s ease`,cursor:`pointer`},onClick:l,"aria-label":`Cancel reply`,onMouseEnter:e=>{e.currentTarget.style.background=`#e5e7eb`,e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.background=`#f3f4f6`,e.currentTarget.style.color=`#6b7280`},children:`×`})]}),u&&(0,f.jsx)(`div`,{style:{marginBottom:`8px`,padding:`0 8px`},children:(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,color:`#111827`,fontSize:`14px`,fontWeight:500,textAlign:`center`},children:[(0,f.jsx)(`span`,{style:{display:`inline-flex`,width:`22px`,height:`22px`,borderRadius:`9999px`,alignItems:`center`,justifyContent:`center`,background:`rgba(59,130,246,0.08)`,color:`var(--flowengage-primary)`},children:(0,f.jsx)(CO,{size:13})}),(0,f.jsx)(`span`,{children:`Please provide your email address so we can help you.`})]})}),y&&!u&&(0,f.jsxs)(`div`,{style:{marginBottom:`10px`,display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`12px`,borderRadius:`16px`,border:`1px solid rgba(0,0,0,0.06)`,background:`#fff`,padding:`12px 14px`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`},children:[(0,f.jsxs)(`div`,{style:{minWidth:0,flex:1},children:[(0,f.jsx)(`div`,{style:{fontSize:`12px`,fontWeight:600,color:`var(--flowengage-primary)`,marginBottom:`2px`},children:`Attachment ready`}),(0,f.jsx)(`div`,{style:{fontSize:`13px`,color:`#111827`,whiteSpace:`nowrap`,overflow:`hidden`,textOverflow:`ellipsis`},children:UO(y)}),(0,f.jsx)(`div`,{style:{fontSize:`12px`,color:`#6b7280`,marginTop:`2px`},children:HO(y.size)})]}),(0,f.jsx)(`button`,{type:`button`,style:{width:`28px`,height:`28px`,borderRadius:`9999px`,border:0,background:`#f3f4f6`,color:`#6b7280`,transition:`color 0.2s ease, background 0.2s ease`,cursor:`pointer`,flexShrink:0},onClick:b,"aria-label":`Remove attachment`,onMouseEnter:e=>{e.currentTarget.style.background=`#e5e7eb`,e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.background=`#f3f4f6`,e.currentTarget.style.color=`#6b7280`},children:`×`})]}),(0,f.jsxs)(`form`,{style:{display:`flex`,alignItems:`center`,gap:`8px`,height:`40px`,padding:`4px`,border:`1px solid rgba(0,0,0,0.06)`,borderRadius:`9999px`,background:`#fff`,boxShadow:`0 4px 14px rgba(0,0,0,0.04)`,opacity:1},onSubmit:n,children:[ie?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(`input`,{ref:te,type:`file`,accept:zO,style:{display:`none`},onChange:e=>{let t=e.target.files?.[0];t&&v?.(t),e.target.value=``}}),(0,f.jsx)(`button`,{type:`button`,style:{width:`32px`,height:`32px`,borderRadius:`9999px`,background:`#f3f4f8`,color:`var(--flowengage-primary)`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`background 0.2s ease, opacity 0.2s ease`,border:0,cursor:`pointer`,flexShrink:0},onClick:()=>te.current?.click(),title:`Attach file`,"aria-label":`Attach file`,disabled:S,onMouseEnter:e=>{e.currentTarget.style.opacity=`0.8`},onMouseLeave:e=>{e.currentTarget.style.opacity=`1`},children:(0,f.jsx)(wO,{size:16,color:`currentColor`})})]}):null,(0,f.jsx)(`input`,{className:`flowengage-chat-text-input`,style:{flex:1,minWidth:0,border:`none`,fontFamily:`inherit`,fontSize:`14px`,outline:`none`,padding:0,paddingLeft:ie?`0`:`8px`,color:`#111827`,background:`transparent`,cursor:`text`},value:u?p:e,onChange:e=>{if(u){m(e.target.value);return}t(e.target.value)},placeholder:u?`Enter your Email`:o===`agent`?`Message the agent…`:ee,disabled:s,type:u?`email`:`text`,autoComplete:u?`email`:`off`}),(0,f.jsx)(`button`,{type:`submit`,style:{width:`32px`,height:`32px`,borderRadius:`9999px`,background:`var(--flowengage-primary)`,color:`#fff`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`opacity 0.2s ease`,cursor:C?`not-allowed`:`pointer`,opacity:C?.45:1,flexShrink:0},disabled:C,onMouseEnter:e=>{C||(e.currentTarget.style.opacity=`0.85`)},onMouseLeave:e=>{e.currentTarget.style.opacity=`1`},children:(0,f.jsx)(yO,{size:16})})]}),!u&&x&&(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`7px 4px 0`},children:[(0,f.jsxs)(`svg`,{width:`13`,height:`13`,viewBox:`0 0 24 24`,fill:`none`,stroke:`#dc2626`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,f.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,f.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),(0,f.jsx)(`span`,{style:{fontSize:`11px`,color:`#dc2626`,fontWeight:500},children:x})]}),u&&h&&(0,f.jsx)(`div`,{style:{padding:`8px 16px 0`,fontSize:`12px`,fontWeight:500,color:`#f43f5e`},children:h})]})}function JO({webRTCError:e,micError:t,setMicError:n,dismissCallError:r,isRateLimited:i,rateLimitMessage:a}){return(0,f.jsxs)(f.Fragment,{children:[(e||t)&&(0,f.jsxs)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,borderRadius:`12px`,background:`#fef2f2`,border:`1px solid #fee2e2`,display:`flex`,alignItems:`flex-start`,gap:`10px`},children:[(0,f.jsx)(SO,{className:``}),(0,f.jsx)(`span`,{style:{fontSize:`12px`,color:`#b91c1c`,lineHeight:1.5,flex:1},children:e||t}),(0,f.jsx)(`button`,{style:{flexShrink:0,background:`transparent`,border:0,color:`#f87171`,cursor:`pointer`,fontSize:`18px`,lineHeight:1},onClick:()=>{n(null),r()},onMouseEnter:e=>{e.currentTarget.style.color=`#dc2626`},onMouseLeave:e=>{e.currentTarget.style.color=`#f87171`},children:`×`})]}),i&&(0,f.jsx)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,fontSize:`13px`,borderRadius:`12px`,background:`#fee2e2`,color:`#991b1b`},children:a})]})}var YO=[`#135bd8`,`#ef334b`,`#ffbd2e`];function XO(e){return!Array.isArray(e)||e.length===0?YO:e.length===1?[e[0],e[0],e[0]]:e.length===2?[e[0],e[1],e[0]]:[e[0],e[1],e[2]]}var ZO={idle:3,listening:.75,thinking:1,speaking:1.4,muted:.75,error:.08};function QO(e){if(!e||typeof e!=`string`)return[0,0,0];let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t;return[parseInt(n.slice(0,2),16)/255,parseInt(n.slice(2,4),16)/255,parseInt(n.slice(4,6),16)/255]}function $O(e,t){if(!e||typeof e!=`string`)return`rgba(0,0,0,${t})`;if(e.startsWith(`rgb`))return e.replace(/[\d.]+\)$/,`${t})`);let n=e.replace(`#`,``),r=n.length===3?n.split(``).map(e=>e+e).join(``):n;return`rgba(${parseInt(r.slice(0,2),16)},${parseInt(r.slice(2,4),16)},${parseInt(r.slice(4,6),16)},${t})`}var ek=`
|
|
333
|
+
`).split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean),r=e=>DD(e).replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,`<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>`).replace(/\*\*([^*]+)\*\*/g,`<strong>$1</strong>`).replace(/\*([^*\n]+)\*/g,`<em>$1</em>`);return MD(n.map(e=>{let t=e.split(`
|
|
334
|
+
`).map(e=>e.trim()).filter(Boolean),n=t.filter(e=>/^[-*]\s+/.test(e));if(n.length>=2&&n.length===t.length)return`<ul>${n.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`;let i=e.split(/\s+(?=[-*]\s+\*\*?)/).map(e=>e.trim()).filter(Boolean);return i.length>=2&&i.every(e=>/^[-*]\s+/.test(e))?`<ul>${i.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`:`<p>${r(e).replace(/\n/g,`<br />`)}</p>`}).join(``))},PD=new Set([`application/pdf`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`]),FD=new Set([`.pdf`,`.docx`,`.png`,`.jpg`,`.jpeg`]),ID=`image/png,image/jpeg,.pdf,.docx`;function LD(e){if(!e)return!1;let t=typeof e.name==`string`?e.name.toLowerCase():``,n=t.includes(`.`)?`.${t.split(`.`).pop()}`:``,r=typeof e.type==`string`?e.type.toLowerCase():``;return r===`image/png`||r===`image/jpeg`||PD.has(r)||FD.has(n)}function RD(e){return e?LD(e)?e.size>2097152?`File must be 2 MB or smaller.`:``:`Only PNG, JPEG, PDF, and DOCX files are allowed.`:`No file selected.`}function zD(e=0){if(!Number.isFinite(e)||e<=0)return``;let t=[`B`,`KB`,`MB`,`GB`],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;let i=n>=10||r===0?0:1;return`${n.toFixed(i)} ${t[r]}`}function BD(e){return e?e.name||`Attachment`:``}function VD(e){if(!e||typeof e!=`string`)return`?`;let t=e.trim();if(!t)return`?`;let n=t.split(/\s+/).filter(Boolean);return n.length>=2?`${n[0][0]}${n[n.length-1][0]}`.toUpperCase():t.slice(0,2).toUpperCase()}function HD({src:e,name:t,imgStyle:n,initialsSpanStyle:r}){let[i,a]=(0,d.useState)(null),o=typeof e==`string`?e.trim():``;return(0,d.useEffect)(()=>{if(!o){a(null);return}a(null);let e=!1,t=new window.Image;return t.onload=()=>{e||a(o)},t.onerror=()=>{e||a(null)},t.src=o,()=>{e=!0}},[o]),i?(0,f.jsx)(`img`,{src:i,alt:``,style:n,onError:()=>a(null)}):(0,f.jsx)(`span`,{style:r,children:VD(t)})}function UD({chatHistory:e,isAiTyping:t,isLoading:n,isAgentTyping:r,setReplyContext:i,primaryColor:a=`#3B82F6`,agentHeadshot:o=null,agentDisplayName:s=`Agent`,botAvatarNode:c=null}){let{resolvedConfig:l}=Tn(),u=(0,d.useRef)(null),[p,m]=(0,d.useState)(null),[h,g]=(0,d.useState)(null),_=(0,d.useRef)(e.length),v=(0,d.useRef)(!0),y=(0,d.useRef)(null),b=(0,d.useCallback)(e=>{let t=e.target.closest(`a[href]`);if(!t)return;let n=t.getAttribute(`href`)||``;if(!(!n||n.startsWith(`mailto:`)||n.startsWith(`tel:`)||n.startsWith(`javascript:`)))try{let t=new URL(n,window.location.href);if(t.origin!==window.location.origin){e.preventDefault(),window.open(t.href,`_blank`,`noopener,noreferrer`);return}e.preventDefault(),hr(t.href,{siteId:l?.siteId,apiBaseUrl:l?.apiBaseUrl}).then(e=>{e&&xr(t.href)})}catch{}},[l]),x=e=>{if(!e)return`just now`;let t=new Date,n=new Date(e),r=Math.max(0,Math.floor((t-n)/1e3));if(r<60)return`just now`;let i=Math.floor(r/60);if(i<60)return`${i} min${i>1?`s`:``} ago`;let a=Math.floor(i/60);if(a<24)return`${a} hr${a>1?`s`:``} ago`;let o=Math.floor(a/24);return`${o} day${o>1?`s`:``} ago`};return(0,d.useEffect)(()=>{if(v.current){v.current=!1,_.current=e.length,y.current&&(y.current.scrollTop=y.current.scrollHeight);return}let n=e.length>_.current;_.current=e.length,(n||t||r)&&u.current?.scrollIntoView({behavior:`smooth`})},[e.length,t,n,r]),(0,f.jsxs)(`div`,{ref:y,style:{flex:1,overflowY:`auto`,overscrollBehavior:`contain`,padding:`10px 16px 20px`,display:`flex`,flexDirection:`column`,background:`transparent`},children:[e.map(e=>{if(e.type===`call_recording`||typeof e.message==`string`&&e.message.includes(`AI chat recording`))return null;let t=e.sender===`system`,n=e.sender===`user`,r=e.sender===`ai`||e.sender===`bot`,l=e.sender===`agent`,u=e.isPending,d=e.type===`file`&&e.metadata?.fileUrl,p=e.agent_name||e.agentName||e.metadata?.agentName||s,_=typeof e.sender_headshot==`string`&&e.sender_headshot.trim()||typeof o==`string`&&o.trim()||null,v=ED(e.replyToContent||e.replyContext?.message||``),y=e.replyToSender===`user`?`You`:e.replyToSender===`agent`?`Agent`:e.replyToSender===`ai`||e.replyToSender===`bot`?`AI Assistant`:`Message`;return t?(0,f.jsx)(`div`,{style:{display:`flex`,justifyContent:`center`,margin:`8px 0`},children:(0,f.jsx)(`div`,{style:{padding:`6px 12px`,borderRadius:`9999px`,background:`#f3f4f6`,color:`#6b7280`,fontSize:`12px`,fontWeight:500},children:e.message})},e.id):(0,f.jsxs)(`div`,{style:{display:`flex`,justifyContent:n?`flex-end`:`flex-start`,alignItems:`flex-start`,marginBottom:`16px`,gap:`8px`,flexDirection:`row`},children:[!n&&(r||l)&&(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,background:l?`#f3f4f6`:c&&r?`transparent`:`var(--flowengage-primary)`,color:l?a:`#fff`,boxShadow:l?`0 2px 8px rgba(0,0,0,0.06)`:c&&r?`none`:`0 8px 20px rgba(59,130,246,0.24)`,overflow:`hidden`,border:l?`1px solid ${a}22`:`none`,fontSize:`12px`,fontWeight:800,marginTop:!u&&(r||l)?`22px`:`0px`},children:r?c||(0,f.jsx)(bD,{size:16}):(0,f.jsx)(HD,{src:_||``,name:p,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}),(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:n?`flex-end`:`flex-start`,maxWidth:`75%`,minWidth:0},children:[!u&&l&&(0,f.jsxs)(`button`,{type:`button`,onClick:()=>i(e),style:{opacity:1,marginBottom:`4px`,display:`flex`,alignItems:`center`,gap:`4px`,fontSize:`11px`,color:`#9ca3af`,background:`transparent`,border:0,cursor:`pointer`,padding:0,marginLeft:`2px`},onMouseEnter:e=>{e.currentTarget.style.color=`#4b5563`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:[(0,f.jsx)(_D,{}),`Reply`]}),(0,f.jsxs)(`div`,{style:{padding:`8px 16px`,borderRadius:n?`20px 6px 20px 20px`:`6px 20px 20px 20px`,lineHeight:1.8,letterSpacing:0,boxShadow:`0 2px 8px rgba(0,0,0,0.06)`,background:n?`var(--flowengage-primary)`:`rgba(255,255,255,0.92)`,color:n?`#fff`:`#111827`,fontSize:`14px`,fontWeight:400,opacity:u?.55:1,transition:`opacity 0.3s ease`,wordBreak:`break-word`,width:`fit-content`},children:[v&&(0,f.jsxs)(`div`,{style:{marginBottom:`8px`,borderRadius:`14px`,borderLeft:n?`2px solid rgba(255,255,255,0.8)`:`2px solid var(--flowengage-primary)`,padding:`8px 12px`,fontSize:`12px`,background:n?`rgba(255,255,255,0.15)`:`#f9fafb`,color:n?`rgba(255,255,255,0.9)`:`#6b7280`},children:[(0,f.jsx)(`div`,{style:{marginBottom:`2px`,fontWeight:600},children:y}),(0,f.jsx)(`div`,{style:{display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,overflow:`hidden`},children:v})]}),d?(()=>{let t=e.metadata.fileType||``,r=e.metadata.fileName||e.message||`File`,i=zD(e.metadata.fileSize),a=t.startsWith(`image/`),o=`shared file: ${r}`.toLowerCase(),s=(e.message||``).trim(),c=s&&s.toLowerCase()!==o&&!s.toLowerCase().startsWith(`shared file:`),l=t===`application/pdf`?{color:`#ef4444`,label:`PDF`}:t.includes(`word`)||t.includes(`docx`)?{color:`#3b82f6`,label:`DOCX`}:t.includes(`excel`)||t.includes(`sheet`)||t===`text/csv`?{color:`#10b981`,label:`XLSX`}:{color:`#6b7280`,label:`FILE`};return(0,f.jsxs)(`div`,{style:{minWidth:`200px`,maxWidth:`240px`},children:[c&&(0,f.jsx)(`div`,{style:{marginBottom:`6px`,fontSize:`14px`,color:n?`#fff`:`#111827`,whiteSpace:`normal`,wordBreak:`break-word`},children:s}),a?(0,f.jsx)(`button`,{type:`button`,onClick:()=>m({url:e.metadata.fileUrl,name:r}),onMouseEnter:()=>g(e.id),onMouseLeave:()=>g(null),style:{display:`block`,width:`100%`,background:`transparent`,border:0,padding:0,margin:0,textAlign:`left`,cursor:`pointer`},children:(0,f.jsxs)(`div`,{style:{position:`relative`},children:[(0,f.jsx)(`img`,{src:e.metadata.fileUrl,alt:r,style:{width:`100%`,borderRadius:`10px`,display:`block`,maxHeight:`180px`,objectFit:`cover`}}),(0,f.jsx)(`div`,{style:{position:`absolute`,inset:0,borderRadius:`10px`,background:h===e.id?`rgba(17,24,39,0.32)`:`rgba(17,24,39,0)`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`#fff`,fontSize:`13px`,fontWeight:700,letterSpacing:`0.02em`,opacity:h===e.id?1:0,transition:`background 0.18s ease, opacity 0.18s ease`,pointerEvents:`none`},children:`Preview`})]})}):(0,f.jsx)(`a`,{href:e.metadata.fileUrl,target:`_blank`,rel:`noopener noreferrer`,style:{textDecoration:`none`,display:`block`},children:(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`10px`,background:n?`rgba(255,255,255,0.15)`:`#f3f4f6`,borderRadius:`12px`,padding:`10px 12px`},children:[(0,f.jsxs)(`div`,{style:{width:`38px`,height:`46px`,borderRadius:`8px`,background:n?`rgba(255,255,255,0.22)`:`#fff`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flexShrink:0,boxShadow:`0 1px 4px rgba(0,0,0,0.1)`,gap:`3px`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:n?`#fff`:l.color,strokeWidth:`1.8`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z`}),(0,f.jsx)(`polyline`,{points:`14 2 14 8 20 8`})]}),(0,f.jsx)(`span`,{style:{fontSize:`7px`,fontWeight:800,letterSpacing:`0.04em`,color:n?`#fff`:l.color,lineHeight:1},children:l.label})]}),(0,f.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(`div`,{style:{fontSize:`13px`,fontWeight:600,color:n?`#fff`:`#111827`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:r}),i&&(0,f.jsx)(`div`,{style:{fontSize:`11px`,marginTop:`3px`,color:n?`rgba(255,255,255,0.6)`:`#9ca3af`},children:i})]}),(0,f.jsxs)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,stroke:n?`rgba(255,255,255,0.65)`:`#9ca3af`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:[(0,f.jsx)(`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`}),(0,f.jsx)(`polyline`,{points:`7 10 12 15 17 10`}),(0,f.jsx)(`line`,{x1:`12`,y1:`15`,x2:`12`,y2:`3`})]})]})})]})})():r?(0,f.jsx)(`div`,{className:`flowengage-message-content fe-bot-message`,dangerouslySetInnerHTML:{__html:ND(e.message)},onClick:b}):(0,f.jsx)(`div`,{style:{whiteSpace:n||l?`normal`:`pre-wrap`},children:e.message})]}),(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`,marginTop:`4px`,padding:`0 4px`,alignSelf:n?`flex-end`:`flex-start`},children:u?(0,f.jsx)(`span`,{style:{fontSize:`10px`,color:`#9ca3af`,fontWeight:500,fontStyle:`italic`},children:`sending…`}):(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(`span`,{style:{fontSize:`10px`,color:`#9ca3af`,fontWeight:500},children:x(e.timestamp||e.createdAt)}),(0,f.jsx)(`span`,{style:{fontSize:`10px`,fontWeight:700,color:n?`var(--flowengage-primary)`:`#9ca3af`},children:`✓`})]})})]})]},e.id)}),(t||n)&&(0,f.jsxs)(`div`,{style:{marginBottom:`16px`,display:`flex`,alignItems:`center`,gap:`8px`},children:[(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,background:c?`transparent`:`var(--flowengage-primary)`,color:`#fff`,boxShadow:c?`none`:`0 8px 20px rgba(59,130,246,0.24)`,overflow:`hidden`},children:c||(0,f.jsx)(bD,{size:16})}),(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`2px`,color:`#374151`,fontSize:`13px`,fontWeight:500,fontStyle:`italic`},children:[`Analysing`,[0,1,2].map(e=>(0,f.jsx)(`span`,{style:{animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`},children:`.`},e))]})]}),r&&(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`flex-start`,gap:`8px`,marginBottom:`12px`},children:[(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,overflow:`hidden`},children:(0,f.jsx)(HD,{src:o||``,name:s,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}),(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))})]}),(0,f.jsx)(`div`,{ref:u}),p&&(0,f.jsx)(`button`,{type:`button`,onClick:()=>m(null),style:{position:`fixed`,inset:0,zIndex:1e4,border:0,padding:`16px`,margin:0,background:`rgba(2,6,23,0.88)`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`default`},children:(0,f.jsxs)(`div`,{style:{position:`relative`,maxWidth:`min(96vw, 1100px)`,maxHeight:`96vh`,width:`100%`,display:`flex`,flexDirection:`column`,gap:`10px`,alignItems:`center`},children:[(0,f.jsx)(`img`,{src:p.url,alt:p.name,style:{width:`100%`,maxHeight:`calc(96vh - 72px)`,objectFit:`contain`,borderRadius:`16px`,boxShadow:`0 30px 80px rgba(0,0,0,0.42)`}}),(0,f.jsx)(`div`,{style:{maxWidth:`100%`,padding:`8px 14px`,borderRadius:`9999px`,background:`rgba(255,255,255,0.92)`,color:`#0f172a`,fontSize:`12px`,fontWeight:600,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:p.name})]})})]})}function WD({input:e,setInput:t,onSubmit:n,isConversationEnded:r,callUiActive:i,handleToggleVoice:a,activeScreen:o,inputDisabled:s,replyContext:c,clearReplyContext:l,requiresEmail:u,emailInput:p,setEmailInput:m,emailError:h,showVoiceToggle:g=!1,voiceEnabled:_=!0,onFileSelect:v,selectedFile:y=null,onRemoveSelectedFile:b,attachmentError:x=``,isUploadingAttachment:S=!1,inputPlaceholder:ee=`Type your message`}){let te=(0,d.useRef)(null),ne=c?.sender===`user`?`You`:c?.sender===`agent`?`Agent`:`AI Assistant`,re=u?!!p?.trim():!!e?.trim()||!!y,ie=s||S||!re,ae=!u&&_&&g;return(0,f.jsxs)(`div`,{style:{padding:`0 16px`,background:`transparent`},children:[c&&(0,f.jsxs)(`div`,{style:{marginBottom:`8px`,display:`flex`,alignItems:`flex-start`,justifyContent:`space-between`,gap:`12px`,borderRadius:`16px`,border:`1px solid rgba(0,0,0,0.05)`,background:`#fff`,padding:`12px 16px`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`},children:[(0,f.jsxs)(`div`,{style:{minWidth:0,flex:1,borderLeft:`2px solid var(--flowengage-primary)`,paddingLeft:`12px`},children:[(0,f.jsxs)(`div`,{style:{fontSize:`12px`,fontWeight:600,color:`var(--flowengage-primary)`},children:[`Replying to `,ne]}),(0,f.jsx)(`div`,{style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`,fontSize:`12px`,color:`#6b7280`},children:c.replyToContent||c.message})]}),(0,f.jsx)(`button`,{type:`button`,style:{width:`28px`,height:`28px`,borderRadius:`9999px`,border:0,background:`#f3f4f6`,color:`#6b7280`,transition:`color 0.2s ease, background 0.2s ease`,cursor:`pointer`},onClick:l,"aria-label":`Cancel reply`,onMouseEnter:e=>{e.currentTarget.style.background=`#e5e7eb`,e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.background=`#f3f4f6`,e.currentTarget.style.color=`#6b7280`},children:`×`})]}),u&&(0,f.jsx)(`div`,{style:{marginBottom:`8px`,padding:`0 8px`},children:(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,color:`#111827`,fontSize:`14px`,fontWeight:500,textAlign:`center`},children:[(0,f.jsx)(`span`,{style:{display:`inline-flex`,width:`22px`,height:`22px`,borderRadius:`9999px`,alignItems:`center`,justifyContent:`center`,background:`rgba(59,130,246,0.08)`,color:`var(--flowengage-primary)`},children:(0,f.jsx)(bD,{size:13})}),(0,f.jsx)(`span`,{children:`Please provide your email address so we can help you.`})]})}),y&&!u&&(0,f.jsxs)(`div`,{style:{marginBottom:`10px`,display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`12px`,borderRadius:`16px`,border:`1px solid rgba(0,0,0,0.06)`,background:`#fff`,padding:`12px 14px`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`},children:[(0,f.jsxs)(`div`,{style:{minWidth:0,flex:1},children:[(0,f.jsx)(`div`,{style:{fontSize:`12px`,fontWeight:600,color:`var(--flowengage-primary)`,marginBottom:`2px`},children:`Attachment ready`}),(0,f.jsx)(`div`,{style:{fontSize:`13px`,color:`#111827`,whiteSpace:`nowrap`,overflow:`hidden`,textOverflow:`ellipsis`},children:BD(y)}),(0,f.jsx)(`div`,{style:{fontSize:`12px`,color:`#6b7280`,marginTop:`2px`},children:zD(y.size)})]}),(0,f.jsx)(`button`,{type:`button`,style:{width:`28px`,height:`28px`,borderRadius:`9999px`,border:0,background:`#f3f4f6`,color:`#6b7280`,transition:`color 0.2s ease, background 0.2s ease`,cursor:`pointer`,flexShrink:0},onClick:b,"aria-label":`Remove attachment`,onMouseEnter:e=>{e.currentTarget.style.background=`#e5e7eb`,e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.background=`#f3f4f6`,e.currentTarget.style.color=`#6b7280`},children:`×`})]}),(0,f.jsxs)(`form`,{style:{display:`flex`,alignItems:`center`,gap:`8px`,height:`40px`,padding:`4px`,border:`1px solid rgba(0,0,0,0.06)`,borderRadius:`9999px`,background:`#fff`,boxShadow:`0 4px 14px rgba(0,0,0,0.04)`,opacity:1},onSubmit:n,children:[ae?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(`input`,{ref:te,type:`file`,accept:ID,style:{display:`none`},onChange:e=>{let t=e.target.files?.[0];t&&v?.(t),e.target.value=``}}),(0,f.jsx)(`button`,{type:`button`,style:{width:`32px`,height:`32px`,borderRadius:`9999px`,background:`#f3f4f8`,color:`var(--flowengage-primary)`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`background 0.2s ease, opacity 0.2s ease`,border:0,cursor:`pointer`,flexShrink:0},onClick:()=>te.current?.click(),title:`Attach file`,"aria-label":`Attach file`,disabled:S,onMouseEnter:e=>{e.currentTarget.style.opacity=`0.8`},onMouseLeave:e=>{e.currentTarget.style.opacity=`1`},children:(0,f.jsx)(xD,{size:16,color:`currentColor`})})]}):null,(0,f.jsx)(`input`,{className:`flowengage-chat-text-input`,style:{flex:1,minWidth:0,border:`none`,fontFamily:`inherit`,fontSize:`14px`,outline:`none`,padding:0,paddingLeft:ae?`0`:`8px`,color:`#111827`,background:`transparent`,cursor:`text`},value:u?p:e,onChange:e=>{if(u){m(e.target.value);return}t(e.target.value)},placeholder:u?`Enter your Email`:o===`agent`?`Message the agent…`:ee,disabled:s,type:u?`email`:`text`,autoComplete:u?`email`:`off`}),(0,f.jsx)(`button`,{type:`submit`,style:{width:`32px`,height:`32px`,borderRadius:`9999px`,background:`var(--flowengage-primary)`,color:`#fff`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`opacity 0.2s ease`,cursor:ie?`not-allowed`:`pointer`,opacity:ie?.45:1,flexShrink:0},disabled:ie,onMouseEnter:e=>{ie||(e.currentTarget.style.opacity=`0.85`)},onMouseLeave:e=>{e.currentTarget.style.opacity=`1`},children:(0,f.jsx)(gD,{size:16})})]}),!u&&x&&(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`7px 4px 0`},children:[(0,f.jsxs)(`svg`,{width:`13`,height:`13`,viewBox:`0 0 24 24`,fill:`none`,stroke:`#dc2626`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,f.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,f.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),(0,f.jsx)(`span`,{style:{fontSize:`11px`,color:`#dc2626`,fontWeight:500},children:x})]}),u&&h&&(0,f.jsx)(`div`,{style:{padding:`8px 16px 0`,fontSize:`12px`,fontWeight:500,color:`#f43f5e`},children:h})]})}function GD({webRTCError:e,micError:t,setMicError:n,dismissCallError:r,isRateLimited:i,rateLimitMessage:a}){return(0,f.jsxs)(f.Fragment,{children:[(e||t)&&(0,f.jsxs)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,borderRadius:`12px`,background:`#fef2f2`,border:`1px solid #fee2e2`,display:`flex`,alignItems:`flex-start`,gap:`10px`},children:[(0,f.jsx)(yD,{className:``}),(0,f.jsx)(`span`,{style:{fontSize:`12px`,color:`#b91c1c`,lineHeight:1.5,flex:1},children:e||t}),(0,f.jsx)(`button`,{style:{flexShrink:0,background:`transparent`,border:0,color:`#f87171`,cursor:`pointer`,fontSize:`18px`,lineHeight:1},onClick:()=>{n(null),r()},onMouseEnter:e=>{e.currentTarget.style.color=`#dc2626`},onMouseLeave:e=>{e.currentTarget.style.color=`#f87171`},children:`×`})]}),i&&(0,f.jsx)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,fontSize:`13px`,borderRadius:`12px`,background:`#fee2e2`,color:`#991b1b`},children:a})]})}var KD=[`#135bd8`,`#ef334b`,`#ffbd2e`];function qD(e){return!Array.isArray(e)||e.length===0?KD:e.length===1?[e[0],e[0],e[0]]:e.length===2?[e[0],e[1],e[0]]:[e[0],e[1],e[2]]}var JD={idle:3,listening:.75,thinking:1,speaking:1.4,muted:.75,error:.08};function YD(e){if(!e||typeof e!=`string`)return[0,0,0];let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t;return[parseInt(n.slice(0,2),16)/255,parseInt(n.slice(2,4),16)/255,parseInt(n.slice(4,6),16)/255]}function XD(e,t){if(!e||typeof e!=`string`)return`rgba(0,0,0,${t})`;if(e.startsWith(`rgb`))return e.replace(/[\d.]+\)$/,`${t})`);let n=e.replace(`#`,``),r=n.length===3?n.split(``).map(e=>e+e).join(``):n;return`rgba(${parseInt(r.slice(0,2),16)},${parseInt(r.slice(2,4),16)},${parseInt(r.slice(4,6),16)},${t})`}var ZD=`
|
|
487
335
|
attribute vec2 a_pos;
|
|
488
336
|
varying vec2 v_uv;
|
|
489
337
|
void main() {
|
|
490
338
|
v_uv = a_pos * 0.5 + 0.5;
|
|
491
339
|
gl_Position = vec4(a_pos, 0.0, 1.0);
|
|
492
340
|
}
|
|
493
|
-
`,
|
|
341
|
+
`,QD=`
|
|
494
342
|
precision highp float;
|
|
495
343
|
|
|
496
344
|
varying vec2 v_uv;
|
|
@@ -605,7 +453,7 @@ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
|
|
|
605
453
|
|
|
606
454
|
gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
|
|
607
455
|
}
|
|
608
|
-
`;function
|
|
456
|
+
`;function $D(e,t,n){let r=(t,n)=>{let r=e.createShader(t);return e.shaderSource(r,n),e.compileShader(r),e.getShaderParameter(r,e.COMPILE_STATUS)?r:(console.error(`[AnimatedOrb shader]`,e.getShaderInfoLog(r)),null)},i=r(e.VERTEX_SHADER,t),a=r(e.FRAGMENT_SHADER,n);if(!i||!a)return null;let o=e.createProgram();return e.attachShader(o,i),e.attachShader(o,a),e.linkProgram(o),e.getProgramParameter(o,e.LINK_STATUS)?o:(console.error(`[AnimatedOrb link]`,e.getProgramInfoLog(o)),null)}function eO({size:e=94,voiceState:t=`idle`,isMuted:n=!1,colors:r,onClick:i,style:a,className:o}){let[s,c,l]=qD(r),u=t===`speaking`,p=e<=50,m=(0,d.useRef)(null),h=(0,d.useRef)(JD[t]??.35);(0,d.useEffect)(()=>{h.current=JD[t]??.35},[t]),(0,d.useEffect)(()=>{let t=m.current;if(!t)return;let n=Math.min(window.devicePixelRatio||1,2);t.width=e*n,t.height=e*n;let r=t.getContext(`webgl`,{alpha:!0,antialias:!0})||t.getContext(`experimental-webgl`,{alpha:!0,antialias:!0});if(!r){console.warn(`[AnimatedOrb] WebGL unavailable.`);return}let i=$D(r,ZD,QD);if(!i){console.error(`[AnimatedOrb] WebGL program failed to compile/link`);return}r.useProgram(i);let a=r.createBuffer();r.bindBuffer(r.ARRAY_BUFFER,a),r.bufferData(r.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),r.STATIC_DRAW);let o=r.getAttribLocation(i,`a_pos`);r.enableVertexAttribArray(o),r.vertexAttribPointer(o,2,r.FLOAT,!1,0,0);let u={time:r.getUniformLocation(i,`u_time`),speed:r.getUniformLocation(i,`u_speed`),c1:r.getUniformLocation(i,`u_c1`),c2:r.getUniformLocation(i,`u_c2`),c3:r.getUniformLocation(i,`u_c3`)};r.uniform3fv(u.c1,YD(s)),r.uniform3fv(u.c2,YD(c)),r.uniform3fv(u.c3,YD(l)),r.viewport(0,0,t.width,t.height);let d=performance.now(),f,p=e=>{r.uniform1f(u.time,(e-d)/1e3),r.uniform1f(u.speed,h.current),r.drawArrays(r.TRIANGLES,0,6),f=requestAnimationFrame(p)};return f=requestAnimationFrame(p),()=>{cancelAnimationFrame(f),r.deleteProgram(i),r.deleteBuffer(a)}},[s,c,l,e]);let g=n?`saturate(0.3) brightness(1.1)`:t===`error`?`saturate(0.4) hue-rotate(28deg)`:`none`;return(0,f.jsxs)(`div`,{style:{position:`relative`,width:e,height:e,flexShrink:0,cursor:i?`pointer`:`default`,...a},className:o,onClick:i,children:[u&&!p&&(0,f.jsx)(Sm.div,{style:{position:`absolute`,inset:-10,borderRadius:`50%`,background:`radial-gradient(circle, ${XD(s,.18)} 0%, transparent 70%)`,pointerEvents:`none`},animate:{opacity:[.3,.75]},transition:{duration:1,repeat:1/0,repeatType:`mirror`,ease:`easeInOut`}}),(0,f.jsx)(`div`,{style:{width:e,height:e,borderRadius:`50%`,overflow:`hidden`,WebkitMaskImage:`-webkit-radial-gradient(white, black)`,filter:g,transition:`filter 1.2s ease`},children:(0,f.jsx)(`canvas`,{ref:m,style:{width:`100%`,height:`100%`,display:`block`}})}),u&&(0,f.jsx)(`div`,{style:{position:`absolute`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,pointerEvents:`none`,zIndex:1},children:(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`3px`},children:[4,8,12,8,4].map((e,t)=>(0,f.jsx)(Sm.div,{style:{width:`3px`,borderRadius:`3px`,background:`rgba(255,255,255,0.85)`},animate:{height:[4,e+8,4]},transition:{duration:.48,delay:t*.08,repeat:1/0,ease:`easeInOut`}},t))})})]})}var tO=`
|
|
609
457
|
@keyframes fe-call-ring-pulse {
|
|
610
458
|
0% { transform: scale(1); opacity: 0.55; }
|
|
611
459
|
70% { transform: scale(1.85); opacity: 0; }
|
|
@@ -634,13 +482,169 @@ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
|
|
|
634
482
|
0%, 100% { opacity: 0.5; transform: scale(1); }
|
|
635
483
|
50% { opacity: 0.9; transform: scale(1.12); }
|
|
636
484
|
}
|
|
637
|
-
`;function ak(e){let t=(e||``).replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t;return`${parseInt(n.slice(0,2),16)},${parseInt(n.slice(2,4),16)},${parseInt(n.slice(4,6),16)}`}function ok(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 sk(e,t){let n=Array.isArray(e)&&e.length>0?e:[t||`#3B82F6`],[r,i,a]=n;return n.length===1?[`radial-gradient(ellipse 110% 65% at 50% -5%, ${r}28 0%, transparent 68%)`,`radial-gradient(ellipse 90% 55% at 50% 108%, ${r}1a 0%, transparent 65%)`,`#f7f8fa`].join(`, `):n.length===2?[`radial-gradient(ellipse 80% 100% at -10% 50%, ${r}22 0%, transparent 70%)`,`radial-gradient(ellipse 80% 100% at 110% 50%, ${i}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `):[`radial-gradient(ellipse 80% 70% at -10% 50%, ${r}22 0%, transparent 70%)`,`radial-gradient(ellipse 70% 80% at 110% 30%, ${i}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 60% at 50% 110%, ${a}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `)}function ck({headshot:e,name:t,size:n=80,primaryColor:r=`#3B82F6`}){let i=(t||`A`)[0].toUpperCase(),a=ok(r),o=n>48?{boxShadow:`0 0 0 3px ${r}44`,border:`3px solid rgba(255,255,255,0.15)`}:{border:`1.5px solid ${r}55`};return e?(0,f.jsx)(`img`,{src:e,alt:t||`Agent`,style:{width:n,height:n,borderRadius:`50%`,objectFit:`cover`,position:`relative`,zIndex:1,flexShrink:0,...o}}):(0,f.jsx)(`div`,{style:{width:n,height:n,borderRadius:`50%`,background:`linear-gradient(135deg, ${r}, ${r}99)`,display:`flex`,alignItems:`center`,justifyContent:`center`,fontSize:Math.round(n*.36)+`px`,fontWeight:700,color:a,position:`relative`,zIndex:1,flexShrink:0,...o},children:i})}function lk(e){let t=(0,d.useRef)(null),n=(0,d.useCallback)(()=>{if(!t.current)return;let{audioContext:e,oscillator:n,interval:r,toneTimeout:i}=t.current;window.clearInterval(r),window.clearTimeout(i);try{n.stop()}catch{}try{e.close()}catch{}t.current=null},[]),r=(0,d.useCallback)(()=>{if(t.current||typeof window>`u`)return;let e=window.AudioContext||window.webkitAudioContext||null;if(e)try{let n=new e,r=n.createOscillator(),i=n.createGain();r.connect(i),i.connect(n.destination),r.frequency.value=0,r.type=`sine`,i.gain.value=.3;let a=()=>{t.current&&(window.clearTimeout(t.current.toneTimeout),r.frequency.value=440,t.current.toneTimeout=window.setTimeout(()=>{r.frequency.value=0},400))};n.state===`suspended`&&n.resume().catch(e=>{console.warn(`[FlowEngage] ringtone autoplay blocked`,e)}),r.start(),t.current={audioContext:n,oscillator:r,interval:null,toneTimeout:null},a(),t.current.interval=window.setInterval(a,1e3)}catch(e){console.warn(`[FlowEngage] failed to start ringtone`,e)}},[]);return(0,d.useEffect)(()=>{if(e){r();return}n()},[e,r,n]),(0,d.useEffect)(()=>()=>n(),[n]),n}function uk({incomingCall:e,activeCallId:t,callConnectionState:n,callDurationSeconds:r,isCallMuted:i,agentName:a,agentHeadshot:o,fallbackAgentName:s,acceptCall:c,rejectCall:l,endWebRTCCall:u,toggleCallMute:d,formatCallDuration:p,onMinimize:m,primaryColor:h=`#3B82F6`,orbColors:g,chatHistory:_=[]}){let v=a||s||`Agent`,y=e?`incoming`:n===`connecting`?`connecting`:`ongoing`,b=lk(!!e),x=async()=>{b(),await c()},S=async()=>{b(),await l()},ee=i?`muted`:n===`connecting`?`idle`:`listening`,te=y===`ongoing`,ne={position:`absolute`,inset:0,zIndex:10,display:`flex`,flexDirection:`column`,borderRadius:`inherit`,overflow:`hidden`,background:sk(g,h),animation:te?`fe-call-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`:`fe-call-fade-in 0.32s ease`};if(y===`incoming`){let e=Array.isArray(g)&&g.length>0?g:[h];return(0,f.jsxs)(`div`,{style:ne,children:[(0,f.jsx)(`style`,{children:ik}),(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`space-between`,padding:`60px 32px 56px`},children:[(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`22px`},children:[(0,f.jsxs)(`div`,{style:{position:`relative`,width:`96px`,height:`96px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[(0,f.jsx)(`div`,{style:{position:`absolute`,width:`96px`,height:`96px`,borderRadius:`50%`,background:`radial-gradient(circle, rgba(${ak(e[0])},0.2) 0%, transparent 70%)`,filter:`blur(10px)`,zIndex:0}}),[0,.5,1].map((t,n)=>(0,f.jsx)(`div`,{style:{position:`absolute`,width:`96px`,height:`96px`,borderRadius:`50%`,border:`1.5px solid ${e[n%e.length]}`,animation:`fe-call-ring-pulse 2.6s cubic-bezier(0.215,0.61,0.355,1) ${t}s infinite`,zIndex:1}},n)),(0,f.jsx)(ck,{headshot:o,name:v,size:82,primaryColor:h})]}),(0,f.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,f.jsx)(`div`,{style:{fontSize:`22px`,fontWeight:700,color:`#111827`,letterSpacing:`-0.015em`,lineHeight:1.2},children:v}),(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`6px`,marginTop:`8px`},children:[(0,f.jsx)(`div`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:e[0],boxShadow:`0 0 5px ${e[0]}88`,animation:`fe-call-dot-blink 1.4s ease-in-out infinite`}}),(0,f.jsx)(`span`,{style:{fontSize:`13px`,color:`#6b7280`,letterSpacing:`0.01em`},children:`Incoming call`})]})]})]}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`56px`,alignItems:`flex-end`},children:[(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`10px`},children:[(0,f.jsx)(`button`,{type:`button`,onClick:S,style:{width:`68px`,height:`68px`,borderRadius:`50%`,background:`#ef4444`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`white`,boxShadow:`0 6px 24px rgba(239,68,68,0.5)`,transition:`transform 0.15s ease, box-shadow 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.08)`,e.currentTarget.style.boxShadow=`0 8px 28px rgba(239,68,68,0.65)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`,e.currentTarget.style.boxShadow=`0 6px 24px rgba(239,68,68,0.5)`},"aria-label":`Decline call`,children:(0,f.jsx)(vO,{size:26})}),(0,f.jsx)(`span`,{style:{fontSize:`12px`,color:`#6b7280`,fontWeight:500,letterSpacing:`0.01em`},children:`Decline`})]}),(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`10px`},children:[(0,f.jsx)(`button`,{type:`button`,onClick:x,style:{width:`68px`,height:`68px`,borderRadius:`50%`,background:`#22c55e`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`white`,boxShadow:`0 6px 24px rgba(34,197,94,0.5)`,transition:`transform 0.15s ease, box-shadow 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.08)`,e.currentTarget.style.boxShadow=`0 8px 28px rgba(34,197,94,0.65)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`,e.currentTarget.style.boxShadow=`0 6px 24px rgba(34,197,94,0.5)`},"aria-label":`Accept call`,children:(0,f.jsx)(xO,{})}),(0,f.jsx)(`span`,{style:{fontSize:`12px`,color:`#6b7280`,fontWeight:500,letterSpacing:`0.01em`},children:`Accept`})]})]})]})]})}return y===`connecting`?(0,f.jsxs)(`div`,{style:ne,children:[(0,f.jsx)(`style`,{children:ik}),(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`24px`},children:[(0,f.jsx)(ck,{headshot:o,name:v,size:64,primaryColor:h}),(0,f.jsx)(`div`,{style:{width:`48px`,height:`48px`,borderRadius:`50%`,border:`3px solid rgba(255,255,255,0.12)`,borderTopColor:Array.isArray(g)&&g[0]||h,animation:`fe-call-spin 0.9s linear infinite`}}),(0,f.jsx)(`span`,{style:{fontSize:`15px`,color:`#6b7280`,letterSpacing:`0.01em`},children:`Connecting…`})]})]}):(0,f.jsxs)(`div`,{style:ne,children:[(0,f.jsx)(`style`,{children:ik}),(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,padding:`16px 16px 10px`,gap:`10px`,flexShrink:0},children:[(0,f.jsx)(`button`,{type:`button`,onClick:m,style:{width:`40px`,height:`40px`,borderRadius:`50%`,background:`rgba(0,0,0,0.06)`,border:`1px solid rgba(0,0,0,0.1)`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`#374151`,transition:`background 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(0,0,0,0.11)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(0,0,0,0.06)`},"aria-label":`Minimize call`,children:(0,f.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`15 18 9 12 15 6`})})}),(0,f.jsx)(rk,{colors:g,size:36,voiceState:ee}),(0,f.jsx)(`div`,{style:{flex:1,minWidth:0,fontSize:`15px`,fontWeight:600,color:`#111827`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:v}),(0,f.jsx)(`div`,{style:{flexShrink:0,padding:`3px 10px`,borderRadius:`999px`,background:`${h}18`,border:`1px solid ${h}44`,display:`flex`,alignItems:`center`},children:(0,f.jsx)(`span`,{style:{fontSize:`11px`,fontWeight:600,color:h,letterSpacing:`0.02em`,lineHeight:1},children:`On Call`})})]}),(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`16px`,padding:`0 24px 16px`},children:[(0,f.jsx)(ck,{headshot:o,name:v,size:116,primaryColor:h}),(0,f.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,f.jsx)(`div`,{style:{fontSize:`20px`,fontWeight:700,color:`#111827`,letterSpacing:`-0.01em`},children:v}),(0,f.jsx)(`div`,{style:{marginTop:`8px`,fontSize:`24px`,fontWeight:300,color:`#9ca3af`,letterSpacing:`0.06em`,fontVariantNumeric:`tabular-nums`},children:p(r)})]})]}),(0,f.jsxs)(`div`,{style:{flexShrink:0,display:`flex`,gap:`12px`,padding:`16px 24px 40px`},children:[(0,f.jsxs)(`button`,{type:`button`,onClick:d,style:{flex:1,height:`54px`,borderRadius:`14px`,background:i?`rgba(239,68,68,0.1)`:`rgba(0,0,0,0.06)`,border:i?`1.5px solid rgba(239,68,68,0.4)`:`1.5px solid rgba(0,0,0,0.1)`,cursor:`pointer`,color:i?`#ef4444`:`#374151`,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,fontSize:`14px`,fontWeight:600,transition:`all 0.2s ease`},"aria-label":i?`Unmute`:`Mute`,children:[i?(0,f.jsx)(OO,{size:18}):(0,f.jsx)(_O,{size:18}),i?`Unmute`:`Mute`]}),(0,f.jsxs)(`button`,{type:`button`,onClick:u,style:{flex:1,height:`54px`,borderRadius:`14px`,background:`rgba(239,68,68,0.9)`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,color:`white`,fontSize:`14px`,fontWeight:600,boxShadow:`0 4px 20px rgba(239,68,68,0.38)`,transition:`transform 0.15s ease, background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`#ef4444`,e.currentTarget.style.transform=`scale(1.02)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(239,68,68,0.9)`,e.currentTarget.style.transform=`scale(1)`},"aria-label":`End call`,children:[(0,f.jsx)(vO,{size:18}),`End Call`]})]})]})}function dk({agentName:e,agentHeadshot:t,fallbackAgentName:n,callDurationSeconds:r,isCallMuted:i,formatCallDuration:a,toggleCallMute:o,endWebRTCCall:s,onExpand:c,primaryColor:l=`#3B82F6`}){let u=e||n||`Agent`;return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(`style`,{children:ik}),(0,f.jsxs)(`div`,{role:`button`,tabIndex:0,onClick:c,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&c?.()},onMouseEnter:e=>{e.currentTarget.style.boxShadow=`0 8px 32px rgba(0,0,0,0.14), 0 2px 8px rgba(0,0,0,0.08), inset 0 1px 0 rgba(255,255,255,0.95)`,e.currentTarget.style.transform=`translateY(-2px)`},onMouseLeave:e=>{e.currentTarget.style.boxShadow=`0 4px 20px rgba(0,0,0,0.09), 0 1px 6px rgba(0,0,0,0.06), inset 0 1px 0 rgba(255,255,255,0.9)`,e.currentTarget.style.transform=`translateY(0)`},style:{display:`flex`,alignItems:`center`,gap:`12px`,padding:`10px 12px 10px 10px`,margin:`0 12px 8px`,borderRadius:`18px`,background:`rgba(255,255,255,0.88)`,backdropFilter:`blur(20px)`,WebkitBackdropFilter:`blur(20px)`,border:`1px solid rgba(255,255,255,0.65)`,boxShadow:`0 4px 20px rgba(0,0,0,0.09), 0 1px 6px rgba(0,0,0,0.06), inset 0 1px 0 rgba(255,255,255,0.9)`,cursor:`pointer`,animation:`fe-call-bar-slide-in 0.3s cubic-bezier(0.16,1,0.3,1)`,flexShrink:0,userSelect:`none`,outline:`none`,transition:`box-shadow 0.22s ease, transform 0.18s ease`},children:[(0,f.jsxs)(`div`,{style:{position:`relative`,flexShrink:0,width:`42px`,height:`42px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[(0,f.jsx)(`div`,{style:{position:`absolute`,inset:`-4px`,borderRadius:`50%`,background:`${l}28`,animation:`fe-call-avatar-breathe 2.8s ease-in-out infinite`}}),(0,f.jsx)(`div`,{style:{position:`absolute`,inset:`-2px`,borderRadius:`50%`,border:`1.5px solid ${l}55`}}),(0,f.jsx)(ck,{headshot:t,name:u,size:38,primaryColor:l})]}),(0,f.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(`div`,{style:{fontSize:`13px`,fontWeight:600,color:`#111827`,lineHeight:1.3,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:u}),(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,marginTop:`3px`},children:[(0,f.jsx)(`div`,{style:{width:`6px`,height:`6px`,borderRadius:`50%`,background:`#22c55e`,flexShrink:0,boxShadow:`0 0 4px rgba(34,197,94,0.6)`,animation:`fe-call-dot-blink 1.6s ease-in-out infinite`}}),(0,f.jsxs)(`span`,{style:{fontSize:`12px`,color:`#6b7280`,fontVariantNumeric:`tabular-nums`,letterSpacing:`0.01em`},children:[`On Call\xA0•\xA0`,a(r)]})]})]}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`8px`,alignItems:`center`,flexShrink:0},children:[(0,f.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),o()},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.12)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},style:{width:`36px`,height:`36px`,borderRadius:`50%`,background:i?`${l}18`:`rgba(0,0,0,0.05)`,border:i?`1.5px solid ${l}55`:`1.5px solid rgba(0,0,0,0.08)`,cursor:`pointer`,color:i?l:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0,transition:`all 0.18s ease`,boxShadow:i?`0 0 0 3px ${l}12`:`none`},"aria-label":i?`Unmute`:`Mute`,children:i?(0,f.jsx)(OO,{size:15}):(0,f.jsx)(_O,{size:15})}),(0,f.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),s()},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.12)`,e.currentTarget.style.boxShadow=`0 4px 16px rgba(239,68,68,0.55)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`,e.currentTarget.style.boxShadow=`0 2px 10px rgba(239,68,68,0.35)`},style:{width:`36px`,height:`36px`,borderRadius:`50%`,background:`#ef4444`,border:`none`,cursor:`pointer`,color:`white`,display:`flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0,boxShadow:`0 2px 10px rgba(239,68,68,0.35)`,transition:`all 0.18s ease`},"aria-label":`End call`,children:(0,f.jsx)(vO,{size:16})})]})]})]})}function fk(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=gh();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 pk={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function mk(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 hk(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 gk(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 _k({logo:e,style:t}){let n=gk(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 vk({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 yk(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)||e===`bot`&&(/\b(that'?s all|we'?re done)\b/i.test(n)||/\b(goodbye|bye)\b/i.test(n)||/\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))):!1}function bk({orbColors:e,...t}){return(0,f.jsx)(rk,{colors:e,...t})}function xk({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a,isClosing:o}){let s=n||pk.green,c=hk(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)(gO.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:`210px`,wordBreak:`break-word`,overflow:`hidden`,display:`-webkit-box`,WebkitLineClamp:4,WebkitBoxOrient:`vertical`},children:e.entryPrompt}),(0,f.jsxs)(gO.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)(gO.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)(bk,{size:l,orbColors:t})})]});return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(gO.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 Sk({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o,isClosing:s}){let c=n||pk.green,l=hk(c);return(0,f.jsxs)(gO.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)(bk,{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 Ck({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,chatId:o,historyRef:s,onMessageSync:c,voiceEndCounter:l,websiteName:u,voiceClientTools:p,preferLocalAgent:m}){(0,d.useEffect)(()=>(console.log(`[FlowEngage:VoiceDebug] 🔵 VoiceMode MOUNTED`),()=>console.log(`[FlowEngage:VoiceDebug] 🔴 VoiceMode UNMOUNTED`)),[]);let[h,g]=(0,d.useState)(`idle`),[_,v]=(0,d.useState)(!1),[y,b]=(0,d.useState)(!1),x=(0,d.useRef)(null),S=(0,d.useRef)(``),ee=(0,d.useRef)(async()=>{}),te=(0,d.useRef)(!1),ne=(0,d.useRef)(!1),re=(0,d.useRef)(!1),C=(0,d.useRef)(!1),ie=(0,d.useRef)(`minimized`),ae=(0,d.useRef)(null),oe=(0,d.useRef)(null),se=(0,d.useRef)(null),ce=(0,d.useRef)(0),le=(0,d.useRef)(!1),ue=(0,d.useRef)(`idle`),de=(0,d.useRef)(!1),fe=(0,d.useRef)(!1),pe=(0,d.useRef)(null),me=(0,d.useRef)(null),he=(0,d.useRef)(!1),ge=(0,d.useCallback)((e=`minimized`)=>{console.warn(`[FlowEngage:VoiceDebug] 🛑 requestSessionShutdown called`,{destination:e,stack:Error().stack?.split(`
|
|
638
|
-
`).slice(1,4).join(` | `)}),ie.current=e,C.current=!0,queueMicrotask(()=>{te.current||(te.current=!0,ee.current?.())})},[s]),_e=(0,d.useCallback)(async e=>{C.current=!0;try{hg()}catch{}if(i)try{Me(i)}catch{}try{await x.current?.endSession?.()}catch{}let t=ae.current,n=oe.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(ae.current=null,oe.current=null,x.current=null,g(`idle`),v(!1),te.current=!1,ug(),i)try{Ce(i)}catch{}typeof c==`function`&&await c(s.current),e?.()},[s,c,i,o,a]);return ee.current=()=>_e(ie.current===`chat`?t:n),(0,d.useEffect)(()=>{ne.current=_},[_]),(0,d.useEffect)(()=>{l&&ge(`chat`)},[l]),(0,d.useEffect)(()=>{let e=!1,l=null,d=null,f=null;return(async()=>{if(!r){g(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;s.current=[],S.current=``,te.current=!1,re.current=!1,C.current=!1,ie.current=`minimized`,lg({onBeforeNavigate:()=>{if(i&&s.current.length>0)try{let e=dg(s.current);e&&xe(i,e)}catch{}if(!Ph()){let e=ae.current,t=oe.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(()=>{}),ae.current=null,oe.current=null}catch{}}Te()}});let t=fk({...y_({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>S.current,requestEndSession:()=>{le.current=!0}}),...p||{}}),n=i?Se(i):null,c=!!n?.transcript,h=!!(i&&Me(i)),_=typeof window<`u`?window.location.pathname:`/`,y=typeof document<`u`?document.title:``,b=_.replace(/^\/[a-z]{2}(?:-[a-z]{2})?(?=\/|$)/i,``)||`/`,ee=b===`/`||b===``,se=null;if(!m)try{let e=await fetch(`${a}/api/voice/signed-url?siteId=${encodeURIComponent(i||``)}`,{method:`GET`,headers:{"Content-Type":`application/json`}});if(e.ok)se=(await e.json()).signedUrl||null,se&&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 _e={clientTools:t,connectionType:`websocket`,minSpeechDurationMs:50,...se?{signedUrl:se}:{agentId:r}},ve=(_.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),ye=``;y&&y.includes(`|`)&&(ye=y.split(`|`).map(e=>e.trim()).filter(Boolean).reduce((e,t)=>e.length<=t.length?e:t));let be=ye||ve||`this page`;if(se)if(h)_e.overrides={agent:{firstMessage:`Here we are — I've taken you to the ${be} page.`}},console.log(`[FlowEngage] 🔄 Agent-nav resume: firstMessage set for "${be}" (${_})`);else if(c)_e.overrides={agent:{firstMessage:`I'm still here. Go ahead!`}};else{let e=u||``;_e.overrides={agent:{firstMessage:ee?e?`Hi, welcome to ${e}!`:`Hi, welcome!`:`Welcome to the ${be} page!`}},ee||console.log(`[FlowEngage] 🏠 Page-context override: "${be}" for ${_}`)}else c&&(_e.overrides={agent:{firstMessage:``}});let Ce=!1,we=h?`NAVIGATION COMPLETE — Your brief intro has been spoken. PRIOR CONVERSATION CONTEXT (continue from here — do NOT re-introduce yourself):\n${n?.transcript?`Prior transcript:\n${n.transcript}\n`:`(no prior transcript)`}\nSTEP 1 — call fwh-get-current-page-mvp NOW with zero speech before it, to load the page sections.\nSTEP 2 — after the tool responds, speak 2-3 sentences about this page, drawing from your knowledge and the visitor's prior context above.\nSTEP 3 — then ask the visitor exactly this: "Would you like to know about a specific section, or should I give you a complete overview?"\nThen STOP — wait for their reply. Do NOT auto-highlight or auto-walkthrough.`:null,Ee=!1,De=!h&&!c?`Your greeting has been spoken. Wait for the visitor to ask a question or tell you what they need. Do NOT auto-start a walkthrough or highlight any sections — let the visitor lead.`:null,Oe=await hh.startSession({..._e,onConnect:({conversationId:e})=>{ae.current=e,oe.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`){me.current&&=(clearTimeout(me.current),null),g(`speaking`),ue.current=`speaking`,de.current=!0,he.current=!1,pe.current&&=(clearTimeout(pe.current),null);return}if(ue.current=`listening`,le.current){le.current=!1,ge();return}if(we&&!Ce){Ce=!0;try{x.current?.sendContextualUpdate?.(we)}catch{}}if(De&&!Ee){Ee=!0;try{x.current?.sendContextualUpdate?.(De)}catch{}}me.current&&clearTimeout(me.current),me.current=setTimeout(()=>{e||ue.current!==`speaking`&&(he.current||(me.current=null,ue.current=`listening`,g(`listening`),de.current&&fe.current&&!ne.current&&(pe.current&&clearTimeout(pe.current),pe.current=setTimeout(()=>{if(!e&&ue.current===`listening`&&!ne.current)try{x.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{}},15e3))))},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`){S.current=r,he.current=!0,fe.current=!0,me.current&&=(clearTimeout(me.current),null),pe.current&&=(clearTimeout(pe.current),null);try{hg()}catch{}}if(s.current=[...s.current,{sender:n,message:r,timestamp:new Date().toISOString()}],i)try{let e=dg(s.current);e&&xe(i,e)}catch{}if(yk(n,r)){le.current=!0;return}if(ne.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(ce.current+=1,ce.current===2)try{x.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 fwh-end-session-mvp tool to end the voice session. Do NOT ask again after that.`)}catch{}else ce.current>=5&&ge(`minimized`)}},onError:t=>{if(!e&&!C.current&&!re.current&&!Ae()){re.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{x.current?.setMicMuted?.(!0)}catch{}v(!0),g(`error`),ge(`chat`)}},onDisconnect:t=>{if(e||C.current||re.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:S.current||``,wasMuted:ne.current}),re.current=!0;try{x.current?.setMicMuted?.(!0)}catch{}v(!0),ge(`chat`)}});if(e){console.warn(`[FlowEngage:VoiceDebug] ❌ cancelled=true after startSession resolved — killing session immediately`),Oe.endSession().catch(()=>{});return}l=Oe,x.current=Oe,g(`listening`);try{let e=typeof window<`u`?window.location.href:``,r=`[]`;try{r=await t[`fwh-list-forms-mvp`]()}catch{}let a=`none`;if(typeof window<`u`&&typeof document<`u`)try{let e=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`,t=document.querySelector(`main, [role='main']`)||document.body,n=Array.from(t.querySelectorAll(`h1, h2, h3`)).filter(t=>!t.closest(e)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200);n.length||(n=Array.from(document.body.querySelectorAll(`h1, h2, h3`)).filter(t=>!t.closest(e)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200)),n.length&&(a=[...new Set(n)].slice(0,15).join(` | `))}catch{}let o=c&&!h?`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`:``;Oe.sendContextualUpdate(`${o}SESSION_CONTEXT (NOT a tool result — do NOT treat as CURRENT_PAGE): Visitor is on: ${e} | Approx headings for awareness only: ${a}. SiteId: ${i||`unknown`}. Forms: ${r}. The visitor is ALREADY on this page — do NOT offer to navigate there. WALKTHROUGH RULE: If the visitor requests a walkthrough, you MUST call fwh-get-current-page-mvp first (zero speech) to get the exact highlightable headings — do NOT use these approximate headings for highlighting. 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(Eh()){t=n;return}let r=t;t=n;let i=window.location.href,a=typeof document<`u`?document.title:``,o=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{hg()}catch{}let s=e=>(e.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`,c=s(r),l=s(n);typeof window<`u`&&(window.__fe_user_nav_during_speech={fromPath:r,toPath:n,fromPageName:c,toPageName:l,ts:Date.now()});try{x.current?.sendUserMessage?.(`[SYSTEM: I navigated away mid-walkthrough — I am now on the "${l}" page (${i}). Page title: "${a}". Sections: ${JSON.stringify(o)}. STOP everything. Do NOT describe the new page. Say EXACTLY: "I see you've navigated to the ${l} page — would you like me to continue what I was explaining, or shall I walk you through this page?" Then wait for my answer. IF I say continue/yes/carry on: resume speaking verbally from where you left off — do NOT call flowengage_navigate, do NOT call flowengage_highlight, the visitor will navigate themselves if needed. IF I want to hear about this page: call flowengage_highlight for sections of "${l}" only.]`)}catch{}};d=window.history.pushState.bind(window.history),window.history.pushState=(...e)=>{d(...e),setTimeout(n,50)},f=()=>setTimeout(n,50),window.addEventListener(`popstate`,f)}}catch(r){e||(console.error(`[FlowEngage] startSession failed`,r),r.message&&r.message.includes(`Too many voice sessions`)?(alert(r.message),n&&n(`minimized`)):(g(`error`),ie.current=`chat`,window.setTimeout(()=>{e||t?.()},0)))}})(),()=>{console.warn(`[FlowEngage:VoiceDebug] ⚠️ useEffect CLEANUP fired — session will be killed`,{agentId:r,siteId:i,apiBaseUrl:a}),e=!0,C.current=!0;try{hg()}catch{}if(i)try{Me(i)}catch{}typeof window<`u`&&(window.__fe_user_nav_during_speech=null),ug(),pe.current&&=(clearTimeout(pe.current),null),me.current&&=(clearTimeout(me.current),null),de.current=!1,he.current=!1,ue.current=`idle`,d&&typeof window<`u`&&(window.history.pushState=d),f&&typeof window<`u`&&window.removeEventListener(`popstate`,f);let t=l||x.current,n=ae.current,u=oe.current;if(t?.endSession?.().catch(()=>{}),n&&o&&a){let e=u?Math.round((Date.now()-u)/1e3):0,t=JSON.stringify({chatId:o,elevenLabsConversationId:n,duration:e,siteId:i}),r=`${a}/api/voice/save-chat-recording`;typeof navigator<`u`&&navigator.sendBeacon&&navigator.sendBeacon(r,new Blob([t],{type:`application/json`}))||fetch(r,{method:`POST`,headers:{"Content-Type":`application/json`},body:t,keepalive:!0}).catch(()=>{}),ae.current=null,oe.current=null}typeof c==`function`&&s.current.length>0&&c(s.current).catch?.(()=>{})}},[r,i,a,ge]),(0,d.useEffect)(()=>{if(!y)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;se.current&&!se.current.contains(t)&&b(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[y]),(0,f.jsxs)(`div`,{ref:se,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:[h===`listening`&&!_&&(0,f.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`white`,fontSize:`18px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Listening...`}),_&&(0,f.jsx)(`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)(bk,{size:72,voiceState:h,isMuted:_,orbColors:e})]}),h===`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(x.current)try{if(_){ce.current=0,await x.current.setMicMuted?.(!1),v(!1);try{x.current.sendContextualUpdate?.(`The visitor has unmuted. Resume normal interaction and wait for them to speak.`)}catch{}}else{ce.current=0,await x.current.setMicMuted?.(!0),v(!0);try{x.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:_?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:_?`#7f1d1d`:`#1f2937`,border:_?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:_?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},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)(`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)(_O,{size:16,color:`currentColor`})}),(0,f.jsx)(`button`,{onClick:()=>b(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)(TO,{size:16,color:`currentColor`})})]}),y&&(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:()=>{b(!1),ie.current=`chat`,_e(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)(EO,{}),`Enter Chat Mode`]}),(0,f.jsxs)(`button`,{onClick:()=>{b(!1),ie.current=`minimized`,_e(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)(DO,{}),`End Conversation`]}),(0,f.jsx)(`button`,{onClick:()=>b(!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 wk({orbColors:e}){let t=Array.isArray(e)&&e.length>0?e:[`#135bd8`,`#ef334b`,`#ffbd2e`],n=t[0],r=t[1]||t[0],i=t[2]||t[0];return(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,borderRadius:`50%`,flexShrink:0,background:`
|
|
485
|
+
`;function nO(e){let t=(e||``).replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t;return`${parseInt(n.slice(0,2),16)},${parseInt(n.slice(2,4),16)},${parseInt(n.slice(4,6),16)}`}function rO(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 iO(e,t){let n=Array.isArray(e)&&e.length>0?e:[t||`#3B82F6`],[r,i,a]=n;return n.length===1?[`radial-gradient(ellipse 110% 65% at 50% -5%, ${r}28 0%, transparent 68%)`,`radial-gradient(ellipse 90% 55% at 50% 108%, ${r}1a 0%, transparent 65%)`,`#f7f8fa`].join(`, `):n.length===2?[`radial-gradient(ellipse 80% 100% at -10% 50%, ${r}22 0%, transparent 70%)`,`radial-gradient(ellipse 80% 100% at 110% 50%, ${i}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `):[`radial-gradient(ellipse 80% 70% at -10% 50%, ${r}22 0%, transparent 70%)`,`radial-gradient(ellipse 70% 80% at 110% 30%, ${i}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 60% at 50% 110%, ${a}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `)}function aO({headshot:e,name:t,size:n=80,primaryColor:r=`#3B82F6`}){let i=(t||`A`)[0].toUpperCase(),a=rO(r),o=n>48?{boxShadow:`0 0 0 3px ${r}44`,border:`3px solid rgba(255,255,255,0.15)`}:{border:`1.5px solid ${r}55`};return e?(0,f.jsx)(`img`,{src:e,alt:t||`Agent`,style:{width:n,height:n,borderRadius:`50%`,objectFit:`cover`,position:`relative`,zIndex:1,flexShrink:0,...o}}):(0,f.jsx)(`div`,{style:{width:n,height:n,borderRadius:`50%`,background:`linear-gradient(135deg, ${r}, ${r}99)`,display:`flex`,alignItems:`center`,justifyContent:`center`,fontSize:Math.round(n*.36)+`px`,fontWeight:700,color:a,position:`relative`,zIndex:1,flexShrink:0,...o},children:i})}function oO(e){let t=(0,d.useRef)(null),n=(0,d.useCallback)(()=>{if(!t.current)return;let{audioContext:e,oscillator:n,interval:r,toneTimeout:i}=t.current;window.clearInterval(r),window.clearTimeout(i);try{n.stop()}catch{}try{e.close()}catch{}t.current=null},[]),r=(0,d.useCallback)(()=>{if(t.current||typeof window>`u`)return;let e=window.AudioContext||window.webkitAudioContext||null;if(e)try{let n=new e,r=n.createOscillator(),i=n.createGain();r.connect(i),i.connect(n.destination),r.frequency.value=0,r.type=`sine`,i.gain.value=.3;let a=()=>{t.current&&(window.clearTimeout(t.current.toneTimeout),r.frequency.value=440,t.current.toneTimeout=window.setTimeout(()=>{r.frequency.value=0},400))};n.state===`suspended`&&n.resume().catch(e=>{console.warn(`[FlowEngage] ringtone autoplay blocked`,e)}),r.start(),t.current={audioContext:n,oscillator:r,interval:null,toneTimeout:null},a(),t.current.interval=window.setInterval(a,1e3)}catch(e){console.warn(`[FlowEngage] failed to start ringtone`,e)}},[]);return(0,d.useEffect)(()=>{if(e){r();return}n()},[e,r,n]),(0,d.useEffect)(()=>()=>n(),[n]),n}function sO({incomingCall:e,activeCallId:t,callConnectionState:n,callDurationSeconds:r,isCallMuted:i,agentName:a,agentHeadshot:o,fallbackAgentName:s,acceptCall:c,rejectCall:l,endWebRTCCall:u,toggleCallMute:d,formatCallDuration:p,onMinimize:m,primaryColor:h=`#3B82F6`,orbColors:g,chatHistory:_=[]}){let v=a||s||`Agent`,y=e?`incoming`:n===`connecting`?`connecting`:`ongoing`,b=oO(!!e),x=async()=>{b(),await c()},S=async()=>{b(),await l()},ee=i?`muted`:n===`connecting`?`idle`:`listening`,te=y===`ongoing`,ne={position:`absolute`,inset:0,zIndex:10,display:`flex`,flexDirection:`column`,borderRadius:`inherit`,overflow:`hidden`,background:iO(g,h),animation:te?`fe-call-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`:`fe-call-fade-in 0.32s ease`};if(y===`incoming`){let e=Array.isArray(g)&&g.length>0?g:[h];return(0,f.jsxs)(`div`,{style:ne,children:[(0,f.jsx)(`style`,{children:tO}),(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`space-between`,padding:`60px 32px 56px`},children:[(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`22px`},children:[(0,f.jsxs)(`div`,{style:{position:`relative`,width:`96px`,height:`96px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[(0,f.jsx)(`div`,{style:{position:`absolute`,width:`96px`,height:`96px`,borderRadius:`50%`,background:`radial-gradient(circle, rgba(${nO(e[0])},0.2) 0%, transparent 70%)`,filter:`blur(10px)`,zIndex:0}}),[0,.5,1].map((t,n)=>(0,f.jsx)(`div`,{style:{position:`absolute`,width:`96px`,height:`96px`,borderRadius:`50%`,border:`1.5px solid ${e[n%e.length]}`,animation:`fe-call-ring-pulse 2.6s cubic-bezier(0.215,0.61,0.355,1) ${t}s infinite`,zIndex:1}},n)),(0,f.jsx)(aO,{headshot:o,name:v,size:82,primaryColor:h})]}),(0,f.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,f.jsx)(`div`,{style:{fontSize:`22px`,fontWeight:700,color:`#111827`,letterSpacing:`-0.015em`,lineHeight:1.2},children:v}),(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`6px`,marginTop:`8px`},children:[(0,f.jsx)(`div`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:e[0],boxShadow:`0 0 5px ${e[0]}88`,animation:`fe-call-dot-blink 1.4s ease-in-out infinite`}}),(0,f.jsx)(`span`,{style:{fontSize:`13px`,color:`#6b7280`,letterSpacing:`0.01em`},children:`Incoming call`})]})]})]}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`56px`,alignItems:`flex-end`},children:[(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`10px`},children:[(0,f.jsx)(`button`,{type:`button`,onClick:S,style:{width:`68px`,height:`68px`,borderRadius:`50%`,background:`#ef4444`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`white`,boxShadow:`0 6px 24px rgba(239,68,68,0.5)`,transition:`transform 0.15s ease, box-shadow 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.08)`,e.currentTarget.style.boxShadow=`0 8px 28px rgba(239,68,68,0.65)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`,e.currentTarget.style.boxShadow=`0 6px 24px rgba(239,68,68,0.5)`},"aria-label":`Decline call`,children:(0,f.jsx)(hD,{size:26})}),(0,f.jsx)(`span`,{style:{fontSize:`12px`,color:`#6b7280`,fontWeight:500,letterSpacing:`0.01em`},children:`Decline`})]}),(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`10px`},children:[(0,f.jsx)(`button`,{type:`button`,onClick:x,style:{width:`68px`,height:`68px`,borderRadius:`50%`,background:`#22c55e`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`white`,boxShadow:`0 6px 24px rgba(34,197,94,0.5)`,transition:`transform 0.15s ease, box-shadow 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.08)`,e.currentTarget.style.boxShadow=`0 8px 28px rgba(34,197,94,0.65)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`,e.currentTarget.style.boxShadow=`0 6px 24px rgba(34,197,94,0.5)`},"aria-label":`Accept call`,children:(0,f.jsx)(vD,{})}),(0,f.jsx)(`span`,{style:{fontSize:`12px`,color:`#6b7280`,fontWeight:500,letterSpacing:`0.01em`},children:`Accept`})]})]})]})]})}return y===`connecting`?(0,f.jsxs)(`div`,{style:ne,children:[(0,f.jsx)(`style`,{children:tO}),(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`24px`},children:[(0,f.jsx)(aO,{headshot:o,name:v,size:64,primaryColor:h}),(0,f.jsx)(`div`,{style:{width:`48px`,height:`48px`,borderRadius:`50%`,border:`3px solid rgba(255,255,255,0.12)`,borderTopColor:Array.isArray(g)&&g[0]||h,animation:`fe-call-spin 0.9s linear infinite`}}),(0,f.jsx)(`span`,{style:{fontSize:`15px`,color:`#6b7280`,letterSpacing:`0.01em`},children:`Connecting…`})]})]}):(0,f.jsxs)(`div`,{style:ne,children:[(0,f.jsx)(`style`,{children:tO}),(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,padding:`16px 16px 10px`,gap:`10px`,flexShrink:0},children:[(0,f.jsx)(`button`,{type:`button`,onClick:m,style:{width:`40px`,height:`40px`,borderRadius:`50%`,background:`rgba(0,0,0,0.06)`,border:`1px solid rgba(0,0,0,0.1)`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`#374151`,transition:`background 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(0,0,0,0.11)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(0,0,0,0.06)`},"aria-label":`Minimize call`,children:(0,f.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`15 18 9 12 15 6`})})}),(0,f.jsx)(eO,{colors:g,size:36,voiceState:ee}),(0,f.jsx)(`div`,{style:{flex:1,minWidth:0,fontSize:`15px`,fontWeight:600,color:`#111827`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:v}),(0,f.jsx)(`div`,{style:{flexShrink:0,padding:`3px 10px`,borderRadius:`999px`,background:`${h}18`,border:`1px solid ${h}44`,display:`flex`,alignItems:`center`},children:(0,f.jsx)(`span`,{style:{fontSize:`11px`,fontWeight:600,color:h,letterSpacing:`0.02em`,lineHeight:1},children:`On Call`})})]}),(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`16px`,padding:`0 24px 16px`},children:[(0,f.jsx)(aO,{headshot:o,name:v,size:116,primaryColor:h}),(0,f.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,f.jsx)(`div`,{style:{fontSize:`20px`,fontWeight:700,color:`#111827`,letterSpacing:`-0.01em`},children:v}),(0,f.jsx)(`div`,{style:{marginTop:`8px`,fontSize:`24px`,fontWeight:300,color:`#9ca3af`,letterSpacing:`0.06em`,fontVariantNumeric:`tabular-nums`},children:p(r)})]})]}),(0,f.jsxs)(`div`,{style:{flexShrink:0,display:`flex`,gap:`12px`,padding:`16px 24px 40px`},children:[(0,f.jsxs)(`button`,{type:`button`,onClick:d,style:{flex:1,height:`54px`,borderRadius:`14px`,background:i?`rgba(239,68,68,0.1)`:`rgba(0,0,0,0.06)`,border:i?`1.5px solid rgba(239,68,68,0.4)`:`1.5px solid rgba(0,0,0,0.1)`,cursor:`pointer`,color:i?`#ef4444`:`#374151`,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,fontSize:`14px`,fontWeight:600,transition:`all 0.2s ease`},"aria-label":i?`Unmute`:`Mute`,children:[i?(0,f.jsx)(TD,{size:18}):(0,f.jsx)(mD,{size:18}),i?`Unmute`:`Mute`]}),(0,f.jsxs)(`button`,{type:`button`,onClick:u,style:{flex:1,height:`54px`,borderRadius:`14px`,background:`rgba(239,68,68,0.9)`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,color:`white`,fontSize:`14px`,fontWeight:600,boxShadow:`0 4px 20px rgba(239,68,68,0.38)`,transition:`transform 0.15s ease, background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`#ef4444`,e.currentTarget.style.transform=`scale(1.02)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(239,68,68,0.9)`,e.currentTarget.style.transform=`scale(1)`},"aria-label":`End call`,children:[(0,f.jsx)(hD,{size:18}),`End Call`]})]})]})}function cO({agentName:e,agentHeadshot:t,fallbackAgentName:n,callDurationSeconds:r,isCallMuted:i,formatCallDuration:a,toggleCallMute:o,endWebRTCCall:s,onExpand:c,primaryColor:l=`#3B82F6`}){let u=e||n||`Agent`;return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(`style`,{children:tO}),(0,f.jsxs)(`div`,{role:`button`,tabIndex:0,onClick:c,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&c?.()},onMouseEnter:e=>{e.currentTarget.style.boxShadow=`0 8px 32px rgba(0,0,0,0.14), 0 2px 8px rgba(0,0,0,0.08), inset 0 1px 0 rgba(255,255,255,0.95)`,e.currentTarget.style.transform=`translateY(-2px)`},onMouseLeave:e=>{e.currentTarget.style.boxShadow=`0 4px 20px rgba(0,0,0,0.09), 0 1px 6px rgba(0,0,0,0.06), inset 0 1px 0 rgba(255,255,255,0.9)`,e.currentTarget.style.transform=`translateY(0)`},style:{display:`flex`,alignItems:`center`,gap:`12px`,padding:`10px 12px 10px 10px`,margin:`0 12px 8px`,borderRadius:`18px`,background:`rgba(255,255,255,0.88)`,backdropFilter:`blur(20px)`,WebkitBackdropFilter:`blur(20px)`,border:`1px solid rgba(255,255,255,0.65)`,boxShadow:`0 4px 20px rgba(0,0,0,0.09), 0 1px 6px rgba(0,0,0,0.06), inset 0 1px 0 rgba(255,255,255,0.9)`,cursor:`pointer`,animation:`fe-call-bar-slide-in 0.3s cubic-bezier(0.16,1,0.3,1)`,flexShrink:0,userSelect:`none`,outline:`none`,transition:`box-shadow 0.22s ease, transform 0.18s ease`},children:[(0,f.jsxs)(`div`,{style:{position:`relative`,flexShrink:0,width:`42px`,height:`42px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[(0,f.jsx)(`div`,{style:{position:`absolute`,inset:`-4px`,borderRadius:`50%`,background:`${l}28`,animation:`fe-call-avatar-breathe 2.8s ease-in-out infinite`}}),(0,f.jsx)(`div`,{style:{position:`absolute`,inset:`-2px`,borderRadius:`50%`,border:`1.5px solid ${l}55`}}),(0,f.jsx)(aO,{headshot:t,name:u,size:38,primaryColor:l})]}),(0,f.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(`div`,{style:{fontSize:`13px`,fontWeight:600,color:`#111827`,lineHeight:1.3,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:u}),(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,marginTop:`3px`},children:[(0,f.jsx)(`div`,{style:{width:`6px`,height:`6px`,borderRadius:`50%`,background:`#22c55e`,flexShrink:0,boxShadow:`0 0 4px rgba(34,197,94,0.6)`,animation:`fe-call-dot-blink 1.6s ease-in-out infinite`}}),(0,f.jsxs)(`span`,{style:{fontSize:`12px`,color:`#6b7280`,fontVariantNumeric:`tabular-nums`,letterSpacing:`0.01em`},children:[`On Call\xA0•\xA0`,a(r)]})]})]}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`8px`,alignItems:`center`,flexShrink:0},children:[(0,f.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),o()},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.12)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},style:{width:`36px`,height:`36px`,borderRadius:`50%`,background:i?`${l}18`:`rgba(0,0,0,0.05)`,border:i?`1.5px solid ${l}55`:`1.5px solid rgba(0,0,0,0.08)`,cursor:`pointer`,color:i?l:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0,transition:`all 0.18s ease`,boxShadow:i?`0 0 0 3px ${l}12`:`none`},"aria-label":i?`Unmute`:`Mute`,children:i?(0,f.jsx)(TD,{size:15}):(0,f.jsx)(mD,{size:15})}),(0,f.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),s()},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.12)`,e.currentTarget.style.boxShadow=`0 4px 16px rgba(239,68,68,0.55)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`,e.currentTarget.style.boxShadow=`0 2px 10px rgba(239,68,68,0.35)`},style:{width:`36px`,height:`36px`,borderRadius:`50%`,background:`#ef4444`,border:`none`,cursor:`pointer`,color:`white`,display:`flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0,boxShadow:`0 2px 10px rgba(239,68,68,0.35)`,transition:`all 0.18s ease`},"aria-label":`End call`,children:(0,f.jsx)(hD,{size:16})})]})]})]})}function lO(e,t={}){let n=t.maxChars??4500;if(!Array.isArray(e)||e.length===0)return``;let r=[];for(let t of e){if(!t||t.isPending)continue;let e=String(t.sender||``).toLowerCase(),n=null;if(e===`user`?n=`Visitor`:(e===`bot`||e===`ai`||e===`agent`)&&(n=`Assistant`),!n)continue;let i=String(t.message||``).replace(/<[^>]+>/g,` `).replace(/\s+/g,` `).trim().slice(0,1200);i&&r.push(`${n}: ${i}`)}if(r.length===0)return``;let i=r.join(`
|
|
486
|
+
`);return i.length>n&&(i=`…(earlier messages omitted)
|
|
487
|
+
`+i.slice(-n)),i}var Q=`fe-vv`;function uO(){if(typeof document>`u`||document.getElementById(`${Q}-styles`))return;let e=`
|
|
488
|
+
/* ── Action toast ───────────────────────────────────────────────────────────── */
|
|
489
|
+
#${Q}-toast {
|
|
490
|
+
position: fixed;
|
|
491
|
+
top: 16px;
|
|
492
|
+
left: 50%;
|
|
493
|
+
transform: translateX(-50%) translateY(-160%);
|
|
494
|
+
background: rgba(10, 10, 20, 0.88);
|
|
495
|
+
color: #f1f5f9;
|
|
496
|
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
|
497
|
+
font-size: 13px;
|
|
498
|
+
font-weight: 500;
|
|
499
|
+
line-height: 1.4;
|
|
500
|
+
padding: 9px 18px 9px 14px;
|
|
501
|
+
border-radius: 999px;
|
|
502
|
+
z-index: 2147483640;
|
|
503
|
+
pointer-events: none;
|
|
504
|
+
opacity: 0;
|
|
505
|
+
transition: transform 0.28s cubic-bezier(0.34, 1.56, 0.64, 1), opacity 0.2s ease;
|
|
506
|
+
white-space: nowrap;
|
|
507
|
+
display: flex;
|
|
508
|
+
align-items: center;
|
|
509
|
+
gap: 9px;
|
|
510
|
+
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.35), 0 1px 4px rgba(0, 0, 0, 0.2);
|
|
511
|
+
backdrop-filter: blur(12px);
|
|
512
|
+
-webkit-backdrop-filter: blur(12px);
|
|
513
|
+
border: 1px solid rgba(255,255,255,0.08);
|
|
514
|
+
max-width: 90vw;
|
|
515
|
+
overflow: hidden;
|
|
516
|
+
text-overflow: ellipsis;
|
|
517
|
+
}
|
|
518
|
+
#${Q}-toast.${Q}-show {
|
|
519
|
+
transform: translateX(-50%) translateY(0);
|
|
520
|
+
opacity: 1;
|
|
521
|
+
}
|
|
522
|
+
#${Q}-toast .${Q}-spin {
|
|
523
|
+
width: 13px;
|
|
524
|
+
height: 13px;
|
|
525
|
+
border: 2px solid rgba(255,255,255,0.25);
|
|
526
|
+
border-top-color: #a78bfa;
|
|
527
|
+
border-radius: 50%;
|
|
528
|
+
animation: ${Q}-spin 0.65s linear infinite;
|
|
529
|
+
flex-shrink: 0;
|
|
530
|
+
}
|
|
531
|
+
#${Q}-toast .${Q}-icon {
|
|
532
|
+
font-size: 14px;
|
|
533
|
+
flex-shrink: 0;
|
|
534
|
+
line-height: 1;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/* ── Navigation progress bar ────────────────────────────────────────────────── */
|
|
538
|
+
#${Q}-bar {
|
|
539
|
+
position: fixed;
|
|
540
|
+
top: 0;
|
|
541
|
+
left: 0;
|
|
542
|
+
width: 0%;
|
|
543
|
+
height: 3px;
|
|
544
|
+
background: linear-gradient(90deg, #7c3aed, #06b6d4, #7c3aed);
|
|
545
|
+
background-size: 200% 100%;
|
|
546
|
+
z-index: 2147483647;
|
|
547
|
+
pointer-events: none;
|
|
548
|
+
opacity: 0;
|
|
549
|
+
transition: width 0.35s ease, opacity 0.25s ease;
|
|
550
|
+
box-shadow: 0 0 12px #7c3aed88;
|
|
551
|
+
animation: ${Q}-bar-shimmer 1.5s linear infinite;
|
|
552
|
+
}
|
|
553
|
+
#${Q}-bar.${Q}-bar-active {
|
|
554
|
+
opacity: 1;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/* ── Field active highlight (about to fill) ─────────────────────────────────── */
|
|
558
|
+
.${Q}-field-active {
|
|
559
|
+
outline: 2.5px solid #7c3aed !important;
|
|
560
|
+
outline-offset: 3px !important;
|
|
561
|
+
box-shadow: 0 0 0 5px rgba(124, 58, 237, 0.14), 0 0 20px rgba(124, 58, 237, 0.28) !important;
|
|
562
|
+
border-radius: 5px !important;
|
|
563
|
+
transition: outline 0.18s ease, box-shadow 0.18s ease !important;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/* ── Field filled confirmation (green flash) ────────────────────────────────── */
|
|
567
|
+
.${Q}-field-filled {
|
|
568
|
+
outline: 2px solid #10b981 !important;
|
|
569
|
+
outline-offset: 3px !important;
|
|
570
|
+
box-shadow: 0 0 0 4px rgba(16, 185, 129, 0.12), 0 0 16px rgba(16, 185, 129, 0.22) !important;
|
|
571
|
+
border-radius: 5px !important;
|
|
572
|
+
animation: ${Q}-fill-flash 0.45s ease forwards !important;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/* ── Ghost cursor ────────────────────────────────────────────────────────────── */
|
|
576
|
+
#${Q}-cursor {
|
|
577
|
+
position: fixed;
|
|
578
|
+
width: 22px;
|
|
579
|
+
height: 22px;
|
|
580
|
+
pointer-events: none;
|
|
581
|
+
z-index: 2147483645;
|
|
582
|
+
opacity: 0;
|
|
583
|
+
transition:
|
|
584
|
+
left 0.32s cubic-bezier(0.25, 0.46, 0.45, 0.94),
|
|
585
|
+
top 0.32s cubic-bezier(0.25, 0.46, 0.45, 0.94),
|
|
586
|
+
opacity 0.2s ease;
|
|
587
|
+
transform: translate(-4px, -4px);
|
|
588
|
+
}
|
|
589
|
+
#${Q}-cursor.${Q}-cursor-visible {
|
|
590
|
+
opacity: 1;
|
|
591
|
+
}
|
|
592
|
+
#${Q}-cursor.${Q}-cursor-click {
|
|
593
|
+
animation: ${Q}-cursor-click 0.25s ease;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/* ── Click ripple ────────────────────────────────────────────────────────────── */
|
|
597
|
+
.${Q}-ripple {
|
|
598
|
+
position: absolute;
|
|
599
|
+
border-radius: 50%;
|
|
600
|
+
transform: scale(0);
|
|
601
|
+
background: rgba(124, 58, 237, 0.35);
|
|
602
|
+
animation: ${Q}-ripple-anim 0.55s linear forwards;
|
|
603
|
+
pointer-events: none;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/* ── Keyframes ───────────────────────────────────────────────────────────────── */
|
|
607
|
+
@keyframes ${Q}-spin {
|
|
608
|
+
to { transform: rotate(360deg); }
|
|
609
|
+
}
|
|
610
|
+
@keyframes ${Q}-bar-shimmer {
|
|
611
|
+
0% { background-position: 0% 0%; }
|
|
612
|
+
100% { background-position: 200% 0%; }
|
|
613
|
+
}
|
|
614
|
+
@keyframes ${Q}-fill-flash {
|
|
615
|
+
0% { background-color: rgba(16, 185, 129, 0.10); }
|
|
616
|
+
40% { background-color: rgba(16, 185, 129, 0.22); }
|
|
617
|
+
100% { background-color: transparent; }
|
|
618
|
+
}
|
|
619
|
+
@keyframes ${Q}-ripple-anim {
|
|
620
|
+
to { transform: scale(3.5); opacity: 0; }
|
|
621
|
+
}
|
|
622
|
+
@keyframes ${Q}-cursor-click {
|
|
623
|
+
0% { transform: translate(-4px,-4px) scale(1); }
|
|
624
|
+
50% { transform: translate(-4px,-4px) scale(0.82); }
|
|
625
|
+
100% { transform: translate(-4px,-4px) scale(1); }
|
|
626
|
+
}
|
|
627
|
+
`,t=document.createElement(`style`);t.id=`${Q}-styles`,t.textContent=e,(document.head||document.documentElement).appendChild(t)}var dO=null,fO=null;function pO(){return(!dO||!dO.isConnected)&&(dO=document.createElement(`div`),dO.id=`${Q}-toast`,document.body.appendChild(dO)),dO}function mO(e,{spinner:t=!0,icon:n=null,duration:r=0}={}){if(typeof document>`u`)return;uO(),fO&&=(clearTimeout(fO),null);let i=pO();if(i.innerHTML=``,n){let e=document.createElement(`span`);e.className=`${Q}-icon`,e.textContent=n,i.appendChild(e)}else if(t){let e=document.createElement(`span`);e.className=`${Q}-spin`,i.appendChild(e)}let a=document.createElement(`span`);a.textContent=e,i.appendChild(a),i.classList.remove(`${Q}-show`),i.offsetHeight,i.classList.add(`${Q}-show`),r>0&&(fO=setTimeout(()=>hO(),r))}function hO(e=0){dO&&(e>0?fO=setTimeout(()=>{dO&&dO.classList.remove(`${Q}-show`)},e):dO&&dO.classList.remove(`${Q}-show`))}var gO=null,_O=[];function vO(){return(!gO||!gO.isConnected)&&(gO=document.createElement(`div`),gO.id=`${Q}-bar`,document.body.appendChild(gO)),gO}function yO(){if(typeof document>`u`)return;uO(),_O.forEach(clearTimeout),_O=[];let e=vO();e.style.transition=`none`,e.style.width=`0%`,e.classList.add(`${Q}-bar-active`),e.offsetHeight,e.style.transition=`width 0.35s ease, opacity 0.25s ease`;let t=[[80,`width 0.6s ease`],[92,`width 1.2s ease`]],n=50;for(let[e,r]of t){let t=n,i=e,a=r;_O.push(setTimeout(()=>{gO&&(gO.style.transition=a,gO.style.width=`${i}%`)},t)),n+=800}}function bO(){gO&&(_O.forEach(clearTimeout),_O=[],gO.style.transition=`width 0.2s ease`,gO.style.width=`100%`,_O.push(setTimeout(()=>{gO&&(gO.style.transition=`opacity 0.35s ease`,gO.style.opacity=`0`,_O.push(setTimeout(()=>{gO&&(gO.style.width=`0%`,gO.classList.remove(`${Q}-bar-active`))},380)))},220)))}var xO=`<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 22 22" fill="none">
|
|
628
|
+
<filter id="${Q}-csh">
|
|
629
|
+
<feDropShadow dx="1" dy="2" stdDeviation="1.5" flood-color="#00000060"/>
|
|
630
|
+
</filter>
|
|
631
|
+
<path d="M4 2L19 10.5L11 12.8L8 20L4 2Z"
|
|
632
|
+
fill="white" stroke="#1e1b4b" stroke-width="1.6" stroke-linejoin="round"
|
|
633
|
+
filter="url(#${Q}-csh)"/>
|
|
634
|
+
</svg>`,SO=null,CO=!1;function wO(){return(!SO||!SO.isConnected)&&(SO=document.createElement(`div`),SO.id=`${Q}-cursor`,SO.innerHTML=xO,document.body.appendChild(SO),CO=!1),SO}async function TO(e){if(typeof document>`u`||!e)return;uO();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=wO();CO||=(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 kO(360)}function EO(e=!1){SO&&(e?(SO.classList.remove(`${Q}-cursor-visible`),CO=!1):(SO.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{CO=!1},250)))}async function DO(e){SO&&(SO.classList.add(`${Q}-cursor-click`),await kO(280),SO.classList.remove(`${Q}-cursor-click`))}function OO(e){if(!e||typeof document>`u`)return;uO();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 kO(e){return new Promise(t=>setTimeout(t,e))}function $(...e){En()&&console.log(`[FlowEngage:voice-tools]`,...e)}function AO(){if(typeof document>`u`)return!1;let e=/(^|\W)(404|page not found|not found|page (?:doesn'?t|does not) exist|no longer exists|couldn'?t find (?:this|that|the) page|error 404|oops[!,. ].*(?:not found|doesn'?t exist))(\W|$)/i,t=(document.title||``).trim();if(t&&e.test(t))return!0;let n=document.querySelector(`main, [role="main"], #content, .content`)||document.body;if(n){let t=n.querySelectorAll(`h1, h2`);for(let n of t){let t=(n.textContent||``).replace(/\s+/g,` `).trim();if(t&&t.length<80&&e.test(t))return!0}}return!1}function jO(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function MO(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(!Mn(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function NO(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function PO(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 NO(r.join(` `))}if(e.labels&&e.labels.length)return NO(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return NO(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return NO(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return NO(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=NO(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 NO(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return NO(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?NO(o):null}function FO(){let e=[];return MO(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(Mn(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=jO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function IO(){return FO().map((e,t)=>{let n={formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:PO(e),placeholder:e.placeholder||null};return e.tagName===`SELECT`&&(n.options=Array.from(e.options).filter(e=>e.value!==``&&!e.disabled).map(e=>({value:e.value,text:e.text.trim()})),n.currentValue=e.value||null),n})}function LO(){let e=[];return MO(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(Mn(e)||e.disabled)return!1;try{let t=jO(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 RO(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,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 BO(e,t){let n=[];MO(e=>{let t=Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"], a[href]`));n.push(...t.filter(e=>{if(Mn(e)||e.disabled)return!1;try{let t=jO(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:zO(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=RO(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function VO(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 HO(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 UO(){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 WO(){let e=e=>{let t=Array.from(e).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)&&!e.closest(`nav, footer, header, aside, .nav, .footer, .header, .sidebar`)),n=[],r=0;for(;r<t.length;){let e=t[r],i=Nn(e);if(!i||i.length<2){r++;continue}let a=i;if(i.length<40&&!/[.!?:;]$/.test(i)&&r+1<t.length){let n=t[r+1],o=Nn(n);o&&n.tagName===e.tagName&&o.length<60&&(e.nextElementSibling===n||e.parentElement===n.parentElement)&&(a=`${i} ${o}`,r++)}a.length>2&&a.length<200&&n.push(a),r++}return n},t=document.querySelector(`main, [role='main']`)||document.body,n=e(t.querySelectorAll(`h1, h2, h3`));n.length||(n=e(document.body.querySelectorAll(`h1, h2, h3`))),n.length||(n=e(document.body.querySelectorAll(`h4, h5`)));let r=[...new Set(n)].slice(0,15),i=Array.from(t.querySelectorAll(`h1`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)&&!e.closest(`nav, footer, header, aside, .nav, .footer, .header, .sidebar`)),a=null;if(i.length===1){let e=Nn(i[0]);e&&r[0]&&r[0].toLowerCase().trim()===e.toLowerCase().trim()&&(a=r[0])}let o=``;try{let e=t.querySelector(`h1, h2, h3, h4, h5`);if(e){let n=document.createRange();n.setStart(t,0),n.setEndBefore(e);let r=n.cloneContents(),i=[];r.querySelectorAll(`p, li`).forEach(e=>{let t=e.textContent.replace(/\s+/g,` `).trim();t.length>20&&i.push(t)}),o=i.join(` `).slice(0,600)}}catch{}return{headings:r,pageTitleHeading:a,introText:o}}function GO(e){if(!e||typeof document>`u`)return``;let t=new Set([`script`,`style`,`noscript`,`svg`,`iframe`,`nav`,`footer`,`header`,`aside`]),n=parseInt(e.tagName[1],10),r=Array.from({length:n},(e,t)=>`h${t+1}`).join(`, `),i=Array.from(document.querySelectorAll(r)).filter(e=>!e.closest(jn)),a=i.indexOf(e),o=a===-1?null:i[a+1],s=document.createRange();try{if(s.setStartAfter(e),o)s.setEndBefore(o);else{let e=document.querySelector(`main, [role='main'], article`)||document.body;s.setEnd(e,e.childNodes.length)}}catch{return e.textContent.replace(/\s+/g,` `).trim()}let c;try{c=s.cloneContents()}catch{return e.textContent.replace(/\s+/g,` `).trim()}let l=[];function u(e){if(e.nodeType===Node.TEXT_NODE){let t=e.textContent.replace(/\s+/g,` `).trim();t&&l.push(t);return}if(e.nodeType!==Node.ELEMENT_NODE)return;let n=e.tagName.toLowerCase();if(!t.has(n)){if(n===`ul`||n===`ol`){let t=Array.from(e.querySelectorAll(`:scope > li`)).map(e=>{let t=e.textContent.replace(/\s+/g,` `).trim();return t?`• ${t}`:null}).filter(Boolean);t.length&&l.push(t.join(`
|
|
635
|
+
`));return}if(n===`table`){let t=Array.from(e.querySelectorAll(`tr`)).map(e=>Array.from(e.querySelectorAll(`td, th`)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(Boolean).join(` | `)).filter(Boolean);t.length&&l.push(t.join(`
|
|
636
|
+
`));return}if(n===`form`){let t=Array.from(e.querySelectorAll(`input, textarea, select`)).map(e=>{let t=(e.getAttribute(`type`)||`text`).toLowerCase();if([`hidden`,`submit`,`button`,`reset`].includes(t))return null;let n=e.getAttribute(`placeholder`)||e.getAttribute(`aria-label`)||e.getAttribute(`name`)||t;return n?String(n).trim().slice(0,40):null}).filter(Boolean),n=e.querySelector(`button[type="submit"], input[type="submit"]`),r=n?(n.textContent||n.value||`Submit`).trim().slice(0,40):`Submit`;t.length&&l.push(`[FORM PRESENT: ${t.length} field(s) — ${t.join(`, `)}. Submit button: "${r}"]`);return}if(n===`p`||n===`blockquote`){let t=e.textContent.replace(/\s+/g,` `).trim();t.length>2&&l.push(t);return}if(/^h[1-6]$/.test(n)){let t=e.textContent.replace(/\s+/g,` `).trim();t.length>2&&l.push(t);return}for(let t of e.childNodes)u(t)}}for(let e of c.childNodes)u(e);let d=new Set;return l.filter(e=>{let t=e.substring(0,80);return d.has(t)?!1:(d.add(t),!0)}).join(`
|
|
637
|
+
`).replace(/\n{3,}/g,`
|
|
638
|
+
|
|
639
|
+
`).trim()}function KO(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={"fwh-navigate-mvp":async n=>{$(`fwh-navigate-mvp ▶ raw parameters:`,n);let i=VO(n),a=HO(i);if($(`fwh-navigate-mvp · coerced:`,{url:a,sectionText:i.section_text??i.sectionText??i.section,expectedLandmarks:Array.isArray(i.expected_landmarks)?i.expected_landmarks:Array.isArray(i.expectedLandmarks)?i.expectedLandmarks:[]}),!a){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`fwh-navigate-mvp ✖`,e),e}if(typeof window<`u`)try{let e=new URL(a,window.location.href);if(e.origin!==window.location.origin&&/^https?:$/i.test(e.protocol)){let t=e.hostname;return $(`fwh-navigate-mvp ✖ external URL blocked:`,e.href),`EXTERNAL_LINK_BLOCKED: The URL "${a}" points to an external site (${t}) that opens in a new tab. I cannot open new tabs or navigate to external sites. Tell the visitor exactly this: "That link opens an external app — I'm not able to open it for you, but you can click the link directly in the navigation header."`}}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 $(`fwh-navigate-mvp ✖ 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{}let e=window.__fe_user_nav_during_speech;if(e&&Date.now()-e.ts<3e4)try{if(new URL(a,window.location.href).pathname===e.fromPath)return $(`flowengage_navigate ✖ blocked — would navigate back to page visitor just left`,e),`NAV_BLOCKED: The visitor just left "${e.fromPageName}" and is now on "${e.toPageName}". Do NOT navigate them back. If they said "continue", resume verbally from where you left off — no navigation needed. If they want to return, they will navigate themselves.`}catch{}}if(!await hr(a,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`PAGE_NOT_IN_SITE: "${a}" is NOT a real page on this site — do NOT guess or invent URL paths. Do NOT tell the visitor you are taking them there. Instead, find the REAL page: look at your Popular Pages / Site Pages list for the closest actual match, or call fwh-list-nav-links-mvp (to read the site's real menu links) or fwh-search-mvp (to find the right page). If a close match exists (e.g. the visitor said "support" and the site has "Technical Support"), tell them the ACTUAL page name and ask "we don't have a page called that, but we do have [real page] — would you like me to take you there?" Then navigate only to that verified URL.`;return $(`fwh-navigate-mvp ✖ blocked`,e),e}try{mO(`Navigating to ${a}...`,{spinner:!0}),yO(),An();try{let e=r?r():``;if(e&&t){let n=lO([{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{}let n=`this`;try{let e=new URL(a,window.location.href).pathname.split(`/`).filter(Boolean).pop()||``;n=e?e.replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()):`Home`}catch{}t&&typeof window<`u`&&w(t,window.location.href,e,n),vr(e),$(`fwh-navigate-mvp → real navigation`,a);let i=typeof window<`u`&&!!Yn();if(typeof window<`u`&&window.__fe_triggerVoiceNavHooks&&window.__fe_triggerVoiceNavHooks(),i&&Bn(12e3),xr(a,{voiceActive:!0}).catch(()=>{}),i)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`;$(`fwh-navigate-mvp → SPA nav complete. target:`,e,`actual:`,n);try{typeof window<`u`&&window.scrollTo(0,0)}catch{}let s=[],c=null,l=``,u=Date.now()+12e3;for(;Date.now()<u&&(await new Promise(e=>setTimeout(e,300)),{headings:s,pageTitleHeading:c,introText:l}=WO(),!(s.length>=1)););UO(),$(`fwh-navigate-mvp → page headings collected:`,s,`titleHeading:`,c);let d=s.length?s.join(` | `):`none`,f=s.length?`Use ONLY these exact heading strings for fwh-highlight-mvp — never invent or abbreviate.`:`No headings collected yet — call fwh-get-current-page-mvp immediately (no speech) to get the live headings before speaking or highlighting.`,p=c?` "${c}" is the PAGE TITLE, not a content section — do not fwh-highlight-mvp it separately; if doing a walkthrough, just fold this intro into your opening line: "${l||`(no intro text found)`}"`:l?` No separate page-title heading detected, but this intro text precedes the first section — mention it briefly before covering sections: "${l}"`:``,m=``;try{if(s.length>0){let e=s.slice(0,3),t=[];for(let n of e){let e=ur(null,n);if(e){let r=GO(e).substring(0,800);r&&t.push(`[Section: ${n}] ${r}`)}}t.length>0&&(m=` CONTENT FOR FIRST FEW SECTIONS: ${t.join(` | `)}. Use this content to answer immediately if the visitor asks about one of these sections.`)}}catch{}return AO()?(yr(),$(`fwh-navigate-mvp ✖ landed on a not-found/404 page:`,r),`NAVIGATION_PAGE_NOT_FOUND. The page at ${r} does not exist — it shows a "not found"/404 error, not real content. Do NOT offer a page overview, do NOT describe or highlight any sections, do NOT claim the navigation succeeded. Tell the visitor EXACTLY: "It looks like that page doesn't exist — I couldn't find it. Would you like me to take you somewhere else?" Then STOP and wait for their reply.`):i?(yr(),`OK_NAVIGATE_SPA. Visitor is now on: ${r} (page: "${o}") | Section headings: ${d}.${p} ${f}${m} Speak EXACTLY: "I have navigated you on ${o} page. Do you want to know about any specific section or want a complete overview?" Then STOP — wait for their reply.`):(yr(),`OK_NAVIGATE_SPA. CURRENT PAGE IS: ${r} (page: "${o}") | Section headings: ${d}.${p} ${f}${m} Speak EXACTLY: "I have navigated you on ${o} page. Do you want to know about any specific section or want a complete overview?" Then STOP — wait for their reply.`)}catch{}let o=`this`;try{let e=new URL(a,window.location.href).pathname.split(`/`).filter(Boolean).pop()||``;o=e?e.replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()):`Home`}catch{}return`OK_NAVIGATE_RELOADING. Navigating to the page now; the voice session will resume automatically on the new page. When the session resumes, say EXACTLY: "I have navigated you on ${o} page. Do you want to know about any specific section or want a complete overview?" Then STOP — wait for the visitor's reply.`}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`fwh-navigate-mvp ✖`,t),mO(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{bO(),hO(900)}},"fwh-highlight-mvp":async e=>{$(`fwh-highlight-mvp ▶`,e);let t=VO(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;if(typeof window<`u`&&window.__fe_user_nav_during_speech){let e=window.__fe_user_nav_during_speech,t=window.location.pathname;if(Date.now()-e.ts>=3e4)window.__fe_user_nav_during_speech=null;else return $(`flowengage_highlight ✖ blocked — user navigated during speech`,e),`NAV_CHANGED: The visitor navigated from "${e.fromPageName}" to "${e.toPageName}" (current path: ${t}) while you were speaking. STOP the current walkthrough immediately. DO NOT call flowengage_highlight again. Say out loud: "I see you've navigated to the ${e.toPageName} page — do you want me to continue what I was explaining, or shall I guide you through this page?" Wait for the visitor's answer before doing anything else.`}UO();let i=(e=>e&&e.replace(/^\d+\.\s*/,``).replace(/^["']|["']$/g,``).trim())(r),a=ur(n||null,i||null);if(!a&&i){let e=Date.now()+600;for(;!a&&Date.now()<e;)await new Promise(e=>setTimeout(e,50)),UO(),a=ur(null,i)}if(!a){$(`fwh-highlight-mvp ✖ no element for:`,i||n);let{headings:e}=WO(),t=e.length?`Page headings: ${e.map(e=>`"${e}"`).join(` | `)}. Use one of these EXACT strings for section_text — no numbers, no quotes around them.`:`No headings found — skip highlight and continue speaking.`;return`HIGHLIGHT_NOT_FOUND: "${i||n}" on the current page. ${t}`}return kn(a),$(`fwh-highlight-mvp ✓`,i||n),`OK_HIGHLIGHT: "${i||n}". WALKTHROUGH: continue immediately to the next section — do NOT pause between sections.`},"fwh-read-content-mvp":async e=>{$(`fwh-read-content-mvp ▶`,e);let t=VO(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=ur(null,n);if(!t)return`Could not find section "${n}" on the page.`;e=GO(t)}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, #flowengage-root, .flowengage-shell, .flowengage-widget-root`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),$(`fwh-read-content-mvp ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return $(`fwh-read-content-mvp ✖`,e.message),`Could not read page content: ${e.message}`}},"fwh-page-content-mvp":async e=>{$(`fwh-page-content-mvp ▶`,e);let r=VO(e),i=r?.url||r?.page_url||``;if($(`fwh-page-content-mvp · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return $(`fwh-page-content-mvp ✖ missing url`),`Missing url parameter.`;if(!t)return $(`fwh-page-content-mvp ✖ no siteId`),`Site is not configured.`;if(!n)return $(`fwh-page-content-mvp ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;$(`fwh-page-content-mvp → 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($(`fwh-page-content-mvp · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return $(`fwh-page-content-mvp ✖`,e),`${e} FALLBACK REQUIRED: This page is not in the search index. Call fwh-read-content-mvp (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 $(`fwh-page-content-mvp ✓`,`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 $(`fwh-page-content-mvp ✖`,t),t}},"fwh-search-mvp":async e=>{$(`fwh-search-mvp ▶`,e);let r=VO(e).query;if(!r)return $(`fwh-search-mvp ✖ missing query`),`Missing query parameter.`;if(!t)return $(`fwh-search-mvp ✖ no siteId`),`Search unavailable (no siteId configured).`;if(!n)return $(`fwh-search-mvp ✖ no api base`),`Search unavailable (no API base URL).`;try{let e=`${n}/api/site-tools/search`;$(`fwh-search-mvp → 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($(`fwh-search-mvp · HTTP`,i.status,`success:`,a.success),!a.success||!a.results?.length)return`No results found for that query. Try rephrasing, or use fwh-read-content-mvp to read the current page.`;let o=a.results.slice(0,5).map((e,t)=>`${t+1}. ${e.title||e.url} (${e.url})${e.snippet?` — ${e.snippet}`:``}`).join(`
|
|
640
|
+
`);return $(`fwh-search-mvp ✓`,`${a.results.length} result(s)`),`SEARCH_RESULTS:\n${o}`}catch(e){return $(`fwh-search-mvp ✖`,e.message),`Search failed. Use fwh-read-content-mvp to read the current page instead.`}},"fwh-list-nav-links-mvp":async()=>{if($(`fwh-list-nav-links-mvp ▶`),typeof window>`u`)return`Cannot read navigation (no browser context).`;let e=new Map,t=[],n=[`nav a`,`[role='navigation'] a`,`header a`,`.navbar a`,`.nav a`,`.menu a`,`.navigation a`,`.header a`,`[class*='nav'] a`,`[class*='menu'] a`,`[class*='header'] a`];if(MO(t=>{for(let r of n)try{t.querySelectorAll(r).forEach(t=>{if(Mn(t))return;let n=t.getAttribute(`href`),r=(t.textContent||``).replace(/\s+/g,` `).trim();if(!r||!n||n===`#`||n.startsWith(`javascript:`))return;try{let e=t.parentElement;if(e&&jO(e).display===`none`&&!e.closest(`nav, [role='navigation'], header, [class*='nav'], [class*='menu']`))return}catch{}let i=r.toLowerCase()+`|`+n;e.has(i)||e.set(i,{text:r,href:n})})}catch{}t.querySelectorAll(`select`).forEach(t=>{if(Mn(t))return;let n=PO(t);/nav|menu|page|section|go to/i.test(n||t.name||t.id||``)&&Array.from(t.options).forEach(r=>{if(!r.value||r.disabled)return;let i=r.text.trim();if(!i)return;let a=i.toLowerCase()+`|`+r.value;e.has(a)||e.set(a,{text:i,href:r.value,isSelectOption:!0,selectLabel:n||t.name||`dropdown`})})})}),e.forEach(e=>t.push(e)),!t.length)return`NAV_LINKS: No navigation links found on this page. Use fwh-read-content-mvp to read page content or fwh-search-mvp to search the site.`;let r=t.slice(0,50).map((e,t)=>`${t+1}. "${e.text}"${e.isSelectOption?` (dropdown option in "${e.selectLabel}")`:``} → ${e.href}`).join(`
|
|
641
|
+
`);return $(`fwh-list-nav-links-mvp ✓`,`${t.length} links`),`NAV_LINKS (${t.length} total, showing up to 50):\n${r}\n\nIMPORTANT: Use the EXACT text shown above when reading link names to the visitor. Do NOT rename, abbreviate, or invent options not listed here. To navigate, call fwh-navigate-mvp with the href value.`},"fwh-end-session-mvp":async()=>($(`fwh-end-session-mvp ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),"fwh-request-email-mvp":async()=>($(`fwh-request-email-mvp ▶`),typeof e.requestEmailCollection==`function`&&e.requestEmailCollection(),`EMAIL_BOX_SHOWN. An email input text box is now visible to the visitor. Say EXACTLY: "Please enter your email in the text box to continue." Then stop and wait silently — do NOT ask them to say it aloud, do NOT repeat, and do NOT answer any other question until you receive the EMAIL_SAVED message.`),"fwh-get-current-page-mvp":async()=>{if($(`fwh-get-current-page-mvp ▶`),typeof window>`u`)return`Cannot determine current page (no browser context).`;let e=window.location.href,t=window.location.pathname,n=document.title||``,{headings:r,pageTitleHeading:i,introText:a}=WO();$(`fwh-get-current-page-mvp ✓`,{url:e,path:t,title:n}),$(`fwh-get-current-page-mvp → page headings collected:`,r,`titleHeading:`,i);let o=i?` NOTE: "${i}" is the PAGE TITLE, not a content section — do NOT fwh-highlight-mvp it or list it as a separate section in a walkthrough. Instead, open with a brief 1-2 sentence summary of this intro text before covering the real sections: "${a||`(no intro text captured)`}"`:a?` NOTE: no separate page-title heading was detected, but this intro text appears before the first section — open your walkthrough with a brief 1-2 sentence summary of it before covering sections: "${a}"`:``;if(!r.length)return`CURRENT_PAGE. URL: ${e} | Title: ${n} |${o} No structured section headings found on this page. If there is intro text above, describe it; otherwise describe the page from your knowledge. Do not call this tool again.`;let s=r.map(e=>`"${e}"`).join(` | `);return`CURRENT_PAGE. URL: ${e} | Title: ${n} | Page sections (${r.length} total): ${s}.${o} *** WALKTHROUGH RULES: (1) For fwh-highlight-mvp, pass the heading text EXACTLY as shown — no numbers, no extra punctuation, no paraphrasing. (2) TIMING IS CRITICAL: the tool fires AFTER the speech that comes before it. This means: put the SHORT TRANSITION (1-5 words) BEFORE the tool call, put the FULL DESCRIPTION AFTER the tool call. Pattern: "Transition phrase." + fwh-highlight-mvp("Heading") + "Full description (3-4 sentences)". NEVER describe a section before calling its highlight tool. (3) DO NOT call this tool again. If the visitor requested a walkthrough: START IT NOW${o?` (open with the intro note above first)`:``} — "Let me walk you through this." + fwh-highlight-mvp("${r[0]||`first heading`}") + "Description..." etc. Cover ALL ${r.length} sections without pausing. ***`},"fwh-list-forms-mvp":async()=>{let e=IO(),t=LO();$(`fwh-list-forms-mvp ✓`,`${e.length} field(s)`,`${t.length} button(s)`);let n=e.map(e=>({...e,inputCategory:e.tag===`SELECT`?`dropdown_select`:`text_input`}));return JSON.stringify({fields:n,buttons:t,hint:`field_key: use the label/placeholder/name shown above. CRITICAL: fields with inputCategory='dropdown_select' are SELECT elements — their field_key must match the SELECT's own label (e.g. 'Company Size'), NOT the option text (e.g. 'Small Business') and NOT a nearby text input label. Never fill a SELECT option value into a text input.`})},"fwh-fill-form-mvp":async()=>`FORM_FILLING_DISABLED: Form filling is not available at this time. Tell the visitor what fields are present (use fwh-list-forms-mvp) and ask them to fill the form themselves.`,"fwh-click-button-mvp":async e=>{let t=VO(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`fwh-click-button-mvp ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=BO(n,i);if(!r)return $(`fwh-click-button-mvp ✖ no match`),`Could not find a button matching "${n}". Call fwh-list-forms-mvp to see button texts.`;try{mO(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await TO(r),r.focus?.(),await DO(r),OO(r),r.click();let e=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`fwh-click-button-mvp ✓`,t),mO(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`fwh-click-button-mvp ✖`,t),mO(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{EO(),hO(700)}}};return{...a,highlightOnPage:a[`fwh-highlight-mvp`],getPageContent:a[`fwh-page-content-mvp`],endVoiceSession:a[`fwh-end-session-mvp`],listPageForms:a[`fwh-list-forms-mvp`],fillFormFields:a[`fwh-fill-form-mvp`],clickPageButton:a[`fwh-click-button-mvp`]}}function qO(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=En();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 JO={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function YO(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 XO(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 ZO(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 QO({logo:e,style:t}){let n=ZO(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 $O({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 ek(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)||e===`bot`&&(/\b(that'?s all|we'?re done)\b/i.test(n)||/\b(goodbye|bye)\b/i.test(n)||/\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))):!1}function tk({orbColors:e,...t}){return(0,f.jsx)(eO,{colors:e,...t})}function nk({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a,isClosing:o}){let s=n||JO.green,c=XO(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)(Sm.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:`210px`,wordBreak:`break-word`,overflow:`hidden`,display:`-webkit-box`,WebkitLineClamp:4,WebkitBoxOrient:`vertical`},children:e.entryPrompt}),(0,f.jsxs)(Sm.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)(Sm.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)(tk,{size:l,orbColors:t})})]});return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(Sm.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 rk({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o,isClosing:s}){let c=n||JO.green,l=XO(c);return(0,f.jsxs)(Sm.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)(tk,{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 ik({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,chatId:o,historyRef:s,onMessageSync:c,voiceEndCounter:l,websiteName:u,voiceFirstMessage:p,captureVisitorEmail:m,emailRequired:h}){(0,d.useEffect)(()=>(console.log(`[FlowEngage:VoiceDebug] 🔵 VoiceMode MOUNTED`),()=>console.log(`[FlowEngage:VoiceDebug] 🔴 VoiceMode UNMOUNTED`)),[]);let[g,_]=(0,d.useState)(`idle`),[v,y]=(0,d.useState)(!1),[b,x]=(0,d.useState)(!1),[S,ee]=(0,d.useState)(!1),[te,ne]=(0,d.useState)(``),[re,ie]=(0,d.useState)(``),ae=(0,d.useRef)(!1),oe=(0,d.useRef)(!1),se=(0,d.useRef)(null),ce=(0,d.useRef)(0),le=(0,d.useRef)(``),C=(0,d.useRef)(null),ue=(0,d.useRef)(``),de=(0,d.useRef)(async()=>{}),fe=(0,d.useRef)(!1),pe=(0,d.useRef)(!1),me=(0,d.useRef)(!1),he=(0,d.useRef)(!1),ge=(0,d.useRef)(`minimized`),_e=(0,d.useRef)(null),ve=(0,d.useRef)(null),ye=(0,d.useRef)(null),be=(0,d.useRef)(0),we=(0,d.useRef)(!1),Ee=(0,d.useRef)(`idle`),De=(0,d.useRef)(!1),Oe=(0,d.useRef)(!1),ke=(0,d.useRef)(null),je=(0,d.useRef)(null),w=(0,d.useRef)(!1),Ne=(0,d.useCallback)((e=`minimized`)=>{console.warn(`[FlowEngage:VoiceDebug] 🛑 requestSessionShutdown called`,{destination:e,stack:Error().stack?.split(`
|
|
642
|
+
`).slice(1,4).join(` | `)}),ge.current=e,he.current=!0,queueMicrotask(()=>{fe.current||(fe.current=!0,de.current?.())})},[s]),Pe=(0,d.useCallback)(()=>{se.current&&=(clearTimeout(se.current),null)},[]),Fe=(0,d.useCallback)(()=>{Pe(),se.current=setTimeout(()=>{if(!(!oe.current||ae.current))if(ce.current<3){ce.current+=1;try{C.current?.sendUserMessage?.(`[SYSTEM: The visitor still has NOT entered their email in the text box. Remind them once, briefly and warmly: 'I still need your email in the box below to continue — could you enter it, please?' Then stay completely silent again. Do NOT answer any other question until the email is provided.]`)}catch{}Fe()}else{try{C.current?.sendUserMessage?.(`[SYSTEM: The visitor did not provide their email after multiple reminders. Say a brief, warm goodbye EXACTLY like: 'Since I haven't received your email, I'll close this session for now. Feel free to come back anytime — take care!' Then stop talking. Do NOT ask for the email again.]`)}catch{}oe.current=!1,ee(!1),Pe(),we.current=!0}},1e4)},[Pe]),Ie=(0,d.useCallback)(async e=>{he.current=!0;try{An()}catch{}if(i)try{Me(i)}catch{}try{await C.current?.endSession?.()}catch{}let t=_e.current,n=ve.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(_e.current=null,ve.current=null,C.current=null,_(`idle`),y(!1),fe.current=!1,Tr(),i)try{Ce(i)}catch{}typeof c==`function`&&await c(s.current),e?.()},[s,c,i,o,a]);de.current=()=>Ie(ge.current===`chat`?t:n),(0,d.useEffect)(()=>{pe.current=v},[v]),(0,d.useEffect)(()=>{l&&Ne(`chat`)},[l]),(0,d.useEffect)(()=>{let e=!1,l=null,d=null,f=null;return(async()=>{if(!r){_(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;s.current=[],ue.current=``,fe.current=!1,me.current=!1,he.current=!1,ge.current=`minimized`,wr({onBeforeNavigate:()=>{if(i&&s.current.length>0)try{let e=lO(s.current);e&&xe(i,e)}catch{}if(!Yn()){let e=_e.current,t=ve.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(()=>{}),_e.current=null,ve.current=null}catch{}}Te()}});let t=qO(KO({siteId:i||null,apiBaseUrl:a||null,chatId:o||null,getLastUserVoiceText:()=>ue.current,requestEndSession:()=>{we.current=!0},requestEmailCollection:()=>{ae.current||oe.current||(oe.current=!0,ce.current=0,ee(!0),Fe())}})),n=i?Se(i):null,c=!!n?.transcript,m=i?Me(i):null,g=!!m,v=typeof window<`u`?window.location.pathname:`/`,b=typeof document<`u`?document.title:``,x=v.replace(/^\/[a-z]{2}(?:-[a-z]{2})?(?=\/|$)/i,``)||`/`,S=x===`/`||x===``,te=null;try{let e=await fetch(`${a}/api/voice/signed-url?siteId=${encodeURIComponent(i||``)}`,{method:`GET`,headers:{"Content-Type":`application/json`}});if(e.ok)te=(await e.json()).signedUrl||null,te&&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 ne={clientTools:t,connectionType:`websocket`,minSpeechDurationMs:50,...te?{signedUrl:te}:{agentId:r}},re=(v.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),ie=``;b&&b.includes(`|`)&&(ie=b.split(`|`).map(e=>e.trim()).filter(Boolean).reduce((e,t)=>e.length<=t.length?e:t));let se=ie||re||`this page`;if(te)if(g){let e=m?.pageName||se;ne.overrides={agent:{firstMessage:`I have navigated you on ${e} page. Do you want to know about any specific section or want a complete overview?`}},console.log(`[FlowEngage] 🔄 Agent-nav resume: firstMessage set for "${e}" (${v})`)}else if(c)ne.overrides={agent:{firstMessage:`Welcome back! I see you're now on the ${se} page. Would you like me to continue what I was explaining before, or would you like to know about this page instead?`}};else{let e=u||``;ne.overrides={agent:{firstMessage:p||(S?e?`Hi, welcome to ${e}! How may I help you?`:`Hi, welcome! How may I help you?`:`Welcome to the ${se} page!`)}},S||console.log(`[FlowEngage] 🏠 Page-context override: "${se}" for ${v}`)}else c&&(ne.overrides={agent:{firstMessage:``}});let de=!1,ye=g?`NAVIGATION COMPLETE — The exact phrase "I have navigated you on [page] page. Do you want to know about any specific section or want a complete overview?" has already been spoken as your firstMessage. DO NOT repeat it. PRIOR CONVERSATION CONTEXT:\n${n?.transcript?`Prior transcript:\n${n.transcript}\n`:`(no prior transcript)`}\nNow STOP — wait silently for the visitor's reply. Do NOT speak, do NOT call any tool until the visitor responds. When they reply: if they name a specific section → call fwh-get-current-page-mvp then answer immediately; if they say "overview" or anything non-specific → call fwh-get-current-page-mvp (zero speech) then do a full highlighted walkthrough.`:null,Ce=!1,Pe=!g&&!c?`Your greeting has been spoken. Wait for the visitor to ask a question or tell you what they need. Do NOT auto-start a walkthrough or highlight any sections — let the visitor lead.`:null,Ie=c&&!g,Le=!1,Re=Ie?`The question "Would you like me to continue what I was explaining before, or would you like to know about this page instead?" has already been spoken as your firstMessage. DO NOT repeat it. PRIOR CONVERSATION CONTEXT:\n${n?.transcript?`Prior transcript:\n${n.transcript}\n`:`(no prior transcript, or the visitor navigated before saying much)`}\nNow STOP — wait silently for the visitor's reply. Do NOT speak, do NOT call any tool until they respond. When they reply: if they want you to CONTINUE the previous topic → resume verbally from the prior transcript above, do NOT call fwh-get-current-page-mvp or describe the new page unless they ask. If they want to know about THIS page → call fwh-get-current-page-mvp (zero speech) then proceed as a normal fresh-page walkthrough/description. If their reply is ambiguous, ask them to clarify which they'd prefer rather than guessing.`:null,ze=!1,Be=!1,Ve=!!h,He=await pD.startSession({...ne,onConnect:({conversationId:e})=>{_e.current=e,ve.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`){je.current&&=(clearTimeout(je.current),null),_(`speaking`),Ee.current=`speaking`,De.current=!0,w.current=!1,ke.current&&=(clearTimeout(ke.current),null);return}if(Ee.current=`listening`,we.current){we.current=!1,Ne();return}if(Ve&&!Be){Be=!0,de=!0,Ce=!0;try{C.current?.sendContextualUpdate?.(`CRITICAL — EMAIL REQUIRED BEFORE ANYTHING ELSE. The visitor has not provided their email. Do NOT speak right now. Wait silently for the visitor to speak first. The MOMENT the visitor says ANYTHING — a question, a request, or just a greeting — your ENTIRE next response must be EXACTLY this one sentence: "Before I answer that, could you please enter your email in the text box below?" Do NOT answer their question. Do NOT say anything about the topic. Do NOT begin an answer and then switch — your first word must be "Before". After you say that sentence, stay completely silent until you receive an EMAIL_SAVED message, then thank them briefly and answer their question in full.`)}catch{}}if(ye&&!de){de=!0;try{C.current?.sendContextualUpdate?.(ye)}catch{}}if(Re&&!Le){Le=!0;try{C.current?.sendContextualUpdate?.(Re)}catch{}}if(Pe&&!Ce){Ce=!0;try{C.current?.sendContextualUpdate?.(Pe)}catch{}}je.current&&clearTimeout(je.current),je.current=setTimeout(()=>{e||Ee.current!==`speaking`&&(w.current||(je.current=null,Ee.current=`listening`,_(`listening`),De.current&&Oe.current&&!pe.current&&!oe.current&&(ke.current&&clearTimeout(ke.current),ke.current=setTimeout(()=>{if(!e&&Ee.current===`listening`&&!pe.current&&!oe.current)try{C.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{}},15e3))))},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`){ue.current=r,w.current=!0,Oe.current=!0,je.current&&=(clearTimeout(je.current),null),ke.current&&=(clearTimeout(ke.current),null);try{An()}catch{}Ve&&!ze&&!ae.current&&(ze=!0,le.current=r,oe.current||(oe.current=!0,ce.current=0,ee(!0),Fe()))}if(s.current=[...s.current,{sender:n,message:r,timestamp:new Date().toISOString()}],i)try{let e=lO(s.current);e&&xe(i,e)}catch{}if(ek(n,r)){we.current=!0;return}if(pe.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(be.current+=1,be.current===2)try{C.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 fwh-end-session-mvp tool to end the voice session. Do NOT ask again after that.`)}catch{}else be.current>=5&&Ne(`minimized`)}},onError:t=>{if(!e&&!he.current&&!me.current&&!Ae()){me.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{C.current?.setMicMuted?.(!0)}catch{}y(!0),_(`error`),Ne(`chat`)}},onDisconnect:t=>{if(e||he.current||me.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:ue.current||``,wasMuted:pe.current}),me.current=!0;try{C.current?.setMicMuted?.(!0)}catch{}y(!0),Ne(`chat`)}});if(e){console.warn(`[FlowEngage:VoiceDebug] ❌ cancelled=true after startSession resolved — killing session immediately`),He.endSession().catch(()=>{});return}l=He,C.current=He,_(`listening`);try{let e=typeof window<`u`?window.location.href:``,r=`[]`;try{r=await t[`fwh-list-forms-mvp`]()}catch{}let a=`none`;if(typeof window<`u`&&typeof document<`u`)try{let e=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`,t=document.querySelector(`main, [role='main']`)||document.body,n=Array.from(t.querySelectorAll(`h1, h2, h3`)).filter(t=>!t.closest(e)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200);n.length||(n=Array.from(document.body.querySelectorAll(`h1, h2, h3`)).filter(t=>!t.closest(e)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200)),n.length&&(a=[...new Set(n)].slice(0,15).join(` | `))}catch{}let o=c&&!g?`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`:``;He.sendContextualUpdate(`${o}SESSION_CONTEXT (NOT a tool result — do NOT treat as CURRENT_PAGE): Visitor is on: ${e} | Approx headings for awareness only: ${a}. SiteId: ${i||`unknown`}. Forms: ${r}. The visitor is ALREADY on this page — do NOT offer to navigate there. WALKTHROUGH RULE: When the visitor asks for a walkthrough or overview of this page, you MUST IMMEDIATELY call fwh-get-current-page-mvp (zero speech — call it silently with NO words before it) to get the exact highlightable headings. The approximate headings above are for routing awareness ONLY — they are NOT precise enough for fwh-highlight-mvp. Do NOT skip fwh-get-current-page-mvp. 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(Vn()){t=n;return}let r=t;t=n;let i=window.location.href,a=typeof document<`u`?document.title:``,o=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{An()}catch{}let s=e=>(e.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`,c=s(r),l=s(n);typeof window<`u`&&(window.__fe_user_nav_during_speech={fromPath:r,toPath:n,fromPageName:c,toPageName:l,ts:Date.now()});try{C.current?.sendUserMessage?.(`[SYSTEM: I navigated away mid-walkthrough — I am now on the "${l}" page (${i}). Page title: "${a}". Sections: ${JSON.stringify(o)}. STOP everything. Do NOT describe the new page. Say EXACTLY: "I see you've navigated to the ${l} page — would you like me to continue what I was explaining, or shall I walk you through this page?" Then wait for my answer. IF I say continue/yes/carry on: resume speaking verbally from where you left off — do NOT call flowengage_navigate, do NOT call flowengage_highlight, the visitor will navigate themselves if needed. IF I want to hear about this page: call flowengage_highlight for sections of "${l}" only.]`)}catch{}};d=window.history.pushState.bind(window.history),window.history.pushState=(...e)=>{d(...e),setTimeout(n,50)},f=()=>setTimeout(n,50),window.addEventListener(`popstate`,f)}}catch(r){e||(console.error(`[FlowEngage] startSession failed`,r),r.message&&r.message.includes(`Too many voice sessions`)?(alert(r.message),n&&n(`minimized`)):(_(`error`),ge.current=`chat`,window.setTimeout(()=>{e||t?.()},0)))}})(),()=>{console.warn(`[FlowEngage:VoiceDebug] ⚠️ useEffect CLEANUP fired — session will be killed`,{agentId:r,siteId:i,apiBaseUrl:a}),e=!0,he.current=!0;try{An()}catch{}if(i)try{Me(i)}catch{}typeof window<`u`&&(window.__fe_user_nav_during_speech=null),Tr(),ke.current&&=(clearTimeout(ke.current),null),je.current&&=(clearTimeout(je.current),null),se.current&&=(clearTimeout(se.current),null),De.current=!1,w.current=!1,Ee.current=`idle`,d&&typeof window<`u`&&(window.history.pushState=d),f&&typeof window<`u`&&window.removeEventListener(`popstate`,f);let t=l||C.current,n=_e.current,u=ve.current;if(t?.endSession?.().catch(()=>{}),n&&o&&a){let e=u?Math.round((Date.now()-u)/1e3):0,t=JSON.stringify({chatId:o,elevenLabsConversationId:n,duration:e,siteId:i}),r=`${a}/api/voice/save-chat-recording`;typeof navigator<`u`&&navigator.sendBeacon&&navigator.sendBeacon(r,new Blob([t],{type:`application/json`}))||fetch(r,{method:`POST`,headers:{"Content-Type":`application/json`},body:t,keepalive:!0}).catch(()=>{}),_e.current=null,ve.current=null}typeof c==`function`&&s.current.length>0&&c(s.current).catch?.(()=>{})}},[r,i,a,Ne]),(0,d.useEffect)(()=>{if(!b)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;ye.current&&!ye.current.contains(t)&&x(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[b]);let Le=async()=>{if(C.current)try{if(v){be.current=0,await C.current.setMicMuted?.(!1),y(!1);try{C.current.sendContextualUpdate?.(`The visitor has unmuted. Resume normal interaction and wait for them to speak.`)}catch{}}else{be.current=0,await C.current.setMicMuted?.(!0),y(!0);try{C.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{}},Re=(0,d.useCallback)(async e=>{e?.preventDefault?.();let t=te.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)){ie(`Please enter a valid email address.`);return}ie(``);try{typeof m==`function`&&await m(t)}catch{}ae.current=!0,oe.current=!1,Pe(),ee(!1),ne(``);let n=le.current;le.current=``;try{C.current?.sendUserMessage?.(`[SYSTEM: EMAIL_SAVED — the visitor typed and submitted their email address. Say a brief 'Thank you!' and then `+(n?`immediately answer their original question fully: "${n}".`:`continue helping them.`)+` Do NOT ask for their email again.]`)}catch{}},[te,m,Pe]),ze=Array.isArray(e)&&e[0]||`#3B82F6`;return(0,f.jsxs)(`div`,{ref:ye,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:[S&&(0,f.jsxs)(`form`,{onSubmit:Re,style:{width:`270px`,maxWidth:`calc(100vw - 40px)`,boxSizing:`border-box`,background:`rgba(15,22,36,0.97)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,padding:`16px`,display:`flex`,flexDirection:`column`,gap:`10px`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,f.jsx)(`span`,{style:{color:`white`,fontSize:`13px`,fontWeight:600,lineHeight:1.4},children:`Please enter your email to continue`}),(0,f.jsx)(`input`,{type:`email`,inputMode:`email`,autoComplete:`email`,autoFocus:!0,value:te,onChange:e=>{ne(e.target.value),re&&ie(``)},placeholder:`you@example.com`,style:{width:`100%`,boxSizing:`border-box`,padding:`10px 12px`,borderRadius:`10px`,border:re?`1.5px solid #ef4444`:`1.5px solid #4b5563`,background:`#1f2937`,color:`white`,fontSize:`14px`,outline:`none`}}),re&&(0,f.jsx)(`span`,{style:{color:`#f87171`,fontSize:`12px`},children:re}),(0,f.jsx)(`button`,{type:`submit`,disabled:!te.trim(),style:{width:`100%`,padding:`10px 12px`,borderRadius:`10px`,border:`none`,background:te.trim()?ze:`#374151`,color:`white`,fontSize:`14px`,fontWeight:600,cursor:te.trim()?`pointer`:`default`,transition:`background 0.2s ease`},children:`Submit`})]}),(0,f.jsxs)(`div`,{style:{position:`relative`},children:[g===`listening`&&!v&&(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...`}),v&&(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)(tk,{size:72,voiceState:g,isMuted:v,orbColors:e})]}),g===`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:Le,title:v?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:v?`#7f1d1d`:`#1f2937`,border:v?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:v?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:v?(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)(mD,{size:16,color:`currentColor`})}),(0,f.jsx)(`button`,{onClick:()=>x(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)(SD,{size:16,color:`currentColor`})})]}),b&&(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:()=>{x(!1),ge.current=`chat`,Ie(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)(CD,{}),`Enter Chat Mode`]}),(0,f.jsxs)(`button`,{onClick:()=>{x(!1),ge.current=`minimized`,Ie(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)(wD,{}),`End Conversation`]}),(0,f.jsx)(`button`,{onClick:()=>x(!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 ak({orbColors:e}){let t=Array.isArray(e)&&e.length>0?e:[`#135bd8`,`#ef334b`,`#ffbd2e`],n=t[0],r=t[1]||t[0],i=t[2]||t[0];return(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,borderRadius:`50%`,flexShrink:0,background:`
|
|
639
643
|
radial-gradient(circle at 18% 50%, ${n} 0%, ${n}99 35%, transparent 65%),
|
|
640
644
|
radial-gradient(circle at 82% 50%, ${r} 0%, ${r}99 35%, transparent 65%),
|
|
641
645
|
radial-gradient(circle at 50% 82%, ${i} 0%, ${i}99 30%, transparent 58%),
|
|
642
646
|
white
|
|
643
|
-
`.replace(/\s+/g,` `).trim()}})}var Tk=()=>(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 Ek({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,voiceEnabled:Ee,headerBgColor:De,onNewChat:Oe,showPoweredBy:ke,privacyPolicyUrl:Ae,getVisitorChatHistory:je,resumeChat:w,isSessionRestoring:Me,isClosing:Ne}){let Pe=c.length>0,Fe=x||S||b,Ie=!!ge,[Le,Re]=(0,d.useState)(!1),[ze,Be]=(0,d.useState)(!1),[Ve,He]=(0,d.useState)([]),[Ue,We]=(0,d.useState)(!1),T=(0,d.useRef)(null),[Ge,Ke]=(0,d.useState)(()=>typeof window<`u`?window.visualViewport?.height??window.innerHeight:600),[qe,Je]=(0,d.useState)(0);(0,d.useEffect)(()=>{if(!s)return;let e=window.visualViewport;if(!e)return;let t=()=>{Ke(e.height),Je(Math.max(0,window.innerHeight-e.offsetTop-e.height))};return e.addEventListener(`resize`,t),e.addEventListener(`scroll`,t),t(),()=>{e.removeEventListener(`resize`,t),e.removeEventListener(`scroll`,t)}},[s]);let Ye=s&&window.innerHeight-Ge>150,Xe=async()=>{Re(!1),Be(!0),We(!0);try{let e=await je();e?.data&&He(e.data)}catch(e){console.error(e)}finally{We(!1)}},Ze=async e=>{Be(!1),w?.(e.chatId)};return(0,d.useEffect)(()=>{if(!Le)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;T.current&&!T.current.contains(t)&&Re(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[Le]),(0,f.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,left:`8px`,right:`8px`,bottom:`${qe}px`,height:Ge>0?`${Math.round(Ge*.92)}px`:`90dvh`,background:r,borderRadius:`16px 16px 0 0`,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:Ne?`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:Ne?`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:De||`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`})})})}),(()=>{let t=!!i,n=!!e.hasCustomTitle,r=t||n,a=t||!r,o=n||!r,c=a&&o;return(0,f.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:c?`minmax(72px, 40%) minmax(0, 60%)`:`1fr`,columnGap:c?`12px`:0,alignItems:`center`,justifyItems:c?`stretch`:`center`},children:[a&&(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,f.jsx)(_k,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,f.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,f.jsx)(vk,{title:e.chatTitle})})}),o&&(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:c?`flex-start`:`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:T,children:[(0,f.jsx)(`button`,{type:`button`,onClick:()=>Re(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`})]})}),Le&&(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:[Ee&&(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{Re(!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`})]}),e.voiceModeLabel]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}})]}),(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{Re(!1),Oe?.()},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`})]}),e.startNewChatLabel]}),je&&(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:Xe,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`})}),e.chatHistoryLabel]})]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{Re(!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`})]}),e.closeConversationLabel]})]})]})]}),(0,f.jsx)(JO,{webRTCError:fe,micError:pe,setMicError:me,dismissCallError:he,isRateLimited:S,rateLimitMessage:ee}),Se&&(0,f.jsx)(dk,{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:[ze?(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:()=>Be(!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:Ue?(0,f.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#6b7280`,fontSize:`14px`},children:`Loading past conversations...`}):Ve.length>0?(0,f.jsx)(`div`,{children:Ve.map(e=>(0,f.jsxs)(`div`,{onClick:()=>Ze(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,Pe?(0,f.jsx)(KO,{chatHistory:c,isAiTyping:l,isLoading:x,isAgentTyping:u,setReplyContext:de,TypingDots:Tk,primaryColor:n,agentHeadshot:h,agentDisplayName:m||g,botAvatarNode:(0,f.jsx)(wk,{orbColors:t})}):Me?(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)(bk,{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)(qO,{input:_,setInput:v,onSubmit:y,isConversationEnded:b,callUiActive:Ie,handleToggleVoice:Te,showVoiceToggle:p===`agent`,activeScreen:p,inputDisabled:Fe,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})}),!Ye&&(0,f.jsxs)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`8px 20px`,paddingBottom:`max(12px, env(safe-area-inset-bottom, 12px))`,pointerEvents:`none`},children:[Ae&&(0,f.jsxs)(`p`,{style:{margin:`0 0 4px`,fontSize:`10px`,color:`#9ca3af`,lineHeight:1.4,userSelect:`none`,pointerEvents:`auto`},children:[`This conversation is recorded for quality assurance purposes.`,` `,(0,f.jsx)(`a`,{href:Ae,target:`_blank`,rel:`noopener noreferrer`,style:{color:`#6b7280`,textDecoration:`underline`},children:`See our privacy policy`})]}),ke&&(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 Dk(){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}=x_();(0,d.useEffect)(()=>{try{qh()}catch{}},[]),(0,d.useEffect)(()=>{De&&k!==`voice_mode`&&k!==`text_chat`&&k!==`call_screen`&&(ue?.(!1),ut(`text_chat`))},[De]);let Ae=t?.widgetSettings||{},je=n?.widgetSettings||{},w={...Ae.branding||{},...je.branding||{}},Me={...Ae.theme||{},...je.theme||{}},Ne={...Ae.features||{},...je.features||{}},Pe=Ne.voice!==!1,Fe=Array.isArray(Me.orbColors)&&Me.orbColors.length>0?Me.orbColors:null,Ie=Me.buttonColor||Me.primaryColor||Fe?.[0]||`#3B82F6`,Le={small:50,medium:64,large:80},Re=Le[Me.orbSize]||Le.small,ze=Me.position||`bottom-right`,Be=w.fallbackAgentName||`Agent`,Ve=mk(Fe??Me.chatBgColors),He=w.logo||w.logoUrl||null,Ue=te||`en`,We=Ae.recommendations?.[Ue]||[],T=(je.recommendations?.[Ue]??We).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),Ge=Array.isArray(w.quickChatOptions)&&w.quickChatOptions.length>0?w.quickChatOptions:T,Ke=w.hideWatermark===!0?!1:w.showPoweredBy!==!1,qe=w.headerBgColor||null,Je=Me.bottomPosition==null?`1.5rem`:`${Me.bottomPosition}px`,Ye=w.privacyPolicyUrl||null,Xe=w.chatbotEnabled!==!1&&Me.chatbotEnabled!==!1,[Ze,Qe]=(0,d.useState)(()=>typeof window<`u`?window.location.pathname:`/`);(0,d.useEffect)(()=>{if(typeof window>`u`)return;let e=()=>Qe(window.location.pathname),t=window.history.pushState.bind(window.history);return window.history.pushState=(...n)=>{t(...n),setTimeout(e,50)},window.addEventListener(`popstate`,e),()=>{window.history.pushState=t,window.removeEventListener(`popstate`,e)}},[]);let $e=(()=>{let e={...Ae.pageVisibility||{},...je.pageVisibility||{}};return Array.isArray(e.allowedPaths)?e.allowedPaths.filter(Boolean):[]})(),et=$e.length===0||$e.some(e=>e===`*`||e===`/*`?!0:e.endsWith(`/*`)?Ze.startsWith(e.slice(0,-1)):Ze.replace(/\/$/,``)===e.replace(/\/$/,``)),tt=Ae.greetings?.[te]||je.greetings?.[te]||w.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,nt={entryPrompt:w.entryPrompt||`Do you want to explore in a new way?`,yesLabel:w.yesLabel||`Yes`,laterLabel:w.laterLabel||`Later`,connectionTitle:w.connectionTitle||`How would you like to connect?`,voiceLabel:w.voiceLabel||`Voice`,textLabel:w.textLabel||`Text`,chatTitle:w.headerName||`Chat with FlowEngage`,hasCustomTitle:!!(w.headerName&&String(w.headerName).trim()),introGreeting:tt,inputPlaceholder:w.inputPlaceholder||`Type your message`,analysingLabel:w.analysingLabel||`analysing...`,voiceModeLabel:w.voiceModeLabel||`Enter Voice Mode`,startNewChatLabel:w.startNewChatLabel||`Start new chat`,chatHistoryLabel:w.chatHistoryLabel||`Chat history`,closeConversationLabel:w.closeConversationLabel||`Close conversation`},rt=je.elevenLabsAgentId||t?.elevenLabsAgentId||null,it=je.voiceClientTools||null,E=!!(je.elevenLabsAgentId&&it),D=t?.siteId||n?.siteId||null,at=t?.apiBaseUrl||``;(0,d.useEffect)(()=>{Nh(t?.siteType||null)},[t?.siteType]);let ot=(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]),O=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,st=r.some(e=>e.sender===`user`),ct=(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]),lt=!!(je._dashboardLivePreview||Ae._dashboardLivePreview),[k,ut]=(0,d.useState)(()=>lt?`text_chat`:`entry_prompt`),[dt,ft]=(0,d.useState)(``),[pt,mt]=(0,d.useState)(null),[ht,gt]=(0,d.useState)(l||``),[_t,vt]=(0,d.useState)(``),[yt,bt]=(0,d.useState)(!1),[xt,St]=(0,d.useState)(0),[Ct,wt]=(0,d.useState)(null),[Tt,Et]=(0,d.useState)(null),[Dt,Ot]=(0,d.useState)(``),[kt,At]=(0,d.useState)(!1),[jt,Mt]=(0,d.useState)(!1),[Nt,Pt]=(0,d.useState)(!1),Ft=(0,d.useRef)(null),It=(0,d.useRef)(!1),Lt=!l&&st&&ct&&k!==`voice_mode`&&!t?.standalone;(0,d.useLayoutEffect)(()=>{if(e!==`ready`||It.current)return;if(It.current=!0,!Pe){ut(`minimized_orb`);return}let t=!1;try{t=ag().shouldResumeVoice}catch{}let n=Ee(),r=D?Se(D):null,i=n||!!r?.transcript;if(t){ce?.({notifyChatInitiated:!0}),ue?.(!0),ut(`voice_mode`);return}if(ke()){ce?.({notifyChatInitiated:!1}),ut(`text_chat`);return}if(i){if((typeof performance<`u`?performance.getEntriesByType?.(`navigation`)?.[0]?.type??`navigate`:`navigate`)===`reload`){ut(`minimized_orb`);return}ce?.({notifyChatInitiated:!0}),ue?.(!0),ut(`voice_mode`);return}if(D)try{Ce(D)}catch{}if(C(D)){ut(`minimized_orb`);return}},[e,r]);let[Rt,zt]=(0,d.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,d.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>zt(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,d.useEffect)(()=>{gt(l||``),l&&vt(``)},[l]);let Bt=(0,d.useCallback)(()=>{Et(null),Ot(``)},[]),Vt=(0,d.useCallback)(e=>{let t=VO(e);if(t){Et(null),Ot(t);return}Et(e),Ot(``)},[]);(0,d.useEffect)(()=>{if(!x||b!==`connected`){St(0);return}let e=()=>{let e=new Date(x).getTime();isNaN(e)||St(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[x,b]);let Ht=(0,d.useCallback)(()=>{ut(`call_screen`),Mt(!1)},[]),Ut=(0,d.useCallback)(()=>{ut(`text_chat`),Mt(!0)},[]);(0,d.useEffect)(()=>{let e=v?.callId||y||null;if(!e){Ft.current=null;return}if(v?.callId||b===`connecting`||b===`connected`){if(k===`minimized_orb`&&jt&&y&&!v?.callId){Ft.current=e;return}!(!i||k===`minimized_orb`||k===`voice_mode`)&&Ft.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:k,hasIncomingCall:!!v?.callId,activeCallId:y,callConnectionState:b}),Ft.current=e,k===`voice_mode`&&ue?.(!1),ce?.(),Ht())}},[y,b,Ht,v?.callId,i,ce,ue,k]),(0,d.useEffect)(()=>{!v&&!y&&k===`call_screen`&&ut(`text_chat`)},[v,y,k]),(0,d.useEffect)(()=>{!y&&jt&&Mt(!1)},[y,jt]),(0,d.useEffect)(()=>{if(!o||_){be?.(``),ye?.();return}if(!dt.trim()||Tt){be?.(``);let e=window.setTimeout(()=>ye?.(),100);return()=>window.clearTimeout(e)}ve?.();let e=window.setTimeout(()=>be?.(dt),120),t=window.setTimeout(()=>ye?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[dt,Tt,o,_,ve,ye,be]);let Wt=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,Gt=async e=>{if(e.preventDefault(),_)return;if(Lt){let e=ht.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){vt(`Please enter a valid email so we can continue helping you.`);return}await le(e),vt(``),bt(!0),setTimeout(()=>bt(!1),3e3);return}let t=Wt(pt);if(!dt.trim()&&!Tt)return;if(Tt){try{At(!0),Ot(``);let e=await se(Tt),n=e?.data||e,r=dt.trim()||`Shared file: ${UO(Tt)}`;ft(``),mt(null),Bt(),await oe(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||Tt.name,fileType:n?.fileType||Tt.type,fileSize:n?.fileSize||Tt.size}})}catch(e){Ot(e?.message||`Failed to upload the selected file.`)}finally{At(!1)}return}let n=dt.trim();ft(``),mt(null),await oe(n,``,t)},Kt=(0,d.useCallback)(()=>{r.length!==0&&fe?.()},[r.length,fe]),qt=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},Jt=(0,d.useCallback)(async e=>{if(_||m)return;let t=e.message||e.label||e.text||``;t.trim()&&await oe(t.trim(),``)},[_,m,oe]),Yt=Rt&&k===`entry_prompt`?{inset:0}:Rt&&k===`text_chat`?{left:0,right:0,bottom:0}:Rt&&k===`call_screen`?{left:0,right:0,bottom:0,height:`90dvh`,overflow:`hidden`,borderRadius:`16px 16px 0 0`}:Rt&&k===`connection_modal`?{left:`12px`,right:`12px`,bottom:`12px`}:k===`call_screen`?{width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,borderRadius:`22px`,overflow:`hidden`,...ze===`bottom-left`?{left:`1.5rem`,bottom:Je}:{right:`1.5rem`,bottom:Je}}:ze===`bottom-left`?{left:`1.5rem`,bottom:Je}:{right:`1.5rem`,bottom:Je},Xt=(0,d.useCallback)(()=>{k!==`minimized_orb`&&(Pt(!0),setTimeout(()=>{ut(`minimized_orb`),Pt(!1),y&&Mt(!0)},280))},[y,k]),Zt=()=>ut(`connection_modal`),Qt=()=>{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),ut(`voice_mode`)},$t=()=>{ce({notifyChatInitiated:!0}),ue?.(!1),ut(`text_chat`)},en=()=>{ue?.(!1),Xt()};return e!==`ready`||!Xe||Ne.chat===!1||!et?null:(0,f.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...Yt},onWheel:e=>e.stopPropagation(),onTouchMove:e=>e.stopPropagation(),children:[k===`entry_prompt`&&(0,f.jsx)(xk,{copy:nt,orbColors:Fe,primaryColor:Ie,onYes:()=>{ie(D),Qt()},onLater:()=>{ie(D),Xt()},isMobile:Rt,isClosing:Nt}),k===`minimized_orb`&&(0,f.jsxs)(gO.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:ze===`bottom-left`?`flex-start`:`flex-end`,gap:`10px`},children:[y&&(0,f.jsxs)(`button`,{type:`button`,onClick:Ht,style:{maxWidth:Rt?`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`?`${qt(xt)} with ${ot}`:`Tap to return to ${ot}`})]})]}),(0,f.jsx)(bk,{size:Re,orbColors:Fe,onClick:y?Ht:Pe?Zt:$t})]}),k===`connection_modal`&&(0,f.jsx)(Sk,{copy:nt,orbColors:Fe,primaryColor:Ie,onVoice:Qt,onText:$t,onClose:Xt,isMobile:Rt,isClosing:Nt}),k===`voice_mode`&&(0,f.jsx)(Ck,{orbColors:Fe,onEnterChat:$t,onEndChat:en,agentId:rt,siteId:D,apiBaseUrl:at,chatId:ne,historyRef:re,onMessageSync:ae,voiceEndCounter:Oe,websiteName:t?.websiteName,voiceClientTools:it,preferLocalAgent:E},`voice`),k===`call_screen`&&(0,f.jsx)(uk,{incomingCall:v,activeCallId:y,callConnectionState:b,callDurationSeconds:xt,isCallMuted:S,agentName:ot,agentHeadshot:O,fallbackAgentName:Be,acceptCall:pe,rejectCall:me,endWebRTCCall:he,toggleCallMute:ge,formatCallDuration:qt,onMinimize:Ut,primaryColor:Ie,orbColors:Fe,chatHistory:r}),k===`text_chat`&&(0,f.jsx)(Ek,{isClosing:Nt,copy:nt,orbColors:Fe,primaryColor:Ie,chatBgGradient:Ve,logo:He,quickChatOptions:Ge,onQuickChatSelect:Jt,isMobile:Rt,chatHistory:r,isAiTyping:p,isAgentTyping:u,activeScreen:a,agentName:ot,agentHeadshot:O,fallbackAgentName:Be,input:dt,setInput:ft,onSubmit:Gt,isConversationEnded:_,isLoading:m,isRateLimited:h,rateLimitMessage:g,selectedFile:Tt,onFileSelect:Vt,onRemoveSelectedFile:Bt,attachmentError:Dt,isUploadingAttachment:kt,requiresEmail:Lt,emailInput:ht,setEmailInput:gt,emailError:_t,emailCaptureSuccess:yt,replyContext:pt,setReplyContext:mt,webRTCError:ee,micError:Ct,setMicError:wt,dismissCallError:_e,activeCallId:y,isCallMuted:S,toggleCallMute:ge,endWebRTCCall:he,formatCallDuration:qt,callDurationSeconds:xt,onCollapse:Xt,onStartVoice:Qt,voiceEnabled:Pe,onNewChat:Kt,onMinimize:Ut,onExpand:Ht,isCallMinimized:!!y,showPoweredBy:Ke,privacyPolicyUrl:Ye,headerBgColor:qe,getVisitorChatHistory:xe,resumeChat:we,isSessionRestoring:Te}),(0,f.jsx)(`style`,{children:`
|
|
647
|
+
`.replace(/\s+/g,` `).trim()}})}var ok=()=>(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 sk({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:ie,isUploadingAttachment:ae,requiresEmail:oe,emailInput:se,setEmailInput:ce,emailError:le,emailCaptureSuccess:C,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,voiceEnabled:Ee,headerBgColor:De,onNewChat:Oe,showPoweredBy:ke,privacyPolicyUrl:Ae,getVisitorChatHistory:je,resumeChat:w,isSessionRestoring:Me,isClosing:Ne}){let Pe=c.length>0,Fe=x||S||b,Ie=!!ge,[Le,Re]=(0,d.useState)(!1),[ze,Be]=(0,d.useState)(!1),[Ve,He]=(0,d.useState)([]),[Ue,We]=(0,d.useState)(!1),T=(0,d.useRef)(null),[Ge,Ke]=(0,d.useState)(()=>typeof window<`u`?window.visualViewport?.height??window.innerHeight:600),[qe,Je]=(0,d.useState)(0);(0,d.useEffect)(()=>{if(!s)return;let e=window.visualViewport;if(!e)return;let t=()=>{Ke(e.height),Je(Math.max(0,window.innerHeight-e.offsetTop-e.height))};return e.addEventListener(`resize`,t),e.addEventListener(`scroll`,t),t(),()=>{e.removeEventListener(`resize`,t),e.removeEventListener(`scroll`,t)}},[s]);let Ye=s&&window.innerHeight-Ge>150,Xe=async()=>{Re(!1),Be(!0),We(!0);try{let e=await je();e?.data&&He(e.data)}catch(e){console.error(e)}finally{We(!1)}},Ze=async e=>{Be(!1),w?.(e.chatId)};return(0,d.useEffect)(()=>{if(!Le)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;T.current&&!T.current.contains(t)&&Re(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[Le]),(0,f.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,left:`8px`,right:`8px`,bottom:`${qe}px`,height:Ge>0?`${Math.round(Ge*.92)}px`:`90dvh`,background:r,borderRadius:`16px 16px 0 0`,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:Ne?`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:Ne?`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:De||`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`})})})}),(()=>{let t=!!i,n=!!e.hasCustomTitle,r=t||n,a=t||!r,o=n||!r,c=a&&o;return(0,f.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:c?`minmax(72px, 40%) minmax(0, 60%)`:`1fr`,columnGap:c?`12px`:0,alignItems:`center`,justifyItems:c?`stretch`:`center`},children:[a&&(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,f.jsx)(QO,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,f.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,f.jsx)($O,{title:e.chatTitle})})}),o&&(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:c?`flex-start`:`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:T,children:[(0,f.jsx)(`button`,{type:`button`,onClick:()=>Re(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`})]})}),Le&&(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:[Ee&&(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{Re(!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:()=>{Re(!1),Oe?.()},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`]}),je&&(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:Xe,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:()=>{Re(!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)(GD,{webRTCError:fe,micError:pe,setMicError:me,dismissCallError:he,isRateLimited:S,rateLimitMessage:ee}),Se&&(0,f.jsx)(cO,{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:[ze?(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:()=>Be(!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:Ue?(0,f.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#6b7280`,fontSize:`14px`},children:`Loading past conversations...`}):Ve.length>0?(0,f.jsx)(`div`,{children:Ve.map(e=>(0,f.jsxs)(`div`,{onClick:()=>Ze(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,Pe?(0,f.jsx)(UD,{chatHistory:c,isAiTyping:l,isLoading:x,isAgentTyping:u,setReplyContext:de,TypingDots:ok,primaryColor:n,agentHeadshot:h,agentDisplayName:m||g,botAvatarNode:(0,f.jsx)(ak,{orbColors:t})}):Me?(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)(tk,{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))})]})]}),C&&(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:oe?`6px 0 0`:`12px 0 0`},children:(0,f.jsx)(WD,{input:_,setInput:v,onSubmit:y,isConversationEnded:b,callUiActive:Ie,handleToggleVoice:Te,showVoiceToggle:p===`agent`,activeScreen:p,inputDisabled:Fe,replyContext:ue,clearReplyContext:()=>de(null),onFileSelect:ne,selectedFile:te,onRemoveSelectedFile:re,attachmentError:ie,isUploadingAttachment:ae,requiresEmail:oe,emailInput:se,setEmailInput:ce,emailError:le,inputPlaceholder:e.inputPlaceholder})}),!Ye&&(0,f.jsxs)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`8px 20px`,paddingBottom:`max(12px, env(safe-area-inset-bottom, 12px))`,pointerEvents:`none`},children:[Ae&&(0,f.jsxs)(`p`,{style:{margin:`0 0 4px`,fontSize:`10px`,color:`#9ca3af`,lineHeight:1.4,userSelect:`none`,pointerEvents:`auto`},children:[`This conversation is recorded for quality assurance purposes.`,` `,(0,f.jsx)(`a`,{href:Ae,target:`_blank`,rel:`noopener noreferrer`,style:{color:`#6b7280`,textDecoration:`underline`},children:`See our privacy policy`})]}),ke&&(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 ck(){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:oe,sendMessage:se,uploadChatFile:ce,openWidget:le,captureVisitorEmail:C,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}=Tn();(0,d.useEffect)(()=>{try{cr()}catch{}},[]),(0,d.useEffect)(()=>{De&&k!==`voice_mode`&&k!==`text_chat`&&k!==`call_screen`&&(ue?.(!1),A(`text_chat`))},[De]);let Ae=t?.widgetSettings||{},je=n?.widgetSettings||{},w={...Ae.branding||{},...je.branding||{}},Me={...Ae.theme||{},...je.theme||{}},Ne={...Ae.features||{},...je.features||{}},Pe=Ne.voice!==!1,Fe=Array.isArray(Me.orbColors)&&Me.orbColors.length>0?Me.orbColors:null,Ie=Me.buttonColor||Me.primaryColor||Fe?.[0]||`#3B82F6`,Le={small:50,medium:64,large:80},Re=Le[Me.orbSize]||Le.small,ze=Me.position||`bottom-right`,Be=w.fallbackAgentName||`Agent`,Ve=YO(Fe??Me.chatBgColors),He=w.logo||w.logoUrl||null,Ue=te||`en`,We=Ae.recommendations?.[Ue]||[],T=(je.recommendations?.[Ue]??We).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),Ge=Array.isArray(w.quickChatOptions)&&w.quickChatOptions.length>0?w.quickChatOptions:T,Ke=w.hideWatermark===!0?!1:w.showPoweredBy!==!1,qe=w.headerBgColor||null,Je=Me.bottomPosition==null?`1.5rem`:`${Me.bottomPosition}px`,Ye=w.privacyPolicyUrl||null,Xe=w.chatbotEnabled!==!1&&Me.chatbotEnabled!==!1,[Ze,Qe]=(0,d.useState)(()=>typeof window<`u`?window.location.pathname:`/`);(0,d.useEffect)(()=>{if(typeof window>`u`)return;let e=()=>Qe(window.location.pathname),t=window.history.pushState.bind(window.history);return window.history.pushState=(...n)=>{t(...n),setTimeout(e,50)},window.addEventListener(`popstate`,e),()=>{window.history.pushState=t,window.removeEventListener(`popstate`,e)}},[]);let $e=(()=>{let e={...Ae.pageVisibility||{},...je.pageVisibility||{}};return Array.isArray(e.allowedPaths)?e.allowedPaths.filter(Boolean):[]})(),et=$e.length===0||$e.some(e=>e===`*`||e===`/*`?!0:e.endsWith(`/*`)?Ze.startsWith(e.slice(0,-1)):Ze.replace(/\/$/,``)===e.replace(/\/$/,``)),tt=Ae.greetings?.[te]||je.greetings?.[te]||w.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,nt={entryPrompt:w.entryPrompt||`Do you want to explore in a new way?`,yesLabel:w.yesLabel||`Yes`,laterLabel:w.laterLabel||`Later`,connectionTitle:w.connectionTitle||`How would you like to connect?`,voiceLabel:w.voiceLabel||`Voice`,textLabel:w.textLabel||`Text`,chatTitle:w.headerName||`Chat with FlowEngage`,hasCustomTitle:!!(w.headerName&&String(w.headerName).trim()),introGreeting:tt,inputPlaceholder:w.inputPlaceholder||`Type your message`,analysingLabel:w.analysingLabel||`analysing...`},rt=je.elevenLabsAgentId||t?.elevenLabsAgentId||null,E=t?.siteId||n?.siteId||null,D=t?.apiBaseUrl||``;(0,d.useEffect)(()=>{Jn(t?.siteType||null)},[t?.siteType]);let it=(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]),at=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,ot=r.some(e=>e.sender===`user`),O=(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]),st=!!(je._dashboardLivePreview||Ae._dashboardLivePreview),[k,A]=(0,d.useState)(()=>st?`text_chat`:`entry_prompt`),[ct,lt]=(0,d.useState)(``),[ut,dt]=(0,d.useState)(null),[ft,pt]=(0,d.useState)(l||``),[mt,ht]=(0,d.useState)(``),[gt,_t]=(0,d.useState)(!1),[vt,yt]=(0,d.useState)(0),[bt,xt]=(0,d.useState)(null),[St,Ct]=(0,d.useState)(null),[wt,Tt]=(0,d.useState)(``),[Et,Dt]=(0,d.useState)(!1),[Ot,kt]=(0,d.useState)(!1),[At,jt]=(0,d.useState)(!1),Mt=(0,d.useRef)(null),Nt=(0,d.useRef)(!1),Pt=!l&&ot&&O&&k!==`voice_mode`;(0,d.useLayoutEffect)(()=>{if(e!==`ready`||Nt.current)return;if(Nt.current=!0,!Pe){A(`minimized_orb`);return}let t=!1;try{t=br().shouldResumeVoice}catch{}let n=Ee(),r=E?Se(E):null,i=n||!!r?.transcript;if(t){le?.({notifyChatInitiated:!0}),ue?.(!0),A(`voice_mode`);return}if(ke()){le?.({notifyChatInitiated:!1}),A(`text_chat`);return}if(i){if((typeof performance<`u`?performance.getEntriesByType?.(`navigation`)?.[0]?.type??`navigate`:`navigate`)===`reload`){A(`minimized_orb`);return}le?.({notifyChatInitiated:!0}),ue?.(!0),A(`voice_mode`);return}if(E)try{Ce(E)}catch{}if(ie(E)){A(`minimized_orb`);return}},[e,r]);let[Ft,It]=(0,d.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,d.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>It(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,d.useEffect)(()=>{pt(l||``),l&&ht(``)},[l]);let Lt=(0,d.useCallback)(()=>{Ct(null),Tt(``)},[]),Rt=(0,d.useCallback)(e=>{let t=RD(e);if(t){Ct(null),Tt(t);return}Ct(e),Tt(``)},[]);(0,d.useEffect)(()=>{if(!x||b!==`connected`){yt(0);return}let e=()=>{let e=new Date(x).getTime();isNaN(e)||yt(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[x,b]);let zt=(0,d.useCallback)(()=>{A(`call_screen`),kt(!1)},[]),Bt=(0,d.useCallback)(()=>{A(`text_chat`),kt(!0)},[]);(0,d.useEffect)(()=>{let e=v?.callId||y||null;if(!e){Mt.current=null;return}if(v?.callId||b===`connecting`||b===`connected`){if(k===`minimized_orb`&&Ot&&y&&!v?.callId){Mt.current=e;return}!(!i||k===`minimized_orb`||k===`voice_mode`)&&Mt.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:k,hasIncomingCall:!!v?.callId,activeCallId:y,callConnectionState:b}),Mt.current=e,k===`voice_mode`&&ue?.(!1),le?.(),zt())}},[y,b,zt,v?.callId,i,le,ue,k]),(0,d.useEffect)(()=>{!v&&!y&&k===`call_screen`&&A(`text_chat`)},[v,y,k]),(0,d.useEffect)(()=>{!y&&Ot&&kt(!1)},[y,Ot]),(0,d.useEffect)(()=>{if(!o||_){be?.(``),ye?.();return}if(!ct.trim()||St){be?.(``);let e=window.setTimeout(()=>ye?.(),100);return()=>window.clearTimeout(e)}ve?.();let e=window.setTimeout(()=>be?.(ct),120),t=window.setTimeout(()=>ye?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[ct,St,o,_,ve,ye,be]);let Vt=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,Ht=async e=>{if(e.preventDefault(),_)return;if(Pt){let e=ft.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){ht(`Please enter a valid email so we can continue helping you.`);return}await C(e),ht(``),_t(!0),setTimeout(()=>_t(!1),3e3);return}let t=Vt(ut);if(!ct.trim()&&!St)return;if(St){try{Dt(!0),Tt(``);let e=await ce(St),n=e?.data||e,r=ct.trim()||`Shared file: ${BD(St)}`;lt(``),dt(null),Lt(),await se(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||St.name,fileType:n?.fileType||St.type,fileSize:n?.fileSize||St.size}})}catch(e){Tt(e?.message||`Failed to upload the selected file.`)}finally{Dt(!1)}return}let n=ct.trim();lt(``),dt(null),await se(n,``,t)},Ut=(0,d.useCallback)(()=>{r.length!==0&&fe?.()},[r.length,fe]),Wt=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},Gt=(0,d.useCallback)(async e=>{if(_||m)return;let t=e.message||e.label||e.text||``;t.trim()&&await se(t.trim(),``)},[_,m,se]),Kt=Ft&&k===`entry_prompt`?{inset:0}:Ft&&k===`text_chat`?{left:0,right:0,bottom:0}:Ft&&k===`call_screen`?{left:0,right:0,bottom:0,height:`90dvh`,overflow:`hidden`,borderRadius:`16px 16px 0 0`}:Ft&&k===`connection_modal`?{left:`12px`,right:`12px`,bottom:`12px`}:k===`call_screen`?{width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,borderRadius:`22px`,overflow:`hidden`,...ze===`bottom-left`?{left:`1.5rem`,bottom:Je}:{right:`1.5rem`,bottom:Je}}:ze===`bottom-left`?{left:`1.5rem`,bottom:Je}:{right:`1.5rem`,bottom:Je},qt=(0,d.useCallback)(()=>{k!==`minimized_orb`&&(jt(!0),setTimeout(()=>{A(`minimized_orb`),jt(!1),y&&kt(!0)},280))},[y,k]),Jt=()=>A(`connection_modal`),Yt=()=>{try{let e=window.AudioContext||window.webkitAudioContext;if(e){let t=new e;t.resume().catch(()=>{}),setTimeout(()=>t.close().catch(()=>{}),3e3)}}catch{}le({notifyChatInitiated:!0}),ue?.(!0),A(`voice_mode`)},Xt=()=>{le({notifyChatInitiated:!0}),ue?.(!1),A(`text_chat`)},Zt=()=>{ue?.(!1),qt()};return e!==`ready`||!Xe||Ne.chat===!1||!et?null:(0,f.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...Kt},onWheel:e=>e.stopPropagation(),onTouchMove:e=>e.stopPropagation(),children:[k===`entry_prompt`&&(0,f.jsx)(nk,{copy:nt,orbColors:Fe,primaryColor:Ie,onYes:()=>{ae(E),Yt()},onLater:()=>{ae(E),qt()},isMobile:Ft,isClosing:At}),k===`minimized_orb`&&(0,f.jsxs)(Sm.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:ze===`bottom-left`?`flex-start`:`flex-end`,gap:`10px`},children:[y&&(0,f.jsxs)(`button`,{type:`button`,onClick:zt,style:{maxWidth:Ft?`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`?`${Wt(vt)} with ${it}`:`Tap to return to ${it}`})]})]}),(0,f.jsx)(tk,{size:Re,orbColors:Fe,onClick:y?zt:Pe?Jt:Xt})]}),k===`connection_modal`&&(0,f.jsx)(rk,{copy:nt,orbColors:Fe,primaryColor:Ie,onVoice:Yt,onText:Xt,onClose:qt,isMobile:Ft,isClosing:At}),k===`voice_mode`&&(0,f.jsx)(ik,{orbColors:Fe,onEnterChat:Xt,onEndChat:Zt,agentId:rt,siteId:E,apiBaseUrl:D,chatId:ne,historyRef:re,onMessageSync:oe,voiceEndCounter:Oe,websiteName:t?.websiteName,voiceFirstMessage:Ae.voiceFirstMessage||null,captureVisitorEmail:C,emailRequired:!l},`voice`),k===`call_screen`&&(0,f.jsx)(sO,{incomingCall:v,activeCallId:y,callConnectionState:b,callDurationSeconds:vt,isCallMuted:S,agentName:it,agentHeadshot:at,fallbackAgentName:Be,acceptCall:pe,rejectCall:me,endWebRTCCall:he,toggleCallMute:ge,formatCallDuration:Wt,onMinimize:Bt,primaryColor:Ie,orbColors:Fe,chatHistory:r}),k===`text_chat`&&(0,f.jsx)(sk,{isClosing:At,copy:nt,orbColors:Fe,primaryColor:Ie,chatBgGradient:Ve,logo:He,quickChatOptions:Ge,onQuickChatSelect:Gt,isMobile:Ft,chatHistory:r,isAiTyping:p,isAgentTyping:u,activeScreen:a,agentName:it,agentHeadshot:at,fallbackAgentName:Be,input:ct,setInput:lt,onSubmit:Ht,isConversationEnded:_,isLoading:m,isRateLimited:h,rateLimitMessage:g,selectedFile:St,onFileSelect:Rt,onRemoveSelectedFile:Lt,attachmentError:wt,isUploadingAttachment:Et,requiresEmail:Pt,emailInput:ft,setEmailInput:pt,emailError:mt,emailCaptureSuccess:gt,replyContext:ut,setReplyContext:dt,webRTCError:ee,micError:bt,setMicError:xt,dismissCallError:_e,activeCallId:y,isCallMuted:S,toggleCallMute:ge,endWebRTCCall:he,formatCallDuration:Wt,callDurationSeconds:vt,onCollapse:qt,onStartVoice:Yt,voiceEnabled:Pe,onNewChat:Ut,onMinimize:Bt,onExpand:zt,isCallMinimized:!!y,showPoweredBy:Ke,privacyPolicyUrl:Ye,headerBgColor:qe,getVisitorChatHistory:xe,resumeChat:we,isSessionRestoring:Te}),(0,f.jsx)(`style`,{children:`
|
|
644
648
|
/* Force any SVG (or img) inside LogoSlot to fill the container height
|
|
645
649
|
regardless of whether the component forwards its style prop. */
|
|
646
650
|
.fe-logo-slot svg,
|
|
@@ -659,4 +663,4 @@ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
|
|
|
659
663
|
@keyframes fe-orb-bar-3 { from{height:8px} to{height:20px} }
|
|
660
664
|
@keyframes fe-orb-bar-4 { from{height:6px} to{height:16px} }
|
|
661
665
|
@keyframes fe-dot-bounce { 0%,80%,100%{transform:translateY(0);opacity:.5} 40%{transform:translateY(-5px);opacity:1} }
|
|
662
|
-
`})]})}var
|
|
666
|
+
`})]})}var lk=class extends d.default.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){console.error(`[FlowEngage] Widget crashed:`,e,t.componentStack)}render(){return this.state.hasError?this.props.fallback??null:this.props.children}};exports.AnimatedOrb=eO,exports.ErrorBoundary=lk,exports.FlowEngageProvider=Nr,exports.FlowEngageWidget=ck,exports.useFlowEngage=Tn;
|