clinic-connect-widget 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- !function(e){"function"==typeof define&&define.amd?define(e):e()}(function(){"use strict";const e="state_change",t="idle",i="loading",n="collapsed",s="expanded",r="patient_form",o="in_consultation",a="completed";const c=new class{constructor(){this.state={status:t,config:{},doctor:null,error:null},this.listeners={}}on(e,t){return this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t),()=>{this.listeners[e]=this.listeners[e].filter(e=>e!==t)}}emit(e,t){this.listeners[e]&&this.listeners[e].forEach(e=>e(t))}setState(t){const i={...this.state};this.state={...this.state,...t},this.emit(e,{prev:i,current:this.state})}getState(){return this.state}};class d{constructor(e){this.config=e}async init(e){return await this.delay(800),{success:!0,data:{clinicName:"Clinic Connect",primaryColor:"#0088cc",features:{videoCall:!0,chat:!0},doctor:{id:"dr_123",name:"Bác sĩ Hà Ngọc Mạnh",specialty:"Nam học - Hiếm muộn",avatarUrl:"https://lh3.googleusercontent.com/aida-public/AB6AXuB5Sne8e7ofIffcXSZ2rXx-XLji_xce_THhR0QnJYMAyov2Tf7BdAYsPQErsdCgvbL-M2AITXy5G9gjGab-hp97I8n_eMI2LMcZ3qGBUBwThyW2fySOfpjUnB7j5ZDnIxqb2NcZZSMCgeaJexvyoKOfoUUlZGKWODkKo4NcnJNiS96NOBKBNij35vrE3YTu0XHB_SSbSqcyRraDHbVVLMnyy1cEjepd9ATN0bxVxGhjbVGDsCi6Kn4Ok7XYWDBLijGDcabxunrvylAg",isOnline:!0}}}}delay(e){return new Promise(t=>setTimeout(t,e))}}const l="wss://call-server.longvan.vn",u="wss://livekit.longvan.vn",h=(e,t)=>{var i,n,s;let r=e;const o=(null==(i=t.doctor)?void 0:i.name)||"Bác sĩ Hà Ngọc Mạnh",a=(null==(n=t.doctor)?void 0:n.specialty)||"Nam học - Hiếm muộn",c=(null==(s=t.doctor)?void 0:s.avatarUrl)||"";return r=r.replace(/{{doctorName}}/g,o),r=r.replace(/{{doctorSpecialty}}/g,a),r=r.replace(/{{doctorAvatar}}/g,c),r},p=Object.create(null);p.open="0",p.close="1",p.ping="2",p.pong="3",p.message="4",p.upgrade="5",p.noop="6";const m=Object.create(null);Object.keys(p).forEach(e=>{m[p[e]]=e});const g={type:"error",data:"parser error"},f="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),v="function"==typeof ArrayBuffer,b=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,y=({type:e,data:t},i,n)=>f&&t instanceof Blob?i?n(t):k(t,n):v&&(t instanceof ArrayBuffer||b(t))?i?n(t):k(new Blob([t]),n):n(p[e]+(t||"")),k=(e,t)=>{const i=new FileReader;return i.onload=function(){const e=i.result.split(",")[1];t("b"+(e||""))},i.readAsDataURL(e)};function T(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let C;const S="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",w="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let yl=0;yl<64;yl++)w[S.charCodeAt(yl)]=yl;const E="function"==typeof ArrayBuffer,R=(e,t)=>{if("string"!=typeof e)return{type:"message",data:x(e,t)};const i=e.charAt(0);if("b"===i)return{type:"message",data:P(e.substring(1),t)};return m[i]?e.length>1?{type:m[i],data:e.substring(1)}:{type:m[i]}:g},P=(e,t)=>{if(E){const i=(e=>{let t,i,n,s,r,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const d=new ArrayBuffer(o),l=new Uint8Array(d);for(t=0;t<a;t+=4)i=w[e.charCodeAt(t)],n=w[e.charCodeAt(t+1)],s=w[e.charCodeAt(t+2)],r=w[e.charCodeAt(t+3)],l[c++]=i<<2|n>>4,l[c++]=(15&n)<<4|s>>2,l[c++]=(3&s)<<6|63&r;return d})(e);return x(i,t)}return{base64:!0,data:e}},x=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,I=String.fromCharCode(30);function _(){return new TransformStream({transform(e,t){!function(e,t){f&&e.data instanceof Blob?e.data.arrayBuffer().then(T).then(t):v&&(e.data instanceof ArrayBuffer||b(e.data))?t(T(e.data)):y(e,!1,e=>{C||(C=new TextEncoder),t(C.encode(e))})}(e,i=>{const n=i.length;let s;if(n<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,n);else if(n<65536){s=new Uint8Array(3);const e=new DataView(s.buffer);e.setUint8(0,126),e.setUint16(1,n)}else{s=new Uint8Array(9);const e=new DataView(s.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(n))}e.data&&"string"!=typeof e.data&&(s[0]|=128),t.enqueue(s),t.enqueue(i)})}})}let O;function D(e){return e.reduce((e,t)=>e+t.length,0)}function A(e,t){if(e[0].length===t)return e.shift();const i=new Uint8Array(t);let n=0;for(let s=0;s<t;s++)i[s]=e[0][n++],n===e[0].length&&(e.shift(),n=0);return e.length&&n<e[0].length&&(e[0]=e[0].slice(n)),i}function M(e){if(e)return function(e){for(var t in M.prototype)e[t]=M.prototype[t];return e}(e)}M.prototype.on=M.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},M.prototype.once=function(e,t){function i(){this.off(e,i),t.apply(this,arguments)}return i.fn=t,this.on(e,i),this},M.prototype.off=M.prototype.removeListener=M.prototype.removeAllListeners=M.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var i,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var s=0;s<n.length;s++)if((i=n[s])===t||i.fn===t){n.splice(s,1);break}return 0===n.length&&delete this._callbacks["$"+e],this},M.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),i=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(i){n=0;for(var s=(i=i.slice(0)).length;n<s;++n)i[n].apply(this,t)}return this},M.prototype.emitReserved=M.prototype.emit,M.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},M.prototype.hasListeners=function(e){return!!this.listeners(e).length};const N="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),L="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function U(e,...t){return t.reduce((t,i)=>(e.hasOwnProperty(i)&&(t[i]=e[i]),t),{})}const j=L.setTimeout,F=L.clearTimeout;function B(e,t){t.useNativeTimers?(e.setTimeoutFn=j.bind(L),e.clearTimeoutFn=F.bind(L)):(e.setTimeoutFn=L.setTimeout.bind(L),e.clearTimeoutFn=L.clearTimeout.bind(L))}function q(e){return"string"==typeof e?function(e){let t=0,i=0;for(let n=0,s=e.length;n<s;n++)t=e.charCodeAt(n),t<128?i+=1:t<2048?i+=2:t<55296||t>=57344?i+=3:(n++,i+=4);return i}(e):Math.ceil(1.33*(e.byteLength||e.size))}function V(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class z extends Error{constructor(e,t,i){super(e),this.description=t,this.context=i,this.type="TransportError"}}class H extends M{constructor(e){super(),this.writable=!1,B(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,i){return super.emitReserved("error",new z(e,t,i)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=R(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(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let i in e)e.hasOwnProperty(i)&&(t.length&&(t+="&"),t+=encodeURIComponent(i)+"="+encodeURIComponent(e[i]));return t}(e);return t.length?"?"+t:""}}class W extends H{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const 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){((e,t)=>{const i=e.split(I),n=[];for(let s=0;s<i.length;s++){const e=R(i[s],t);if(n.push(e),"error"===e.type)break}return n})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const i=e.length,n=new Array(i);let s=0;e.forEach((e,r)=>{y(e,!1,e=>{n[r]=e,++s===i&&t(n.join(I))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=V()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let K=!1;try{K="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(bl){}const G=K;function J(){}class Q extends W{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let i=location.port;i||(i=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||i!==e.port}}doWrite(e,t){const i=this.request({method:"POST",data:e});i.on("success",t),i.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const 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}}class Y extends M{constructor(e,t,i){super(),this.createRequest=e,B(this,i),this._opts=i,this._method=i.method||"GET",this._uri=t,this._data=void 0!==i.data?i.data:null,this._create()}_create(){var e;const t=U(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const i=this._xhr=this.createRequest(t);try{i.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&i.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(n){}if("POST"===this._method)try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(n){}try{i.setRequestHeader("Accept","*/*")}catch(n){}null===(e=this._opts.cookieJar)||void 0===e||e.addCookies(i),"withCredentials"in i&&(i.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(i.timeout=this._opts.requestTimeout),i.onreadystatechange=()=>{var e;3===i.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(i.getResponseHeader("set-cookie"))),4===i.readyState&&(200===i.status||1223===i.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof i.status?i.status:0)},0))},i.send(this._data)}catch(n){return void this.setTimeoutFn(()=>{this._onError(n)},0)}"undefined"!=typeof document&&(this._index=Y.requestsCount++,Y.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=J,e)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete Y.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(Y.requestsCount=0,Y.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",X);else if("function"==typeof addEventListener){addEventListener("onpagehide"in L?"pagehide":"unload",X,!1)}function X(){for(let e in Y.requests)Y.requests.hasOwnProperty(e)&&Y.requests[e].abort()}const Z=function(){const e=$({xdomain:!1});return e&&null!==e.responseType}();function $(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||G))return new XMLHttpRequest}catch(i){}if(!t)try{return new(L[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(i){}}const ee="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class te extends H{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,i=ee?{}:U(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(i.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,i)}catch(bl){return this.emitReserved("error",bl)}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++){const i=e[t],n=t===e.length-1;y(i,this.supportsBinary,e=>{try{this.doWrite(i,e)}catch(t){}n&&N(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=V()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const ie=L.WebSocket||L.MozWebSocket;const ne={websocket:class extends te{createSocket(e,t,i){return ee?new ie(e,t,i):t?new ie(e,t):new ie(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends H{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(bl){return this.emitReserved("error",bl)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=function(e,t){O||(O=new TextDecoder);const i=[];let n=0,s=-1,r=!1;return new TransformStream({transform(o,a){for(i.push(o);;){if(0===n){if(D(i)<1)break;const e=A(i,1);r=!(128&~e[0]),s=127&e[0],n=s<126?3:126===s?1:2}else if(1===n){if(D(i)<2)break;const e=A(i,2);s=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),n=3}else if(2===n){if(D(i)<8)break;const e=A(i,8),t=new DataView(e.buffer,e.byteOffset,e.length),r=t.getUint32(0);if(r>Math.pow(2,21)-1){a.enqueue(g);break}s=r*Math.pow(2,32)+t.getUint32(4),n=3}else{if(D(i)<s)break;const e=A(i,s);a.enqueue(R(r?e:O.decode(e),t)),n=0}if(0===s||s>e){a.enqueue(g);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=e.readable.pipeThrough(t).getReader(),n=_();n.readable.pipeTo(e.writable),this._writer=n.writable.getWriter();const s=()=>{i.read().then(({done:e,value:t})=>{e||(this.onPacket(t),s())}).catch(e=>{})};s();const r={type:"open"};this.query.sid&&(r.data=`{"sid":"${this.query.sid}"}`),this._writer.write(r).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const i=e[t],n=t===e.length-1;this._writer.write(i).then(()=>{n&&N(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends Q{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Z&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Y($,this.uri(),e)}}},se=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,re=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function oe(e){if(e.length>8e3)throw"URI too long";const t=e,i=e.indexOf("["),n=e.indexOf("]");-1!=i&&-1!=n&&(e=e.substring(0,i)+e.substring(i,n).replace(/:/g,";")+e.substring(n,e.length));let s=se.exec(e||""),r={},o=14;for(;o--;)r[re[o]]=s[o]||"";return-1!=i&&-1!=n&&(r.source=t,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=function(e,t){const i=/\/{2,9}/g,n=t.replace(i,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1);"/"==t.slice(-1)&&n.splice(n.length-1,1);return n}(0,r.path),r.queryKey=function(e,t){const i={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,n){t&&(i[t]=n)}),i}(0,r.query),r}const ae="function"==typeof addEventListener&&"function"==typeof removeEventListener,ce=[];ae&&addEventListener("offline",()=>{ce.forEach(e=>e())},!1);class de extends M{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const i=oe(e);t.hostname=i.host,t.secure="https"===i.protocol||"wss"===i.protocol,t.port=i.port,i.query&&(t.query=i.query)}else t.host&&(t.hostname=oe(t.host).host);B(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{const 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?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},i=e.split("&");for(let n=0,s=i.length;n<s;n++){let e=i[n].split("=");t[decodeURIComponent(e[0])]=decodeURIComponent(e[1])}return t}(this.opts.query)),ae&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},ce.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const i=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](i)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&de.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}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",de.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)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":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}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(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const 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,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const i=this.writeBuffer[t].data;if(i&&(e+=q(i)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,N(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,i){return this._sendPacket("message",e,t,i),this}send(e,t,i){return this._sendPacket("message",e,t,i),this}_sendPacket(e,t,i,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof i&&(n=i,i=null),"closing"===this.readyState||"closed"===this.readyState)return;(i=i||{}).compress=!1!==i.compress;const s={type:e,data:t,options:i};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),n&&this.once("flush",n),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},i=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?i():e()}):this.upgrading?i():e()),this}_onError(e){if(de.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),ae&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=ce.indexOf(this._offlineEventListener);-1!==e&&ce.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}de.protocol=4;class le extends de{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),i=!1;de.priorWebsocketSuccess=!1;const n=()=>{i||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!i)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;de.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{i||"closed"!==this.readyState&&(d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function s(){i||(i=!0,d(),t.close(),t=null)}const r=e=>{const i=new Error("probe error: "+e);i.transport=t.name,s(),this.emitReserved("upgradeError",i)};function o(){r("transport closed")}function a(){r("socket closed")}function c(e){t&&e.name!==t.name&&s()}const d=()=>{t.removeListener("open",n),t.removeListener("error",r),t.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};t.once("open",n),t.once("error",r),t.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{i||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let i=0;i<e.length;i++)~this.transports.indexOf(e[i])&&t.push(e[i]);return t}}let ue=class extends le{constructor(e,t={}){const i="object"==typeof e?e:t;(!i.transports||i.transports&&"string"==typeof i.transports[0])&&(i.transports=(i.transports||["polling","websocket","webtransport"]).map(e=>ne[e]).filter(e=>!!e)),super(e,i)}};const he="function"==typeof ArrayBuffer,pe=Object.prototype.toString,me="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===pe.call(Blob),ge="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===pe.call(File);function fe(e){return he&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||me&&e instanceof Blob||ge&&e instanceof File}function ve(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,i=e.length;t<i;t++)if(ve(e[t]))return!0;return!1}if(fe(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return ve(e.toJSON(),!0);for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)&&ve(e[i]))return!0;return!1}function be(e){const t=[],i=e.data,n=e;return n.data=ye(i,t),n.attachments=t.length,{packet:n,buffers:t}}function ye(e,t){if(!e)return e;if(fe(e)){const i={_placeholder:!0,num:t.length};return t.push(e),i}if(Array.isArray(e)){const i=new Array(e.length);for(let n=0;n<e.length;n++)i[n]=ye(e[n],t);return i}if("object"==typeof e&&!(e instanceof Date)){const i={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(i[n]=ye(e[n],t));return i}return e}function ke(e,t){return e.data=Te(e.data,t),delete e.attachments,e}function Te(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let i=0;i<e.length;i++)e[i]=Te(e[i],t);else if("object"==typeof e)for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(e[i]=Te(e[i],t));return e}const Ce=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Se,we;(we=Se||(Se={}))[we.CONNECT=0]="CONNECT",we[we.DISCONNECT=1]="DISCONNECT",we[we.EVENT=2]="EVENT",we[we.ACK=3]="ACK",we[we.CONNECT_ERROR=4]="CONNECT_ERROR",we[we.BINARY_EVENT=5]="BINARY_EVENT",we[we.BINARY_ACK=6]="BINARY_ACK";class Ee extends M{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const i=t.type===Se.BINARY_EVENT;i||t.type===Se.BINARY_ACK?(t.type=i?Se.EVENT:Se.ACK,this.reconstructor=new Re(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!fe(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const i={type:Number(e.charAt(0))};if(void 0===Se[i.type])throw new Error("unknown packet type "+i.type);if(i.type===Se.BINARY_EVENT||i.type===Se.BINARY_ACK){const n=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const s=e.substring(n,t);if(s!=Number(s)||"-"!==e.charAt(t))throw new Error("Illegal attachments");i.attachments=Number(s)}if("/"===e.charAt(t+1)){const n=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}i.nsp=e.substring(n,t)}else i.nsp="/";const n=e.charAt(t+1);if(""!==n&&Number(n)==n){const n=t+1;for(;++t;){const i=e.charAt(t);if(null==i||Number(i)!=i){--t;break}if(t===e.length)break}i.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){const n=this.tryParse(e.substr(t));if(!Ee.isPayloadValid(i.type,n))throw new Error("invalid payload");i.data=n}return i}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(t){return!1}}static isPayloadValid(e,t){switch(e){case Se.CONNECT:return xe(t);case Se.DISCONNECT:return void 0===t;case Se.CONNECT_ERROR:return"string"==typeof t||xe(t);case Se.EVENT:case Se.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Ce.indexOf(t[0]));case Se.ACK:case Se.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Re{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=ke(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Pe=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function xe(e){return"[object Object]"===Object.prototype.toString.call(e)}const Ie=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Ee,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Se.EVENT&&e.type!==Se.ACK||!ve(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Se.EVENT?Se.BINARY_EVENT:Se.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Se.BINARY_EVENT&&e.type!==Se.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=be(e),i=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(i),n}},get PacketType(){return Se},isPacketValid:function(e){return"string"==typeof e.nsp&&(void 0===(t=e.id)||Pe(t))&&function(e,t){switch(e){case Se.CONNECT:return void 0===t||xe(t);case Se.DISCONNECT:return void 0===t;case Se.EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Ce.indexOf(t[0]));case Se.ACK:return Array.isArray(t);case Se.CONNECT_ERROR:return"string"==typeof t||xe(t);default:return!1}}(e.type,e.data);var t},protocol:5},Symbol.toStringTag,{value:"Module"}));function _e(e,t,i){return e.on(t,i),function(){e.off(t,i)}}const Oe=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class De extends M{constructor(e,t,i){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,i&&i.auth&&(this.auth=i.auth),this._opts=Object.assign({},i),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[_e(e,"open",this.onopen.bind(this)),_e(e,"packet",this.onpacket.bind(this)),_e(e,"error",this.onerror.bind(this)),_e(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var i,n,s;if(Oe.hasOwnProperty(e))throw new 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;const r={type:Se.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,i=t.pop();this._registerAckCallback(e,i),r.id=e}const o=null===(n=null===(i=this.io.engine)||void 0===i?void 0:i.transport)||void 0===n?void 0:n.writable,a=this.connected&&!(null===(s=this.io.engine)||void 0===s?void 0:s._hasPingExpired());return this.flags.volatile&&!o||(a?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,t){var i;const n=null!==(i=this.flags.timeout)&&void 0!==i?i:this._opts.ackTimeout;if(void 0===n)return void(this.acks[e]=t);const s=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,new Error("operation has timed out"))},n),r=(...e)=>{this.io.clearTimeoutFn(s),t.apply(this,e)};r.withError=!0,this.acks[e]=r}emitWithAck(e,...t){return new Promise((i,n)=>{const s=(e,t)=>e?n(e):i(t);s.withError=!0,t.push(s),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const i={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...n)=>{this._queue[0];return null!==e?i.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...n)),i.pending=!1,this._drainQueue()}),this._queue.push(i),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const 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(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Se.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)){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Se.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new 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 Se.EVENT:case Se.BINARY_EVENT:this.onevent(e);break;case Se.ACK:case Se.BINARY_ACK:this.onack(e);break;case Se.DISCONNECT:this.ondisconnect();break;case Se.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&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){const t=this._anyListeners.slice();for(const i of t)i.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let i=!1;return function(...n){i||(i=!0,t.packet({type:Se.ACK,id:e,data:n}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(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()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Se.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){const t=this._anyListeners;for(let i=0;i<t.length;i++)if(e===t[i])return t.splice(i,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){const t=this._anyOutgoingListeners;for(let i=0;i<t.length;i++)if(e===t[i])return t.splice(i,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const i of t)i.apply(this,e.data)}}}function Ae(e){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}Ae.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),i=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+i:e-i}return 0|Math.min(e,this.max)},Ae.prototype.reset=function(){this.attempts=0},Ae.prototype.setMin=function(e){this.ms=e},Ae.prototype.setMax=function(e){this.max=e},Ae.prototype.setJitter=function(e){this.jitter=e};class Me extends M{constructor(e,t){var i;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,B(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(i=t.randomizationFactor)&&void 0!==i?i:.5),this.backoff=new Ae({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const n=t.parser||Ie;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new ue(this.uri,this.opts);const t=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;const n=_e(t,"open",function(){i.onopen(),e&&e()}),s=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},r=_e(t,"error",s);if(!1!==this._timeout){const e=this._timeout,i=this.setTimeoutFn(()=>{n(),s(new Error("timeout")),t.close()},e);this.opts.autoUnref&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}return this.subs.push(n),this.subs.push(r),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(_e(e,"ping",this.onping.bind(this)),_e(e,"data",this.ondata.bind(this)),_e(e,"error",this.onerror.bind(this)),_e(e,"close",this.onclose.bind(this)),_e(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){N(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let i=this.nsps[e];return i?this._autoConnect&&!i.active&&i.connect():(i=new De(this,e,t),this.nsps[e]=i),i}_destroy(e){const t=Object.keys(this.nsps);for(const i of t){if(this.nsps[i].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let i=0;i<t.length;i++)this.engine.write(t[i],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 i;this.cleanup(),null===(i=this.engine)||void 0===i||i.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;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const i=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&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const Ne={};function Le(e,t){"object"==typeof e&&(t=e,e=void 0);const i=function(e,t="",i){let n=e;i=i||"undefined"!=typeof location&&location,null==e&&(e=i.protocol+"//"+i.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?i.protocol+e:i.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==i?i.protocol+"//"+e:"https://"+e),n=oe(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const s=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+s+":"+n.port+t,n.href=n.protocol+"://"+s+(i&&i.port===n.port?"":":"+n.port),n}(e,(t=t||{}).path||"/socket.io"),n=i.source,s=i.id,r=i.path,o=Ne[s]&&r in Ne[s].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new Me(n,t):(Ne[s]||(Ne[s]=new Me(n,t)),a=Ne[s]),i.query&&!t.query&&(t.query=i.queryKey),a.socket(i.path,t)}Object.assign(Le,{Manager:Me,Socket:De,io:Le,connect:Le});class Ue{constructor(e){this.url=e,this.socket=null}connect(e){this.socket||(this.socket=Le(this.url,{transports:["websocket"],reconnection:!0}),this.socket.on("connect",()=>{console.log("[Socket.IO] connected:",this.socket.id),e&&e()}),this.socket.on("disconnect",e=>{console.log("[Socket.IO] disconnected:",e)}),this.socket.on("connect_error",e=>{console.error("[Socket.IO] error:",e)}),this.socket.onAny((e,...t)=>{console.log(`[Socket.IO] event: ${e}`,t)}))}emit(e,t){this.socket?this.socket.emit(e,t):console.warn("[Socket.IO] not connected")}on(e,t){this.socket&&this.socket.on(e,t)}disconnect(){this.socket&&(this.socket.disconnect(),this.socket=null)}}function je(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(e)}var Fe=Object.defineProperty,Be=(e,t,i)=>((e,t,i)=>t in e?Fe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class qe{constructor(){Be(this,"_locking"),Be(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise(t=>e=()=>{this._locks-=1,t()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function Ve(e,t){if(!e)throw new Error(t)}function ze(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function He(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function We(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}const Ke=Symbol("@bufbuild/protobuf/enum-type");function Ge(e){const t=e[Ke];return Ve(t,"missing enum type on enum object"),t}function Je(e,t,i,n){e[Ke]=Qe(t,i.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function Qe(e,t,i){const n=Object.create(null),s=Object.create(null),r=[];for(const o of t){const e=Xe(o);r.push(e),n[o.name]=e,s[o.no]=e}return{typeName:e,values:r,findName:e=>n[e],findNumber:e=>s[e]}}function Ye(e,t,i){const n={};for(const s of t){const e=Xe(s);n[e.localName]=e.no,n[e.no]=e.localName}return Je(n,e,t),n}function Xe(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class Ze{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){const i=this.getType(),n=i.runtime.json,s=n.makeReadOptions(t);return n.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(n){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(n instanceof Error?n.message:String(n)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){const t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function $e(){let e=0,t=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(e|=(127&i)<<n,!(128&i))return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,!(128&i))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(t|=(127&i)<<n,!(128&i))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function et(e,t,i){for(let r=0;r<28;r+=7){const n=e>>>r,s=!(n>>>7==0&&0==t),o=255&(s?128|n:n);if(i.push(o),!s)return}const n=e>>>28&15|(7&t)<<4,s=!!(t>>3);if(i.push(255&(s?128|n:n)),s){for(let e=3;e<31;e+=7){const n=t>>>e,s=!(n>>>7==0),r=255&(s?128|n:n);if(i.push(r),!s)return}i.push(t>>>31&1)}}const tt=4294967296;function it(e){const t="-"===e[0];t&&(e=e.slice(1));const i=1e6;let n=0,s=0;function r(t,r){const o=Number(e.slice(t,r));s*=i,n=n*i+o,n>=tt&&(s+=n/tt|0,n%=tt)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),t?rt(n,s):st(n,s)}function nt(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(tt*t+e);const i=16777215&(e>>>24|t<<8),n=t>>16&65535;let s=(16777215&e)+6777216*i+6710656*n,r=i+8147497*n,o=2*n;const a=1e7;return s>=a&&(r+=Math.floor(s/a),s%=a),r>=a&&(o+=Math.floor(r/a),r%=a),o.toString()+ot(r)+ot(s)}function st(e,t){return{lo:0|e,hi:0|t}}function rt(e,t){return t=~t,e?e=1+~e:t+=1,st(e,t)}const ot=e=>{const t=String(e);return"0000000".slice(t.length)+t};function at(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let i=0;i<9;i++)t.push(127&e|128),e>>=7;t.push(1)}}function ct(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let i=5;128&e&&i<10;i++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const dt=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw new Error("int64 invalid: ".concat(e));return n},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>s||t<n)throw new Error("uint64 invalid: ".concat(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,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}const t=e=>Ve(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>Ve(/^[0-9]+$/.test(e),"uint64 invalid: ".concat(e));return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),t(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),i(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),it(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),it(e)),dec:(e,t)=>function(e,t){let i=st(e,t);const n=2147483648&i.hi;n&&(i=rt(i.lo,i.hi));const s=nt(i.lo,i.hi);return n?"-"+s:s}(e,t),uDec:(e,t)=>nt(e,t)}}();var lt,ut,ht,pt,mt,gt;function ft(e,t,i){if(t===i)return!0;if(e==lt.BYTES){if(!(t instanceof Uint8Array&&i instanceof Uint8Array))return!1;if(t.length!==i.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==i[e])return!1;return!0}switch(e){case lt.UINT64:case lt.FIXED64:case lt.INT64:case lt.SFIXED64:case lt.SINT64:return t==i}return!1}function vt(e,t){switch(e){case lt.BOOL:return!1;case lt.UINT64:case lt.FIXED64:case lt.INT64:case lt.SFIXED64:case lt.SINT64:return 0==t?dt.zero:"0";case lt.DOUBLE:case lt.FLOAT:return 0;case lt.BYTES:return new Uint8Array(0);case lt.STRING:return"";default:return 0}}function bt(e,t){switch(e){case lt.BOOL:return!1===t;case lt.STRING:return""===t;case lt.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}(ut=lt||(lt={}))[ut.DOUBLE=1]="DOUBLE",ut[ut.FLOAT=2]="FLOAT",ut[ut.INT64=3]="INT64",ut[ut.UINT64=4]="UINT64",ut[ut.INT32=5]="INT32",ut[ut.FIXED64=6]="FIXED64",ut[ut.FIXED32=7]="FIXED32",ut[ut.BOOL=8]="BOOL",ut[ut.STRING=9]="STRING",ut[ut.BYTES=12]="BYTES",ut[ut.UINT32=13]="UINT32",ut[ut.SFIXED32=15]="SFIXED32",ut[ut.SFIXED64=16]="SFIXED64",ut[ut.SINT32=17]="SINT32",ut[ut.SINT64=18]="SINT64",(pt=ht||(ht={}))[pt.BIGINT=0]="BIGINT",pt[pt.STRING=1]="STRING",(gt=mt||(mt={}))[gt.Varint=0]="Varint",gt[gt.Bit64=1]="Bit64",gt[gt.LengthDelimited=2]="LengthDelimited",gt[gt.StartGroup=3]="StartGroup",gt[gt.EndGroup=4]="EndGroup",gt[gt.Bit32=5]="Bit32";class yt{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let n=0;n<this.chunks.length;n++)e+=this.chunks[n].length;let t=new Uint8Array(e),i=0;for(let n=0;n<this.chunks.length;n++)t.set(this.chunks[n],i),i+=this.chunks[n].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 new 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(He(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return ze(e),at(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){We(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){He(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){ze(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return ze(e),at(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=dt.enc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=dt.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=dt.enc(e);return et(t.lo,t.hi,this.buf),this}sint64(e){let t=dt.enc(e),i=t.hi>>31;return et(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=dt.uEnc(e);return et(t.lo,t.hi,this.buf),this}}class kt{constructor(e,t){this.varint64=$e,this.uint32=ct,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=7&e;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case mt.Varint:for(;128&this.buf[this.pos++];);break;case mt.Bit64:this.pos+=4;case mt.Bit32:this.pos+=4;break;case mt.LengthDelimited:let i=this.uint32();this.pos+=i;break;case mt.StartGroup:for(;;){const[e,i]=this.tag();if(i===mt.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(i,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return dt.dec(...this.varint64())}uint64(){return dt.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,dt.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return dt.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return dt.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 Tt(e){const t=e.field.localName,i=Object.create(null);return i[t]=function(e){const t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return vt(t.T,t.L);case"message":const e=t.T,i=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let Ct="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),St=[];for(let yl=0;yl<Ct.length;yl++)St[Ct[yl].charCodeAt(0)]=yl;St["-".charCodeAt(0)]=Ct.indexOf("+"),St["_".charCodeAt(0)]=Ct.indexOf("/");const wt={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i,n=new Uint8Array(t),s=0,r=0,o=0;for(let a=0;a<e.length;a++){if(i=St[e.charCodeAt(a)],void 0===i)switch(e[a]){case"=":r=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=i,r=1;break;case 1:n[s++]=o<<2|(48&i)>>4,o=i,r=2;break;case 2:n[s++]=(15&o)<<4|(60&i)>>2,o=i,r=3;break;case 3:n[s++]=(3&o)<<6|i,r=0}}if(1==r)throw Error("invalid base64 string.");return n.subarray(0,s)},enc(e){let t,i="",n=0,s=0;for(let r=0;r<e.length;r++)switch(t=e[r],n){case 0:i+=Ct[t>>2],s=(3&t)<<4,n=1;break;case 1:i+=Ct[s|t>>4],s=(15&t)<<2,n=2;break;case 2:i+=Ct[s|t>>6],i+=Ct[63&t],n=0}return n&&(i+=Ct[s],i+="=",1==n&&(i+="=")),i}};function Et(e,t,i){xt(t,e);const n=t.runtime.bin.makeReadOptions(i),s=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let i=e.length-1;i>=0;--i)if(e[i].no==t.no)return[e[i]];return[]}return e.filter(e=>e.no===t.no)}(e.getType().runtime.bin.listUnknownFields(e),t.field),[r,o]=Tt(t);for(const a of s)t.runtime.bin.readField(r,n.readerFactory(a.data),t.field,a.wireType,n);return o()}function Rt(e,t,i,n){xt(t,e);const s=t.runtime.bin.makeReadOptions(n),r=t.runtime.bin.makeWriteOptions(n);if(Pt(e,t)){const i=e.getType().runtime.bin.listUnknownFields(e).filter(e=>e.no!=t.field.no);e.getType().runtime.bin.discardUnknownFields(e);for(const t of i)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const o=r.writerFactory();let a=t.field;a.opt||a.repeated||"enum"!=a.kind&&"scalar"!=a.kind||(a=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(a,i,o,r);const c=s.readerFactory(o.finish());for(;c.pos<c.len;){const[t,i]=c.tag(),n=c.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}function Pt(e,t){const i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find(e=>e.no==t.field.no)}function xt(e,t){Ve(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function It(e,t){const i=e.localName;if(e.repeated)return t[i].length>0;if(e.oneof)return t[e.oneof.localName].case===i;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?void 0!==t[i]:"enum"==e.kind?t[i]!==e.T.values[0].no:!bt(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function _t(e,t){const i=e.localName,n=!e.opt&&!e.req;if(e.repeated)t[i]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[i]={};break;case"enum":t[i]=n?e.T.values[0].no:void 0;break;case"scalar":t[i]=n?vt(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function Ot(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(Ze.prototype).every(t=>t in e&&"function"==typeof e[t]))return!1;const i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function Dt(e,t){return Ot(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}lt.DOUBLE,lt.FLOAT,lt.INT64,lt.UINT64,lt.INT32,lt.UINT32,lt.BOOL,lt.STRING,lt.BYTES;const At={ignoreUnknownFields:!1},Mt={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Nt(e){return e?Object.assign(Object.assign({},At),e):At}function Lt(e){return e?Object.assign(Object.assign({},Mt),e):Mt}const Ut=Symbol(),jt=Symbol();function Ft(e){if(null===e)return"null";switch(typeof e){case"object":return Array.isArray(e)?"array":"object";case"string":return e.length>100?"string":'"'.concat(e.split('"').join('\\"'),'"');default:return String(e)}}function Bt(e,t,i,n,s){let r=i.localName;if(i.repeated){if(Ve("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Ft(t)));const a=e[r];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Ft(e)));switch(i.kind){case"message":a.push(i.T.fromJson(e,n));break;case"enum":const t=zt(i.T,e,n.ignoreUnknownFields,!0);t!==jt&&a.push(t);break;case"scalar":try{a.push(Vt(i.T,e,i.L,!0))}catch(o){let t="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Ft(e));throw o instanceof Error&&o.message.length>0&&(t+=": ".concat(o.message)),new Error(t)}}}}else if("map"==i.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Ft(t)));const a=e[r];for(const[e,r]of Object.entries(t)){if(null===r)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: map value null"));let c;try{c=qt(i.K,e)}catch(o){let e="cannot decode map key for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Ft(t));throw o instanceof Error&&o.message.length>0&&(e+=": ".concat(o.message)),new Error(e)}switch(i.V.kind){case"message":a[c]=i.V.T.fromJson(r,n);break;case"enum":const e=zt(i.V.T,r,n.ignoreUnknownFields,!0);e!==jt&&(a[c]=e);break;case"scalar":try{a[c]=Vt(i.V.T,r,ht.BIGINT,!0)}catch(o){let e="cannot decode map value for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Ft(t));throw o instanceof Error&&o.message.length>0&&(e+=": ".concat(o.message)),new Error(e)}}}}else switch(i.oneof&&(e=e[i.oneof.localName]={case:r},r="value"),i.kind){case"message":const a=i.T;if(null===t&&"google.protobuf.Value"!=a.typeName)return;let c=e[r];Ot(c)?c.fromJson(t,n):(e[r]=c=a.fromJson(t,n),a.fieldWrapper&&!i.oneof&&(e[r]=a.fieldWrapper.unwrapField(c)));break;case"enum":const d=zt(i.T,t,n.ignoreUnknownFields,!1);switch(d){case Ut:_t(i,e);break;case jt:break;default:e[r]=d}break;case"scalar":try{const n=Vt(i.T,t,i.L,!1);if(n===Ut)_t(i,e);else e[r]=n}catch(o){let e="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Ft(t));throw o instanceof Error&&o.message.length>0&&(e+=": ".concat(o.message)),new Error(e)}}}function qt(e,t){if(e===lt.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return Vt(e,t,ht.BIGINT,!0).toString()}function Vt(e,t,i,n){if(null===t)return n?vt(e,i):Ut;switch(e){case lt.DOUBLE:case lt.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t)break;if("string"==typeof t&&t.trim().length!==t.length)break;if("string"!=typeof t&&"number"!=typeof t)break;const n=Number(t);if(Number.isNaN(n))break;if(!Number.isFinite(n))break;return e==lt.FLOAT&&We(n),n;case lt.INT32:case lt.FIXED32:case lt.SFIXED32:case lt.SINT32:case lt.UINT32:let r;if("number"==typeof t?r=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(r=Number(t)),void 0===r)break;return e==lt.UINT32||e==lt.FIXED32?He(r):ze(r),r;case lt.INT64:case lt.SFIXED64:case lt.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=dt.parse(t);return i?o.toString():o;case lt.FIXED64:case lt.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const a=dt.uParse(t);return i?a.toString():a;case lt.BOOL:if("boolean"!=typeof t)break;return t;case lt.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(s){throw new Error("invalid UTF8")}return t;case lt.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return wt.dec(t)}throw new Error}function zt(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:Ut;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const n=e.findName(t);if(void 0!==n)return n.no;if(i)return jt}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(Ft(t)))}function Ht(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function Wt(e,t,i){if("map"==e.kind){Ve("object"==typeof t&&null!=t);const n={},s=Object.entries(t);switch(e.V.kind){case"scalar":for(const[i,r]of s)n[i.toString()]=Gt(e.V.T,r);break;case"message":for(const[e,r]of s)n[e.toString()]=r.toJson(i);break;case"enum":const t=e.V.T;for(const[e,r]of s)n[e.toString()]=Kt(t,r,i.enumAsInteger)}return i.emitDefaultValues||s.length>0?n:void 0}if(e.repeated){Ve(Array.isArray(t));const n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(Gt(e.T,t[i]));break;case"enum":for(let s=0;s<t.length;s++)n.push(Kt(e.T,t[s],i.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)n.push(t[e].toJson(i))}return i.emitDefaultValues||n.length>0?n:void 0}switch(e.kind){case"scalar":return Gt(e.T,t);case"enum":return Kt(e.T,t,i.enumAsInteger);case"message":return Dt(e.T,t).toJson(i)}}function Kt(e,t,i){var n;if(Ve("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;const s=e.findNumber(t);return null!==(n=null==s?void 0:s.name)&&void 0!==n?n:t}function Gt(e,t){switch(e){case lt.INT32:case lt.SFIXED32:case lt.SINT32:case lt.FIXED32:case lt.UINT32:return Ve("number"==typeof t),t;case lt.FLOAT:case lt.DOUBLE:return Ve("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case lt.STRING:return Ve("string"==typeof t),t;case lt.BOOL:return Ve("boolean"==typeof t),t;case lt.UINT64:case lt.FIXED64:case lt.INT64:case lt.SFIXED64:case lt.SINT64:return Ve("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case lt.BYTES:return Ve(t instanceof Uint8Array),wt.enc(t)}}const Jt=Symbol("@bufbuild/protobuf/unknown-fields"),Qt={readUnknownFields:!0,readerFactory:e=>new kt(e)},Yt={writeUnknownFields:!0,writerFactory:()=>new yt};function Xt(e){return e?Object.assign(Object.assign({},Qt),e):Qt}function Zt(e){return e?Object.assign(Object.assign({},Yt),e):Yt}function $t(e,t,i,n,s){let{repeated:r,localName:o}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=o&&delete e.value,e.case=o,o="value"),i.kind){case"scalar":case"enum":const a="enum"==i.kind?lt.INT32:i.T;let c=ii;if("scalar"==i.kind&&i.L>0&&(c=ti),r){let i=e[o];if(n==mt.LengthDelimited&&a!=lt.STRING&&a!=lt.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(c(t,a))}else i.push(c(t,a))}else e[o]=c(t,a);break;case"message":const d=i.T;r?e[o].push(ei(t,new d,s,i)):Ot(e[o])?ei(t,e[o],s,i):(e[o]=ei(t,new d,s,i),!d.fieldWrapper||i.oneof||i.repeated||(e[o]=d.fieldWrapper.unwrapField(e[o])));break;case"map":let[l,u]=function(e,t,i){const n=t.uint32(),s=t.pos+n;let r,o;for(;t.pos<s;){const[n]=t.tag();switch(n){case 1:r=ii(t,e.K);break;case 2:switch(e.V.kind){case"scalar":o=ii(t,e.V.T);break;case"enum":o=t.int32();break;case"message":o=ei(t,new e.V.T,i,void 0)}}}void 0===r&&(r=vt(e.K,ht.BIGINT));"string"!=typeof r&&"number"!=typeof r&&(r=r.toString());if(void 0===o)switch(e.V.kind){case"scalar":o=vt(e.V.T,ht.BIGINT);break;case"enum":o=e.V.T.values[0].no;break;case"message":o=new e.V.T}return[r,o]}(i,t,s);e[o][l]=u}}function ei(e,t,i,n){const s=t.getType().runtime.bin,r=null==n?void 0:n.delimited;return s.readMessage(t,e,r?n.no:e.uint32(),i,r),t}function ti(e,t){const i=ii(e,t);return"bigint"==typeof i?i.toString():i}function ii(e,t){switch(t){case lt.STRING:return e.string();case lt.BOOL:return e.bool();case lt.DOUBLE:return e.double();case lt.FLOAT:return e.float();case lt.INT32:return e.int32();case lt.INT64:return e.int64();case lt.UINT64:return e.uint64();case lt.FIXED64:return e.fixed64();case lt.BYTES:return e.bytes();case lt.FIXED32:return e.fixed32();case lt.SFIXED32:return e.sfixed32();case lt.SFIXED64:return e.sfixed64();case lt.SINT64:return e.sint64();case lt.UINT32:return e.uint32();case lt.SINT32:return e.sint32()}}function ni(e,t,i,n){Ve(void 0!==t);const s=e.repeated;switch(e.kind){case"scalar":case"enum":let r="enum"==e.kind?lt.INT32:e.T;if(s)if(Ve(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,mt.LengthDelimited).fork();let[,s]=ai(t);for(let r=0;r<n.length;r++)e[s](n[r]);e.join()}(i,r,e.no,t);else for(const n of t)oi(i,r,e.no,n);else oi(i,r,e.no,t);break;case"message":if(s){Ve(Array.isArray(t));for(const s of t)ri(i,n,e,s)}else ri(i,n,e,t);break;case"map":Ve("object"==typeof t&&null!=t);for(const[s,o]of Object.entries(t))si(i,n,e,s,o)}}function si(e,t,i,n,s){e.tag(i.no,mt.LengthDelimited),e.fork();let r=n;switch(i.K){case lt.INT32:case lt.FIXED32:case lt.UINT32:case lt.SFIXED32:case lt.SINT32:r=Number.parseInt(n);break;case lt.BOOL:Ve("true"==n||"false"==n),r="true"==n}switch(oi(e,i.K,1,r),i.V.kind){case"scalar":oi(e,i.V.T,2,s);break;case"enum":oi(e,lt.INT32,2,s);break;case"message":Ve(void 0!==s),e.tag(2,mt.LengthDelimited).bytes(s.toBinary(t))}e.join()}function ri(e,t,i,n){const s=Dt(i.T,n);i.delimited?e.tag(i.no,mt.StartGroup).raw(s.toBinary(t)).tag(i.no,mt.EndGroup):e.tag(i.no,mt.LengthDelimited).bytes(s.toBinary(t))}function oi(e,t,i,n){Ve(void 0!==n);let[s,r]=ai(t);e.tag(i,s)[r](n)}function ai(e){let t=mt.Varint;switch(e){case lt.BYTES:case lt.STRING:t=mt.LengthDelimited;break;case lt.DOUBLE:case lt.FIXED64:case lt.SFIXED64:t=mt.Bit64;break;case lt.FIXED32:case lt.SFIXED32:case lt.FLOAT:t=mt.Bit32}return[t,lt[e].toLowerCase()]}function ci(e){if(void 0===e)return e;if(Ot(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function di(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class li{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const e={};for(const t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){const e={};for(const t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function ui(e,t){const i=pi(e);return t?i:bi(vi(i))}const hi=pi;function pi(e){let t=!1;const i=[];for(let n=0;n<e.length;n++){let s=e.charAt(n);switch(s){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":i.push(s),t=!1;break;default:t&&(t=!1,s=s.toUpperCase()),i.push(s)}}return i.join("")}const mi=new Set(["constructor","toString","toJSON","valueOf"]),gi=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),fi=e=>"".concat(e,"$"),vi=e=>gi.has(e)?fi(e):e,bi=e=>mi.has(e)?fi(e):e;class yi{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=ui(e,!1)}addField(e){Ve(e.oneof===this,"field ".concat(e.name," not one of ").concat(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]}}const ki=(Ti=e=>new li(e,e=>function(e){var t,i,n,s,r,o;const a=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=ui(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:hi(d.name),e.repeated=null!==(i=d.repeated)&&void 0!==i&&i,"scalar"==d.kind&&(e.L=null!==(n=d.L)&&void 0!==n?n:ht.BIGINT),e.delimited=null!==(s=d.delimited)&&void 0!==s&&s,e.req=null!==(r=d.req)&&void 0!==r&&r,e.opt=null!==(o=d.opt)&&void 0!==o&&o,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=lt.BYTES&&d.T!=lt.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new yi(t)),e.oneof=c,c.addField(e)}a.push(e)}return a}(e)),Ci=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const i=t.localName,n=e;if(t.repeated)n[i]=[];else switch(t.kind){case"oneof":n[i]={case:void 0};break;case"enum":n[i]=0;break;case"map":n[i]={};break;case"scalar":n[i]=vt(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:Nt,makeWriteOptions:Lt,readMessage(e,t,i,n){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(Ft(t)));n=null!=n?n:new e;const s=new Map,r=i.typeRegistry;for(const[o,a]of Object.entries(t)){const t=e.fields.findJsonName(o);if(t){if(t.oneof){if(null===a&&"scalar"==t.kind)continue;const i=s.get(t.oneof);if(void 0!==i)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(o,'"'));s.set(t.oneof,o)}Bt(n,a,t,i,e)}else{let t=!1;if((null==r?void 0:r.findExtension)&&o.startsWith("[")&&o.endsWith("]")){const s=r.findExtension(o.substring(1,o.length-1));if(s&&s.extendee.typeName==e.typeName){t=!0;const[e,r]=Tt(s);Bt(e,a,s.field,i,s),Rt(n,s,r(),i)}}if(!t&&!i.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return n},writeMessage(e,t){const i=e.getType(),n={};let s;try{for(s of i.fields.byNumber()){if(!It(s,e)){if(s.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!Ht(s))continue}const i=Wt(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t);void 0!==i&&(n[t.useProtoFieldName?s.name:s.jsonName]=i)}const r=t.typeRegistry;if(null==r?void 0:r.findExtensionFor)for(const s of i.runtime.bin.listUnknownFields(e)){const o=r.findExtensionFor(i.typeName,s.no);if(o&&Pt(e,o)){const i=Et(e,o,t),s=Wt(o.field,i,t);void 0!==s&&(n[o.field.jsonName]=s)}}}catch(r){const e=s?"cannot encode field ".concat(i.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(i.typeName," to JSON"),t=r instanceof Error?r.message:String(r);throw new Error(e+(t.length>0?": ".concat(t):""))}return n},readScalar:(e,t,i)=>Vt(e,t,null!=i?i:ht.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t)return i||bt(e,t)?Gt(e,t):void 0},debug:Ft},bin:{makeReadOptions:Xt,makeWriteOptions:Zt,listUnknownFields(e){var t;return null!==(t=e[Jt])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[Jt]},writeUnknownFields(e,t){const i=e[Jt];if(i)for(const n of i)t.tag(n.no,n.wireType).raw(n.data)},onUnknownField(e,t,i,n){const s=e;Array.isArray(s[Jt])||(s[Jt]=[]),s[Jt].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,s){const r=e.getType(),o=s?t.len:t.pos+i;let a,c;for(;t.pos<o&&([a,c]=t.tag(),!0!==s||c!=mt.EndGroup);){const i=r.fields.find(a);if(!i){const i=t.skip(c,a);n.readUnknownFields&&this.onUnknownField(e,a,c,i);continue}$t(e,t,i,c,n)}if(s&&(c!=mt.EndGroup||a!==i))throw new Error("invalid end group tag")},readField:$t,writeMessage(e,t,i){const n=e.getType();for(const s of n.fields.byNumber())if(It(s,e))ni(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t,i);else if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&ni(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:Je,initPartial(e,t){if(void 0===e)return;const i=t.getType();for(const n of i.fields.byMember()){const i=n.localName,s=t,r=e;if(null!=r[i])switch(n.kind){case"oneof":const e=r[i].case;if(void 0===e)continue;const t=n.findField(e);let o=r[i].value;t&&"message"==t.kind&&!Ot(o,t.T)?o=new t.T(o):t&&"scalar"===t.kind&&t.T===lt.BYTES&&(o=di(o)),s[i]={case:e,value:o};break;case"scalar":case"enum":let a=r[i];n.T===lt.BYTES&&(a=n.repeated?a.map(di):di(a)),s[i]=a;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===lt.BYTES)for(const[t,n]of Object.entries(r[i]))s[i][t]=di(n);else Object.assign(s[i],r[i]);break;case"message":const e=n.V.T;for(const t of Object.keys(r[i])){let n=r[i][t];e.fieldWrapper||(n=new e(n)),s[i][t]=n}}break;case"message":const c=n.T;if(n.repeated)s[i]=r[i].map(e=>Ot(e,c)?e:new c(e));else{const e=r[i];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?s[i]=di(e):s[i]=e:s[i]=Ot(e,c)?e:new c(e)}}}},equals:(e,t,i)=>t===i||!(!t||!i)&&e.fields.byMember().every(e=>{const n=t[e.localName],s=i[e.localName];if(e.repeated){if(n.length!==s.length)return!1;switch(e.kind){case"message":return n.every((t,i)=>e.T.equals(t,s[i]));case"scalar":return n.every((t,i)=>ft(e.T,t,s[i]));case"enum":return n.every((e,t)=>ft(lt.INT32,e,s[t]))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let t=n,i=s;return e.T.fieldWrapper&&(void 0===t||Ot(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===i||Ot(i)||(i=e.T.fieldWrapper.wrapField(i))),e.T.equals(t,i);case"enum":return ft(lt.INT32,n,s);case"scalar":return ft(e.T,n,s);case"oneof":if(n.case!==s.case)return!1;const r=e.findField(n.case);if(void 0===r)return!0;switch(r.kind){case"message":return r.T.equals(n.value,s.value);case"enum":return ft(lt.INT32,n.value,s.value);case"scalar":return ft(r.T,n.value,s.value)}throw new Error("oneof cannot contain ".concat(r.kind));case"map":const o=Object.keys(n).concat(Object.keys(s));switch(e.V.kind){case"message":const t=e.V.T;return o.every(e=>t.equals(n[e],s[e]));case"enum":return o.every(e=>ft(lt.INT32,n[e],s[e]));case"scalar":const i=e.V.T;return o.every(e=>ft(i,n[e],s[e]))}}}),clone(e){const t=e.getType(),i=new t,n=i;for(const s of t.fields.byMember()){const t=e[s.localName];let i;if(s.repeated)i=t.map(ci);else if("map"==s.kind){i=n[s.localName];for(const[e,n]of Object.entries(t))i[e]=ci(n)}else i="oneof"==s.kind?s.findField(t.case)?{case:t.case,value:ci(t.value)}:{case:void 0}:ci(t);n[s.localName]=i}for(const s of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(n,s.no,s.wireType,s.data);return i}}),{newFieldList:Ti,initFields:Ci}),makeMessageType(e,t,i){return function(e,t,i,n){var s;const r=null!==(s=null==n?void 0:n.localName)&&void 0!==s?s:t.substring(t.lastIndexOf(".")+1),o={[r]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[r];return Object.setPrototypeOf(o.prototype,new Ze),Object.assign(o,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>(new o).fromBinary(e,t),fromJson:(e,t)=>(new o).fromJson(e,t),fromJsonString:(e,t)=>(new o).fromJsonString(e,t),equals:(t,i)=>e.util.equals(o,t,i)}),o}(this,e,t,i)},makeEnum:Ye,makeEnumType:Qe,getEnumType:Ge,makeExtension(e,t,i){return function(e,t,i,n){let s;return{typeName:t,extendee:i,get field(){if(!s){const i="function"==typeof n?n():n;i.name=t.split(".").pop(),i.jsonName="[".concat(t,"]"),s=e.util.newFieldList([i]).list()[0]}return s},runtime:e}}(this,e,t,i)}});var Ti,Ci;class Si extends Ze{constructor(e){super(),this.seconds=dt.zero,this.nanos=0,ki.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(ki.json.debug(e)));const i=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(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw new 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=dt.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=1e3*Number(this.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new 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 new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const e=(this.nanos+1e9).toString().substring(1);i="000000"===e.substring(3)?"."+e.substring(0,3)+"Z":"000"===e.substring(6)?"."+e.substring(0,6)+"Z":"."+e+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return Si.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new Si({seconds:dt.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new Si).fromBinary(e,t)}static fromJson(e,t){return(new Si).fromJson(e,t)}static fromJsonString(e,t){return(new Si).fromJsonString(e,t)}static equals(e,t){return ki.util.equals(Si,e,t)}}Si.runtime=ki,Si.typeName="google.protobuf.Timestamp",Si.fields=ki.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const wi=ki.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Si},{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:Pi,repeated:!0}]),Ei=ki.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:Ri,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),Ri=ki.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Si},{no:3,name:"value",kind:"scalar",T:2}]),Pi=ki.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:Si},{no:7,name:"normalized_end_timestamp",kind:"message",T:Si,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),xi=ki.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Ii=ki.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),_i=ki.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"}]),Oi=ki.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Di=ki.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Ai=ki.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Mi=ki.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"}]),Ni=ki.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=ki.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Ui=ki.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"}]),ji=ki.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:Fi,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:kn}]),Fi=ki.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),Bi=ki.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:ki.getEnumType(_i),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}]),qi=ki.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:ki.getEnumType(Vi)},{no:4,name:"tracks",kind:"message",T:Gi,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:Bi},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:ki.getEnumType(zi)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:ki.getEnumType(Mi)},{no:18,name:"kind_details",kind:"enum",T:ki.getEnumType(Hi),repeated:!0}]),Vi=ki.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),zi=ki.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"}]),Hi=ki.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),Wi=ki.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Ki=ki.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:Ji,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:ki.getEnumType(Qi)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),Gi=ki.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:ki.getEnumType(Ii)},{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:ki.getEnumType(_i)},{no:10,name:"layers",kind:"message",T:Ji,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:ki.getEnumType(Wi)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:kn},{no:19,name:"audio_features",kind:"enum",T:ki.getEnumType(Ui),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:ki.getEnumType(xi)}]),Ji=ki.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:ki.getEnumType(Oi)},{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}]),Qi=ki.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"}]),Yi=ki.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:ki.getEnumType(Xi)},{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:nn,oneof:"value"},{no:3,name:"speaker",kind:"message",T:en,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:sn,oneof:"value"},{no:7,name:"transcription",kind:"message",T:rn,oneof:"value"},{no:8,name:"metrics",kind:"message",T:wi,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:an,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:cn,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:dn,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:ln,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:wn,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:En,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Rn,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:Zi,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),Xi=ki.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Zi=ki.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:ki.getEnumType(Wi)},{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}]),$i=ki.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:nn,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:an,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:cn,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:dn,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:ln,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:wn,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:En,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:Rn,oneof:"value"}]),en=ki.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:tn,repeated:!0}]),tn=ki.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}]),nn=ki.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}]),sn=ki.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),rn=ki.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:on,repeated:!0}]),on=ki.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}]),an=ki.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}]),cn=ki.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}]),dn=ki.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),ln=ki.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:un,oneof:"value"}]),un=ki.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}]),hn=ki.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),pn=ki.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:ki.getEnumType(mn)},{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}]),mn=ki.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),gn=ki.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:ki.getEnumType(fn)},{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}]),fn=ki.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"}]),vn=ki.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:bn},{no:2,name:"screen",kind:"message",T:bn},{no:3,name:"resume_connection",kind:"enum",T:ki.getEnumType(Ai)},{no:4,name:"disabled_codecs",kind:"message",T:yn},{no:5,name:"force_relay",kind:"enum",T:ki.getEnumType(Ai)}]),bn=ki.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:ki.getEnumType(Ai)}]),yn=ki.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:Fi,repeated:!0},{no:2,name:"publish",kind:"message",T:Fi,repeated:!0}]),kn=ki.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Tn=ki.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Cn=ki.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:ki.getEnumType(Tn)},{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"}),Sn=ki.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),wn=ki.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:ki.getEnumType(Wi)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Cn,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Sn,oneof:"content_header"}],{localName:"DataStream_Header"}),En=ki.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"}),Rn=ki.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"}),Pn=ki.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),xn=ki.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),In=ki.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),_n=ki.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),On=ki.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:qn,oneof:"message"},{no:2,name:"answer",kind:"message",T:qn,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Nn,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Mn,oneof:"message"},{no:5,name:"mute",kind:"message",T:Ln,oneof:"message"},{no:6,name:"subscription",kind:"message",T:zn,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Hn,oneof:"message"},{no:8,name:"leave",kind:"message",T:Gn,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Qn,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:ds,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:hs,oneof:"message"},{no:13,name:"simulate",kind:"message",T:gs,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Yn,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:fs,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Wn,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Kn,oneof:"message"}]),Dn=ki.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:Un,oneof:"message"},{no:2,name:"answer",kind:"message",T:qn,oneof:"message"},{no:3,name:"offer",kind:"message",T:qn,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Nn,oneof:"message"},{no:5,name:"update",kind:"message",T:Vn,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Fn,oneof:"message"},{no:8,name:"leave",kind:"message",T:Gn,oneof:"message"},{no:9,name:"mute",kind:"message",T:Ln,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Zn,oneof:"message"},{no:11,name:"room_update",kind:"message",T:$n,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:ts,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:ns,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:os,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:ls,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Bn,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:jn,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:vs,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:ks,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Ts,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Ss,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:us,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:xs,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:as,oneof:"message"}]),An=ki.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:Ji,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:ki.getEnumType(Qi)}]),Mn=ki.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:ki.getEnumType(Ii)},{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:ki.getEnumType(_i)},{no:9,name:"layers",kind:"message",T:Ji,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:An,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:ki.getEnumType(Wi)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:ki.getEnumType(xi)},{no:17,name:"audio_features",kind:"enum",T:ki.getEnumType(Ui),repeated:!0}]),Nn=ki.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:ki.getEnumType(xn)},{no:3,name:"final",kind:"scalar",T:8}]),Ln=ki.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),Un=ki.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:ji},{no:2,name:"participant",kind:"message",T:qi},{no:3,name:"other_participants",kind:"message",T:qi,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Xn,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:vn},{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:pn},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Fi,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),jn=ki.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:Xn,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:vn},{no:3,name:"server_info",kind:"message",T:pn},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Fn=ki.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Gi}]),Bn=ki.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),qn=ki.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}}]),Vn=ki.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:qi,repeated:!0}]),zn=ki.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:hn,repeated:!0}]),Hn=ki.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:ki.getEnumType(Oi)},{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}]),Wn=ki.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:ki.getEnumType(Ui),repeated:!0}]),Kn=ki.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}]),Gn=ki.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:ki.getEnumType(Mi)},{no:3,name:"action",kind:"enum",T:ki.getEnumType(Jn)},{no:4,name:"regions",kind:"message",T:bs}]),Jn=ki.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Qn=ki.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Ji,repeated:!0}]),Yn=ki.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}]),Xn=ki.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}]),Zn=ki.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:tn,repeated:!0}]),$n=ki.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:ji}]),es=ki.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:ki.getEnumType(Di)},{no:3,name:"score",kind:"scalar",T:2}]),ts=ki.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:es,repeated:!0}]),is=ki.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:ki.getEnumType(In)}]),ns=ki.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:is,repeated:!0}]),ss=ki.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:ki.getEnumType(Oi)},{no:2,name:"enabled",kind:"scalar",T:8}]),rs=ki.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:ss,repeated:!0}]),os=ki.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:ss,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:rs,repeated:!0}]),as=ki.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Pn,repeated:!0}]),cs=ki.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}]),ds=ki.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:cs,repeated:!0}]),ls=ki.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}]),us=ki.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:ji},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:qi},{no:4,name:"other_participants",kind:"message",T:qi,repeated:!0}]),hs=ki.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:qn},{no:2,name:"subscription",kind:"message",T:zn},{no:3,name:"publish_tracks",kind:"message",T:Fn,repeated:!0},{no:4,name:"data_channels",kind:"message",T:ms,repeated:!0},{no:5,name:"offer",kind:"message",T:qn},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:ps,repeated:!0}]),ps=ki.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),ms=ki.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:ki.getEnumType(xn)}]),gs=ki.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:ki.getEnumType(_n),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"}]),fs=ki.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),vs=ki.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),bs=ki.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:ys,repeated:!0}]),ys=ki.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}]),ks=ki.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:ki.getEnumType(Li)}]),Ts=ki.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:ki.getEnumType(Cs)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:Nn,oneof:"request"},{no:5,name:"add_track",kind:"message",T:Mn,oneof:"request"},{no:6,name:"mute",kind:"message",T:Ln,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:Yn,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:Wn,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Kn,oneof:"request"}]),Cs=ki.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"}]),Ss=ki.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),ws=ki.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}]),Es=ki.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:gn},{no:2,name:"connection_settings",kind:"message",T:ws},{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:Mn,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:qn},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:ki.getEnumType(Ni)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:hs}]),Rs=ki.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:ki.getEnumType(Ps)},{no:2,name:"join_request",kind:"scalar",T:12}]),Ps=ki.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),xs=ki.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function Is(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var _s,Os={exports:{}};var Ds,As,Ms,Ns,Ls,Us,js,Fs=(_s||(_s=1,As=Os.exports,Ms=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],s={},r=null;function o(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(n){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),s=0;s<n.length;s++){var r=n[s];this[r]=s<i?e:this.methodFactory(r,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function l(n,s,r){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?a:void 0!==console[n]?o(console,n):void 0!==console.log?o(console,"log"):e)}(n)||d.apply(this,arguments)}function u(e,i){var o,a,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(r){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),s=i.indexOf(n+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s+n.length+1))[1])}catch(r){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||l,u.getLevel=function(){return null!=d?d:null!=a?a:o},u.setLevel=function(e,i){return d=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=i)}catch(s){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(s){}}}(d),c.call(u)},u.setDefaultLevel=function(e){a=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(r!==u&&(o=m(r.getLevel())),c.call(u),r===u)for(var e in s)s[e].rebuild()},o=m(r?r.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(r=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=s[e];return t||(t=s[e]=new u(e,r.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return r.noConflict=function(){return typeof window!==t&&window.log===r&&(window.log=h),r},r.getLoggers=function(){return s},r.default=r,r},(Ds=Os).exports?Ds.exports=Ms():As.log=Ms()),Os.exports);(Ls=Ns||(Ns={}))[Ls.trace=0]="trace",Ls[Ls.debug=1]="debug",Ls[Ls.info=2]="info",Ls[Ls.warn=3]="warn",Ls[Ls.error=4]="error",Ls[Ls.silent=5]="silent",(js=Us||(Us={})).Default="livekit",js.Room="livekit-room",js.TokenSource="livekit-token-source",js.Participant="livekit-participant",js.Track="livekit-track",js.Publication="livekit-track-publication",js.Engine="livekit-engine",js.Signal="livekit-signal",js.PCManager="livekit-pc-manager",js.PCTransport="livekit-pc-transport",js.E2EE="lk-e2ee";let Bs=Fs.getLogger("livekit");function qs(e){const t=Fs.getLogger(e);return t.setDefaultLevel(Bs.getLevel()),t}Object.values(Us).map(e=>Fs.getLogger(e)),Bs.setDefaultLevel(Ns.info);const Vs=Fs.getLogger("lk-e2ee"),zs=7e3,Hs=[0,300,1200,2700,4800,zs,zs,zs,zs,zs];function Ws(e,t,i,n){return new(i||(i=Promise))(function(s,r){function o(e){try{c(n.next(e))}catch(t){r(t)}}function a(e){try{c(n.throw(e))}catch(t){r(t)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})}function Ks(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Gs(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=Ks(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise(function(n,s){(function(e,t,i,n){Promise.resolve(n).then(function(t){e({value:t,done:i})},t)})(n,s,(t=e[i](t)).done,t.value)})}}}"function"==typeof SuppressedError&&SuppressedError;var Js,Qs={exports:{}};var Ys=function(){if(Js)return Qs.exports;Js=1;var e,t="object"==typeof Reflect?Reflect:null,i=t&&"function"==typeof t.apply?t.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}Qs.exports=s,Qs.exports.once=function(e,t){return new Promise(function(i,n){function s(i){e.removeListener(t,r),n(i)}function r(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}m(e,t,r,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&m(e,"error",t,i)}(e,s,{once:!0})})},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var r=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function a(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){var s,r,c,d;if(o(i),void 0===(r=e._events)?(r=e._events=Object.create(null),e._eventsCount=0):(void 0!==r.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),r=e._events),c=r[t]),void 0===c)c=r[t]=i,++e._eventsCount;else if("function"==typeof c?c=r[t]=n?[i,c]:[c,i]:n?c.unshift(i):c.push(i),(s=a(e))>0&&c.length>s&&!c.warned){c.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,d=l,console&&console.warn&&console.warn(d)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=d.bind(n);return s.listener=i,n.wrapFn=s,s}function u(e,t,i){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(s):p(s,s.length)}function h(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function p(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function m(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function s(r){n.once&&e.removeEventListener(t,s),i(r)})}}return Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return r},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");r=e}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return a(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var s="error"===e,r=this._events;if(void 0!==r)s=s&&void 0===r.error;else if(!s)return!1;if(s){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=r[e];if(void 0===c)return!1;if("function"==typeof c)i(c,this,t);else{var d=c.length,l=p(c,d);for(n=0;n<d;++n)i(l[n],this,t)}return!0},s.prototype.addListener=function(e,t){return c(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return c(this,e,t,!0)},s.prototype.once=function(e,t){return o(t),this.on(e,l(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,l(this,e,t)),this},s.prototype.removeListener=function(e,t){var i,n,s,r,a;if(o(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(s=-1,r=i.length-1;r>=0;r--)if(i[r]===t||i[r].listener===t){a=i[r].listener,s=r;break}if(s<0)return this;0===s?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,s),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var s,r=Object.keys(i);for(n=0;n<r.length;++n)"removeListener"!==(s=r[n])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return u(this,e,!0)},s.prototype.rawListeners=function(e){return u(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h,s.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},Qs.exports}();let Xs=!0,Zs=!0;function $s(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseFloat(n[i],10)}function er(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return s.apply(this,arguments);const r=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,r),s.apply(this,[e,r])};const r=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return r.apply(this,arguments);if(!this._eventMap[t].has(i))return r.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,r.apply(this,[e,n])},Object.defineProperty(n,"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 tr(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Xs=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function ir(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Zs=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function nr(){if("object"==typeof window){if(Xs)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function sr(e,t){Zs&&console.warn(e+" is deprecated, please use "+t+" instead.")}function rr(e){return"[object Object]"===Object.prototype.toString.call(e)}function or(e){return rr(e)?Object.keys(e).reduce(function(t,i){const n=rr(e[i]),s=n?or(e[i]):e[i],r=n&&!Object.keys(s).length;return void 0===s||r?t:Object.assign(t,{[i]:s})},{}):e}function ar(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach(n=>{n.endsWith("Id")?ar(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach(t=>{ar(e,e.get(t),i)})}))}function cr(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",s=new Map;if(null===t)return s;const r=[];return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&r.push(e)}),r.forEach(t=>{e.forEach(i=>{i.type===n&&i.trackId===t.id&&ar(e,i,s)})}),s}const dr=nr;function lr(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach(i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const s=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[s("min",i)]=n.ideal,t.optional.push(e),e={},e[s("max",i)]=n.ideal,t.optional.push(e)):(e[s("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[s("",i)]=n.exact):["min","max"].forEach(e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[s(e,i)]=n[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},s=function(e,s){if(t.version>=61)return s(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let r=e.video.facingMode;r=r&&("object"==typeof r?r:{ideal:r});const o=t.version<66;if(r&&("user"===r.exact||"environment"===r.exact||"user"===r.ideal||"environment"===r.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===r.exact||"environment"===r.ideal?t=["back","rear"]:"user"!==r.exact&&"user"!==r.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then(i=>{let o=(i=i.filter(e=>"videoinput"===e.kind)).find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=r.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),dr("chrome: "+JSON.stringify(e)),s(e)})}e.video=n(e.video)}return dr("chrome: "+JSON.stringify(e)),s(e)},r=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(i.getUserMedia=function(e,t,n){s(e,e=>{i.webkitGetUserMedia(e,t,e=>{n&&n(r(e))})})}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return s(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(r(e))))}}}function ur(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function hr(e){if("object"==typeof e&&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});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.track.id):{track:i.track};const s=new Event("track");s.track=i.track,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)}),t.stream.getTracks().forEach(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.id):{track:i};const s=new Event("track");s.track=i,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else er(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function pr(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?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()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let s=i.apply(this,arguments);return s||(s=t(this,e),this._senders.push(s)),s};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{const t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function mr(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>cr(t,e.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),er(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>cr(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach(i=>{i.track===e&&(t?n=!0:t=i)}),this.getReceivers().forEach(t=>(t.track===e&&(i?n=!0:i=t),t.track===e)),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function gr(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=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")});const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]}),s.apply(this,arguments)}}function fr(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return gr(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};const n=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]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const s=e.RTCPeerConnection.prototype.removeStream;function r(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(s.id,"g"),n.id)}),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.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,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[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||{};const s=this._streams[i.id];if(s)s.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find(e=>e.track===t)},["createOffer","createAnswer"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=r(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then(e=>r(this,e))}};e.RTCPeerConnection.prototype[t]=n[t]});const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),s.id)}),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:r(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)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");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach(i=>{this._streams[i].getTracks().find(t=>e.track===t)&&(t=this._streams[i])}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function vr(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]})}function br(e,t){er(e,"negotiationneeded",e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e})}var yr=Object.freeze({__proto__:null,fixNegotiationNeeded:br,shimAddTrackRemoveTrack:fr,shimAddTrackRemoveTrackWithNative:gr,shimGetSendersWithDtmf:pr,shimGetUserMedia:lr,shimMediaStream:ur,shimOnTrack:hr,shimPeerConnection:vr,shimSenderReceiverGetStats:mr});function kr(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){sr("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function Tr(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Cr(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]});const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,s,r]=arguments;return n.apply(this,[e||null]).then(e=>{if(t.version<53&&!s)try{e.forEach(e=>{e.type=i[e.type]||e.type})}catch(n){if("TypeError"!==n.name)throw n;e.forEach((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))})}return e}).then(s,r)}}function Sr(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.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 wr(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),er(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Er(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){sr("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function Rr(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Pr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach(e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return n})}function xr(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Ir(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const 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 _r(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const 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 Or=Object.freeze({__proto__:null,shimAddTransceiver:Pr,shimCreateAnswer:_r,shimCreateOffer:Ir,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:xr,shimGetUserMedia:kr,shimOnTrack:Tr,shimPeerConnection:Cr,shimRTCDataChannel:Rr,shimReceiverGetStats:wr,shimRemoveStream:Er,shimSenderGetStats:Sr});function Dr(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(i=>t.call(this,i,e)),e.getVideoTracks().forEach(i=>t.call(this,i,e))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];return n&&n.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||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach(e=>{i.includes(e.track)&&this.removeTrack(e)})})}}function Ar(e){if("object"==typeof e&&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=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)})})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)})}),t.apply(e,arguments)}}}function Mr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,s=t.setLocalDescription,r=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],s=i.apply(this,[n]);return t?(s.then(e,t),Promise.resolve()):s},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],s=n.apply(this,[i]);return t?(s.then(e,t),Promise.resolve()):s};let a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function Nr(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(Lr(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function Lr(e){return e&&void 0!==e.video?Object.assign({},e,{video:or(e.video)}):e}function Ur(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(sr("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function jr(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Fr(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find(e=>"audio"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Br(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var qr,Vr=Object.freeze({__proto__:null,shimAudioContext:Br,shimCallbacksAPI:Mr,shimConstraints:Lr,shimCreateOfferLegacy:Fr,shimGetUserMedia:Nr,shimLocalStreamsAPI:Dr,shimRTCIceServerUrls:Ur,shimRemoteStreamsAPI:Ar,shimTrackEventTransceiver:jr}),zr={exports:{}};var Hr=(qr||(qr=1,function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},t.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter(e=>0===e.indexOf(i))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={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 n=8;n<t.length;n+=2)switch(t[n]){case"raddr":i.relatedAddress=t[n+1];break;case"rport":i.relatedPort=parseInt(t[n+1],10);break;case"tcptype":i.tcpType=t[n+1];break;case"ufrag":i.ufrag=t[n+1],i.usernameFragment=t[n+1];break;default:void 0===i[t[n]]&&(i[t[n]]=t[n+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(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(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let s=0;s<n.length;s++)i=n[s].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach(t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)}),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],s=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substring(12),password:s.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){const s=n[r],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const n=t.parseRtpMap(o),r=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach(e=>{i.headerExtensions.push(t.parseExtmap(e))});const s=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach(e=>{s.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach(e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)});let s=0;return i.codecs.forEach(e=>{e.maxptime>s&&(s=e.maxptime)}),s>0&&(n+="a=maxptime:"+s+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach(e=>{n+=t.writeExtmap(e)}),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),r=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),a=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),s&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:r?"red+ulpfec":"red"},i.push(t))}}),0===i.length&&a&&i.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach(e=>{e.maxBitrate=l})),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute)[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const s=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=0===s.length;const r=t.matchPrefix(e,"a=rtcp-mux");return i.mux=r.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"msid"===e.attribute);return s.length>0?(i=s[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const r=t.matchPrefix(e,"a=sctp-port:");if(r.length>0)return{port:parseInt(r[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:s}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let s;const r=void 0!==i?i:2;return s=e||t.generateSessionId(),"v=0\r\no="+(n||"thisisadapterortc")+" "+s+" "+r+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let t=0;t<n.length;t++)switch(n[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[t].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let t=0;t<i.length;t++)if(i[t].length<2||"="!==i[t].charAt(1))return!1;return!0},e.exports=t}(zr)),zr.exports),Wr=Is(Hr),Kr=je({__proto__:null,default:Wr},[Hr]);function Gr(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),n=Wr.parseCandidate(e.candidate);for(const e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,er(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Jr(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||er(e,"icecandidate",e=>{if(e.candidate){const t=Wr.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Qr(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=Wr.splitSections(e.sdp);return t.shift(),t.some(e=>{const t=Wr.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")})}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const s=Wr.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?n=parseInt(s[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let s;s=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const r={};Object.defineProperty(r,"maxMessageSize",{get:()=>s}),this._sctp=r}return i.apply(this,arguments)}}function Yr(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],s=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&s>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},er(e,"datachannel",e=>(t(e.channel,e.target),e))}function Xr(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const 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=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function Zr(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t._safariVersion>=13.1)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==e.trim()).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function $r(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function eo(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.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"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>i.apply(this,[e]))})}var to=Object.freeze({__proto__:null,removeExtmapAllowMixed:Zr,shimAddIceCandidateNullOrEmpty:$r,shimConnectionState:Xr,shimMaxMessageSize:Qr,shimParameterlessSetLocalDescription:eo,shimRTCIceCandidate:Gr,shimRTCIceCandidateRelayProtocol:Jr,shimSendThrowTypeError:Yr});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=nr,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.userAgentData&&i.userAgentData.brands){const e=i.userAgentData.brands.find(e=>"Chromium"===e.brand);if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(i.mozGetUserMedia)t.browser="firefox",t.version=parseInt($s(i.userAgent,/Firefox\/(\d+)\./,1));else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt($s(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt($s(i.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=$s(i.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),s={browserDetails:n,commonShim:to,extractVersion:$s,disableLog:tr,disableWarnings:ir,sdp:Kr};switch(n.browser){case"chrome":if(!yr||!vr||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=yr,$r(e,n),eo(e),lr(e,n),ur(e),vr(e,n),hr(e),fr(e,n),pr(e),mr(e),br(e,n),Gr(e),Jr(e),Xr(e),Qr(e,n),Yr(e),Zr(e,n);break;case"firefox":if(!Or||!Cr||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=Or,$r(e,n),eo(e),kr(e,n),Cr(e,n),Tr(e),Er(e),Sr(e),wr(e),Rr(e),Pr(e),xr(e),Ir(e),_r(e),Gr(e),Xr(e),Qr(e,n),Yr(e);break;case"safari":if(!Vr||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=Vr,$r(e,n),eo(e),Ur(e),Fr(e),Mr(e),Dr(e),Ar(e),jr(e),Nr(e),Br(e),Gr(e),Jr(e),Qr(e,n),Yr(e),Zr(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});const io=/version\/(\d+(\.?_?\d+)+)/i;let no;function so(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if("undefined"==typeof navigator)return;const i=navigator.userAgent.toLowerCase();if(void 0===no||t){const e=ro.find(e=>{let{test:t}=e;return t.test(i)});no=null==e?void 0:e.describe(i)}return no}const ro=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:oo(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:ao(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:oo(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:ao(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:oo(io,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:ao(e)})}];function oo(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const n=t.match(e);return n&&n.length>=i&&n[i]||""}function ao(e){return e.includes("mac os")?oo(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class co extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var lo,uo,ho,po,mo,go,fo,vo,bo,yo,ko,To,Co,So;(uo=lo||(lo={}))[uo.NotAllowed=0]="NotAllowed",uo[uo.ServerUnreachable=1]="ServerUnreachable",uo[uo.InternalError=2]="InternalError",uo[uo.Cancelled=3]="Cancelled",uo[uo.LeaveRequest=4]="LeaveRequest",uo[uo.Timeout=5]="Timeout",uo[uo.WebSocket=6]="WebSocket";class wo extends co{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=lo[t]}static notAllowed(e,t,i){return new wo(e,lo.NotAllowed,t,i)}static timeout(e){return new wo(e,lo.Timeout)}static leaveRequest(e,t){return new wo(e,lo.LeaveRequest,void 0,t)}static internal(e,t){return new wo(e,lo.InternalError,void 0,t)}static cancelled(e){return new wo(e,lo.Cancelled)}static serverUnreachable(e,t){return new wo(e,lo.ServerUnreachable,t)}static websocket(e,t,i){return new wo(e,lo.WebSocket,t,i)}}class Eo extends co{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class Ro extends co{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class Po extends co{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class xo extends co{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Io extends co{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class _o extends co{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Oo extends co{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName="string"==typeof t?t:Cs[t]}}(po=ho||(ho={}))[po.AlreadyOpened=0]="AlreadyOpened",po[po.AbnormalEnd=1]="AbnormalEnd",po[po.DecodeFailed=2]="DecodeFailed",po[po.LengthExceeded=3]="LengthExceeded",po[po.Incomplete=4]="Incomplete",po[po.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",po[po.EncryptionTypeMismatch=8]="EncryptionTypeMismatch";class Do extends co{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=ho[t]}}class Ao extends co{constructor(e){super(18,e),this.name="SignalReconnectError"}}(go=mo||(mo={})).PermissionDenied="PermissionDenied",go.NotFound="NotFound",go.DeviceInUse="DeviceInUse",go.Other="Other",function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(mo||(mo={}));class Mo{}Mo.setTimeout=function(){return setTimeout(...arguments)},Mo.setInterval=function(){return setInterval(...arguments)},Mo.clearTimeout=function(){return clearTimeout(...arguments)},Mo.clearInterval=function(){return clearInterval(...arguments)},(vo=fo||(fo={})).Connected="connected",vo.Reconnecting="reconnecting",vo.SignalReconnecting="signalReconnecting",vo.Reconnected="reconnected",vo.Disconnected="disconnected",vo.ConnectionStateChanged="connectionStateChanged",vo.Moved="moved",vo.MediaDevicesChanged="mediaDevicesChanged",vo.ParticipantConnected="participantConnected",vo.ParticipantDisconnected="participantDisconnected",vo.TrackPublished="trackPublished",vo.TrackSubscribed="trackSubscribed",vo.TrackSubscriptionFailed="trackSubscriptionFailed",vo.TrackUnpublished="trackUnpublished",vo.TrackUnsubscribed="trackUnsubscribed",vo.TrackMuted="trackMuted",vo.TrackUnmuted="trackUnmuted",vo.LocalTrackPublished="localTrackPublished",vo.LocalTrackUnpublished="localTrackUnpublished",vo.LocalAudioSilenceDetected="localAudioSilenceDetected",vo.ActiveSpeakersChanged="activeSpeakersChanged",vo.ParticipantMetadataChanged="participantMetadataChanged",vo.ParticipantNameChanged="participantNameChanged",vo.ParticipantAttributesChanged="participantAttributesChanged",vo.ParticipantActive="participantActive",vo.RoomMetadataChanged="roomMetadataChanged",vo.DataReceived="dataReceived",vo.SipDTMFReceived="sipDTMFReceived",vo.TranscriptionReceived="transcriptionReceived",vo.ConnectionQualityChanged="connectionQualityChanged",vo.TrackStreamStateChanged="trackStreamStateChanged",vo.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",vo.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",vo.AudioPlaybackStatusChanged="audioPlaybackChanged",vo.VideoPlaybackStatusChanged="videoPlaybackChanged",vo.MediaDevicesError="mediaDevicesError",vo.ParticipantPermissionsChanged="participantPermissionsChanged",vo.SignalConnected="signalConnected",vo.RecordingStatusChanged="recordingStatusChanged",vo.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",vo.EncryptionError="encryptionError",vo.DCBufferStatusChanged="dcBufferStatusChanged",vo.ActiveDeviceChanged="activeDeviceChanged",vo.ChatMessage="chatMessage",vo.LocalTrackSubscribed="localTrackSubscribed",vo.MetricsReceived="metricsReceived",(yo=bo||(bo={})).TrackPublished="trackPublished",yo.TrackSubscribed="trackSubscribed",yo.TrackSubscriptionFailed="trackSubscriptionFailed",yo.TrackUnpublished="trackUnpublished",yo.TrackUnsubscribed="trackUnsubscribed",yo.TrackMuted="trackMuted",yo.TrackUnmuted="trackUnmuted",yo.LocalTrackPublished="localTrackPublished",yo.LocalTrackUnpublished="localTrackUnpublished",yo.LocalTrackCpuConstrained="localTrackCpuConstrained",yo.LocalSenderCreated="localSenderCreated",yo.ParticipantMetadataChanged="participantMetadataChanged",yo.ParticipantNameChanged="participantNameChanged",yo.DataReceived="dataReceived",yo.SipDTMFReceived="sipDTMFReceived",yo.TranscriptionReceived="transcriptionReceived",yo.IsSpeakingChanged="isSpeakingChanged",yo.ConnectionQualityChanged="connectionQualityChanged",yo.TrackStreamStateChanged="trackStreamStateChanged",yo.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",yo.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",yo.TrackCpuConstrained="trackCpuConstrained",yo.MediaDevicesError="mediaDevicesError",yo.AudioStreamAcquired="audioStreamAcquired",yo.ParticipantPermissionsChanged="participantPermissionsChanged",yo.PCTrackAdded="pcTrackAdded",yo.AttributesChanged="attributesChanged",yo.LocalTrackSubscribed="localTrackSubscribed",yo.ChatMessage="chatMessage",yo.Active="active",(To=ko||(ko={})).TransportsCreated="transportsCreated",To.Connected="connected",To.Disconnected="disconnected",To.Resuming="resuming",To.Resumed="resumed",To.Restarting="restarting",To.Restarted="restarted",To.SignalResumed="signalResumed",To.SignalRestarted="signalRestarted",To.Closing="closing",To.MediaTrackAdded="mediaTrackAdded",To.ActiveSpeakersUpdate="activeSpeakersUpdate",To.DataPacketReceived="dataPacketReceived",To.RTPVideoMapUpdate="rtpVideoMapUpdate",To.DCBufferStatusChanged="dcBufferStatusChanged",To.ParticipantUpdate="participantUpdate",To.RoomUpdate="roomUpdate",To.SpeakersChanged="speakersChanged",To.StreamStateChanged="streamStateChanged",To.ConnectionQualityUpdate="connectionQualityUpdate",To.SubscriptionError="subscriptionError",To.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",To.RemoteMute="remoteMute",To.SubscribedQualityUpdate="subscribedQualityUpdate",To.LocalTrackUnpublished="localTrackUnpublished",To.LocalTrackSubscribed="localTrackSubscribed",To.Offline="offline",To.SignalRequestResponse="signalRequestResponse",To.SignalConnected="signalConnected",To.RoomMoved="roomMoved",(So=Co||(Co={})).Message="message",So.Muted="muted",So.Unmuted="unmuted",So.Restarted="restarted",So.Ended="ended",So.Subscribed="subscribed",So.Unsubscribed="unsubscribed",So.CpuConstrained="cpuConstrained",So.UpdateSettings="updateSettings",So.UpdateSubscription="updateSubscription",So.AudioPlaybackStarted="audioPlaybackStarted",So.AudioPlaybackFailed="audioPlaybackFailed",So.AudioSilenceDetected="audioSilenceDetected",So.VisibilityChanged="visibilityChanged",So.VideoDimensionsChanged="videoDimensionsChanged",So.VideoPlaybackStarted="videoPlaybackStarted",So.VideoPlaybackFailed="videoPlaybackFailed",So.ElementAttached="elementAttached",So.ElementDetached="elementDetached",So.UpstreamPaused="upstreamPaused",So.UpstreamResumed="upstreamResumed",So.SubscriptionPermissionChanged="subscriptionPermissionChanged",So.SubscriptionStatusChanged="subscriptionStatusChanged",So.SubscriptionFailed="subscriptionFailed",So.TrackProcessorUpdate="trackProcessorUpdate",So.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",So.TranscriptionReceived="transcriptionReceived",So.TimeSyncUpdate="timeSyncUpdate",So.PreConnectBufferFlushed="preConnectBufferFlushed";class No{constructor(e,t,i,n,s){if("object"==typeof e)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(void 0===t||void 0===i)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:n,priority:s}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const Lo=["vp8","h264"],Uo=["vp8","h264","vp9","av1","h265"];const jo=function(e){return!!Lo.find(t=>t===e)};var Fo,Bo,qo,Vo;(Bo=Fo||(Fo={}))[Bo.PREFER_REGRESSION=0]="PREFER_REGRESSION",Bo[Bo.SIMULCAST=1]="SIMULCAST",Bo[Bo.REGRESSION=2]="REGRESSION",(Vo=qo||(qo={})).telephone={maxBitrate:12e3},Vo.speech={maxBitrate:24e3},Vo.music={maxBitrate:48e3},Vo.musicStereo={maxBitrate:64e3},Vo.musicHighQuality={maxBitrate:96e3},Vo.musicHighQualityStereo={maxBitrate:128e3};const zo={h90:new No(160,90,9e4,20),h180:new No(320,180,16e4,20),h216:new No(384,216,18e4,20),h360:new No(640,360,45e4,20),h540:new No(960,540,8e5,25),h720:new No(1280,720,17e5,30),h1080:new No(1920,1080,3e6,30),h1440:new No(2560,1440,5e6,30),h2160:new No(3840,2160,8e6,30)},Ho={h120:new No(160,120,7e4,20),h180:new No(240,180,125e3,20),h240:new No(320,240,14e4,20),h360:new No(480,360,33e4,20),h480:new No(640,480,5e5,20),h540:new No(720,540,6e5,25),h720:new No(960,720,13e5,30),h1080:new No(1440,1080,23e5,30),h1440:new No(1920,1440,38e5,30)},Wo={h360fps3:new No(640,360,2e5,3,"medium"),h360fps15:new No(640,360,4e5,15,"medium"),h720fps5:new No(1280,720,8e5,5,"medium"),h720fps15:new No(1280,720,15e5,15,"medium"),h720fps30:new No(1280,720,2e6,30,"medium"),h1080fps15:new No(1920,1080,25e5,15,"medium"),h1080fps30:new No(1920,1080,5e6,30,"medium"),original:new No(0,0,7e6,30,"medium")};function Ko(e,t,i){var n,s,r,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:d}=ia(null!=e?e:{}),l=null==t?void 0:t.processor,u=null==i?void 0:i.processor,h=null!=a?a:{};return!0===h.audio&&(h.audio={}),!0===h.video&&(h.video={}),h.audio&&(Go(h.audio,t),null!==(n=(r=h.audio).deviceId)&&void 0!==n||(r.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=null!=c?c:l)),h.video&&(Go(h.video,i),null!==(s=(o=h.video).deviceId)&&void 0!==s||(o.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=null!=d?d:u)),h}function Go(e,t){return Object.keys(t).forEach(i=>{void 0===e[i]&&(e[i]=t[i])}),e}function Jo(e){var t,i,n,s;const r={};if(e.video)if("object"==typeof e.video){const i={},s=i,o=e.video;Object.keys(o).forEach(e=>{if("resolution"===e)Go(s,o.resolution);else s[e]=o[e]}),r.video=i,null!==(t=(n=r.video).deviceId)&&void 0!==t||(n.deviceId={ideal:"default"})}else r.video=!!e.video&&{deviceId:{ideal:"default"}};else r.video=!1;return e.audio?"object"==typeof e.audio?(r.audio=e.audio,null!==(i=(s=r.audio).deviceId)&&void 0!==i||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function Qo(e){return Ws(this,arguments,void 0,function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const i=Yo();if(i){const n=i.createAnalyser();n.fftSize=2048;const s=n.frequencyBinCount,r=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield ua(t),n.getByteTimeDomainData(r);const o=r.some(e=>128!==e&&0!==e);return i.close(),!o}return!1}()})}function Yo(){var e;const t="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){const i=new t({latencyHint:"interactive"});if("suspended"===i.state&&"undefined"!=typeof window&&(null===(e=window.document)||void 0===e?void 0:e.body)){const e=()=>Ws(this,void 0,void 0,function*(){var t;try{"suspended"===i.state&&(yield i.resume())}catch(n){console.warn("Error trying to auto-resume audio context",n)}finally{null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)}});i.addEventListener("statechange",()=>{var t;"closed"===i.state&&(null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e))}),window.document.body.addEventListener("click",e)}return i}}function Xo(e){return"audioinput"===e?aa.Source.Microphone:"videoinput"===e?aa.Source.Camera:aa.Source.Unknown}function Zo(e){return e===aa.Source.Microphone?"audioinput":e===aa.Source.Camera?"videoinput":void 0}function $o(e){return e.split("/")[1].toLowerCase()}function ea(e){const t=[];return e.forEach(e=>{void 0!==e.track&&t.push(new Fn({cid:e.track.mediaStreamID,track:e.trackInfo}))}),t}function ta(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?ta(e.track):{})}}function ia(e){const t=Object.assign({},e);let i,n;return"object"==typeof t.audio&&t.audio.processor&&(i=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),"object"==typeof t.video&&t.video.processor&&(n=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:i,videoProcessor:n,optionsWithoutProcessor:(s=t,void 0===s?s:"function"==typeof structuredClone?"object"==typeof s&&null!==s?structuredClone(Object.assign({},s)):structuredClone(s):JSON.parse(JSON.stringify(s)))};var s}function na(e,t){return e.width*e.height<t.width*t.height}const sa=[];var ra,oa;(oa=ra||(ra={}))[oa.LOW=0]="LOW",oa[oa.MEDIUM=1]="MEDIUM",oa[oa.HIGH=2]="HIGH";class aa extends Ys.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var n;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=aa.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Bs,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),5e3):this.handleAppVisibilityChanged()},this.log=qs(null!==(n=i.loggerName)&&void 0!==n?n:Us.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=aa.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),ta(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===aa.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===aa.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(sa.forEach(t=>{null!==t.parentElement||e||(e=t)}),e&&sa.splice(sa.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),ca(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),n=i.some(e=>"audio"===e.kind);return e.play().then(()=>{this.emit(n?Co.AudioPlaybackStarted:Co.VideoPlaybackStarted)}).catch(t=>{"NotAllowedError"===t.name?this.emit(n?Co.AudioPlaybackFailed:Co.VideoPlaybackFailed,t):"AbortError"===t.name?Bs.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):Bs.warn("could not playback ".concat(n?"audio":"video"),t),n&&e&&i.some(e=>"video"===e.kind)&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(Co.ElementAttached,e),e}detach(e){try{if(e){da(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(Co.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(e=>{da(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(Co.ElementDetached,e)}),this.attachedElements=[],t}finally{0===this.attachedElements.length&&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=qs(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),sa.forEach(e=>{e.parentElement||(t=!1)}),t&&sa.push(e)}}handleAppVisibilityChanged(){return Ws(this,void 0,void 0,function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==aa.Kind.Video||setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Ta()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Ta()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function ca(e,t){let i,n;i=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks(),n.includes(e)||(n.forEach(e=>{i.removeTrack(e)}),i.addTrack(e)),ba()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(ba()||fa())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=i,t.play().catch(()=>{})},0))}function da(e,t){if(t.srcObject instanceof MediaStream){const i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}!function(e){let t;var i;let n;var s;let r;var o;(i=t=e.Kind||(e.Kind={})).Audio="audio",i.Video="video",i.Unknown="unknown",(s=n=e.Source||(e.Source={})).Camera="camera",s.Microphone="microphone",s.ScreenShare="screen_share",s.ScreenShareAudio="screen_share_audio",s.Unknown="unknown",(o=r=e.StreamState||(e.StreamState={})).Active="active",o.Paused="paused",o.Unknown="unknown",e.kindToProto=function(e){switch(e){case t.Audio:return Ii.AUDIO;case t.Video:return Ii.VIDEO;default:return Ii.DATA}},e.kindFromProto=function(e){switch(e){case Ii.AUDIO:return t.Audio;case Ii.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return _i.CAMERA;case n.Microphone:return _i.MICROPHONE;case n.ScreenShare:return _i.SCREEN_SHARE;case n.ScreenShareAudio:return _i.SCREEN_SHARE_AUDIO;default:return _i.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case _i.CAMERA:return n.Camera;case _i.MICROPHONE:return n.Microphone;case _i.SCREEN_SHARE:return n.ScreenShare;case _i.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case In.ACTIVE:return r.Active;case In.PAUSED:return r.Paused;default:return r.Unknown}}}(aa||(aa={}));const la="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function ua(e){return Ws(this,void 0,void 0,function*(){return new Promise(t=>Mo.setTimeout(t,e))})}function ha(){return"addTransceiver"in RTCPeerConnection.prototype}function pa(){return"addTrack"in RTCPeerConnection.prototype}function ma(e){return"av1"===e||"vp9"===e}function ga(e){return!(!document||ya())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function fa(){var e;return"Firefox"===(null===(e=so())||void 0===e?void 0:e.name)}function va(){const e=so();return!!e&&"Chrome"===e.name&&"iOS"!==e.os}function ba(){var e;return"Safari"===(null===(e=so())||void 0===e?void 0:e.name)}function ya(){const e=so();return"Safari"===(null==e?void 0:e.name)||"iOS"===(null==e?void 0:e.os)}function ka(){var e,t;return!!Ta()&&(null!==(t=null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile)&&void 0!==t?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function Ta(){return"undefined"!=typeof document}function Ca(){return"ReactNative"==navigator.product}function Sa(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function wa(e){return Sa(e)?e.hostname.split(".")[0]:null}function Ea(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Ra(){if(!Ca())return;let e=Ea();return e?e.platform:void 0}function Pa(){if(Ta())return window.devicePixelRatio;if(Ca()){let e=Ea();if(e)return e.devicePixelRatio}return 1}function xa(e,t){const i=e.split("."),n=t.split("."),s=Math.min(i.length,n.length);for(let r=0;r<s;++r){const e=parseInt(i[r],10),t=parseInt(n[r],10);if(e>t)return 1;if(e<t)return-1;if(r===s-1&&e===t)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function Ia(e){for(const t of e)t.target.handleResize(t)}function _a(e){for(const t of e)t.target.handleVisibilityChanged(t)}let Oa=null;const Da=()=>(Oa||(Oa=new ResizeObserver(Ia)),Oa);let Aa=null;const Ma=()=>(Aa||(Aa=new IntersectionObserver(_a,{root:null,rootMargin:"0px"})),Aa);function Na(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const s=document.createElement("canvas");s.width=e,s.height=t;const r=s.getContext("2d");null==r||r.fillRect(0,0,s.width,s.height),n&&r&&(r.beginPath(),r.arc(e/2,t/2,50,0,2*Math.PI,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=i,a}let La;function Ua(){if(!La){const e=new AudioContext,t=e.createOscillator(),i=e.createGain();i.gain.setValueAtTime(0,0);const n=e.createMediaStreamDestination();if(t.connect(i),i.connect(n),t.start(),[La]=n.stream.getAudioTracks(),!La)throw Error("Could not get empty media stream audio track");La.enabled=!1}return La.clone()}class ja{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,i)=>Ws(this,void 0,void 0,function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})).finally(()=>{var e;this._isResolved=!0,null===(e=this.onFinally)||void 0===e||e.call(this)})}}function Fa(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(void 0!==e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(void 0!==e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function Ba(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function qa(e){switch(e.reason){case lo.LeaveRequest:return e.context;case lo.Cancelled:return Mi.CLIENT_INITIATED;case lo.NotAllowed:return Mi.USER_REJECTED;case lo.ServerUnreachable:return Mi.JOIN_FAILURE;default:return Mi.UNKNOWN_REASON}}function Va(e){return void 0!==e?Number(e):void 0}function za(e){return void 0!==e?BigInt(e):void 0}function Ha(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function Wa(e){return!!e&&e.kind==aa.Kind.Audio}function Ka(e){return!!e&&e.kind==aa.Kind.Video}function Ga(e){return Ha(e)&&Ka(e)}function Ja(e){return Ha(e)&&Wa(e)}function Qa(e){return!!e&&!e.isLocal}function Ya(e){return!!e&&!e.isLocal}function Xa(e){return Qa(e)&&Ka(e)}function Za(e){return e.endsWith("/")?e:"".concat(e,"/")}function $a(e,t){return e.pathname="".concat(Za(e.pathname)).concat(t),e.toString()}function ec(e){if("string"==typeof e)return Dn.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return Dn.fromBinary(new Uint8Array(e));throw new Error("could not decode websocket message: ".concat(typeof e))}const tc="lk_e2ee";var ic,nc,sc,rc,oc,ac,cc,dc;function lc(){return void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||uc()}function uc(){return void 0!==window.RTCRtpScriptTransform}(nc=ic||(ic={})).SetKey="setKey",nc.RatchetRequest="ratchetRequest",nc.KeyRatcheted="keyRatcheted",(sc||(sc={})).KeyRatcheted="keyRatcheted",(oc=rc||(rc={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",oc.EncryptionError="encryptionError",(ac||(ac={})).Error="cryptorError";Ys.EventEmitter;(dc=cc||(cc={}))[dc.InvalidKey=0]="InvalidKey",dc[dc.MissingKey=1]="MissingKey",dc[dc.InternalError=2]="InternalError";class hc extends Ys.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=e=>{var t,i;const{kind:n,data:s}=e.data;switch(n){case"error":if(Bs.error(s.error.message),s.uuid){const e=this.decryptDataRequests.get(s.uuid);if(null==e?void 0:e.reject){e.reject(s.error);break}const t=this.encryptDataRequests.get(s.uuid);if(null==t?void 0:t.reject){t.reject(s.error);break}}this.emit(rc.EncryptionError,s.error,s.participantIdentity);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)});break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)}),this.encryptionEnabled!==s.enabled&&s.participantIdentity===(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))this.emit(rc.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const e=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(rc.ParticipantEncryptionStatusChanged,s.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(ic.KeyRatcheted,s.ratchetResult,s.participantIdentity,s.keyIndex);break;case"decryptDataResponse":const e=this.decryptDataRequests.get(s.uuid);(null==e?void 0:e.resolve)&&e.resolve(s);break;case"encryptDataResponse":const n=this.encryptDataRequests.get(s.uuid);(null==n?void 0:n.resolve)&&n.resolve(s)}},this.onWorkerError=e=>{Bs.error("e2ee worker encountered an error:",{error:e.error}),this.emit(rc.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(!lc())throw new Eo("tried to setup end-to-end encryption on an unsupported browser");if(Bs.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Vs.getLevel()}};this.worker&&(Bs.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){Bs.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):Bs.warn("ignoring server sent trailer as it's empty")}setupEngine(e){e.on(ko.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(fo.TrackPublished,(e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==Wi.NONE,t.identity)),e.on(fo.ConnectionStateChanged,t=>{t===il.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==Wi.NONE,e.identity)})})}).on(fo.TrackUnsubscribed,(e,t,i)=>{var n;const s={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(s)}).on(fo.TrackSubscribed,(e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)}).on(fo.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(e=>{this.postKey(e)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(bo.LocalSenderCreated,(e,t)=>Ws(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),e.localParticipant.on(bo.LocalTrackPublished,e=>{if(!Ka(e.track)||!ya())return;const t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:$o(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}),t.on(ic.SetKey,e=>this.postKey(e)).on(ic.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}encryptData(e){return Ws(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},n=new ja;return n.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,n),this.worker.postMessage(i),n.promise})}handleEncryptedData(e,t,i,n){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const s=crypto.randomUUID(),r={kind:"decryptDataRequest",data:{uuid:s,payload:e,iv:t,participantIdentity:i,keyIndex:n}},o=new ja;return o.onFinally=()=>{this.decryptDataRequests.delete(s)},this.decryptDataRequests.set(s,o),this.worker.postMessage(r),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:n}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const r={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:t,keyIndex:n}};this.worker.postMessage(r)}postEnable(e,t){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?$o(i.mimeType):void 0)}}setupE2EESender(e,t){Ha(e)&&t?this.handleSender(t,e.mediaStreamID,void 0):t||Bs.warn("early return because sender is not ready")}handleReceiver(e,t,i,n){return Ws(this,void 0,void 0,function*(){if(this.worker){if(uc()&&!va()){const s={kind:"decode",participantIdentity:i,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(tc in e&&n){const e={kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}};return void this.worker.postMessage(e)}let s=e.writableStream,r=e.readableStream;if(!s||!r){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,r=t.readable}const o={kind:"decode",data:{readableStream:r,writableStream:s,trackId:t,codec:n,participantIdentity:i,isReuse:tc in e}};this.worker.postMessage(o,[r,s])}e[tc]=!0}})}handleSender(e,t,i){var n;if(!(tc in e)&&this.worker){if(!(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(uc()&&!va()){Bs.info("initialize script transform");const n={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,n)}else{Bs.info("initialize encoded streams");const n=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(s,[n.readable,n.writable])}e[tc]=!0}}}class pc{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new pc),this._instance}addFailedConnectionAttempt(e){var t;const i=wa(new URL(e));if(!i)return;let n=null!==(t=this.failedConnectionAttempts.get(i))&&void 0!==t?t:0;this.failedConnectionAttempts.set(i,n+1),this.backOffPromises.set(i,ua(Math.min(500*Math.pow(2,n),15e3)))}getBackOffPromise(e){const t=new URL(e),i=t&&wa(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),i=t&&wa(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}pc._instance=null;const mc="default";class gc{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new gc),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return Ws(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;if((null===(n=gc.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){Bs.debug("awaiting getUserMedia promise");try{e?yield gc.userMediaPromiseMap.get(e):yield Promise.all(gc.userMediaPromiseMap.values())}catch(r){Bs.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&(!ba()||!t.hasDeviceInUse(e))){if(0===s.filter(t=>t.kind===e).length||s.some(t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n})){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}},i=yield navigator.mediaDevices.getUserMedia(t);s=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach(e=>{e.stop()})}}return t._previousDevices=s,e&&(s=s.filter(t=>t.kind===e)),s}()})}normalizeDeviceId(e,t,i){return Ws(this,void 0,void 0,function*(){if(t!==mc)return t;const n=yield this.getDevices(e),s=n.find(e=>e.deviceId===mc);if(!s)return void Bs.warn("could not reliably determine default device");const r=n.find(e=>e.deviceId!==mc&&e.groupId===(null!=i?i:s.groupId));if(r)return null==r?void 0:r.deviceId;Bs.warn("could not reliably determine default device")})}hasDeviceInUse(e){return e?gc.userMediaPromiseMap.has(e):gc.userMediaPromiseMap.size>0}}var fc,vc;gc.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],gc.userMediaPromiseMap=new Map,(vc=fc||(fc={}))[vc.WAITING=0]="WAITING",vc[vc.RUNNING=1]="RUNNING",vc[vc.COMPLETED=2]="COMPLETED";class bc{constructor(){this.pendingTasks=new Map,this.taskMutex=new qe,this.nextTaskIndex=0}run(e){return Ws(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:fc.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=fc.RUNNING,yield e()}finally{t.status=fc.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return Ws(this,void 0,void 0,function*(){return this.run(()=>Ws(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class yc{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i,n;if(null===(i=t.signal)||void 0===i?void 0:i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const s=new WebSocket(e,null!==(n=t.protocols)&&void 0!==n?n:[]);s.binaryType="arraybuffer",this.ws=s;const r=function(){let{closeCode:e,reason:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return s.close(e,t)};this.opened=new Promise((e,t)=>{s.onopen=()=>{e({readable:new ReadableStream({start(e){s.onmessage=t=>{let{data:i}=t;return e.enqueue(i)},s.onerror=t=>e.error(t)},cancel:r}),writable:new WritableStream({write(e){s.send(e)},abort(){s.close()},close:r}),protocol:s.protocol,extensions:s.extensions}),s.removeEventListener("error",t)},s.addEventListener("error",t)}),this.closed=new Promise((e,t)=>{const i=()=>Ws(this,void 0,void 0,function*(){const i=new Promise(e=>{s.readyState!==WebSocket.CLOSED&&s.addEventListener("close",t=>{e(t)},{once:!0})}),n=yield Promise.race([ua(250),i]);n?e(n):t(new Error("Encountered unspecified websocket error without a timely close event"))});s.onclose=t=>{let{code:n,reason:r}=t;e({closeCode:n,reason:r}),s.removeEventListener("error",i)},s.addEventListener("error",i)}),t.signal&&(t.signal.onabort=()=>s.close()),this.close=r}}const kc=["syncState","trickle","offer","answer","simulate","leave"];var Tc,Cc;(Cc=Tc||(Tc={}))[Cc.CONNECTING=0]="CONNECTING",Cc[Cc.CONNECTED=1]="CONNECTED",Cc[Cc.RECONNECTING=2]="RECONNECTING",Cc[Cc.DISCONNECTING=3]="DISCONNECTING",Cc[Cc.DISCONNECTED=4]="DISCONNECTED";class Sc{get currentState(){return this.state}get isDisconnected(){return this.state===Tc.DISCONNECTING||this.state===Tc.DISCONNECTED}get isEstablishingConnection(){return this.state===Tc.CONNECTING||this.state===Tc.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;this.rtt=0,this.state=Tc.DISCONNECTED,this.log=Bs,this._requestId=0,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=qs(null!==(i=t.loggerName)&&void 0!==i?i:Us.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new bc,this.queuedRequests=[],this.closingLock=new qe,this.connectionLock=new qe,this.state=Tc.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,i,n){return Ws(this,void 0,void 0,function*(){this.state=Tc.CONNECTING,this.options=i;return yield this.connect(e,t,i,n)})}reconnect(e,t,i,n){return Ws(this,void 0,void 0,function*(){if(!this.options)return void this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);this.state=Tc.RECONNECTING,this.clearPingInterval();return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}))})}connect(e,t,i,n){return Ws(this,void 0,void 0,function*(){const s=yield this.connectionLock.lock();this.connectOptions=i;const r=function(){var e;const t=new gn({sdk:fn.JS,protocol:16,version:"2.16.1"});return Ca()&&(t.os=null!==(e=Ra())&&void 0!==e?e:""),t}(),o=i.singlePeerConnection?function(e,t,i){const n=new URLSearchParams;n.set("access_token",e);const s=new Es({clientInfo:t,connectionSettings:new ws({autoSubscribe:!!i.autoSubscribe,adaptiveStream:!!i.adaptiveStream}),reconnect:!!i.reconnect,participantSid:i.sid?i.sid:void 0});i.reconnectReason&&(s.reconnectReason=i.reconnectReason);const r=new Rs({joinRequest:s.toBinary()});return n.set("join_request",btoa(new TextDecoder("utf-8").decode(r.toBinary()))),n}(t,r,i):function(e,t,i){var n;const s=new URLSearchParams;s.set("access_token",e),i.reconnect&&(s.set("reconnect","1"),i.sid&&s.set("sid",i.sid));s.set("auto_subscribe",i.autoSubscribe?"1":"0"),s.set("sdk",Ca()?"reactnative":"js"),s.set("version",t.version),s.set("protocol",t.protocol.toString()),t.deviceModel&&s.set("device_model",t.deviceModel);t.os&&s.set("os",t.os);t.osVersion&&s.set("os_version",t.osVersion);t.browser&&s.set("browser",t.browser);t.browserVersion&&s.set("browser_version",t.browserVersion);i.adaptiveStream&&s.set("adaptive_stream","1");i.reconnectReason&&s.set("reconnect_reason",i.reconnectReason.toString());(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&s.set("network",navigator.connection.type);return s}(t,r,i),a=function(e,t){const i=new URL(function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e));return t.forEach((e,t)=>{i.searchParams.set(t,e)}),$a(i,"rtc")}(e,o),c=$a(new URL(Ba(a)),"validate");return new Promise((e,t)=>Ws(this,void 0,void 0,function*(){var r,o;try{let s=!1;const l=e=>Ws(this,void 0,void 0,function*(){if(s)return;s=!0;const i=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unknown reason";if(!(e instanceof AbortSignal))return t;const i=e.reason;switch(typeof i){case"string":return i;case"object":return i instanceof Error?i.message:t;default:return"toString"in i?i.toString():t}}(e instanceof Event?e.currentTarget:e,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(i)).catch(e=>{this.log.error(e),this.close()}):this.close(),u(),t(wo.cancelled(i))});null==n||n.addEventListener("abort",l);const u=()=>{clearTimeout(h),null==n||n.removeEventListener("abort",l)},h=setTimeout(()=>{l(wo.timeout("room connection has timed out (signal)"))},i.websocketTimeout),p=(e,t)=>{this.handleSignalConnected(e,h,t)},m=new URL(a);m.searchParams.has("access_token")&&m.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(m),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new yc(a);try{this.ws.closed.then(e=>{var i;this.isEstablishingConnection&&t(wo.internal("Websocket got closed during a (re)connection attempt: ".concat(e.reason))),1e3!==e.closeCode&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.closeCode,wasClean:1e3===e.closeCode,state:this.state})),this.state===Tc.CONNECTED&&this.handleOnClose(null!==(i=e.reason)&&void 0!==i?i:"Unexpected WS error"))}).catch(e=>{this.isEstablishingConnection&&t(wo.internal("Websocket error during a (re)connection attempt: ".concat(e)))});const n=yield this.ws.opened.catch(e=>Ws(this,void 0,void 0,function*(){if(this.state!==Tc.CONNECTED){this.state=Tc.DISCONNECTED,clearTimeout(h);const i=yield this.handleConnectionError(e,c);return void t(i)}this.handleWSError(e),t(e)}));if(clearTimeout(h),!n)return;const s=n.readable.getReader();this.streamWriter=n.writable.getWriter();const a=yield s.read();if(s.releaseLock(),!a.value)throw wo.internal("no message received as first message");const d=ec(a.value),l=this.validateFirstMessage(d,null!==(r=i.reconnect)&&void 0!==r&&r);if(!l.isValid)return void t(l.error);"join"===(null===(o=d.message)||void 0===o?void 0:o.case)&&(this.pingTimeoutDuration=d.message.value.pingTimeout,this.pingIntervalDuration=d.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})));p(n,l.shouldProcessFirstMessage?d:void 0),e(l.response)}catch(d){t(d)}finally{u()}}finally{s()}}))})}startReadingLoop(e,t){return Ws(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield ua(this.signalLatency));const{done:t,value:i}=yield e.read();if(t)break;const n=ec(i);this.handleSignalResponse(n)}})}close(){return Ws(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Close method called on signal client";return function*(){if([Tc.DISCONNECTING||Tc.DISCONNECTED].includes(e.state))return void e.log.debug("ignoring signal close as it's already in disconnecting state");const n=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Tc.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});const t=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([t,ua(250)])}}catch(s){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:s}))}finally{t&&(e.state=Tc.DISCONNECTED),n()}}()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Ec(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:Ec(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 Nn({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Ln({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return Ws(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const s=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new Yn({requestId:s,metadata:e,name:t,attributes:n})}),s}()})}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 Qn({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new ds({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:dt.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new fs({timestamp:dt.parse(Date.now()),rtt:dt.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Wn({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Gn({reason:Mi.CLIENT_INITIATED,action:Jn.DISCONNECT})})}sendRequest(e){return Ws(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){const n=!i&&!function(e){const t=kc.indexOf(e.case)>=0;return Bs.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(n&&t.state===Tc.RECONNECTING)return void t.queuedRequests.push(()=>Ws(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield ua(t.signalLatency)),t.isDisconnected)return void t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));if(!t.streamWriter)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);const s=new On({message:e});try{t.useJSON?yield t.streamWriter.write(s.toJsonString()):yield t.streamWriter.write(s.toBinary())}catch(r){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:r}))}}()})}handleSignalResponse(e){var t,i;const n=e.message;if(null==n)return void this.log.debug("received unsupported message",this.logContext);let s=!1;if("answer"===n.case){const e=wc(n.value);this.onAnswer&&this.onAnswer(e,n.value.id,n.value.midToTrackId)}else if("offer"===n.case){const e=wc(n.value);this.onOffer&&this.onOffer(e,n.value.id,n.value.midToTrackId)}else if("trickle"===n.case){const e=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(e,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=n.value.participants)&&void 0!==t?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.value.speakers)&&void 0!==i?i:[]):"leave"===n.case?this.onLeave&&this.onLeave(n.value):"mute"===n.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.value.sid,n.value.muted):"roomUpdate"===n.case?this.onRoomUpdate&&n.value.room&&this.onRoomUpdate(n.value.room):"connectionQuality"===n.case?this.onConnectionQuality&&this.onConnectionQuality(n.value):"streamStateUpdate"===n.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.value):"subscribedQualityUpdate"===n.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.value):"subscriptionPermissionUpdate"===n.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.value):"refreshToken"===n.case?this.onTokenRefresh&&this.onTokenRefresh(n.value):"trackUnpublished"===n.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.value):"subscriptionResponse"===n.case?this.onSubscriptionError&&this.onSubscriptionError(n.value):"pong"===n.case||("pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):"roomMoved"===n.case?(this.onTokenRefresh&&this.onTokenRefresh(n.value.token),this.onRoomMoved&&this.onRoomMoved(n.value)):"mediaSectionsRequirement"===n.case?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(n.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return Ws(this,void 0,void 0,function*(){if(this.state===Tc.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(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(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=Mo.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set",this.logContext)}clearPingTimeout(){this.pingTimeout&&Mo.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=Mo.setInterval(()=>{this.sendPing()},1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set",this.logContext)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Mo.clearInterval(this.pingInterval)}handleSignalConnected(e,t,i){this.state=Tc.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,t){var i,n,s,r,o;return"join"===(null===(i=e.message)||void 0===i?void 0:i.case)?{isValid:!0,response:e.message.value}:this.state===Tc.RECONNECTING&&"leave"!==(null===(n=e.message)||void 0===n?void 0:n.case)?"reconnect"===(null===(s=e.message)||void 0===s?void 0:s.case)?{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&&"leave"===(null===(r=e.message)||void 0===r?void 0:r.case)?{isValid:!1,error:wo.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:wo.internal("Unexpected first message")}:{isValid:!1,error:wo.internal("did not receive join response, got ".concat(null===(o=e.message)||void 0===o?void 0:o.case," instead"))}}handleConnectionError(e,t){return Ws(this,void 0,void 0,function*(){try{const i=yield fetch(t);if(i.status.toFixed(0).startsWith("4")){const e=yield i.text();return wo.notAllowed(e,i.status)}return e instanceof wo?e:wo.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(i){return i instanceof wo?i:wo.serverUnreachable(i instanceof Error?i.message:"server was not reachable")}})}}function wc(e){const t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function Ec(e,t){return new qn({sdp:e.sdp,type:e.type,id:t})}class Rc{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0;){if(!(this.buffer[0].sequence<=e))break;this.pop()}}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class Pc{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const n=i+this.ttl;return this._map.set(e,{value:t,expiresAt:n}),this}get(e){const t=this._map.get(e);if(t){if(!(t.expiresAt<Date.now()))return t.value;this._map.delete(e)}}has(e){const t=this._map.get(e);return!!t&&(!(t.expiresAt<Date.now())||(this._map.delete(e),!1))}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[t,i]of this._map.entries())i.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e(i.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],i=this.asValueMap();for(const[n,s]of i.entries())t.push(e(s,n,i));return t}asValueMap(){const e=new Map;for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(t,i.value);return e}}var xc,Ic,_c,Oc,Dc,Ac={},Mc={},Nc={exports:{}};function Lc(){if(xc)return Nc.exports;xc=1;var e=Nc.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 null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{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 null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%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 null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %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+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{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 null!=e.attribute&&(t+=" %s",null!=e.value&&(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 null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%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:new 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:new 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"+(null!=e.clksrcExt?"=%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+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{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.reg=/(.*)/),e.format||(e.format="%s")})}),Nc.exports}function Uc(){return Ic||(Ic=1,function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var s=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:s&&!i[e.name]&&(i[e.name]={});var r=e.push?{}:s?i[e.name]:i;!function(e,i,n,s){if(s&&!n)i[s]=t(e[1]);else for(var r=0;r<n.length;r+=1)null!=e[r+1]&&(i[n[r]]=t(e[r+1]))}(n.match(e.reg),r,e.names,e.name),e.push&&i[e.push].push(r)},n=Lc(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},r=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(s).forEach(function(e){var t=e[0],s=e.slice(2);"m"===t&&(r.push({rtp:[],fmtp:[]}),o=r[r.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(s))return i(c,o,s)}}),t.media=r,t};var r=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(r,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),s=0;s<n.length;s+=3)i.push({component:n[s],ip:n[s+1],port:n[s+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(r,{})})},e.parseSimulcastStreamList=function(e){return e.split(";").map(function(e){return e.split(",").map(function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}})})}}(Mc)),Mc}function jc(){if(Oc)return _c;Oc=1;var e=Lc(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,s=n.length;return e.replace(t,function(e){if(i>=s)return e;var t=n[i];switch(i+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}})},n=function(e,t,n){var s=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var r=0;r<t.names.length;r+=1){var o=t.names[r];t.name?s.push(n[t.name][o]):s.push(n[t.names[r]])}else s.push(n[t.name]);return i.apply(null,s)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return _c=function(t,i){i=i||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach(function(e){null==e.payloads&&(e.payloads="")});var o=i.outerOrder||s,a=i.innerOrder||r,c=[];return o.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){c.push(n(i,e,t))})})}),t.media.forEach(function(t){c.push(n("m",e.m[0],t)),a.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){c.push(n(i,e,t))})})})}),c.join("\r\n")+"\r\n"}}var Fc=function(){if(Dc)return Ac;Dc=1;var e=Uc(),t=jc(),i=Lc();return Ac.grammar=i,Ac.write=t,Ac.parse=e.parse,Ac.parseParams=e.parseParams,Ac.parseFmtpConfig=e.parseFmtpConfig,Ac.parsePayloads=e.parsePayloads,Ac.parseRemoteCandidates=e.parseRemoteCandidates,Ac.parseImageAttributes=e.parseImageAttributes,Ac.parseSimulcastStreamList=e.parseSimulcastStreamList,Ac}();function Bc(e,t,i){var n,s,r;void 0===t&&(t=50),void 0===i&&(i={});var o=null!=(n=i.isImmediate)&&n,a=null!=(s=i.callback)&&s,c=i.maxWait,d=Date.now(),l=[];var u=function(){var i=[].slice.call(arguments),n=this;return new Promise(function(s,u){var h=o&&void 0===r;if(void 0!==r&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,d=Date.now(),!o){var t=e.apply(n,i);a&&a(t),l.forEach(function(e){return(0,e.resolve)(t)}),l=[]}},function(){if(void 0!==c){var e=Date.now()-d;if(e+t>=c)return c-e}return t}()),h){var p=e.apply(n,i);return a&&a(p),s(p)}l.push({resolve:s,reject:u})})};return u.cancel=function(e){void 0!==r&&clearTimeout(r),l.forEach(function(t){return(0,t.reject)(e)}),l=[]},u}const qc="negotiationStarted",Vc="negotiationComplete",zc="rtpVideoPayloadTypes";class Hc extends Ys.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.log=Bs,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Bc(e=>Ws(this,void 0,void 0,function*(){this.emit(qc);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}),20),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,this._pc=null)},this.log=qs(null!==(i=t.loggerName)&&void 0!==i?i:Us.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new qe}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return Ws(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 Ws(this,void 0,void 0,function*(){var i;if("answer"===e.type&&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("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;const i=[],n=[],s=Fc.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let r=0;return s.media.forEach(e=>{var t;const s=Gc(e.mid);"audio"===e.type&&(e.rtp.some(e=>"opus"===e.codec&&(r=e.payload,!0)),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some(e=>e.payload===r&&"nack"===e.type))&&n.push(s),e.fmtp.some(e=>e.payload===r&&(e.config.includes("sprop-stereo=1")&&i.push(s),!0)))}),{stereoMids:i,nackMids:n}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}else if("answer"===e.type){const t=Fc.parse(null!==(i=e.sdp)&&void 0!==i?i:"");t.media.forEach(e=>{const t=Gc(e.mid);"audio"===e.type&&this.trackBitrates.some(i=>{if(!i.transceiver||t!=i.transceiver.mid)return!1;let n=0;if(e.rtp.some(e=>e.codec.toUpperCase()===i.codec.toUpperCase()&&(n=e.payload,!0)),0===n)return!0;let s=!1;for(const t of e.fmtp)if(t.payload===n){t.config=t.config.split(";").filter(e=>!e.includes("maxaveragebitrate")).join(";"),i.maxbr>0&&(t.config+=";maxaveragebitrate=".concat(1e3*i.maxbr)),s=!0;break}return s||i.maxbr>0&&e.fmtp.push({payload:n,config:"maxaveragebitrate=".concat(1e3*i.maxbr)}),!0})}),n=Fc.write(t)}if(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();else if("answer"===e.type&&(this.emit(Vc),e.sdp)){Fc.parse(e.sdp).media.forEach(e=>{"video"===e.type&&this.emit(zc,e.rtp)})}return!0})}createAndSendOffer(e){return Ws(this,void 0,void 0,function*(){var t;const i=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);yield this._pc.setRemoteDescription(t)}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);const i=this.latestOfferId+1;this.latestOfferId=i;const n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));const s=Fc.parse(null!==(t=n.sdp)&&void 0!==t?t:"");if(s.media.forEach(e=>{Kc(e),"audio"===e.type?Wc(e,["all"],[]):"video"===e.type&&this.trackBitrates.some(t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0)),0===i)return!0;if(ma(t.codec)&&!ba()&&this.ensureVideoDDExtensionForSVC(e,s),!ma(t.codec))return!0;const n=Math.round(.7*t.maxbr);for(const s of e.fmtp)if(s.payload===i){s.config.includes("x-google-start-bitrate")||(s.config+=";x-google-start-bitrate=".concat(n));break}return!0})}),this.latestOfferId>i)return void this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:i}));yield this.setMungedSDP(n,Fc.write(s)),this.onOffer(n,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return Ws(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=Fc.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach(e=>{Kc(e),"audio"===e.type&&Wc(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Fc.write(i)),t})}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 xo("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new xo("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return Ws(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,n=new Map;if((yield this._pc.getStats()).forEach(e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),i.set(e.id,e);break;case"remote-candidate":n.set(e.id,"".concat(e.address,":").concat(e.port))}}),""===t)return;const s=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==s?n.get(s):void 0})}setMungedSDP(e,t,i){return Ws(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{return this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),void(i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(n){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:n,sdp:t})),e.sdp=s}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(n){let t="unknown error";n instanceof Error?t=n.message:"string"==typeof n&&(t=n);const s={error:t,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new Io(t)}})}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null===(i=e.ext)||void 0===i?void 0:i.some(e=>e.uri===la))){if(0===this.ddExtID){let e=0;t.media.forEach(t=>{var i;"video"===t.type&&(null===(i=t.ext)||void 0===i||i.forEach(t=>{t.value>e&&(e=t.value)}))}),this.ddExtID=e+1}null===(n=e.ext)||void 0===n||n.push({value:this.ddExtID,uri:la})}}}function Wc(e,t,i){const n=Gc(e.mid);let s=0;e.rtp.some(e=>"opus"===e.codec&&(s=e.payload,!0)),s>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(n)&&!e.rtcpFb.some(e=>e.payload===s&&"nack"===e.type)&&e.rtcpFb.push({payload:s,type:"nack"}),(t.includes(n)||1===t.length&&"all"===t[0])&&e.fmtp.some(e=>e.payload===s&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0)))}function Kc(e){if(e.connection){const t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}function Gc(e){return"number"==typeof e?e.toFixed(0):e}const Jc="vp8",Qc={audioPreset:qo.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Wo.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Jc,backupCodec:!0,preConnectBuffer:!1},Yc={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Xc={deviceId:{ideal:"default"},resolution:zo.h720.resolution},Zc={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(e){this._retryDelays=void 0!==e?[...e]:Hs}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}},disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!1},$c={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var ed,td;(td=ed||(ed={}))[td.NEW=0]="NEW",td[td.CONNECTING=1]="CONNECTING",td[td.CONNECTED=2]="CONNECTED",td[td.FAILED=3]="FAILED",td[td.CLOSING=4]="CLOSING",td[td.CLOSED=5]="CLOSED";class id{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var n;this.peerConnectionTimeout=$c.peerConnectionTimeout,this.log=Bs,this.updateState=()=>{var e,t;const i=this.state,n=this.requiredTransports.map(e=>e.getConnectionState());n.every(e=>"connected"===e)?this.state=ed.CONNECTED:n.some(e=>"failed"===e)?this.state=ed.FAILED:n.some(e=>"connecting"===e)?this.state=ed.CONNECTING:n.every(e=>"closed"===e)?this.state=ed.CLOSED:n.some(e=>"closed"===e)?this.state=ed.CLOSING:n.every(e=>"new"===e)&&(this.state=ed.NEW),i!==this.state&&(this.log.debug("pc state change: from ".concat(ed[i]," to ").concat(ed[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),null===(t=this.subscriber)||void 0===t?void 0:t.getConnectionState()))},this.log=qs(null!==(n=i.loggerName)&&void 0!==n?n:Us.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired="subscriber-primary"!==t,this.isSubscriberConnectionRequired="subscriber-primary"===t,this.publisher=new Hc(e,i),"publisher-only"!==t&&(this.subscriber=new Hc(e,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,xn.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||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;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,xn.PUBLISHER)},this.publisher.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var i;null===(i=this.onPublisherOffer)||void 0===i||i.call(this,e,t)},this.state=ed.NEW,this.connectionLock=new qe,this.remoteOfferLock=new qe}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isPublisherConnectionRequired=e,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 Ws(this,void 0,void 0,function*(){var e;if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const e=this.publisher;for(const i of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(i)}catch(t){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:t}))}}yield Promise.all([this.publisher.close(),null===(e=this.subscriber)||void 0===e?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return Ws(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return Ws(this,void 0,void 0,function*(){var i;t===xn.PUBLISHER?yield this.publisher.addIceCandidate(e):yield null===(i=this.subscriber)||void 0===i?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return Ws(this,void 0,void 0,function*(){var i,n,s;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:null===(i=this.subscriber)||void 0===i?void 0:i.getSignallingState().toString()}));const r=yield this.remoteOfferLock.lock();try{if(!(yield null===(n=this.subscriber)||void 0===n?void 0:n.setRemoteDescription(e,t)))return;return yield null===(s=this.subscriber)||void 0===s?void 0:s.createAndSetAnswer()}finally{r()}})}updateConfiguration(e,t){var i;this.publisher.setConfiguration(e),null===(i=this.subscriber)||void 0===i||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return Ws(this,void 0,void 0,function*(){var i;const n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null===(i=this.requiredTransports)||void 0===i?void 0:i.map(i=>this.ensureTransportConnected(i,e,t)))}finally{n()}})}negotiate(e){return Ws(this,void 0,void 0,function*(){return new Promise((t,i)=>Ws(this,void 0,void 0,function*(){const n=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout);e.signal.addEventListener("abort",()=>{clearTimeout(n),i("negotiation aborted")}),this.publisher.once(qc,()=>{e.signal.aborted||this.publisher.once(Vc,()=>{clearTimeout(n),t()})}),yield this.publisher.negotiate(e=>{clearTimeout(n),i(e)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const t=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(t=>t.receiver===e);return null==t?void 0:t.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===xn.PUBLISHER||e===xn.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return Ws(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise((e,s)=>Ws(i,void 0,void 0,function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),Mo.clearTimeout(r),s(wo.cancelled("room connection has been cancelled"))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);const r=Mo.setTimeout(()=>{null==t||t.signal.removeEventListener("abort",i),s(wo.internal("could not establish pc connection"))},n);for(;this.state!==ed.CONNECTED;)if(yield ua(50),null==t?void 0:t.signal.aborted)return void s(wo.cancelled("room connection has been cancelled"));Mo.clearTimeout(r),null==t||t.signal.removeEventListener("abort",i),e()}))}()})}}class nd{static fetchRegionSettings(e,t,i){return Ws(this,void 0,void 0,function*(){const n=yield nd.fetchLock.lock();try{const n=yield fetch("".concat(function(e){return"".concat(e.protocol.replace("ws","http"),"//").concat(e.host,"/settings")}(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(n.ok){const e=function(e){var t;const i=e.get("Cache-Control");if(i){const e=null===(t=i.match(/(?:^|[,\s])max-age=(\d+)/))||void 0===t?void 0:t[1];if(e)return parseInt(e,10)}}(n.headers),t=e?1e3*e:5e3;return{regionSettings:yield n.json(),updatedAtInMs:Date.now(),maxAgeInMs:t}}throw 401===n.status?wo.notAllowed("Could not fetch region settings: ".concat(n.statusText),n.status):wo.internal("Could not fetch region settings: ".concat(n.statusText))}catch(s){throw s instanceof wo?s:(null==i?void 0:i.aborted)?wo.cancelled("Region fetching was aborted"):wo.serverUnreachable("Could not fetch region settings, ".concat(s instanceof Error?"".concat(s.name,": ").concat(s.message):s))}finally{n()}})}static scheduleRefetch(e,t,i){return Ws(this,void 0,void 0,function*(){const n=nd.settingsTimeouts.get(e.hostname);clearTimeout(n),nd.settingsTimeouts.set(e.hostname,setTimeout(()=>Ws(this,void 0,void 0,function*(){try{const i=yield nd.fetchRegionSettings(e,t);nd.updateCachedRegionSettings(e,t,i)}catch(n){if(n instanceof wo&&n.reason===lo.NotAllowed)return void Bs.debug("token is not valid, cancelling auto region refresh");Bs.debug("auto refetching of region settings failed",{error:n}),nd.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){nd.cache.set(e.hostname,i),nd.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=nd.settingsTimeouts.get(e);t&&(clearTimeout(t),nd.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=nd.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const t=nd.connectionTrackers.get(e);t&&0===t.connectionCount&&(Bs.debug("stopping region refetch after disconnect delay",{hostname:e}),nd.stopRefetch(e)),t&&(t.cleanupTimeout=void 0)},3e4))}static cancelCleanup(e){const t=nd.connectionTrackers.get(e);(null==t?void 0:t.cleanupTimeout)&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=nd.connectionTrackers.get(e);t||(t={connectionCount:0},nd.connectionTrackers.set(e,t)),t.connectionCount++,nd.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=nd.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),0===t.connectionCount&&nd.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Sa(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return Ws(this,void 0,void 0,function*(){return nd.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return Ws(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=nd.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),nd.updateCachedRegionSettings(this.serverUrl,this.token,t));const i=t.regionSettings.regions.filter(e=>!this.attemptedRegions.find(t=>t.url===e.url));if(i.length>0){const e=i[0];return this.attemptedRegions.push(e),Bs.debug("next region: ".concat(e.region)),e.url}return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){nd.updateCachedRegionSettings(this.serverUrl,this.token,e)}}nd.cache=new Map,nd.settingsTimeouts=new Map,nd.connectionTrackers=new Map,nd.fetchLock=new qe;class sd extends Error{constructor(e,t,i){super(t),this.code=e,this.message=od(t,sd.MAX_MESSAGE_BYTES),this.data=i?od(i,sd.MAX_DATA_BYTES):void 0}static fromProto(e){return new sd(e.code,e.message,e.data)}toProto(){return new un({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new sd(sd.ErrorCode[e],sd.ErrorMessage[e],t)}}sd.MAX_MESSAGE_BYTES=256,sd.MAX_DATA_BYTES=15360,sd.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},sd.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"};function rd(e){return(new TextEncoder).encode(e).length}function od(e,t){if(rd(e)<=t)return e;let i=0,n=e.length;const s=new TextEncoder;for(;i<n;){const r=Math.floor((i+n+1)/2);s.encode(e.slice(0,r)).length<=t?i=r:n=r-1}return e.slice(0,i)}const ad=2e3;function cd(e,t){if(!t)return 0;let i,n;return"bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp?0:8*(i-n)*1e3/(e.timestamp-t.timestamp)}const dd="undefined"!=typeof MediaRecorder;const ld=dd?MediaRecorder:class{constructor(){throw new Error("MediaRecorder is not available in this environment")}};class ud extends ld{constructor(e,t){if(!dd)throw new Error("MediaRecorder is not available in this environment");let i,n;super(new MediaStream([e.mediaStreamTrack]),t);const s=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",r),null==n||n.close(),n=void 0},r=e=>{null==n||n.error(e),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",r),n=void 0};this.byteStream=new ReadableStream({start:e=>{n=e,i=t=>Ws(this,void 0,void 0,function*(){let i;if(t.data.arrayBuffer){const e=yield t.data.arrayBuffer();i=new Uint8Array(e)}else{if(!t.data.byteArray)throw new Error("no data available!");i=t.data.byteArray}void 0!==n&&e.enqueue(i)}),this.addEventListener("dataavailable",i)},cancel:()=>{s()}}),this.addEventListener("stop",s),this.addEventListener("error",r)}}class hd extends aa{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(e,t,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!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=Bc(()=>Ws(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>Ws(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(Co.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new qe,this.pauseUpstreamLock=new qe,this.trackChangeLock=new qe,this.trackChangeLock.lock().then(t=>Ws(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==aa.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return Ws(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!t)return;let n;if(this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{da(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()),this.processor&&e){if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(ca(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}this.sender&&"closed"!==(null===(i=this.sender.transport)||void 0===i?void 0:i.state)&&(yield this.sender.replaceTrack(null!=n?n:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{ca(null!=n?n:e,t)}))})}waitForDimensions(){return Ws(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(e.kind===aa.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(i=so())||void 0===i?void 0:i.os)&&(yield ua(10));const n=Date.now();for(;Date.now()-n<t;){const t=e.dimensions;if(t)return t;yield ua(50)}throw new Ro("unable to get track dimensions after timeout")}()})}setDeviceId(e){return Ws(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Fa(e)||(this._constraints.deviceId=e,!!this.isMuted||(yield this.restartTrack(),Fa(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return Ws(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===aa.Source.ScreenShare)return;const{deviceId:i,groupId:n}=e._mediaStreamTrack.getSettings(),s=e.kind===aa.Kind.Audio?"audioinput":"videoinput";return t?gc.getInstance().normalizeDeviceId(s,i,n):i}()})}mute(){return Ws(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return Ws(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return Ws(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Ro("unable to replace an unpublished track");let i,n;return"boolean"==typeof t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return Ws(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:t,facingMode:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(i[n[s]]=e[n[s]])}return i}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const s={audio:!1,video:!1};this.kind===aa.Kind.Video?s.video=!t&&!i||{deviceId:t,facingMode:i}:s.audio=!t||Object.assign({deviceId:t},n),this.attachedElements.forEach(e=>{da(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const r=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return this.kind===aa.Kind.Video&&(yield r.applyConstraints(n)),r.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(r),this._constraints=e,this.emit(Co.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),this.isMuted===e&&this._mediaStreamTrack.enabled!==e||(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Co.Muted:Co.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Ws(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),ka()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(this.log.debug("track needs to be reacquired, restarting ".concat(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),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return Ws(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to pause upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!0,this.emit(Co.UpstreamPaused,this);const t=so();if("Safari"===(null==t?void 0:t.name)&&xa(t.version,"12.0")<0)throw new Eo("pauseUpstream is not supported on Safari < 12.");"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return Ws(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to resume upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!1,this.emit(Co.UpstreamResumed,this),"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return Ws(this,void 0,void 0,function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;return yield this.sender.getStats()})}setProcessor(e){return Ws(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;const s=yield t.trackChangeLock.lock();try{t.log.debug("setting up processor",t.logContext);const s=document.createElement(t.kind),r={kind:t.kind,track:t._mediaStreamTrack,element:s,audioContext:t.audioContext};if(yield e.init(r),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.internalStopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(ca(t._mediaStreamTrack,s),s.muted=!0,s.play().catch(e=>{e instanceof DOMException&&"AbortError"===e.name?(t.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout(()=>{s.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=s,t.processor.processedTrack){for(const e of t.attachedElements)e!==t.processorElement&&i&&(da(t._mediaStreamTrack,e),ca(t.processor.processedTrack,e));yield null===(n=t.sender)||void 0===n?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit(Co.TrackProcessorUpdate,t.processor)}finally{s()}}()})}getProcessor(){return this.processor}stopProcessor(){return Ws(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}}()})}internalStopProcessor(){return Ws(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n;e.processor&&(e.log.debug("stopping processor",e.logContext),null===(i=e.processor.processedTrack)||void 0===i||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||(null===(n=e.processorElement)||void 0===n||n.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(Co.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(dd)if(this.localTrackRecorder)this.log.warn("preconnect buffer already started");else{{let e="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(e)||(e="video/mp4"),this.localTrackRecorder=new ud(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},1e4)}else this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.mimeType}}class pd extends hd{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,aa.Kind.Audio,t,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>Ws(this,void 0,void 0,function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(t){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:t}))}e&&this.prevStats&&(this._currentBitrate=cd(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(Co.AudioTrackFeatureUpdate,this,Ui.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(Co.AudioTrackFeatureUpdate,this,Ui.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Ws(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===aa.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(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return Ws(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Fa(this._constraints.deviceId);return this.source!==aa.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!t||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return Ws(this,void 0,void 0,function*(){let t;if(e){const i=Jo({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return Ws(this,void 0,void 0,function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){Ta()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},ad)))}setProcessor(e){return Ws(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!Ca()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),this.processor=e,this.processor.processedTrack&&(yield null===(t=this.sender)||void 0===t?void 0:t.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(Co.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return Ws(this,void 0,void 0,function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield this.sender.getStats()).forEach(e=>{"outbound-rtp"===e.type&&(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 Ws(this,void 0,void 0,function*(){const e=yield Qo(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(Co.AudioSilenceDetected)),e})}}const md=Object.values(zo),gd=Object.values(Ho),fd=Object.values(Wo),vd=[zo.h180,zo.h360],bd=[Ho.h180,Ho.h360],yd=["q","h","f"];function kd(e,t,i,n){var s,r;let o=null==n?void 0:n.videoEncoding;e&&(o=null==n?void 0:n.screenShareEncoding);const a=null==n?void 0:n.simulcast,c=null==n?void 0:n.scalabilityMode,d=null==n?void 0:n.videoCodec;if(!o&&!a&&!c||!t||!i)return[{}];o||(o=function(e,t,i,n){const s=function(e,t,i){if(e)return fd;const n=t>i?t/i:i/t;if(Math.abs(n-16/9)<Math.abs(n-4/3))return md;return gd}(e,t,i);let{encoding:r}=s[0];const o=Math.max(t,i);for(let a=0;a<s.length;a+=1){const e=s[a];if(r=e.encoding,e.width>=o)break}if(n)switch(n){case"av1":case"h265":r=Object.assign({},r),r.maxBitrate=.7*r.maxBitrate;break;case"vp9":r=Object.assign({},r),r.maxBitrate=.85*r.maxBitrate}return r}(e,t,i,d),Bs.debug("using video encoding",o));const l=o.maxFramerate,u=new No(t,i,o.maxBitrate,o.maxFramerate,o.priority);if(c&&ma(d)){const e=new wd(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const i=so();if(ya()||Ca()||"Chrome"===(null==i?void 0:i.name)&&xa(null==i?void 0:i.version,"113")<0){const n="h"==e.suffix?2:3,s=function(e){return e||(e=so()),"Safari"===(null==e?void 0:e.name)&&xa(e.version,"18.3")>0||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&xa(e.osVersion,"18.3")>0}(i);for(let i=0;i<e.spatial;i+=1)t.push({rid:yd[2-i],maxBitrate:o.maxBitrate/Math.pow(n,i),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:s?Math.pow(2,i):void 0});t[0].scalabilityMode=c}else t.push({maxBitrate:o.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),Bs.debug("using svc encoding",{encodings:t}),t}if(!a)return[o];let h,p=[];if(p=e?null!==(s=Sd(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:Td(e,u):null!==(r=Sd(null==n?void 0:n.videoSimulcastLayers))&&void 0!==r?r:Td(e,u),p.length>0){const e=p[0];p.length>1&&([,h]=p);const n=Math.max(t,i);if(n>=960&&h)return Cd(t,i,[e,h,u],l);if(n>=480)return Cd(t,i,[e,u],l)}return Cd(t,i,[u])}function Td(e,t){if(e)return[{scaleResolutionDownBy:2,fps:(i=t).encoding.maxFramerate}].map(e=>{var t,n;return new No(Math.floor(i.width/e.scaleResolutionDownBy),Math.floor(i.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!==(t=i.encoding.maxFramerate)&&void 0!==t?t:30)/(null!==(n=e.fps)&&void 0!==n?n:30))))),e.fps,i.encoding.priority)});var i;const{width:n,height:s}=t,r=n>s?n/s:s/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?vd:bd}function Cd(e,t,i,n){const s=[];if(i.forEach((i,r)=>{if(r>=yd.length)return;const o=Math.min(e,t),a={rid:yd[r],scaleResolutionDownBy:Math.max(1,o/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},c=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;c&&(a.maxFramerate=c);const d=fa()||0===r;i.encoding.priority&&d&&(a.priority=i.encoding.priority,a.networkPriority=i.encoding.priority),s.push(a)}),Ca()&&"ios"===Ra()){let e;s.forEach(t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate});let t=!0;s.forEach(i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,Bs.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Bs.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)})}return s}function Sd(e){if(e)return e.sort((e,t)=>{const{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitrate<n.maxBitrate?-1:i.maxBitrate===n.maxBitrate&&i.maxFramerate&&n.maxFramerate?i.maxFramerate>n.maxFramerate?1:-1:0})}class wd{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new 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(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!==(e=this.suffix)&&void 0!==e?e:"")}}class Ed extends hd{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0;super(e,aa.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>Ws(this,void 0,void 0,function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(n){return void this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:n}))}const t=new Map(e.map(e=>[e.rid,e])),i=e.some(e=>"cpu"===e.qualityLimitationReason);if(i!==this.isCpuConstrained&&(this.isCpuConstrained=i,this.isCpuConstrained&&this.emit(Co.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,i)=>{var n;const s=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=cd(t,s)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new qe}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Ta())return;const i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},ad))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return Ws(this,void 0,void 0,function*(){var t,i,n,s,r;yield e.pauseUpstream.call(this);try{for(var o,a=!0,c=Gs(this.simulcastCodecs.values());!(t=(o=yield c.next()).done);a=!0){s=o.value,a=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(null)}}catch(d){i={error:d}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return Ws(this,void 0,void 0,function*(){var t,i,n,s,r;yield e.resumeUpstream.call(this);try{for(var o,a=!0,c=Gs(this.simulcastCodecs.values());!(t=(o=yield c.next()).done);a=!0){s=o.value,a=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(e.mediaStreamTrack)}}catch(d){i={error:d}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Ws(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source!==aa.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return Ws(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==aa.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return Ws(this,void 0,void 0,function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(e=>{var n;if("outbound-rtp"===e.type){const s={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,framesSent:e.framesSent,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,rid:null!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},r=i.get(e.remoteId);r&&(s.jitter=r.jitter,s.packetsLost=r.packetsLost,s.roundTripTime=r.roundTripTime),t.push(s)}}),t.sort((e,t)=>{var i,n;return(null!==(i=t.frameWidth)&&void 0!==i?i:0)-(null!==(n=e.frameWidth)&&void 0!==n?n:0)}),t})}setPublishingQuality(e){const t=[];for(let i=ra.LOW;i<=ra.HIGH;i+=1)t.push(new ss({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(ma(this.codec),t)}restartTrack(e){return Ws(this,void 0,void 0,function*(){var t,i,n,s,r;let o;if(e){const t=Jo({video:e});"boolean"!=typeof t.video&&(o=t.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var a,c=!0,d=Gs(this.simulcastCodecs.values());!(t=(a=yield d.next()).done);c=!0){s=a.value,c=!1;const e=s;e.sender&&"closed"!==(null===(r=e.sender.transport)||void 0===r?void 0:r.state)&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(l){i={error:l}}finally{try{c||t||!(n=d.return)||(yield n.call(d))}finally{if(i)throw i.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return Ws(this,arguments,void 0,function(e){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s,r,o,a,c,d;if(yield t.setProcessor.call(i,e,n),null===(c=i.processor)||void 0===c?void 0:c.processedTrack)try{for(var l,u=!0,h=Gs(i.simulcastCodecs.values());!(s=(l=yield h.next()).done);u=!0){a=l.value,u=!1;const e=a;yield null===(d=e.sender)||void 0===d?void 0:d.replaceTrack(i.processor.processedTrack)}}catch(p){r={error:p}}finally{try{u||s||!(o=h.return)||(yield o.call(h))}finally{if(r)throw r.error}}}()})}setDegradationPreference(e){return Ws(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},5e3))}setPublishingCodecs(e){return Ws(this,void 0,void 0,function*(){var t,i,n,s,r,o,a;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(ma(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,i=Gs(e);!(s=(n=yield i.next()).done);t=!0){a=n.value,t=!1;const e=a;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(this.log.debug("try setPublishingCodec for ".concat(e.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),t&&t.sender)t.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(e.codec),this.logContext),yield Rd(t.sender,t.encodings,e.qualities,this.senderLock,ma(e.codec),this.log,this.logContext));else for(const i of e.qualities)if(i.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(ma(e.codec),e.qualities)}}catch(d){r={error:d}}finally{try{t||s||!(o=i.return)||(yield o.call(i))}finally{if(r)throw r.error}}return c})}setPublishingLayers(e,t){return Ws(this,void 0,void 0,function*(){this.optimizeForPerformance?this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t})):(this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),this.sender&&this.encodings&&(yield Rd(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))})}prioritizePerformance(){return Ws(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const e=this.sender.getParameters();e.encodings=e.encodings.map((e,t)=>{var i;return Object.assign(Object.assign({},e),{active:0===t,scaleResolutionDownBy:Math.max(1,Math.ceil((null!==(i=this.mediaStreamTrack.getSettings().height)&&void 0!==i?i:360)/360)),scalabilityMode:0===t&&ma(this.codec)?"L1T3":void 0,maxFramerate:0===t?15:0,maxBitrate:0===t?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(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Ws(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),ka()&&this.isInBackground&&this.source===aa.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Rd(e,t,i,n,s,r,o){return Ws(this,void 0,void 0,function*(){const a=yield n.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:e,qualities:i,senderEncodings:t}));try{const n=e.getParameters(),{encodings:a}=n;if(!a)return;if(a.length!==t.length)return void r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:a,senderEncodings:t}));let c=!1;if(!1&&a[0].scalabilityMode);else{if(s){i.some(e=>e.enabled)&&i.forEach(e=>e.enabled=!0)}a.forEach((e,n)=>{var s;let a=null!==(s=e.rid)&&void 0!==s?s:"";""===a&&(a="q");const d=Pd(a),l=i.find(e=>e.quality===d);l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,r.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),o),fa()&&(l.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))})}c&&(n.encodings=a,r.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:n.encodings})),yield e.setParameters(n))}finally{a()}})}function Pd(e){switch(e){case"f":default:return ra.HIGH;case"h":return ra.MEDIUM;case"q":return ra.LOW}}function xd(e,t,i,n){if(!i)return[new Ji({quality:ra.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){const n=i[0].scalabilityMode,s=new wd(n),r=[],o="h"==s.suffix?1.5:2,a="h"==s.suffix?2:3;for(let c=0;c<s.spatial;c+=1)r.push(new Ji({quality:Math.min(ra.HIGH,s.spatial-1)-c,width:Math.ceil(e/Math.pow(o,c)),height:Math.ceil(t/Math.pow(o,c)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(a,c)):0,ssrc:0}));return r}return i.map(i=>{var n,s,r;const o=null!==(n=i.scaleResolutionDownBy)&&void 0!==n?n:1;let a=Pd(null!==(s=i.rid)&&void 0!==s?s:"");return new Ji({quality:a,width:Math.ceil(e/o),height:Math.ceil(t/o),bitrate:null!==(r=i.maxBitrate)&&void 0!==r?r:0,ssrc:0})})}const Id="_lossy",_d="_reliable",Od="leave-reconnect";var Dd,Ad;(Ad=Dd||(Dd={}))[Ad.New=0]="New",Ad[Ad.Connected=1]="Connected",Ad[Ad.Disconnected=2]="Disconnected",Ad[Ad.Reconnecting=3]="Reconnecting",Ad[Ad.Closed=4]="Closed";class Md extends Ys.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=$c.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Dd.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=Bs,this.reliableDataSequence=1,this.reliableMessageBuffer=new Rc,this.reliableReceivedState=new Pc(3e4),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>Ws(this,[e],void 0,function(e){var t=this;let{channel:i}=e;return function*(){if(i){if(i.label===_d)t.reliableDCSub=i;else{if(i.label!==Id)return;t.lossyDCSub=i}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label),t.logContext),i.onmessage=t.handleDataMessage}}()}),this.handleDataMessage=e=>Ws(this,void 0,void 0,function*(){var t,i,n,s,r;const o=yield this.dataProcessLock.lock();try{let o;if(e.data instanceof ArrayBuffer)o=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:e.data}));o=yield e.data.arrayBuffer()}const a=Yi.fromBinary(new Uint8Array(o));if(a.sequence>0&&""!==a.participantSid){const e=this.reliableReceivedState.get(a.participantSid);if(e&&a.sequence<=e)return;this.reliableReceivedState.set(a.participantSid,a.sequence)}if("speaker"===(null===(t=a.value)||void 0===t?void 0:t.case))this.emit(ko.ActiveSpeakersUpdate,a.value.value.speakers);else if("encryptedPacket"===(null===(i=a.value)||void 0===i?void 0:i.case)){if(!this.e2eeManager)return void this.log.error("Received encrypted packet but E2EE not set up",this.logContext);const e=yield null===(n=this.e2eeManager)||void 0===n?void 0:n.handleEncryptedData(a.value.value.encryptedValue,a.value.value.iv,a.participantIdentity,a.value.value.keyIndex),t=$i.fromBinary(e.payload),i=new Yi({value:t.value,participantIdentity:a.participantIdentity,participantSid:a.participantSid});"user"===(null===(s=i.value)||void 0===s?void 0:s.case)&&Nd(i,i.value.value),this.emit(ko.DataPacketReceived,i,a.value.value.encryptionType)}else"user"===(null===(r=a.value)||void 0===r?void 0:r.case)&&Nd(a,a.value.value),this.emit(ko.DataPacketReceived,a,Wi.NONE)}finally{o()}}),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:i}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:i}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{const t=0===e.currentTarget.maxRetransmits?Xi.LOSSY:Xi.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const i=e=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up"),this.logContext),this.emit(ko.Disconnected),this.close()},n=Date.now()-this.reconnectStart;let s=this.getNextRetryDelay({elapsedMs:n,retryCount:this.reconnectAttempts});null!==s?(e===Od&&(s=0),this.log.debug("reconnecting in ".concat(s,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Mo.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),s)):i(n)},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===Dd.Connected&&e();const i=()=>{this.off(ko.Disconnected,n),e()},n=()=>{this.off(ko.Restarted,i),t()};this.once(ko.Restarted,i),this.once(ko.Disconnected,n)}),this.updateAndEmitDCBufferStatus=e=>{if(e===Xi.RELIABLE){const t=this.dataChannelForKind(e);t&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount)}const t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(ko.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>Ws(this,void 0,void 0,function*(){if(!this.url)return;(yield fetch(Ba(this.url),{method:"HEAD"}).then(e=>e.ok).catch(()=>!1))&&(this.log.info("detected network reconnected"),(this.client.currentState===Tc.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Tc.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Ni.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>Ws(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Ba(this.url),{method:"HEAD"}),ua(4e3).then(()=>Promise.reject())])}catch(e){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=qs(null!==(t=e.loggerName)&&void 0!==t?t:Us.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Sc(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new qe,this.dataProcessLock=new qe,this.dcBufferStatus=new Map([[Xi.LOSSY,!0],[Xi.RELIABLE,!0]]),this.client.onParticipantUpdate=e=>this.emit(ko.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(ko.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(ko.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(ko.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(ko.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(ko.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(ko.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(ko.SignalRequestResponse,e)}get logContext(){var e,t,i,n,s,r;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(n=null===(i=this.latestJoinResponse)||void 0===i?void 0:i.room)||void 0===n?void 0:n.sid,participant:null===(r=null===(s=this.latestJoinResponse)||void 0===s?void 0:s.participant)||void 0===r?void 0:r.identity,pID:this.participantSid}}join(e,t,i,n){return Ws(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,t,i,n);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),this.subscriberPrimary&&!s.fastPublish||this.negotiate().catch(e=>{Bs.error(e,this.logContext)}),this.registerOnLineListener(),this.clientConfiguration=s.clientConfiguration,this.emit(ko.SignalConnected,s),s}catch(s){if(s instanceof wo&&s.reason===lo.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,i,n);throw s}})}close(){return Ws(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed)e();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(ko.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return Ws(this,void 0,void 0,function*(){var e;yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;const t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new Rc,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return Ws(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Ro("a track with the same ID has already been published");return new Promise((t,i)=>{const n=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(wo.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return Ws(this,void 0,void 0,function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return Ws(this,void 0,void 0,function*(){var t,i;if(this.pcManager&&this.pcManager.currentState!==ed.NEW)return;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid;const n=this.makeRTCConfiguration(e);var s;this.pcManager=new id(n,this.options.singlePeerConnection?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(ko.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=(t,i,n)=>Ws(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(t),this.logContext),["closed","disconnected","failed"].includes(i)&&(this.publisherConnectionPromise=void 0),t===ed.CONNECTED){const t=this.pcState===Dd.New;this.pcState=Dd.Connected,t&&this.emit(ko.Connected,e)}else t===ed.FAILED&&(this.pcState!==Dd.Connected&&this.pcState!==Dd.Reconnecting||(this.pcState=Dd.Disconnected,this.handleDisconnect("peerconnection failed","failed"===n?Ni.RR_SUBSCRIBER_FAILED:Ni.RR_PUBLISHER_FAILED)));const s=this.client.isDisconnected||this.client.currentState===Tc.RECONNECTING,r=[ed.FAILED,ed.CLOSING,ed.CLOSED].includes(t);s&&r&&!this._isClosed&&this.emit(ko.Offline)}),this.pcManager.onTrack=e=>{0!==e.streams.length&&this.emit(ko.MediaTrackAdded,e.track,e.streams[0],e.receiver)},void 0!==(s=null===(i=e.serverInfo)||void 0===i?void 0:i.protocol)&&s>13||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>Ws(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:i})),this.midToTrackId=i,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,i)=>Ws(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;const n=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);n&&this.client.sendAnswer(n,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null===(t=e.track)||void 0===t?void 0:t.sid})),!this.pendingTrackResolvers[e.cid])return void this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(ko.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(ko.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,null===(t=this.regionUrlProvider)||void 0===t||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(ko.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(ko.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(ko.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var t,i;const n={direction:"recvonly"};for(let s=0;s<e.numAudios;s++)null===(t=this.pcManager)||void 0===t||t.addPublisherTransceiverOfKind("audio",n);for(let s=0;s<e.numVideos;s++)null===(i=this.pcManager)||void 0===i||i.addPublisherTransceiverOfKind("video",n);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",Ni.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==e?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:5e3,regionSettings:e.regions})),e.action){case Jn.DISCONNECT:this.emit(ko.Disconnected,null==e?void 0:e.reason),this.close();break;case Jn.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Od);break;case Jn.RESUME:this.handleDisconnect(Od)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const t=[];e.iceServers.forEach(e=>{const i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)}),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ai.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",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.lossyDC=this.pcManager.createPublisherDataChannel(Id,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(_d,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow,this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(Xi.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,8192),262144)}},1e3))}createSender(e,t,i){return Ws(this,void 0,void 0,function*(){if(ha()){return yield this.createTransceiverRTCRtpSender(e,t,i)}if(pa()){this.log.warn("using add-track fallback",this.logContext);return yield this.createRTCRtpSender(e.mediaStreamTrack)}throw new xo("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,n){return Ws(this,void 0,void 0,function*(){if(ha())return this.createSimulcastTransceiverSender(e,t,i,n);if(pa())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new xo("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return Ws(this,void 0,void 0,function*(){if(!this.pcManager)throw new xo("publisher is closed");const n=[];e.mediaStream&&n.push(e.mediaStream),Ka(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:n};i&&(s.sendEncodings=i);return(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,t,i,n){return Ws(this,void 0,void 0,function*(){if(!this.pcManager)throw new xo("publisher is closed");const s={direction:"sendonly"};n&&(s.sendEncodings=n);const r=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,r.sender),r.sender})}createRTCRtpSender(e){return Ws(this,void 0,void 0,function*(){if(!this.pcManager)throw new xo("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return Ws(this,void 0,void 0,function*(){var t,i,n;if(!this._isClosed)if(this.attemptingReconnect)Bs.warn("already attempting reconnect, returning early",this.logContext);else{(null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)!==Ai.DISABLED&&(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==n?n:ed.NEW)!==ed.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let e=!0;s instanceof xo?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),e=!1):s instanceof Ao||(this.fullReconnectOnNext=!0),e?this.handleDisconnect("reconnect",Ni.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(ko.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return Ws(this,void 0,void 0,function*(){var t,i,n;try{if(!this.url||!this.token)throw new xo("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(ko.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Ao;i=yield this.join(null!=e?e:this.url,this.token,this.signalOpts)}catch(s){if(s instanceof wo&&s.reason===lo.NotAllowed)throw new xo("could not reconnect, token might be expired");throw new Ao}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(ko.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==Tc.CONNECTED)throw new Ao("Signal connection got severed during reconnect");null===(t=this.regionUrlProvider)||void 0===t||t.resetAttempts(),this.emit(ko.Restarted)}catch(r){const e=yield null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getNextBestRegionUrl();if(e)return void(yield this.restartConnection(e));throw null===(n=this.regionUrlProvider)||void 0===n||n.resetAttempts(),r}})}resumeConnection(e){return Ws(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new xo("could not reconnect, url or token not saved");if(!this.pcManager)throw new xo("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(ko.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(n){let e="";if(n instanceof Error&&(e=n.message,this.log.error(n.message,Object.assign(Object.assign({},this.logContext),{error:n}))),n instanceof wo&&n.reason===lo.NotAllowed)throw new xo("could not reconnect, token might be expired");if(n instanceof wo&&n.reason===lo.LeaveRequest)throw n;throw new Ao(e)}if(this.emit(ko.SignalResumed),i){const e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Tc.CONNECTED)throw new Ao("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(t=this.reliableDC)||void 0===t?void 0:t.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),(null==i?void 0:i.lastMessageSeq)&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(ko.Resumed)})}waitForPCInitialConnection(e,t){return Ws(this,void 0,void 0,function*(){if(!this.pcManager)throw new xo("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return Ws(this,void 0,void 0,function*(){this.pcState=Dd.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield ua(2e3),!this.pcManager)throw new xo("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Dd.Connected}catch(e){throw this.pcState=Dd.Disconnected,wo.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,i,n){return Ws(this,void 0,void 0,function*(){const s=new Yi({destinationIdentities:[e],kind:Xi.RELIABLE,value:{case:"rpcResponse",value:new ln({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(s,Xi.RELIABLE)})}publishRpcAck(e,t){return Ws(this,void 0,void 0,function*(){const i=new Yi({destinationIdentities:[e],kind:Xi.RELIABLE,value:{case:"rpcAck",value:new dn({requestId:t})}});yield this.sendDataPacket(i,Xi.RELIABLE)})}sendDataPacket(e,t){return Ws(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const t=function(e){var t,i,n,s,r;if("sipDtmf"!==(null===(t=e.value)||void 0===t?void 0:t.case)&&"metrics"!==(null===(i=e.value)||void 0===i?void 0:i.case)&&"speaker"!==(null===(n=e.value)||void 0===n?void 0:n.case)&&"transcription"!==(null===(s=e.value)||void 0===s?void 0:s.case)&&"encryptedPacket"!==(null===(r=e.value)||void 0===r?void 0:r.case))return new $i({value:e.value})}(e);if(t){const i=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:"encryptedPacket",value:new Zi({encryptedValue:i.payload,iv:i.iv,keyIndex:i.keyIndex})}}}t===Xi.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),n=this.dataChannelForKind(t);if(n){if(t===Xi.RELIABLE)yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:i,sequence:e.sequence});else{if(!this.isBufferStatusLow(t))return this.lossyDataDropCount+=1,void(this.lossyDataDropCount%100==0&&this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount),this.logContext));this.lossyDataStatCurrentBytes+=i.byteLength}if(this.attemptingReconnect)return;n.send(i)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return Ws(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(Xi.RELIABLE);const t=this.dataChannelForKind(Xi.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(e=>{t.send(e.data)})),this.updateAndEmitDCBufferStatus(Xi.RELIABLE)})}waitForBufferStatusLow(e){return new Promise((t,i)=>Ws(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const n=()=>i("Engine closed");for(this.once(ko.Closing,n);!this.dcBufferStatus.get(e);)yield ua(10);this.off(ko.Closing,n),t()}}))}ensureDataTransportConnected(e){return Ws(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var n;if(!t.pcManager)throw new xo("PC manager is closed");const s=i?t.pcManager.subscriber:t.pcManager.publisher,r=i?"Subscriber":"Publisher";if(!s)throw wo.internal("".concat(r," connection not set"));let o=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),o=!0),o||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(o=!0),o&&t.negotiate().catch(e=>{Bs.error(e,t.logContext)});const a=t.dataChannelForKind(e,i);if("open"===(null==a?void 0:a.readyState))return;const c=(new Date).getTime()+t.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(s.isICEConnected&&"open"===(null===(n=t.dataChannelForKind(e,i))||void 0===n?void 0:n.readyState))return;yield ua(50)}throw wo.internal("could not establish ".concat(r," connection, state: ").concat(s.getICEConnectionState()))}()})}ensurePublisherConnected(e){return Ws(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!!this.pcManager&&(this.pcManager.currentState===ed.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED))}negotiate(){return Ws(this,void 0,void 0,function*(){return new Promise((e,t)=>Ws(this,void 0,void 0,function*(){if(!this.pcManager)return void t(new Io("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();const i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(ko.Closing,n),this.pcManager.publisher.once(zc,e=>{const t=new Map;e.forEach(e=>{const i=e.codec.toLowerCase();var n;n=i,Uo.includes(n)&&t.set(e.payload,i)}),this.emit(ko.RTPVideoMapUpdate,t)});try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof Io&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Ni.RR_UNKNOWN),t(s)}finally{this.off(ko.Closing,n)}}))})}dataChannelForKind(e,t){if(t){if(e===Xi.LOSSY)return this.lossyDCSub;if(e===Xi.RELIABLE)return this.reliableDCSub}else{if(e===Xi.LOSSY)return this.lossyDC;if(e===Xi.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,n,s,r;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);const o=this.pcManager.publisher.getLocalDescription(),a=this.pcManager.publisher.getRemoteDescription(),c=null===(i=this.pcManager.subscriber)||void 0===i?void 0:i.getRemoteDescription(),d=null===(n=this.pcManager.subscriber)||void 0===n?void 0:n.getLocalDescription(),l=null===(r=null===(s=this.signalOpts)||void 0===s?void 0:s.autoSubscribe)||void 0===r||r,u=new Array,h=new Array;e.forEach(e=>{e.isDesired!==l&&u.push(e.trackSid),e.isEnabled||h.push(e.trackSid)}),this.client.sendSyncState(new hs({answer:this.options.singlePeerConnection?a?Ec({sdp:a.sdp,type:a.type}):void 0:d?Ec({sdp:d.sdp,type:d.type}):void 0,offer:this.options.singlePeerConnection?o?Ec({sdp:o.sdp,type:o.type}):void 0:c?Ec({sdp:c.sdp,type:c.type}):void 0,subscription:new zn({trackSids:u,subscribe:!l,participantTracks:[]}),publishTracks:ea(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:h,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new ps({publisherSid:t,lastSeq:e}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(t,i)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new ms({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(Xi.LOSSY),xn.PUBLISHER),t(this.dataChannelForKind(Xi.RELIABLE),xn.PUBLISHER),t(this.dataChannelForKind(Xi.LOSSY,!0),xn.SUBSCRIBER),t(this.dataChannelForKind(Xi.RELIABLE,!0),xn.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Mo.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Ta()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){Ta()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const i=null===(t=this.pcManager)||void 0===t?void 0:t.getMidForReceiver(e);if(i){const e=Object.entries(this.midToTrackId).find(e=>{let[t]=e;return t===i});if(e)return e[1]}}}function Nd(e,t){const i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;const n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}class Ld{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if("number"==typeof this.totalByteSize&&0!==this.totalByteSize){if(e&&this.bytesReceived<this.totalByteSize)throw new Do("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),ho.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Do("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),ho.LengthExceeded)}}constructor(e,t,i,n){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=n}}class Ud extends Ld{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();let t=new ja,i=null,n=null;if(this.signal){const e=this.signal;n=()=>{var i;null===(i=t.reject)||void 0===i||i.call(t,e.reason)},e.addEventListener("abort",n),i=e}const s=()=>{e.releaseLock(),i&&n&&i.removeEventListener("abort",n),this.signal=void 0};return{next:()=>Ws(this,void 0,void 0,function*(){var i,n;try{const{done:s,value:r}=yield Promise.race([e.read(),t.promise,null!==(n=null===(i=this.outOfBandFailureRejectingFuture)||void 0===i?void 0:i.promise)&&void 0!==n?n:new Promise(()=>{})]);return s?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(r),{done:!1,value:r.content})}catch(bl){throw s(),bl}}),return(){return Ws(this,void 0,void 0,function*(){return s(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Ws(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,s,r;let o=new Set;const a=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=Gs(a);!(i=(c=yield l.next()).done);d=!0){r=c.value,d=!1;const e=r;o.add(e)}}catch(u){n={error:u}}finally{try{d||i||!(s=l.return)||(yield s.call(l))}finally{if(n)throw n.error}}return Array.from(o)}()})}}class jd extends Ld{constructor(e,t,i,n){super(e,t,i,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Va(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0});let i=new ja,n=null,s=null;if(this.signal){const e=this.signal;s=()=>{var t;null===(t=i.reject)||void 0===t||t.call(i,e.reason)},e.addEventListener("abort",s),n=e}const r=()=>{e.releaseLock(),n&&s&&n.removeEventListener("abort",s),this.signal=void 0};return{next:()=>Ws(this,void 0,void 0,function*(){var n,s;try{const{done:r,value:o}=yield Promise.race([e.read(),i.promise,null!==(s=null===(n=this.outOfBandFailureRejectingFuture)||void 0===n?void 0:n.promise)&&void 0!==s?s:new Promise(()=>{})]);if(r)return this.validateBytesReceived(!0),{done:!0,value:void 0};{let e;this.handleChunkReceived(o);try{e=t.decode(o.content)}catch(bl){throw new Do("Cannot decode datastream chunk ".concat(o.chunkIndex," as text: ").concat(bl),ho.DecodeFailed)}return{done:!1,value:e}}}catch(bl){throw r(),bl}}),return(){return Ws(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Ws(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,s,r;let o="";const a=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=Gs(a);!(i=(c=yield l.next()).done);d=!0){r=c.value,d=!1;o+=r}}catch(u){n={error:u}}finally{try{d||i||!(s=l.return)||(yield s.call(l))}finally{if(n)throw n.error}}return o}()})}}class Fd{constructor(){this.log=Bs,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 Do('A text stream handler for topic "'.concat(e,'" has already been set.'),ho.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Do('A byte stream handler for topic "'.concat(e,'" has already been set.'),ho.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,i,n,s;const r=Array.from(this.textStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e),o=Array.from(this.byteStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e);if(r.length>0||o.length>0){const a=new Do("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),ho.AbnormalEnd);for(const[e,n]of o)null===(i=(t=n.outOfBandFailureRejectingFuture).reject)||void 0===i||i.call(t,a),this.byteStreamControllers.delete(e);for(const[e,t]of r)null===(s=(n=t.outOfBandFailureRejectingFuture).reject)||void 0===s||s.call(n,a),this.textStreamControllers.delete(e)}}handleDataStreamPacket(e,t){return Ws(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 new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t,i){return Ws(this,void 0,void 0,function*(){var n;if("byteHeader"===e.contentHeader.case){const s=this.byteStreamHandlers.get(e.topic);if(!s)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);let r;const o=new ja;o.promise.catch(e=>{this.log.error(e)});const a={id:e.streamId,name:null!==(n=e.contentHeader.value.name)&&void 0!==n?n:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Va(e.timestamp),attributes:e.attributes,encryptionType:i},c=new ReadableStream({start:i=>{if(r=i,this.textStreamControllers.has(e.streamId))throw new Do("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),ho.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:r,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:o})}});s(new Ud(a,c,Va(e.totalLength),o),{identity:t})}else if("textHeader"===e.contentHeader.case){const n=this.textStreamHandlers.get(e.topic);if(!n)return void this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);let s;const r=new ja;r.promise.catch(e=>{this.log.error(e)});const o={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:i},a=new ReadableStream({start:i=>{if(s=i,this.textStreamControllers.has(e.streamId))throw new Do("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),ho.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:o,controller:s,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:r})}});n(new jd(o,a,Va(e.totalLength),r),{identity:t})}})}handleStreamChunk(e,t){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new Do("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),ho.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new Do("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),ho.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&n.controller.enqueue(e))}handleStreamTrailer(e,t){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new Do("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),ho.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new Do("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),ho.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class Bd{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return Ws(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null===(e=this.onClose)||void 0===e||e.call(this)})}}class qd extends Bd{}class Vd extends Bd{}class zd{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return Ws(this,void 0,void 0,function*(){var i;const n=crypto.randomUUID(),s=(new TextEncoder).encode(e).byteLength,r=null===(i=null==t?void 0:t.attachments)||void 0===i?void 0:i.map(()=>crypto.randomUUID()),o=new Array(r?r.length+1:1).fill(0),a=(e,i)=>{var n;o[i]=e;const s=o.reduce((e,t)=>e+t,0);null===(n=null==t?void 0:t.onProgress)||void 0===n||n.call(t,s)},c=yield this.streamText({streamId:n,totalSize:s,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:r,attributes:null==t?void 0:t.attributes});return yield c.write(e),a(1,0),yield c.close(),(null==t?void 0:t.attachments)&&r&&(yield Promise.all(t.attachments.map((e,i)=>Ws(this,void 0,void 0,function*(){return this._sendFile(r[i],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{a(e,i+1)}})})))),c.info})}streamText(e){return Ws(this,void 0,void 0,function*(){var t,i,n;const s=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),r={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==e?void 0:e.topic)&&void 0!==i?i:"",size:null==e?void 0:e.totalSize,attributes:null==e?void 0:e.attributes,encryptionType:(null===(n=this.engine.e2eeManager)||void 0===n?void 0:n.isDataChannelEncryptionEnabled)?Wi.GCM:Wi.NONE},o=new wn({streamId:s,mimeType:r.mimeType,topic:r.topic,timestamp:za(r.timestamp),totalLength:za(null==e?void 0:e.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new Cn({version:null==e?void 0:e.version,attachedStreamIds:null==e?void 0:e.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:"update"===(null==e?void 0:e.type)?Tn.UPDATE:Tn.CREATE})}}),a=null==e?void 0:e.destinationIdentities,c=new Yi({destinationIdentities:a,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,Xi.RELIABLE);let d=0;const l=this.engine,u=new WritableStream({write(e){return Ws(this,void 0,void 0,function*(){for(const t of function(e,t){const i=[];let n=(new TextEncoder).encode(e);for(;n.length>t;){let e=t;for(;e>0;){const t=n[e];if(void 0!==t&&128!=(192&t))break;e--}i.push(n.slice(0,e)),n=n.slice(e)}return n.length>0&&i.push(n),i}(e,15e3)){const e=new En({content:t,streamId:s,chunkIndex:za(d)}),i=new Yi({destinationIdentities:a,value:{case:"streamChunk",value:e}});yield l.sendDataPacket(i,Xi.RELIABLE),d+=1}})},close(){return Ws(this,void 0,void 0,function*(){const e=new Rn({streamId:s}),t=new Yi({destinationIdentities:a,value:{case:"streamTrailer",value:e}});yield l.sendDataPacket(t,Xi.RELIABLE)})},abort(e){console.log("Sink error:",e)}});let h=()=>Ws(this,void 0,void 0,function*(){yield p.close()});l.once(ko.Closing,h);const p=new qd(u,r,()=>this.engine.off(ko.Closing,h));return p})}sendFile(e,t){return Ws(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return Ws(this,void 0,void 0,function*(){var n;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(n=null==i?void 0:i.mimeType)&&void 0!==n?n:t.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),r=t.stream().getReader();for(;;){const{done:e,value:t}=yield r.read();if(e)break;yield s.write(t)}return yield s.close(),s.info})}streamBytes(e){return Ws(this,void 0,void 0,function*(){var t,i,n,s,r,o;const a=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),c=null==e?void 0:e.destinationIdentities,d={id:a,mimeType:null!==(i=null==e?void 0:e.mimeType)&&void 0!==i?i:"application/octet-stream",topic:null!==(n=null==e?void 0:e.topic)&&void 0!==n?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!==(s=null==e?void 0:e.name)&&void 0!==s?s:"unknown",encryptionType:(null===(r=this.engine.e2eeManager)||void 0===r?void 0:r.isDataChannelEncryptionEnabled)?Wi.GCM:Wi.NONE},l=new wn({totalLength:za(null!==(o=d.size)&&void 0!==o?o:0),mimeType:d.mimeType,streamId:a,topic:d.topic,timestamp:za(Date.now()),attributes:d.attributes,contentHeader:{case:"byteHeader",value:new Sn({name:d.name})}}),u=new Yi({destinationIdentities:c,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(u,Xi.RELIABLE);let h=0;const p=new qe,m=this.engine,g=this.log,f=new WritableStream({write(e){return Ws(this,void 0,void 0,function*(){const t=yield p.lock();let i=0;try{for(;i<e.byteLength;){const t=e.slice(i,i+15e3),n=new Yi({destinationIdentities:c,value:{case:"streamChunk",value:new En({content:t,streamId:a,chunkIndex:za(h)})}});yield m.sendDataPacket(n,Xi.RELIABLE),h+=1,i+=t.byteLength}}finally{t()}})},close(){return Ws(this,void 0,void 0,function*(){const e=new Rn({streamId:a}),t=new Yi({destinationIdentities:c,value:{case:"streamTrailer",value:e}});yield m.sendDataPacket(t,Xi.RELIABLE)})},abort(e){g.error("Sink error:",e)}});return new Vd(f,d)})}}class Hd extends aa{constructor(e,t,i,n,s){super(e,i,s),this.sid=t,this.receiver=n}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Co.Muted:Co.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.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(Co.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return Ws(this,void 0,void 0,function*(){var e;if(!(null===(e=this.receiver)||void 0===e?void 0:e.getStats))return;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||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),ad)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=null===(t=this.receiver)||void 0===t?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:e,rtpTimestamp:t}=i;t&&this.rtpTimestamp!==t&&(this.emit(Co.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class Wd extends Hd{constructor(e,t,i,n,s,r){super(e,t,aa.Kind.Audio,i,r),this.monitorReceiver=()=>Ws(this,void 0,void 0,function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=cd(e,this.prevStats)),this.prevStats=e}),this.audioContext=n,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;Ca()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Ca())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return Ws(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(ga(t))return t.setSinkId(e)}))})}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&ga(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 i=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{i.connect(e),i=e}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then(()=>{"running"!==e.state&&this.emit(Co.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(e=>{this.emit(Co.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return Ws(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield this.receiver.getStats()).forEach(t=>{"inbound-rtp"===t.type&&(e={type:"audio",streamId:t.id,timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})}),e})}}class Kd extends Hd{constructor(e,t,i,n,s){super(e,t,aa.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>Ws(this,void 0,void 0,function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=cd(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=Bc(()=>{this.updateDimensions()},100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===aa.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?da(this._mediaStreamTrack,t):ca(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t.element===e)){const t=new Gd(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t===e)?(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)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);const t=this.elementInfos.filter(t=>t===e);for(const i of t)i.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(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return Ws(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",n=new Map;return e.forEach(e=>{"inbound-rtp"===e.type?(i=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}):"codec"===e.type&&n.set(e.id,e)}),t&&""!==i&&n.get(i)&&(t.mimeType=n.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(t=>t.element===e);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Ws(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;const n=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),s=!(null!==(i=null===(t=this.adaptiveStreamSettings)||void 0===t?void 0:t.pauseVideoInBackground)&&void 0!==i&&!i)&&this.isInBackground,r=this.elementInfos.some(e=>e.pictureInPicture),o=this.elementInfos.some(e=>e.visible)&&!s||r;(this.lastVisible!==o||e)&&(!o&&Date.now()-n<100?Mo.setTimeout(()=>{this.updateVisibility()},100):(this.lastVisible=o,this.emit(Co.VisibilityChanged,o,this)))}updateDimensions(){var e,t;let i=0,n=0;const s=this.getPixelDensity();for(const r of this.elementInfos){const e=r.width()*s,t=r.height()*s;e+t>i+n&&(i=e,n=t)}(null===(e=this.lastDimensions)||void 0===e?void 0:e.width)===i&&(null===(t=this.lastDimensions)||void 0===t?void 0:t.height)===n||(this.lastDimensions={width:i,height:n},this.emit(Co.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;if("screen"===t)return Pa();if(!t){return Pa()>2?2:1}return t}}class Gd{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.isPiP=Jd(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t,i;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Jd(this.element),null===(i=this.handleVisibilityChanged)||void 0===i||i.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=Jd(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:Qd(e),this.isPiP=Ta()&&Jd(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=Qd(this.element),this.isPiP=Jd(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Ma().observe(this.element),Da().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null===(e=window.documentPictureInPicture)||void 0===e||e.addEventListener("enter",this.onEnterPiP),null===(i=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===i||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,n,s;null===(e=Ma())||void 0===e||e.unobserve(this.element),null===(t=Da())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(i=window.documentPictureInPicture)||void 0===i||i.removeEventListener("enter",this.onEnterPiP),null===(s=null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)||void 0===s||s.removeEventListener("pagehide",this.onLeavePiP)}}function Jd(e){var t,i;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&Qd(e,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function Qd(e,t){const i=t||window;let n=e.offsetTop,s=e.offsetLeft;const r=e.offsetWidth,o=e.offsetHeight,{hidden:a}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,s+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&s<i.pageXOffset+i.innerWidth&&n+o>i.pageYOffset&&s+r>i.pageXOffset&&!a&&"none"!==c}class Yd extends Ys.EventEmitter{constructor(e,t,i,n){var s;super(),this.metadataMuted=!1,this.encryption=Wi.NONE,this.log=Bs,this.handleMuted=()=>{this.emit(Co.Muted)},this.handleUnmuted=()=>{this.emit(Co.Unmuted)},this.log=qs(null!==(s=null==n?void 0:n.loggerName)&&void 0!==s?s:Us.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=aa.Source.Unknown}setTrack(e){this.track&&(this.track.off(Co.Muted,this.handleMuted),this.track.off(Co.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(Co.Muted,this.handleMuted),e.on(Co.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),ta(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==Wi.NONE}get audioTrack(){if(Wa(this.track))return this.track}get videoTrack(){if(Ka(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=aa.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===aa.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}))}}var Xd,Zd,$d,el,tl,il,nl;Xd=Yd||(Yd={}),(Zd=Xd.SubscriptionStatus||(Xd.SubscriptionStatus={})).Desired="desired",Zd.Subscribed="subscribed",Zd.Unsubscribed="unsubscribed",($d=Xd.PermissionStatus||(Xd.PermissionStatus={})).Allowed="allowed",$d.NotAllowed="not_allowed";class sl extends Yd{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit(Co.Ended)},this.handleCpuConstrained=()=>{this.track&&Ka(this.track)&&this.emit(Co.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(Co.Ended,this.handleTrackEnded),this.track.off(Co.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(Co.Ended,this.handleTrackEnded),e.on(Co.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 Ws(this,void 0,void 0,function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()})}unmute(){return Ws(this,void 0,void 0,function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()})}pauseUpstream(){return Ws(this,void 0,void 0,function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()})}resumeUpstream(){return Ws(this,void 0,void 0,function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Wa(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(Ui.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(Ui.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(Ui.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(Ui.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||i.add(Ui.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(Ui.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}return[]}}function rl(e,t){return Ws(this,void 0,void 0,function*(){null!=e||(e={});let i=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:r}=ia(e);let o=r.audio,a=r.video;if(n&&"object"==typeof r.audio&&(r.audio.processor=n),s&&"object"==typeof r.video&&(r.video.processor=s),e.audio&&"object"==typeof r.audio&&"string"==typeof r.audio.deviceId){const e=r.audio.deviceId;r.audio.deviceId={exact:e},i=!0,o=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:e}})}if(r.video&&"object"==typeof r.video&&"string"==typeof r.video.deviceId){const e=r.video.deviceId;r.video.deviceId={exact:e},i=!0,a=Object.assign(Object.assign({},r.video),{deviceId:{ideal:e}})}!0===r.audio?r.audio={deviceId:"default"}:"object"==typeof r.audio&&null!==r.audio&&(r.audio=Object.assign(Object.assign({},r.audio),{deviceId:r.audio.deviceId||"default"})),!0===r.video?r.video={deviceId:"default"}:"object"!=typeof r.video||r.video.deviceId||(r.video.deviceId="default");const c=Ko(r,Yc,Xc),d=Jo(c),l=navigator.mediaDevices.getUserMedia(d);r.audio&&(gc.userMediaPromiseMap.set("audioinput",l),l.catch(()=>gc.userMediaPromiseMap.delete("audioinput"))),r.video&&(gc.userMediaPromiseMap.set("videoinput",l),l.catch(()=>gc.userMediaPromiseMap.delete("videoinput")));try{const e=yield l;return yield Promise.all(e.getTracks().map(i=>Ws(this,void 0,void 0,function*(){const r="audio"===i.kind;let o,a=r?c.audio:c.video;"boolean"!=typeof a&&a||(a={});const l=r?d.audio:d.video;"boolean"!=typeof l&&(o=l);const u=i.getSettings().deviceId;(null==o?void 0:o.deviceId)&&Fa(o.deviceId)!==u?o.deviceId=u:o||(o={deviceId:u});const h=function(e,t,i){switch(e.kind){case"audio":return new pd(e,t,!1,void 0,i);case"video":return new Ed(e,t,!1,i);default:throw new Ro("unsupported track type: ".concat(e.kind))}}(i,o,t);return h.kind===aa.Kind.Video?h.source=aa.Source.Camera:h.kind===aa.Kind.Audio&&(h.source=aa.Source.Microphone),h.mediaStream=e,Wa(h)&&n?yield h.setProcessor(n):Ka(h)&&s&&(yield h.setProcessor(s)),h})))}catch(u){if(!i)throw u;return rl(Object.assign(Object.assign({},e),{audio:o,video:a}),t)}})}(tl=el||(el={})).Excellent="excellent",tl.Good="good",tl.Poor="poor",tl.Lost="lost",tl.Unknown="unknown";class ol extends Ys.EventEmitter{get logContext(){var e,t;return Object.assign({},null===(t=null===(e=this.loggerOptions)||void 0===e?void 0:e.loggerContextCb)||void 0===t?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return(null===(e=this.permissions)||void 0===e?void 0:e.agent)||this.kind===zi.AGENT}get isActive(){var e;return(null===(e=this.participantInfo)||void 0===e?void 0:e.state)===Vi.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,n,s,r){let o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:zi.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=el.Unknown,this.log=Bs,this.log=qs(null!==(a=null==r?void 0:r.loggerName)&&void 0!==a?a:Us.Participant),this.loggerOptions=r,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=null!=s?s:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new ja,this.once(bo.Active,()=>{var e,t;null===(t=null===(e=this.activeFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.activeFuture=void 0})),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(aa.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(aa.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(aa.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){var t;return!(this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version)&&(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===Vi.ACTIVE&&(null===(t=this.participantInfo)||void 0===t?void 0:t.state)!==Vi.ACTIVE&&this.emit(bo.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(bo.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(bo.ParticipantNameChanged,e)}_setAttributes(e){const t=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});const n=[...Object.keys(t),...Object.keys(e)],s={};for(const r of n)e[r]!==t[r]&&(s[r]=null!==(i=t[r])&&void 0!==i?i:"");return s}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(bo.AttributesChanged,t)}setPermissions(e){var t,i,n,s,r,o;const a=this.permissions,c=e.canPublish!==(null===(t=this.permissions)||void 0===t?void 0:t.canPublish)||e.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||e.canPublishData!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishData)||e.hidden!==(null===(s=this.permissions)||void 0===s?void 0:s.hidden)||e.recorder!==(null===(r=this.permissions)||void 0===r?void 0:r.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])})||e.canSubscribeMetrics!==(null===(o=this.permissions)||void 0===o?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit(bo.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(bo.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case Di.EXCELLENT:return el.Excellent;case Di.GOOD:return el.Good;case Di.POOR:return el.Poor;case Di.LOST:return el.Lost;default:return el.Unknown}}(e),t!==this._connectionQuality&&this.emit(bo.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&(null===(t=(e=this.activeFuture).reject)||void 0===t||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>Wa(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(Co.Muted,()=>{this.emit(bo.TrackMuted,e)}),e.on(Co.Unmuted,()=>{this.emit(bo.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case aa.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case aa.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class al extends ol{constructor(e,t,i,n,s,r){super(e,t,void 0,void 0,void 0,{loggerName:n.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Wi.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new ja)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,i,n,s,r;this.reconnectFuture&&(this.reconnectFuture.promise.catch(e=>this.log.warn(e.message,this.logContext)),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null===(n=(i=this.signalConnectedFuture).reject)||void 0===n||n.call(i,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),null===(r=null===(s=this.activeAgentFuture)||void 0===s?void 0:s.reject)||void 0===r||r.call(s,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,i;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new ja),null===(i=(t=this.signalConnectedFuture).resolve)||void 0===i||i.call(t)},this.handleSignalRequestResponse=e=>{const{requestId:t,reason:i,message:n}=e,s=this.pendingSignalRequests.get(t);s&&(i!==Cs.OK&&s.reject(new Oo(n,i)),this.pendingSignalRequests.delete(t))},this.handleDataPacket=e=>{switch(e.value.case){case"rpcResponse":let t=e.value.value,i=null,n=null;"payload"===t.value.case?i=t.value.value:"error"===t.value.case&&(n=sd.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,i,n);break;case"rpcAck":let s=e.value.value;this.handleIncomingRpcAck(s.requestId)}},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=>function(e){var t,i,n;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new cs({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(i=e.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=e.allowAll)&&void 0!==n&&n,trackSids:e.allowedTrackSids||[]})}(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),ta(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),ta(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),ta(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{const t=this.audioTrackPublications.get(e.sid);t?this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext)},this.onTrackCpuConstrained=(e,t)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),ta(t))),this.emit(bo.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>Ws(this,void 0,void 0,function*(){var t,i,n,s,r;if(!(null===(r=this.roomOptions)||void 0===r?void 0:r.dynacast))return;const o=this.videoTrackPublications.get(e.trackSid);if(!o)return void this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));if(!o.videoTrack)return;const a=yield o.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=Gs(a);!(t=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;jo(e)&&(this.log.debug("publish ".concat(e," for ").concat(o.videoTrack.sid),Object.assign(Object.assign({},this.logContext),ta(o))),yield this.publishAdditionalCodecForTrack(o.videoTrack,e,o.options))}}catch(u){i={error:u}}finally{try{d||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}}),this.handleLocalTrackUnpublished=e=>{const t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))},this.handleTrackEnded=e=>Ws(this,void 0,void 0,function*(){if(e.source===aa.Source.ScreenShare||e.source===aa.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),ta(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(Ja(e)||Ga(e))try{if(Ta())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===aa.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),ta(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(t){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),ta(e))),Ja(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),ta(e))),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s,this.roomOutgoingDataStreamManager=r}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Wi.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(ko.RemoteMute,(e,t)=>{const i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.unmute())}),(null===(t=this.signalConnectedFuture)||void 0===t?void 0:t.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(ko.Connected,this.handleReconnected).on(ko.SignalConnected,this.handleSignalConnected).on(ko.SignalRestarted,this.handleReconnected).on(ko.SignalResumed,this.handleReconnected).on(ko.Restarting,this.handleReconnecting).on(ko.Resuming,this.handleReconnecting).on(ko.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(ko.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(ko.Closing,this.handleClosing).on(ko.SignalRequestResponse,this.handleSignalRequestResponse).on(ko.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return Ws(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return Ws(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return Ws(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return Ws(this,arguments,void 0,function(e){var t=this;let{metadata:i,name:n,attributes:s}=e;return function*(){return new Promise((e,r)=>Ws(t,void 0,void 0,function*(){var t,o;try{let a=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(o=null!=n?n:this.name)&&void 0!==o?o:"",s),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{r(e),a=!0},values:{name:n,metadata:i,attributes:s}});performance.now()-d<5e3&&!a;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every(e=>{let[t,i]=e;return this.attributes[t]===i||""===i&&!this.attributes[t]})))return this.pendingSignalRequests.delete(c),void e();yield ua(50)}r(new Oo("Request to update local metadata timed out","TimeoutError"))}catch(a){a instanceof Error&&r(a)}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(aa.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(aa.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(aa.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return Ws(this,void 0,void 0,function*(){this.encryptionType=e?Wi.GCM:Wi.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,n){return Ws(this,void 0,void 0,function*(){var s,r;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let t;if(this.pendingPublishing.has(e)){const 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 null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case aa.Source.Camera:t=yield this.createTracks({video:null===(s=i)||void 0===s||s});break;case aa.Source.Microphone:t=yield this.createTracks({audio:null===(r=i)||void 0===r||r});break;case aa.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Ro(e)}}catch(a){throw null==t||t.forEach(e=>{e.stop()}),a instanceof Error&&this.emit(bo.MediaDevicesError,a,Zo(e)),this.pendingPublishing.delete(e),a}for(const n of t){const t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===aa.Source.Microphone&&Wa(n)&&t.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),n.startPreConnectBuffer())}try{const e=[];for(const s of t)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),ta(s))),e.push(this.publishTrack(s,n));const i=yield Promise.all(e);[o]=i}catch(a){throw null==t||t.forEach(e=>{e.stop()}),a}finally{this.pendingPublishing.delete(e)}}else if(!(null==o?void 0:o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===aa.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const e=this.getTrackPublication(aa.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return Ws(this,void 0,void 0,function*(){if(!this.pendingPublishing.has(aa.Source.Camera)&&!this.pendingPublishing.has(aa.Source.Microphone)){this.pendingPublishing.add(aa.Source.Camera),this.pendingPublishing.add(aa.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete(aa.Source.Camera),this.pendingPublishing.delete(aa.Source.Microphone)}}})}createTracks(e){return Ws(this,void 0,void 0,function*(){var t,i;null!=e||(e={});const n=Ko(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults);try{const e=yield rl(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return e.map(e=>(Wa(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=aa.Source.Microphone,this.emit(bo.AudioStreamAcquired)),Ka(e)&&(this.cameraError=void 0,e.source=aa.Source.Camera),e))}catch(bl){throw bl instanceof Error&&(e.audio&&(this.microphoneError=bl),e.video&&(this.cameraError=bl)),bl}})}createScreenTracks(e){return Ws(this,void 0,void 0,function*(){if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new Eo("getDisplayMedia not supported");void 0!==e.resolution||function(){const e=so();return"Safari"===(null==e?void 0:e.name)&&e.version.startsWith("17.")||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&xa(e.osVersion,"17")>=0}()||(e.resolution=Wo.h1080fps30.resolution);const t=function(e){var t,i;let n=null===(t=e.video)||void 0===t||t;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(n="boolean"==typeof n?{}:n,n=ba()?Object.assign(Object.assign({},n),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},n),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:null!==(i=e.audio)&&void 0!==i&&i,video:n,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}(e),i=yield navigator.mediaDevices.getDisplayMedia(t),n=i.getVideoTracks();if(0===n.length)throw new Ro("no video track found");const s=new Ed(n[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=aa.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const r=[s];if(i.getAudioTracks().length>0){this.emit(bo.AudioStreamAcquired);const e=new pd(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=aa.Source.ScreenShareAudio,r.push(e)}return r})}publishTrack(e,t){return Ws(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return Ws(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var s,r,o,a;let c,d;if(Ja(e)&&e.setAudioContext(i.audioContext),yield null===(s=i.reconnectFuture)||void 0===s?void 0:s.promise,i.republishPromise&&!n&&(yield i.republishPromise),Ha(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)c=e.getConstraints();else{let t;switch(c=e.constraints,e.source){case aa.Source.Microphone:t="audioinput";break;case aa.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(c=Object.assign(Object.assign({},c),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new pd(e,c,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new Ed(e,c,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new Ro("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});if(i.trackPublications.forEach(t=>{t.track&&t.track===e&&(d=t)}),d)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),ta(d))),d;const l=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t),u="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,h=null!==(r=l.forceStereo)&&void 0!==r?r:u;h&&(void 0===l.dtx&&i.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},i.logContext),ta(e))),void 0===l.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(o=l.dtx)&&void 0!==o||(l.dtx=!1),null!==(a=l.red)&&void 0!==a||(l.red=!1)),!function(){const e=so(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&xa(e.osVersion,t)>=0)||"Safari"===e.name&&xa(e.version,t)>=0}()&&i.roomOptions.e2ee&&(i.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({},i.logContext)),l.simulcast=!1),l.source&&(e.source=l.source);const p=new Promise((t,n)=>Ws(i,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Tc.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:ta(e)}));let i=!1;const s=setTimeout(()=>{i=!0,e.stop(),n(new _o("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(s),i)return;const r=yield this.publish(e,l,h);t(r)}else try{const i=yield this.publish(e,l,h);t(i)}catch(i){n(i)}}catch(i){n(i)}}));i.pendingPublishPromises.set(e,p);try{return yield p}catch(m){throw m}finally{i.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new ja),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),ta(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return!(!t||0!==i.length&&!i.map(e=>function(e){switch(e){case _i.CAMERA:return aa.Source.Camera;case _i.MICROPHONE:return aa.Source.Microphone;case _i.SCREEN_SHARE:return aa.Source.ScreenShare;case _i.SCREEN_SHARE_AUDIO:return aa.Source.ScreenShareAudio;default:return aa.Source.Unknown}}(e)).includes(e.source))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),ta(e))),!1)}publish(e,t,i){return Ws(this,void 0,void 0,function*(){var n,s,r,o,a,c,d,l,u,h;if(!this.hasPermissionsToPublish(e))throw new _o("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(t=>Ha(e)&&t.source===e.source)&&e.source!==aa.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),ta(e))),t.stopMicTrackOnMute&&Wa(e)&&(e.stopOnMute=!0),e.source===aa.Source.ScreenShare&&fa()&&(t.simulcast=!1),"av1"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(ba()||fa())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/av1"===i.mimeType.toLowerCase()){t=!0;break}return t}()||(t.videoCodec=void 0),"vp9"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(fa())return!1;if(ba()){const e=so();if((null==e?void 0:e.version)&&xa(e.version,"16")<0)return!1;if("iOS"===(null==e?void 0:e.os)&&(null==e?void 0:e.osVersion)&&xa(e.osVersion,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/vp9"===i.mimeType.toLowerCase()){t=!0;break}return t}()||(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec=Jc),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(e=>t.videoCodec===$o(e.mime))||(t.videoCodec=$o(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(Co.Muted,this.onTrackMuted),e.on(Co.Unmuted,this.onTrackUnmuted),e.on(Co.Ended,this.handleTrackEnded),e.on(Co.UpstreamPaused,this.onTrackUpstreamPaused),e.on(Co.UpstreamResumed,this.onTrackUpstreamResumed),e.on(Co.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=[],g=!(null===(n=t.dtx)||void 0===n||n),f=e.getSourceTrackSettings();f.autoGainControl&&m.push(Ui.TF_AUTO_GAIN_CONTROL),f.echoCancellation&&m.push(Ui.TF_ECHO_CANCELLATION),f.noiseSuppression&&m.push(Ui.TF_NOISE_SUPPRESSION),f.channelCount&&f.channelCount>1&&m.push(Ui.TF_STEREO),g&&m.push(Ui.TF_NO_DTX),Ja(e)&&e.hasPreConnectBuffer&&m.push(Ui.TF_PRECONNECT_BUFFER);const v=new Mn({cid:e.mediaStreamTrack.id,name:t.name,type:aa.kindToProto(e.kind),muted:e.isMuted,source:aa.sourceToProto(e.source),disableDtx:g,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(s=t.red)||void 0===s||s),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy,audioFeatures:m});let b;if(e.kind===aa.Kind.Video){let i={width:0,height:0};try{i=yield e.waitForDimensions()}catch(S){const t=null!==(o=null===(r=this.roomOptions.videoCaptureDefaults)||void 0===r?void 0:r.resolution)&&void 0!==o?o:zo.h720.resolution;i={width:t.width,height:t.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),ta(e)),{dims:i}))}v.width=i.width,v.height=i.height,Ga(e)&&(ma(p)&&(e.source===aa.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),ta(e))))),t.scalabilityMode=null!==(a=t.scalabilityMode)&&void 0!==a?a:"L3T3_KEY"),v.simulcastCodecs=[new An({codec:p,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:Jc}),t.backupCodec&&p!==t.backupCodec.codec&&v.encryption===Wi.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),v.simulcastCodecs.push(new An({codec:t.backupCodec.codec,cid:""})))),b=kd(e.source===aa.Source.ScreenShare,v.width,v.height,t),v.layers=xd(v.width,v.height,b,ma(t.videoCodec))}else e.kind===aa.Kind.Audio&&(b=[{maxBitrate:null===(c=t.audioPreset)||void 0===c?void 0:c.maxBitrate,priority:null!==(l=null===(d=t.audioPreset)||void 0===d?void 0:d.priority)&&void 0!==l?l:"high",networkPriority:null!==(h=null===(u=t.audioPreset)||void 0===u?void 0:u.priority)&&void 0!==h?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new xo("cannot publish track when not connected");const y=()=>Ws(this,void 0,void 0,function*(){var i,n,s;if(!this.engine.pcManager)throw new xo("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),this.emit(bo.LocalSenderCreated,e.sender,e),Ga(e)&&(null!==(i=t.degradationPreference)&&void 0!==i||(t.degradationPreference=function(e){return e.source===aa.Source.ScreenShare||e.constraints.height&&Fa(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(e)),e.setDegradationPreference(t.degradationPreference)),b)if(fa()&&e.kind===aa.Kind.Audio){let t;for(const i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===e.sender){t=i;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:"opus",maxbr:(null===(n=b[0])||void 0===n?void 0:n.maxBitrate)?b[0].maxBitrate/1e3:0})}else e.codec&&ma(e.codec)&&(null===(s=b[0])||void 0===s?void 0:s.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:v.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()});let k;const T=new Promise((t,i)=>Ws(this,void 0,void 0,function*(){var n;try{k=yield this.engine.addTrack(v),t(k)}catch(bl){e.sender&&(null===(n=this.engine.pcManager)||void 0===n?void 0:n.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),ta(e)),{error:t}))})),i(bl)}}));if(this.enabledPublishVideoCodecs.length>0){const e=yield Promise.all([T,y()]);k=e[0]}else{let i;if(k=yield T,k.codecs.forEach(e=>{void 0===i&&(i=e.mimeType)}),i&&e.kind===aa.Kind.Video){const n=$o(i);n!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),ta(e)),{codec:n})),t.videoCodec=n,b=kd(e.source===aa.Source.ScreenShare,v.width,v.height,t))}yield y()}const C=new sl(e.kind,k,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(C.on(Co.CpuConstrained,e=>this.onTrackCpuConstrained(e,C)),C.options=t,e.sid=k.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:k})),Ga(e)?e.startMonitor(this.engine.client):Ja(e)&&e.startMonitor(),this.addTrackPublication(C),this.emit(bo.LocalTrackPublished,C),Ja(e)&&k.audioFeatures.includes(Ui.TF_PRECONNECT_BUFFER)){const t=e.getPreConnectBuffer(),i=e.getPreConnectBufferMimeType();if(this.on(bo.LocalTrackSubscribed,t=>{if(t.trackSid===k.sid){if(!e.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed",this.logContext);this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),ta(e))),e.stopPreConnectBuffer()}}),t){new Promise((n,s)=>Ws(this,void 0,void 0,function*(){var r,o,a,c,d,l;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),ta(e)));const g=setTimeout(()=>{s(new Error("agent not active within 10 seconds"))},1e4),v=yield this.waitUntilActiveAgentPresent();clearTimeout(g),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),ta(e)));const b=yield this.streamBytes({name:"preconnect-buffer",mimeType:i,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[v.identity],attributes:{trackId:C.trackSid,sampleRate:String(null!==(d=f.sampleRate)&&void 0!==d?d:"48000"),channels:String(null!==(l=f.channelCount)&&void 0!==l?l:"1")}});try{for(var u,h=!0,p=Gs(t);!(r=(u=yield p.next()).done);h=!0){c=u.value,h=!1;const e=c;yield b.write(e)}}catch(m){o={error:m}}finally{try{h||r||!(a=p.return)||(yield a.call(p))}finally{if(o)throw o.error}}yield b.close(),n()}catch(S){s(S)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),ta(e)))}).catch(t=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),ta(e)),{error:t}))})}}return C})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return Ws(this,void 0,void 0,function*(){var n;if(this.encryptionType!==Wi.NONE)return;let s;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(s=t)}),!s)throw new Ro("track is not published");if(!Ga(e))throw new Ro("track is not a video track");const r=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),o=function(e,t,i){var n,s,r,o;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&Bs.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const a=e.mediaStreamTrack.getSettings(),c=null!==(n=a.width)&&void 0!==n?n:null===(s=e.dimensions)||void 0===s?void 0:s.width,d=null!==(r=a.height)&&void 0!==r?r:null===(o=e.dimensions)||void 0===o?void 0:o.height;return e.source===aa.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),kd(e.source===aa.Source.ScreenShare,c,d,i)}(e,t,r);if(!o)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),ta(e)));const a=e.addSimulcastTrack(t,o);if(!a)return;const c=new Mn({cid:a.mediaStreamTrack.id,type:aa.kindToProto(e.kind),muted:e.isMuted,source:aa.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:r.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=xd(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new xo("cannot publish track when not connected");const d=(yield Promise.all([this.engine.addTrack(c),(()=>Ws(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,a,r,o),yield this.engine.negotiate()}))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:d}))})}unpublishTrack(e,t){return Ws(this,void 0,void 0,function*(){var i,n;if(Ha(e)){const t=this.pendingPublishPromises.get(e);t&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),ta(e))),yield t)}const s=this.getPublicationForTrack(e),r=s?ta(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),r)),!s||!s.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),r));(e=s.track).off(Co.Muted,this.onTrackMuted),e.off(Co.Unmuted,this.onTrackUnmuted),e.off(Co.Ended,this.handleTrackEnded),e.off(Co.UpstreamPaused,this.onTrackUpstreamPaused),e.off(Co.UpstreamResumed,this.onTrackUpstreamResumed),e.off(Co.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null===(n=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===n||n),t?e.stop():e.stopMonitor();let o=!1;const a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<ed.FAILED&&a)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),Ga(e)){for(const[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(o=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(c){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),r),{error:c}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case aa.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case aa.Kind.Video:this.videoTrackPublications.delete(s.trackSid)}return this.emit(bo.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return Ws(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return Ws(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new Promise((n,s)=>Ws(t,void 0,void 0,function*(){try{const t=[];this.trackPublications.forEach(i=>{i.track&&(e&&(i.options=Object.assign(Object.assign({},i.options),e)),t.push(i))}),yield Promise.all(t.map(e=>Ws(this,void 0,void 0,function*(){const t=e.track;yield this.unpublishTrack(t,!1),!i||t.isMuted||t.source===aa.Source.ScreenShare||t.source===aa.Source.ScreenShareAudio||!Ja(t)&&!Ga(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)}))),n()}catch(t){s(t)}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return Ws(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){const n=i.reliable?Xi.RELIABLE:Xi.LOSSY,s=i.destinationIdentities,r=i.topic;let o=new nn({participantIdentity:t.identity,payload:e,destinationIdentities:s,topic:r});const a=new Yi({kind:n,value:{case:"user",value:o}});yield t.engine.sendDataPacket(a,n)}()})}publishDtmf(e,t){return Ws(this,void 0,void 0,function*(){const i=new Yi({kind:Xi.RELIABLE,value:{case:"sipDtmf",value:new sn({code:e,digit:t})}});yield this.engine.sendDataPacket(i,Xi.RELIABLE)})}sendChatMessage(e,t){return Ws(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments},n=new Yi({value:{case:"chatMessage",value:new an(Object.assign(Object.assign({},i),{timestamp:dt.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,Xi.RELIABLE),this.emit(bo.ChatMessage,i),i})}editChatMessage(e,t){return Ws(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new Yi({value:{case:"chatMessage",value:new an(Object.assign(Object.assign({},i),{timestamp:dt.parse(i.timestamp),editTimestamp:dt.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,Xi.RELIABLE),this.emit(bo.ChatMessage,i),i})}sendText(e,t){return Ws(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return Ws(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return Ws(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return Ws(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return Ws(this,arguments,void 0,function(e){var t=this;let{destinationIdentity:i,method:n,payload:s,responseTimeout:r=15e3}=e;return function*(){return new Promise((e,o)=>Ws(t,void 0,void 0,function*(){var t,a,c,d;if(rd(s)>15360)return void o(sd.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null===(a=null===(t=this.engine.latestJoinResponse)||void 0===t?void 0:t.serverInfo)||void 0===a?void 0:a.version)&&xa(null===(d=null===(c=this.engine.latestJoinResponse)||void 0===c?void 0:c.serverInfo)||void 0===d?void 0:d.version,"1.8.0")<0)return void o(sd.builtIn("UNSUPPORTED_SERVER"));const l=Math.max(r,8e3),u=crypto.randomUUID();yield this.publishRpcRequest(i,u,n,s,l);const h=setTimeout(()=>{this.pendingAcks.delete(u),o(sd.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(u),clearTimeout(p)},7e3);this.pendingAcks.set(u,{resolve:()=>{clearTimeout(h)},participantIdentity:i});const p=setTimeout(()=>{this.pendingResponses.delete(u),o(sd.builtIn("RESPONSE_TIMEOUT"))},r);this.pendingResponses.set(u,{resolve:(t,i)=>{clearTimeout(p),this.pendingAcks.has(u)&&(this.log.warn("RPC response received before ack",u),this.pendingAcks.delete(u),clearTimeout(h)),i?o(i):e(null!=t?t:"")},participantIdentity:i})}))}()})}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const n=this.pendingResponses.get(e);n?(n.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,n,s){return Ws(this,void 0,void 0,function*(){const r=new Yi({destinationIdentities:[e],kind:Xi.RELIABLE,value:{case:"rpcRequest",value:new cn({id:t,method:i,payload:n,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(r,Xi.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===e&&(n(null,sd.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(e=>"video"===e.mime.split("/")[0].toLowerCase())}updateInfo(e){return!!super.updateInfo(e)&&(e.tracks.forEach(e=>{var t,i;const n=this.trackPublications.get(e.sid);if(n){const s=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;s!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),ta(n)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(e.sid,s))}}),!0)}setActiveAgent(e){var t,i,n,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?null===(i=null===(t=this.activeAgentFuture)||void 0===t?void 0:t.resolve)||void 0===i||i.call(t,e):null===(s=null===(n=this.activeAgentFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new ja),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(Ja(n)||Ga(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))}),t}waitForPendingPublicationOfSource(e){return Ws(this,void 0,void 0,function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find(t=>{let[i]=t;return i.source===e});if(t)return t[1];yield ua(20)}})}}class cl extends Yd{constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(Co.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const n=new zn({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new hn({participantSid:"",trackSids:[this.trackSid]})]});this.emit(Co.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?Yd.SubscriptionStatus.Unsubscribed:super.isSubscribed?Yd.SubscriptionStatus.Subscribed:Yd.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Yd.PermissionStatus.Allowed:Yd.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return void 0!==this.requestedDisabled?!this.requestedDisabled:!this.isAdaptiveStream||this.visible}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){var t,i;this.isManualOperationAllowed()&&((null===(t=this.requestedVideoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(i=this.requestedVideoDimensions)||void 0===i?void 0:i.height)===e.height||(Xa(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Xa(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return null!==(e=this.requestedMaxQuality)&&void 0!==e?e:ra.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(Co.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(Co.VisibilityChanged,this.handleVisibilityChange),n.off(Co.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(Co.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(Co.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(Co.VisibilityChanged,this.handleVisibilityChange),e.on(Co.Ended,this.handleEnded),this.emit(Co.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(Co.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?Co.Muted:Co.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(Co.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(Co.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Xa(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Hn({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===aa.Kind.Video){let s=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(s){na(this.videoDimensionsAdaptiveStream,s)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),s=this.videoDimensionsAdaptiveStream)}else if(void 0!==this.requestedMaxQuality&&this.trackInfo){const e=(t=this.trackInfo,i=this.requestedMaxQuality,null===(n=t.layers)||void 0===n?void 0:n.find(e=>e.quality===i));e&&na(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),s=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),s=this.videoDimensionsAdaptiveStream;s?(e.width=Math.ceil(s.width),e.height=Math.ceil(s.height)):void 0!==this.requestedMaxQuality?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:ra.HIGH})),e.quality=ra.HIGH)}var t,i,n;this.emit(Co.UpdateSettings,e)}}class dl extends ol{static fromParticipantInfo(e,t,i){return new dl(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,n,s,r,o){super(t,i||"",n,s,r,o,arguments.length>7&&void 0!==arguments[7]?arguments[7]:zi.STANDARD),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(Co.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),ta(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(Co.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(Co.SubscriptionPermissionChanged,t=>{this.emit(bo.TrackSubscriptionPermissionChanged,e,t)}),e.on(Co.SubscriptionStatusChanged,t=>{this.emit(bo.TrackSubscriptionStatusChanged,e,t)}),e.on(Co.Subscribed,t=>{this.emit(bo.TrackSubscribed,t,e)}),e.on(Co.Unsubscribed,t=>{this.emit(bo.TrackUnsubscribed,t,e)}),e.on(Co.SubscriptionFailed,t=>{this.emit(bo.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:aa.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:aa.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,n,s,r){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(t=>{o||e.kind!==t.kind.toString()||(o=t)}),!o)return 0===r?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),void this.emit(bo.TrackSubscriptionFailed,t)):(void 0===r&&(r=20),void setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,n,s,r-1)},150));if("ended"===e.readyState)return this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),ta(o))),void this.emit(bo.TrackSubscriptionFailed,t);let a;return a="video"===e.kind?new Kd(e,t,n,s):new Wd(e,t,n,this.audioContext,this.audioOutput),a.source=o.source,a.isMuted=o.isMuted,a.setMediaStream(i),a.start(),o.setTrack(a),this.volumeMap.has(o.source)&&Qa(a)&&Wa(a)&&a.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;const t=new Map,i=new Map;return e.tracks.forEach(e=>{var n,s;let r=this.getTrackPublicationBySid(e.sid);if(r)r.updateInfo(e);else{const t=aa.kindFromProto(e.type);if(!t)return;r=new cl(t,e,null===(n=this.signalClient.connectOptions)||void 0===n?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(s=this.loggerOptions)||void 0===s?void 0:s.loggerName}),r.updateInfo(e),i.set(e.sid,r);const o=Array.from(this.trackPublications.values()).find(e=>e.source===(null==r?void 0:r.source));o&&r.source!==aa.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(r.source),Object.assign(Object.assign({},this.logContext),{oldTrack:ta(o),newTrack:ta(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),ta(e))),this.unpublishTrack(e.trackSid,!0))}),i.forEach(e=>{this.emit(bo.TrackPublished,e)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case aa.Kind.Audio:this.audioTrackPublications.delete(e);break;case aa.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(bo.TrackUnpublished,i)}setAudioOutput(e){return Ws(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var n;Wa(i.track)&&Qa(i.track)&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}(nl=il||(il={})).Disconnected="disconnected",nl.Connecting="connecting",nl.Connected="connected",nl.Reconnecting="reconnecting",nl.SignalReconnecting="signalReconnecting";class ll extends Ys.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(e){var t,i,n,s;if(super(),t=this,this.state=il.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Bs,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(e,t,i)=>Ws(this,void 0,void 0,function*(){var n;if("undefined"==typeof RTCPeerConnection||!ha()&&!pa())throw Ca()?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.");const s=yield this.disconnectLock.lock();if(this.state===il.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),s(),Promise.resolve();if(this.connectFuture)return s(),this.connectFuture.promise;this.setAndEmitConnectionState(il.Connecting),(null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getServerUrl().toString())!==Za(e)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Sa(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new nd(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))}));const r=(n,o,a)=>Ws(this,void 0,void 0,function*(){var c,d;this.abortController&&this.abortController.abort();const l=new AbortController;this.abortController=l,null==s||s();try{if(yield pc.getInstance().getBackOffPromise(e),l.signal.aborted)throw wo.cancelled("Connection attempt aborted");yield this.attemptConnection(null!=a?a:e,t,i,l),this.abortController=void 0,n()}catch(u){if(this.regionUrlProvider&&u instanceof wo&&u.reason!==lo.Cancelled&&u.reason!==lo.NotAllowed){let t=null;try{this.log.debug("Fetching next region"),t=yield this.regionUrlProvider.getNextBestRegionUrl(null===(c=this.abortController)||void 0===c?void 0:c.signal)}catch(h){if(h instanceof wo&&(401===h.status||h.reason===lo.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void o(h)}[lo.InternalError,lo.ServerUnreachable,lo.Timeout].includes(u.reason)&&(this.log.debug("Adding failed connection attempt to back off"),pc.getInstance().addFailedConnectionAttempt(e)),t&&!(null===(d=this.abortController)||void 0===d?void 0:d.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(u.message,". Retrying with another region: ").concat(t),this.logContext),this.recreateEngine(),yield r(n,o,t)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,qa(u)),o(u))}else{let e=Mi.UNKNOWN_REASON;u instanceof wo&&(e=qa(u)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),o(u)}}}),o=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new ja((e,t)=>{r(e,t,o)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,i,n,s,r)=>Ws(this,void 0,void 0,function*(){var o,a,c;const d=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof s.adaptiveStream||s.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout,singlePeerConnection:s.singlePeerConnection},r.signal);let l=d.serverInfo;if(l||(l={version:d.serverVersion,region:d.serverRegion}),this.serverInfo=l,this.log.debug("connected to Livekit Server ".concat(Object.entries(l).map(e=>{let[t,i]=e;return"".concat(t,": ").concat(i)}).join(", ")),{room:null===(o=d.room)||void 0===o?void 0:o.name,roomSid:null===(a=d.room)||void 0===a?void 0:a.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!l.version)throw new Po("unknown server version");return"0.15.1"===l.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),s.dynacast=!1),d}),this.applyJoinResponse=e=>{const 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(i){this.log.error(i instanceof Error?i.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:i}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>Ws(this,void 0,void 0,function*(){var s,r;this.state===il.Reconnecting||this.isResuming||(null===(s=this.engine)||void 0===s?void 0:s.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(r=this.regionUrlProvider)||void 0===r?void 0:r.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},$c),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,n);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(fo.SignalConnected)}catch(bl){yield this.engine.close(),this.recreateEngine();const t=n.signal.aborted?wo.cancelled("Signal connection aborted"):wo.serverUnreachable("could not establish signal connection");throw bl instanceof Error&&(t.message="".concat(t.message,": ").concat(bl.message)),bl instanceof wo&&(t.reason=bl.reason,t.status=bl.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:bl})),t}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),wo.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(o){throw yield this.engine.close(),this.recreateEngine(),o}Ta()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Ta()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(il.Connected),this.emit(fo.Connected),pc.getInstance().resetFailedConnectionAttempts(e),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];return Ws(t,[...i],void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n,s;const r=yield e.disconnectLock.lock();try{if(e.state===il.Disconnected)return void e.log.debug("already disconnected",e.logContext);if(e.log.info("disconnect from room",Object.assign({},e.logContext)),e.state===il.Connecting||e.state===il.Reconnecting||e.isResuming){const t="Abort connection attempt due to user initiated disconnect";e.log.warn(t,e.logContext),null===(i=e.abortController)||void 0===i||i.abort(t),null===(s=null===(n=e.connectFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,wo.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,Mi.CLIENT_INITIATED),e.engine=void 0}finally{r()}}()})},this.onPageLeave=()=>Ws(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>Ws(this,void 0,void 0,function*(){const e=[],t=so();if(t&&"iOS"===t.os){const t="livekit-dummy-audio-el";let i=document.getElementById(t);if(!i){i=document.createElement("audio"),i.id=t,i.autoplay=!0,i.hidden=!0;const e=Ua();e.enabled=!0;const n=new MediaStream([e]);i.srcObject=n,document.addEventListener("visibilitychange",()=>{i&&(i.srcObject=document.hidden?null:n,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(i),this.once(fo.Disconnected,()=>{null==i||i.remove(),i=null})}e.push(i)}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(bl){throw this.handleAudioPlaybackFailed(bl),bl}}),this.startVideo=()=>Ws(this,void 0,void 0,function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var i;null===(i=t.track)||void 0===i||i.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{"NotAllowedError"===e.name?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(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(il.Reconnecting)&&this.emit(fo.Reconnecting)},this.handleSignalRestarted=e=>Ws(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(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(t){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:t}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch(i){return}this.setAndEmitConnectionState(il.Connected),this.emit(fo.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{e.forEach(e=>{var t;if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);""===e.identity&&(e.identity=null!==(t=this.sidToIdentity.get(e.sid))&&void 0!==t?t:"");let i=this.remoteParticipants.get(e.identity);e.state===Vi.DISCONNECTED?this.handleParticipantDisconnected(e.identity,i):i=this.getOrCreateParticipant(e.identity,e)})},this.handleActiveSpeakersUpdate=e=>{const t=[],i={};e.forEach(e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{const i=this.getRemoteParticipantBySid(e.sid);i&&(i.audioLevel=e.level,i.setIsSpeaking(!0),t.push(i))}}),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(fo.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{const t=new Map;this.activeSpeakers.forEach(e=>{const i=this.remoteParticipants.get(e.identity);i&&i.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let i=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=e.level,i.setIsSpeaking(e.active),e.active?t.set(e.sid,i):t.delete(e.sid))});const i=Array.from(t.values());i.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=i,this.emitWhenConnected(fo.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);if(!i||!i.track)return;const n=aa.streamStateFromProto(e.state);i.track.setStreamState(n),n!==i.track.streamState&&(t.emit(bo.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(fo.TrackStreamStateChanged,i,i.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{const i=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(i,e.value.value,e.kind,t);else if("transcription"===e.value.case)this.handleTranscription(i,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(i,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(i,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,i);else if("streamHeader"===e.value.case||"streamChunk"===e.value.case||"streamTrailer"===e.value.case)this.handleDataStream(e,t);else if("rpcRequest"===e.value.case){const t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,i,n)=>{this.emit(fo.DataReceived,t.payload,e,i,t.topic,n),null==e||e.emit(bo.DataReceived,t.payload,i,n)},this.handleSipDtmf=(e,t)=>{this.emit(fo.SipDTMFReceived,t,e),null==e||e.emit(bo.SipDTMFReceived,t)},this.handleTranscription=(e,t)=>{const i=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),n=null==i?void 0:i.trackPublications.get(t.trackId),s=function(e,t){return e.segments.map(e=>{let{id:i,text:n,language:s,startTime:r,endTime:o,final:a}=e;var c;const d=null!==(c=t.get(i))&&void 0!==c?c:Date.now(),l=Date.now();return a?t.delete(i):t.set(i,d),{id:i,text:n,startTime:Number.parseInt(r.toString()),endTime:Number.parseInt(o.toString()),final:a,language:s,firstReceivedTime:d,lastReceivedTime:l}})}(t,this.transcriptionReceivedTimes);null==n||n.emit(Co.TranscriptionReceived,s),null==i||i.emit(bo.TranscriptionReceived,s,n),this.emit(fo.TranscriptionReceived,s,i,n)},this.handleChatMessage=(e,t)=>{const i=function(e){const{id:t,timestamp:i,message:n,editTimestamp:s}=e;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}(t);this.emit(fo.ChatMessage,i,e)},this.handleMetrics=(e,t)=>{this.emit(fo.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(fo.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(fo.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(fo.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(fo.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>Ws(this,void 0,void 0,function*(){var e;"iOS"!==(null===(e=so())||void 0===e?void 0:e.os)&&(yield this.selectDefaultDevices()),this.emit(fo.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{const t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(fo.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(fo.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach(e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)})},this.onLocalParticipantMetadataChanged=e=>{this.emit(fo.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(fo.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(fo.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(fo.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(fo.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=e=>Ws(this,void 0,void 0,function*(){var t,i,n,s,r,o;if(null===(t=e.track)||void 0===t||t.on(Co.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.on(Co.Restarted,this.onLocalTrackRestarted),null===(r=null===(s=null===(n=e.track)||void 0===n?void 0:n.getProcessor())||void 0===s?void 0:s.onPublish)||void 0===r||r.call(s,this),this.emit(fo.LocalTrackPublished,e,this.localParticipant),Ja(e.track)){(yield e.track.checkForSilence())&&this.emit(fo.LocalAudioSilenceDetected,e)}const a=yield null===(o=e.track)||void 0===o?void 0:o.getDeviceId(!1),c=Zo(e.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,a),this.emit(fo.ActiveDeviceChanged,c,a))}),this.onLocalTrackUnpublished=e=>{var t,i;null===(t=e.track)||void 0===t||t.off(Co.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.off(Co.Restarted,this.onLocalTrackRestarted),this.emit(fo.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>Ws(this,void 0,void 0,function*(){const t=yield e.getDeviceId(!1),i=Zo(e.source);i&&t&&t!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(t," active"),this.logContext),this.localParticipant.activeDeviceMap.set(i,t),this.emit(fo.ActiveDeviceChanged,i,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(fo.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(fo.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(fo.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(fo.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Zc),e),this.log=qs(null!==(i=this.options.loggerName)&&void 0!==i?i:Us.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Yc),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Xc),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Qc),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Fd,this.outgoingDataStreamManager=new zd(this.engine,this.log),this.disconnectLock=new qe,this.localParticipant=new al("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Fa(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Fa(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",Fa(this.options.audioOutput.deviceId)).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),Ta()){const e=new AbortController;null===(s=navigator.mediaDevices)||void 0===s||s.addEventListener("devicechange",this.handleDeviceChange,{signal:e.signal}),ll.cleanupRegistry&&ll.cleanupRegistry.register(this,()=>{e.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 ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return Ws(this,void 0,void 0,function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity)})}setupE2EE(){var e;const t=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new hc(i,t),this.e2eeManager.on(rc.ParticipantEncryptionStatusChanged,(e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit(fo.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(rc.EncryptionError,(e,t)=>{const i=t?this.getParticipantByIdentity(t):void 0;this.emit(fo.EncryptionError,e,i)}),null===(e=this.e2eeManager)||void 0===e||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}getSid(){return Ws(this,void 0,void 0,function*(){return this.state===il.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise((e,t)=>{const i=t=>{""!==t.sid&&(this.engine.off(ko.RoomUpdate,i),e(t.sid))};this.engine.on(ko.RoomUpdate,i),this.once(fo.Disconnected,()=>{this.engine.off(ko.RoomUpdate,i),t("Room disconnected before room server id was available")})})})}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Md(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(ko.ParticipantUpdate,this.handleParticipantUpdates).on(ko.RoomUpdate,this.handleRoomUpdate).on(ko.SpeakersChanged,this.handleSpeakersChanged).on(ko.StreamStateChanged,this.handleStreamStateUpdate).on(ko.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(ko.SubscriptionError,this.handleSubscriptionError).on(ko.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(ko.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(ko.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(ko.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(ko.DataPacketReceived,this.handleDataPacket).on(ko.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(il.SignalReconnecting)&&this.emit(fo.SignalReconnecting)}).on(ko.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(il.Connected)&&this.emit(fo.Reconnected)}).on(ko.SignalResumed,()=>{this.bufferedEvents=[],(this.state===il.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(ko.Restarting,this.handleRestarting).on(ko.SignalRestarted,this.handleSignalRestarted).on(ko.Offline,()=>{this.setAndEmitConnectionState(il.Reconnecting)&&this.emit(fo.Reconnecting)}).on(ko.DCBufferStatusChanged,(e,t)=>{this.emit(fo.DCBufferStatusChanged,e,t)}).on(ko.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(t=>{let{trackSid:i}=t;return i===e});t?(this.localParticipant.emit(bo.LocalTrackSubscribed,t),this.emitWhenConnected(fo.LocalTrackSubscribed,t,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)}).on(ko.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(fo.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),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&&void 0!==arguments[1])||arguments[1];return gc.getInstance().getDevices(e,t)}prepareConnection(e,t){return Ws(this,void 0,void 0,function*(){if(this.state===il.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Sa(new URL(e))&&t){this.regionUrlProvider=new nd(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===il.Disconnected&&(this.regionUrl=i,yield fetch(Ba(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Ba(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return Ws(this,void 0,void 0,function*(){let i,n=()=>Ws(this,void 0,void 0,function*(){});switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new gs({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new gs({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new gs({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new gs({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=()=>Ws(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new gs({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>Ws(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new gs({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":i=new gs({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>Ws(this,void 0,void 0,function*(){const e=this.engine.client.onLeave;e&&e(new Gn({reason:Mi.CLIENT_INITIATED,action:Jn.RECONNECT}))});break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");i=new gs({scenario:{case:"subscriberBandwidth",value:za(t)}});break;case"leave-full-reconnect":i=new gs({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return Ws(this,arguments,void 0,function(e,t){var i=this;let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var s,r,o,a,c,d,l;let u=!0,h=!1;const p=n?{exact:t}:t;if("audioinput"===e){h=0===i.localParticipant.audioTrackPublications.size;const t=null!==(s=i.getActiveDevice(e))&&void 0!==s?s:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=p;const n=Array.from(i.localParticipant.audioTrackPublications.values()).filter(e=>e.source===aa.Source.Microphone);try{u=(yield Promise.all(n.map(e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(p)}))).every(e=>!0===e)}catch(m){throw i.options.audioCaptureDefaults.deviceId=t,m}const r=n.some(e=>{var t,i;return null!==(i=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==i&&i});u&&r&&(h=!0)}else if("videoinput"===e){h=0===i.localParticipant.videoTrackPublications.size;const t=null!==(r=i.getActiveDevice(e))&&void 0!==r?r:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=p;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter(e=>e.source===aa.Source.Camera);try{u=(yield Promise.all(n.map(e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(p)}))).every(e=>!0===e)}catch(m){throw i.options.videoCaptureDefaults.deviceId=t,m}const s=n.some(e=>{var t,i;return null!==(i=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==i&&i});u&&s&&(h=!0)}else if("audiooutput"===e){if(h=!0,!ga()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");i.options.webAudioMix&&(t=null!==(o=yield gc.getInstance().normalizeDeviceId("audiooutput",t))&&void 0!==o?o:""),null!==(a=(l=i.options).audioOutput)&&void 0!==a||(l.audioOutput={});const n=null!==(c=i.getActiveDevice(e))&&void 0!==c?c:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=t;try{i.options.webAudioMix&&(null===(d=i.audioContext)||void 0===d||d.setSinkId(t)),yield Promise.all(Array.from(i.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(m){throw i.options.audioOutput.deviceId=n,m}}return h&&(i.localParticipant.activeDeviceMap.set(e,t),i.emit(fo.ActiveDeviceChanged,e,t)),u}()})}setupLocalParticipantEvents(){this.localParticipant.on(bo.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(bo.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(bo.AttributesChanged,this.onLocalAttributesChanged).on(bo.TrackMuted,this.onLocalTrackMuted).on(bo.TrackUnmuted,this.onLocalTrackUnmuted).on(bo.LocalTrackPublished,this.onLocalTrackPublished).on(bo.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(bo.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(bo.MediaDevicesError,this.onMediaDevicesError).on(bo.AudioStreamAcquired,this.startAudio).on(bo.ChatMessage,this.onLocalChatMessageSent).on(bo.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===il.Connecting||this.state===il.Reconnecting){const n=()=>{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,i),s()},s=()=>{this.off(fo.Reconnected,n),this.off(fo.Connected,n),this.off(fo.Disconnected,s)};return this.once(fo.Reconnected,n),this.once(fo.Connected,n),void this.once(fo.Disconnected,s)}if(this.state===il.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);if("ended"===e.readyState)return void this.log.info("skipping incoming track as it already ended",this.logContext);const n=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),s=n[0];let r=n[1],o=e.id;if(r&&r.startsWith("TR")&&(o=r),s===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);const a=Array.from(this.remoteParticipants.values()).find(e=>e.sid===s);if(!a)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);if(!o.startsWith("TR")){const e=this.engine.getTrackIdForReceiver(i);if(!e)return void this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(s),this.logContext);o=e}let c;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: ".concat(s,", streamId: ").concat(r,", trackId: ").concat(o),Object.assign(Object.assign({},this.logContext),{rpID:s,streamId:r,trackId:o})),this.options.adaptiveStream&&(c="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});const d=a.addSubscribedMediaTrack(e,o,t,i,c);(null==d?void 0:d.isEncrypted)&&!this.e2eeManager&&this.emit(fo.EncryptionError,new Error("Encrypted ".concat(d.source," track received from participant ").concat(a.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==il.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 i,n,s;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?(null===(i=t.track)||void 0===i||i.detach(),null===(n=t.track)||void 0===n||n.stop()):null===(s=t.track)||void 0===s||s.stopMonitor()}),this.localParticipant.off(bo.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(bo.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(bo.AttributesChanged,this.onLocalAttributesChanged).off(bo.TrackMuted,this.onLocalTrackMuted).off(bo.TrackUnmuted,this.onLocalTrackUnmuted).off(bo.LocalTrackPublished,this.onLocalTrackPublished).off(bo.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(bo.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(bo.MediaDevicesError,this.onMediaDevicesError).off(bo.AudioStreamAcquired,this.startAudio).off(bo.ChatMessage,this.onLocalChatMessageSent).off(bo.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&&"boolean"==typeof this.options.webAudioMix&&(this.audioContext.close(),this.audioContext=void 0),Ta()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(i=navigator.mediaDevices)||void 0===i||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(il.Disconnected),this.emit(fo.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(fo.ParticipantDisconnected,t),t.setDisconnected(),null===(i=this.localParticipant)||void 0===i||i.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,i,n,s,r){return Ws(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),1!==r)return void(yield this.engine.publishRpcResponse(e,t,null,sd.builtIn("UNSUPPORTED_VERSION")));const o=this.rpcHandlers.get(i);if(!o)return void(yield this.engine.publishRpcResponse(e,t,null,sd.builtIn("UNSUPPORTED_METHOD")));let a=null,c=null;try{const r=yield o({requestId:t,callerIdentity:e,payload:n,responseTimeout:s});rd(r)>15360?(a=sd.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):c=r}catch(d){d instanceof sd?a=d:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),d),a=sd.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)})}selectDefaultDevices(){return Ws(this,void 0,void 0,function*(){var e,t,i;const n=gc.getInstance().previousDevices,s=yield gc.getInstance().getDevices(void 0,!1),r=so();if("Chrome"===(null==r?void 0:r.name)&&"iOS"!==r.os)for(let a of s){const e=n.find(e=>e.deviceId===a.deviceId);e&&""!==e.label&&e.kind===a.kind&&e.label!==a.label&&"default"===this.getActiveDevice(a.kind)&&this.emit(fo.ActiveDeviceChanged,a.kind,a.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let a of o){const r=Xo(a),o=this.localParticipant.getTrackPublication(r);if(o&&(null===(e=o.track)||void 0===e?void 0:e.isUserProvided))continue;const c=s.filter(e=>e.kind===a),d=this.getActiveDevice(a);d===(null===(t=n.filter(e=>e.kind===a)[0])||void 0===t?void 0:t.deviceId)&&c.length>0&&(null===(i=c[0])||void 0===i?void 0:i.deviceId)!==d?yield this.switchActiveDevice(a,c[0].deviceId):"audioinput"===a&&!ya()||"videoinput"===a||!(c.length>0)||c.find(e=>e.deviceId===this.getActiveDevice(a))||"audiooutput"===a&&ya()||(yield this.switchActiveDevice(a,c[0].deviceId))}})}acquireAudioContext(){return Ws(this,void 0,void 0,function*(){var e,t;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(e=Yo())&&void 0!==e?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),ua(200)])}catch(n){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:n}))}const i="running"===(null===(t=this.audioContext)||void 0===t?void 0:t.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(fo.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let n;return n=t?dl.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new dl(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),(null===(i=this.options.audioOutput)||void 0===i?void 0:i.deviceId)&&n.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const i=this.remoteParticipants.get(e);if(t){i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity)}return i}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(fo.ParticipantConnected,i),i.on(bo.TrackPublished,e=>{this.emitWhenConnected(fo.TrackPublished,e,i)}).on(bo.TrackSubscribed,(e,t)=>{e.kind===aa.Kind.Audio?(e.on(Co.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(Co.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===aa.Kind.Video&&(e.on(Co.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(Co.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(fo.TrackSubscribed,e,t,i)}).on(bo.TrackUnpublished,e=>{this.emit(fo.TrackUnpublished,e,i)}).on(bo.TrackUnsubscribed,(e,t)=>{this.emit(fo.TrackUnsubscribed,e,t,i)}).on(bo.TrackMuted,e=>{this.emitWhenConnected(fo.TrackMuted,e,i)}).on(bo.TrackUnmuted,e=>{this.emitWhenConnected(fo.TrackUnmuted,e,i)}).on(bo.ParticipantMetadataChanged,e=>{this.emitWhenConnected(fo.ParticipantMetadataChanged,e,i)}).on(bo.ParticipantNameChanged,e=>{this.emitWhenConnected(fo.ParticipantNameChanged,e,i)}).on(bo.AttributesChanged,e=>{this.emitWhenConnected(fo.ParticipantAttributesChanged,e,i)}).on(bo.ConnectionQualityChanged,e=>{this.emitWhenConnected(fo.ConnectionQualityChanged,e,i)}).on(bo.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(fo.ParticipantPermissionsChanged,e,i)}).on(bo.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(fo.TrackSubscriptionStatusChanged,e,t,i)}).on(bo.TrackSubscriptionFailed,(e,t)=>{this.emit(fo.TrackSubscriptionFailed,e,i,t)}).on(bo.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(fo.TrackSubscriptionPermissionChanged,e,t,i)}).on(bo.Active,()=>{this.emitWhenConnected(fo.ParticipantActive,i),i.kind===zi.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&Ya(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Mo.setInterval(()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Mi.STATE_MISMATCH)))},4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&Mo.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.emit(fo.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(this.state===il.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===il.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return Ws(this,void 0,void 0,function*(){var t,i;const n=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new ji({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:dt.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new qi({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(fo.SignalConnected),this.emit(fo.Connected),this.setAndEmitConnectionState(il.Connected),n.video){const e=new sl(aa.Kind.Video,new Gi({source:_i.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ii.AUDIO,name:"video-dummy"}),new Ed(n.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Na(160*(null!==(t=s.aspectRatios[0])&&void 0!==t?t: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(bo.LocalTrackPublished,e)}if(n.audio){const e=new sl(aa.Kind.Audio,new Gi({source:_i.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ii.AUDIO}),new pd(n.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ua(),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(bo.LocalTrackPublished,e)}for(let e=0;e<s.count-1;e+=1){let t=new qi({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:Vi.ACTIVE,tracks:[],joinedAt:dt.parse(Date.now())});const n=this.getOrCreateParticipant(t.identity,t);if(s.video){const r=Na(160*(null!==(i=s.aspectRatios[e%s.aspectRatios.length])&&void 0!==i?i:1),160,!1,!0),o=new Gi({source:_i.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ii.AUDIO});n.addSubscribedMediaTrack(r,o.sid,new MediaStream([r]),new RTCRtpReceiver),t.tracks=[...t.tracks,o]}if(s.audio){const e=Ua(),i=new Gi({source:_i.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ii.AUDIO});n.addSubscribedMediaTrack(e,i.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,i]}n.updateInfo(t)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(e!==fo.ActiveSpeakersChanged&&e!==fo.TranscriptionReceived){const t=ul(i).filter(e=>void 0!==e);e!==fo.TrackSubscribed&&e!==fo.TrackUnsubscribed||this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t}))}return super.emit(e,...i)}}function ul(e){return e.map(e=>{if(e)return Array.isArray(e)?ul(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e})}var hl,pl;ll.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()}),(pl=hl||(hl={}))[pl.IDLE=0]="IDLE",pl[pl.RUNNING=1]="RUNNING",pl[pl.SKIPPED=2]="SKIPPED",pl[pl.SUCCESS=3]="SUCCESS",pl[pl.FAILED=4]="FAILED";Ys.EventEmitter;Ys.EventEmitter;function ml(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}new TextEncoder,new TextDecoder;class gl extends Error{constructor(e,t){var i;super(e,t),ml(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(i=Error.captureStackTrace)||void 0===i||i.call(Error,this,this.constructor)}}ml(gl,"code","ERR_JOSE_GENERIC");ml(class extends gl{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:n,payload:t}}),ml(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),ml(this,"claim",void 0),ml(this,"reason",void 0),ml(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED");ml(class extends gl{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:n,payload:t}}),ml(this,"code","ERR_JWT_EXPIRED"),ml(this,"claim",void 0),ml(this,"reason",void 0),ml(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}},"code","ERR_JWT_EXPIRED");ml(class extends gl{constructor(){super(...arguments),ml(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED");ml(class extends gl{constructor(){super(...arguments),ml(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED");ml(class extends gl{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),ml(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED");ml(class extends gl{constructor(){super(...arguments),ml(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID");ml(class extends gl{constructor(){super(...arguments),ml(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID");ml(class extends gl{constructor(){super(...arguments),ml(this,"code","ERR_JWT_INVALID")}},"code","ERR_JWT_INVALID");ml(class extends gl{constructor(){super(...arguments),ml(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID");ml(class extends gl{constructor(){super(...arguments),ml(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID");ml(class extends gl{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"no applicable key found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),ml(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY");ml(class extends gl{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"multiple matching keys found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),ml(this,Symbol.asyncIterator,void 0),ml(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");ml(class extends gl{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),ml(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT");ml(class extends gl{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),ml(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");class fl{constructor(){this.room=null,this.wrapper=null}async connect(e,t,i){if(e&&t){console.log("[LiveKit] Connecting with wrapper:",i),this.wrapper=i,this.room=new ll({adaptiveStream:!0,dynacast:!0,videoCaptureDefaults:{resolution:zo.h720.resolution}}),this.bindEvents();try{await this.room.connect(e,t),console.log("[LiveKit] Connected to room:",this.room.name),await this.publishLocalTracks()}catch(n){console.error("[LiveKit] Connection failed:",n)}}else console.error("[LiveKit] Missing url or token")}bindEvents(){this.room&&this.room.on(fo.SignalConnected,()=>{console.log("[LiveKit] Signal connected")}).on(fo.TrackSubscribed,(e,t,i)=>{this.handleTrackSubscribed(e,i)}).on(fo.TrackUnsubscribed,(e,t,i)=>{this.handleTrackUnsubscribed(e,i)}).on(fo.Disconnected,()=>{console.log("[LiveKit] Disconnected")}).on(fo.MediaDevicesError,e=>{console.error("[LiveKit] Media Device Error:",e)})}async publishLocalTracks(){const e=this.wrapper.querySelector(".td-pip");try{await this.room.localParticipant.setCameraEnabled(!0);const t=Array.from(this.room.localParticipant.videoTrackPublications.values()).find(e=>"camera"===e.source);if(t&&t.track&&e){e.innerHTML="",e.style.backgroundImage="none";const i=t.track.attach();i.style.width="100%",i.style.height="100%",i.style.objectFit="cover",i.style.transform="scale(-1, 1)",e.appendChild(i),console.log("[LiveKit] Local video attached")}}catch(t){console.error("[LiveKit] Failed to enable Camera:",t),"NotAllowedError"===t.name&&alert("Không thể mở Camera. Hãy kiểm tra icon ổ khóa trên thanh địa chỉ hoặc cài đặt Quyền Riêng Tư (Privacy) của máy tính.")}try{const e=await ll.getLocalDevices("audioinput");console.log("[LiveKit] Audio Input Devices:",e),0===e.length&&alert("Không tìm thấy Micro nào trên thiết bị của bạn!"),await this.room.localParticipant.setMicrophoneEnabled(!0)}catch(t){console.error("[LiveKit] Failed to enable Microphone:",t),"NotAllowedError"===t.name&&alert("Không thể mở Micro. Cuộc gọi sẽ không có tiếng.")}}handleTrackSubscribed(e,t){if(console.log("[LiveKit] Track subscribed:",e.kind,t.identity),"video"===e.kind){const t=this.wrapper.querySelector(".td-main-video");if(console.log("[LiveKit] Looking for remote container (.td-main-video):",t),t){t.style.backgroundImage="none",t.innerHTML="";const i=e.attach();i.style.width="100%",i.style.height="100%",i.style.objectFit="cover",t.appendChild(i),console.log("[LiveKit] Remote video attached")}else console.warn("[LiveKit] Remote container not found!")}if("audio"===e.kind){const t=e.attach();document.body.appendChild(t),console.log("[LiveKit] Remote audio attached")}}handleTrackUnsubscribed(e,t){e.detach().forEach(e=>e.remove())}disconnect(){this.room&&(this.room.disconnect(),this.room=null)}}class vl{constructor(e={}){this.config=e,this.api=new d(e),this.container=null,this.shadowRoot=null,this.unsubscribe=null,this.ws=null,this.socket=null,this.livekit=null}async init(){var s;this.mount(),this.unsubscribe=c.on(e,this.handleStateChange.bind(this)),c.setState({status:i});try{const e=await this.api.init(this.config.widgetId);e.success?(c.setState({config:e.data,storeId:this.config.storeId,orgId:this.config.orgId,productId:this.config.productId,doctor:{...e.data.doctor,id:this.config.doctorId||(null==(s=e.data.doctor)?void 0:s.id)},status:n}),this.checkInlineTrigger(),this.startSocket()):c.setState({status:t,error:"Init failed"})}catch(bl){console.error("Widget Init Error:",bl),c.setState({status:t,error:bl.message})}}mount(){if(document.getElementById("clinic-widget-host"))return;this.container=document.createElement("div"),this.container.id="clinic-widget-host",this.container.style.position="fixed",this.container.style.zIndex="2147483647",this.container.style.bottom="0",this.container.style.right="0",document.body.appendChild(this.container),this.shadowRoot=this.container.attachShadow({mode:"open"});const e="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0&display=swap";if(!document.querySelector(`link[href="${e}"]`)){const t=document.createElement("link");t.rel="stylesheet",t.href=e,document.head.appendChild(t)}const t=document.createElement("link");t.rel="stylesheet",t.href=e;const i=document.createElement("style");i.textContent=':host{--td-primary: #0e65f1;--td-primary-hover: #0b50c0;--td-bg-light: #ffffff;--td-bg-dark: #1a202c;--td-text-main: #0d131c;--td-text-sub: #49699c;--td-border: #e7ecf4;--td-success: #22c55e;--td-danger: #ef4444;--font-family: "Inter", system-ui, -apple-system, sans-serif;--z-index: 9999;font-family:var(--font-family);color:var(--td-text-main)}*{box-sizing:border-box;margin:0;padding:0}.hidden{display:none!important}.material-symbols-outlined{font-family:Material Symbols Outlined;font-weight:400;font-style:normal;font-size:24px;line-height:1;letter-spacing:normal;text-transform:none;display:inline-block;white-space:nowrap;word-wrap:normal;direction:ltr}.td-widget-fab{position:fixed;bottom:24px;right:24px;display:flex;align-items:center;gap:12px;z-index:var(--z-index);cursor:pointer;font-family:var(--font-family)}.td-fab-card{background:var(--td-bg-light);border:1px solid var(--td-border);border-radius:12px;box-shadow:0 8px 30px #0000001f;display:flex;align-items:center;padding:6px 16px 6px 6px;transition:transform .2s ease,box-shadow .2s ease;max-width:320px;position:relative;overflow:hidden}.td-fab-card:hover{transform:translateY(-4px);box-shadow:0 20px 40px #00000026}.td-avatar-container{width:64px;height:64px;border-radius:8px;overflow:hidden;position:relative;flex-shrink:0}.td-avatar{width:100%;height:100%;background-size:cover;background-position:center}.td-status-dot{position:absolute;bottom:4px;right:4px;width:14px;height:14px;background:var(--td-success);border:2px solid #fff;border-radius:50%}.td-info{margin-left:12px;display:flex;flex-direction:column}.td-brand{display:flex;align-items:center;gap:4px;font-size:10px;font-weight:700;text-transform:uppercase;color:var(--td-primary);letter-spacing:.05em}.td-cta{font-size:15px;font-weight:700;color:var(--td-text-main);margin-top:2px}.td-sub{font-size:12px;color:var(--td-text-sub);margin-top:2px}.td-close-fab{position:absolute;top:4px;right:4px;opacity:0;cursor:pointer;background:none;border:none;color:#94a3b8;transition:opacity .2s;padding:4px}.td-fab-card:hover .td-close-fab{opacity:1}.td-widget-expanded{position:fixed;bottom:100px;right:24px;width:380px;max-height:80vh;background:var(--td-bg-light);border-radius:12px;box-shadow:0 25px 50px -12px #00000040;border:1px solid var(--td-border);display:flex;flex-direction:column;overflow:hidden;z-index:var(--z-index);animation:slideUp .3s cubic-bezier(.16,1,.3,1)}@keyframes slideUp{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}.td-header{display:flex;align-items:center;justify-content:space-between;padding:16px;border-bottom:1px solid var(--td-border)}.td-header-title{display:flex;align-items:center;gap:12px;font-weight:700;font-size:18px}.td-icon-box{width:32px;height:32px;background:#0e65f11a;color:var(--td-primary);border-radius:8px;display:flex;align-items:center;justify-content:center}.td-close-btn{background:transparent;border:none;cursor:pointer;color:#64748b;padding:4px;border-radius:50%;display:flex;align-items:center;justify-content:center}.td-close-btn:hover{background:#f1f5f9}.td-content{flex:1;overflow-y:auto;padding:0}.td-doctor-profile{display:flex;flex-direction:column;align-items:center;padding:32px 24px 24px}.td-online-badge{display:inline-flex;align-items:center;gap:6px;padding:4px 12px;background:#f0fdf4;border:1px solid #dcfce7;border-radius:999px}.td-pulse{width:8px;height:8px;background:var(--td-success);border-radius:50%}.td-badge-text{font-size:12px;font-weight:600;color:#15803d;text-transform:uppercase}.td-trust-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;padding:0 24px 24px}.td-trust-item{background:#f8f9fc;border:1px solid var(--td-border);border-radius:12px;padding:12px;text-align:center;display:flex;flex-direction:column;align-items:center;gap:8px}.td-trust-title{font-size:12px;font-weight:700}.td-actions{padding:0 24px 24px;display:flex;flex-direction:column;gap:12px}.td-btn{width:100%;height:48px;border-radius:8px;font-size:16px;font-weight:700;display:flex;align-items:center;justify-content:center;cursor:pointer;transition:all .2s;border:none}.td-btn-primary{background:var(--td-primary);color:#fff;box-shadow:0 10px 15px -3px #0e65f133}.td-btn-primary:hover{background:var(--td-primary-hover)}.td-btn-outline{background:transparent;border:1px solid var(--td-border);color:var(--td-text-main);font-size:14px}.td-btn-outline:hover{background:#f8f9fc}.td-footer{padding:12px;text-align:center;background:#f8f9fc;border-top:1px solid var(--td-border);font-size:12px;color:var(--td-text-sub)}.td-consultation-modal{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);width:90vw;height:90vh;max-width:1200px;max-height:800px;background:var(--td-bg-light);border-radius:16px;box-shadow:0 25px 50px -12px #00000080;border:1px solid var(--td-border);display:flex;overflow:hidden;z-index:var(--z-index);animation:fadeIn .3s ease-out}@keyframes fadeIn{0%{opacity:0;transform:translate(-50%,-48%)}to{opacity:1;transform:translate(-50%,-50%)}}.td-video-panel{flex:1;background:#000;position:relative;display:flex;align-items:center;justify-content:center;overflow:hidden}.td-main-video{width:100%;height:100%;background-size:cover;background-position:center}.td-overlay{position:absolute;top:0;right:0;bottom:0;left:0;background:linear-gradient(to bottom,rgba(0,0,0,.3),transparent,rgba(0,0,0,.6))}.td-video-header{position:absolute;top:16px;left:16px;right:16px;display:flex;justify-content:space-between;z-index:10}.td-badge-glass{background:#0006;-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);padding:6px 12px;border-radius:20px;display:flex;align-items:center;gap:8px;color:#fff;font-size:12px;font-weight:500}.td-pip{position:absolute;top:24px;right:24px;width:160px;aspect-ratio:16/9;background:#333;border-radius:8px;border:2px solid rgba(255,255,255,.2);overflow:hidden;z-index:20;background-size:cover;background-position:center;box-shadow:0 4px 6px #0000004d}.td-pip-label{position:absolute;bottom:4px;left:4px;background:#0009;color:#fff;font-size:10px;padding:2px 6px;border-radius:4px}.td-controls{position:absolute;bottom:32px;left:50%;transform:translate(-50%);display:flex;align-items:center;gap:16px;z-index:20}.td-ctrl-btn{width:48px;height:48px;border-radius:50%;background:#fff3;-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);border:none;color:#fff;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all .2s}.td-ctrl-btn:hover{background:#fff;color:var(--td-primary)}.td-ctrl-end{height:48px;padding:0 24px;border-radius:24px;background:var(--td-danger);color:#fff;display:flex;align-items:center;gap:8px;font-weight:600;border:none;cursor:pointer}.td-ctrl-end:hover{background:#dc2626}.td-chat-panel{width:400px;background:var(--td-bg-light);border-left:1px solid var(--td-border);display:flex;flex-direction:column}.td-chat-header{padding:16px;border-bottom:1px solid var(--td-border)}.td-chat-doc-info{display:flex;gap:12px;align-items:center;margin-bottom:12px}.td-chat-avatar{width:48px;height:48px;border-radius:50%;background-size:cover;background-position:center}.td-chat-timer{background:#f8f9fc;padding:8px 12px;border-radius:8px;display:flex;justify-content:space-between;align-items:center}.td-timer-val{font-family:monospace;font-weight:700;font-size:16px}.td-chat-messages{flex:1;overflow-y:auto;padding:16px;background:#f8f9fc;display:flex;flex-direction:column;gap:16px}.td-msg-system{text-align:center;font-size:12px;color:var(--td-text-sub);background:#e2e8f0;padding:4px 12px;border-radius:12px;align-self:center;max-width:90%}.td-msg-row{display:flex;gap:8px}.td-msg-row.own{flex-direction:row-reverse}.td-msg-bubble{padding:10px 14px;border-radius:12px;font-size:14px;line-height:1.5;max-width:85%}.td-msg-row.doctor .td-msg-bubble{background:#fff;border:1px solid var(--td-border);border-top-left-radius:2px}.td-msg-row.own .td-msg-bubble{background:#e0f2fe;color:var(--td-text-main);border:1px solid #bae6fd;border-top-right-radius:2px}.td-msg-time{font-size:10px;color:var(--td-text-sub);margin-top:2px}.td-chat-input-area{padding:16px;border-top:1px solid var(--td-border);background:var(--td-bg-light)}.td-input-wrapper{display:flex;gap:8px;align-items:flex-end}.td-chat-input{flex:1;border:1px solid var(--td-border);border-radius:8px;padding:10px;font-family:inherit;font-size:14px;resize:none;height:48px}.td-send-btn{width:48px;height:48px;background:var(--td-primary);color:#fff;border:none;border-radius:8px;cursor:pointer;display:flex;align-items:center;justify-content:center}.td-send-btn:hover{background:var(--td-primary-hover)}@media (max-width: 768px){.td-consultation-modal{width:100vw;height:100vh;border-radius:0;flex-direction:column}.td-video-panel{height:40vh}.td-chat-panel{width:100%;flex:1}}.td-form-container{display:flex;flex-direction:column;height:100%;padding:0 24px}.td-form-page-header{padding:24px 0 16px}.td-form-title{font-size:24px;font-weight:700;color:var(--td-text-main);margin-bottom:8px}.td-form-desc{font-size:14px;color:var(--td-text-sub);line-height:normal}.td-form{display:flex;flex-direction:column;gap:20px;padding-bottom:24px}.td-input-group{display:flex;flex-direction:column;gap:8px}.td-label{font-size:14px;font-weight:500;color:var(--td-text-main)}.td-input{width:100%;height:48px;padding:0 16px;border-radius:8px;border:1px solid var(--td-border);background:#f8f9fc;font-family:inherit;font-size:16px;color:var(--td-text-main);transition:all .2s}.td-input:focus{outline:none;border-color:var(--td-primary);box-shadow:0 0 0 2px #0e65f133}.td-textarea{width:100%;min-height:100px;padding:16px;border-radius:8px;border:1px solid var(--td-border);background:#f8f9fc;font-family:inherit;font-size:16px;color:var(--td-text-main);resize:none}.td-textarea:focus{outline:none;border-color:var(--td-primary)}.td-chips-group{display:flex;flex-wrap:wrap;gap:8px}.td-chip{padding:8px 16px;border-radius:99px;font-size:14px;font-weight:500;cursor:pointer;border:1px solid var(--td-border);background:#fff;color:var(--td-text-sub);transition:all .2s}.td-chip:hover{border-color:var(--td-primary);color:var(--td-primary);background:#0e65f10d}.td-chip.active{border-color:var(--td-primary);background:#0e65f11a;color:var(--td-primary);display:flex;align-items:center;gap:6px}.td-secure-note{display:flex;align-items:center;justify-content:center;gap:6px;font-size:12px;color:var(--td-text-sub);opacity:.8;margin-top:8px}.td-summary-container{display:flex;flex-direction:column;height:100%}.td-success-header{display:flex;flex-direction:column;align-items:center;padding:32px 24px;text-align:center}.td-success-icon{width:80px;height:80px;background:#0e65f11a;color:var(--td-primary);border-radius:50%;display:flex;align-items:center;justify-content:center;margin-bottom:16px}.td-summary-title{font-size:24px;font-weight:700;margin-bottom:8px}.td-summary-desc{font-size:14px;color:var(--td-text-sub);max-width:360px;margin:0 auto}.td-summary-card{margin:0 24px;padding:16px;border-radius:12px;border:1px solid var(--td-border);background:#f8f9fc;display:flex;align-items:center;gap:16px}.td-summary-details{padding:8px 24px}.td-detail-row{display:flex;justify-content:space-between;padding:12px 0;border-bottom:1px dashed var(--td-border);font-size:14px}.td-note-box{margin:16px 24px;padding:16px;background:#0e65f10d;border:1px solid rgba(14,101,241,.1);border-radius:8px}.td-note-title{font-size:14px;font-weight:700;margin-bottom:8px;display:flex;align-items:center;gap:8px}.td-grid-actions{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:12px}',this.shadowRoot.appendChild(t),this.shadowRoot.appendChild(i)}handleStateChange({prev:e,current:t}){e.status!==t.status&&this.render(t.status)}render(e){const t=this.shadowRoot.querySelector(".td-widget-content");t&&t.remove();const i=document.createElement("div");i.className="td-widget-content";const d=c.getState();switch(e){case n:i.innerHTML=h('<div class="td-widget-fab" id="td-widget-fab">\n <div class="td-fab-card">\n <button class="td-close-fab" id="td-fab-close">\n <span class="material-symbols-outlined" style="font-size: 16px;">close</span>\n </button>\n <div class="td-avatar-container">\n <div class="td-avatar" style="background-image: url(\'{{doctorAvatar}}\');"></div>\n <div class="td-status-dot" style="background: #22c55e;"></div>\n </div>\n <div class="td-info">\n <div class="td-brand">\n <span class="material-symbols-outlined" style="font-size: 14px;">local_hospital</span>\n <span>Clinic</span>\n </div>\n <h3 class="td-cta">Khám online ngay</h3>\n <p class="td-sub">Bác sĩ đang Online</p>\n </div>\n </div>\n</div>',d);break;case s:i.innerHTML=(e=>h('<div class="td-widget-expanded" id="td-widget-expanded">\n <header class="td-header">\n <div class="td-header-title">\n <div class="td-icon-box">\n <span class="material-symbols-outlined">medical_services</span>\n </div>\n <span>Clinic</span>\n </div>\n <button class="td-close-btn" id="td-expanded-close">\n <span class="material-symbols-outlined">close</span>\n </button>\n </header>\n\n <div class="td-content">\n <div class="td-doctor-profile">\n <div class="td-doctor-avatar" style="background-image: url(\'{{doctorAvatar}}\');">\n <div class="td-status-dot"\n style="width: 20px; height: 20px; border-width: 3px; bottom: 4px; right: 4px; background: #22c55e;">\n </div>\n </div>\n <h1 class="td-doctor-name">{{doctorName}}</h1>\n <p class="td-doctor-specialty">{{doctorSpecialty}}</p>\n\n <div class="td-online-badge">\n <span class="td-pulse"></span>\n <span class="td-badge-text">Đang trực tuyến</span>\n </div>\n </div>\n\n <div class="td-trust-grid">\n <div class="td-trust-item">\n <div class="td-icon-box">\n <span class="material-symbols-outlined">verified</span>\n </div>\n <h3 class="td-trust-title">Bác sĩ được xác thực</h3>\n </div>\n <div class="td-trust-item">\n <div class="td-icon-box">\n <span class="material-symbols-outlined">security</span>\n </div>\n <h3 class="td-trust-title">Bảo mật thông tin</h3>\n </div>\n </div>\n\n <div class="td-actions">\n <button class="td-btn td-btn-primary" id="td-btn-consult">\n <span class="material-symbols-outlined" style="margin-right: 8px;">videocam</span>\n Bắt đầu tư vấn ngay\n </button>\n <button class="td-btn td-btn-outline" id="td-btn-schedule">\n Đặt lịch hẹn sau\n </button>\n </div>\n </div>\n\n <div class="td-footer">\n Powered by <b>Clinic Connect</b>\n </div>\n</div>',e))(d);break;case r:i.innerHTML=(e=>h('<div class="td-widget-expanded" id="td-patient-form">\n <header class="td-header">\n <div class="td-header-title">\n <div class="td-icon-box">\n <span class="material-symbols-outlined">medical_services</span>\n </div>\n <span>Clinic</span>\n </div>\n <button class="td-close-btn" id="td-form-close">\n <span class="material-symbols-outlined">close</span>\n </button>\n </header>\n\n <div class="td-content">\n <div class="td-form-container">\n <div class="td-form-page-header">\n <h1 class="td-form-title">Kết nối với Bác sĩ</h1>\n <p class="td-form-desc">Vui lòng nhập thông tin để bắt đầu tư vấn trực tuyến.</p>\n </div>\n\n <form class="td-form" id="td-info-form">\n <div class="td-input-group">\n <label class="td-label">Họ và tên</label>\n <input type="text" class="td-input" name="name" placeholder="VD: Nguyễn Văn A" required />\n </div>\n\n <div class="td-input-group">\n <label class="td-label">Số điện thoại</label>\n <div style="position: relative;">\n <input type="tel" class="td-input" name="phone" placeholder="VD: 0912 345 678" required />\n <div\n style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); color: var(--td-primary);">\n <span class="material-symbols-outlined" style="font-size: 20px;">smartphone</span>\n </div>\n </div>\n </div>\n\n <div class="td-input-group">\n <label class="td-label">Triệu chứng của bạn?</label>\n <div class="td-chips-group">\n <button type="button" class="td-chip active">Sốt <span class="material-symbols-outlined"\n style="font-size: 16px;">check</span></button>\n <button type="button" class="td-chip">Ho / Cảm cúm</button>\n <button type="button" class="td-chip">Đau đầu</button>\n <button type="button" class="td-chip">Đau bụng</button>\n </div>\n </div>\n\n <div class="td-input-group">\n <label class="td-label">Mô tả thêm <span style="color: var(--td-text-sub); font-weight: 400;">(Tùy\n chọn)</span></label>\n <textarea class="td-textarea" name="symptoms"\n placeholder="Bạn đang cảm thấy như thế nào?"></textarea>\n </div>\n\n <div style="margin-top: 8px;">\n <button type="submit" class="td-btn td-btn-primary" id="td-form-submit">\n Bắt đầu tư vấn\n <span class="material-symbols-outlined" style="margin-left: 8px;">arrow_forward</span>\n </button>\n </div>\n\n <div class="td-secure-note">\n <span class="material-symbols-outlined" style="font-size: 14px;">lock</span>\n Thông tin y tế được bảo mật 100%\n </div>\n </form>\n </div>\n </div>\n</div>',e))(d);break;case o:i.innerHTML=(e=>h('<div class="td-consultation-modal">\n \x3c!-- Left: Video Panel --\x3e\n <div class="td-video-panel">\n <div class="td-main-video"\n style="background-image: url(\'https://lh3.googleusercontent.com/aida-public/AB6AXuC54B68xwAiOWZFQNVMIVKNBTKwo-nPCTsEgkaekhx9PbGDRCwcy18cFeALhbiaeOyaIS88c9RZst2sRWUyKTeSif-HqEfgU5Aoht-mk6Tjtuts2M4XmoMaxNSAi7qjKoQRYx61I4MolGfjCkxRN0lW5rlSlQfMwY0T8K1440SLM9hW_4u0N1Vg6kQTcSUitouGRmWktBHr-yH5QTu78AC1IOZLd5-HyWw0NUb6uESPpNZoZHoIEKIjFhsGBnCRmzHCUP9Ex6mP0XvW\');">\n </div>\n <div class="td-overlay"></div>\n\n <div class="td-video-header">\n <div class="td-badge-glass">\n <span class="material-symbols-outlined"\n style="color: #ef4444; font-size: 16px;">radio_button_checked</span>\n REC\n </div>\n <div class="td-badge-glass">\n <span class="material-symbols-outlined" style="font-size: 16px;">signal_cellular_alt</span>\n HD Quality\n </div>\n </div>\n\n <div class="td-pip"\n style="background-image: url(\'https://lh3.googleusercontent.com/aida-public/AB6AXuDnITTxxwp-J6t7xkVqnh6C9NPQS8i_k6_4F4IfzTfDM_ZgdX2HRvc947W1BU0LJYKOAA8qtHglPXseoj0Vk4sLfoRnKDOz88bUmK_ytSEvP_oYeeDKGRCfcEa6ugQO6aKR2l9W8glr63dswTODHe4am5IB3FRknTxNnZ0XuDU0z1xzkDMGpspRrXWwdoi8j9teleBeRsmkCdSe8dVb0q1r5eS8YjQ-nzo5f3qBB2-Eo9zyegUSaOCXhuaqSmqpVyICmTLvoIppbKNo\');">\n <span class="td-pip-label">You</span>\n </div>\n\n <div class="td-controls">\n <button class="td-ctrl-btn">\n <span class="material-symbols-outlined">mic</span>\n </button>\n <button class="td-ctrl-btn">\n <span class="material-symbols-outlined">videocam</span>\n </button>\n <button class="td-ctrl-end" id="td-consult-end">\n <span class="material-symbols-outlined">call_end</span>\n Kết thúc\n </button>\n <button class="td-ctrl-btn">\n <span class="material-symbols-outlined">settings</span>\n </button>\n </div>\n </div>\n\n \x3c!-- Right: Chat Panel --\x3e\n <div class="td-chat-panel">\n <div class="td-chat-header">\n <div class="td-chat-doc-info">\n <div class="td-chat-avatar" style="background-image: url(\'{{doctorAvatar}}\');"></div>\n <div>\n <h3 style="font-size: 16px; font-weight: 700;">{{doctorName}}</h3>\n <p style="font-size: 12px; color: var(--td-text-sub);">Online • Verified</p>\n </div>\n </div>\n <div class="td-chat-timer">\n <div style="display: flex; align-items: center; gap: 4px; font-size: 12px;">\n <span class="material-symbols-outlined"\n style="font-size: 16px; color: var(--td-primary);">timer</span>\n SESSION\n </div>\n <div class="td-timer-val">00:03:12</div>\n </div>\n </div>\n\n <div class="td-chat-messages">\n <div class="td-msg-system">\n Consultation started\n </div>\n <div class="td-msg-row doctor">\n <div class="td-msg-bubble">\n Xin chào. Tôi có thể giúp gì cho bạn hôm nay?\n <div class="td-msg-time">14:01</div>\n </div>\n </div>\n <div class="td-msg-row own">\n <div class="td-msg-bubble">\n Chào bác sĩ, tôi bị đau đầu...\n <div class="td-msg-time">14:02</div>\n </div>\n </div>\n </div>\n\n <div class="td-chat-input-area">\n <div class="td-input-wrapper">\n <textarea class="td-chat-input" placeholder="Nhập tin nhắn..."></textarea>\n <button class="td-send-btn">\n <span class="material-symbols-outlined">send</span>\n </button>\n </div>\n <div style="text-align: center; margin-top: 8px; font-size: 10px; color: var(--td-text-sub);">\n <span class="material-symbols-outlined" style="font-size: 10px; vertical-align: middle;">lock</span>\n Mã hóa đầu cuối\n </div>\n </div>\n </div>\n</div>',e))(d);break;case a:i.innerHTML=(e=>h('<div class="td-widget-expanded" id="td-summary-view">\n <header class="td-header">\n <h2 class="td-header-title" style="font-size: 16px;">Tổng kết tư vấn</h2>\n <button class="td-close-btn" id="td-summary-close">\n <span class="material-symbols-outlined">close</span>\n </button>\n </header>\n\n <div class="td-content">\n <div class="td-summary-container">\n <div class="td-success-header">\n <div class="td-success-icon">\n <span class="material-symbols-outlined" style="font-size: 48px;">check_circle</span>\n </div>\n <h3 class="td-summary-title">Tư vấn Hoàn tất</h3>\n <p class="td-summary-desc">Cuộc hẹn đã được ghi nhận vào hồ sơ sức khỏe của bạn.</p>\n </div>\n\n <div class="td-summary-card">\n <div class="td-chat-avatar"\n style="background-image: url(\'{{doctorAvatar}}\'); width: 56px; height: 56px;"></div>\n <div>\n <div style="font-weight: 700;">{{doctorName}}</div>\n <div style="color: var(--td-text-sub); font-size: 14px;">{{doctorSpecialty}}</div>\n </div>\n <div style="margin-left: auto; color: var(--td-primary);">\n <span class="material-symbols-outlined">verified_user</span>\n </div>\n </div>\n\n <div class="td-summary-details">\n <div class="td-detail-row">\n <span style="color: var(--td-text-sub); display: flex; gap: 6px;">\n <span class="material-symbols-outlined" style="font-size: 18px;">tag</span> Mã tư vấn\n </span>\n <span style="font-weight: 600;">#TD-93821</span>\n </div>\n <div class="td-detail-row">\n <span style="color: var(--td-text-sub); display: flex; gap: 6px;">\n <span class="material-symbols-outlined" style="font-size: 18px;">schedule</span> Thời gian\n </span>\n <span style="font-weight: 600;">10:00 AM, Today</span>\n </div>\n </div>\n\n <div class="td-note-box">\n <div class="td-note-title">\n <span class="material-symbols-outlined"\n style="font-size: 16px; color: var(--td-primary);">clinical_notes</span>\n Ghi chú bác sĩ\n </div>\n <p style="font-size: 14px; line-height: 1.5;">Bệnh nhân cần nghỉ ngơi và uống nhiều nước. Hạn chế vận\n động mạnh trong 2 ngày tới.</p>\n </div>\n\n <div class="td-actions">\n <div class="td-grid-actions">\n <button class="td-btn td-btn-outline" style="font-size: 12px; height: 40px; margin-bottom: 0;">\n Xem kết luận\n </button>\n <button class="td-btn td-btn-outline" style="font-size: 12px; height: 40px; margin-bottom: 0;">\n Tải đơn thuốc\n </button>\n </div>\n <button class="td-btn td-btn-primary">\n <span class="material-symbols-outlined" style="margin-right: 8px;">calendar_month</span>\n Đặt lịch tái khám\n </button>\n </div>\n </div>\n </div>\n</div>',e))(d);break;default:return}this.shadowRoot.appendChild(i),this.bindEvents(e)}bindEvents(e){if(e===n){const e=this.shadowRoot.getElementById("td-widget-fab"),t=this.shadowRoot.getElementById("td-fab-close");e&&e.addEventListener("click",e=>{e.composedPath().includes(t)||c.setState({status:s})}),t&&t.addEventListener("click",e=>{e.stopPropagation(),this.destroy()})}else if(e===s){const e=this.shadowRoot.getElementById("td-expanded-close"),t=this.shadowRoot.getElementById("td-btn-consult");e&&e.addEventListener("click",()=>{c.setState({status:n})}),t&&t.addEventListener("click",()=>{c.setState({status:r})})}else if(e===r){const e=this.shadowRoot.getElementById("td-form-close"),t=this.shadowRoot.getElementById("td-info-form");e&&e.addEventListener("click",()=>{c.setState({status:s})}),t&&t.addEventListener("submit",e=>{e.preventDefault();const i=new FormData(t),n=i.get("name"),s=i.get("phone");this.triggerCallback("onConsultationStarted",{name:n,phone:s}),c.setState({user:{name:n,phone:s},status:o})})}else if(e===o){this.joinVideoCall();const e=this.shadowRoot.getElementById("td-consult-end");e&&e.addEventListener("click",()=>{this.stopSocket(),c.setState({status:a})});const t=this.shadowRoot.querySelector(".td-send-btn"),i=this.shadowRoot.querySelector(".td-chat-input"),n=()=>{const e=i.value.trim();e&&(this.appendChatMessage(e,"own"),i.value="")};t&&t.addEventListener("click",n),i&&i.addEventListener("keypress",e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),n())})}else if(e===a){const e=this.shadowRoot.getElementById("td-summary-close");e&&e.addEventListener("click",()=>{c.setState({status:n})})}}triggerCallback(e,t){var i;"function"==typeof(null==(i=window.Clinic)?void 0:i[e])&&window.Clinic[e](t)}destroy(){this.container&&this.container.remove(),this.unsubscribe&&this.unsubscribe(),this.socket&&this.stopSocket(),this.livekit&&this.livekit.disconnect()}checkInlineTrigger(){const e=c.getState(),t=this.config.triggerElementId;if(t){const i=document.getElementById(t);if(i){i.innerHTML=h('<style>\n @keyframes td-pulse-animation {\n 0% {\n box-shadow: 0 0 0 0 rgba(34, 197, 94, 0.4);\n }\n\n 70% {\n box-shadow: 0 0 0 6px rgba(34, 197, 94, 0);\n }\n\n 100% {\n box-shadow: 0 0 0 0 rgba(34, 197, 94, 0);\n }\n }\n\n .td-inline-container {\n display: flex;\n flex-direction: column;\n padding: 14px;\n background: #f8faff;\n border: 1px solid #e2e8f0;\n border-radius: 10px;\n font-family: system-ui, -apple-system, sans-serif;\n }\n\n .td-inline-row {\n display: flex;\n align-items: center;\n gap: 12px;\n }\n\n .td-inline-footer {\n display: flex;\n align-items: center;\n justify-content: space-between;\n margin-top: 14px;\n padding-top: 12px;\n border-top: 1px solid #e5e7eb;\n }\n\n .td-inline-status {\n display: flex;\n align-items: center;\n gap: 8px;\n }\n\n .td-inline-pulse {\n width: 8px;\n height: 8px;\n background: #22c55e;\n border-radius: 50%;\n animation: td-pulse-animation 2s infinite;\n }\n\n .td-inline-text {\n color: #16a34a;\n font-weight: 600;\n font-size: 13px;\n }\n</style>\n<div class="td-inline-container">\n \x3c!-- Top: Doctor Info --\x3e\n <div class="td-inline-row">\n <div\n style="width: 48px; height: 48px; border-radius: 50%; background-image: url(\'{{doctorAvatar}}\'); background-size: cover; background-position: center; flex-shrink: 0; background-color: #e5e7eb; border: 2px solid white; box-shadow: 0 2px 4px rgba(0,0,0,0.05);">\n </div>\n <div style="flex: 1; min-width: 0;">\n <div\n style="font-weight: 700; font-size: 15px; color: #1f2937; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">\n {{doctorName}}</div>\n <div\n style="font-size: 13px; color: #6b7280; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">\n {{doctorSpecialty}}</div>\n </div>\n </div>\n\n \x3c!-- Bottom: Status & Action --\x3e\n <div class="td-inline-footer">\n <div class="td-inline-status">\n <span class="td-inline-pulse"></span>\n <span class="td-inline-text">Bác sĩ đang Online</span>\n </div>\n\n <button id="td-inline-btn" style="\n background: #0066ff; \n color: white; \n border: none; \n padding: 8px 16px; \n border-radius: 6px; \n font-weight: 600; \n font-size: 13px; \n cursor: pointer; \n display: flex; \n align-items: center; \n gap: 6px;\n white-space: nowrap;\n transition: all 0.2s;\n box-shadow: 0 2px 5px rgba(0,102,255,0.2);\n " onmouseover="this.style.background=\'#0052cc\'" onmouseout="this.style.background=\'#0066ff\'">\n <span class="material-symbols-outlined" style="font-size: 18px;">videocam</span>\n Tư vấn ngay\n </button>\n </div>\n</div>',e);const t=i.querySelector("#td-inline-btn");t&&t.addEventListener("click",()=>{c.setState({status:r})})}else console.warn(`Clinic Widget: Target element "${t}" not found.`)}}startSocket(){const e=c.getState(),t=e.config.socketUrl||l,{user:i,doctor:n}=e;this.socket||(this.socket=new Ue(t),this.socket.connect(()=>{console.log("Socket connected, registering...");this.socket.emit("register",{userId:"20.183299.4158",userName:(null==i?void 0:i.name)||"Guest",role:"customer"})}),this.socket.on("users-online",e=>{var t;console.log("[Widget] Received users-online event:",e);const i=Array.isArray(e)&&Array.isArray(e[0])?e[0]:e,n=null==(t=c.getState().doctor)?void 0:t.id;if(console.log("[Widget] Current Doctor ID (Config):",n),n&&Array.isArray(i)){const e=i.find(e=>{var t;return String(e.userId)===String(n)&&"DOCTOR"===(null==(t=e.role)?void 0:t.toUpperCase())}),t=!!e;console.log("[Widget] Doctor Status:",t?"Online":"Offline","Doctor Entry:",e),c.setState({doctorOnline:t})}}),this.socket.on("customer:token",e=>{if(console.log("Received token from server:",e),e.token){this.livekit||(this.livekit=new fl);const t=this.shadowRoot.querySelector(".td-consultation-modal");t?(console.log("[Widget] LiveKit Params:",{url:u,token:e.token}),this.livekit.connect(u,e.token,t)):console.error("Consultation modal not found for video rendering")}}))}joinVideoCall(){const e=c.getState(),{user:t,doctor:i}=e,n="20.183299.4158";this.socket?(console.log("Joining video call room with user:",null==t?void 0:t.name),this.socket.emit("register",{userId:n,userName:null==t?void 0:t.name,role:"customer"}),this.socket.emit("customer:join",{participantId:n,participantName:t.name,doctorId:i.id,type:"video"})):console.error("Socket not connected, cannot join video call")}appendChatMessage(e,t){const i=this.shadowRoot.querySelector(".td-chat-messages");if(!i)return;const n=document.createElement("div");n.className=`td-msg-row ${t}`;const s=document.createElement("div");s.className="td-msg-bubble",s.textContent=e;const r=document.createElement("div");r.className="td-msg-time";const o=new Date;r.textContent=`${o.getHours()}:${String(o.getMinutes()).padStart(2,"0")}`,s.appendChild(r),n.appendChild(s),i.appendChild(n),i.scrollTop=i.scrollHeight}stopSocket(){this.socket&&(this.socket.disconnect(),this.socket=null)}}!function(){const e=document.querySelector("script[data-widget-id]"),t=e?e.getAttribute("data-widget-id"):null,i=e?e.getAttribute("data-trigger-element-id"):null,n=e&&e.getAttribute("data-locale")||"vi",s=e&&e.getAttribute("data-store-id")||"longvan-store",r=e&&e.getAttribute("data-org-id")||"longvan-org",o=e&&e.getAttribute("data-doctor-id")||"20.184041.6561",a=e&&e.getAttribute("data-product-id")||"product-1",c={widgetId:t,triggerElementId:i,locale:n,storeId:s,orgId:r,doctorId:o,productId:a,scriptElement:e};function d(){if(!t)return void console.warn("Clinic Widget: No widget-id provided.");const e=new vl(c);window.Clinic=window.Clinic||{},window.Clinic.instance=e,e.init(),window.Clinic.onReady&&window.Clinic.onReady()}"complete"===document.readyState||"interactive"===document.readyState?setTimeout(d,1):document.addEventListener("DOMContentLoaded",d)}()});
1
+ !function(e){"function"==typeof define&&define.amd?define(e):e()}(function(){"use strict";const e="state_change",t="idle",i="loading",n="collapsed",s="expanded",r="patient_form",o="in_consultation",a="completed";const c=new class{constructor(){this.state={status:t,config:{},doctor:null,error:null},this.listeners={}}on(e,t){return this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t),()=>{this.listeners[e]=this.listeners[e].filter(e=>e!==t)}}emit(e,t){this.listeners[e]&&this.listeners[e].forEach(e=>e(t))}setState(t){const i={...this.state};this.state={...this.state,...t},this.emit(e,{prev:i,current:this.state})}getState(){return this.state}};class d{constructor(e){this.config=e}async init(e){return await this.delay(800),{success:!0,data:{clinicName:"Clinic Connect",primaryColor:"#0088cc",features:{videoCall:!0,chat:!0},doctor:{id:"dr_123",name:"Bác sĩ Hà Ngọc Mạnh",specialty:"Nam học - Hiếm muộn",avatarUrl:"https://lh3.googleusercontent.com/aida-public/AB6AXuB5Sne8e7ofIffcXSZ2rXx-XLji_xce_THhR0QnJYMAyov2Tf7BdAYsPQErsdCgvbL-M2AITXy5G9gjGab-hp97I8n_eMI2LMcZ3qGBUBwThyW2fySOfpjUnB7j5ZDnIxqb2NcZZSMCgeaJexvyoKOfoUUlZGKWODkKo4NcnJNiS96NOBKBNij35vrE3YTu0XHB_SSbSqcyRraDHbVVLMnyy1cEjepd9ATN0bxVxGhjbVGDsCi6Kn4Ok7XYWDBLijGDcabxunrvylAg",isOnline:!0}}}}delay(e){return new Promise(t=>setTimeout(t,e))}}const l="wss://call-server.longvan.vn",u="wss://livekit.longvan.vn",h=(e,t)=>{var i,n,s;let r=e;const o=(null==(i=t.doctor)?void 0:i.name)||"Bác sĩ Hà Ngọc Mạnh",a=(null==(n=t.doctor)?void 0:n.specialty)||"Nam học - Hiếm muộn",c=(null==(s=t.doctor)?void 0:s.avatarUrl)||"";return r=r.replace(/{{doctorName}}/g,o),r=r.replace(/{{doctorSpecialty}}/g,a),r=r.replace(/{{doctorAvatar}}/g,c),r},p=Object.create(null);p.open="0",p.close="1",p.ping="2",p.pong="3",p.message="4",p.upgrade="5",p.noop="6";const m=Object.create(null);Object.keys(p).forEach(e=>{m[p[e]]=e});const g={type:"error",data:"parser error"},f="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),v="function"==typeof ArrayBuffer,b=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,y=({type:e,data:t},i,n)=>f&&t instanceof Blob?i?n(t):k(t,n):v&&(t instanceof ArrayBuffer||b(t))?i?n(t):k(new Blob([t]),n):n(p[e]+(t||"")),k=(e,t)=>{const i=new FileReader;return i.onload=function(){const e=i.result.split(",")[1];t("b"+(e||""))},i.readAsDataURL(e)};function T(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let C;const S="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",w="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let yl=0;yl<64;yl++)w[S.charCodeAt(yl)]=yl;const E="function"==typeof ArrayBuffer,R=(e,t)=>{if("string"!=typeof e)return{type:"message",data:x(e,t)};const i=e.charAt(0);if("b"===i)return{type:"message",data:P(e.substring(1),t)};return m[i]?e.length>1?{type:m[i],data:e.substring(1)}:{type:m[i]}:g},P=(e,t)=>{if(E){const i=(e=>{let t,i,n,s,r,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const d=new ArrayBuffer(o),l=new Uint8Array(d);for(t=0;t<a;t+=4)i=w[e.charCodeAt(t)],n=w[e.charCodeAt(t+1)],s=w[e.charCodeAt(t+2)],r=w[e.charCodeAt(t+3)],l[c++]=i<<2|n>>4,l[c++]=(15&n)<<4|s>>2,l[c++]=(3&s)<<6|63&r;return d})(e);return x(i,t)}return{base64:!0,data:e}},x=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,I=String.fromCharCode(30);function _(){return new TransformStream({transform(e,t){!function(e,t){f&&e.data instanceof Blob?e.data.arrayBuffer().then(T).then(t):v&&(e.data instanceof ArrayBuffer||b(e.data))?t(T(e.data)):y(e,!1,e=>{C||(C=new TextEncoder),t(C.encode(e))})}(e,i=>{const n=i.length;let s;if(n<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,n);else if(n<65536){s=new Uint8Array(3);const e=new DataView(s.buffer);e.setUint8(0,126),e.setUint16(1,n)}else{s=new Uint8Array(9);const e=new DataView(s.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(n))}e.data&&"string"!=typeof e.data&&(s[0]|=128),t.enqueue(s),t.enqueue(i)})}})}let O;function D(e){return e.reduce((e,t)=>e+t.length,0)}function A(e,t){if(e[0].length===t)return e.shift();const i=new Uint8Array(t);let n=0;for(let s=0;s<t;s++)i[s]=e[0][n++],n===e[0].length&&(e.shift(),n=0);return e.length&&n<e[0].length&&(e[0]=e[0].slice(n)),i}function M(e){if(e)return function(e){for(var t in M.prototype)e[t]=M.prototype[t];return e}(e)}M.prototype.on=M.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},M.prototype.once=function(e,t){function i(){this.off(e,i),t.apply(this,arguments)}return i.fn=t,this.on(e,i),this},M.prototype.off=M.prototype.removeListener=M.prototype.removeAllListeners=M.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var i,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var s=0;s<n.length;s++)if((i=n[s])===t||i.fn===t){n.splice(s,1);break}return 0===n.length&&delete this._callbacks["$"+e],this},M.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),i=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(i){n=0;for(var s=(i=i.slice(0)).length;n<s;++n)i[n].apply(this,t)}return this},M.prototype.emitReserved=M.prototype.emit,M.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},M.prototype.hasListeners=function(e){return!!this.listeners(e).length};const N="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),L="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function U(e,...t){return t.reduce((t,i)=>(e.hasOwnProperty(i)&&(t[i]=e[i]),t),{})}const j=L.setTimeout,F=L.clearTimeout;function B(e,t){t.useNativeTimers?(e.setTimeoutFn=j.bind(L),e.clearTimeoutFn=F.bind(L)):(e.setTimeoutFn=L.setTimeout.bind(L),e.clearTimeoutFn=L.clearTimeout.bind(L))}function q(e){return"string"==typeof e?function(e){let t=0,i=0;for(let n=0,s=e.length;n<s;n++)t=e.charCodeAt(n),t<128?i+=1:t<2048?i+=2:t<55296||t>=57344?i+=3:(n++,i+=4);return i}(e):Math.ceil(1.33*(e.byteLength||e.size))}function V(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class z extends Error{constructor(e,t,i){super(e),this.description=t,this.context=i,this.type="TransportError"}}class H extends M{constructor(e){super(),this.writable=!1,B(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,i){return super.emitReserved("error",new z(e,t,i)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=R(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(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let i in e)e.hasOwnProperty(i)&&(t.length&&(t+="&"),t+=encodeURIComponent(i)+"="+encodeURIComponent(e[i]));return t}(e);return t.length?"?"+t:""}}class W extends H{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const 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){((e,t)=>{const i=e.split(I),n=[];for(let s=0;s<i.length;s++){const e=R(i[s],t);if(n.push(e),"error"===e.type)break}return n})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const i=e.length,n=new Array(i);let s=0;e.forEach((e,r)=>{y(e,!1,e=>{n[r]=e,++s===i&&t(n.join(I))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=V()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let K=!1;try{K="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(bl){}const G=K;function J(){}class Q extends W{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let i=location.port;i||(i=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||i!==e.port}}doWrite(e,t){const i=this.request({method:"POST",data:e});i.on("success",t),i.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const 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}}class Y extends M{constructor(e,t,i){super(),this.createRequest=e,B(this,i),this._opts=i,this._method=i.method||"GET",this._uri=t,this._data=void 0!==i.data?i.data:null,this._create()}_create(){var e;const t=U(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const i=this._xhr=this.createRequest(t);try{i.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&i.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(n){}if("POST"===this._method)try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(n){}try{i.setRequestHeader("Accept","*/*")}catch(n){}null===(e=this._opts.cookieJar)||void 0===e||e.addCookies(i),"withCredentials"in i&&(i.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(i.timeout=this._opts.requestTimeout),i.onreadystatechange=()=>{var e;3===i.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(i.getResponseHeader("set-cookie"))),4===i.readyState&&(200===i.status||1223===i.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof i.status?i.status:0)},0))},i.send(this._data)}catch(n){return void this.setTimeoutFn(()=>{this._onError(n)},0)}"undefined"!=typeof document&&(this._index=Y.requestsCount++,Y.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=J,e)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete Y.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(Y.requestsCount=0,Y.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",X);else if("function"==typeof addEventListener){addEventListener("onpagehide"in L?"pagehide":"unload",X,!1)}function X(){for(let e in Y.requests)Y.requests.hasOwnProperty(e)&&Y.requests[e].abort()}const Z=function(){const e=$({xdomain:!1});return e&&null!==e.responseType}();function $(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||G))return new XMLHttpRequest}catch(i){}if(!t)try{return new(L[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(i){}}const ee="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class te extends H{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,i=ee?{}:U(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(i.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,i)}catch(bl){return this.emitReserved("error",bl)}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++){const i=e[t],n=t===e.length-1;y(i,this.supportsBinary,e=>{try{this.doWrite(i,e)}catch(t){}n&&N(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=V()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const ie=L.WebSocket||L.MozWebSocket;const ne={websocket:class extends te{createSocket(e,t,i){return ee?new ie(e,t,i):t?new ie(e,t):new ie(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends H{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(bl){return this.emitReserved("error",bl)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=function(e,t){O||(O=new TextDecoder);const i=[];let n=0,s=-1,r=!1;return new TransformStream({transform(o,a){for(i.push(o);;){if(0===n){if(D(i)<1)break;const e=A(i,1);r=!(128&~e[0]),s=127&e[0],n=s<126?3:126===s?1:2}else if(1===n){if(D(i)<2)break;const e=A(i,2);s=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),n=3}else if(2===n){if(D(i)<8)break;const e=A(i,8),t=new DataView(e.buffer,e.byteOffset,e.length),r=t.getUint32(0);if(r>Math.pow(2,21)-1){a.enqueue(g);break}s=r*Math.pow(2,32)+t.getUint32(4),n=3}else{if(D(i)<s)break;const e=A(i,s);a.enqueue(R(r?e:O.decode(e),t)),n=0}if(0===s||s>e){a.enqueue(g);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=e.readable.pipeThrough(t).getReader(),n=_();n.readable.pipeTo(e.writable),this._writer=n.writable.getWriter();const s=()=>{i.read().then(({done:e,value:t})=>{e||(this.onPacket(t),s())}).catch(e=>{})};s();const r={type:"open"};this.query.sid&&(r.data=`{"sid":"${this.query.sid}"}`),this._writer.write(r).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const i=e[t],n=t===e.length-1;this._writer.write(i).then(()=>{n&&N(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends Q{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Z&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Y($,this.uri(),e)}}},se=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,re=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function oe(e){if(e.length>8e3)throw"URI too long";const t=e,i=e.indexOf("["),n=e.indexOf("]");-1!=i&&-1!=n&&(e=e.substring(0,i)+e.substring(i,n).replace(/:/g,";")+e.substring(n,e.length));let s=se.exec(e||""),r={},o=14;for(;o--;)r[re[o]]=s[o]||"";return-1!=i&&-1!=n&&(r.source=t,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=function(e,t){const i=/\/{2,9}/g,n=t.replace(i,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1);"/"==t.slice(-1)&&n.splice(n.length-1,1);return n}(0,r.path),r.queryKey=function(e,t){const i={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,n){t&&(i[t]=n)}),i}(0,r.query),r}const ae="function"==typeof addEventListener&&"function"==typeof removeEventListener,ce=[];ae&&addEventListener("offline",()=>{ce.forEach(e=>e())},!1);class de extends M{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const i=oe(e);t.hostname=i.host,t.secure="https"===i.protocol||"wss"===i.protocol,t.port=i.port,i.query&&(t.query=i.query)}else t.host&&(t.hostname=oe(t.host).host);B(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{const 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?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},i=e.split("&");for(let n=0,s=i.length;n<s;n++){let e=i[n].split("=");t[decodeURIComponent(e[0])]=decodeURIComponent(e[1])}return t}(this.opts.query)),ae&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},ce.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const i=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](i)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&de.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}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",de.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)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":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}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(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const 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,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const i=this.writeBuffer[t].data;if(i&&(e+=q(i)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,N(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,i){return this._sendPacket("message",e,t,i),this}send(e,t,i){return this._sendPacket("message",e,t,i),this}_sendPacket(e,t,i,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof i&&(n=i,i=null),"closing"===this.readyState||"closed"===this.readyState)return;(i=i||{}).compress=!1!==i.compress;const s={type:e,data:t,options:i};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),n&&this.once("flush",n),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},i=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?i():e()}):this.upgrading?i():e()),this}_onError(e){if(de.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),ae&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=ce.indexOf(this._offlineEventListener);-1!==e&&ce.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}de.protocol=4;class le extends de{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),i=!1;de.priorWebsocketSuccess=!1;const n=()=>{i||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!i)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;de.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{i||"closed"!==this.readyState&&(d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function s(){i||(i=!0,d(),t.close(),t=null)}const r=e=>{const i=new Error("probe error: "+e);i.transport=t.name,s(),this.emitReserved("upgradeError",i)};function o(){r("transport closed")}function a(){r("socket closed")}function c(e){t&&e.name!==t.name&&s()}const d=()=>{t.removeListener("open",n),t.removeListener("error",r),t.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};t.once("open",n),t.once("error",r),t.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{i||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let i=0;i<e.length;i++)~this.transports.indexOf(e[i])&&t.push(e[i]);return t}}let ue=class extends le{constructor(e,t={}){const i="object"==typeof e?e:t;(!i.transports||i.transports&&"string"==typeof i.transports[0])&&(i.transports=(i.transports||["polling","websocket","webtransport"]).map(e=>ne[e]).filter(e=>!!e)),super(e,i)}};const he="function"==typeof ArrayBuffer,pe=Object.prototype.toString,me="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===pe.call(Blob),ge="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===pe.call(File);function fe(e){return he&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||me&&e instanceof Blob||ge&&e instanceof File}function ve(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,i=e.length;t<i;t++)if(ve(e[t]))return!0;return!1}if(fe(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return ve(e.toJSON(),!0);for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)&&ve(e[i]))return!0;return!1}function be(e){const t=[],i=e.data,n=e;return n.data=ye(i,t),n.attachments=t.length,{packet:n,buffers:t}}function ye(e,t){if(!e)return e;if(fe(e)){const i={_placeholder:!0,num:t.length};return t.push(e),i}if(Array.isArray(e)){const i=new Array(e.length);for(let n=0;n<e.length;n++)i[n]=ye(e[n],t);return i}if("object"==typeof e&&!(e instanceof Date)){const i={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(i[n]=ye(e[n],t));return i}return e}function ke(e,t){return e.data=Te(e.data,t),delete e.attachments,e}function Te(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let i=0;i<e.length;i++)e[i]=Te(e[i],t);else if("object"==typeof e)for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(e[i]=Te(e[i],t));return e}const Ce=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Se,we;(we=Se||(Se={}))[we.CONNECT=0]="CONNECT",we[we.DISCONNECT=1]="DISCONNECT",we[we.EVENT=2]="EVENT",we[we.ACK=3]="ACK",we[we.CONNECT_ERROR=4]="CONNECT_ERROR",we[we.BINARY_EVENT=5]="BINARY_EVENT",we[we.BINARY_ACK=6]="BINARY_ACK";class Ee extends M{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const i=t.type===Se.BINARY_EVENT;i||t.type===Se.BINARY_ACK?(t.type=i?Se.EVENT:Se.ACK,this.reconstructor=new Re(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!fe(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const i={type:Number(e.charAt(0))};if(void 0===Se[i.type])throw new Error("unknown packet type "+i.type);if(i.type===Se.BINARY_EVENT||i.type===Se.BINARY_ACK){const n=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const s=e.substring(n,t);if(s!=Number(s)||"-"!==e.charAt(t))throw new Error("Illegal attachments");i.attachments=Number(s)}if("/"===e.charAt(t+1)){const n=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}i.nsp=e.substring(n,t)}else i.nsp="/";const n=e.charAt(t+1);if(""!==n&&Number(n)==n){const n=t+1;for(;++t;){const i=e.charAt(t);if(null==i||Number(i)!=i){--t;break}if(t===e.length)break}i.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){const n=this.tryParse(e.substr(t));if(!Ee.isPayloadValid(i.type,n))throw new Error("invalid payload");i.data=n}return i}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(t){return!1}}static isPayloadValid(e,t){switch(e){case Se.CONNECT:return xe(t);case Se.DISCONNECT:return void 0===t;case Se.CONNECT_ERROR:return"string"==typeof t||xe(t);case Se.EVENT:case Se.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Ce.indexOf(t[0]));case Se.ACK:case Se.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Re{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=ke(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Pe=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function xe(e){return"[object Object]"===Object.prototype.toString.call(e)}const Ie=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Ee,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Se.EVENT&&e.type!==Se.ACK||!ve(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Se.EVENT?Se.BINARY_EVENT:Se.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Se.BINARY_EVENT&&e.type!==Se.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=be(e),i=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(i),n}},get PacketType(){return Se},isPacketValid:function(e){return"string"==typeof e.nsp&&(void 0===(t=e.id)||Pe(t))&&function(e,t){switch(e){case Se.CONNECT:return void 0===t||xe(t);case Se.DISCONNECT:return void 0===t;case Se.EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Ce.indexOf(t[0]));case Se.ACK:return Array.isArray(t);case Se.CONNECT_ERROR:return"string"==typeof t||xe(t);default:return!1}}(e.type,e.data);var t},protocol:5},Symbol.toStringTag,{value:"Module"}));function _e(e,t,i){return e.on(t,i),function(){e.off(t,i)}}const Oe=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class De extends M{constructor(e,t,i){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,i&&i.auth&&(this.auth=i.auth),this._opts=Object.assign({},i),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[_e(e,"open",this.onopen.bind(this)),_e(e,"packet",this.onpacket.bind(this)),_e(e,"error",this.onerror.bind(this)),_e(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var i,n,s;if(Oe.hasOwnProperty(e))throw new 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;const r={type:Se.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,i=t.pop();this._registerAckCallback(e,i),r.id=e}const o=null===(n=null===(i=this.io.engine)||void 0===i?void 0:i.transport)||void 0===n?void 0:n.writable,a=this.connected&&!(null===(s=this.io.engine)||void 0===s?void 0:s._hasPingExpired());return this.flags.volatile&&!o||(a?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,t){var i;const n=null!==(i=this.flags.timeout)&&void 0!==i?i:this._opts.ackTimeout;if(void 0===n)return void(this.acks[e]=t);const s=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,new Error("operation has timed out"))},n),r=(...e)=>{this.io.clearTimeoutFn(s),t.apply(this,e)};r.withError=!0,this.acks[e]=r}emitWithAck(e,...t){return new Promise((i,n)=>{const s=(e,t)=>e?n(e):i(t);s.withError=!0,t.push(s),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const i={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...n)=>{this._queue[0];return null!==e?i.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...n)),i.pending=!1,this._drainQueue()}),this._queue.push(i),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const 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(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Se.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)){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Se.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new 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 Se.EVENT:case Se.BINARY_EVENT:this.onevent(e);break;case Se.ACK:case Se.BINARY_ACK:this.onack(e);break;case Se.DISCONNECT:this.ondisconnect();break;case Se.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&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){const t=this._anyListeners.slice();for(const i of t)i.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let i=!1;return function(...n){i||(i=!0,t.packet({type:Se.ACK,id:e,data:n}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(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()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Se.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){const t=this._anyListeners;for(let i=0;i<t.length;i++)if(e===t[i])return t.splice(i,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){const t=this._anyOutgoingListeners;for(let i=0;i<t.length;i++)if(e===t[i])return t.splice(i,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const i of t)i.apply(this,e.data)}}}function Ae(e){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}Ae.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),i=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+i:e-i}return 0|Math.min(e,this.max)},Ae.prototype.reset=function(){this.attempts=0},Ae.prototype.setMin=function(e){this.ms=e},Ae.prototype.setMax=function(e){this.max=e},Ae.prototype.setJitter=function(e){this.jitter=e};class Me extends M{constructor(e,t){var i;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,B(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(i=t.randomizationFactor)&&void 0!==i?i:.5),this.backoff=new Ae({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const n=t.parser||Ie;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new ue(this.uri,this.opts);const t=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;const n=_e(t,"open",function(){i.onopen(),e&&e()}),s=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},r=_e(t,"error",s);if(!1!==this._timeout){const e=this._timeout,i=this.setTimeoutFn(()=>{n(),s(new Error("timeout")),t.close()},e);this.opts.autoUnref&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}return this.subs.push(n),this.subs.push(r),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(_e(e,"ping",this.onping.bind(this)),_e(e,"data",this.ondata.bind(this)),_e(e,"error",this.onerror.bind(this)),_e(e,"close",this.onclose.bind(this)),_e(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){N(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let i=this.nsps[e];return i?this._autoConnect&&!i.active&&i.connect():(i=new De(this,e,t),this.nsps[e]=i),i}_destroy(e){const t=Object.keys(this.nsps);for(const i of t){if(this.nsps[i].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let i=0;i<t.length;i++)this.engine.write(t[i],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 i;this.cleanup(),null===(i=this.engine)||void 0===i||i.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;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const i=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&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const Ne={};function Le(e,t){"object"==typeof e&&(t=e,e=void 0);const i=function(e,t="",i){let n=e;i=i||"undefined"!=typeof location&&location,null==e&&(e=i.protocol+"//"+i.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?i.protocol+e:i.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==i?i.protocol+"//"+e:"https://"+e),n=oe(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const s=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+s+":"+n.port+t,n.href=n.protocol+"://"+s+(i&&i.port===n.port?"":":"+n.port),n}(e,(t=t||{}).path||"/socket.io"),n=i.source,s=i.id,r=i.path,o=Ne[s]&&r in Ne[s].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new Me(n,t):(Ne[s]||(Ne[s]=new Me(n,t)),a=Ne[s]),i.query&&!t.query&&(t.query=i.queryKey),a.socket(i.path,t)}Object.assign(Le,{Manager:Me,Socket:De,io:Le,connect:Le});class Ue{constructor(e){this.url=e,this.socket=null}connect(e){this.socket||(this.socket=Le(this.url,{transports:["websocket"],reconnection:!0}),this.socket.on("connect",()=>{console.log("[Socket.IO] connected:",this.socket.id),e&&e()}),this.socket.on("disconnect",e=>{console.log("[Socket.IO] disconnected:",e)}),this.socket.on("connect_error",e=>{console.error("[Socket.IO] error:",e)}),this.socket.onAny((e,...t)=>{console.log(`[Socket.IO] event: ${e}`,t)}))}emit(e,t){this.socket?this.socket.emit(e,t):console.warn("[Socket.IO] not connected")}on(e,t){this.socket&&this.socket.on(e,t)}disconnect(){this.socket&&(this.socket.disconnect(),this.socket=null)}}function je(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(e)}var Fe=Object.defineProperty,Be=(e,t,i)=>((e,t,i)=>t in e?Fe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class qe{constructor(){Be(this,"_locking"),Be(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise(t=>e=()=>{this._locks-=1,t()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function Ve(e,t){if(!e)throw new Error(t)}function ze(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function He(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function We(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}const Ke=Symbol("@bufbuild/protobuf/enum-type");function Ge(e){const t=e[Ke];return Ve(t,"missing enum type on enum object"),t}function Je(e,t,i,n){e[Ke]=Qe(t,i.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function Qe(e,t,i){const n=Object.create(null),s=Object.create(null),r=[];for(const o of t){const e=Xe(o);r.push(e),n[o.name]=e,s[o.no]=e}return{typeName:e,values:r,findName:e=>n[e],findNumber:e=>s[e]}}function Ye(e,t,i){const n={};for(const s of t){const e=Xe(s);n[e.localName]=e.no,n[e.no]=e.localName}return Je(n,e,t),n}function Xe(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class Ze{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){const i=this.getType(),n=i.runtime.json,s=n.makeReadOptions(t);return n.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(n){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(n instanceof Error?n.message:String(n)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){const t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function $e(){let e=0,t=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(e|=(127&i)<<n,!(128&i))return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,!(128&i))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(t|=(127&i)<<n,!(128&i))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function et(e,t,i){for(let r=0;r<28;r+=7){const n=e>>>r,s=!(n>>>7==0&&0==t),o=255&(s?128|n:n);if(i.push(o),!s)return}const n=e>>>28&15|(7&t)<<4,s=!!(t>>3);if(i.push(255&(s?128|n:n)),s){for(let e=3;e<31;e+=7){const n=t>>>e,s=!(n>>>7==0),r=255&(s?128|n:n);if(i.push(r),!s)return}i.push(t>>>31&1)}}const tt=4294967296;function it(e){const t="-"===e[0];t&&(e=e.slice(1));const i=1e6;let n=0,s=0;function r(t,r){const o=Number(e.slice(t,r));s*=i,n=n*i+o,n>=tt&&(s+=n/tt|0,n%=tt)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),t?rt(n,s):st(n,s)}function nt(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(tt*t+e);const i=16777215&(e>>>24|t<<8),n=t>>16&65535;let s=(16777215&e)+6777216*i+6710656*n,r=i+8147497*n,o=2*n;const a=1e7;return s>=a&&(r+=Math.floor(s/a),s%=a),r>=a&&(o+=Math.floor(r/a),r%=a),o.toString()+ot(r)+ot(s)}function st(e,t){return{lo:0|e,hi:0|t}}function rt(e,t){return t=~t,e?e=1+~e:t+=1,st(e,t)}const ot=e=>{const t=String(e);return"0000000".slice(t.length)+t};function at(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let i=0;i<9;i++)t.push(127&e|128),e>>=7;t.push(1)}}function ct(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let i=5;128&e&&i<10;i++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const dt=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw new Error("int64 invalid: ".concat(e));return n},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>s||t<n)throw new Error("uint64 invalid: ".concat(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,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}const t=e=>Ve(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>Ve(/^[0-9]+$/.test(e),"uint64 invalid: ".concat(e));return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),t(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),i(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),it(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),it(e)),dec:(e,t)=>function(e,t){let i=st(e,t);const n=2147483648&i.hi;n&&(i=rt(i.lo,i.hi));const s=nt(i.lo,i.hi);return n?"-"+s:s}(e,t),uDec:(e,t)=>nt(e,t)}}();var lt,ut,ht,pt,mt,gt;function ft(e,t,i){if(t===i)return!0;if(e==lt.BYTES){if(!(t instanceof Uint8Array&&i instanceof Uint8Array))return!1;if(t.length!==i.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==i[e])return!1;return!0}switch(e){case lt.UINT64:case lt.FIXED64:case lt.INT64:case lt.SFIXED64:case lt.SINT64:return t==i}return!1}function vt(e,t){switch(e){case lt.BOOL:return!1;case lt.UINT64:case lt.FIXED64:case lt.INT64:case lt.SFIXED64:case lt.SINT64:return 0==t?dt.zero:"0";case lt.DOUBLE:case lt.FLOAT:return 0;case lt.BYTES:return new Uint8Array(0);case lt.STRING:return"";default:return 0}}function bt(e,t){switch(e){case lt.BOOL:return!1===t;case lt.STRING:return""===t;case lt.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}(ut=lt||(lt={}))[ut.DOUBLE=1]="DOUBLE",ut[ut.FLOAT=2]="FLOAT",ut[ut.INT64=3]="INT64",ut[ut.UINT64=4]="UINT64",ut[ut.INT32=5]="INT32",ut[ut.FIXED64=6]="FIXED64",ut[ut.FIXED32=7]="FIXED32",ut[ut.BOOL=8]="BOOL",ut[ut.STRING=9]="STRING",ut[ut.BYTES=12]="BYTES",ut[ut.UINT32=13]="UINT32",ut[ut.SFIXED32=15]="SFIXED32",ut[ut.SFIXED64=16]="SFIXED64",ut[ut.SINT32=17]="SINT32",ut[ut.SINT64=18]="SINT64",(pt=ht||(ht={}))[pt.BIGINT=0]="BIGINT",pt[pt.STRING=1]="STRING",(gt=mt||(mt={}))[gt.Varint=0]="Varint",gt[gt.Bit64=1]="Bit64",gt[gt.LengthDelimited=2]="LengthDelimited",gt[gt.StartGroup=3]="StartGroup",gt[gt.EndGroup=4]="EndGroup",gt[gt.Bit32=5]="Bit32";class yt{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let n=0;n<this.chunks.length;n++)e+=this.chunks[n].length;let t=new Uint8Array(e),i=0;for(let n=0;n<this.chunks.length;n++)t.set(this.chunks[n],i),i+=this.chunks[n].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 new 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(He(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return ze(e),at(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){We(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){He(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){ze(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return ze(e),at(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=dt.enc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=dt.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=dt.enc(e);return et(t.lo,t.hi,this.buf),this}sint64(e){let t=dt.enc(e),i=t.hi>>31;return et(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=dt.uEnc(e);return et(t.lo,t.hi,this.buf),this}}class kt{constructor(e,t){this.varint64=$e,this.uint32=ct,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=7&e;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case mt.Varint:for(;128&this.buf[this.pos++];);break;case mt.Bit64:this.pos+=4;case mt.Bit32:this.pos+=4;break;case mt.LengthDelimited:let i=this.uint32();this.pos+=i;break;case mt.StartGroup:for(;;){const[e,i]=this.tag();if(i===mt.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(i,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return dt.dec(...this.varint64())}uint64(){return dt.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,dt.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return dt.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return dt.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 Tt(e){const t=e.field.localName,i=Object.create(null);return i[t]=function(e){const t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return vt(t.T,t.L);case"message":const e=t.T,i=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let Ct="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),St=[];for(let yl=0;yl<Ct.length;yl++)St[Ct[yl].charCodeAt(0)]=yl;St["-".charCodeAt(0)]=Ct.indexOf("+"),St["_".charCodeAt(0)]=Ct.indexOf("/");const wt={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i,n=new Uint8Array(t),s=0,r=0,o=0;for(let a=0;a<e.length;a++){if(i=St[e.charCodeAt(a)],void 0===i)switch(e[a]){case"=":r=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=i,r=1;break;case 1:n[s++]=o<<2|(48&i)>>4,o=i,r=2;break;case 2:n[s++]=(15&o)<<4|(60&i)>>2,o=i,r=3;break;case 3:n[s++]=(3&o)<<6|i,r=0}}if(1==r)throw Error("invalid base64 string.");return n.subarray(0,s)},enc(e){let t,i="",n=0,s=0;for(let r=0;r<e.length;r++)switch(t=e[r],n){case 0:i+=Ct[t>>2],s=(3&t)<<4,n=1;break;case 1:i+=Ct[s|t>>4],s=(15&t)<<2,n=2;break;case 2:i+=Ct[s|t>>6],i+=Ct[63&t],n=0}return n&&(i+=Ct[s],i+="=",1==n&&(i+="=")),i}};function Et(e,t,i){xt(t,e);const n=t.runtime.bin.makeReadOptions(i),s=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let i=e.length-1;i>=0;--i)if(e[i].no==t.no)return[e[i]];return[]}return e.filter(e=>e.no===t.no)}(e.getType().runtime.bin.listUnknownFields(e),t.field),[r,o]=Tt(t);for(const a of s)t.runtime.bin.readField(r,n.readerFactory(a.data),t.field,a.wireType,n);return o()}function Rt(e,t,i,n){xt(t,e);const s=t.runtime.bin.makeReadOptions(n),r=t.runtime.bin.makeWriteOptions(n);if(Pt(e,t)){const i=e.getType().runtime.bin.listUnknownFields(e).filter(e=>e.no!=t.field.no);e.getType().runtime.bin.discardUnknownFields(e);for(const t of i)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const o=r.writerFactory();let a=t.field;a.opt||a.repeated||"enum"!=a.kind&&"scalar"!=a.kind||(a=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(a,i,o,r);const c=s.readerFactory(o.finish());for(;c.pos<c.len;){const[t,i]=c.tag(),n=c.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}function Pt(e,t){const i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find(e=>e.no==t.field.no)}function xt(e,t){Ve(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function It(e,t){const i=e.localName;if(e.repeated)return t[i].length>0;if(e.oneof)return t[e.oneof.localName].case===i;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?void 0!==t[i]:"enum"==e.kind?t[i]!==e.T.values[0].no:!bt(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function _t(e,t){const i=e.localName,n=!e.opt&&!e.req;if(e.repeated)t[i]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[i]={};break;case"enum":t[i]=n?e.T.values[0].no:void 0;break;case"scalar":t[i]=n?vt(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function Ot(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(Ze.prototype).every(t=>t in e&&"function"==typeof e[t]))return!1;const i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function Dt(e,t){return Ot(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}lt.DOUBLE,lt.FLOAT,lt.INT64,lt.UINT64,lt.INT32,lt.UINT32,lt.BOOL,lt.STRING,lt.BYTES;const At={ignoreUnknownFields:!1},Mt={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Nt(e){return e?Object.assign(Object.assign({},At),e):At}function Lt(e){return e?Object.assign(Object.assign({},Mt),e):Mt}const Ut=Symbol(),jt=Symbol();function Ft(e){if(null===e)return"null";switch(typeof e){case"object":return Array.isArray(e)?"array":"object";case"string":return e.length>100?"string":'"'.concat(e.split('"').join('\\"'),'"');default:return String(e)}}function Bt(e,t,i,n,s){let r=i.localName;if(i.repeated){if(Ve("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Ft(t)));const a=e[r];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Ft(e)));switch(i.kind){case"message":a.push(i.T.fromJson(e,n));break;case"enum":const t=zt(i.T,e,n.ignoreUnknownFields,!0);t!==jt&&a.push(t);break;case"scalar":try{a.push(Vt(i.T,e,i.L,!0))}catch(o){let t="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Ft(e));throw o instanceof Error&&o.message.length>0&&(t+=": ".concat(o.message)),new Error(t)}}}}else if("map"==i.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Ft(t)));const a=e[r];for(const[e,r]of Object.entries(t)){if(null===r)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: map value null"));let c;try{c=qt(i.K,e)}catch(o){let e="cannot decode map key for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Ft(t));throw o instanceof Error&&o.message.length>0&&(e+=": ".concat(o.message)),new Error(e)}switch(i.V.kind){case"message":a[c]=i.V.T.fromJson(r,n);break;case"enum":const e=zt(i.V.T,r,n.ignoreUnknownFields,!0);e!==jt&&(a[c]=e);break;case"scalar":try{a[c]=Vt(i.V.T,r,ht.BIGINT,!0)}catch(o){let e="cannot decode map value for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Ft(t));throw o instanceof Error&&o.message.length>0&&(e+=": ".concat(o.message)),new Error(e)}}}}else switch(i.oneof&&(e=e[i.oneof.localName]={case:r},r="value"),i.kind){case"message":const a=i.T;if(null===t&&"google.protobuf.Value"!=a.typeName)return;let c=e[r];Ot(c)?c.fromJson(t,n):(e[r]=c=a.fromJson(t,n),a.fieldWrapper&&!i.oneof&&(e[r]=a.fieldWrapper.unwrapField(c)));break;case"enum":const d=zt(i.T,t,n.ignoreUnknownFields,!1);switch(d){case Ut:_t(i,e);break;case jt:break;default:e[r]=d}break;case"scalar":try{const n=Vt(i.T,t,i.L,!1);if(n===Ut)_t(i,e);else e[r]=n}catch(o){let e="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Ft(t));throw o instanceof Error&&o.message.length>0&&(e+=": ".concat(o.message)),new Error(e)}}}function qt(e,t){if(e===lt.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return Vt(e,t,ht.BIGINT,!0).toString()}function Vt(e,t,i,n){if(null===t)return n?vt(e,i):Ut;switch(e){case lt.DOUBLE:case lt.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t)break;if("string"==typeof t&&t.trim().length!==t.length)break;if("string"!=typeof t&&"number"!=typeof t)break;const n=Number(t);if(Number.isNaN(n))break;if(!Number.isFinite(n))break;return e==lt.FLOAT&&We(n),n;case lt.INT32:case lt.FIXED32:case lt.SFIXED32:case lt.SINT32:case lt.UINT32:let r;if("number"==typeof t?r=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(r=Number(t)),void 0===r)break;return e==lt.UINT32||e==lt.FIXED32?He(r):ze(r),r;case lt.INT64:case lt.SFIXED64:case lt.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=dt.parse(t);return i?o.toString():o;case lt.FIXED64:case lt.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const a=dt.uParse(t);return i?a.toString():a;case lt.BOOL:if("boolean"!=typeof t)break;return t;case lt.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(s){throw new Error("invalid UTF8")}return t;case lt.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return wt.dec(t)}throw new Error}function zt(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:Ut;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const n=e.findName(t);if(void 0!==n)return n.no;if(i)return jt}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(Ft(t)))}function Ht(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function Wt(e,t,i){if("map"==e.kind){Ve("object"==typeof t&&null!=t);const n={},s=Object.entries(t);switch(e.V.kind){case"scalar":for(const[i,r]of s)n[i.toString()]=Gt(e.V.T,r);break;case"message":for(const[e,r]of s)n[e.toString()]=r.toJson(i);break;case"enum":const t=e.V.T;for(const[e,r]of s)n[e.toString()]=Kt(t,r,i.enumAsInteger)}return i.emitDefaultValues||s.length>0?n:void 0}if(e.repeated){Ve(Array.isArray(t));const n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(Gt(e.T,t[i]));break;case"enum":for(let s=0;s<t.length;s++)n.push(Kt(e.T,t[s],i.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)n.push(t[e].toJson(i))}return i.emitDefaultValues||n.length>0?n:void 0}switch(e.kind){case"scalar":return Gt(e.T,t);case"enum":return Kt(e.T,t,i.enumAsInteger);case"message":return Dt(e.T,t).toJson(i)}}function Kt(e,t,i){var n;if(Ve("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;const s=e.findNumber(t);return null!==(n=null==s?void 0:s.name)&&void 0!==n?n:t}function Gt(e,t){switch(e){case lt.INT32:case lt.SFIXED32:case lt.SINT32:case lt.FIXED32:case lt.UINT32:return Ve("number"==typeof t),t;case lt.FLOAT:case lt.DOUBLE:return Ve("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case lt.STRING:return Ve("string"==typeof t),t;case lt.BOOL:return Ve("boolean"==typeof t),t;case lt.UINT64:case lt.FIXED64:case lt.INT64:case lt.SFIXED64:case lt.SINT64:return Ve("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case lt.BYTES:return Ve(t instanceof Uint8Array),wt.enc(t)}}const Jt=Symbol("@bufbuild/protobuf/unknown-fields"),Qt={readUnknownFields:!0,readerFactory:e=>new kt(e)},Yt={writeUnknownFields:!0,writerFactory:()=>new yt};function Xt(e){return e?Object.assign(Object.assign({},Qt),e):Qt}function Zt(e){return e?Object.assign(Object.assign({},Yt),e):Yt}function $t(e,t,i,n,s){let{repeated:r,localName:o}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=o&&delete e.value,e.case=o,o="value"),i.kind){case"scalar":case"enum":const a="enum"==i.kind?lt.INT32:i.T;let c=ii;if("scalar"==i.kind&&i.L>0&&(c=ti),r){let i=e[o];if(n==mt.LengthDelimited&&a!=lt.STRING&&a!=lt.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(c(t,a))}else i.push(c(t,a))}else e[o]=c(t,a);break;case"message":const d=i.T;r?e[o].push(ei(t,new d,s,i)):Ot(e[o])?ei(t,e[o],s,i):(e[o]=ei(t,new d,s,i),!d.fieldWrapper||i.oneof||i.repeated||(e[o]=d.fieldWrapper.unwrapField(e[o])));break;case"map":let[l,u]=function(e,t,i){const n=t.uint32(),s=t.pos+n;let r,o;for(;t.pos<s;){const[n]=t.tag();switch(n){case 1:r=ii(t,e.K);break;case 2:switch(e.V.kind){case"scalar":o=ii(t,e.V.T);break;case"enum":o=t.int32();break;case"message":o=ei(t,new e.V.T,i,void 0)}}}void 0===r&&(r=vt(e.K,ht.BIGINT));"string"!=typeof r&&"number"!=typeof r&&(r=r.toString());if(void 0===o)switch(e.V.kind){case"scalar":o=vt(e.V.T,ht.BIGINT);break;case"enum":o=e.V.T.values[0].no;break;case"message":o=new e.V.T}return[r,o]}(i,t,s);e[o][l]=u}}function ei(e,t,i,n){const s=t.getType().runtime.bin,r=null==n?void 0:n.delimited;return s.readMessage(t,e,r?n.no:e.uint32(),i,r),t}function ti(e,t){const i=ii(e,t);return"bigint"==typeof i?i.toString():i}function ii(e,t){switch(t){case lt.STRING:return e.string();case lt.BOOL:return e.bool();case lt.DOUBLE:return e.double();case lt.FLOAT:return e.float();case lt.INT32:return e.int32();case lt.INT64:return e.int64();case lt.UINT64:return e.uint64();case lt.FIXED64:return e.fixed64();case lt.BYTES:return e.bytes();case lt.FIXED32:return e.fixed32();case lt.SFIXED32:return e.sfixed32();case lt.SFIXED64:return e.sfixed64();case lt.SINT64:return e.sint64();case lt.UINT32:return e.uint32();case lt.SINT32:return e.sint32()}}function ni(e,t,i,n){Ve(void 0!==t);const s=e.repeated;switch(e.kind){case"scalar":case"enum":let r="enum"==e.kind?lt.INT32:e.T;if(s)if(Ve(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,mt.LengthDelimited).fork();let[,s]=ai(t);for(let r=0;r<n.length;r++)e[s](n[r]);e.join()}(i,r,e.no,t);else for(const n of t)oi(i,r,e.no,n);else oi(i,r,e.no,t);break;case"message":if(s){Ve(Array.isArray(t));for(const s of t)ri(i,n,e,s)}else ri(i,n,e,t);break;case"map":Ve("object"==typeof t&&null!=t);for(const[s,o]of Object.entries(t))si(i,n,e,s,o)}}function si(e,t,i,n,s){e.tag(i.no,mt.LengthDelimited),e.fork();let r=n;switch(i.K){case lt.INT32:case lt.FIXED32:case lt.UINT32:case lt.SFIXED32:case lt.SINT32:r=Number.parseInt(n);break;case lt.BOOL:Ve("true"==n||"false"==n),r="true"==n}switch(oi(e,i.K,1,r),i.V.kind){case"scalar":oi(e,i.V.T,2,s);break;case"enum":oi(e,lt.INT32,2,s);break;case"message":Ve(void 0!==s),e.tag(2,mt.LengthDelimited).bytes(s.toBinary(t))}e.join()}function ri(e,t,i,n){const s=Dt(i.T,n);i.delimited?e.tag(i.no,mt.StartGroup).raw(s.toBinary(t)).tag(i.no,mt.EndGroup):e.tag(i.no,mt.LengthDelimited).bytes(s.toBinary(t))}function oi(e,t,i,n){Ve(void 0!==n);let[s,r]=ai(t);e.tag(i,s)[r](n)}function ai(e){let t=mt.Varint;switch(e){case lt.BYTES:case lt.STRING:t=mt.LengthDelimited;break;case lt.DOUBLE:case lt.FIXED64:case lt.SFIXED64:t=mt.Bit64;break;case lt.FIXED32:case lt.SFIXED32:case lt.FLOAT:t=mt.Bit32}return[t,lt[e].toLowerCase()]}function ci(e){if(void 0===e)return e;if(Ot(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function di(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class li{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const e={};for(const t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){const e={};for(const t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function ui(e,t){const i=pi(e);return t?i:bi(vi(i))}const hi=pi;function pi(e){let t=!1;const i=[];for(let n=0;n<e.length;n++){let s=e.charAt(n);switch(s){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":i.push(s),t=!1;break;default:t&&(t=!1,s=s.toUpperCase()),i.push(s)}}return i.join("")}const mi=new Set(["constructor","toString","toJSON","valueOf"]),gi=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),fi=e=>"".concat(e,"$"),vi=e=>gi.has(e)?fi(e):e,bi=e=>mi.has(e)?fi(e):e;class yi{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=ui(e,!1)}addField(e){Ve(e.oneof===this,"field ".concat(e.name," not one of ").concat(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]}}const ki=(Ti=e=>new li(e,e=>function(e){var t,i,n,s,r,o;const a=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=ui(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:hi(d.name),e.repeated=null!==(i=d.repeated)&&void 0!==i&&i,"scalar"==d.kind&&(e.L=null!==(n=d.L)&&void 0!==n?n:ht.BIGINT),e.delimited=null!==(s=d.delimited)&&void 0!==s&&s,e.req=null!==(r=d.req)&&void 0!==r&&r,e.opt=null!==(o=d.opt)&&void 0!==o&&o,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=lt.BYTES&&d.T!=lt.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new yi(t)),e.oneof=c,c.addField(e)}a.push(e)}return a}(e)),Ci=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const i=t.localName,n=e;if(t.repeated)n[i]=[];else switch(t.kind){case"oneof":n[i]={case:void 0};break;case"enum":n[i]=0;break;case"map":n[i]={};break;case"scalar":n[i]=vt(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:Nt,makeWriteOptions:Lt,readMessage(e,t,i,n){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(Ft(t)));n=null!=n?n:new e;const s=new Map,r=i.typeRegistry;for(const[o,a]of Object.entries(t)){const t=e.fields.findJsonName(o);if(t){if(t.oneof){if(null===a&&"scalar"==t.kind)continue;const i=s.get(t.oneof);if(void 0!==i)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(o,'"'));s.set(t.oneof,o)}Bt(n,a,t,i,e)}else{let t=!1;if((null==r?void 0:r.findExtension)&&o.startsWith("[")&&o.endsWith("]")){const s=r.findExtension(o.substring(1,o.length-1));if(s&&s.extendee.typeName==e.typeName){t=!0;const[e,r]=Tt(s);Bt(e,a,s.field,i,s),Rt(n,s,r(),i)}}if(!t&&!i.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return n},writeMessage(e,t){const i=e.getType(),n={};let s;try{for(s of i.fields.byNumber()){if(!It(s,e)){if(s.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!Ht(s))continue}const i=Wt(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t);void 0!==i&&(n[t.useProtoFieldName?s.name:s.jsonName]=i)}const r=t.typeRegistry;if(null==r?void 0:r.findExtensionFor)for(const s of i.runtime.bin.listUnknownFields(e)){const o=r.findExtensionFor(i.typeName,s.no);if(o&&Pt(e,o)){const i=Et(e,o,t),s=Wt(o.field,i,t);void 0!==s&&(n[o.field.jsonName]=s)}}}catch(r){const e=s?"cannot encode field ".concat(i.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(i.typeName," to JSON"),t=r instanceof Error?r.message:String(r);throw new Error(e+(t.length>0?": ".concat(t):""))}return n},readScalar:(e,t,i)=>Vt(e,t,null!=i?i:ht.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t)return i||bt(e,t)?Gt(e,t):void 0},debug:Ft},bin:{makeReadOptions:Xt,makeWriteOptions:Zt,listUnknownFields(e){var t;return null!==(t=e[Jt])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[Jt]},writeUnknownFields(e,t){const i=e[Jt];if(i)for(const n of i)t.tag(n.no,n.wireType).raw(n.data)},onUnknownField(e,t,i,n){const s=e;Array.isArray(s[Jt])||(s[Jt]=[]),s[Jt].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,s){const r=e.getType(),o=s?t.len:t.pos+i;let a,c;for(;t.pos<o&&([a,c]=t.tag(),!0!==s||c!=mt.EndGroup);){const i=r.fields.find(a);if(!i){const i=t.skip(c,a);n.readUnknownFields&&this.onUnknownField(e,a,c,i);continue}$t(e,t,i,c,n)}if(s&&(c!=mt.EndGroup||a!==i))throw new Error("invalid end group tag")},readField:$t,writeMessage(e,t,i){const n=e.getType();for(const s of n.fields.byNumber())if(It(s,e))ni(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t,i);else if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&ni(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:Je,initPartial(e,t){if(void 0===e)return;const i=t.getType();for(const n of i.fields.byMember()){const i=n.localName,s=t,r=e;if(null!=r[i])switch(n.kind){case"oneof":const e=r[i].case;if(void 0===e)continue;const t=n.findField(e);let o=r[i].value;t&&"message"==t.kind&&!Ot(o,t.T)?o=new t.T(o):t&&"scalar"===t.kind&&t.T===lt.BYTES&&(o=di(o)),s[i]={case:e,value:o};break;case"scalar":case"enum":let a=r[i];n.T===lt.BYTES&&(a=n.repeated?a.map(di):di(a)),s[i]=a;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===lt.BYTES)for(const[t,n]of Object.entries(r[i]))s[i][t]=di(n);else Object.assign(s[i],r[i]);break;case"message":const e=n.V.T;for(const t of Object.keys(r[i])){let n=r[i][t];e.fieldWrapper||(n=new e(n)),s[i][t]=n}}break;case"message":const c=n.T;if(n.repeated)s[i]=r[i].map(e=>Ot(e,c)?e:new c(e));else{const e=r[i];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?s[i]=di(e):s[i]=e:s[i]=Ot(e,c)?e:new c(e)}}}},equals:(e,t,i)=>t===i||!(!t||!i)&&e.fields.byMember().every(e=>{const n=t[e.localName],s=i[e.localName];if(e.repeated){if(n.length!==s.length)return!1;switch(e.kind){case"message":return n.every((t,i)=>e.T.equals(t,s[i]));case"scalar":return n.every((t,i)=>ft(e.T,t,s[i]));case"enum":return n.every((e,t)=>ft(lt.INT32,e,s[t]))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let t=n,i=s;return e.T.fieldWrapper&&(void 0===t||Ot(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===i||Ot(i)||(i=e.T.fieldWrapper.wrapField(i))),e.T.equals(t,i);case"enum":return ft(lt.INT32,n,s);case"scalar":return ft(e.T,n,s);case"oneof":if(n.case!==s.case)return!1;const r=e.findField(n.case);if(void 0===r)return!0;switch(r.kind){case"message":return r.T.equals(n.value,s.value);case"enum":return ft(lt.INT32,n.value,s.value);case"scalar":return ft(r.T,n.value,s.value)}throw new Error("oneof cannot contain ".concat(r.kind));case"map":const o=Object.keys(n).concat(Object.keys(s));switch(e.V.kind){case"message":const t=e.V.T;return o.every(e=>t.equals(n[e],s[e]));case"enum":return o.every(e=>ft(lt.INT32,n[e],s[e]));case"scalar":const i=e.V.T;return o.every(e=>ft(i,n[e],s[e]))}}}),clone(e){const t=e.getType(),i=new t,n=i;for(const s of t.fields.byMember()){const t=e[s.localName];let i;if(s.repeated)i=t.map(ci);else if("map"==s.kind){i=n[s.localName];for(const[e,n]of Object.entries(t))i[e]=ci(n)}else i="oneof"==s.kind?s.findField(t.case)?{case:t.case,value:ci(t.value)}:{case:void 0}:ci(t);n[s.localName]=i}for(const s of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(n,s.no,s.wireType,s.data);return i}}),{newFieldList:Ti,initFields:Ci}),makeMessageType(e,t,i){return function(e,t,i,n){var s;const r=null!==(s=null==n?void 0:n.localName)&&void 0!==s?s:t.substring(t.lastIndexOf(".")+1),o={[r]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[r];return Object.setPrototypeOf(o.prototype,new Ze),Object.assign(o,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>(new o).fromBinary(e,t),fromJson:(e,t)=>(new o).fromJson(e,t),fromJsonString:(e,t)=>(new o).fromJsonString(e,t),equals:(t,i)=>e.util.equals(o,t,i)}),o}(this,e,t,i)},makeEnum:Ye,makeEnumType:Qe,getEnumType:Ge,makeExtension(e,t,i){return function(e,t,i,n){let s;return{typeName:t,extendee:i,get field(){if(!s){const i="function"==typeof n?n():n;i.name=t.split(".").pop(),i.jsonName="[".concat(t,"]"),s=e.util.newFieldList([i]).list()[0]}return s},runtime:e}}(this,e,t,i)}});var Ti,Ci;class Si extends Ze{constructor(e){super(),this.seconds=dt.zero,this.nanos=0,ki.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(ki.json.debug(e)));const i=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(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw new 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=dt.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=1e3*Number(this.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new 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 new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const e=(this.nanos+1e9).toString().substring(1);i="000000"===e.substring(3)?"."+e.substring(0,3)+"Z":"000"===e.substring(6)?"."+e.substring(0,6)+"Z":"."+e+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return Si.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new Si({seconds:dt.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new Si).fromBinary(e,t)}static fromJson(e,t){return(new Si).fromJson(e,t)}static fromJsonString(e,t){return(new Si).fromJsonString(e,t)}static equals(e,t){return ki.util.equals(Si,e,t)}}Si.runtime=ki,Si.typeName="google.protobuf.Timestamp",Si.fields=ki.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const wi=ki.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Si},{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:Pi,repeated:!0}]),Ei=ki.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:Ri,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),Ri=ki.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Si},{no:3,name:"value",kind:"scalar",T:2}]),Pi=ki.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:Si},{no:7,name:"normalized_end_timestamp",kind:"message",T:Si,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),xi=ki.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Ii=ki.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),_i=ki.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"}]),Oi=ki.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Di=ki.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Ai=ki.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Mi=ki.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"}]),Ni=ki.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=ki.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Ui=ki.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"}]),ji=ki.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:Fi,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:kn}]),Fi=ki.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),Bi=ki.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:ki.getEnumType(_i),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}]),qi=ki.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:ki.getEnumType(Vi)},{no:4,name:"tracks",kind:"message",T:Gi,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:Bi},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:ki.getEnumType(zi)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:ki.getEnumType(Mi)},{no:18,name:"kind_details",kind:"enum",T:ki.getEnumType(Hi),repeated:!0}]),Vi=ki.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),zi=ki.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"}]),Hi=ki.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),Wi=ki.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Ki=ki.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:Ji,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:ki.getEnumType(Qi)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),Gi=ki.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:ki.getEnumType(Ii)},{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:ki.getEnumType(_i)},{no:10,name:"layers",kind:"message",T:Ji,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:ki.getEnumType(Wi)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:kn},{no:19,name:"audio_features",kind:"enum",T:ki.getEnumType(Ui),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:ki.getEnumType(xi)}]),Ji=ki.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:ki.getEnumType(Oi)},{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}]),Qi=ki.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"}]),Yi=ki.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:ki.getEnumType(Xi)},{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:nn,oneof:"value"},{no:3,name:"speaker",kind:"message",T:en,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:sn,oneof:"value"},{no:7,name:"transcription",kind:"message",T:rn,oneof:"value"},{no:8,name:"metrics",kind:"message",T:wi,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:an,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:cn,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:dn,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:ln,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:wn,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:En,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Rn,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:Zi,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),Xi=ki.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Zi=ki.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:ki.getEnumType(Wi)},{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}]),$i=ki.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:nn,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:an,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:cn,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:dn,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:ln,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:wn,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:En,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:Rn,oneof:"value"}]),en=ki.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:tn,repeated:!0}]),tn=ki.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}]),nn=ki.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}]),sn=ki.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),rn=ki.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:on,repeated:!0}]),on=ki.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}]),an=ki.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}]),cn=ki.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}]),dn=ki.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),ln=ki.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:un,oneof:"value"}]),un=ki.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}]),hn=ki.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),pn=ki.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:ki.getEnumType(mn)},{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}]),mn=ki.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),gn=ki.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:ki.getEnumType(fn)},{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}]),fn=ki.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"}]),vn=ki.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:bn},{no:2,name:"screen",kind:"message",T:bn},{no:3,name:"resume_connection",kind:"enum",T:ki.getEnumType(Ai)},{no:4,name:"disabled_codecs",kind:"message",T:yn},{no:5,name:"force_relay",kind:"enum",T:ki.getEnumType(Ai)}]),bn=ki.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:ki.getEnumType(Ai)}]),yn=ki.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:Fi,repeated:!0},{no:2,name:"publish",kind:"message",T:Fi,repeated:!0}]),kn=ki.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Tn=ki.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Cn=ki.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:ki.getEnumType(Tn)},{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"}),Sn=ki.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),wn=ki.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:ki.getEnumType(Wi)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Cn,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Sn,oneof:"content_header"}],{localName:"DataStream_Header"}),En=ki.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"}),Rn=ki.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"}),Pn=ki.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),xn=ki.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),In=ki.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),_n=ki.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),On=ki.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:qn,oneof:"message"},{no:2,name:"answer",kind:"message",T:qn,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Nn,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Mn,oneof:"message"},{no:5,name:"mute",kind:"message",T:Ln,oneof:"message"},{no:6,name:"subscription",kind:"message",T:zn,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Hn,oneof:"message"},{no:8,name:"leave",kind:"message",T:Gn,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Qn,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:ds,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:hs,oneof:"message"},{no:13,name:"simulate",kind:"message",T:gs,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Yn,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:fs,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Wn,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Kn,oneof:"message"}]),Dn=ki.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:Un,oneof:"message"},{no:2,name:"answer",kind:"message",T:qn,oneof:"message"},{no:3,name:"offer",kind:"message",T:qn,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Nn,oneof:"message"},{no:5,name:"update",kind:"message",T:Vn,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Fn,oneof:"message"},{no:8,name:"leave",kind:"message",T:Gn,oneof:"message"},{no:9,name:"mute",kind:"message",T:Ln,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Zn,oneof:"message"},{no:11,name:"room_update",kind:"message",T:$n,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:ts,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:ns,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:os,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:ls,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Bn,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:jn,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:vs,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:ks,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Ts,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Ss,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:us,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:xs,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:as,oneof:"message"}]),An=ki.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:Ji,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:ki.getEnumType(Qi)}]),Mn=ki.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:ki.getEnumType(Ii)},{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:ki.getEnumType(_i)},{no:9,name:"layers",kind:"message",T:Ji,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:An,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:ki.getEnumType(Wi)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:ki.getEnumType(xi)},{no:17,name:"audio_features",kind:"enum",T:ki.getEnumType(Ui),repeated:!0}]),Nn=ki.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:ki.getEnumType(xn)},{no:3,name:"final",kind:"scalar",T:8}]),Ln=ki.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),Un=ki.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:ji},{no:2,name:"participant",kind:"message",T:qi},{no:3,name:"other_participants",kind:"message",T:qi,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Xn,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:vn},{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:pn},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Fi,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),jn=ki.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:Xn,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:vn},{no:3,name:"server_info",kind:"message",T:pn},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Fn=ki.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Gi}]),Bn=ki.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),qn=ki.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}}]),Vn=ki.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:qi,repeated:!0}]),zn=ki.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:hn,repeated:!0}]),Hn=ki.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:ki.getEnumType(Oi)},{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}]),Wn=ki.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:ki.getEnumType(Ui),repeated:!0}]),Kn=ki.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}]),Gn=ki.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:ki.getEnumType(Mi)},{no:3,name:"action",kind:"enum",T:ki.getEnumType(Jn)},{no:4,name:"regions",kind:"message",T:bs}]),Jn=ki.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Qn=ki.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Ji,repeated:!0}]),Yn=ki.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}]),Xn=ki.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}]),Zn=ki.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:tn,repeated:!0}]),$n=ki.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:ji}]),es=ki.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:ki.getEnumType(Di)},{no:3,name:"score",kind:"scalar",T:2}]),ts=ki.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:es,repeated:!0}]),is=ki.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:ki.getEnumType(In)}]),ns=ki.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:is,repeated:!0}]),ss=ki.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:ki.getEnumType(Oi)},{no:2,name:"enabled",kind:"scalar",T:8}]),rs=ki.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:ss,repeated:!0}]),os=ki.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:ss,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:rs,repeated:!0}]),as=ki.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Pn,repeated:!0}]),cs=ki.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}]),ds=ki.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:cs,repeated:!0}]),ls=ki.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}]),us=ki.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:ji},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:qi},{no:4,name:"other_participants",kind:"message",T:qi,repeated:!0}]),hs=ki.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:qn},{no:2,name:"subscription",kind:"message",T:zn},{no:3,name:"publish_tracks",kind:"message",T:Fn,repeated:!0},{no:4,name:"data_channels",kind:"message",T:ms,repeated:!0},{no:5,name:"offer",kind:"message",T:qn},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:ps,repeated:!0}]),ps=ki.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),ms=ki.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:ki.getEnumType(xn)}]),gs=ki.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:ki.getEnumType(_n),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"}]),fs=ki.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),vs=ki.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),bs=ki.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:ys,repeated:!0}]),ys=ki.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}]),ks=ki.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:ki.getEnumType(Li)}]),Ts=ki.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:ki.getEnumType(Cs)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:Nn,oneof:"request"},{no:5,name:"add_track",kind:"message",T:Mn,oneof:"request"},{no:6,name:"mute",kind:"message",T:Ln,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:Yn,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:Wn,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Kn,oneof:"request"}]),Cs=ki.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"}]),Ss=ki.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),ws=ki.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}]),Es=ki.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:gn},{no:2,name:"connection_settings",kind:"message",T:ws},{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:Mn,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:qn},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:ki.getEnumType(Ni)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:hs}]),Rs=ki.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:ki.getEnumType(Ps)},{no:2,name:"join_request",kind:"scalar",T:12}]),Ps=ki.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),xs=ki.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function Is(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var _s,Os={exports:{}};var Ds,As,Ms,Ns,Ls,Us,js,Fs=(_s||(_s=1,As=Os.exports,Ms=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],s={},r=null;function o(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(n){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),s=0;s<n.length;s++){var r=n[s];this[r]=s<i?e:this.methodFactory(r,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function l(n,s,r){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?a:void 0!==console[n]?o(console,n):void 0!==console.log?o(console,"log"):e)}(n)||d.apply(this,arguments)}function u(e,i){var o,a,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(r){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),s=i.indexOf(n+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s+n.length+1))[1])}catch(r){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||l,u.getLevel=function(){return null!=d?d:null!=a?a:o},u.setLevel=function(e,i){return d=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=i)}catch(s){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(s){}}}(d),c.call(u)},u.setDefaultLevel=function(e){a=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(r!==u&&(o=m(r.getLevel())),c.call(u),r===u)for(var e in s)s[e].rebuild()},o=m(r?r.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(r=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=s[e];return t||(t=s[e]=new u(e,r.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return r.noConflict=function(){return typeof window!==t&&window.log===r&&(window.log=h),r},r.getLoggers=function(){return s},r.default=r,r},(Ds=Os).exports?Ds.exports=Ms():As.log=Ms()),Os.exports);(Ls=Ns||(Ns={}))[Ls.trace=0]="trace",Ls[Ls.debug=1]="debug",Ls[Ls.info=2]="info",Ls[Ls.warn=3]="warn",Ls[Ls.error=4]="error",Ls[Ls.silent=5]="silent",(js=Us||(Us={})).Default="livekit",js.Room="livekit-room",js.TokenSource="livekit-token-source",js.Participant="livekit-participant",js.Track="livekit-track",js.Publication="livekit-track-publication",js.Engine="livekit-engine",js.Signal="livekit-signal",js.PCManager="livekit-pc-manager",js.PCTransport="livekit-pc-transport",js.E2EE="lk-e2ee";let Bs=Fs.getLogger("livekit");function qs(e){const t=Fs.getLogger(e);return t.setDefaultLevel(Bs.getLevel()),t}Object.values(Us).map(e=>Fs.getLogger(e)),Bs.setDefaultLevel(Ns.info);const Vs=Fs.getLogger("lk-e2ee"),zs=7e3,Hs=[0,300,1200,2700,4800,zs,zs,zs,zs,zs];function Ws(e,t,i,n){return new(i||(i=Promise))(function(s,r){function o(e){try{c(n.next(e))}catch(t){r(t)}}function a(e){try{c(n.throw(e))}catch(t){r(t)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})}function Ks(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Gs(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=Ks(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise(function(n,s){(function(e,t,i,n){Promise.resolve(n).then(function(t){e({value:t,done:i})},t)})(n,s,(t=e[i](t)).done,t.value)})}}}"function"==typeof SuppressedError&&SuppressedError;var Js,Qs={exports:{}};var Ys=function(){if(Js)return Qs.exports;Js=1;var e,t="object"==typeof Reflect?Reflect:null,i=t&&"function"==typeof t.apply?t.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}Qs.exports=s,Qs.exports.once=function(e,t){return new Promise(function(i,n){function s(i){e.removeListener(t,r),n(i)}function r(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}m(e,t,r,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&m(e,"error",t,i)}(e,s,{once:!0})})},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var r=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function a(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){var s,r,c,d;if(o(i),void 0===(r=e._events)?(r=e._events=Object.create(null),e._eventsCount=0):(void 0!==r.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),r=e._events),c=r[t]),void 0===c)c=r[t]=i,++e._eventsCount;else if("function"==typeof c?c=r[t]=n?[i,c]:[c,i]:n?c.unshift(i):c.push(i),(s=a(e))>0&&c.length>s&&!c.warned){c.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,d=l,console&&console.warn&&console.warn(d)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=d.bind(n);return s.listener=i,n.wrapFn=s,s}function u(e,t,i){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(s):p(s,s.length)}function h(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function p(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function m(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function s(r){n.once&&e.removeEventListener(t,s),i(r)})}}return Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return r},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");r=e}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return a(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var s="error"===e,r=this._events;if(void 0!==r)s=s&&void 0===r.error;else if(!s)return!1;if(s){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=r[e];if(void 0===c)return!1;if("function"==typeof c)i(c,this,t);else{var d=c.length,l=p(c,d);for(n=0;n<d;++n)i(l[n],this,t)}return!0},s.prototype.addListener=function(e,t){return c(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return c(this,e,t,!0)},s.prototype.once=function(e,t){return o(t),this.on(e,l(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,l(this,e,t)),this},s.prototype.removeListener=function(e,t){var i,n,s,r,a;if(o(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(s=-1,r=i.length-1;r>=0;r--)if(i[r]===t||i[r].listener===t){a=i[r].listener,s=r;break}if(s<0)return this;0===s?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,s),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var s,r=Object.keys(i);for(n=0;n<r.length;++n)"removeListener"!==(s=r[n])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return u(this,e,!0)},s.prototype.rawListeners=function(e){return u(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h,s.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},Qs.exports}();let Xs=!0,Zs=!0;function $s(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseFloat(n[i],10)}function er(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return s.apply(this,arguments);const r=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,r),s.apply(this,[e,r])};const r=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return r.apply(this,arguments);if(!this._eventMap[t].has(i))return r.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,r.apply(this,[e,n])},Object.defineProperty(n,"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 tr(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Xs=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function ir(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Zs=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function nr(){if("object"==typeof window){if(Xs)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function sr(e,t){Zs&&console.warn(e+" is deprecated, please use "+t+" instead.")}function rr(e){return"[object Object]"===Object.prototype.toString.call(e)}function or(e){return rr(e)?Object.keys(e).reduce(function(t,i){const n=rr(e[i]),s=n?or(e[i]):e[i],r=n&&!Object.keys(s).length;return void 0===s||r?t:Object.assign(t,{[i]:s})},{}):e}function ar(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach(n=>{n.endsWith("Id")?ar(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach(t=>{ar(e,e.get(t),i)})}))}function cr(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",s=new Map;if(null===t)return s;const r=[];return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&r.push(e)}),r.forEach(t=>{e.forEach(i=>{i.type===n&&i.trackId===t.id&&ar(e,i,s)})}),s}const dr=nr;function lr(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach(i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const s=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[s("min",i)]=n.ideal,t.optional.push(e),e={},e[s("max",i)]=n.ideal,t.optional.push(e)):(e[s("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[s("",i)]=n.exact):["min","max"].forEach(e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[s(e,i)]=n[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},s=function(e,s){if(t.version>=61)return s(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let r=e.video.facingMode;r=r&&("object"==typeof r?r:{ideal:r});const o=t.version<66;if(r&&("user"===r.exact||"environment"===r.exact||"user"===r.ideal||"environment"===r.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===r.exact||"environment"===r.ideal?t=["back","rear"]:"user"!==r.exact&&"user"!==r.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then(i=>{let o=(i=i.filter(e=>"videoinput"===e.kind)).find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=r.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),dr("chrome: "+JSON.stringify(e)),s(e)})}e.video=n(e.video)}return dr("chrome: "+JSON.stringify(e)),s(e)},r=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(i.getUserMedia=function(e,t,n){s(e,e=>{i.webkitGetUserMedia(e,t,e=>{n&&n(r(e))})})}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return s(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(r(e))))}}}function ur(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function hr(e){if("object"==typeof e&&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});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.track.id):{track:i.track};const s=new Event("track");s.track=i.track,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)}),t.stream.getTracks().forEach(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.id):{track:i};const s=new Event("track");s.track=i,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else er(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function pr(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?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()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let s=i.apply(this,arguments);return s||(s=t(this,e),this._senders.push(s)),s};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{const t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function mr(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>cr(t,e.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),er(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>cr(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach(i=>{i.track===e&&(t?n=!0:t=i)}),this.getReceivers().forEach(t=>(t.track===e&&(i?n=!0:i=t),t.track===e)),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function gr(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=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")});const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]}),s.apply(this,arguments)}}function fr(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return gr(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};const n=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]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const s=e.RTCPeerConnection.prototype.removeStream;function r(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(s.id,"g"),n.id)}),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.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,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[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||{};const s=this._streams[i.id];if(s)s.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find(e=>e.track===t)},["createOffer","createAnswer"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=r(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then(e=>r(this,e))}};e.RTCPeerConnection.prototype[t]=n[t]});const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),s.id)}),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:r(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)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");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach(i=>{this._streams[i].getTracks().find(t=>e.track===t)&&(t=this._streams[i])}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function vr(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]})}function br(e,t){er(e,"negotiationneeded",e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e})}var yr=Object.freeze({__proto__:null,fixNegotiationNeeded:br,shimAddTrackRemoveTrack:fr,shimAddTrackRemoveTrackWithNative:gr,shimGetSendersWithDtmf:pr,shimGetUserMedia:lr,shimMediaStream:ur,shimOnTrack:hr,shimPeerConnection:vr,shimSenderReceiverGetStats:mr});function kr(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){sr("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function Tr(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Cr(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]});const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,s,r]=arguments;return n.apply(this,[e||null]).then(e=>{if(t.version<53&&!s)try{e.forEach(e=>{e.type=i[e.type]||e.type})}catch(n){if("TypeError"!==n.name)throw n;e.forEach((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))})}return e}).then(s,r)}}function Sr(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.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 wr(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),er(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Er(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){sr("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function Rr(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Pr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach(e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return n})}function xr(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Ir(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const 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 _r(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const 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 Or=Object.freeze({__proto__:null,shimAddTransceiver:Pr,shimCreateAnswer:_r,shimCreateOffer:Ir,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:xr,shimGetUserMedia:kr,shimOnTrack:Tr,shimPeerConnection:Cr,shimRTCDataChannel:Rr,shimReceiverGetStats:wr,shimRemoveStream:Er,shimSenderGetStats:Sr});function Dr(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(i=>t.call(this,i,e)),e.getVideoTracks().forEach(i=>t.call(this,i,e))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];return n&&n.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||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach(e=>{i.includes(e.track)&&this.removeTrack(e)})})}}function Ar(e){if("object"==typeof e&&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=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)})})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)})}),t.apply(e,arguments)}}}function Mr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,s=t.setLocalDescription,r=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],s=i.apply(this,[n]);return t?(s.then(e,t),Promise.resolve()):s},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],s=n.apply(this,[i]);return t?(s.then(e,t),Promise.resolve()):s};let a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function Nr(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(Lr(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function Lr(e){return e&&void 0!==e.video?Object.assign({},e,{video:or(e.video)}):e}function Ur(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(sr("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function jr(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Fr(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find(e=>"audio"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Br(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var qr,Vr=Object.freeze({__proto__:null,shimAudioContext:Br,shimCallbacksAPI:Mr,shimConstraints:Lr,shimCreateOfferLegacy:Fr,shimGetUserMedia:Nr,shimLocalStreamsAPI:Dr,shimRTCIceServerUrls:Ur,shimRemoteStreamsAPI:Ar,shimTrackEventTransceiver:jr}),zr={exports:{}};var Hr=(qr||(qr=1,function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},t.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter(e=>0===e.indexOf(i))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={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 n=8;n<t.length;n+=2)switch(t[n]){case"raddr":i.relatedAddress=t[n+1];break;case"rport":i.relatedPort=parseInt(t[n+1],10);break;case"tcptype":i.tcpType=t[n+1];break;case"ufrag":i.ufrag=t[n+1],i.usernameFragment=t[n+1];break;default:void 0===i[t[n]]&&(i[t[n]]=t[n+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(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(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let s=0;s<n.length;s++)i=n[s].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach(t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)}),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],s=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substring(12),password:s.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){const s=n[r],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const n=t.parseRtpMap(o),r=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach(e=>{i.headerExtensions.push(t.parseExtmap(e))});const s=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach(e=>{s.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach(e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)});let s=0;return i.codecs.forEach(e=>{e.maxptime>s&&(s=e.maxptime)}),s>0&&(n+="a=maxptime:"+s+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach(e=>{n+=t.writeExtmap(e)}),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),r=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),a=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),s&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:r?"red+ulpfec":"red"},i.push(t))}}),0===i.length&&a&&i.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach(e=>{e.maxBitrate=l})),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute)[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const s=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=0===s.length;const r=t.matchPrefix(e,"a=rtcp-mux");return i.mux=r.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"msid"===e.attribute);return s.length>0?(i=s[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const r=t.matchPrefix(e,"a=sctp-port:");if(r.length>0)return{port:parseInt(r[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:s}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let s;const r=void 0!==i?i:2;return s=e||t.generateSessionId(),"v=0\r\no="+(n||"thisisadapterortc")+" "+s+" "+r+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let t=0;t<n.length;t++)switch(n[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[t].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let t=0;t<i.length;t++)if(i[t].length<2||"="!==i[t].charAt(1))return!1;return!0},e.exports=t}(zr)),zr.exports),Wr=Is(Hr),Kr=je({__proto__:null,default:Wr},[Hr]);function Gr(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),n=Wr.parseCandidate(e.candidate);for(const e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,er(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Jr(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||er(e,"icecandidate",e=>{if(e.candidate){const t=Wr.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Qr(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=Wr.splitSections(e.sdp);return t.shift(),t.some(e=>{const t=Wr.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")})}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const s=Wr.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?n=parseInt(s[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let s;s=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const r={};Object.defineProperty(r,"maxMessageSize",{get:()=>s}),this._sctp=r}return i.apply(this,arguments)}}function Yr(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],s=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&s>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},er(e,"datachannel",e=>(t(e.channel,e.target),e))}function Xr(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const 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=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function Zr(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t._safariVersion>=13.1)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==e.trim()).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function $r(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function eo(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.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"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>i.apply(this,[e]))})}var to=Object.freeze({__proto__:null,removeExtmapAllowMixed:Zr,shimAddIceCandidateNullOrEmpty:$r,shimConnectionState:Xr,shimMaxMessageSize:Qr,shimParameterlessSetLocalDescription:eo,shimRTCIceCandidate:Gr,shimRTCIceCandidateRelayProtocol:Jr,shimSendThrowTypeError:Yr});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=nr,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.userAgentData&&i.userAgentData.brands){const e=i.userAgentData.brands.find(e=>"Chromium"===e.brand);if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(i.mozGetUserMedia)t.browser="firefox",t.version=parseInt($s(i.userAgent,/Firefox\/(\d+)\./,1));else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt($s(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt($s(i.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=$s(i.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),s={browserDetails:n,commonShim:to,extractVersion:$s,disableLog:tr,disableWarnings:ir,sdp:Kr};switch(n.browser){case"chrome":if(!yr||!vr||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=yr,$r(e,n),eo(e),lr(e,n),ur(e),vr(e,n),hr(e),fr(e,n),pr(e),mr(e),br(e,n),Gr(e),Jr(e),Xr(e),Qr(e,n),Yr(e),Zr(e,n);break;case"firefox":if(!Or||!Cr||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=Or,$r(e,n),eo(e),kr(e,n),Cr(e,n),Tr(e),Er(e),Sr(e),wr(e),Rr(e),Pr(e),xr(e),Ir(e),_r(e),Gr(e),Xr(e),Qr(e,n),Yr(e);break;case"safari":if(!Vr||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=Vr,$r(e,n),eo(e),Ur(e),Fr(e),Mr(e),Dr(e),Ar(e),jr(e),Nr(e),Br(e),Gr(e),Jr(e),Qr(e,n),Yr(e),Zr(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});const io=/version\/(\d+(\.?_?\d+)+)/i;let no;function so(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if("undefined"==typeof navigator)return;const i=navigator.userAgent.toLowerCase();if(void 0===no||t){const e=ro.find(e=>{let{test:t}=e;return t.test(i)});no=null==e?void 0:e.describe(i)}return no}const ro=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:oo(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:ao(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:oo(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:ao(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:oo(io,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:ao(e)})}];function oo(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const n=t.match(e);return n&&n.length>=i&&n[i]||""}function ao(e){return e.includes("mac os")?oo(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class co extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var lo,uo,ho,po,mo,go,fo,vo,bo,yo,ko,To,Co,So;(uo=lo||(lo={}))[uo.NotAllowed=0]="NotAllowed",uo[uo.ServerUnreachable=1]="ServerUnreachable",uo[uo.InternalError=2]="InternalError",uo[uo.Cancelled=3]="Cancelled",uo[uo.LeaveRequest=4]="LeaveRequest",uo[uo.Timeout=5]="Timeout",uo[uo.WebSocket=6]="WebSocket";class wo extends co{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=lo[t]}static notAllowed(e,t,i){return new wo(e,lo.NotAllowed,t,i)}static timeout(e){return new wo(e,lo.Timeout)}static leaveRequest(e,t){return new wo(e,lo.LeaveRequest,void 0,t)}static internal(e,t){return new wo(e,lo.InternalError,void 0,t)}static cancelled(e){return new wo(e,lo.Cancelled)}static serverUnreachable(e,t){return new wo(e,lo.ServerUnreachable,t)}static websocket(e,t,i){return new wo(e,lo.WebSocket,t,i)}}class Eo extends co{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class Ro extends co{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class Po extends co{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class xo extends co{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Io extends co{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class _o extends co{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Oo extends co{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName="string"==typeof t?t:Cs[t]}}(po=ho||(ho={}))[po.AlreadyOpened=0]="AlreadyOpened",po[po.AbnormalEnd=1]="AbnormalEnd",po[po.DecodeFailed=2]="DecodeFailed",po[po.LengthExceeded=3]="LengthExceeded",po[po.Incomplete=4]="Incomplete",po[po.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",po[po.EncryptionTypeMismatch=8]="EncryptionTypeMismatch";class Do extends co{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=ho[t]}}class Ao extends co{constructor(e){super(18,e),this.name="SignalReconnectError"}}(go=mo||(mo={})).PermissionDenied="PermissionDenied",go.NotFound="NotFound",go.DeviceInUse="DeviceInUse",go.Other="Other",function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(mo||(mo={}));class Mo{}Mo.setTimeout=function(){return setTimeout(...arguments)},Mo.setInterval=function(){return setInterval(...arguments)},Mo.clearTimeout=function(){return clearTimeout(...arguments)},Mo.clearInterval=function(){return clearInterval(...arguments)},(vo=fo||(fo={})).Connected="connected",vo.Reconnecting="reconnecting",vo.SignalReconnecting="signalReconnecting",vo.Reconnected="reconnected",vo.Disconnected="disconnected",vo.ConnectionStateChanged="connectionStateChanged",vo.Moved="moved",vo.MediaDevicesChanged="mediaDevicesChanged",vo.ParticipantConnected="participantConnected",vo.ParticipantDisconnected="participantDisconnected",vo.TrackPublished="trackPublished",vo.TrackSubscribed="trackSubscribed",vo.TrackSubscriptionFailed="trackSubscriptionFailed",vo.TrackUnpublished="trackUnpublished",vo.TrackUnsubscribed="trackUnsubscribed",vo.TrackMuted="trackMuted",vo.TrackUnmuted="trackUnmuted",vo.LocalTrackPublished="localTrackPublished",vo.LocalTrackUnpublished="localTrackUnpublished",vo.LocalAudioSilenceDetected="localAudioSilenceDetected",vo.ActiveSpeakersChanged="activeSpeakersChanged",vo.ParticipantMetadataChanged="participantMetadataChanged",vo.ParticipantNameChanged="participantNameChanged",vo.ParticipantAttributesChanged="participantAttributesChanged",vo.ParticipantActive="participantActive",vo.RoomMetadataChanged="roomMetadataChanged",vo.DataReceived="dataReceived",vo.SipDTMFReceived="sipDTMFReceived",vo.TranscriptionReceived="transcriptionReceived",vo.ConnectionQualityChanged="connectionQualityChanged",vo.TrackStreamStateChanged="trackStreamStateChanged",vo.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",vo.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",vo.AudioPlaybackStatusChanged="audioPlaybackChanged",vo.VideoPlaybackStatusChanged="videoPlaybackChanged",vo.MediaDevicesError="mediaDevicesError",vo.ParticipantPermissionsChanged="participantPermissionsChanged",vo.SignalConnected="signalConnected",vo.RecordingStatusChanged="recordingStatusChanged",vo.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",vo.EncryptionError="encryptionError",vo.DCBufferStatusChanged="dcBufferStatusChanged",vo.ActiveDeviceChanged="activeDeviceChanged",vo.ChatMessage="chatMessage",vo.LocalTrackSubscribed="localTrackSubscribed",vo.MetricsReceived="metricsReceived",(yo=bo||(bo={})).TrackPublished="trackPublished",yo.TrackSubscribed="trackSubscribed",yo.TrackSubscriptionFailed="trackSubscriptionFailed",yo.TrackUnpublished="trackUnpublished",yo.TrackUnsubscribed="trackUnsubscribed",yo.TrackMuted="trackMuted",yo.TrackUnmuted="trackUnmuted",yo.LocalTrackPublished="localTrackPublished",yo.LocalTrackUnpublished="localTrackUnpublished",yo.LocalTrackCpuConstrained="localTrackCpuConstrained",yo.LocalSenderCreated="localSenderCreated",yo.ParticipantMetadataChanged="participantMetadataChanged",yo.ParticipantNameChanged="participantNameChanged",yo.DataReceived="dataReceived",yo.SipDTMFReceived="sipDTMFReceived",yo.TranscriptionReceived="transcriptionReceived",yo.IsSpeakingChanged="isSpeakingChanged",yo.ConnectionQualityChanged="connectionQualityChanged",yo.TrackStreamStateChanged="trackStreamStateChanged",yo.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",yo.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",yo.TrackCpuConstrained="trackCpuConstrained",yo.MediaDevicesError="mediaDevicesError",yo.AudioStreamAcquired="audioStreamAcquired",yo.ParticipantPermissionsChanged="participantPermissionsChanged",yo.PCTrackAdded="pcTrackAdded",yo.AttributesChanged="attributesChanged",yo.LocalTrackSubscribed="localTrackSubscribed",yo.ChatMessage="chatMessage",yo.Active="active",(To=ko||(ko={})).TransportsCreated="transportsCreated",To.Connected="connected",To.Disconnected="disconnected",To.Resuming="resuming",To.Resumed="resumed",To.Restarting="restarting",To.Restarted="restarted",To.SignalResumed="signalResumed",To.SignalRestarted="signalRestarted",To.Closing="closing",To.MediaTrackAdded="mediaTrackAdded",To.ActiveSpeakersUpdate="activeSpeakersUpdate",To.DataPacketReceived="dataPacketReceived",To.RTPVideoMapUpdate="rtpVideoMapUpdate",To.DCBufferStatusChanged="dcBufferStatusChanged",To.ParticipantUpdate="participantUpdate",To.RoomUpdate="roomUpdate",To.SpeakersChanged="speakersChanged",To.StreamStateChanged="streamStateChanged",To.ConnectionQualityUpdate="connectionQualityUpdate",To.SubscriptionError="subscriptionError",To.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",To.RemoteMute="remoteMute",To.SubscribedQualityUpdate="subscribedQualityUpdate",To.LocalTrackUnpublished="localTrackUnpublished",To.LocalTrackSubscribed="localTrackSubscribed",To.Offline="offline",To.SignalRequestResponse="signalRequestResponse",To.SignalConnected="signalConnected",To.RoomMoved="roomMoved",(So=Co||(Co={})).Message="message",So.Muted="muted",So.Unmuted="unmuted",So.Restarted="restarted",So.Ended="ended",So.Subscribed="subscribed",So.Unsubscribed="unsubscribed",So.CpuConstrained="cpuConstrained",So.UpdateSettings="updateSettings",So.UpdateSubscription="updateSubscription",So.AudioPlaybackStarted="audioPlaybackStarted",So.AudioPlaybackFailed="audioPlaybackFailed",So.AudioSilenceDetected="audioSilenceDetected",So.VisibilityChanged="visibilityChanged",So.VideoDimensionsChanged="videoDimensionsChanged",So.VideoPlaybackStarted="videoPlaybackStarted",So.VideoPlaybackFailed="videoPlaybackFailed",So.ElementAttached="elementAttached",So.ElementDetached="elementDetached",So.UpstreamPaused="upstreamPaused",So.UpstreamResumed="upstreamResumed",So.SubscriptionPermissionChanged="subscriptionPermissionChanged",So.SubscriptionStatusChanged="subscriptionStatusChanged",So.SubscriptionFailed="subscriptionFailed",So.TrackProcessorUpdate="trackProcessorUpdate",So.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",So.TranscriptionReceived="transcriptionReceived",So.TimeSyncUpdate="timeSyncUpdate",So.PreConnectBufferFlushed="preConnectBufferFlushed";class No{constructor(e,t,i,n,s){if("object"==typeof e)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(void 0===t||void 0===i)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:n,priority:s}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const Lo=["vp8","h264"],Uo=["vp8","h264","vp9","av1","h265"];const jo=function(e){return!!Lo.find(t=>t===e)};var Fo,Bo,qo,Vo;(Bo=Fo||(Fo={}))[Bo.PREFER_REGRESSION=0]="PREFER_REGRESSION",Bo[Bo.SIMULCAST=1]="SIMULCAST",Bo[Bo.REGRESSION=2]="REGRESSION",(Vo=qo||(qo={})).telephone={maxBitrate:12e3},Vo.speech={maxBitrate:24e3},Vo.music={maxBitrate:48e3},Vo.musicStereo={maxBitrate:64e3},Vo.musicHighQuality={maxBitrate:96e3},Vo.musicHighQualityStereo={maxBitrate:128e3};const zo={h90:new No(160,90,9e4,20),h180:new No(320,180,16e4,20),h216:new No(384,216,18e4,20),h360:new No(640,360,45e4,20),h540:new No(960,540,8e5,25),h720:new No(1280,720,17e5,30),h1080:new No(1920,1080,3e6,30),h1440:new No(2560,1440,5e6,30),h2160:new No(3840,2160,8e6,30)},Ho={h120:new No(160,120,7e4,20),h180:new No(240,180,125e3,20),h240:new No(320,240,14e4,20),h360:new No(480,360,33e4,20),h480:new No(640,480,5e5,20),h540:new No(720,540,6e5,25),h720:new No(960,720,13e5,30),h1080:new No(1440,1080,23e5,30),h1440:new No(1920,1440,38e5,30)},Wo={h360fps3:new No(640,360,2e5,3,"medium"),h360fps15:new No(640,360,4e5,15,"medium"),h720fps5:new No(1280,720,8e5,5,"medium"),h720fps15:new No(1280,720,15e5,15,"medium"),h720fps30:new No(1280,720,2e6,30,"medium"),h1080fps15:new No(1920,1080,25e5,15,"medium"),h1080fps30:new No(1920,1080,5e6,30,"medium"),original:new No(0,0,7e6,30,"medium")};function Ko(e,t,i){var n,s,r,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:d}=ia(null!=e?e:{}),l=null==t?void 0:t.processor,u=null==i?void 0:i.processor,h=null!=a?a:{};return!0===h.audio&&(h.audio={}),!0===h.video&&(h.video={}),h.audio&&(Go(h.audio,t),null!==(n=(r=h.audio).deviceId)&&void 0!==n||(r.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=null!=c?c:l)),h.video&&(Go(h.video,i),null!==(s=(o=h.video).deviceId)&&void 0!==s||(o.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=null!=d?d:u)),h}function Go(e,t){return Object.keys(t).forEach(i=>{void 0===e[i]&&(e[i]=t[i])}),e}function Jo(e){var t,i,n,s;const r={};if(e.video)if("object"==typeof e.video){const i={},s=i,o=e.video;Object.keys(o).forEach(e=>{if("resolution"===e)Go(s,o.resolution);else s[e]=o[e]}),r.video=i,null!==(t=(n=r.video).deviceId)&&void 0!==t||(n.deviceId={ideal:"default"})}else r.video=!!e.video&&{deviceId:{ideal:"default"}};else r.video=!1;return e.audio?"object"==typeof e.audio?(r.audio=e.audio,null!==(i=(s=r.audio).deviceId)&&void 0!==i||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function Qo(e){return Ws(this,arguments,void 0,function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const i=Yo();if(i){const n=i.createAnalyser();n.fftSize=2048;const s=n.frequencyBinCount,r=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield ua(t),n.getByteTimeDomainData(r);const o=r.some(e=>128!==e&&0!==e);return i.close(),!o}return!1}()})}function Yo(){var e;const t="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){const i=new t({latencyHint:"interactive"});if("suspended"===i.state&&"undefined"!=typeof window&&(null===(e=window.document)||void 0===e?void 0:e.body)){const e=()=>Ws(this,void 0,void 0,function*(){var t;try{"suspended"===i.state&&(yield i.resume())}catch(n){console.warn("Error trying to auto-resume audio context",n)}finally{null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)}});i.addEventListener("statechange",()=>{var t;"closed"===i.state&&(null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e))}),window.document.body.addEventListener("click",e)}return i}}function Xo(e){return"audioinput"===e?aa.Source.Microphone:"videoinput"===e?aa.Source.Camera:aa.Source.Unknown}function Zo(e){return e===aa.Source.Microphone?"audioinput":e===aa.Source.Camera?"videoinput":void 0}function $o(e){return e.split("/")[1].toLowerCase()}function ea(e){const t=[];return e.forEach(e=>{void 0!==e.track&&t.push(new Fn({cid:e.track.mediaStreamID,track:e.trackInfo}))}),t}function ta(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?ta(e.track):{})}}function ia(e){const t=Object.assign({},e);let i,n;return"object"==typeof t.audio&&t.audio.processor&&(i=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),"object"==typeof t.video&&t.video.processor&&(n=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:i,videoProcessor:n,optionsWithoutProcessor:(s=t,void 0===s?s:"function"==typeof structuredClone?"object"==typeof s&&null!==s?structuredClone(Object.assign({},s)):structuredClone(s):JSON.parse(JSON.stringify(s)))};var s}function na(e,t){return e.width*e.height<t.width*t.height}const sa=[];var ra,oa;(oa=ra||(ra={}))[oa.LOW=0]="LOW",oa[oa.MEDIUM=1]="MEDIUM",oa[oa.HIGH=2]="HIGH";class aa extends Ys.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var n;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=aa.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Bs,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),5e3):this.handleAppVisibilityChanged()},this.log=qs(null!==(n=i.loggerName)&&void 0!==n?n:Us.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=aa.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),ta(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===aa.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===aa.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(sa.forEach(t=>{null!==t.parentElement||e||(e=t)}),e&&sa.splice(sa.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),ca(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),n=i.some(e=>"audio"===e.kind);return e.play().then(()=>{this.emit(n?Co.AudioPlaybackStarted:Co.VideoPlaybackStarted)}).catch(t=>{"NotAllowedError"===t.name?this.emit(n?Co.AudioPlaybackFailed:Co.VideoPlaybackFailed,t):"AbortError"===t.name?Bs.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):Bs.warn("could not playback ".concat(n?"audio":"video"),t),n&&e&&i.some(e=>"video"===e.kind)&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(Co.ElementAttached,e),e}detach(e){try{if(e){da(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(Co.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(e=>{da(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(Co.ElementDetached,e)}),this.attachedElements=[],t}finally{0===this.attachedElements.length&&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=qs(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),sa.forEach(e=>{e.parentElement||(t=!1)}),t&&sa.push(e)}}handleAppVisibilityChanged(){return Ws(this,void 0,void 0,function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==aa.Kind.Video||setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Ta()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Ta()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function ca(e,t){let i,n;i=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks(),n.includes(e)||(n.forEach(e=>{i.removeTrack(e)}),i.addTrack(e)),ba()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(ba()||fa())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=i,t.play().catch(()=>{})},0))}function da(e,t){if(t.srcObject instanceof MediaStream){const i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}!function(e){let t;var i;let n;var s;let r;var o;(i=t=e.Kind||(e.Kind={})).Audio="audio",i.Video="video",i.Unknown="unknown",(s=n=e.Source||(e.Source={})).Camera="camera",s.Microphone="microphone",s.ScreenShare="screen_share",s.ScreenShareAudio="screen_share_audio",s.Unknown="unknown",(o=r=e.StreamState||(e.StreamState={})).Active="active",o.Paused="paused",o.Unknown="unknown",e.kindToProto=function(e){switch(e){case t.Audio:return Ii.AUDIO;case t.Video:return Ii.VIDEO;default:return Ii.DATA}},e.kindFromProto=function(e){switch(e){case Ii.AUDIO:return t.Audio;case Ii.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return _i.CAMERA;case n.Microphone:return _i.MICROPHONE;case n.ScreenShare:return _i.SCREEN_SHARE;case n.ScreenShareAudio:return _i.SCREEN_SHARE_AUDIO;default:return _i.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case _i.CAMERA:return n.Camera;case _i.MICROPHONE:return n.Microphone;case _i.SCREEN_SHARE:return n.ScreenShare;case _i.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case In.ACTIVE:return r.Active;case In.PAUSED:return r.Paused;default:return r.Unknown}}}(aa||(aa={}));const la="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function ua(e){return Ws(this,void 0,void 0,function*(){return new Promise(t=>Mo.setTimeout(t,e))})}function ha(){return"addTransceiver"in RTCPeerConnection.prototype}function pa(){return"addTrack"in RTCPeerConnection.prototype}function ma(e){return"av1"===e||"vp9"===e}function ga(e){return!(!document||ya())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function fa(){var e;return"Firefox"===(null===(e=so())||void 0===e?void 0:e.name)}function va(){const e=so();return!!e&&"Chrome"===e.name&&"iOS"!==e.os}function ba(){var e;return"Safari"===(null===(e=so())||void 0===e?void 0:e.name)}function ya(){const e=so();return"Safari"===(null==e?void 0:e.name)||"iOS"===(null==e?void 0:e.os)}function ka(){var e,t;return!!Ta()&&(null!==(t=null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile)&&void 0!==t?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function Ta(){return"undefined"!=typeof document}function Ca(){return"ReactNative"==navigator.product}function Sa(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function wa(e){return Sa(e)?e.hostname.split(".")[0]:null}function Ea(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Ra(){if(!Ca())return;let e=Ea();return e?e.platform:void 0}function Pa(){if(Ta())return window.devicePixelRatio;if(Ca()){let e=Ea();if(e)return e.devicePixelRatio}return 1}function xa(e,t){const i=e.split("."),n=t.split("."),s=Math.min(i.length,n.length);for(let r=0;r<s;++r){const e=parseInt(i[r],10),t=parseInt(n[r],10);if(e>t)return 1;if(e<t)return-1;if(r===s-1&&e===t)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function Ia(e){for(const t of e)t.target.handleResize(t)}function _a(e){for(const t of e)t.target.handleVisibilityChanged(t)}let Oa=null;const Da=()=>(Oa||(Oa=new ResizeObserver(Ia)),Oa);let Aa=null;const Ma=()=>(Aa||(Aa=new IntersectionObserver(_a,{root:null,rootMargin:"0px"})),Aa);function Na(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const s=document.createElement("canvas");s.width=e,s.height=t;const r=s.getContext("2d");null==r||r.fillRect(0,0,s.width,s.height),n&&r&&(r.beginPath(),r.arc(e/2,t/2,50,0,2*Math.PI,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=i,a}let La;function Ua(){if(!La){const e=new AudioContext,t=e.createOscillator(),i=e.createGain();i.gain.setValueAtTime(0,0);const n=e.createMediaStreamDestination();if(t.connect(i),i.connect(n),t.start(),[La]=n.stream.getAudioTracks(),!La)throw Error("Could not get empty media stream audio track");La.enabled=!1}return La.clone()}class ja{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,i)=>Ws(this,void 0,void 0,function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})).finally(()=>{var e;this._isResolved=!0,null===(e=this.onFinally)||void 0===e||e.call(this)})}}function Fa(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(void 0!==e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(void 0!==e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function Ba(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function qa(e){switch(e.reason){case lo.LeaveRequest:return e.context;case lo.Cancelled:return Mi.CLIENT_INITIATED;case lo.NotAllowed:return Mi.USER_REJECTED;case lo.ServerUnreachable:return Mi.JOIN_FAILURE;default:return Mi.UNKNOWN_REASON}}function Va(e){return void 0!==e?Number(e):void 0}function za(e){return void 0!==e?BigInt(e):void 0}function Ha(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function Wa(e){return!!e&&e.kind==aa.Kind.Audio}function Ka(e){return!!e&&e.kind==aa.Kind.Video}function Ga(e){return Ha(e)&&Ka(e)}function Ja(e){return Ha(e)&&Wa(e)}function Qa(e){return!!e&&!e.isLocal}function Ya(e){return!!e&&!e.isLocal}function Xa(e){return Qa(e)&&Ka(e)}function Za(e){return e.endsWith("/")?e:"".concat(e,"/")}function $a(e,t){return e.pathname="".concat(Za(e.pathname)).concat(t),e.toString()}function ec(e){if("string"==typeof e)return Dn.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return Dn.fromBinary(new Uint8Array(e));throw new Error("could not decode websocket message: ".concat(typeof e))}const tc="lk_e2ee";var ic,nc,sc,rc,oc,ac,cc,dc;function lc(){return void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||uc()}function uc(){return void 0!==window.RTCRtpScriptTransform}(nc=ic||(ic={})).SetKey="setKey",nc.RatchetRequest="ratchetRequest",nc.KeyRatcheted="keyRatcheted",(sc||(sc={})).KeyRatcheted="keyRatcheted",(oc=rc||(rc={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",oc.EncryptionError="encryptionError",(ac||(ac={})).Error="cryptorError";Ys.EventEmitter;(dc=cc||(cc={}))[dc.InvalidKey=0]="InvalidKey",dc[dc.MissingKey=1]="MissingKey",dc[dc.InternalError=2]="InternalError";class hc extends Ys.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=e=>{var t,i;const{kind:n,data:s}=e.data;switch(n){case"error":if(Bs.error(s.error.message),s.uuid){const e=this.decryptDataRequests.get(s.uuid);if(null==e?void 0:e.reject){e.reject(s.error);break}const t=this.encryptDataRequests.get(s.uuid);if(null==t?void 0:t.reject){t.reject(s.error);break}}this.emit(rc.EncryptionError,s.error,s.participantIdentity);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)});break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)}),this.encryptionEnabled!==s.enabled&&s.participantIdentity===(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))this.emit(rc.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const e=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(rc.ParticipantEncryptionStatusChanged,s.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(ic.KeyRatcheted,s.ratchetResult,s.participantIdentity,s.keyIndex);break;case"decryptDataResponse":const e=this.decryptDataRequests.get(s.uuid);(null==e?void 0:e.resolve)&&e.resolve(s);break;case"encryptDataResponse":const n=this.encryptDataRequests.get(s.uuid);(null==n?void 0:n.resolve)&&n.resolve(s)}},this.onWorkerError=e=>{Bs.error("e2ee worker encountered an error:",{error:e.error}),this.emit(rc.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(!lc())throw new Eo("tried to setup end-to-end encryption on an unsupported browser");if(Bs.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Vs.getLevel()}};this.worker&&(Bs.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){Bs.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):Bs.warn("ignoring server sent trailer as it's empty")}setupEngine(e){e.on(ko.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(fo.TrackPublished,(e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==Wi.NONE,t.identity)),e.on(fo.ConnectionStateChanged,t=>{t===il.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==Wi.NONE,e.identity)})})}).on(fo.TrackUnsubscribed,(e,t,i)=>{var n;const s={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(s)}).on(fo.TrackSubscribed,(e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)}).on(fo.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(e=>{this.postKey(e)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(bo.LocalSenderCreated,(e,t)=>Ws(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),e.localParticipant.on(bo.LocalTrackPublished,e=>{if(!Ka(e.track)||!ya())return;const t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:$o(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}),t.on(ic.SetKey,e=>this.postKey(e)).on(ic.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}encryptData(e){return Ws(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},n=new ja;return n.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,n),this.worker.postMessage(i),n.promise})}handleEncryptedData(e,t,i,n){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const s=crypto.randomUUID(),r={kind:"decryptDataRequest",data:{uuid:s,payload:e,iv:t,participantIdentity:i,keyIndex:n}},o=new ja;return o.onFinally=()=>{this.decryptDataRequests.delete(s)},this.decryptDataRequests.set(s,o),this.worker.postMessage(r),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:n}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const r={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:t,keyIndex:n}};this.worker.postMessage(r)}postEnable(e,t){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?$o(i.mimeType):void 0)}}setupE2EESender(e,t){Ha(e)&&t?this.handleSender(t,e.mediaStreamID,void 0):t||Bs.warn("early return because sender is not ready")}handleReceiver(e,t,i,n){return Ws(this,void 0,void 0,function*(){if(this.worker){if(uc()&&!va()){const s={kind:"decode",participantIdentity:i,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(tc in e&&n){const e={kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}};return void this.worker.postMessage(e)}let s=e.writableStream,r=e.readableStream;if(!s||!r){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,r=t.readable}const o={kind:"decode",data:{readableStream:r,writableStream:s,trackId:t,codec:n,participantIdentity:i,isReuse:tc in e}};this.worker.postMessage(o,[r,s])}e[tc]=!0}})}handleSender(e,t,i){var n;if(!(tc in e)&&this.worker){if(!(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(uc()&&!va()){Bs.info("initialize script transform");const n={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,n)}else{Bs.info("initialize encoded streams");const n=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(s,[n.readable,n.writable])}e[tc]=!0}}}class pc{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new pc),this._instance}addFailedConnectionAttempt(e){var t;const i=wa(new URL(e));if(!i)return;let n=null!==(t=this.failedConnectionAttempts.get(i))&&void 0!==t?t:0;this.failedConnectionAttempts.set(i,n+1),this.backOffPromises.set(i,ua(Math.min(500*Math.pow(2,n),15e3)))}getBackOffPromise(e){const t=new URL(e),i=t&&wa(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),i=t&&wa(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}pc._instance=null;const mc="default";class gc{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new gc),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return Ws(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;if((null===(n=gc.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){Bs.debug("awaiting getUserMedia promise");try{e?yield gc.userMediaPromiseMap.get(e):yield Promise.all(gc.userMediaPromiseMap.values())}catch(r){Bs.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&(!ba()||!t.hasDeviceInUse(e))){if(0===s.filter(t=>t.kind===e).length||s.some(t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n})){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}},i=yield navigator.mediaDevices.getUserMedia(t);s=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach(e=>{e.stop()})}}return t._previousDevices=s,e&&(s=s.filter(t=>t.kind===e)),s}()})}normalizeDeviceId(e,t,i){return Ws(this,void 0,void 0,function*(){if(t!==mc)return t;const n=yield this.getDevices(e),s=n.find(e=>e.deviceId===mc);if(!s)return void Bs.warn("could not reliably determine default device");const r=n.find(e=>e.deviceId!==mc&&e.groupId===(null!=i?i:s.groupId));if(r)return null==r?void 0:r.deviceId;Bs.warn("could not reliably determine default device")})}hasDeviceInUse(e){return e?gc.userMediaPromiseMap.has(e):gc.userMediaPromiseMap.size>0}}var fc,vc;gc.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],gc.userMediaPromiseMap=new Map,(vc=fc||(fc={}))[vc.WAITING=0]="WAITING",vc[vc.RUNNING=1]="RUNNING",vc[vc.COMPLETED=2]="COMPLETED";class bc{constructor(){this.pendingTasks=new Map,this.taskMutex=new qe,this.nextTaskIndex=0}run(e){return Ws(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:fc.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=fc.RUNNING,yield e()}finally{t.status=fc.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return Ws(this,void 0,void 0,function*(){return this.run(()=>Ws(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class yc{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i,n;if(null===(i=t.signal)||void 0===i?void 0:i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const s=new WebSocket(e,null!==(n=t.protocols)&&void 0!==n?n:[]);s.binaryType="arraybuffer",this.ws=s;const r=function(){let{closeCode:e,reason:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return s.close(e,t)};this.opened=new Promise((e,t)=>{s.onopen=()=>{e({readable:new ReadableStream({start(e){s.onmessage=t=>{let{data:i}=t;return e.enqueue(i)},s.onerror=t=>e.error(t)},cancel:r}),writable:new WritableStream({write(e){s.send(e)},abort(){s.close()},close:r}),protocol:s.protocol,extensions:s.extensions}),s.removeEventListener("error",t)},s.addEventListener("error",t)}),this.closed=new Promise((e,t)=>{const i=()=>Ws(this,void 0,void 0,function*(){const i=new Promise(e=>{s.readyState!==WebSocket.CLOSED&&s.addEventListener("close",t=>{e(t)},{once:!0})}),n=yield Promise.race([ua(250),i]);n?e(n):t(new Error("Encountered unspecified websocket error without a timely close event"))});s.onclose=t=>{let{code:n,reason:r}=t;e({closeCode:n,reason:r}),s.removeEventListener("error",i)},s.addEventListener("error",i)}),t.signal&&(t.signal.onabort=()=>s.close()),this.close=r}}const kc=["syncState","trickle","offer","answer","simulate","leave"];var Tc,Cc;(Cc=Tc||(Tc={}))[Cc.CONNECTING=0]="CONNECTING",Cc[Cc.CONNECTED=1]="CONNECTED",Cc[Cc.RECONNECTING=2]="RECONNECTING",Cc[Cc.DISCONNECTING=3]="DISCONNECTING",Cc[Cc.DISCONNECTED=4]="DISCONNECTED";class Sc{get currentState(){return this.state}get isDisconnected(){return this.state===Tc.DISCONNECTING||this.state===Tc.DISCONNECTED}get isEstablishingConnection(){return this.state===Tc.CONNECTING||this.state===Tc.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;this.rtt=0,this.state=Tc.DISCONNECTED,this.log=Bs,this._requestId=0,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=qs(null!==(i=t.loggerName)&&void 0!==i?i:Us.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new bc,this.queuedRequests=[],this.closingLock=new qe,this.connectionLock=new qe,this.state=Tc.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,i,n){return Ws(this,void 0,void 0,function*(){this.state=Tc.CONNECTING,this.options=i;return yield this.connect(e,t,i,n)})}reconnect(e,t,i,n){return Ws(this,void 0,void 0,function*(){if(!this.options)return void this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);this.state=Tc.RECONNECTING,this.clearPingInterval();return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}))})}connect(e,t,i,n){return Ws(this,void 0,void 0,function*(){const s=yield this.connectionLock.lock();this.connectOptions=i;const r=function(){var e;const t=new gn({sdk:fn.JS,protocol:16,version:"2.16.1"});return Ca()&&(t.os=null!==(e=Ra())&&void 0!==e?e:""),t}(),o=i.singlePeerConnection?function(e,t,i){const n=new URLSearchParams;n.set("access_token",e);const s=new Es({clientInfo:t,connectionSettings:new ws({autoSubscribe:!!i.autoSubscribe,adaptiveStream:!!i.adaptiveStream}),reconnect:!!i.reconnect,participantSid:i.sid?i.sid:void 0});i.reconnectReason&&(s.reconnectReason=i.reconnectReason);const r=new Rs({joinRequest:s.toBinary()});return n.set("join_request",btoa(new TextDecoder("utf-8").decode(r.toBinary()))),n}(t,r,i):function(e,t,i){var n;const s=new URLSearchParams;s.set("access_token",e),i.reconnect&&(s.set("reconnect","1"),i.sid&&s.set("sid",i.sid));s.set("auto_subscribe",i.autoSubscribe?"1":"0"),s.set("sdk",Ca()?"reactnative":"js"),s.set("version",t.version),s.set("protocol",t.protocol.toString()),t.deviceModel&&s.set("device_model",t.deviceModel);t.os&&s.set("os",t.os);t.osVersion&&s.set("os_version",t.osVersion);t.browser&&s.set("browser",t.browser);t.browserVersion&&s.set("browser_version",t.browserVersion);i.adaptiveStream&&s.set("adaptive_stream","1");i.reconnectReason&&s.set("reconnect_reason",i.reconnectReason.toString());(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&s.set("network",navigator.connection.type);return s}(t,r,i),a=function(e,t){const i=new URL(function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e));return t.forEach((e,t)=>{i.searchParams.set(t,e)}),$a(i,"rtc")}(e,o),c=$a(new URL(Ba(a)),"validate");return new Promise((e,t)=>Ws(this,void 0,void 0,function*(){var r,o;try{let s=!1;const l=e=>Ws(this,void 0,void 0,function*(){if(s)return;s=!0;const i=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unknown reason";if(!(e instanceof AbortSignal))return t;const i=e.reason;switch(typeof i){case"string":return i;case"object":return i instanceof Error?i.message:t;default:return"toString"in i?i.toString():t}}(e instanceof Event?e.currentTarget:e,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(i)).catch(e=>{this.log.error(e),this.close()}):this.close(),u(),t(wo.cancelled(i))});null==n||n.addEventListener("abort",l);const u=()=>{clearTimeout(h),null==n||n.removeEventListener("abort",l)},h=setTimeout(()=>{l(wo.timeout("room connection has timed out (signal)"))},i.websocketTimeout),p=(e,t)=>{this.handleSignalConnected(e,h,t)},m=new URL(a);m.searchParams.has("access_token")&&m.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(m),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new yc(a);try{this.ws.closed.then(e=>{var i;this.isEstablishingConnection&&t(wo.internal("Websocket got closed during a (re)connection attempt: ".concat(e.reason))),1e3!==e.closeCode&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.closeCode,wasClean:1e3===e.closeCode,state:this.state})),this.state===Tc.CONNECTED&&this.handleOnClose(null!==(i=e.reason)&&void 0!==i?i:"Unexpected WS error"))}).catch(e=>{this.isEstablishingConnection&&t(wo.internal("Websocket error during a (re)connection attempt: ".concat(e)))});const n=yield this.ws.opened.catch(e=>Ws(this,void 0,void 0,function*(){if(this.state!==Tc.CONNECTED){this.state=Tc.DISCONNECTED,clearTimeout(h);const i=yield this.handleConnectionError(e,c);return void t(i)}this.handleWSError(e),t(e)}));if(clearTimeout(h),!n)return;const s=n.readable.getReader();this.streamWriter=n.writable.getWriter();const a=yield s.read();if(s.releaseLock(),!a.value)throw wo.internal("no message received as first message");const d=ec(a.value),l=this.validateFirstMessage(d,null!==(r=i.reconnect)&&void 0!==r&&r);if(!l.isValid)return void t(l.error);"join"===(null===(o=d.message)||void 0===o?void 0:o.case)&&(this.pingTimeoutDuration=d.message.value.pingTimeout,this.pingIntervalDuration=d.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})));p(n,l.shouldProcessFirstMessage?d:void 0),e(l.response)}catch(d){t(d)}finally{u()}}finally{s()}}))})}startReadingLoop(e,t){return Ws(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield ua(this.signalLatency));const{done:t,value:i}=yield e.read();if(t)break;const n=ec(i);this.handleSignalResponse(n)}})}close(){return Ws(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Close method called on signal client";return function*(){if([Tc.DISCONNECTING||Tc.DISCONNECTED].includes(e.state))return void e.log.debug("ignoring signal close as it's already in disconnecting state");const n=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Tc.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});const t=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([t,ua(250)])}}catch(s){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:s}))}finally{t&&(e.state=Tc.DISCONNECTED),n()}}()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Ec(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:Ec(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 Nn({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Ln({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return Ws(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const s=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new Yn({requestId:s,metadata:e,name:t,attributes:n})}),s}()})}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 Qn({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new ds({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:dt.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new fs({timestamp:dt.parse(Date.now()),rtt:dt.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Wn({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Gn({reason:Mi.CLIENT_INITIATED,action:Jn.DISCONNECT})})}sendRequest(e){return Ws(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){const n=!i&&!function(e){const t=kc.indexOf(e.case)>=0;return Bs.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(n&&t.state===Tc.RECONNECTING)return void t.queuedRequests.push(()=>Ws(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield ua(t.signalLatency)),t.isDisconnected)return void t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));if(!t.streamWriter)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);const s=new On({message:e});try{t.useJSON?yield t.streamWriter.write(s.toJsonString()):yield t.streamWriter.write(s.toBinary())}catch(r){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:r}))}}()})}handleSignalResponse(e){var t,i;const n=e.message;if(null==n)return void this.log.debug("received unsupported message",this.logContext);let s=!1;if("answer"===n.case){const e=wc(n.value);this.onAnswer&&this.onAnswer(e,n.value.id,n.value.midToTrackId)}else if("offer"===n.case){const e=wc(n.value);this.onOffer&&this.onOffer(e,n.value.id,n.value.midToTrackId)}else if("trickle"===n.case){const e=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(e,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=n.value.participants)&&void 0!==t?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.value.speakers)&&void 0!==i?i:[]):"leave"===n.case?this.onLeave&&this.onLeave(n.value):"mute"===n.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.value.sid,n.value.muted):"roomUpdate"===n.case?this.onRoomUpdate&&n.value.room&&this.onRoomUpdate(n.value.room):"connectionQuality"===n.case?this.onConnectionQuality&&this.onConnectionQuality(n.value):"streamStateUpdate"===n.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.value):"subscribedQualityUpdate"===n.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.value):"subscriptionPermissionUpdate"===n.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.value):"refreshToken"===n.case?this.onTokenRefresh&&this.onTokenRefresh(n.value):"trackUnpublished"===n.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.value):"subscriptionResponse"===n.case?this.onSubscriptionError&&this.onSubscriptionError(n.value):"pong"===n.case||("pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):"roomMoved"===n.case?(this.onTokenRefresh&&this.onTokenRefresh(n.value.token),this.onRoomMoved&&this.onRoomMoved(n.value)):"mediaSectionsRequirement"===n.case?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(n.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return Ws(this,void 0,void 0,function*(){if(this.state===Tc.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(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(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=Mo.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set",this.logContext)}clearPingTimeout(){this.pingTimeout&&Mo.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=Mo.setInterval(()=>{this.sendPing()},1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set",this.logContext)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Mo.clearInterval(this.pingInterval)}handleSignalConnected(e,t,i){this.state=Tc.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,t){var i,n,s,r,o;return"join"===(null===(i=e.message)||void 0===i?void 0:i.case)?{isValid:!0,response:e.message.value}:this.state===Tc.RECONNECTING&&"leave"!==(null===(n=e.message)||void 0===n?void 0:n.case)?"reconnect"===(null===(s=e.message)||void 0===s?void 0:s.case)?{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&&"leave"===(null===(r=e.message)||void 0===r?void 0:r.case)?{isValid:!1,error:wo.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:wo.internal("Unexpected first message")}:{isValid:!1,error:wo.internal("did not receive join response, got ".concat(null===(o=e.message)||void 0===o?void 0:o.case," instead"))}}handleConnectionError(e,t){return Ws(this,void 0,void 0,function*(){try{const i=yield fetch(t);if(i.status.toFixed(0).startsWith("4")){const e=yield i.text();return wo.notAllowed(e,i.status)}return e instanceof wo?e:wo.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(i){return i instanceof wo?i:wo.serverUnreachable(i instanceof Error?i.message:"server was not reachable")}})}}function wc(e){const t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function Ec(e,t){return new qn({sdp:e.sdp,type:e.type,id:t})}class Rc{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0;){if(!(this.buffer[0].sequence<=e))break;this.pop()}}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class Pc{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const n=i+this.ttl;return this._map.set(e,{value:t,expiresAt:n}),this}get(e){const t=this._map.get(e);if(t){if(!(t.expiresAt<Date.now()))return t.value;this._map.delete(e)}}has(e){const t=this._map.get(e);return!!t&&(!(t.expiresAt<Date.now())||(this._map.delete(e),!1))}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[t,i]of this._map.entries())i.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e(i.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],i=this.asValueMap();for(const[n,s]of i.entries())t.push(e(s,n,i));return t}asValueMap(){const e=new Map;for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(t,i.value);return e}}var xc,Ic,_c,Oc,Dc,Ac={},Mc={},Nc={exports:{}};function Lc(){if(xc)return Nc.exports;xc=1;var e=Nc.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 null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{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 null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%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 null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %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+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{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 null!=e.attribute&&(t+=" %s",null!=e.value&&(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 null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%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:new 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:new 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"+(null!=e.clksrcExt?"=%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+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{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.reg=/(.*)/),e.format||(e.format="%s")})}),Nc.exports}function Uc(){return Ic||(Ic=1,function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var s=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:s&&!i[e.name]&&(i[e.name]={});var r=e.push?{}:s?i[e.name]:i;!function(e,i,n,s){if(s&&!n)i[s]=t(e[1]);else for(var r=0;r<n.length;r+=1)null!=e[r+1]&&(i[n[r]]=t(e[r+1]))}(n.match(e.reg),r,e.names,e.name),e.push&&i[e.push].push(r)},n=Lc(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},r=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(s).forEach(function(e){var t=e[0],s=e.slice(2);"m"===t&&(r.push({rtp:[],fmtp:[]}),o=r[r.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(s))return i(c,o,s)}}),t.media=r,t};var r=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(r,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),s=0;s<n.length;s+=3)i.push({component:n[s],ip:n[s+1],port:n[s+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(r,{})})},e.parseSimulcastStreamList=function(e){return e.split(";").map(function(e){return e.split(",").map(function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}})})}}(Mc)),Mc}function jc(){if(Oc)return _c;Oc=1;var e=Lc(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,s=n.length;return e.replace(t,function(e){if(i>=s)return e;var t=n[i];switch(i+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}})},n=function(e,t,n){var s=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var r=0;r<t.names.length;r+=1){var o=t.names[r];t.name?s.push(n[t.name][o]):s.push(n[t.names[r]])}else s.push(n[t.name]);return i.apply(null,s)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return _c=function(t,i){i=i||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach(function(e){null==e.payloads&&(e.payloads="")});var o=i.outerOrder||s,a=i.innerOrder||r,c=[];return o.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){c.push(n(i,e,t))})})}),t.media.forEach(function(t){c.push(n("m",e.m[0],t)),a.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){c.push(n(i,e,t))})})})}),c.join("\r\n")+"\r\n"}}var Fc=function(){if(Dc)return Ac;Dc=1;var e=Uc(),t=jc(),i=Lc();return Ac.grammar=i,Ac.write=t,Ac.parse=e.parse,Ac.parseParams=e.parseParams,Ac.parseFmtpConfig=e.parseFmtpConfig,Ac.parsePayloads=e.parsePayloads,Ac.parseRemoteCandidates=e.parseRemoteCandidates,Ac.parseImageAttributes=e.parseImageAttributes,Ac.parseSimulcastStreamList=e.parseSimulcastStreamList,Ac}();function Bc(e,t,i){var n,s,r;void 0===t&&(t=50),void 0===i&&(i={});var o=null!=(n=i.isImmediate)&&n,a=null!=(s=i.callback)&&s,c=i.maxWait,d=Date.now(),l=[];var u=function(){var i=[].slice.call(arguments),n=this;return new Promise(function(s,u){var h=o&&void 0===r;if(void 0!==r&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,d=Date.now(),!o){var t=e.apply(n,i);a&&a(t),l.forEach(function(e){return(0,e.resolve)(t)}),l=[]}},function(){if(void 0!==c){var e=Date.now()-d;if(e+t>=c)return c-e}return t}()),h){var p=e.apply(n,i);return a&&a(p),s(p)}l.push({resolve:s,reject:u})})};return u.cancel=function(e){void 0!==r&&clearTimeout(r),l.forEach(function(t){return(0,t.reject)(e)}),l=[]},u}const qc="negotiationStarted",Vc="negotiationComplete",zc="rtpVideoPayloadTypes";class Hc extends Ys.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.log=Bs,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Bc(e=>Ws(this,void 0,void 0,function*(){this.emit(qc);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}),20),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,this._pc=null)},this.log=qs(null!==(i=t.loggerName)&&void 0!==i?i:Us.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new qe}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return Ws(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 Ws(this,void 0,void 0,function*(){var i;if("answer"===e.type&&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("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;const i=[],n=[],s=Fc.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let r=0;return s.media.forEach(e=>{var t;const s=Gc(e.mid);"audio"===e.type&&(e.rtp.some(e=>"opus"===e.codec&&(r=e.payload,!0)),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some(e=>e.payload===r&&"nack"===e.type))&&n.push(s),e.fmtp.some(e=>e.payload===r&&(e.config.includes("sprop-stereo=1")&&i.push(s),!0)))}),{stereoMids:i,nackMids:n}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}else if("answer"===e.type){const t=Fc.parse(null!==(i=e.sdp)&&void 0!==i?i:"");t.media.forEach(e=>{const t=Gc(e.mid);"audio"===e.type&&this.trackBitrates.some(i=>{if(!i.transceiver||t!=i.transceiver.mid)return!1;let n=0;if(e.rtp.some(e=>e.codec.toUpperCase()===i.codec.toUpperCase()&&(n=e.payload,!0)),0===n)return!0;let s=!1;for(const t of e.fmtp)if(t.payload===n){t.config=t.config.split(";").filter(e=>!e.includes("maxaveragebitrate")).join(";"),i.maxbr>0&&(t.config+=";maxaveragebitrate=".concat(1e3*i.maxbr)),s=!0;break}return s||i.maxbr>0&&e.fmtp.push({payload:n,config:"maxaveragebitrate=".concat(1e3*i.maxbr)}),!0})}),n=Fc.write(t)}if(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();else if("answer"===e.type&&(this.emit(Vc),e.sdp)){Fc.parse(e.sdp).media.forEach(e=>{"video"===e.type&&this.emit(zc,e.rtp)})}return!0})}createAndSendOffer(e){return Ws(this,void 0,void 0,function*(){var t;const i=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);yield this._pc.setRemoteDescription(t)}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);const i=this.latestOfferId+1;this.latestOfferId=i;const n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));const s=Fc.parse(null!==(t=n.sdp)&&void 0!==t?t:"");if(s.media.forEach(e=>{Kc(e),"audio"===e.type?Wc(e,["all"],[]):"video"===e.type&&this.trackBitrates.some(t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0)),0===i)return!0;if(ma(t.codec)&&!ba()&&this.ensureVideoDDExtensionForSVC(e,s),!ma(t.codec))return!0;const n=Math.round(.7*t.maxbr);for(const s of e.fmtp)if(s.payload===i){s.config.includes("x-google-start-bitrate")||(s.config+=";x-google-start-bitrate=".concat(n));break}return!0})}),this.latestOfferId>i)return void this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:i}));yield this.setMungedSDP(n,Fc.write(s)),this.onOffer(n,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return Ws(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=Fc.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach(e=>{Kc(e),"audio"===e.type&&Wc(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Fc.write(i)),t})}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 xo("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new xo("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return Ws(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,n=new Map;if((yield this._pc.getStats()).forEach(e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),i.set(e.id,e);break;case"remote-candidate":n.set(e.id,"".concat(e.address,":").concat(e.port))}}),""===t)return;const s=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==s?n.get(s):void 0})}setMungedSDP(e,t,i){return Ws(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{return this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),void(i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(n){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:n,sdp:t})),e.sdp=s}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(n){let t="unknown error";n instanceof Error?t=n.message:"string"==typeof n&&(t=n);const s={error:t,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new Io(t)}})}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null===(i=e.ext)||void 0===i?void 0:i.some(e=>e.uri===la))){if(0===this.ddExtID){let e=0;t.media.forEach(t=>{var i;"video"===t.type&&(null===(i=t.ext)||void 0===i||i.forEach(t=>{t.value>e&&(e=t.value)}))}),this.ddExtID=e+1}null===(n=e.ext)||void 0===n||n.push({value:this.ddExtID,uri:la})}}}function Wc(e,t,i){const n=Gc(e.mid);let s=0;e.rtp.some(e=>"opus"===e.codec&&(s=e.payload,!0)),s>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(n)&&!e.rtcpFb.some(e=>e.payload===s&&"nack"===e.type)&&e.rtcpFb.push({payload:s,type:"nack"}),(t.includes(n)||1===t.length&&"all"===t[0])&&e.fmtp.some(e=>e.payload===s&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0)))}function Kc(e){if(e.connection){const t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}function Gc(e){return"number"==typeof e?e.toFixed(0):e}const Jc="vp8",Qc={audioPreset:qo.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Wo.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Jc,backupCodec:!0,preConnectBuffer:!1},Yc={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Xc={deviceId:{ideal:"default"},resolution:zo.h720.resolution},Zc={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(e){this._retryDelays=void 0!==e?[...e]:Hs}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}},disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!1},$c={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var ed,td;(td=ed||(ed={}))[td.NEW=0]="NEW",td[td.CONNECTING=1]="CONNECTING",td[td.CONNECTED=2]="CONNECTED",td[td.FAILED=3]="FAILED",td[td.CLOSING=4]="CLOSING",td[td.CLOSED=5]="CLOSED";class id{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var n;this.peerConnectionTimeout=$c.peerConnectionTimeout,this.log=Bs,this.updateState=()=>{var e,t;const i=this.state,n=this.requiredTransports.map(e=>e.getConnectionState());n.every(e=>"connected"===e)?this.state=ed.CONNECTED:n.some(e=>"failed"===e)?this.state=ed.FAILED:n.some(e=>"connecting"===e)?this.state=ed.CONNECTING:n.every(e=>"closed"===e)?this.state=ed.CLOSED:n.some(e=>"closed"===e)?this.state=ed.CLOSING:n.every(e=>"new"===e)&&(this.state=ed.NEW),i!==this.state&&(this.log.debug("pc state change: from ".concat(ed[i]," to ").concat(ed[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),null===(t=this.subscriber)||void 0===t?void 0:t.getConnectionState()))},this.log=qs(null!==(n=i.loggerName)&&void 0!==n?n:Us.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired="subscriber-primary"!==t,this.isSubscriberConnectionRequired="subscriber-primary"===t,this.publisher=new Hc(e,i),"publisher-only"!==t&&(this.subscriber=new Hc(e,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,xn.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||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;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,xn.PUBLISHER)},this.publisher.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var i;null===(i=this.onPublisherOffer)||void 0===i||i.call(this,e,t)},this.state=ed.NEW,this.connectionLock=new qe,this.remoteOfferLock=new qe}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isPublisherConnectionRequired=e,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 Ws(this,void 0,void 0,function*(){var e;if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const e=this.publisher;for(const i of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(i)}catch(t){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:t}))}}yield Promise.all([this.publisher.close(),null===(e=this.subscriber)||void 0===e?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return Ws(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return Ws(this,void 0,void 0,function*(){var i;t===xn.PUBLISHER?yield this.publisher.addIceCandidate(e):yield null===(i=this.subscriber)||void 0===i?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return Ws(this,void 0,void 0,function*(){var i,n,s;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:null===(i=this.subscriber)||void 0===i?void 0:i.getSignallingState().toString()}));const r=yield this.remoteOfferLock.lock();try{if(!(yield null===(n=this.subscriber)||void 0===n?void 0:n.setRemoteDescription(e,t)))return;return yield null===(s=this.subscriber)||void 0===s?void 0:s.createAndSetAnswer()}finally{r()}})}updateConfiguration(e,t){var i;this.publisher.setConfiguration(e),null===(i=this.subscriber)||void 0===i||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return Ws(this,void 0,void 0,function*(){var i;const n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null===(i=this.requiredTransports)||void 0===i?void 0:i.map(i=>this.ensureTransportConnected(i,e,t)))}finally{n()}})}negotiate(e){return Ws(this,void 0,void 0,function*(){return new Promise((t,i)=>Ws(this,void 0,void 0,function*(){const n=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout);e.signal.addEventListener("abort",()=>{clearTimeout(n),i("negotiation aborted")}),this.publisher.once(qc,()=>{e.signal.aborted||this.publisher.once(Vc,()=>{clearTimeout(n),t()})}),yield this.publisher.negotiate(e=>{clearTimeout(n),i(e)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const t=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(t=>t.receiver===e);return null==t?void 0:t.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===xn.PUBLISHER||e===xn.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return Ws(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise((e,s)=>Ws(i,void 0,void 0,function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),Mo.clearTimeout(r),s(wo.cancelled("room connection has been cancelled"))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);const r=Mo.setTimeout(()=>{null==t||t.signal.removeEventListener("abort",i),s(wo.internal("could not establish pc connection"))},n);for(;this.state!==ed.CONNECTED;)if(yield ua(50),null==t?void 0:t.signal.aborted)return void s(wo.cancelled("room connection has been cancelled"));Mo.clearTimeout(r),null==t||t.signal.removeEventListener("abort",i),e()}))}()})}}class nd{static fetchRegionSettings(e,t,i){return Ws(this,void 0,void 0,function*(){const n=yield nd.fetchLock.lock();try{const n=yield fetch("".concat(function(e){return"".concat(e.protocol.replace("ws","http"),"//").concat(e.host,"/settings")}(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(n.ok){const e=function(e){var t;const i=e.get("Cache-Control");if(i){const e=null===(t=i.match(/(?:^|[,\s])max-age=(\d+)/))||void 0===t?void 0:t[1];if(e)return parseInt(e,10)}}(n.headers),t=e?1e3*e:5e3;return{regionSettings:yield n.json(),updatedAtInMs:Date.now(),maxAgeInMs:t}}throw 401===n.status?wo.notAllowed("Could not fetch region settings: ".concat(n.statusText),n.status):wo.internal("Could not fetch region settings: ".concat(n.statusText))}catch(s){throw s instanceof wo?s:(null==i?void 0:i.aborted)?wo.cancelled("Region fetching was aborted"):wo.serverUnreachable("Could not fetch region settings, ".concat(s instanceof Error?"".concat(s.name,": ").concat(s.message):s))}finally{n()}})}static scheduleRefetch(e,t,i){return Ws(this,void 0,void 0,function*(){const n=nd.settingsTimeouts.get(e.hostname);clearTimeout(n),nd.settingsTimeouts.set(e.hostname,setTimeout(()=>Ws(this,void 0,void 0,function*(){try{const i=yield nd.fetchRegionSettings(e,t);nd.updateCachedRegionSettings(e,t,i)}catch(n){if(n instanceof wo&&n.reason===lo.NotAllowed)return void Bs.debug("token is not valid, cancelling auto region refresh");Bs.debug("auto refetching of region settings failed",{error:n}),nd.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){nd.cache.set(e.hostname,i),nd.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=nd.settingsTimeouts.get(e);t&&(clearTimeout(t),nd.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=nd.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const t=nd.connectionTrackers.get(e);t&&0===t.connectionCount&&(Bs.debug("stopping region refetch after disconnect delay",{hostname:e}),nd.stopRefetch(e)),t&&(t.cleanupTimeout=void 0)},3e4))}static cancelCleanup(e){const t=nd.connectionTrackers.get(e);(null==t?void 0:t.cleanupTimeout)&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=nd.connectionTrackers.get(e);t||(t={connectionCount:0},nd.connectionTrackers.set(e,t)),t.connectionCount++,nd.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=nd.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),0===t.connectionCount&&nd.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Sa(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return Ws(this,void 0,void 0,function*(){return nd.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return Ws(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=nd.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),nd.updateCachedRegionSettings(this.serverUrl,this.token,t));const i=t.regionSettings.regions.filter(e=>!this.attemptedRegions.find(t=>t.url===e.url));if(i.length>0){const e=i[0];return this.attemptedRegions.push(e),Bs.debug("next region: ".concat(e.region)),e.url}return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){nd.updateCachedRegionSettings(this.serverUrl,this.token,e)}}nd.cache=new Map,nd.settingsTimeouts=new Map,nd.connectionTrackers=new Map,nd.fetchLock=new qe;class sd extends Error{constructor(e,t,i){super(t),this.code=e,this.message=od(t,sd.MAX_MESSAGE_BYTES),this.data=i?od(i,sd.MAX_DATA_BYTES):void 0}static fromProto(e){return new sd(e.code,e.message,e.data)}toProto(){return new un({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new sd(sd.ErrorCode[e],sd.ErrorMessage[e],t)}}sd.MAX_MESSAGE_BYTES=256,sd.MAX_DATA_BYTES=15360,sd.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},sd.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"};function rd(e){return(new TextEncoder).encode(e).length}function od(e,t){if(rd(e)<=t)return e;let i=0,n=e.length;const s=new TextEncoder;for(;i<n;){const r=Math.floor((i+n+1)/2);s.encode(e.slice(0,r)).length<=t?i=r:n=r-1}return e.slice(0,i)}const ad=2e3;function cd(e,t){if(!t)return 0;let i,n;return"bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp?0:8*(i-n)*1e3/(e.timestamp-t.timestamp)}const dd="undefined"!=typeof MediaRecorder;const ld=dd?MediaRecorder:class{constructor(){throw new Error("MediaRecorder is not available in this environment")}};class ud extends ld{constructor(e,t){if(!dd)throw new Error("MediaRecorder is not available in this environment");let i,n;super(new MediaStream([e.mediaStreamTrack]),t);const s=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",r),null==n||n.close(),n=void 0},r=e=>{null==n||n.error(e),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",r),n=void 0};this.byteStream=new ReadableStream({start:e=>{n=e,i=t=>Ws(this,void 0,void 0,function*(){let i;if(t.data.arrayBuffer){const e=yield t.data.arrayBuffer();i=new Uint8Array(e)}else{if(!t.data.byteArray)throw new Error("no data available!");i=t.data.byteArray}void 0!==n&&e.enqueue(i)}),this.addEventListener("dataavailable",i)},cancel:()=>{s()}}),this.addEventListener("stop",s),this.addEventListener("error",r)}}class hd extends aa{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(e,t,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!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=Bc(()=>Ws(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>Ws(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(Co.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new qe,this.pauseUpstreamLock=new qe,this.trackChangeLock=new qe,this.trackChangeLock.lock().then(t=>Ws(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==aa.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return Ws(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!t)return;let n;if(this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{da(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()),this.processor&&e){if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(ca(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}this.sender&&"closed"!==(null===(i=this.sender.transport)||void 0===i?void 0:i.state)&&(yield this.sender.replaceTrack(null!=n?n:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{ca(null!=n?n:e,t)}))})}waitForDimensions(){return Ws(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(e.kind===aa.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(i=so())||void 0===i?void 0:i.os)&&(yield ua(10));const n=Date.now();for(;Date.now()-n<t;){const t=e.dimensions;if(t)return t;yield ua(50)}throw new Ro("unable to get track dimensions after timeout")}()})}setDeviceId(e){return Ws(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Fa(e)||(this._constraints.deviceId=e,!!this.isMuted||(yield this.restartTrack(),Fa(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return Ws(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===aa.Source.ScreenShare)return;const{deviceId:i,groupId:n}=e._mediaStreamTrack.getSettings(),s=e.kind===aa.Kind.Audio?"audioinput":"videoinput";return t?gc.getInstance().normalizeDeviceId(s,i,n):i}()})}mute(){return Ws(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return Ws(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return Ws(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Ro("unable to replace an unpublished track");let i,n;return"boolean"==typeof t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return Ws(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:t,facingMode:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(i[n[s]]=e[n[s]])}return i}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const s={audio:!1,video:!1};this.kind===aa.Kind.Video?s.video=!t&&!i||{deviceId:t,facingMode:i}:s.audio=!t||Object.assign({deviceId:t},n),this.attachedElements.forEach(e=>{da(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const r=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return this.kind===aa.Kind.Video&&(yield r.applyConstraints(n)),r.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(r),this._constraints=e,this.emit(Co.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),this.isMuted===e&&this._mediaStreamTrack.enabled!==e||(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Co.Muted:Co.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Ws(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),ka()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(this.log.debug("track needs to be reacquired, restarting ".concat(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),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return Ws(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to pause upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!0,this.emit(Co.UpstreamPaused,this);const t=so();if("Safari"===(null==t?void 0:t.name)&&xa(t.version,"12.0")<0)throw new Eo("pauseUpstream is not supported on Safari < 12.");"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return Ws(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to resume upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!1,this.emit(Co.UpstreamResumed,this),"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return Ws(this,void 0,void 0,function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;return yield this.sender.getStats()})}setProcessor(e){return Ws(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;const s=yield t.trackChangeLock.lock();try{t.log.debug("setting up processor",t.logContext);const s=document.createElement(t.kind),r={kind:t.kind,track:t._mediaStreamTrack,element:s,audioContext:t.audioContext};if(yield e.init(r),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.internalStopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(ca(t._mediaStreamTrack,s),s.muted=!0,s.play().catch(e=>{e instanceof DOMException&&"AbortError"===e.name?(t.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout(()=>{s.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=s,t.processor.processedTrack){for(const e of t.attachedElements)e!==t.processorElement&&i&&(da(t._mediaStreamTrack,e),ca(t.processor.processedTrack,e));yield null===(n=t.sender)||void 0===n?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit(Co.TrackProcessorUpdate,t.processor)}finally{s()}}()})}getProcessor(){return this.processor}stopProcessor(){return Ws(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}}()})}internalStopProcessor(){return Ws(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n;e.processor&&(e.log.debug("stopping processor",e.logContext),null===(i=e.processor.processedTrack)||void 0===i||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||(null===(n=e.processorElement)||void 0===n||n.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(Co.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(dd)if(this.localTrackRecorder)this.log.warn("preconnect buffer already started");else{{let e="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(e)||(e="video/mp4"),this.localTrackRecorder=new ud(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},1e4)}else this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.mimeType}}class pd extends hd{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,aa.Kind.Audio,t,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>Ws(this,void 0,void 0,function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(t){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:t}))}e&&this.prevStats&&(this._currentBitrate=cd(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(Co.AudioTrackFeatureUpdate,this,Ui.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(Co.AudioTrackFeatureUpdate,this,Ui.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Ws(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===aa.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(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return Ws(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Fa(this._constraints.deviceId);return this.source!==aa.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!t||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return Ws(this,void 0,void 0,function*(){let t;if(e){const i=Jo({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return Ws(this,void 0,void 0,function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){Ta()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},ad)))}setProcessor(e){return Ws(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!Ca()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),this.processor=e,this.processor.processedTrack&&(yield null===(t=this.sender)||void 0===t?void 0:t.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(Co.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return Ws(this,void 0,void 0,function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield this.sender.getStats()).forEach(e=>{"outbound-rtp"===e.type&&(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 Ws(this,void 0,void 0,function*(){const e=yield Qo(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(Co.AudioSilenceDetected)),e})}}const md=Object.values(zo),gd=Object.values(Ho),fd=Object.values(Wo),vd=[zo.h180,zo.h360],bd=[Ho.h180,Ho.h360],yd=["q","h","f"];function kd(e,t,i,n){var s,r;let o=null==n?void 0:n.videoEncoding;e&&(o=null==n?void 0:n.screenShareEncoding);const a=null==n?void 0:n.simulcast,c=null==n?void 0:n.scalabilityMode,d=null==n?void 0:n.videoCodec;if(!o&&!a&&!c||!t||!i)return[{}];o||(o=function(e,t,i,n){const s=function(e,t,i){if(e)return fd;const n=t>i?t/i:i/t;if(Math.abs(n-16/9)<Math.abs(n-4/3))return md;return gd}(e,t,i);let{encoding:r}=s[0];const o=Math.max(t,i);for(let a=0;a<s.length;a+=1){const e=s[a];if(r=e.encoding,e.width>=o)break}if(n)switch(n){case"av1":case"h265":r=Object.assign({},r),r.maxBitrate=.7*r.maxBitrate;break;case"vp9":r=Object.assign({},r),r.maxBitrate=.85*r.maxBitrate}return r}(e,t,i,d),Bs.debug("using video encoding",o));const l=o.maxFramerate,u=new No(t,i,o.maxBitrate,o.maxFramerate,o.priority);if(c&&ma(d)){const e=new wd(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const i=so();if(ya()||Ca()||"Chrome"===(null==i?void 0:i.name)&&xa(null==i?void 0:i.version,"113")<0){const n="h"==e.suffix?2:3,s=function(e){return e||(e=so()),"Safari"===(null==e?void 0:e.name)&&xa(e.version,"18.3")>0||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&xa(e.osVersion,"18.3")>0}(i);for(let i=0;i<e.spatial;i+=1)t.push({rid:yd[2-i],maxBitrate:o.maxBitrate/Math.pow(n,i),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:s?Math.pow(2,i):void 0});t[0].scalabilityMode=c}else t.push({maxBitrate:o.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),Bs.debug("using svc encoding",{encodings:t}),t}if(!a)return[o];let h,p=[];if(p=e?null!==(s=Sd(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:Td(e,u):null!==(r=Sd(null==n?void 0:n.videoSimulcastLayers))&&void 0!==r?r:Td(e,u),p.length>0){const e=p[0];p.length>1&&([,h]=p);const n=Math.max(t,i);if(n>=960&&h)return Cd(t,i,[e,h,u],l);if(n>=480)return Cd(t,i,[e,u],l)}return Cd(t,i,[u])}function Td(e,t){if(e)return[{scaleResolutionDownBy:2,fps:(i=t).encoding.maxFramerate}].map(e=>{var t,n;return new No(Math.floor(i.width/e.scaleResolutionDownBy),Math.floor(i.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!==(t=i.encoding.maxFramerate)&&void 0!==t?t:30)/(null!==(n=e.fps)&&void 0!==n?n:30))))),e.fps,i.encoding.priority)});var i;const{width:n,height:s}=t,r=n>s?n/s:s/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?vd:bd}function Cd(e,t,i,n){const s=[];if(i.forEach((i,r)=>{if(r>=yd.length)return;const o=Math.min(e,t),a={rid:yd[r],scaleResolutionDownBy:Math.max(1,o/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},c=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;c&&(a.maxFramerate=c);const d=fa()||0===r;i.encoding.priority&&d&&(a.priority=i.encoding.priority,a.networkPriority=i.encoding.priority),s.push(a)}),Ca()&&"ios"===Ra()){let e;s.forEach(t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate});let t=!0;s.forEach(i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,Bs.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Bs.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)})}return s}function Sd(e){if(e)return e.sort((e,t)=>{const{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitrate<n.maxBitrate?-1:i.maxBitrate===n.maxBitrate&&i.maxFramerate&&n.maxFramerate?i.maxFramerate>n.maxFramerate?1:-1:0})}class wd{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new 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(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!==(e=this.suffix)&&void 0!==e?e:"")}}class Ed extends hd{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0;super(e,aa.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>Ws(this,void 0,void 0,function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(n){return void this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:n}))}const t=new Map(e.map(e=>[e.rid,e])),i=e.some(e=>"cpu"===e.qualityLimitationReason);if(i!==this.isCpuConstrained&&(this.isCpuConstrained=i,this.isCpuConstrained&&this.emit(Co.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,i)=>{var n;const s=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=cd(t,s)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new qe}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Ta())return;const i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},ad))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return Ws(this,void 0,void 0,function*(){var t,i,n,s,r;yield e.pauseUpstream.call(this);try{for(var o,a=!0,c=Gs(this.simulcastCodecs.values());!(t=(o=yield c.next()).done);a=!0){s=o.value,a=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(null)}}catch(d){i={error:d}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return Ws(this,void 0,void 0,function*(){var t,i,n,s,r;yield e.resumeUpstream.call(this);try{for(var o,a=!0,c=Gs(this.simulcastCodecs.values());!(t=(o=yield c.next()).done);a=!0){s=o.value,a=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(e.mediaStreamTrack)}}catch(d){i={error:d}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Ws(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source!==aa.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return Ws(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==aa.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return Ws(this,void 0,void 0,function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(e=>{var n;if("outbound-rtp"===e.type){const s={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,framesSent:e.framesSent,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,rid:null!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},r=i.get(e.remoteId);r&&(s.jitter=r.jitter,s.packetsLost=r.packetsLost,s.roundTripTime=r.roundTripTime),t.push(s)}}),t.sort((e,t)=>{var i,n;return(null!==(i=t.frameWidth)&&void 0!==i?i:0)-(null!==(n=e.frameWidth)&&void 0!==n?n:0)}),t})}setPublishingQuality(e){const t=[];for(let i=ra.LOW;i<=ra.HIGH;i+=1)t.push(new ss({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(ma(this.codec),t)}restartTrack(e){return Ws(this,void 0,void 0,function*(){var t,i,n,s,r;let o;if(e){const t=Jo({video:e});"boolean"!=typeof t.video&&(o=t.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var a,c=!0,d=Gs(this.simulcastCodecs.values());!(t=(a=yield d.next()).done);c=!0){s=a.value,c=!1;const e=s;e.sender&&"closed"!==(null===(r=e.sender.transport)||void 0===r?void 0:r.state)&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(l){i={error:l}}finally{try{c||t||!(n=d.return)||(yield n.call(d))}finally{if(i)throw i.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return Ws(this,arguments,void 0,function(e){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s,r,o,a,c,d;if(yield t.setProcessor.call(i,e,n),null===(c=i.processor)||void 0===c?void 0:c.processedTrack)try{for(var l,u=!0,h=Gs(i.simulcastCodecs.values());!(s=(l=yield h.next()).done);u=!0){a=l.value,u=!1;const e=a;yield null===(d=e.sender)||void 0===d?void 0:d.replaceTrack(i.processor.processedTrack)}}catch(p){r={error:p}}finally{try{u||s||!(o=h.return)||(yield o.call(h))}finally{if(r)throw r.error}}}()})}setDegradationPreference(e){return Ws(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},5e3))}setPublishingCodecs(e){return Ws(this,void 0,void 0,function*(){var t,i,n,s,r,o,a;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(ma(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,i=Gs(e);!(s=(n=yield i.next()).done);t=!0){a=n.value,t=!1;const e=a;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(this.log.debug("try setPublishingCodec for ".concat(e.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),t&&t.sender)t.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(e.codec),this.logContext),yield Rd(t.sender,t.encodings,e.qualities,this.senderLock,ma(e.codec),this.log,this.logContext));else for(const i of e.qualities)if(i.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(ma(e.codec),e.qualities)}}catch(d){r={error:d}}finally{try{t||s||!(o=i.return)||(yield o.call(i))}finally{if(r)throw r.error}}return c})}setPublishingLayers(e,t){return Ws(this,void 0,void 0,function*(){this.optimizeForPerformance?this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t})):(this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),this.sender&&this.encodings&&(yield Rd(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))})}prioritizePerformance(){return Ws(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const e=this.sender.getParameters();e.encodings=e.encodings.map((e,t)=>{var i;return Object.assign(Object.assign({},e),{active:0===t,scaleResolutionDownBy:Math.max(1,Math.ceil((null!==(i=this.mediaStreamTrack.getSettings().height)&&void 0!==i?i:360)/360)),scalabilityMode:0===t&&ma(this.codec)?"L1T3":void 0,maxFramerate:0===t?15:0,maxBitrate:0===t?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(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Ws(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),ka()&&this.isInBackground&&this.source===aa.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Rd(e,t,i,n,s,r,o){return Ws(this,void 0,void 0,function*(){const a=yield n.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:e,qualities:i,senderEncodings:t}));try{const n=e.getParameters(),{encodings:a}=n;if(!a)return;if(a.length!==t.length)return void r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:a,senderEncodings:t}));let c=!1;if(!1&&a[0].scalabilityMode);else{if(s){i.some(e=>e.enabled)&&i.forEach(e=>e.enabled=!0)}a.forEach((e,n)=>{var s;let a=null!==(s=e.rid)&&void 0!==s?s:"";""===a&&(a="q");const d=Pd(a),l=i.find(e=>e.quality===d);l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,r.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),o),fa()&&(l.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))})}c&&(n.encodings=a,r.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:n.encodings})),yield e.setParameters(n))}finally{a()}})}function Pd(e){switch(e){case"f":default:return ra.HIGH;case"h":return ra.MEDIUM;case"q":return ra.LOW}}function xd(e,t,i,n){if(!i)return[new Ji({quality:ra.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){const n=i[0].scalabilityMode,s=new wd(n),r=[],o="h"==s.suffix?1.5:2,a="h"==s.suffix?2:3;for(let c=0;c<s.spatial;c+=1)r.push(new Ji({quality:Math.min(ra.HIGH,s.spatial-1)-c,width:Math.ceil(e/Math.pow(o,c)),height:Math.ceil(t/Math.pow(o,c)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(a,c)):0,ssrc:0}));return r}return i.map(i=>{var n,s,r;const o=null!==(n=i.scaleResolutionDownBy)&&void 0!==n?n:1;let a=Pd(null!==(s=i.rid)&&void 0!==s?s:"");return new Ji({quality:a,width:Math.ceil(e/o),height:Math.ceil(t/o),bitrate:null!==(r=i.maxBitrate)&&void 0!==r?r:0,ssrc:0})})}const Id="_lossy",_d="_reliable",Od="leave-reconnect";var Dd,Ad;(Ad=Dd||(Dd={}))[Ad.New=0]="New",Ad[Ad.Connected=1]="Connected",Ad[Ad.Disconnected=2]="Disconnected",Ad[Ad.Reconnecting=3]="Reconnecting",Ad[Ad.Closed=4]="Closed";class Md extends Ys.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=$c.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Dd.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=Bs,this.reliableDataSequence=1,this.reliableMessageBuffer=new Rc,this.reliableReceivedState=new Pc(3e4),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>Ws(this,[e],void 0,function(e){var t=this;let{channel:i}=e;return function*(){if(i){if(i.label===_d)t.reliableDCSub=i;else{if(i.label!==Id)return;t.lossyDCSub=i}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label),t.logContext),i.onmessage=t.handleDataMessage}}()}),this.handleDataMessage=e=>Ws(this,void 0,void 0,function*(){var t,i,n,s,r;const o=yield this.dataProcessLock.lock();try{let o;if(e.data instanceof ArrayBuffer)o=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:e.data}));o=yield e.data.arrayBuffer()}const a=Yi.fromBinary(new Uint8Array(o));if(a.sequence>0&&""!==a.participantSid){const e=this.reliableReceivedState.get(a.participantSid);if(e&&a.sequence<=e)return;this.reliableReceivedState.set(a.participantSid,a.sequence)}if("speaker"===(null===(t=a.value)||void 0===t?void 0:t.case))this.emit(ko.ActiveSpeakersUpdate,a.value.value.speakers);else if("encryptedPacket"===(null===(i=a.value)||void 0===i?void 0:i.case)){if(!this.e2eeManager)return void this.log.error("Received encrypted packet but E2EE not set up",this.logContext);const e=yield null===(n=this.e2eeManager)||void 0===n?void 0:n.handleEncryptedData(a.value.value.encryptedValue,a.value.value.iv,a.participantIdentity,a.value.value.keyIndex),t=$i.fromBinary(e.payload),i=new Yi({value:t.value,participantIdentity:a.participantIdentity,participantSid:a.participantSid});"user"===(null===(s=i.value)||void 0===s?void 0:s.case)&&Nd(i,i.value.value),this.emit(ko.DataPacketReceived,i,a.value.value.encryptionType)}else"user"===(null===(r=a.value)||void 0===r?void 0:r.case)&&Nd(a,a.value.value),this.emit(ko.DataPacketReceived,a,Wi.NONE)}finally{o()}}),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:i}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:i}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{const t=0===e.currentTarget.maxRetransmits?Xi.LOSSY:Xi.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const i=e=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up"),this.logContext),this.emit(ko.Disconnected),this.close()},n=Date.now()-this.reconnectStart;let s=this.getNextRetryDelay({elapsedMs:n,retryCount:this.reconnectAttempts});null!==s?(e===Od&&(s=0),this.log.debug("reconnecting in ".concat(s,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Mo.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),s)):i(n)},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===Dd.Connected&&e();const i=()=>{this.off(ko.Disconnected,n),e()},n=()=>{this.off(ko.Restarted,i),t()};this.once(ko.Restarted,i),this.once(ko.Disconnected,n)}),this.updateAndEmitDCBufferStatus=e=>{if(e===Xi.RELIABLE){const t=this.dataChannelForKind(e);t&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount)}const t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(ko.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>Ws(this,void 0,void 0,function*(){if(!this.url)return;(yield fetch(Ba(this.url),{method:"HEAD"}).then(e=>e.ok).catch(()=>!1))&&(this.log.info("detected network reconnected"),(this.client.currentState===Tc.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Tc.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Ni.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>Ws(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Ba(this.url),{method:"HEAD"}),ua(4e3).then(()=>Promise.reject())])}catch(e){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=qs(null!==(t=e.loggerName)&&void 0!==t?t:Us.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Sc(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new qe,this.dataProcessLock=new qe,this.dcBufferStatus=new Map([[Xi.LOSSY,!0],[Xi.RELIABLE,!0]]),this.client.onParticipantUpdate=e=>this.emit(ko.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(ko.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(ko.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(ko.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(ko.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(ko.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(ko.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(ko.SignalRequestResponse,e)}get logContext(){var e,t,i,n,s,r;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(n=null===(i=this.latestJoinResponse)||void 0===i?void 0:i.room)||void 0===n?void 0:n.sid,participant:null===(r=null===(s=this.latestJoinResponse)||void 0===s?void 0:s.participant)||void 0===r?void 0:r.identity,pID:this.participantSid}}join(e,t,i,n){return Ws(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,t,i,n);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),this.subscriberPrimary&&!s.fastPublish||this.negotiate().catch(e=>{Bs.error(e,this.logContext)}),this.registerOnLineListener(),this.clientConfiguration=s.clientConfiguration,this.emit(ko.SignalConnected,s),s}catch(s){if(s instanceof wo&&s.reason===lo.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,i,n);throw s}})}close(){return Ws(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed)e();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(ko.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return Ws(this,void 0,void 0,function*(){var e;yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;const t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new Rc,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return Ws(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Ro("a track with the same ID has already been published");return new Promise((t,i)=>{const n=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(wo.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return Ws(this,void 0,void 0,function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return Ws(this,void 0,void 0,function*(){var t,i;if(this.pcManager&&this.pcManager.currentState!==ed.NEW)return;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid;const n=this.makeRTCConfiguration(e);var s;this.pcManager=new id(n,this.options.singlePeerConnection?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(ko.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=(t,i,n)=>Ws(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(t),this.logContext),["closed","disconnected","failed"].includes(i)&&(this.publisherConnectionPromise=void 0),t===ed.CONNECTED){const t=this.pcState===Dd.New;this.pcState=Dd.Connected,t&&this.emit(ko.Connected,e)}else t===ed.FAILED&&(this.pcState!==Dd.Connected&&this.pcState!==Dd.Reconnecting||(this.pcState=Dd.Disconnected,this.handleDisconnect("peerconnection failed","failed"===n?Ni.RR_SUBSCRIBER_FAILED:Ni.RR_PUBLISHER_FAILED)));const s=this.client.isDisconnected||this.client.currentState===Tc.RECONNECTING,r=[ed.FAILED,ed.CLOSING,ed.CLOSED].includes(t);s&&r&&!this._isClosed&&this.emit(ko.Offline)}),this.pcManager.onTrack=e=>{0!==e.streams.length&&this.emit(ko.MediaTrackAdded,e.track,e.streams[0],e.receiver)},void 0!==(s=null===(i=e.serverInfo)||void 0===i?void 0:i.protocol)&&s>13||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>Ws(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:i})),this.midToTrackId=i,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,i)=>Ws(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;const n=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);n&&this.client.sendAnswer(n,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null===(t=e.track)||void 0===t?void 0:t.sid})),!this.pendingTrackResolvers[e.cid])return void this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(ko.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(ko.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,null===(t=this.regionUrlProvider)||void 0===t||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(ko.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(ko.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(ko.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var t,i;const n={direction:"recvonly"};for(let s=0;s<e.numAudios;s++)null===(t=this.pcManager)||void 0===t||t.addPublisherTransceiverOfKind("audio",n);for(let s=0;s<e.numVideos;s++)null===(i=this.pcManager)||void 0===i||i.addPublisherTransceiverOfKind("video",n);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",Ni.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==e?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:5e3,regionSettings:e.regions})),e.action){case Jn.DISCONNECT:this.emit(ko.Disconnected,null==e?void 0:e.reason),this.close();break;case Jn.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Od);break;case Jn.RESUME:this.handleDisconnect(Od)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const t=[];e.iceServers.forEach(e=>{const i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)}),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ai.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",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.lossyDC=this.pcManager.createPublisherDataChannel(Id,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(_d,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow,this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(Xi.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,8192),262144)}},1e3))}createSender(e,t,i){return Ws(this,void 0,void 0,function*(){if(ha()){return yield this.createTransceiverRTCRtpSender(e,t,i)}if(pa()){this.log.warn("using add-track fallback",this.logContext);return yield this.createRTCRtpSender(e.mediaStreamTrack)}throw new xo("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,n){return Ws(this,void 0,void 0,function*(){if(ha())return this.createSimulcastTransceiverSender(e,t,i,n);if(pa())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new xo("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return Ws(this,void 0,void 0,function*(){if(!this.pcManager)throw new xo("publisher is closed");const n=[];e.mediaStream&&n.push(e.mediaStream),Ka(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:n};i&&(s.sendEncodings=i);return(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,t,i,n){return Ws(this,void 0,void 0,function*(){if(!this.pcManager)throw new xo("publisher is closed");const s={direction:"sendonly"};n&&(s.sendEncodings=n);const r=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,r.sender),r.sender})}createRTCRtpSender(e){return Ws(this,void 0,void 0,function*(){if(!this.pcManager)throw new xo("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return Ws(this,void 0,void 0,function*(){var t,i,n;if(!this._isClosed)if(this.attemptingReconnect)Bs.warn("already attempting reconnect, returning early",this.logContext);else{(null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)!==Ai.DISABLED&&(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==n?n:ed.NEW)!==ed.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let e=!0;s instanceof xo?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),e=!1):s instanceof Ao||(this.fullReconnectOnNext=!0),e?this.handleDisconnect("reconnect",Ni.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(ko.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return Ws(this,void 0,void 0,function*(){var t,i,n;try{if(!this.url||!this.token)throw new xo("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(ko.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Ao;i=yield this.join(null!=e?e:this.url,this.token,this.signalOpts)}catch(s){if(s instanceof wo&&s.reason===lo.NotAllowed)throw new xo("could not reconnect, token might be expired");throw new Ao}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(ko.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==Tc.CONNECTED)throw new Ao("Signal connection got severed during reconnect");null===(t=this.regionUrlProvider)||void 0===t||t.resetAttempts(),this.emit(ko.Restarted)}catch(r){const e=yield null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getNextBestRegionUrl();if(e)return void(yield this.restartConnection(e));throw null===(n=this.regionUrlProvider)||void 0===n||n.resetAttempts(),r}})}resumeConnection(e){return Ws(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new xo("could not reconnect, url or token not saved");if(!this.pcManager)throw new xo("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(ko.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(n){let e="";if(n instanceof Error&&(e=n.message,this.log.error(n.message,Object.assign(Object.assign({},this.logContext),{error:n}))),n instanceof wo&&n.reason===lo.NotAllowed)throw new xo("could not reconnect, token might be expired");if(n instanceof wo&&n.reason===lo.LeaveRequest)throw n;throw new Ao(e)}if(this.emit(ko.SignalResumed),i){const e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Tc.CONNECTED)throw new Ao("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(t=this.reliableDC)||void 0===t?void 0:t.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),(null==i?void 0:i.lastMessageSeq)&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(ko.Resumed)})}waitForPCInitialConnection(e,t){return Ws(this,void 0,void 0,function*(){if(!this.pcManager)throw new xo("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return Ws(this,void 0,void 0,function*(){this.pcState=Dd.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield ua(2e3),!this.pcManager)throw new xo("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Dd.Connected}catch(e){throw this.pcState=Dd.Disconnected,wo.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,i,n){return Ws(this,void 0,void 0,function*(){const s=new Yi({destinationIdentities:[e],kind:Xi.RELIABLE,value:{case:"rpcResponse",value:new ln({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(s,Xi.RELIABLE)})}publishRpcAck(e,t){return Ws(this,void 0,void 0,function*(){const i=new Yi({destinationIdentities:[e],kind:Xi.RELIABLE,value:{case:"rpcAck",value:new dn({requestId:t})}});yield this.sendDataPacket(i,Xi.RELIABLE)})}sendDataPacket(e,t){return Ws(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const t=function(e){var t,i,n,s,r;if("sipDtmf"!==(null===(t=e.value)||void 0===t?void 0:t.case)&&"metrics"!==(null===(i=e.value)||void 0===i?void 0:i.case)&&"speaker"!==(null===(n=e.value)||void 0===n?void 0:n.case)&&"transcription"!==(null===(s=e.value)||void 0===s?void 0:s.case)&&"encryptedPacket"!==(null===(r=e.value)||void 0===r?void 0:r.case))return new $i({value:e.value})}(e);if(t){const i=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:"encryptedPacket",value:new Zi({encryptedValue:i.payload,iv:i.iv,keyIndex:i.keyIndex})}}}t===Xi.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),n=this.dataChannelForKind(t);if(n){if(t===Xi.RELIABLE)yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:i,sequence:e.sequence});else{if(!this.isBufferStatusLow(t))return this.lossyDataDropCount+=1,void(this.lossyDataDropCount%100==0&&this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount),this.logContext));this.lossyDataStatCurrentBytes+=i.byteLength}if(this.attemptingReconnect)return;n.send(i)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return Ws(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(Xi.RELIABLE);const t=this.dataChannelForKind(Xi.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(e=>{t.send(e.data)})),this.updateAndEmitDCBufferStatus(Xi.RELIABLE)})}waitForBufferStatusLow(e){return new Promise((t,i)=>Ws(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const n=()=>i("Engine closed");for(this.once(ko.Closing,n);!this.dcBufferStatus.get(e);)yield ua(10);this.off(ko.Closing,n),t()}}))}ensureDataTransportConnected(e){return Ws(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var n;if(!t.pcManager)throw new xo("PC manager is closed");const s=i?t.pcManager.subscriber:t.pcManager.publisher,r=i?"Subscriber":"Publisher";if(!s)throw wo.internal("".concat(r," connection not set"));let o=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),o=!0),o||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(o=!0),o&&t.negotiate().catch(e=>{Bs.error(e,t.logContext)});const a=t.dataChannelForKind(e,i);if("open"===(null==a?void 0:a.readyState))return;const c=(new Date).getTime()+t.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(s.isICEConnected&&"open"===(null===(n=t.dataChannelForKind(e,i))||void 0===n?void 0:n.readyState))return;yield ua(50)}throw wo.internal("could not establish ".concat(r," connection, state: ").concat(s.getICEConnectionState()))}()})}ensurePublisherConnected(e){return Ws(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!!this.pcManager&&(this.pcManager.currentState===ed.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED))}negotiate(){return Ws(this,void 0,void 0,function*(){return new Promise((e,t)=>Ws(this,void 0,void 0,function*(){if(!this.pcManager)return void t(new Io("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();const i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(ko.Closing,n),this.pcManager.publisher.once(zc,e=>{const t=new Map;e.forEach(e=>{const i=e.codec.toLowerCase();var n;n=i,Uo.includes(n)&&t.set(e.payload,i)}),this.emit(ko.RTPVideoMapUpdate,t)});try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof Io&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Ni.RR_UNKNOWN),t(s)}finally{this.off(ko.Closing,n)}}))})}dataChannelForKind(e,t){if(t){if(e===Xi.LOSSY)return this.lossyDCSub;if(e===Xi.RELIABLE)return this.reliableDCSub}else{if(e===Xi.LOSSY)return this.lossyDC;if(e===Xi.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,n,s,r;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);const o=this.pcManager.publisher.getLocalDescription(),a=this.pcManager.publisher.getRemoteDescription(),c=null===(i=this.pcManager.subscriber)||void 0===i?void 0:i.getRemoteDescription(),d=null===(n=this.pcManager.subscriber)||void 0===n?void 0:n.getLocalDescription(),l=null===(r=null===(s=this.signalOpts)||void 0===s?void 0:s.autoSubscribe)||void 0===r||r,u=new Array,h=new Array;e.forEach(e=>{e.isDesired!==l&&u.push(e.trackSid),e.isEnabled||h.push(e.trackSid)}),this.client.sendSyncState(new hs({answer:this.options.singlePeerConnection?a?Ec({sdp:a.sdp,type:a.type}):void 0:d?Ec({sdp:d.sdp,type:d.type}):void 0,offer:this.options.singlePeerConnection?o?Ec({sdp:o.sdp,type:o.type}):void 0:c?Ec({sdp:c.sdp,type:c.type}):void 0,subscription:new zn({trackSids:u,subscribe:!l,participantTracks:[]}),publishTracks:ea(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:h,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new ps({publisherSid:t,lastSeq:e}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(t,i)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new ms({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(Xi.LOSSY),xn.PUBLISHER),t(this.dataChannelForKind(Xi.RELIABLE),xn.PUBLISHER),t(this.dataChannelForKind(Xi.LOSSY,!0),xn.SUBSCRIBER),t(this.dataChannelForKind(Xi.RELIABLE,!0),xn.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Mo.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Ta()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){Ta()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const i=null===(t=this.pcManager)||void 0===t?void 0:t.getMidForReceiver(e);if(i){const e=Object.entries(this.midToTrackId).find(e=>{let[t]=e;return t===i});if(e)return e[1]}}}function Nd(e,t){const i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;const n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}class Ld{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if("number"==typeof this.totalByteSize&&0!==this.totalByteSize){if(e&&this.bytesReceived<this.totalByteSize)throw new Do("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),ho.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Do("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),ho.LengthExceeded)}}constructor(e,t,i,n){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=n}}class Ud extends Ld{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();let t=new ja,i=null,n=null;if(this.signal){const e=this.signal;n=()=>{var i;null===(i=t.reject)||void 0===i||i.call(t,e.reason)},e.addEventListener("abort",n),i=e}const s=()=>{e.releaseLock(),i&&n&&i.removeEventListener("abort",n),this.signal=void 0};return{next:()=>Ws(this,void 0,void 0,function*(){var i,n;try{const{done:s,value:r}=yield Promise.race([e.read(),t.promise,null!==(n=null===(i=this.outOfBandFailureRejectingFuture)||void 0===i?void 0:i.promise)&&void 0!==n?n:new Promise(()=>{})]);return s?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(r),{done:!1,value:r.content})}catch(bl){throw s(),bl}}),return(){return Ws(this,void 0,void 0,function*(){return s(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Ws(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,s,r;let o=new Set;const a=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=Gs(a);!(i=(c=yield l.next()).done);d=!0){r=c.value,d=!1;const e=r;o.add(e)}}catch(u){n={error:u}}finally{try{d||i||!(s=l.return)||(yield s.call(l))}finally{if(n)throw n.error}}return Array.from(o)}()})}}class jd extends Ld{constructor(e,t,i,n){super(e,t,i,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Va(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0});let i=new ja,n=null,s=null;if(this.signal){const e=this.signal;s=()=>{var t;null===(t=i.reject)||void 0===t||t.call(i,e.reason)},e.addEventListener("abort",s),n=e}const r=()=>{e.releaseLock(),n&&s&&n.removeEventListener("abort",s),this.signal=void 0};return{next:()=>Ws(this,void 0,void 0,function*(){var n,s;try{const{done:r,value:o}=yield Promise.race([e.read(),i.promise,null!==(s=null===(n=this.outOfBandFailureRejectingFuture)||void 0===n?void 0:n.promise)&&void 0!==s?s:new Promise(()=>{})]);if(r)return this.validateBytesReceived(!0),{done:!0,value:void 0};{let e;this.handleChunkReceived(o);try{e=t.decode(o.content)}catch(bl){throw new Do("Cannot decode datastream chunk ".concat(o.chunkIndex," as text: ").concat(bl),ho.DecodeFailed)}return{done:!1,value:e}}}catch(bl){throw r(),bl}}),return(){return Ws(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Ws(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,s,r;let o="";const a=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=Gs(a);!(i=(c=yield l.next()).done);d=!0){r=c.value,d=!1;o+=r}}catch(u){n={error:u}}finally{try{d||i||!(s=l.return)||(yield s.call(l))}finally{if(n)throw n.error}}return o}()})}}class Fd{constructor(){this.log=Bs,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 Do('A text stream handler for topic "'.concat(e,'" has already been set.'),ho.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Do('A byte stream handler for topic "'.concat(e,'" has already been set.'),ho.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,i,n,s;const r=Array.from(this.textStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e),o=Array.from(this.byteStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e);if(r.length>0||o.length>0){const a=new Do("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),ho.AbnormalEnd);for(const[e,n]of o)null===(i=(t=n.outOfBandFailureRejectingFuture).reject)||void 0===i||i.call(t,a),this.byteStreamControllers.delete(e);for(const[e,t]of r)null===(s=(n=t.outOfBandFailureRejectingFuture).reject)||void 0===s||s.call(n,a),this.textStreamControllers.delete(e)}}handleDataStreamPacket(e,t){return Ws(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 new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t,i){return Ws(this,void 0,void 0,function*(){var n;if("byteHeader"===e.contentHeader.case){const s=this.byteStreamHandlers.get(e.topic);if(!s)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);let r;const o=new ja;o.promise.catch(e=>{this.log.error(e)});const a={id:e.streamId,name:null!==(n=e.contentHeader.value.name)&&void 0!==n?n:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Va(e.timestamp),attributes:e.attributes,encryptionType:i},c=new ReadableStream({start:i=>{if(r=i,this.textStreamControllers.has(e.streamId))throw new Do("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),ho.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:r,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:o})}});s(new Ud(a,c,Va(e.totalLength),o),{identity:t})}else if("textHeader"===e.contentHeader.case){const n=this.textStreamHandlers.get(e.topic);if(!n)return void this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);let s;const r=new ja;r.promise.catch(e=>{this.log.error(e)});const o={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:i},a=new ReadableStream({start:i=>{if(s=i,this.textStreamControllers.has(e.streamId))throw new Do("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),ho.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:o,controller:s,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:r})}});n(new jd(o,a,Va(e.totalLength),r),{identity:t})}})}handleStreamChunk(e,t){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new Do("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),ho.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new Do("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),ho.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&n.controller.enqueue(e))}handleStreamTrailer(e,t){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new Do("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),ho.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new Do("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),ho.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class Bd{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return Ws(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null===(e=this.onClose)||void 0===e||e.call(this)})}}class qd extends Bd{}class Vd extends Bd{}class zd{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return Ws(this,void 0,void 0,function*(){var i;const n=crypto.randomUUID(),s=(new TextEncoder).encode(e).byteLength,r=null===(i=null==t?void 0:t.attachments)||void 0===i?void 0:i.map(()=>crypto.randomUUID()),o=new Array(r?r.length+1:1).fill(0),a=(e,i)=>{var n;o[i]=e;const s=o.reduce((e,t)=>e+t,0);null===(n=null==t?void 0:t.onProgress)||void 0===n||n.call(t,s)},c=yield this.streamText({streamId:n,totalSize:s,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:r,attributes:null==t?void 0:t.attributes});return yield c.write(e),a(1,0),yield c.close(),(null==t?void 0:t.attachments)&&r&&(yield Promise.all(t.attachments.map((e,i)=>Ws(this,void 0,void 0,function*(){return this._sendFile(r[i],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{a(e,i+1)}})})))),c.info})}streamText(e){return Ws(this,void 0,void 0,function*(){var t,i,n;const s=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),r={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==e?void 0:e.topic)&&void 0!==i?i:"",size:null==e?void 0:e.totalSize,attributes:null==e?void 0:e.attributes,encryptionType:(null===(n=this.engine.e2eeManager)||void 0===n?void 0:n.isDataChannelEncryptionEnabled)?Wi.GCM:Wi.NONE},o=new wn({streamId:s,mimeType:r.mimeType,topic:r.topic,timestamp:za(r.timestamp),totalLength:za(null==e?void 0:e.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new Cn({version:null==e?void 0:e.version,attachedStreamIds:null==e?void 0:e.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:"update"===(null==e?void 0:e.type)?Tn.UPDATE:Tn.CREATE})}}),a=null==e?void 0:e.destinationIdentities,c=new Yi({destinationIdentities:a,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,Xi.RELIABLE);let d=0;const l=this.engine,u=new WritableStream({write(e){return Ws(this,void 0,void 0,function*(){for(const t of function(e,t){const i=[];let n=(new TextEncoder).encode(e);for(;n.length>t;){let e=t;for(;e>0;){const t=n[e];if(void 0!==t&&128!=(192&t))break;e--}i.push(n.slice(0,e)),n=n.slice(e)}return n.length>0&&i.push(n),i}(e,15e3)){const e=new En({content:t,streamId:s,chunkIndex:za(d)}),i=new Yi({destinationIdentities:a,value:{case:"streamChunk",value:e}});yield l.sendDataPacket(i,Xi.RELIABLE),d+=1}})},close(){return Ws(this,void 0,void 0,function*(){const e=new Rn({streamId:s}),t=new Yi({destinationIdentities:a,value:{case:"streamTrailer",value:e}});yield l.sendDataPacket(t,Xi.RELIABLE)})},abort(e){console.log("Sink error:",e)}});let h=()=>Ws(this,void 0,void 0,function*(){yield p.close()});l.once(ko.Closing,h);const p=new qd(u,r,()=>this.engine.off(ko.Closing,h));return p})}sendFile(e,t){return Ws(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return Ws(this,void 0,void 0,function*(){var n;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(n=null==i?void 0:i.mimeType)&&void 0!==n?n:t.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),r=t.stream().getReader();for(;;){const{done:e,value:t}=yield r.read();if(e)break;yield s.write(t)}return yield s.close(),s.info})}streamBytes(e){return Ws(this,void 0,void 0,function*(){var t,i,n,s,r,o;const a=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),c=null==e?void 0:e.destinationIdentities,d={id:a,mimeType:null!==(i=null==e?void 0:e.mimeType)&&void 0!==i?i:"application/octet-stream",topic:null!==(n=null==e?void 0:e.topic)&&void 0!==n?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!==(s=null==e?void 0:e.name)&&void 0!==s?s:"unknown",encryptionType:(null===(r=this.engine.e2eeManager)||void 0===r?void 0:r.isDataChannelEncryptionEnabled)?Wi.GCM:Wi.NONE},l=new wn({totalLength:za(null!==(o=d.size)&&void 0!==o?o:0),mimeType:d.mimeType,streamId:a,topic:d.topic,timestamp:za(Date.now()),attributes:d.attributes,contentHeader:{case:"byteHeader",value:new Sn({name:d.name})}}),u=new Yi({destinationIdentities:c,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(u,Xi.RELIABLE);let h=0;const p=new qe,m=this.engine,g=this.log,f=new WritableStream({write(e){return Ws(this,void 0,void 0,function*(){const t=yield p.lock();let i=0;try{for(;i<e.byteLength;){const t=e.slice(i,i+15e3),n=new Yi({destinationIdentities:c,value:{case:"streamChunk",value:new En({content:t,streamId:a,chunkIndex:za(h)})}});yield m.sendDataPacket(n,Xi.RELIABLE),h+=1,i+=t.byteLength}}finally{t()}})},close(){return Ws(this,void 0,void 0,function*(){const e=new Rn({streamId:a}),t=new Yi({destinationIdentities:c,value:{case:"streamTrailer",value:e}});yield m.sendDataPacket(t,Xi.RELIABLE)})},abort(e){g.error("Sink error:",e)}});return new Vd(f,d)})}}class Hd extends aa{constructor(e,t,i,n,s){super(e,i,s),this.sid=t,this.receiver=n}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Co.Muted:Co.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.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(Co.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return Ws(this,void 0,void 0,function*(){var e;if(!(null===(e=this.receiver)||void 0===e?void 0:e.getStats))return;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||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),ad)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=null===(t=this.receiver)||void 0===t?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:e,rtpTimestamp:t}=i;t&&this.rtpTimestamp!==t&&(this.emit(Co.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class Wd extends Hd{constructor(e,t,i,n,s,r){super(e,t,aa.Kind.Audio,i,r),this.monitorReceiver=()=>Ws(this,void 0,void 0,function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=cd(e,this.prevStats)),this.prevStats=e}),this.audioContext=n,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;Ca()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Ca())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return Ws(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(ga(t))return t.setSinkId(e)}))})}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&ga(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 i=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{i.connect(e),i=e}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then(()=>{"running"!==e.state&&this.emit(Co.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(e=>{this.emit(Co.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return Ws(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield this.receiver.getStats()).forEach(t=>{"inbound-rtp"===t.type&&(e={type:"audio",streamId:t.id,timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})}),e})}}class Kd extends Hd{constructor(e,t,i,n,s){super(e,t,aa.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>Ws(this,void 0,void 0,function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=cd(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=Bc(()=>{this.updateDimensions()},100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===aa.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?da(this._mediaStreamTrack,t):ca(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t.element===e)){const t=new Gd(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t===e)?(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)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);const t=this.elementInfos.filter(t=>t===e);for(const i of t)i.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(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return Ws(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",n=new Map;return e.forEach(e=>{"inbound-rtp"===e.type?(i=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}):"codec"===e.type&&n.set(e.id,e)}),t&&""!==i&&n.get(i)&&(t.mimeType=n.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(t=>t.element===e);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Ws(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;const n=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),s=!(null!==(i=null===(t=this.adaptiveStreamSettings)||void 0===t?void 0:t.pauseVideoInBackground)&&void 0!==i&&!i)&&this.isInBackground,r=this.elementInfos.some(e=>e.pictureInPicture),o=this.elementInfos.some(e=>e.visible)&&!s||r;(this.lastVisible!==o||e)&&(!o&&Date.now()-n<100?Mo.setTimeout(()=>{this.updateVisibility()},100):(this.lastVisible=o,this.emit(Co.VisibilityChanged,o,this)))}updateDimensions(){var e,t;let i=0,n=0;const s=this.getPixelDensity();for(const r of this.elementInfos){const e=r.width()*s,t=r.height()*s;e+t>i+n&&(i=e,n=t)}(null===(e=this.lastDimensions)||void 0===e?void 0:e.width)===i&&(null===(t=this.lastDimensions)||void 0===t?void 0:t.height)===n||(this.lastDimensions={width:i,height:n},this.emit(Co.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;if("screen"===t)return Pa();if(!t){return Pa()>2?2:1}return t}}class Gd{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.isPiP=Jd(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t,i;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Jd(this.element),null===(i=this.handleVisibilityChanged)||void 0===i||i.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=Jd(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:Qd(e),this.isPiP=Ta()&&Jd(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=Qd(this.element),this.isPiP=Jd(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Ma().observe(this.element),Da().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null===(e=window.documentPictureInPicture)||void 0===e||e.addEventListener("enter",this.onEnterPiP),null===(i=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===i||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,n,s;null===(e=Ma())||void 0===e||e.unobserve(this.element),null===(t=Da())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(i=window.documentPictureInPicture)||void 0===i||i.removeEventListener("enter",this.onEnterPiP),null===(s=null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)||void 0===s||s.removeEventListener("pagehide",this.onLeavePiP)}}function Jd(e){var t,i;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&Qd(e,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function Qd(e,t){const i=t||window;let n=e.offsetTop,s=e.offsetLeft;const r=e.offsetWidth,o=e.offsetHeight,{hidden:a}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,s+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&s<i.pageXOffset+i.innerWidth&&n+o>i.pageYOffset&&s+r>i.pageXOffset&&!a&&"none"!==c}class Yd extends Ys.EventEmitter{constructor(e,t,i,n){var s;super(),this.metadataMuted=!1,this.encryption=Wi.NONE,this.log=Bs,this.handleMuted=()=>{this.emit(Co.Muted)},this.handleUnmuted=()=>{this.emit(Co.Unmuted)},this.log=qs(null!==(s=null==n?void 0:n.loggerName)&&void 0!==s?s:Us.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=aa.Source.Unknown}setTrack(e){this.track&&(this.track.off(Co.Muted,this.handleMuted),this.track.off(Co.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(Co.Muted,this.handleMuted),e.on(Co.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),ta(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==Wi.NONE}get audioTrack(){if(Wa(this.track))return this.track}get videoTrack(){if(Ka(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=aa.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===aa.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}))}}var Xd,Zd,$d,el,tl,il,nl;Xd=Yd||(Yd={}),(Zd=Xd.SubscriptionStatus||(Xd.SubscriptionStatus={})).Desired="desired",Zd.Subscribed="subscribed",Zd.Unsubscribed="unsubscribed",($d=Xd.PermissionStatus||(Xd.PermissionStatus={})).Allowed="allowed",$d.NotAllowed="not_allowed";class sl extends Yd{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit(Co.Ended)},this.handleCpuConstrained=()=>{this.track&&Ka(this.track)&&this.emit(Co.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(Co.Ended,this.handleTrackEnded),this.track.off(Co.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(Co.Ended,this.handleTrackEnded),e.on(Co.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 Ws(this,void 0,void 0,function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()})}unmute(){return Ws(this,void 0,void 0,function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()})}pauseUpstream(){return Ws(this,void 0,void 0,function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()})}resumeUpstream(){return Ws(this,void 0,void 0,function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Wa(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(Ui.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(Ui.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(Ui.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(Ui.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||i.add(Ui.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(Ui.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}return[]}}function rl(e,t){return Ws(this,void 0,void 0,function*(){null!=e||(e={});let i=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:r}=ia(e);let o=r.audio,a=r.video;if(n&&"object"==typeof r.audio&&(r.audio.processor=n),s&&"object"==typeof r.video&&(r.video.processor=s),e.audio&&"object"==typeof r.audio&&"string"==typeof r.audio.deviceId){const e=r.audio.deviceId;r.audio.deviceId={exact:e},i=!0,o=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:e}})}if(r.video&&"object"==typeof r.video&&"string"==typeof r.video.deviceId){const e=r.video.deviceId;r.video.deviceId={exact:e},i=!0,a=Object.assign(Object.assign({},r.video),{deviceId:{ideal:e}})}!0===r.audio?r.audio={deviceId:"default"}:"object"==typeof r.audio&&null!==r.audio&&(r.audio=Object.assign(Object.assign({},r.audio),{deviceId:r.audio.deviceId||"default"})),!0===r.video?r.video={deviceId:"default"}:"object"!=typeof r.video||r.video.deviceId||(r.video.deviceId="default");const c=Ko(r,Yc,Xc),d=Jo(c),l=navigator.mediaDevices.getUserMedia(d);r.audio&&(gc.userMediaPromiseMap.set("audioinput",l),l.catch(()=>gc.userMediaPromiseMap.delete("audioinput"))),r.video&&(gc.userMediaPromiseMap.set("videoinput",l),l.catch(()=>gc.userMediaPromiseMap.delete("videoinput")));try{const e=yield l;return yield Promise.all(e.getTracks().map(i=>Ws(this,void 0,void 0,function*(){const r="audio"===i.kind;let o,a=r?c.audio:c.video;"boolean"!=typeof a&&a||(a={});const l=r?d.audio:d.video;"boolean"!=typeof l&&(o=l);const u=i.getSettings().deviceId;(null==o?void 0:o.deviceId)&&Fa(o.deviceId)!==u?o.deviceId=u:o||(o={deviceId:u});const h=function(e,t,i){switch(e.kind){case"audio":return new pd(e,t,!1,void 0,i);case"video":return new Ed(e,t,!1,i);default:throw new Ro("unsupported track type: ".concat(e.kind))}}(i,o,t);return h.kind===aa.Kind.Video?h.source=aa.Source.Camera:h.kind===aa.Kind.Audio&&(h.source=aa.Source.Microphone),h.mediaStream=e,Wa(h)&&n?yield h.setProcessor(n):Ka(h)&&s&&(yield h.setProcessor(s)),h})))}catch(u){if(!i)throw u;return rl(Object.assign(Object.assign({},e),{audio:o,video:a}),t)}})}(tl=el||(el={})).Excellent="excellent",tl.Good="good",tl.Poor="poor",tl.Lost="lost",tl.Unknown="unknown";class ol extends Ys.EventEmitter{get logContext(){var e,t;return Object.assign({},null===(t=null===(e=this.loggerOptions)||void 0===e?void 0:e.loggerContextCb)||void 0===t?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return(null===(e=this.permissions)||void 0===e?void 0:e.agent)||this.kind===zi.AGENT}get isActive(){var e;return(null===(e=this.participantInfo)||void 0===e?void 0:e.state)===Vi.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,n,s,r){let o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:zi.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=el.Unknown,this.log=Bs,this.log=qs(null!==(a=null==r?void 0:r.loggerName)&&void 0!==a?a:Us.Participant),this.loggerOptions=r,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=null!=s?s:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new ja,this.once(bo.Active,()=>{var e,t;null===(t=null===(e=this.activeFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.activeFuture=void 0})),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(aa.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(aa.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(aa.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){var t;return!(this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version)&&(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===Vi.ACTIVE&&(null===(t=this.participantInfo)||void 0===t?void 0:t.state)!==Vi.ACTIVE&&this.emit(bo.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(bo.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(bo.ParticipantNameChanged,e)}_setAttributes(e){const t=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});const n=[...Object.keys(t),...Object.keys(e)],s={};for(const r of n)e[r]!==t[r]&&(s[r]=null!==(i=t[r])&&void 0!==i?i:"");return s}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(bo.AttributesChanged,t)}setPermissions(e){var t,i,n,s,r,o;const a=this.permissions,c=e.canPublish!==(null===(t=this.permissions)||void 0===t?void 0:t.canPublish)||e.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||e.canPublishData!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishData)||e.hidden!==(null===(s=this.permissions)||void 0===s?void 0:s.hidden)||e.recorder!==(null===(r=this.permissions)||void 0===r?void 0:r.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])})||e.canSubscribeMetrics!==(null===(o=this.permissions)||void 0===o?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit(bo.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(bo.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case Di.EXCELLENT:return el.Excellent;case Di.GOOD:return el.Good;case Di.POOR:return el.Poor;case Di.LOST:return el.Lost;default:return el.Unknown}}(e),t!==this._connectionQuality&&this.emit(bo.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&(null===(t=(e=this.activeFuture).reject)||void 0===t||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>Wa(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(Co.Muted,()=>{this.emit(bo.TrackMuted,e)}),e.on(Co.Unmuted,()=>{this.emit(bo.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case aa.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case aa.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class al extends ol{constructor(e,t,i,n,s,r){super(e,t,void 0,void 0,void 0,{loggerName:n.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Wi.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new ja)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,i,n,s,r;this.reconnectFuture&&(this.reconnectFuture.promise.catch(e=>this.log.warn(e.message,this.logContext)),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null===(n=(i=this.signalConnectedFuture).reject)||void 0===n||n.call(i,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),null===(r=null===(s=this.activeAgentFuture)||void 0===s?void 0:s.reject)||void 0===r||r.call(s,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,i;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new ja),null===(i=(t=this.signalConnectedFuture).resolve)||void 0===i||i.call(t)},this.handleSignalRequestResponse=e=>{const{requestId:t,reason:i,message:n}=e,s=this.pendingSignalRequests.get(t);s&&(i!==Cs.OK&&s.reject(new Oo(n,i)),this.pendingSignalRequests.delete(t))},this.handleDataPacket=e=>{switch(e.value.case){case"rpcResponse":let t=e.value.value,i=null,n=null;"payload"===t.value.case?i=t.value.value:"error"===t.value.case&&(n=sd.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,i,n);break;case"rpcAck":let s=e.value.value;this.handleIncomingRpcAck(s.requestId)}},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=>function(e){var t,i,n;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new cs({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(i=e.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=e.allowAll)&&void 0!==n&&n,trackSids:e.allowedTrackSids||[]})}(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),ta(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),ta(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),ta(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{const t=this.audioTrackPublications.get(e.sid);t?this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext)},this.onTrackCpuConstrained=(e,t)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),ta(t))),this.emit(bo.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>Ws(this,void 0,void 0,function*(){var t,i,n,s,r;if(!(null===(r=this.roomOptions)||void 0===r?void 0:r.dynacast))return;const o=this.videoTrackPublications.get(e.trackSid);if(!o)return void this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));if(!o.videoTrack)return;const a=yield o.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=Gs(a);!(t=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;jo(e)&&(this.log.debug("publish ".concat(e," for ").concat(o.videoTrack.sid),Object.assign(Object.assign({},this.logContext),ta(o))),yield this.publishAdditionalCodecForTrack(o.videoTrack,e,o.options))}}catch(u){i={error:u}}finally{try{d||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}}),this.handleLocalTrackUnpublished=e=>{const t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))},this.handleTrackEnded=e=>Ws(this,void 0,void 0,function*(){if(e.source===aa.Source.ScreenShare||e.source===aa.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),ta(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(Ja(e)||Ga(e))try{if(Ta())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===aa.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),ta(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(t){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),ta(e))),Ja(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),ta(e))),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s,this.roomOutgoingDataStreamManager=r}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Wi.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(ko.RemoteMute,(e,t)=>{const i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.unmute())}),(null===(t=this.signalConnectedFuture)||void 0===t?void 0:t.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(ko.Connected,this.handleReconnected).on(ko.SignalConnected,this.handleSignalConnected).on(ko.SignalRestarted,this.handleReconnected).on(ko.SignalResumed,this.handleReconnected).on(ko.Restarting,this.handleReconnecting).on(ko.Resuming,this.handleReconnecting).on(ko.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(ko.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(ko.Closing,this.handleClosing).on(ko.SignalRequestResponse,this.handleSignalRequestResponse).on(ko.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return Ws(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return Ws(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return Ws(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return Ws(this,arguments,void 0,function(e){var t=this;let{metadata:i,name:n,attributes:s}=e;return function*(){return new Promise((e,r)=>Ws(t,void 0,void 0,function*(){var t,o;try{let a=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(o=null!=n?n:this.name)&&void 0!==o?o:"",s),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{r(e),a=!0},values:{name:n,metadata:i,attributes:s}});performance.now()-d<5e3&&!a;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every(e=>{let[t,i]=e;return this.attributes[t]===i||""===i&&!this.attributes[t]})))return this.pendingSignalRequests.delete(c),void e();yield ua(50)}r(new Oo("Request to update local metadata timed out","TimeoutError"))}catch(a){a instanceof Error&&r(a)}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(aa.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(aa.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(aa.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return Ws(this,void 0,void 0,function*(){this.encryptionType=e?Wi.GCM:Wi.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,n){return Ws(this,void 0,void 0,function*(){var s,r;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let t;if(this.pendingPublishing.has(e)){const 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 null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case aa.Source.Camera:t=yield this.createTracks({video:null===(s=i)||void 0===s||s});break;case aa.Source.Microphone:t=yield this.createTracks({audio:null===(r=i)||void 0===r||r});break;case aa.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Ro(e)}}catch(a){throw null==t||t.forEach(e=>{e.stop()}),a instanceof Error&&this.emit(bo.MediaDevicesError,a,Zo(e)),this.pendingPublishing.delete(e),a}for(const n of t){const t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===aa.Source.Microphone&&Wa(n)&&t.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),n.startPreConnectBuffer())}try{const e=[];for(const s of t)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),ta(s))),e.push(this.publishTrack(s,n));const i=yield Promise.all(e);[o]=i}catch(a){throw null==t||t.forEach(e=>{e.stop()}),a}finally{this.pendingPublishing.delete(e)}}else if(!(null==o?void 0:o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===aa.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const e=this.getTrackPublication(aa.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return Ws(this,void 0,void 0,function*(){if(!this.pendingPublishing.has(aa.Source.Camera)&&!this.pendingPublishing.has(aa.Source.Microphone)){this.pendingPublishing.add(aa.Source.Camera),this.pendingPublishing.add(aa.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete(aa.Source.Camera),this.pendingPublishing.delete(aa.Source.Microphone)}}})}createTracks(e){return Ws(this,void 0,void 0,function*(){var t,i;null!=e||(e={});const n=Ko(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults);try{const e=yield rl(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return e.map(e=>(Wa(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=aa.Source.Microphone,this.emit(bo.AudioStreamAcquired)),Ka(e)&&(this.cameraError=void 0,e.source=aa.Source.Camera),e))}catch(bl){throw bl instanceof Error&&(e.audio&&(this.microphoneError=bl),e.video&&(this.cameraError=bl)),bl}})}createScreenTracks(e){return Ws(this,void 0,void 0,function*(){if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new Eo("getDisplayMedia not supported");void 0!==e.resolution||function(){const e=so();return"Safari"===(null==e?void 0:e.name)&&e.version.startsWith("17.")||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&xa(e.osVersion,"17")>=0}()||(e.resolution=Wo.h1080fps30.resolution);const t=function(e){var t,i;let n=null===(t=e.video)||void 0===t||t;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(n="boolean"==typeof n?{}:n,n=ba()?Object.assign(Object.assign({},n),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},n),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:null!==(i=e.audio)&&void 0!==i&&i,video:n,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}(e),i=yield navigator.mediaDevices.getDisplayMedia(t),n=i.getVideoTracks();if(0===n.length)throw new Ro("no video track found");const s=new Ed(n[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=aa.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const r=[s];if(i.getAudioTracks().length>0){this.emit(bo.AudioStreamAcquired);const e=new pd(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=aa.Source.ScreenShareAudio,r.push(e)}return r})}publishTrack(e,t){return Ws(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return Ws(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var s,r,o,a;let c,d;if(Ja(e)&&e.setAudioContext(i.audioContext),yield null===(s=i.reconnectFuture)||void 0===s?void 0:s.promise,i.republishPromise&&!n&&(yield i.republishPromise),Ha(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)c=e.getConstraints();else{let t;switch(c=e.constraints,e.source){case aa.Source.Microphone:t="audioinput";break;case aa.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(c=Object.assign(Object.assign({},c),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new pd(e,c,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new Ed(e,c,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new Ro("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});if(i.trackPublications.forEach(t=>{t.track&&t.track===e&&(d=t)}),d)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),ta(d))),d;const l=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t),u="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,h=null!==(r=l.forceStereo)&&void 0!==r?r:u;h&&(void 0===l.dtx&&i.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},i.logContext),ta(e))),void 0===l.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(o=l.dtx)&&void 0!==o||(l.dtx=!1),null!==(a=l.red)&&void 0!==a||(l.red=!1)),!function(){const e=so(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&xa(e.osVersion,t)>=0)||"Safari"===e.name&&xa(e.version,t)>=0}()&&i.roomOptions.e2ee&&(i.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({},i.logContext)),l.simulcast=!1),l.source&&(e.source=l.source);const p=new Promise((t,n)=>Ws(i,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Tc.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:ta(e)}));let i=!1;const s=setTimeout(()=>{i=!0,e.stop(),n(new _o("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(s),i)return;const r=yield this.publish(e,l,h);t(r)}else try{const i=yield this.publish(e,l,h);t(i)}catch(i){n(i)}}catch(i){n(i)}}));i.pendingPublishPromises.set(e,p);try{return yield p}catch(m){throw m}finally{i.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new ja),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),ta(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return!(!t||0!==i.length&&!i.map(e=>function(e){switch(e){case _i.CAMERA:return aa.Source.Camera;case _i.MICROPHONE:return aa.Source.Microphone;case _i.SCREEN_SHARE:return aa.Source.ScreenShare;case _i.SCREEN_SHARE_AUDIO:return aa.Source.ScreenShareAudio;default:return aa.Source.Unknown}}(e)).includes(e.source))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),ta(e))),!1)}publish(e,t,i){return Ws(this,void 0,void 0,function*(){var n,s,r,o,a,c,d,l,u,h;if(!this.hasPermissionsToPublish(e))throw new _o("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(t=>Ha(e)&&t.source===e.source)&&e.source!==aa.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),ta(e))),t.stopMicTrackOnMute&&Wa(e)&&(e.stopOnMute=!0),e.source===aa.Source.ScreenShare&&fa()&&(t.simulcast=!1),"av1"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(ba()||fa())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/av1"===i.mimeType.toLowerCase()){t=!0;break}return t}()||(t.videoCodec=void 0),"vp9"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(fa())return!1;if(ba()){const e=so();if((null==e?void 0:e.version)&&xa(e.version,"16")<0)return!1;if("iOS"===(null==e?void 0:e.os)&&(null==e?void 0:e.osVersion)&&xa(e.osVersion,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/vp9"===i.mimeType.toLowerCase()){t=!0;break}return t}()||(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec=Jc),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(e=>t.videoCodec===$o(e.mime))||(t.videoCodec=$o(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(Co.Muted,this.onTrackMuted),e.on(Co.Unmuted,this.onTrackUnmuted),e.on(Co.Ended,this.handleTrackEnded),e.on(Co.UpstreamPaused,this.onTrackUpstreamPaused),e.on(Co.UpstreamResumed,this.onTrackUpstreamResumed),e.on(Co.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=[],g=!(null===(n=t.dtx)||void 0===n||n),f=e.getSourceTrackSettings();f.autoGainControl&&m.push(Ui.TF_AUTO_GAIN_CONTROL),f.echoCancellation&&m.push(Ui.TF_ECHO_CANCELLATION),f.noiseSuppression&&m.push(Ui.TF_NOISE_SUPPRESSION),f.channelCount&&f.channelCount>1&&m.push(Ui.TF_STEREO),g&&m.push(Ui.TF_NO_DTX),Ja(e)&&e.hasPreConnectBuffer&&m.push(Ui.TF_PRECONNECT_BUFFER);const v=new Mn({cid:e.mediaStreamTrack.id,name:t.name,type:aa.kindToProto(e.kind),muted:e.isMuted,source:aa.sourceToProto(e.source),disableDtx:g,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(s=t.red)||void 0===s||s),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy,audioFeatures:m});let b;if(e.kind===aa.Kind.Video){let i={width:0,height:0};try{i=yield e.waitForDimensions()}catch(S){const t=null!==(o=null===(r=this.roomOptions.videoCaptureDefaults)||void 0===r?void 0:r.resolution)&&void 0!==o?o:zo.h720.resolution;i={width:t.width,height:t.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),ta(e)),{dims:i}))}v.width=i.width,v.height=i.height,Ga(e)&&(ma(p)&&(e.source===aa.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),ta(e))))),t.scalabilityMode=null!==(a=t.scalabilityMode)&&void 0!==a?a:"L3T3_KEY"),v.simulcastCodecs=[new An({codec:p,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:Jc}),t.backupCodec&&p!==t.backupCodec.codec&&v.encryption===Wi.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),v.simulcastCodecs.push(new An({codec:t.backupCodec.codec,cid:""})))),b=kd(e.source===aa.Source.ScreenShare,v.width,v.height,t),v.layers=xd(v.width,v.height,b,ma(t.videoCodec))}else e.kind===aa.Kind.Audio&&(b=[{maxBitrate:null===(c=t.audioPreset)||void 0===c?void 0:c.maxBitrate,priority:null!==(l=null===(d=t.audioPreset)||void 0===d?void 0:d.priority)&&void 0!==l?l:"high",networkPriority:null!==(h=null===(u=t.audioPreset)||void 0===u?void 0:u.priority)&&void 0!==h?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new xo("cannot publish track when not connected");const y=()=>Ws(this,void 0,void 0,function*(){var i,n,s;if(!this.engine.pcManager)throw new xo("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),this.emit(bo.LocalSenderCreated,e.sender,e),Ga(e)&&(null!==(i=t.degradationPreference)&&void 0!==i||(t.degradationPreference=function(e){return e.source===aa.Source.ScreenShare||e.constraints.height&&Fa(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(e)),e.setDegradationPreference(t.degradationPreference)),b)if(fa()&&e.kind===aa.Kind.Audio){let t;for(const i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===e.sender){t=i;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:"opus",maxbr:(null===(n=b[0])||void 0===n?void 0:n.maxBitrate)?b[0].maxBitrate/1e3:0})}else e.codec&&ma(e.codec)&&(null===(s=b[0])||void 0===s?void 0:s.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:v.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()});let k;const T=new Promise((t,i)=>Ws(this,void 0,void 0,function*(){var n;try{k=yield this.engine.addTrack(v),t(k)}catch(bl){e.sender&&(null===(n=this.engine.pcManager)||void 0===n?void 0:n.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),ta(e)),{error:t}))})),i(bl)}}));if(this.enabledPublishVideoCodecs.length>0){const e=yield Promise.all([T,y()]);k=e[0]}else{let i;if(k=yield T,k.codecs.forEach(e=>{void 0===i&&(i=e.mimeType)}),i&&e.kind===aa.Kind.Video){const n=$o(i);n!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),ta(e)),{codec:n})),t.videoCodec=n,b=kd(e.source===aa.Source.ScreenShare,v.width,v.height,t))}yield y()}const C=new sl(e.kind,k,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(C.on(Co.CpuConstrained,e=>this.onTrackCpuConstrained(e,C)),C.options=t,e.sid=k.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:k})),Ga(e)?e.startMonitor(this.engine.client):Ja(e)&&e.startMonitor(),this.addTrackPublication(C),this.emit(bo.LocalTrackPublished,C),Ja(e)&&k.audioFeatures.includes(Ui.TF_PRECONNECT_BUFFER)){const t=e.getPreConnectBuffer(),i=e.getPreConnectBufferMimeType();if(this.on(bo.LocalTrackSubscribed,t=>{if(t.trackSid===k.sid){if(!e.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed",this.logContext);this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),ta(e))),e.stopPreConnectBuffer()}}),t){new Promise((n,s)=>Ws(this,void 0,void 0,function*(){var r,o,a,c,d,l;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),ta(e)));const g=setTimeout(()=>{s(new Error("agent not active within 10 seconds"))},1e4),v=yield this.waitUntilActiveAgentPresent();clearTimeout(g),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),ta(e)));const b=yield this.streamBytes({name:"preconnect-buffer",mimeType:i,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[v.identity],attributes:{trackId:C.trackSid,sampleRate:String(null!==(d=f.sampleRate)&&void 0!==d?d:"48000"),channels:String(null!==(l=f.channelCount)&&void 0!==l?l:"1")}});try{for(var u,h=!0,p=Gs(t);!(r=(u=yield p.next()).done);h=!0){c=u.value,h=!1;const e=c;yield b.write(e)}}catch(m){o={error:m}}finally{try{h||r||!(a=p.return)||(yield a.call(p))}finally{if(o)throw o.error}}yield b.close(),n()}catch(S){s(S)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),ta(e)))}).catch(t=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),ta(e)),{error:t}))})}}return C})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return Ws(this,void 0,void 0,function*(){var n;if(this.encryptionType!==Wi.NONE)return;let s;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(s=t)}),!s)throw new Ro("track is not published");if(!Ga(e))throw new Ro("track is not a video track");const r=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),o=function(e,t,i){var n,s,r,o;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&Bs.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const a=e.mediaStreamTrack.getSettings(),c=null!==(n=a.width)&&void 0!==n?n:null===(s=e.dimensions)||void 0===s?void 0:s.width,d=null!==(r=a.height)&&void 0!==r?r:null===(o=e.dimensions)||void 0===o?void 0:o.height;return e.source===aa.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),kd(e.source===aa.Source.ScreenShare,c,d,i)}(e,t,r);if(!o)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),ta(e)));const a=e.addSimulcastTrack(t,o);if(!a)return;const c=new Mn({cid:a.mediaStreamTrack.id,type:aa.kindToProto(e.kind),muted:e.isMuted,source:aa.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:r.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=xd(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new xo("cannot publish track when not connected");const d=(yield Promise.all([this.engine.addTrack(c),(()=>Ws(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,a,r,o),yield this.engine.negotiate()}))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:d}))})}unpublishTrack(e,t){return Ws(this,void 0,void 0,function*(){var i,n;if(Ha(e)){const t=this.pendingPublishPromises.get(e);t&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),ta(e))),yield t)}const s=this.getPublicationForTrack(e),r=s?ta(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),r)),!s||!s.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),r));(e=s.track).off(Co.Muted,this.onTrackMuted),e.off(Co.Unmuted,this.onTrackUnmuted),e.off(Co.Ended,this.handleTrackEnded),e.off(Co.UpstreamPaused,this.onTrackUpstreamPaused),e.off(Co.UpstreamResumed,this.onTrackUpstreamResumed),e.off(Co.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null===(n=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===n||n),t?e.stop():e.stopMonitor();let o=!1;const a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<ed.FAILED&&a)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),Ga(e)){for(const[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(o=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(c){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),r),{error:c}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case aa.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case aa.Kind.Video:this.videoTrackPublications.delete(s.trackSid)}return this.emit(bo.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return Ws(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return Ws(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new Promise((n,s)=>Ws(t,void 0,void 0,function*(){try{const t=[];this.trackPublications.forEach(i=>{i.track&&(e&&(i.options=Object.assign(Object.assign({},i.options),e)),t.push(i))}),yield Promise.all(t.map(e=>Ws(this,void 0,void 0,function*(){const t=e.track;yield this.unpublishTrack(t,!1),!i||t.isMuted||t.source===aa.Source.ScreenShare||t.source===aa.Source.ScreenShareAudio||!Ja(t)&&!Ga(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)}))),n()}catch(t){s(t)}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return Ws(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){const n=i.reliable?Xi.RELIABLE:Xi.LOSSY,s=i.destinationIdentities,r=i.topic;let o=new nn({participantIdentity:t.identity,payload:e,destinationIdentities:s,topic:r});const a=new Yi({kind:n,value:{case:"user",value:o}});yield t.engine.sendDataPacket(a,n)}()})}publishDtmf(e,t){return Ws(this,void 0,void 0,function*(){const i=new Yi({kind:Xi.RELIABLE,value:{case:"sipDtmf",value:new sn({code:e,digit:t})}});yield this.engine.sendDataPacket(i,Xi.RELIABLE)})}sendChatMessage(e,t){return Ws(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments},n=new Yi({value:{case:"chatMessage",value:new an(Object.assign(Object.assign({},i),{timestamp:dt.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,Xi.RELIABLE),this.emit(bo.ChatMessage,i),i})}editChatMessage(e,t){return Ws(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new Yi({value:{case:"chatMessage",value:new an(Object.assign(Object.assign({},i),{timestamp:dt.parse(i.timestamp),editTimestamp:dt.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,Xi.RELIABLE),this.emit(bo.ChatMessage,i),i})}sendText(e,t){return Ws(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return Ws(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return Ws(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return Ws(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return Ws(this,arguments,void 0,function(e){var t=this;let{destinationIdentity:i,method:n,payload:s,responseTimeout:r=15e3}=e;return function*(){return new Promise((e,o)=>Ws(t,void 0,void 0,function*(){var t,a,c,d;if(rd(s)>15360)return void o(sd.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null===(a=null===(t=this.engine.latestJoinResponse)||void 0===t?void 0:t.serverInfo)||void 0===a?void 0:a.version)&&xa(null===(d=null===(c=this.engine.latestJoinResponse)||void 0===c?void 0:c.serverInfo)||void 0===d?void 0:d.version,"1.8.0")<0)return void o(sd.builtIn("UNSUPPORTED_SERVER"));const l=Math.max(r,8e3),u=crypto.randomUUID();yield this.publishRpcRequest(i,u,n,s,l);const h=setTimeout(()=>{this.pendingAcks.delete(u),o(sd.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(u),clearTimeout(p)},7e3);this.pendingAcks.set(u,{resolve:()=>{clearTimeout(h)},participantIdentity:i});const p=setTimeout(()=>{this.pendingResponses.delete(u),o(sd.builtIn("RESPONSE_TIMEOUT"))},r);this.pendingResponses.set(u,{resolve:(t,i)=>{clearTimeout(p),this.pendingAcks.has(u)&&(this.log.warn("RPC response received before ack",u),this.pendingAcks.delete(u),clearTimeout(h)),i?o(i):e(null!=t?t:"")},participantIdentity:i})}))}()})}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const n=this.pendingResponses.get(e);n?(n.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,n,s){return Ws(this,void 0,void 0,function*(){const r=new Yi({destinationIdentities:[e],kind:Xi.RELIABLE,value:{case:"rpcRequest",value:new cn({id:t,method:i,payload:n,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(r,Xi.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===e&&(n(null,sd.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(e=>"video"===e.mime.split("/")[0].toLowerCase())}updateInfo(e){return!!super.updateInfo(e)&&(e.tracks.forEach(e=>{var t,i;const n=this.trackPublications.get(e.sid);if(n){const s=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;s!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),ta(n)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(e.sid,s))}}),!0)}setActiveAgent(e){var t,i,n,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?null===(i=null===(t=this.activeAgentFuture)||void 0===t?void 0:t.resolve)||void 0===i||i.call(t,e):null===(s=null===(n=this.activeAgentFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new ja),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(Ja(n)||Ga(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))}),t}waitForPendingPublicationOfSource(e){return Ws(this,void 0,void 0,function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find(t=>{let[i]=t;return i.source===e});if(t)return t[1];yield ua(20)}})}}class cl extends Yd{constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(Co.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const n=new zn({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new hn({participantSid:"",trackSids:[this.trackSid]})]});this.emit(Co.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?Yd.SubscriptionStatus.Unsubscribed:super.isSubscribed?Yd.SubscriptionStatus.Subscribed:Yd.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Yd.PermissionStatus.Allowed:Yd.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return void 0!==this.requestedDisabled?!this.requestedDisabled:!this.isAdaptiveStream||this.visible}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){var t,i;this.isManualOperationAllowed()&&((null===(t=this.requestedVideoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(i=this.requestedVideoDimensions)||void 0===i?void 0:i.height)===e.height||(Xa(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Xa(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return null!==(e=this.requestedMaxQuality)&&void 0!==e?e:ra.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(Co.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(Co.VisibilityChanged,this.handleVisibilityChange),n.off(Co.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(Co.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(Co.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(Co.VisibilityChanged,this.handleVisibilityChange),e.on(Co.Ended,this.handleEnded),this.emit(Co.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(Co.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?Co.Muted:Co.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(Co.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(Co.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Xa(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Hn({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===aa.Kind.Video){let s=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(s){na(this.videoDimensionsAdaptiveStream,s)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),s=this.videoDimensionsAdaptiveStream)}else if(void 0!==this.requestedMaxQuality&&this.trackInfo){const e=(t=this.trackInfo,i=this.requestedMaxQuality,null===(n=t.layers)||void 0===n?void 0:n.find(e=>e.quality===i));e&&na(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),s=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),s=this.videoDimensionsAdaptiveStream;s?(e.width=Math.ceil(s.width),e.height=Math.ceil(s.height)):void 0!==this.requestedMaxQuality?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:ra.HIGH})),e.quality=ra.HIGH)}var t,i,n;this.emit(Co.UpdateSettings,e)}}class dl extends ol{static fromParticipantInfo(e,t,i){return new dl(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,n,s,r,o){super(t,i||"",n,s,r,o,arguments.length>7&&void 0!==arguments[7]?arguments[7]:zi.STANDARD),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(Co.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),ta(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(Co.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(Co.SubscriptionPermissionChanged,t=>{this.emit(bo.TrackSubscriptionPermissionChanged,e,t)}),e.on(Co.SubscriptionStatusChanged,t=>{this.emit(bo.TrackSubscriptionStatusChanged,e,t)}),e.on(Co.Subscribed,t=>{this.emit(bo.TrackSubscribed,t,e)}),e.on(Co.Unsubscribed,t=>{this.emit(bo.TrackUnsubscribed,t,e)}),e.on(Co.SubscriptionFailed,t=>{this.emit(bo.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:aa.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:aa.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,n,s,r){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(t=>{o||e.kind!==t.kind.toString()||(o=t)}),!o)return 0===r?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),void this.emit(bo.TrackSubscriptionFailed,t)):(void 0===r&&(r=20),void setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,n,s,r-1)},150));if("ended"===e.readyState)return this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),ta(o))),void this.emit(bo.TrackSubscriptionFailed,t);let a;return a="video"===e.kind?new Kd(e,t,n,s):new Wd(e,t,n,this.audioContext,this.audioOutput),a.source=o.source,a.isMuted=o.isMuted,a.setMediaStream(i),a.start(),o.setTrack(a),this.volumeMap.has(o.source)&&Qa(a)&&Wa(a)&&a.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;const t=new Map,i=new Map;return e.tracks.forEach(e=>{var n,s;let r=this.getTrackPublicationBySid(e.sid);if(r)r.updateInfo(e);else{const t=aa.kindFromProto(e.type);if(!t)return;r=new cl(t,e,null===(n=this.signalClient.connectOptions)||void 0===n?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(s=this.loggerOptions)||void 0===s?void 0:s.loggerName}),r.updateInfo(e),i.set(e.sid,r);const o=Array.from(this.trackPublications.values()).find(e=>e.source===(null==r?void 0:r.source));o&&r.source!==aa.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(r.source),Object.assign(Object.assign({},this.logContext),{oldTrack:ta(o),newTrack:ta(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),ta(e))),this.unpublishTrack(e.trackSid,!0))}),i.forEach(e=>{this.emit(bo.TrackPublished,e)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case aa.Kind.Audio:this.audioTrackPublications.delete(e);break;case aa.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(bo.TrackUnpublished,i)}setAudioOutput(e){return Ws(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var n;Wa(i.track)&&Qa(i.track)&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}(nl=il||(il={})).Disconnected="disconnected",nl.Connecting="connecting",nl.Connected="connected",nl.Reconnecting="reconnecting",nl.SignalReconnecting="signalReconnecting";class ll extends Ys.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(e){var t,i,n,s;if(super(),t=this,this.state=il.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Bs,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(e,t,i)=>Ws(this,void 0,void 0,function*(){var n;if("undefined"==typeof RTCPeerConnection||!ha()&&!pa())throw Ca()?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.");const s=yield this.disconnectLock.lock();if(this.state===il.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),s(),Promise.resolve();if(this.connectFuture)return s(),this.connectFuture.promise;this.setAndEmitConnectionState(il.Connecting),(null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getServerUrl().toString())!==Za(e)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Sa(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new nd(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))}));const r=(n,o,a)=>Ws(this,void 0,void 0,function*(){var c,d;this.abortController&&this.abortController.abort();const l=new AbortController;this.abortController=l,null==s||s();try{if(yield pc.getInstance().getBackOffPromise(e),l.signal.aborted)throw wo.cancelled("Connection attempt aborted");yield this.attemptConnection(null!=a?a:e,t,i,l),this.abortController=void 0,n()}catch(u){if(this.regionUrlProvider&&u instanceof wo&&u.reason!==lo.Cancelled&&u.reason!==lo.NotAllowed){let t=null;try{this.log.debug("Fetching next region"),t=yield this.regionUrlProvider.getNextBestRegionUrl(null===(c=this.abortController)||void 0===c?void 0:c.signal)}catch(h){if(h instanceof wo&&(401===h.status||h.reason===lo.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void o(h)}[lo.InternalError,lo.ServerUnreachable,lo.Timeout].includes(u.reason)&&(this.log.debug("Adding failed connection attempt to back off"),pc.getInstance().addFailedConnectionAttempt(e)),t&&!(null===(d=this.abortController)||void 0===d?void 0:d.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(u.message,". Retrying with another region: ").concat(t),this.logContext),this.recreateEngine(),yield r(n,o,t)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,qa(u)),o(u))}else{let e=Mi.UNKNOWN_REASON;u instanceof wo&&(e=qa(u)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),o(u)}}}),o=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new ja((e,t)=>{r(e,t,o)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,i,n,s,r)=>Ws(this,void 0,void 0,function*(){var o,a,c;const d=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof s.adaptiveStream||s.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout,singlePeerConnection:s.singlePeerConnection},r.signal);let l=d.serverInfo;if(l||(l={version:d.serverVersion,region:d.serverRegion}),this.serverInfo=l,this.log.debug("connected to Livekit Server ".concat(Object.entries(l).map(e=>{let[t,i]=e;return"".concat(t,": ").concat(i)}).join(", ")),{room:null===(o=d.room)||void 0===o?void 0:o.name,roomSid:null===(a=d.room)||void 0===a?void 0:a.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!l.version)throw new Po("unknown server version");return"0.15.1"===l.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),s.dynacast=!1),d}),this.applyJoinResponse=e=>{const 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(i){this.log.error(i instanceof Error?i.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:i}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>Ws(this,void 0,void 0,function*(){var s,r;this.state===il.Reconnecting||this.isResuming||(null===(s=this.engine)||void 0===s?void 0:s.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(r=this.regionUrlProvider)||void 0===r?void 0:r.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},$c),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,n);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(fo.SignalConnected)}catch(bl){yield this.engine.close(),this.recreateEngine();const t=n.signal.aborted?wo.cancelled("Signal connection aborted"):wo.serverUnreachable("could not establish signal connection");throw bl instanceof Error&&(t.message="".concat(t.message,": ").concat(bl.message)),bl instanceof wo&&(t.reason=bl.reason,t.status=bl.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:bl})),t}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),wo.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(o){throw yield this.engine.close(),this.recreateEngine(),o}Ta()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Ta()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(il.Connected),this.emit(fo.Connected),pc.getInstance().resetFailedConnectionAttempts(e),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];return Ws(t,[...i],void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n,s;const r=yield e.disconnectLock.lock();try{if(e.state===il.Disconnected)return void e.log.debug("already disconnected",e.logContext);if(e.log.info("disconnect from room",Object.assign({},e.logContext)),e.state===il.Connecting||e.state===il.Reconnecting||e.isResuming){const t="Abort connection attempt due to user initiated disconnect";e.log.warn(t,e.logContext),null===(i=e.abortController)||void 0===i||i.abort(t),null===(s=null===(n=e.connectFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,wo.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,Mi.CLIENT_INITIATED),e.engine=void 0}finally{r()}}()})},this.onPageLeave=()=>Ws(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>Ws(this,void 0,void 0,function*(){const e=[],t=so();if(t&&"iOS"===t.os){const t="livekit-dummy-audio-el";let i=document.getElementById(t);if(!i){i=document.createElement("audio"),i.id=t,i.autoplay=!0,i.hidden=!0;const e=Ua();e.enabled=!0;const n=new MediaStream([e]);i.srcObject=n,document.addEventListener("visibilitychange",()=>{i&&(i.srcObject=document.hidden?null:n,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(i),this.once(fo.Disconnected,()=>{null==i||i.remove(),i=null})}e.push(i)}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(bl){throw this.handleAudioPlaybackFailed(bl),bl}}),this.startVideo=()=>Ws(this,void 0,void 0,function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var i;null===(i=t.track)||void 0===i||i.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{"NotAllowedError"===e.name?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(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(il.Reconnecting)&&this.emit(fo.Reconnecting)},this.handleSignalRestarted=e=>Ws(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(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(t){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:t}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch(i){return}this.setAndEmitConnectionState(il.Connected),this.emit(fo.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{e.forEach(e=>{var t;if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);""===e.identity&&(e.identity=null!==(t=this.sidToIdentity.get(e.sid))&&void 0!==t?t:"");let i=this.remoteParticipants.get(e.identity);e.state===Vi.DISCONNECTED?this.handleParticipantDisconnected(e.identity,i):i=this.getOrCreateParticipant(e.identity,e)})},this.handleActiveSpeakersUpdate=e=>{const t=[],i={};e.forEach(e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{const i=this.getRemoteParticipantBySid(e.sid);i&&(i.audioLevel=e.level,i.setIsSpeaking(!0),t.push(i))}}),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(fo.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{const t=new Map;this.activeSpeakers.forEach(e=>{const i=this.remoteParticipants.get(e.identity);i&&i.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let i=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=e.level,i.setIsSpeaking(e.active),e.active?t.set(e.sid,i):t.delete(e.sid))});const i=Array.from(t.values());i.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=i,this.emitWhenConnected(fo.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);if(!i||!i.track)return;const n=aa.streamStateFromProto(e.state);i.track.setStreamState(n),n!==i.track.streamState&&(t.emit(bo.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(fo.TrackStreamStateChanged,i,i.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{const i=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(i,e.value.value,e.kind,t);else if("transcription"===e.value.case)this.handleTranscription(i,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(i,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(i,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,i);else if("streamHeader"===e.value.case||"streamChunk"===e.value.case||"streamTrailer"===e.value.case)this.handleDataStream(e,t);else if("rpcRequest"===e.value.case){const t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,i,n)=>{this.emit(fo.DataReceived,t.payload,e,i,t.topic,n),null==e||e.emit(bo.DataReceived,t.payload,i,n)},this.handleSipDtmf=(e,t)=>{this.emit(fo.SipDTMFReceived,t,e),null==e||e.emit(bo.SipDTMFReceived,t)},this.handleTranscription=(e,t)=>{const i=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),n=null==i?void 0:i.trackPublications.get(t.trackId),s=function(e,t){return e.segments.map(e=>{let{id:i,text:n,language:s,startTime:r,endTime:o,final:a}=e;var c;const d=null!==(c=t.get(i))&&void 0!==c?c:Date.now(),l=Date.now();return a?t.delete(i):t.set(i,d),{id:i,text:n,startTime:Number.parseInt(r.toString()),endTime:Number.parseInt(o.toString()),final:a,language:s,firstReceivedTime:d,lastReceivedTime:l}})}(t,this.transcriptionReceivedTimes);null==n||n.emit(Co.TranscriptionReceived,s),null==i||i.emit(bo.TranscriptionReceived,s,n),this.emit(fo.TranscriptionReceived,s,i,n)},this.handleChatMessage=(e,t)=>{const i=function(e){const{id:t,timestamp:i,message:n,editTimestamp:s}=e;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}(t);this.emit(fo.ChatMessage,i,e)},this.handleMetrics=(e,t)=>{this.emit(fo.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(fo.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(fo.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(fo.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(fo.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>Ws(this,void 0,void 0,function*(){var e;"iOS"!==(null===(e=so())||void 0===e?void 0:e.os)&&(yield this.selectDefaultDevices()),this.emit(fo.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{const t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(fo.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(fo.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach(e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)})},this.onLocalParticipantMetadataChanged=e=>{this.emit(fo.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(fo.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(fo.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(fo.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(fo.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=e=>Ws(this,void 0,void 0,function*(){var t,i,n,s,r,o;if(null===(t=e.track)||void 0===t||t.on(Co.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.on(Co.Restarted,this.onLocalTrackRestarted),null===(r=null===(s=null===(n=e.track)||void 0===n?void 0:n.getProcessor())||void 0===s?void 0:s.onPublish)||void 0===r||r.call(s,this),this.emit(fo.LocalTrackPublished,e,this.localParticipant),Ja(e.track)){(yield e.track.checkForSilence())&&this.emit(fo.LocalAudioSilenceDetected,e)}const a=yield null===(o=e.track)||void 0===o?void 0:o.getDeviceId(!1),c=Zo(e.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,a),this.emit(fo.ActiveDeviceChanged,c,a))}),this.onLocalTrackUnpublished=e=>{var t,i;null===(t=e.track)||void 0===t||t.off(Co.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.off(Co.Restarted,this.onLocalTrackRestarted),this.emit(fo.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>Ws(this,void 0,void 0,function*(){const t=yield e.getDeviceId(!1),i=Zo(e.source);i&&t&&t!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(t," active"),this.logContext),this.localParticipant.activeDeviceMap.set(i,t),this.emit(fo.ActiveDeviceChanged,i,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(fo.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(fo.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(fo.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(fo.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Zc),e),this.log=qs(null!==(i=this.options.loggerName)&&void 0!==i?i:Us.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Yc),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Xc),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Qc),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Fd,this.outgoingDataStreamManager=new zd(this.engine,this.log),this.disconnectLock=new qe,this.localParticipant=new al("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Fa(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Fa(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",Fa(this.options.audioOutput.deviceId)).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),Ta()){const e=new AbortController;null===(s=navigator.mediaDevices)||void 0===s||s.addEventListener("devicechange",this.handleDeviceChange,{signal:e.signal}),ll.cleanupRegistry&&ll.cleanupRegistry.register(this,()=>{e.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 ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return Ws(this,void 0,void 0,function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity)})}setupE2EE(){var e;const t=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new hc(i,t),this.e2eeManager.on(rc.ParticipantEncryptionStatusChanged,(e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit(fo.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(rc.EncryptionError,(e,t)=>{const i=t?this.getParticipantByIdentity(t):void 0;this.emit(fo.EncryptionError,e,i)}),null===(e=this.e2eeManager)||void 0===e||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}getSid(){return Ws(this,void 0,void 0,function*(){return this.state===il.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise((e,t)=>{const i=t=>{""!==t.sid&&(this.engine.off(ko.RoomUpdate,i),e(t.sid))};this.engine.on(ko.RoomUpdate,i),this.once(fo.Disconnected,()=>{this.engine.off(ko.RoomUpdate,i),t("Room disconnected before room server id was available")})})})}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Md(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(ko.ParticipantUpdate,this.handleParticipantUpdates).on(ko.RoomUpdate,this.handleRoomUpdate).on(ko.SpeakersChanged,this.handleSpeakersChanged).on(ko.StreamStateChanged,this.handleStreamStateUpdate).on(ko.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(ko.SubscriptionError,this.handleSubscriptionError).on(ko.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(ko.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(ko.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(ko.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(ko.DataPacketReceived,this.handleDataPacket).on(ko.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(il.SignalReconnecting)&&this.emit(fo.SignalReconnecting)}).on(ko.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(il.Connected)&&this.emit(fo.Reconnected)}).on(ko.SignalResumed,()=>{this.bufferedEvents=[],(this.state===il.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(ko.Restarting,this.handleRestarting).on(ko.SignalRestarted,this.handleSignalRestarted).on(ko.Offline,()=>{this.setAndEmitConnectionState(il.Reconnecting)&&this.emit(fo.Reconnecting)}).on(ko.DCBufferStatusChanged,(e,t)=>{this.emit(fo.DCBufferStatusChanged,e,t)}).on(ko.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(t=>{let{trackSid:i}=t;return i===e});t?(this.localParticipant.emit(bo.LocalTrackSubscribed,t),this.emitWhenConnected(fo.LocalTrackSubscribed,t,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)}).on(ko.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(fo.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),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&&void 0!==arguments[1])||arguments[1];return gc.getInstance().getDevices(e,t)}prepareConnection(e,t){return Ws(this,void 0,void 0,function*(){if(this.state===il.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Sa(new URL(e))&&t){this.regionUrlProvider=new nd(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===il.Disconnected&&(this.regionUrl=i,yield fetch(Ba(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Ba(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return Ws(this,void 0,void 0,function*(){let i,n=()=>Ws(this,void 0,void 0,function*(){});switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new gs({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new gs({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new gs({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new gs({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=()=>Ws(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new gs({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>Ws(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new gs({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":i=new gs({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>Ws(this,void 0,void 0,function*(){const e=this.engine.client.onLeave;e&&e(new Gn({reason:Mi.CLIENT_INITIATED,action:Jn.RECONNECT}))});break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");i=new gs({scenario:{case:"subscriberBandwidth",value:za(t)}});break;case"leave-full-reconnect":i=new gs({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return Ws(this,arguments,void 0,function(e,t){var i=this;let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var s,r,o,a,c,d,l;let u=!0,h=!1;const p=n?{exact:t}:t;if("audioinput"===e){h=0===i.localParticipant.audioTrackPublications.size;const t=null!==(s=i.getActiveDevice(e))&&void 0!==s?s:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=p;const n=Array.from(i.localParticipant.audioTrackPublications.values()).filter(e=>e.source===aa.Source.Microphone);try{u=(yield Promise.all(n.map(e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(p)}))).every(e=>!0===e)}catch(m){throw i.options.audioCaptureDefaults.deviceId=t,m}const r=n.some(e=>{var t,i;return null!==(i=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==i&&i});u&&r&&(h=!0)}else if("videoinput"===e){h=0===i.localParticipant.videoTrackPublications.size;const t=null!==(r=i.getActiveDevice(e))&&void 0!==r?r:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=p;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter(e=>e.source===aa.Source.Camera);try{u=(yield Promise.all(n.map(e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(p)}))).every(e=>!0===e)}catch(m){throw i.options.videoCaptureDefaults.deviceId=t,m}const s=n.some(e=>{var t,i;return null!==(i=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==i&&i});u&&s&&(h=!0)}else if("audiooutput"===e){if(h=!0,!ga()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");i.options.webAudioMix&&(t=null!==(o=yield gc.getInstance().normalizeDeviceId("audiooutput",t))&&void 0!==o?o:""),null!==(a=(l=i.options).audioOutput)&&void 0!==a||(l.audioOutput={});const n=null!==(c=i.getActiveDevice(e))&&void 0!==c?c:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=t;try{i.options.webAudioMix&&(null===(d=i.audioContext)||void 0===d||d.setSinkId(t)),yield Promise.all(Array.from(i.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(m){throw i.options.audioOutput.deviceId=n,m}}return h&&(i.localParticipant.activeDeviceMap.set(e,t),i.emit(fo.ActiveDeviceChanged,e,t)),u}()})}setupLocalParticipantEvents(){this.localParticipant.on(bo.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(bo.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(bo.AttributesChanged,this.onLocalAttributesChanged).on(bo.TrackMuted,this.onLocalTrackMuted).on(bo.TrackUnmuted,this.onLocalTrackUnmuted).on(bo.LocalTrackPublished,this.onLocalTrackPublished).on(bo.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(bo.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(bo.MediaDevicesError,this.onMediaDevicesError).on(bo.AudioStreamAcquired,this.startAudio).on(bo.ChatMessage,this.onLocalChatMessageSent).on(bo.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===il.Connecting||this.state===il.Reconnecting){const n=()=>{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,i),s()},s=()=>{this.off(fo.Reconnected,n),this.off(fo.Connected,n),this.off(fo.Disconnected,s)};return this.once(fo.Reconnected,n),this.once(fo.Connected,n),void this.once(fo.Disconnected,s)}if(this.state===il.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);if("ended"===e.readyState)return void this.log.info("skipping incoming track as it already ended",this.logContext);const n=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),s=n[0];let r=n[1],o=e.id;if(r&&r.startsWith("TR")&&(o=r),s===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);const a=Array.from(this.remoteParticipants.values()).find(e=>e.sid===s);if(!a)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);if(!o.startsWith("TR")){const e=this.engine.getTrackIdForReceiver(i);if(!e)return void this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(s),this.logContext);o=e}let c;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: ".concat(s,", streamId: ").concat(r,", trackId: ").concat(o),Object.assign(Object.assign({},this.logContext),{rpID:s,streamId:r,trackId:o})),this.options.adaptiveStream&&(c="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});const d=a.addSubscribedMediaTrack(e,o,t,i,c);(null==d?void 0:d.isEncrypted)&&!this.e2eeManager&&this.emit(fo.EncryptionError,new Error("Encrypted ".concat(d.source," track received from participant ").concat(a.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==il.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 i,n,s;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?(null===(i=t.track)||void 0===i||i.detach(),null===(n=t.track)||void 0===n||n.stop()):null===(s=t.track)||void 0===s||s.stopMonitor()}),this.localParticipant.off(bo.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(bo.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(bo.AttributesChanged,this.onLocalAttributesChanged).off(bo.TrackMuted,this.onLocalTrackMuted).off(bo.TrackUnmuted,this.onLocalTrackUnmuted).off(bo.LocalTrackPublished,this.onLocalTrackPublished).off(bo.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(bo.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(bo.MediaDevicesError,this.onMediaDevicesError).off(bo.AudioStreamAcquired,this.startAudio).off(bo.ChatMessage,this.onLocalChatMessageSent).off(bo.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&&"boolean"==typeof this.options.webAudioMix&&(this.audioContext.close(),this.audioContext=void 0),Ta()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(i=navigator.mediaDevices)||void 0===i||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(il.Disconnected),this.emit(fo.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(fo.ParticipantDisconnected,t),t.setDisconnected(),null===(i=this.localParticipant)||void 0===i||i.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,i,n,s,r){return Ws(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),1!==r)return void(yield this.engine.publishRpcResponse(e,t,null,sd.builtIn("UNSUPPORTED_VERSION")));const o=this.rpcHandlers.get(i);if(!o)return void(yield this.engine.publishRpcResponse(e,t,null,sd.builtIn("UNSUPPORTED_METHOD")));let a=null,c=null;try{const r=yield o({requestId:t,callerIdentity:e,payload:n,responseTimeout:s});rd(r)>15360?(a=sd.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):c=r}catch(d){d instanceof sd?a=d:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),d),a=sd.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)})}selectDefaultDevices(){return Ws(this,void 0,void 0,function*(){var e,t,i;const n=gc.getInstance().previousDevices,s=yield gc.getInstance().getDevices(void 0,!1),r=so();if("Chrome"===(null==r?void 0:r.name)&&"iOS"!==r.os)for(let a of s){const e=n.find(e=>e.deviceId===a.deviceId);e&&""!==e.label&&e.kind===a.kind&&e.label!==a.label&&"default"===this.getActiveDevice(a.kind)&&this.emit(fo.ActiveDeviceChanged,a.kind,a.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let a of o){const r=Xo(a),o=this.localParticipant.getTrackPublication(r);if(o&&(null===(e=o.track)||void 0===e?void 0:e.isUserProvided))continue;const c=s.filter(e=>e.kind===a),d=this.getActiveDevice(a);d===(null===(t=n.filter(e=>e.kind===a)[0])||void 0===t?void 0:t.deviceId)&&c.length>0&&(null===(i=c[0])||void 0===i?void 0:i.deviceId)!==d?yield this.switchActiveDevice(a,c[0].deviceId):"audioinput"===a&&!ya()||"videoinput"===a||!(c.length>0)||c.find(e=>e.deviceId===this.getActiveDevice(a))||"audiooutput"===a&&ya()||(yield this.switchActiveDevice(a,c[0].deviceId))}})}acquireAudioContext(){return Ws(this,void 0,void 0,function*(){var e,t;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(e=Yo())&&void 0!==e?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),ua(200)])}catch(n){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:n}))}const i="running"===(null===(t=this.audioContext)||void 0===t?void 0:t.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(fo.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let n;return n=t?dl.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new dl(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),(null===(i=this.options.audioOutput)||void 0===i?void 0:i.deviceId)&&n.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const i=this.remoteParticipants.get(e);if(t){i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity)}return i}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(fo.ParticipantConnected,i),i.on(bo.TrackPublished,e=>{this.emitWhenConnected(fo.TrackPublished,e,i)}).on(bo.TrackSubscribed,(e,t)=>{e.kind===aa.Kind.Audio?(e.on(Co.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(Co.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===aa.Kind.Video&&(e.on(Co.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(Co.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(fo.TrackSubscribed,e,t,i)}).on(bo.TrackUnpublished,e=>{this.emit(fo.TrackUnpublished,e,i)}).on(bo.TrackUnsubscribed,(e,t)=>{this.emit(fo.TrackUnsubscribed,e,t,i)}).on(bo.TrackMuted,e=>{this.emitWhenConnected(fo.TrackMuted,e,i)}).on(bo.TrackUnmuted,e=>{this.emitWhenConnected(fo.TrackUnmuted,e,i)}).on(bo.ParticipantMetadataChanged,e=>{this.emitWhenConnected(fo.ParticipantMetadataChanged,e,i)}).on(bo.ParticipantNameChanged,e=>{this.emitWhenConnected(fo.ParticipantNameChanged,e,i)}).on(bo.AttributesChanged,e=>{this.emitWhenConnected(fo.ParticipantAttributesChanged,e,i)}).on(bo.ConnectionQualityChanged,e=>{this.emitWhenConnected(fo.ConnectionQualityChanged,e,i)}).on(bo.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(fo.ParticipantPermissionsChanged,e,i)}).on(bo.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(fo.TrackSubscriptionStatusChanged,e,t,i)}).on(bo.TrackSubscriptionFailed,(e,t)=>{this.emit(fo.TrackSubscriptionFailed,e,i,t)}).on(bo.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(fo.TrackSubscriptionPermissionChanged,e,t,i)}).on(bo.Active,()=>{this.emitWhenConnected(fo.ParticipantActive,i),i.kind===zi.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&Ya(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Mo.setInterval(()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Mi.STATE_MISMATCH)))},4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&Mo.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.emit(fo.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(this.state===il.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===il.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return Ws(this,void 0,void 0,function*(){var t,i;const n=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new ji({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:dt.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new qi({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(fo.SignalConnected),this.emit(fo.Connected),this.setAndEmitConnectionState(il.Connected),n.video){const e=new sl(aa.Kind.Video,new Gi({source:_i.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ii.AUDIO,name:"video-dummy"}),new Ed(n.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Na(160*(null!==(t=s.aspectRatios[0])&&void 0!==t?t: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(bo.LocalTrackPublished,e)}if(n.audio){const e=new sl(aa.Kind.Audio,new Gi({source:_i.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ii.AUDIO}),new pd(n.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ua(),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(bo.LocalTrackPublished,e)}for(let e=0;e<s.count-1;e+=1){let t=new qi({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:Vi.ACTIVE,tracks:[],joinedAt:dt.parse(Date.now())});const n=this.getOrCreateParticipant(t.identity,t);if(s.video){const r=Na(160*(null!==(i=s.aspectRatios[e%s.aspectRatios.length])&&void 0!==i?i:1),160,!1,!0),o=new Gi({source:_i.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ii.AUDIO});n.addSubscribedMediaTrack(r,o.sid,new MediaStream([r]),new RTCRtpReceiver),t.tracks=[...t.tracks,o]}if(s.audio){const e=Ua(),i=new Gi({source:_i.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ii.AUDIO});n.addSubscribedMediaTrack(e,i.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,i]}n.updateInfo(t)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(e!==fo.ActiveSpeakersChanged&&e!==fo.TranscriptionReceived){const t=ul(i).filter(e=>void 0!==e);e!==fo.TrackSubscribed&&e!==fo.TrackUnsubscribed||this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t}))}return super.emit(e,...i)}}function ul(e){return e.map(e=>{if(e)return Array.isArray(e)?ul(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e})}var hl,pl;ll.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()}),(pl=hl||(hl={}))[pl.IDLE=0]="IDLE",pl[pl.RUNNING=1]="RUNNING",pl[pl.SKIPPED=2]="SKIPPED",pl[pl.SUCCESS=3]="SUCCESS",pl[pl.FAILED=4]="FAILED";Ys.EventEmitter;Ys.EventEmitter;function ml(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}new TextEncoder,new TextDecoder;class gl extends Error{constructor(e,t){var i;super(e,t),ml(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(i=Error.captureStackTrace)||void 0===i||i.call(Error,this,this.constructor)}}ml(gl,"code","ERR_JOSE_GENERIC");ml(class extends gl{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:n,payload:t}}),ml(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),ml(this,"claim",void 0),ml(this,"reason",void 0),ml(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED");ml(class extends gl{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:n,payload:t}}),ml(this,"code","ERR_JWT_EXPIRED"),ml(this,"claim",void 0),ml(this,"reason",void 0),ml(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}},"code","ERR_JWT_EXPIRED");ml(class extends gl{constructor(){super(...arguments),ml(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED");ml(class extends gl{constructor(){super(...arguments),ml(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED");ml(class extends gl{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),ml(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED");ml(class extends gl{constructor(){super(...arguments),ml(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID");ml(class extends gl{constructor(){super(...arguments),ml(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID");ml(class extends gl{constructor(){super(...arguments),ml(this,"code","ERR_JWT_INVALID")}},"code","ERR_JWT_INVALID");ml(class extends gl{constructor(){super(...arguments),ml(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID");ml(class extends gl{constructor(){super(...arguments),ml(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID");ml(class extends gl{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"no applicable key found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),ml(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY");ml(class extends gl{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"multiple matching keys found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),ml(this,Symbol.asyncIterator,void 0),ml(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");ml(class extends gl{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),ml(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT");ml(class extends gl{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),ml(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");class fl{constructor(){this.room=null,this.wrapper=null}async connect(e,t,i){if(e&&t){console.log("[LiveKit] Connecting with wrapper:",i),this.wrapper=i,this.room=new ll({adaptiveStream:!0,dynacast:!0,videoCaptureDefaults:{resolution:zo.h720.resolution}}),this.bindEvents();try{await this.room.connect(e,t),console.log("[LiveKit] Connected to room:",this.room.name),await this.publishLocalTracks()}catch(n){console.error("[LiveKit] Connection failed:",n)}}else console.error("[LiveKit] Missing url or token")}bindEvents(){this.room&&this.room.on(fo.SignalConnected,()=>{console.log("[LiveKit] Signal connected")}).on(fo.TrackSubscribed,(e,t,i)=>{this.handleTrackSubscribed(e,i)}).on(fo.TrackUnsubscribed,(e,t,i)=>{this.handleTrackUnsubscribed(e,i)}).on(fo.Disconnected,()=>{console.log("[LiveKit] Disconnected")}).on(fo.MediaDevicesError,e=>{console.error("[LiveKit] Media Device Error:",e)})}async publishLocalTracks(){const e=this.wrapper.querySelector(".td-pip");try{await this.room.localParticipant.setCameraEnabled(!0);const t=Array.from(this.room.localParticipant.videoTrackPublications.values()).find(e=>"camera"===e.source);if(t&&t.track&&e){e.innerHTML="",e.style.backgroundImage="none";const i=t.track.attach();i.style.width="100%",i.style.height="100%",i.style.objectFit="cover",i.style.transform="scale(-1, 1)",e.appendChild(i),console.log("[LiveKit] Local video attached")}}catch(t){console.error("[LiveKit] Failed to enable Camera:",t),"NotAllowedError"===t.name&&alert("Không thể mở Camera. Hãy kiểm tra icon ổ khóa trên thanh địa chỉ hoặc cài đặt Quyền Riêng Tư (Privacy) của máy tính.")}try{const e=await ll.getLocalDevices("audioinput");console.log("[LiveKit] Audio Input Devices:",e),0===e.length&&alert("Không tìm thấy Micro nào trên thiết bị của bạn!"),await this.room.localParticipant.setMicrophoneEnabled(!0)}catch(t){console.error("[LiveKit] Failed to enable Microphone:",t),"NotAllowedError"===t.name&&alert("Không thể mở Micro. Cuộc gọi sẽ không có tiếng.")}}handleTrackSubscribed(e,t){if(console.log("[LiveKit] Track subscribed:",e.kind,t.identity),"video"===e.kind){const t=this.wrapper.querySelector(".td-main-video");if(console.log("[LiveKit] Looking for remote container (.td-main-video):",t),t){t.style.backgroundImage="none",t.innerHTML="";const i=e.attach();i.style.width="100%",i.style.height="100%",i.style.objectFit="cover",t.appendChild(i),console.log("[LiveKit] Remote video attached")}else console.warn("[LiveKit] Remote container not found!")}if("audio"===e.kind){const t=e.attach();document.body.appendChild(t),console.log("[LiveKit] Remote audio attached")}}handleTrackUnsubscribed(e,t){e.detach().forEach(e=>e.remove())}disconnect(){this.room&&(this.room.disconnect(),this.room=null)}}class vl{constructor(e={}){this.config=e,this.api=new d(e),this.container=null,this.shadowRoot=null,this.unsubscribe=null,this.ws=null,this.socket=null,this.livekit=null}async init(){var s;this.mount(),this.unsubscribe=c.on(e,this.handleStateChange.bind(this)),c.setState({status:i});try{const e=await this.api.init(this.config.widgetId);e.success?(c.setState({config:e.data,storeId:this.config.storeId,orgId:this.config.orgId,productId:this.config.productId,doctor:{...e.data.doctor,id:this.config.doctorId||(null==(s=e.data.doctor)?void 0:s.id)},status:n}),this.checkInlineTrigger(),this.startSocket()):c.setState({status:t,error:"Init failed"})}catch(bl){console.error("Widget Init Error:",bl),c.setState({status:t,error:bl.message})}}mount(){if(document.getElementById("clinic-widget-host"))return;this.container=document.createElement("div"),this.container.id="clinic-widget-host",this.container.style.position="fixed",this.container.style.zIndex="2147483647",this.container.style.bottom="0",this.container.style.right="0",document.body.appendChild(this.container),this.shadowRoot=this.container.attachShadow({mode:"open"});const e="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0&display=swap";if(!document.querySelector(`link[href="${e}"]`)){const t=document.createElement("link");t.rel="stylesheet",t.href=e,document.head.appendChild(t)}const t=document.createElement("link");t.rel="stylesheet",t.href=e;const i=document.createElement("style");i.textContent=':host{--td-primary: #0e65f1;--td-primary-hover: #0b50c0;--td-bg-light: #ffffff;--td-bg-dark: #1a202c;--td-text-main: #0d131c;--td-text-sub: #49699c;--td-border: #e7ecf4;--td-success: #22c55e;--td-danger: #ef4444;--font-family: "Inter", system-ui, -apple-system, sans-serif;--z-index: 9999;font-family:var(--font-family);color:var(--td-text-main)}*{box-sizing:border-box;margin:0;padding:0}.hidden{display:none!important}.material-symbols-outlined{font-family:Material Symbols Outlined;font-weight:400;font-style:normal;font-size:24px;line-height:1;letter-spacing:normal;text-transform:none;display:inline-block;white-space:nowrap;word-wrap:normal;direction:ltr}.td-widget-fab{position:fixed;bottom:24px;right:24px;display:flex;align-items:center;gap:12px;z-index:var(--z-index);cursor:pointer;font-family:var(--font-family)}.td-fab-card{background:var(--td-bg-light);border:1px solid var(--td-border);border-radius:12px;box-shadow:0 8px 30px #0000001f;display:flex;align-items:center;padding:6px 16px 6px 6px;transition:transform .2s ease,box-shadow .2s ease;max-width:320px;position:relative;overflow:hidden}.td-fab-card:hover{transform:translateY(-4px);box-shadow:0 20px 40px #00000026}.td-avatar-container{width:64px;height:64px;border-radius:8px;overflow:hidden;position:relative;flex-shrink:0}.td-avatar{width:100%;height:100%;background-size:cover;background-position:center}.td-status-dot{position:absolute;bottom:4px;right:4px;width:14px;height:14px;background:var(--td-success);border:2px solid #fff;border-radius:50%}.td-info{margin-left:12px;display:flex;flex-direction:column}.td-brand{display:flex;align-items:center;gap:4px;font-size:10px;font-weight:700;text-transform:uppercase;color:var(--td-primary);letter-spacing:.05em}.td-cta{font-size:15px;font-weight:700;color:var(--td-text-main);margin-top:2px}.td-sub{font-size:12px;color:var(--td-text-sub);margin-top:2px}.td-close-fab{position:absolute;top:4px;right:4px;opacity:0;cursor:pointer;background:none;border:none;color:#94a3b8;transition:opacity .2s;padding:4px}.td-fab-card:hover .td-close-fab{opacity:1}.td-widget-expanded{position:fixed;bottom:100px;right:24px;width:380px;max-height:80vh;background:var(--td-bg-light);border-radius:12px;box-shadow:0 25px 50px -12px #00000040;border:1px solid var(--td-border);display:flex;flex-direction:column;overflow:hidden;z-index:var(--z-index);animation:slideUp .3s cubic-bezier(.16,1,.3,1)}@keyframes slideUp{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}.td-header{display:flex;align-items:center;justify-content:space-between;padding:16px;border-bottom:1px solid var(--td-border)}.td-header-title{display:flex;align-items:center;gap:12px;font-weight:700;font-size:18px}.td-icon-box{width:32px;height:32px;background:#0e65f11a;color:var(--td-primary);border-radius:8px;display:flex;align-items:center;justify-content:center}.td-close-btn{background:transparent;border:none;cursor:pointer;color:#64748b;padding:4px;border-radius:50%;display:flex;align-items:center;justify-content:center}.td-close-btn:hover{background:#f1f5f9}.td-content{flex:1;overflow-y:auto;padding:0}.td-doctor-profile{display:flex;flex-direction:column;align-items:center;padding:32px 24px 24px}.td-online-badge{display:inline-flex;align-items:center;gap:6px;padding:4px 12px;background:#f0fdf4;border:1px solid #dcfce7;border-radius:999px}.td-pulse{width:8px;height:8px;background:var(--td-success);border-radius:50%}.td-badge-text{font-size:12px;font-weight:600;color:#15803d;text-transform:uppercase}.td-trust-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;padding:0 24px 24px}.td-trust-item{background:#f8f9fc;border:1px solid var(--td-border);border-radius:12px;padding:12px;text-align:center;display:flex;flex-direction:column;align-items:center;gap:8px}.td-trust-title{font-size:12px;font-weight:700}.td-actions{padding:0 24px 24px;display:flex;flex-direction:column;gap:12px}.td-btn{width:100%;height:48px;border-radius:8px;font-size:16px;font-weight:700;display:flex;align-items:center;justify-content:center;cursor:pointer;transition:all .2s;border:none}.td-btn-primary{background:var(--td-primary);color:#fff;box-shadow:0 10px 15px -3px #0e65f133}.td-btn-primary:hover{background:var(--td-primary-hover)}.td-btn-outline{background:transparent;border:1px solid var(--td-border);color:var(--td-text-main);font-size:14px}.td-btn-outline:hover{background:#f8f9fc}.td-footer{padding:12px;text-align:center;background:#f8f9fc;border-top:1px solid var(--td-border);font-size:12px;color:var(--td-text-sub)}.td-consultation-modal{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);width:90vw;height:90vh;max-width:1200px;max-height:800px;background:var(--td-bg-light);border-radius:16px;box-shadow:0 25px 50px -12px #00000080;border:1px solid var(--td-border);display:flex;overflow:hidden;z-index:var(--z-index);animation:fadeIn .3s ease-out}@keyframes fadeIn{0%{opacity:0;transform:translate(-50%,-48%)}to{opacity:1;transform:translate(-50%,-50%)}}.td-video-panel{flex:1;background:#000;position:relative;display:flex;align-items:center;justify-content:center;overflow:hidden}.td-main-video{width:100%;height:100%;background-size:cover;background-position:center}.td-overlay{position:absolute;top:0;right:0;bottom:0;left:0;background:linear-gradient(to bottom,rgba(0,0,0,.3),transparent,rgba(0,0,0,.6))}.td-video-header{position:absolute;top:16px;left:16px;right:16px;display:flex;justify-content:space-between;z-index:10}.td-badge-glass{background:#0006;-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);padding:6px 12px;border-radius:20px;display:flex;align-items:center;gap:8px;color:#fff;font-size:12px;font-weight:500}.td-pip{position:absolute;top:24px;right:24px;width:160px;aspect-ratio:16/9;background:#333;border-radius:8px;border:2px solid rgba(255,255,255,.2);overflow:hidden;z-index:20;background-size:cover;background-position:center;box-shadow:0 4px 6px #0000004d}.td-pip-label{position:absolute;bottom:4px;left:4px;background:#0009;color:#fff;font-size:10px;padding:2px 6px;border-radius:4px}.td-controls{position:absolute;bottom:32px;left:50%;transform:translate(-50%);display:flex;align-items:center;gap:16px;z-index:20}.td-ctrl-btn{width:48px;height:48px;border-radius:50%;background:#fff3;-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);border:none;color:#fff;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all .2s}.td-ctrl-btn:hover{background:#fff;color:var(--td-primary)}.td-ctrl-end{height:48px;padding:0 24px;border-radius:24px;background:var(--td-danger);color:#fff;display:flex;align-items:center;gap:8px;font-weight:600;border:none;cursor:pointer}.td-ctrl-end:hover{background:#dc2626}.td-chat-panel{width:400px;background:var(--td-bg-light);border-left:1px solid var(--td-border);display:flex;flex-direction:column}.td-chat-header{padding:16px;border-bottom:1px solid var(--td-border)}.td-chat-doc-info{display:flex;gap:12px;align-items:center;margin-bottom:12px}.td-chat-avatar{width:48px;height:48px;border-radius:50%;background-size:cover;background-position:center}.td-chat-timer{background:#f8f9fc;padding:8px 12px;border-radius:8px;display:flex;justify-content:space-between;align-items:center}.td-timer-val{font-family:monospace;font-weight:700;font-size:16px}.td-chat-messages{flex:1;overflow-y:auto;padding:16px;background:#f8f9fc;display:flex;flex-direction:column;gap:16px}.td-msg-system{text-align:center;font-size:12px;color:var(--td-text-sub);background:#e2e8f0;padding:4px 12px;border-radius:12px;align-self:center;max-width:90%}.td-msg-row{display:flex;gap:8px}.td-msg-row.own{flex-direction:row-reverse}.td-msg-bubble{padding:10px 14px;border-radius:12px;font-size:14px;line-height:1.5;max-width:85%}.td-msg-row.doctor .td-msg-bubble{background:#fff;border:1px solid var(--td-border);border-top-left-radius:2px}.td-msg-row.own .td-msg-bubble{background:#e0f2fe;color:var(--td-text-main);border:1px solid #bae6fd;border-top-right-radius:2px}.td-msg-time{font-size:10px;color:var(--td-text-sub);margin-top:2px}.td-chat-input-area{padding:16px;border-top:1px solid var(--td-border);background:var(--td-bg-light)}.td-input-wrapper{display:flex;gap:8px;align-items:flex-end}.td-chat-input{flex:1;border:1px solid var(--td-border);border-radius:8px;padding:10px;font-family:inherit;font-size:14px;resize:none;height:48px}.td-send-btn{width:48px;height:48px;background:var(--td-primary);color:#fff;border:none;border-radius:8px;cursor:pointer;display:flex;align-items:center;justify-content:center}.td-send-btn:hover{background:var(--td-primary-hover)}@media (max-width: 768px){.td-consultation-modal{width:100vw;height:100vh;border-radius:0;flex-direction:column}.td-video-panel{height:40vh}.td-chat-panel{width:100%;flex:1}}.td-form-container{display:flex;flex-direction:column;height:100%;padding:0 24px}.td-form-page-header{padding:24px 0 16px}.td-form-title{font-size:24px;font-weight:700;color:var(--td-text-main);margin-bottom:8px}.td-form-desc{font-size:14px;color:var(--td-text-sub);line-height:normal}.td-form{display:flex;flex-direction:column;gap:20px;padding-bottom:24px}.td-input-group{display:flex;flex-direction:column;gap:8px}.td-label{font-size:14px;font-weight:500;color:var(--td-text-main)}.td-input{width:100%;height:48px;padding:0 16px;border-radius:8px;border:1px solid var(--td-border);background:#f8f9fc;font-family:inherit;font-size:16px;color:var(--td-text-main);transition:all .2s}.td-input:focus{outline:none;border-color:var(--td-primary);box-shadow:0 0 0 2px #0e65f133}.td-textarea{width:100%;min-height:100px;padding:16px;border-radius:8px;border:1px solid var(--td-border);background:#f8f9fc;font-family:inherit;font-size:16px;color:var(--td-text-main);resize:none}.td-textarea:focus{outline:none;border-color:var(--td-primary)}.td-chips-group{display:flex;flex-wrap:wrap;gap:8px}.td-chip{padding:8px 16px;border-radius:99px;font-size:14px;font-weight:500;cursor:pointer;border:1px solid var(--td-border);background:#fff;color:var(--td-text-sub);transition:all .2s}.td-chip:hover{border-color:var(--td-primary);color:var(--td-primary);background:#0e65f10d}.td-chip.active{border-color:var(--td-primary);background:#0e65f11a;color:var(--td-primary);display:flex;align-items:center;gap:6px}.td-secure-note{display:flex;align-items:center;justify-content:center;gap:6px;font-size:12px;color:var(--td-text-sub);opacity:.8;margin-top:8px}.td-summary-container{display:flex;flex-direction:column;height:100%}.td-success-header{display:flex;flex-direction:column;align-items:center;padding:32px 24px;text-align:center}.td-success-icon{width:80px;height:80px;background:#0e65f11a;color:var(--td-primary);border-radius:50%;display:flex;align-items:center;justify-content:center;margin-bottom:16px}.td-summary-title{font-size:24px;font-weight:700;margin-bottom:8px}.td-summary-desc{font-size:14px;color:var(--td-text-sub);max-width:360px;margin:0 auto}.td-summary-card{margin:0 24px;padding:16px;border-radius:12px;border:1px solid var(--td-border);background:#f8f9fc;display:flex;align-items:center;gap:16px}.td-summary-details{padding:8px 24px}.td-detail-row{display:flex;justify-content:space-between;padding:12px 0;border-bottom:1px dashed var(--td-border);font-size:14px}.td-note-box{margin:16px 24px;padding:16px;background:#0e65f10d;border:1px solid rgba(14,101,241,.1);border-radius:8px}.td-note-title{font-size:14px;font-weight:700;margin-bottom:8px;display:flex;align-items:center;gap:8px}.td-grid-actions{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:12px}',this.shadowRoot.appendChild(t),this.shadowRoot.appendChild(i)}handleStateChange({prev:e,current:t}){e.status!==t.status&&this.render(t.status)}render(e){const t=this.shadowRoot.querySelector(".td-widget-content");t&&t.remove();const i=document.createElement("div");i.className="td-widget-content";const d=c.getState();switch(e){case n:i.innerHTML=h('<div class="td-widget-fab" id="td-widget-fab">\r\n <div class="td-fab-card">\r\n <button class="td-close-fab" id="td-fab-close">\r\n <span class="material-symbols-outlined" style="font-size: 16px;">close</span>\r\n </button>\r\n <div class="td-avatar-container">\r\n <div class="td-avatar" style="background-image: url(\'{{doctorAvatar}}\');"></div>\r\n <div class="td-status-dot" style="background: #22c55e;"></div>\r\n </div>\r\n <div class="td-info">\r\n <div class="td-brand">\r\n <span class="material-symbols-outlined" style="font-size: 14px;">local_hospital</span>\r\n <span>Clinic</span>\r\n </div>\r\n <h3 class="td-cta">Khám online ngay</h3>\r\n <p class="td-sub">Bác sĩ đang Online</p>\r\n </div>\r\n </div>\r\n</div>',d);break;case s:i.innerHTML=(e=>h('<div class="td-widget-expanded" id="td-widget-expanded">\r\n <header class="td-header">\r\n <div class="td-header-title">\r\n <div class="td-icon-box">\r\n <span class="material-symbols-outlined">medical_services</span>\r\n </div>\r\n <span>Clinic</span>\r\n </div>\r\n <button class="td-close-btn" id="td-expanded-close">\r\n <span class="material-symbols-outlined">close</span>\r\n </button>\r\n </header>\r\n\r\n <div class="td-content">\r\n <div class="td-doctor-profile">\r\n <div class="td-doctor-avatar" style="background-image: url(\'{{doctorAvatar}}\');">\r\n <div class="td-status-dot"\r\n style="width: 20px; height: 20px; border-width: 3px; bottom: 4px; right: 4px; background: #22c55e;">\r\n </div>\r\n </div>\r\n <h1 class="td-doctor-name">{{doctorName}}</h1>\r\n <p class="td-doctor-specialty">{{doctorSpecialty}}</p>\r\n\r\n <div class="td-online-badge">\r\n <span class="td-pulse"></span>\r\n <span class="td-badge-text">Đang trực tuyến</span>\r\n </div>\r\n </div>\r\n\r\n <div class="td-trust-grid">\r\n <div class="td-trust-item">\r\n <div class="td-icon-box">\r\n <span class="material-symbols-outlined">verified</span>\r\n </div>\r\n <h3 class="td-trust-title">Bác sĩ được xác thực</h3>\r\n </div>\r\n <div class="td-trust-item">\r\n <div class="td-icon-box">\r\n <span class="material-symbols-outlined">security</span>\r\n </div>\r\n <h3 class="td-trust-title">Bảo mật thông tin</h3>\r\n </div>\r\n </div>\r\n\r\n <div class="td-actions">\r\n <button class="td-btn td-btn-primary" id="td-btn-consult">\r\n <span class="material-symbols-outlined" style="margin-right: 8px;">videocam</span>\r\n Bắt đầu tư vấn ngay\r\n </button>\r\n <button class="td-btn td-btn-outline" id="td-btn-schedule">\r\n Đặt lịch hẹn sau\r\n </button>\r\n </div>\r\n </div>\r\n\r\n <div class="td-footer">\r\n Powered by <b>Clinic Connect</b>\r\n </div>\r\n</div>',e))(d);break;case r:i.innerHTML=(e=>h('<div class="td-widget-expanded" id="td-patient-form">\r\n <header class="td-header">\r\n <div class="td-header-title">\r\n <div class="td-icon-box">\r\n <span class="material-symbols-outlined">medical_services</span>\r\n </div>\r\n <span>Clinic</span>\r\n </div>\r\n <button class="td-close-btn" id="td-form-close">\r\n <span class="material-symbols-outlined">close</span>\r\n </button>\r\n </header>\r\n\r\n <div class="td-content">\r\n <div class="td-form-container">\r\n <div class="td-form-page-header">\r\n <h1 class="td-form-title">Kết nối với Bác sĩ</h1>\r\n <p class="td-form-desc">Vui lòng nhập thông tin để bắt đầu tư vấn trực tuyến.</p>\r\n </div>\r\n\r\n <form class="td-form" id="td-info-form">\r\n <div class="td-input-group">\r\n <label class="td-label">Họ và tên</label>\r\n <input type="text" class="td-input" name="name" placeholder="VD: Nguyễn Văn A" required />\r\n </div>\r\n\r\n <div class="td-input-group">\r\n <label class="td-label">Số điện thoại</label>\r\n <div style="position: relative;">\r\n <input type="tel" class="td-input" name="phone" placeholder="VD: 0912 345 678" required />\r\n <div\r\n style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); color: var(--td-primary);">\r\n <span class="material-symbols-outlined" style="font-size: 20px;">smartphone</span>\r\n </div>\r\n </div>\r\n </div>\r\n\r\n <div class="td-input-group">\r\n <label class="td-label">Triệu chứng của bạn?</label>\r\n <div class="td-chips-group">\r\n <button type="button" class="td-chip active">Sốt <span class="material-symbols-outlined"\r\n style="font-size: 16px;">check</span></button>\r\n <button type="button" class="td-chip">Ho / Cảm cúm</button>\r\n <button type="button" class="td-chip">Đau đầu</button>\r\n <button type="button" class="td-chip">Đau bụng</button>\r\n </div>\r\n </div>\r\n\r\n <div class="td-input-group">\r\n <label class="td-label">Mô tả thêm <span style="color: var(--td-text-sub); font-weight: 400;">(Tùy\r\n chọn)</span></label>\r\n <textarea class="td-textarea" name="symptoms"\r\n placeholder="Bạn đang cảm thấy như thế nào?"></textarea>\r\n </div>\r\n\r\n <div style="margin-top: 8px;">\r\n <button type="submit" class="td-btn td-btn-primary" id="td-form-submit">\r\n Bắt đầu tư vấn\r\n <span class="material-symbols-outlined" style="margin-left: 8px;">arrow_forward</span>\r\n </button>\r\n </div>\r\n\r\n <div class="td-secure-note">\r\n <span class="material-symbols-outlined" style="font-size: 14px;">lock</span>\r\n Thông tin y tế được bảo mật 100%\r\n </div>\r\n </form>\r\n </div>\r\n </div>\r\n</div>',e))(d);break;case o:i.innerHTML=(e=>h('<div class="td-consultation-modal">\r\n \x3c!-- Left: Video Panel --\x3e\r\n <div class="td-video-panel">\r\n <div class="td-main-video"\r\n style="background-image: url(\'https://lh3.googleusercontent.com/aida-public/AB6AXuC54B68xwAiOWZFQNVMIVKNBTKwo-nPCTsEgkaekhx9PbGDRCwcy18cFeALhbiaeOyaIS88c9RZst2sRWUyKTeSif-HqEfgU5Aoht-mk6Tjtuts2M4XmoMaxNSAi7qjKoQRYx61I4MolGfjCkxRN0lW5rlSlQfMwY0T8K1440SLM9hW_4u0N1Vg6kQTcSUitouGRmWktBHr-yH5QTu78AC1IOZLd5-HyWw0NUb6uESPpNZoZHoIEKIjFhsGBnCRmzHCUP9Ex6mP0XvW\');">\r\n </div>\r\n <div class="td-overlay"></div>\r\n\r\n <div class="td-video-header">\r\n <div class="td-badge-glass">\r\n <span class="material-symbols-outlined"\r\n style="color: #ef4444; font-size: 16px;">radio_button_checked</span>\r\n REC\r\n </div>\r\n <div class="td-badge-glass">\r\n <span class="material-symbols-outlined" style="font-size: 16px;">signal_cellular_alt</span>\r\n HD Quality\r\n </div>\r\n </div>\r\n\r\n <div class="td-pip"\r\n style="background-image: url(\'https://lh3.googleusercontent.com/aida-public/AB6AXuDnITTxxwp-J6t7xkVqnh6C9NPQS8i_k6_4F4IfzTfDM_ZgdX2HRvc947W1BU0LJYKOAA8qtHglPXseoj0Vk4sLfoRnKDOz88bUmK_ytSEvP_oYeeDKGRCfcEa6ugQO6aKR2l9W8glr63dswTODHe4am5IB3FRknTxNnZ0XuDU0z1xzkDMGpspRrXWwdoi8j9teleBeRsmkCdSe8dVb0q1r5eS8YjQ-nzo5f3qBB2-Eo9zyegUSaOCXhuaqSmqpVyICmTLvoIppbKNo\');">\r\n <span class="td-pip-label">You</span>\r\n </div>\r\n\r\n <div class="td-controls">\r\n <button class="td-ctrl-btn">\r\n <span class="material-symbols-outlined">mic</span>\r\n </button>\r\n <button class="td-ctrl-btn">\r\n <span class="material-symbols-outlined">videocam</span>\r\n </button>\r\n <button class="td-ctrl-end" id="td-consult-end">\r\n <span class="material-symbols-outlined">call_end</span>\r\n Kết thúc\r\n </button>\r\n <button class="td-ctrl-btn">\r\n <span class="material-symbols-outlined">settings</span>\r\n </button>\r\n </div>\r\n </div>\r\n\r\n \x3c!-- Right: Chat Panel --\x3e\r\n <div class="td-chat-panel">\r\n <div class="td-chat-header">\r\n <div class="td-chat-doc-info">\r\n <div class="td-chat-avatar" style="background-image: url(\'{{doctorAvatar}}\');"></div>\r\n <div>\r\n <h3 style="font-size: 16px; font-weight: 700;">{{doctorName}}</h3>\r\n <p style="font-size: 12px; color: var(--td-text-sub);">Online • Verified</p>\r\n </div>\r\n </div>\r\n <div class="td-chat-timer">\r\n <div style="display: flex; align-items: center; gap: 4px; font-size: 12px;">\r\n <span class="material-symbols-outlined"\r\n style="font-size: 16px; color: var(--td-primary);">timer</span>\r\n SESSION\r\n </div>\r\n <div class="td-timer-val">00:03:12</div>\r\n </div>\r\n </div>\r\n\r\n <div class="td-chat-messages">\r\n <div class="td-msg-system">\r\n Consultation started\r\n </div>\r\n <div class="td-msg-row doctor">\r\n <div class="td-msg-bubble">\r\n Xin chào. Tôi có thể giúp gì cho bạn hôm nay?\r\n <div class="td-msg-time">14:01</div>\r\n </div>\r\n </div>\r\n <div class="td-msg-row own">\r\n <div class="td-msg-bubble">\r\n Chào bác sĩ, tôi bị đau đầu...\r\n <div class="td-msg-time">14:02</div>\r\n </div>\r\n </div>\r\n </div>\r\n\r\n <div class="td-chat-input-area">\r\n <div class="td-input-wrapper">\r\n <textarea class="td-chat-input" placeholder="Nhập tin nhắn..."></textarea>\r\n <button class="td-send-btn">\r\n <span class="material-symbols-outlined">send</span>\r\n </button>\r\n </div>\r\n <div style="text-align: center; margin-top: 8px; font-size: 10px; color: var(--td-text-sub);">\r\n <span class="material-symbols-outlined" style="font-size: 10px; vertical-align: middle;">lock</span>\r\n Mã hóa đầu cuối\r\n </div>\r\n </div>\r\n </div>\r\n</div>',e))(d);break;case a:i.innerHTML=(e=>h('<div class="td-widget-expanded" id="td-summary-view">\r\n <header class="td-header">\r\n <h2 class="td-header-title" style="font-size: 16px;">Tổng kết tư vấn</h2>\r\n <button class="td-close-btn" id="td-summary-close">\r\n <span class="material-symbols-outlined">close</span>\r\n </button>\r\n </header>\r\n\r\n <div class="td-content">\r\n <div class="td-summary-container">\r\n <div class="td-success-header">\r\n <div class="td-success-icon">\r\n <span class="material-symbols-outlined" style="font-size: 48px;">check_circle</span>\r\n </div>\r\n <h3 class="td-summary-title">Tư vấn Hoàn tất</h3>\r\n <p class="td-summary-desc">Cuộc hẹn đã được ghi nhận vào hồ sơ sức khỏe của bạn.</p>\r\n </div>\r\n\r\n <div class="td-summary-card">\r\n <div class="td-chat-avatar"\r\n style="background-image: url(\'{{doctorAvatar}}\'); width: 56px; height: 56px;"></div>\r\n <div>\r\n <div style="font-weight: 700;">{{doctorName}}</div>\r\n <div style="color: var(--td-text-sub); font-size: 14px;">{{doctorSpecialty}}</div>\r\n </div>\r\n <div style="margin-left: auto; color: var(--td-primary);">\r\n <span class="material-symbols-outlined">verified_user</span>\r\n </div>\r\n </div>\r\n\r\n <div class="td-summary-details">\r\n <div class="td-detail-row">\r\n <span style="color: var(--td-text-sub); display: flex; gap: 6px;">\r\n <span class="material-symbols-outlined" style="font-size: 18px;">tag</span> Mã tư vấn\r\n </span>\r\n <span style="font-weight: 600;">#TD-93821</span>\r\n </div>\r\n <div class="td-detail-row">\r\n <span style="color: var(--td-text-sub); display: flex; gap: 6px;">\r\n <span class="material-symbols-outlined" style="font-size: 18px;">schedule</span> Thời gian\r\n </span>\r\n <span style="font-weight: 600;">10:00 AM, Today</span>\r\n </div>\r\n </div>\r\n\r\n <div class="td-note-box">\r\n <div class="td-note-title">\r\n <span class="material-symbols-outlined"\r\n style="font-size: 16px; color: var(--td-primary);">clinical_notes</span>\r\n Ghi chú bác sĩ\r\n </div>\r\n <p style="font-size: 14px; line-height: 1.5;">Bệnh nhân cần nghỉ ngơi và uống nhiều nước. Hạn chế vận\r\n động mạnh trong 2 ngày tới.</p>\r\n </div>\r\n\r\n <div class="td-actions">\r\n <div class="td-grid-actions">\r\n <button class="td-btn td-btn-outline" style="font-size: 12px; height: 40px; margin-bottom: 0;">\r\n Xem kết luận\r\n </button>\r\n <button class="td-btn td-btn-outline" style="font-size: 12px; height: 40px; margin-bottom: 0;">\r\n Tải đơn thuốc\r\n </button>\r\n </div>\r\n <button class="td-btn td-btn-primary">\r\n <span class="material-symbols-outlined" style="margin-right: 8px;">calendar_month</span>\r\n Đặt lịch tái khám\r\n </button>\r\n </div>\r\n </div>\r\n </div>\r\n</div>',e))(d);break;default:return}this.shadowRoot.appendChild(i),this.bindEvents(e)}bindEvents(e){if(e===n){const e=this.shadowRoot.getElementById("td-widget-fab"),t=this.shadowRoot.getElementById("td-fab-close");e&&e.addEventListener("click",e=>{e.composedPath().includes(t)||c.setState({status:s})}),t&&t.addEventListener("click",e=>{e.stopPropagation(),this.destroy()})}else if(e===s){const e=this.shadowRoot.getElementById("td-expanded-close"),t=this.shadowRoot.getElementById("td-btn-consult");e&&e.addEventListener("click",()=>{c.setState({status:n})}),t&&t.addEventListener("click",()=>{c.setState({status:r})})}else if(e===r){const e=this.shadowRoot.getElementById("td-form-close"),t=this.shadowRoot.getElementById("td-info-form");e&&e.addEventListener("click",()=>{c.setState({status:s})}),t&&t.addEventListener("submit",e=>{e.preventDefault();const i=new FormData(t),n=i.get("name"),s=i.get("phone");this.triggerCallback("onConsultationStarted",{name:n,phone:s}),c.setState({user:{name:n,phone:s},status:o})})}else if(e===o){this.joinVideoCall();const e=this.shadowRoot.getElementById("td-consult-end");e&&e.addEventListener("click",()=>{this.stopSocket(),c.setState({status:a})});const t=this.shadowRoot.querySelector(".td-send-btn"),i=this.shadowRoot.querySelector(".td-chat-input"),n=()=>{const e=i.value.trim();e&&(this.appendChatMessage(e,"own"),i.value="")};t&&t.addEventListener("click",n),i&&i.addEventListener("keypress",e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),n())})}else if(e===a){const e=this.shadowRoot.getElementById("td-summary-close");e&&e.addEventListener("click",()=>{c.setState({status:n})})}}triggerCallback(e,t){var i;"function"==typeof(null==(i=window.Clinic)?void 0:i[e])&&window.Clinic[e](t)}destroy(){this.container&&this.container.remove(),this.unsubscribe&&this.unsubscribe(),this.socket&&this.stopSocket(),this.livekit&&this.livekit.disconnect()}checkInlineTrigger(){const e=c.getState(),t=this.config.triggerElementId;if(t){const i=document.getElementById(t);if(i){i.innerHTML=h('<style>\r\n @keyframes td-pulse-animation {\r\n 0% {\r\n box-shadow: 0 0 0 0 rgba(34, 197, 94, 0.4);\r\n }\r\n\r\n 70% {\r\n box-shadow: 0 0 0 6px rgba(34, 197, 94, 0);\r\n }\r\n\r\n 100% {\r\n box-shadow: 0 0 0 0 rgba(34, 197, 94, 0);\r\n }\r\n }\r\n\r\n .td-inline-container {\r\n display: flex;\r\n flex-direction: column;\r\n padding: 14px;\r\n background: #f8faff;\r\n border: 1px solid #e2e8f0;\r\n border-radius: 10px;\r\n font-family: system-ui, -apple-system, sans-serif;\r\n }\r\n\r\n .td-inline-row {\r\n display: flex;\r\n align-items: center;\r\n gap: 12px;\r\n }\r\n\r\n .td-inline-footer {\r\n display: flex;\r\n align-items: center;\r\n justify-content: space-between;\r\n margin-top: 14px;\r\n padding-top: 12px;\r\n border-top: 1px solid #e5e7eb;\r\n }\r\n\r\n .td-inline-status {\r\n display: flex;\r\n align-items: center;\r\n gap: 8px;\r\n }\r\n\r\n .td-inline-pulse {\r\n width: 8px;\r\n height: 8px;\r\n background: #22c55e;\r\n border-radius: 50%;\r\n animation: td-pulse-animation 2s infinite;\r\n }\r\n\r\n .td-inline-text {\r\n color: #16a34a;\r\n font-weight: 600;\r\n font-size: 13px;\r\n }\r\n</style>\r\n<div class="td-inline-container">\r\n \x3c!-- Top: Doctor Info --\x3e\r\n <div class="td-inline-row">\r\n <div\r\n style="width: 48px; height: 48px; border-radius: 50%; background-image: url(\'{{doctorAvatar}}\'); background-size: cover; background-position: center; flex-shrink: 0; background-color: #e5e7eb; border: 2px solid white; box-shadow: 0 2px 4px rgba(0,0,0,0.05);">\r\n </div>\r\n <div style="flex: 1; min-width: 0;">\r\n <div\r\n style="font-weight: 700; font-size: 15px; color: #1f2937; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">\r\n {{doctorName}}</div>\r\n <div\r\n style="font-size: 13px; color: #6b7280; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">\r\n {{doctorSpecialty}}</div>\r\n </div>\r\n </div>\r\n\r\n \x3c!-- Bottom: Status & Action --\x3e\r\n <div class="td-inline-footer">\r\n <div class="td-inline-status">\r\n <span class="td-inline-pulse"></span>\r\n <span class="td-inline-text">Bác sĩ đang Online</span>\r\n </div>\r\n\r\n <button id="td-inline-btn" style="\r\n background: #0066ff; \r\n color: white; \r\n border: none; \r\n padding: 8px 16px; \r\n border-radius: 6px; \r\n font-weight: 600; \r\n font-size: 13px; \r\n cursor: pointer; \r\n display: flex; \r\n align-items: center; \r\n gap: 6px;\r\n white-space: nowrap;\r\n transition: all 0.2s;\r\n box-shadow: 0 2px 5px rgba(0,102,255,0.2);\r\n " onmouseover="this.style.background=\'#0052cc\'" onmouseout="this.style.background=\'#0066ff\'">\r\n <span class="material-symbols-outlined" style="font-size: 18px;">videocam</span>\r\n Tư vấn ngay\r\n </button>\r\n </div>\r\n</div>',e);const t=i.querySelector("#td-inline-btn");t&&t.addEventListener("click",()=>{c.setState({status:r})})}else console.warn(`Clinic Widget: Target element "${t}" not found.`)}}startSocket(){const e=c.getState(),t=e.config.socketUrl||l,{user:i,doctor:n}=e;this.socket||(this.socket=new Ue(t),this.socket.connect(()=>{console.log("Socket connected, registering...");this.socket.emit("register",{userId:"20.183299.4158",userName:(null==i?void 0:i.name)||"Guest",role:"customer"})}),this.socket.on("users-online",e=>{var t;console.log("[Widget] Received users-online event:",e);const i=Array.isArray(e)&&Array.isArray(e[0])?e[0]:e,n=null==(t=c.getState().doctor)?void 0:t.id;if(console.log("[Widget] Current Doctor ID (Config):",n),n&&Array.isArray(i)){const e=i.find(e=>{var t;return String(e.userId)===String(n)&&"DOCTOR"===(null==(t=e.role)?void 0:t.toUpperCase())}),t=!!e;console.log("[Widget] Doctor Status:",t?"Online":"Offline","Doctor Entry:",e),c.setState({doctorOnline:t})}}),this.socket.on("customer:token",e=>{if(console.log("Received token from server:",e),e.token){this.livekit||(this.livekit=new fl);const t=this.shadowRoot.querySelector(".td-consultation-modal");t?(console.log("[Widget] LiveKit Params:",{url:u,token:e.token}),this.livekit.connect(u,e.token,t)):console.error("Consultation modal not found for video rendering")}}))}joinVideoCall(){const e=c.getState(),{user:t,doctor:i}=e,n="20.183299.4158";this.socket?(console.log("Joining video call room with user:",null==t?void 0:t.name),this.socket.emit("register",{userId:n,userName:null==t?void 0:t.name,role:"customer"}),this.socket.emit("customer:join",{participantId:n,participantName:t.name,doctorId:i.id,type:"video"})):console.error("Socket not connected, cannot join video call")}appendChatMessage(e,t){const i=this.shadowRoot.querySelector(".td-chat-messages");if(!i)return;const n=document.createElement("div");n.className=`td-msg-row ${t}`;const s=document.createElement("div");s.className="td-msg-bubble",s.textContent=e;const r=document.createElement("div");r.className="td-msg-time";const o=new Date;r.textContent=`${o.getHours()}:${String(o.getMinutes()).padStart(2,"0")}`,s.appendChild(r),n.appendChild(s),i.appendChild(n),i.scrollTop=i.scrollHeight}stopSocket(){this.socket&&(this.socket.disconnect(),this.socket=null)}}!function(){const e=document.querySelector("script[data-widget-id]"),t=e?e.getAttribute("data-widget-id"):null,i=e?e.getAttribute("data-trigger-element-id"):null,n=e&&e.getAttribute("data-locale")||"vi",s=e&&e.getAttribute("data-store-id")||"longvan-store",r=e&&e.getAttribute("data-org-id")||"longvan-org",o=e&&e.getAttribute("data-doctor-id")||"20.184041.6561",a=e&&e.getAttribute("data-product-id")||"product-1",c={widgetId:t,triggerElementId:i,locale:n,storeId:s,orgId:r,doctorId:o,productId:a,scriptElement:e};function d(){if(!t)return void console.warn("Clinic Widget: No widget-id provided.");const e=new vl(c);window.Clinic=window.Clinic||{},window.Clinic.instance=e,e.init(),window.Clinic.onReady&&window.Clinic.onReady()}"complete"===document.readyState||"interactive"===document.readyState?setTimeout(d,1):document.addEventListener("DOMContentLoaded",d)}()});