livekit-client 2.22.1 → 2.22.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.
- package/dist/livekit-client.e2ee.worker.js +1 -1
- package/dist/livekit-client.e2ee.worker.js.map +1 -1
- package/dist/livekit-client.e2ee.worker.mjs +177 -39
- package/dist/livekit-client.e2ee.worker.mjs.map +1 -1
- package/dist/livekit-client.esm.mjs +85 -60
- package/dist/livekit-client.esm.mjs.map +1 -1
- package/dist/livekit-client.umd.js +1 -1
- package/dist/livekit-client.umd.js.map +1 -1
- package/dist/src/api/SignalClient.d.ts.map +1 -1
- package/dist/src/e2ee/E2eeManager.d.ts +7 -0
- package/dist/src/e2ee/E2eeManager.d.ts.map +1 -1
- package/dist/src/e2ee/constants.d.ts +5 -0
- package/dist/src/e2ee/constants.d.ts.map +1 -1
- package/dist/src/e2ee/types.d.ts +9 -2
- package/dist/src/e2ee/types.d.ts.map +1 -1
- package/dist/src/e2ee/worker/FrameCryptor.d.ts +42 -1
- package/dist/src/e2ee/worker/FrameCryptor.d.ts.map +1 -1
- package/dist/src/room/PCTransportManager.d.ts +12 -0
- package/dist/src/room/PCTransportManager.d.ts.map +1 -1
- package/dist/src/room/data-stream/incoming/StreamReader.d.ts +17 -17
- package/dist/src/room/data-stream/incoming/StreamReader.d.ts.map +1 -1
- package/dist/ts4.2/e2ee/E2eeManager.d.ts +7 -0
- package/dist/ts4.2/e2ee/constants.d.ts +5 -0
- package/dist/ts4.2/e2ee/types.d.ts +9 -2
- package/dist/ts4.2/e2ee/worker/FrameCryptor.d.ts +42 -1
- package/dist/ts4.2/room/PCTransportManager.d.ts +12 -0
- package/dist/ts4.2/room/data-stream/incoming/StreamReader.d.ts +17 -17
- package/package.json +1 -1
- package/src/api/SignalClient.ts +2 -1
- package/src/e2ee/E2eeManager.ts +38 -14
- package/src/e2ee/constants.ts +6 -0
- package/src/e2ee/subscriberBlackScreen.test.ts +544 -0
- package/src/e2ee/types.ts +9 -2
- package/src/e2ee/worker/FrameCryptor.race.test.ts +9 -26
- package/src/e2ee/worker/FrameCryptor.test.ts +0 -1
- package/src/e2ee/worker/FrameCryptor.ts +185 -52
- package/src/e2ee/worker/e2ee.worker.ts +38 -6
- package/src/room/PCTransportManager.test.ts +35 -0
- package/src/room/PCTransportManager.ts +12 -4
- package/src/room/data-stream/incoming/IncomingDataStreamManager.test.ts +171 -0
- package/src/room/data-stream/incoming/IncomingDataStreamManager.ts +17 -18
- package/src/room/data-stream/incoming/StreamReader.ts +20 -50
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LivekitClient={})}(this,(function(e){"use strict";function t(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(n){if("default"!==n&&!(n in e)){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}}))})),Object.freeze(e)}var n=Object.defineProperty,i=(e,t,i)=>((e,t,i)=>t in e?n(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class r{constructor(){i(this,"_locking"),i(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()})),n=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),n}}function s(e,t){if(!e)throw new Error(t)}function a(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 o(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 c(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 d=Symbol("@bufbuild/protobuf/enum-type");function l(e){const t=e[d];return s(t,"missing enum type on enum object"),t}function u(e,t,n,i){e[d]=h(t,n.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function h(e,t,n){const i=Object.create(null),r=Object.create(null),s=[];for(const a of t){const e=m(a);s.push(e),i[a.name]=e,r[a.no]=e}return{typeName:e,values:s,findName:e=>i[e],findNumber:e=>r[e]}}function p(e,t,n){const i={};for(const r of t){const e=m(r);i[e.localName]=e.no,i[e.no]=e.localName}return u(i,e,t),i}function m(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class g{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const n=this.getType().runtime.bin,i=n.makeReadOptions(t);return n.readMessage(this,i.readerFactory(e),e.byteLength,i),this}fromJson(e,t){const n=this.getType(),i=n.runtime.json,r=i.makeReadOptions(t);return i.readMessage(n,e,r,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,n=t.makeWriteOptions(e),i=n.writerFactory();return t.writeMessage(this,i,n),i.finish()}toJson(e){const t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,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 v(){let e=0,t=0;for(let i=0;i<28;i+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<i,!(128&n))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(15&n)<<28,t=(112&n)>>4,!(128&n))return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,!(128&n))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function f(e,t,n){for(let s=0;s<28;s+=7){const i=e>>>s,r=!(i>>>7==0&&0==t),a=255&(r?128|i:i);if(n.push(a),!r)return}const i=e>>>28&15|(7&t)<<4,r=!!(t>>3);if(n.push(255&(r?128|i:i)),r){for(let e=3;e<31;e+=7){const i=t>>>e,r=!(i>>>7==0),s=255&(r?128|i:i);if(n.push(s),!r)return}n.push(t>>>31&1)}}const k=4294967296;function y(e){const t="-"===e[0];t&&(e=e.slice(1));const n=1e6;let i=0,r=0;function s(t,s){const a=Number(e.slice(t,s));r*=n,i=i*n+a,i>=k&&(r+=i/k|0,i%=k)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),t?S(i,r):T(i,r)}function b(e,t){var n=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t);if(e=n.lo,(t=n.hi)<=2097151)return String(k*t+e);const i=16777215&(e>>>24|t<<8),r=t>>16&65535;let s=(16777215&e)+6777216*i+6710656*r,a=i+8147497*r,o=2*r;const c=1e7;return s>=c&&(a+=Math.floor(s/c),s%=c),a>=c&&(o+=Math.floor(a/c),a%=c),o.toString()+E(a)+E(s)}function T(e,t){return{lo:0|e,hi:0|t}}function S(e,t){return t=~t,e?e=1+~e:t+=1,T(e,t)}const E=e=>{const t=String(e);return"0000000".slice(t.length)+t};function C(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(127&e|128),e>>=7;t.push(1)}}function w(){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 n=5;128&e&&n<10;n++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const R=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"),n=BigInt("9223372036854775807"),i=BigInt("0"),r=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const i="bigint"==typeof e?e:BigInt(e);if(i>n||i<t)throw new Error("int64 invalid: ".concat(e));return i},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>r||t<i)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,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)),uDec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0))}}const t=e=>s(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),n=e=>s(/^[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()),n(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),y(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),n(e),y(e)),dec:(e,t)=>function(e,t){let n=T(e,t);const i=2147483648&n.hi;i&&(n=S(n.lo,n.hi));const r=b(n.lo,n.hi);return i?"-"+r:r}(e,t),uDec:(e,t)=>b(e,t)}}();var P,I,_;function M(e,t,n){if(t===n)return!0;if(e==P.BYTES){if(!(t instanceof Uint8Array&&n instanceof Uint8Array))return!1;if(t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}switch(e){case P.UINT64:case P.FIXED64:case P.INT64:case P.SFIXED64:case P.SINT64:return t==n}return!1}function D(e,t){switch(e){case P.BOOL:return!1;case P.UINT64:case P.FIXED64:case P.INT64:case P.SFIXED64:case P.SINT64:return 0==t?R.zero:"0";case P.DOUBLE:case P.FLOAT:return 0;case P.BYTES:return new Uint8Array(0);case P.STRING:return"";default:return 0}}function O(e,t){switch(e){case P.BOOL:return!1===t;case P.STRING:return""===t;case P.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}function A(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function N(e){if(Array.isArray(e))return e}function L(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t);if("object"!=typeof i)return i;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:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function x(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function U(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function F(e,t){return N(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,r,s,a,o=[],c=!0,d=!1;try{if(s=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=s.call(n)).done)&&(o.push(i.value),o.length!==t);c=!0);}catch(e){d=!0,r=e}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(d)throw r}}return o}}(e,t)||j(e,t)||x()}function B(e){return N(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||j(e)||x()}function j(e,t){if(e){if("string"==typeof e)return A(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?A(e,t):void 0}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(P||(P={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(I||(I={})),function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(_||(_={}));class q{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 i=0;i<this.chunks.length;i++)e+=this.chunks[i].length;let t=new Uint8Array(e),n=0;for(let i=0;i<this.chunks.length;i++)t.set(this.chunks[i],n),n+=this.chunks[i].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(o(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return a(e),C(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){c(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){o(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){a(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return a(e),C(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=R.enc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=R.uEnc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}int64(e){let t=R.enc(e);return f(t.lo,t.hi,this.buf),this}sint64(e){let t=R.enc(e),n=t.hi>>31;return f(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=R.uEnc(e);return f(t.lo,t.hi,this.buf),this}}class V{constructor(e,t){this.varint64=v,this.uint32=w,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,n=7&e;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case _.Varint:for(;128&this.buf[this.pos++];);break;case _.Bit64:this.pos+=4;case _.Bit32:this.pos+=4;break;case _.LengthDelimited:let n=this.uint32();this.pos+=n;break;case _.StartGroup:for(;;){const e=F(this.tag(),2),n=e[0],i=e[1];if(i===_.EndGroup){if(void 0!==t&&n!==t)throw new Error("invalid end group tag");break}this.skip(i,n)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,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 R.dec(...this.varint64())}uint64(){return R.uDec(...this.varint64())}sint64(){let e=F(this.varint64(),2),t=e[0],n=e[1],i=-(1&t);return t=(t>>>1|(1&n)<<31)^i,n=n>>>1^i,R.dec(t,n)}bool(){let e=F(this.varint64(),2),t=e[0],n=e[1];return 0!==t||0!==n}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return R.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return R.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 W(e){const t=e.field.localName,n=Object.create(null);return n[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 D(t.T,t.L);case"message":const e=t.T,n=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}(e),[n,()=>n[t]]}let H="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),K=[];for(let Vh=0;Vh<H.length;Vh++)K[H[Vh].charCodeAt(0)]=Vh;K["-".charCodeAt(0)]=H.indexOf("+"),K["_".charCodeAt(0)]=H.indexOf("/");const z={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let n,i=new Uint8Array(t),r=0,s=0,a=0;for(let o=0;o<e.length;o++){if(n=K[e.charCodeAt(o)],void 0===n)switch(e[o]){case"=":s=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:a=n,s=1;break;case 1:i[r++]=a<<2|(48&n)>>4,a=n,s=2;break;case 2:i[r++]=(15&a)<<4|(60&n)>>2,a=n,s=3;break;case 3:i[r++]=(3&a)<<6|n,s=0}}if(1==s)throw Error("invalid base64 string.");return i.subarray(0,r)},enc(e){let t,n="",i=0,r=0;for(let s=0;s<e.length;s++)switch(t=e[s],i){case 0:n+=H[t>>2],r=(3&t)<<4,i=1;break;case 1:n+=H[r|t>>4],r=(15&t)<<2,i=2;break;case 2:n+=H[r|t>>6],n+=H[63&t],i=0}return i&&(n+=H[r],n+="=",1==i&&(n+="=")),n}};function G(e,t,n){Y(t,e);const i=t.runtime.bin.makeReadOptions(n),r=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter((e=>e.no===t.no))}(e.getType().runtime.bin.listUnknownFields(e),t.field),s=F(W(t),2),a=s[0],o=s[1];for(const c of r)t.runtime.bin.readField(a,i.readerFactory(c.data),t.field,c.wireType,i);return o()}function J(e,t,n,i){Y(t,e);const r=t.runtime.bin.makeReadOptions(i),s=t.runtime.bin.makeWriteOptions(i);if(Q(e,t)){const n=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of n)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const a=s.writerFactory();let o=t.field;o.opt||o.repeated||"enum"!=o.kind&&"scalar"!=o.kind||(o=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(o,n,a,s);const c=r.readerFactory(a.finish());for(;c.pos<c.len;){const t=F(c.tag(),2),n=t[0],i=t[1],r=c.skip(i,n);e.getType().runtime.bin.onUnknownField(e,n,i,r)}}function Q(e,t){const n=e.getType();return t.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(e).find((e=>e.no==t.field.no))}function Y(e,t){s(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function X(e,t){const n=e.localName;if(e.repeated)return t[n].length>0;if(e.oneof)return t[e.oneof.localName].case===n;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?void 0!==t[n]:"enum"==e.kind?t[n]!==e.T.values[0].no:!O(e.T,t[n]);case"message":return void 0!==t[n];case"map":return Object.keys(t[n]).length>0}}function Z(e,t){const n=e.localName,i=!e.opt&&!e.req;if(e.repeated)t[n]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[n]={};break;case"enum":t[n]=i?e.T.values[0].no:void 0;break;case"scalar":t[n]=i?D(e.T,e.L):void 0;break;case"message":t[n]=void 0}}function $(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(g.prototype).every((t=>t in e&&"function"==typeof e[t])))return!1;const n=e.getType();return null!==n&&"function"==typeof n&&"typeName"in n&&"string"==typeof n.typeName&&(void 0===t||n.typeName==t.typeName)}function ee(e,t){return $(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}P.DOUBLE,P.FLOAT,P.INT64,P.UINT64,P.INT32,P.UINT32,P.BOOL,P.STRING,P.BYTES;const te={ignoreUnknownFields:!1},ne={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function ie(e){return e?Object.assign(Object.assign({},te),e):te}function re(e){return e?Object.assign(Object.assign({},ne),e):ne}const se=Symbol(),ae=Symbol();function oe(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 ce(e,t,i,r,a){let o=i.localName;if(i.repeated){if(s("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(a.typeName,".").concat(i.name," from JSON: ").concat(oe(t)));const c=e[o];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(a.typeName,".").concat(i.name," from JSON: ").concat(oe(e)));switch(i.kind){case"message":c.push(i.T.fromJson(e,r));break;case"enum":const t=ue(i.T,e,r.ignoreUnknownFields,!0);t!==ae&&c.push(t);break;case"scalar":try{c.push(le(i.T,e,i.L,!0))}catch(n){let r="cannot decode field ".concat(a.typeName,".").concat(i.name," from JSON: ").concat(oe(e));throw n instanceof Error&&n.message.length>0&&(r+=": ".concat(n.message)),new Error(r)}}}}else if("map"==i.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(a.typeName,".").concat(i.name," from JSON: ").concat(oe(t)));const s=e[o];for(const e of Object.entries(t)){var c=F(e,2);const o=c[0],d=c[1];if(null===d)throw new Error("cannot decode field ".concat(a.typeName,".").concat(i.name," from JSON: map value null"));let l;try{l=de(i.K,o)}catch(n){let r="cannot decode map key for field ".concat(a.typeName,".").concat(i.name," from JSON: ").concat(oe(t));throw n instanceof Error&&n.message.length>0&&(r+=": ".concat(n.message)),new Error(r)}switch(i.V.kind){case"message":s[l]=i.V.T.fromJson(d,r);break;case"enum":const e=ue(i.V.T,d,r.ignoreUnknownFields,!0);e!==ae&&(s[l]=e);break;case"scalar":try{s[l]=le(i.V.T,d,I.BIGINT,!0)}catch(n){let r="cannot decode map value for field ".concat(a.typeName,".").concat(i.name," from JSON: ").concat(oe(t));throw n instanceof Error&&n.message.length>0&&(r+=": ".concat(n.message)),new Error(r)}}}}else switch(i.oneof&&(e=e[i.oneof.localName]={case:o},o="value"),i.kind){case"message":const s=i.T;if(null===t&&"google.protobuf.Value"!=s.typeName)return;let c=e[o];$(c)?c.fromJson(t,r):(e[o]=c=s.fromJson(t,r),s.fieldWrapper&&!i.oneof&&(e[o]=s.fieldWrapper.unwrapField(c)));break;case"enum":const d=ue(i.T,t,r.ignoreUnknownFields,!1);switch(d){case se:Z(i,e);break;case ae:break;default:e[o]=d}break;case"scalar":try{const n=le(i.T,t,i.L,!1);if(n===se)Z(i,e);else e[o]=n}catch(n){let r="cannot decode field ".concat(a.typeName,".").concat(i.name," from JSON: ").concat(oe(t));throw n instanceof Error&&n.message.length>0&&(r+=": ".concat(n.message)),new Error(r)}}}function de(e,t){if(e===P.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return le(e,t,I.BIGINT,!0).toString()}function le(e,t,i,r){if(null===t)return r?D(e,i):se;switch(e){case P.DOUBLE:case P.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 r=Number(t);if(Number.isNaN(r))break;if(!Number.isFinite(r))break;return e==P.FLOAT&&c(r),r;case P.INT32:case P.FIXED32:case P.SFIXED32:case P.SINT32:case P.UINT32:let s;if("number"==typeof t?s=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(s=Number(t)),void 0===s)break;return e==P.UINT32||e==P.FIXED32?o(s):a(s),s;case P.INT64:case P.SFIXED64:case P.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const d=R.parse(t);return i?d.toString():d;case P.FIXED64:case P.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const l=R.uParse(t);return i?l.toString():l;case P.BOOL:if("boolean"!=typeof t)break;return t;case P.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(n){throw new Error("invalid UTF8")}return t;case P.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return z.dec(t)}throw new Error}function ue(e,t,n,i){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:i?e.values[0].no:se;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const i=e.findName(t);if(void 0!==i)return i.no;if(n)return ae}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(oe(t)))}function he(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function pe(e,t,n){if("map"==e.kind){s("object"==typeof t&&null!=t);const o={},c=Object.entries(t);switch(e.V.kind){case"scalar":for(const n of c){var i=F(n,2);const t=i[0],r=i[1];o[t.toString()]=ge(e.V.T,r)}break;case"message":for(const e of c){var r=F(e,2);const t=r[0],i=r[1];o[t.toString()]=i.toJson(n)}break;case"enum":const t=e.V.T;for(const e of c){var a=F(e,2);const i=a[0],r=a[1];o[i.toString()]=me(t,r,n.enumAsInteger)}}return n.emitDefaultValues||c.length>0?o:void 0}if(e.repeated){s(Array.isArray(t));const i=[];switch(e.kind){case"scalar":for(let n=0;n<t.length;n++)i.push(ge(e.T,t[n]));break;case"enum":for(let r=0;r<t.length;r++)i.push(me(e.T,t[r],n.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)i.push(t[e].toJson(n))}return n.emitDefaultValues||i.length>0?i:void 0}switch(e.kind){case"scalar":return ge(e.T,t);case"enum":return me(e.T,t,n.enumAsInteger);case"message":return ee(e.T,t).toJson(n)}}function me(e,t,n){var i;if(s("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(n)return t;const r=e.findNumber(t);return null!==(i=null==r?void 0:r.name)&&void 0!==i?i:t}function ge(e,t){switch(e){case P.INT32:case P.SFIXED32:case P.SINT32:case P.FIXED32:case P.UINT32:return s("number"==typeof t),t;case P.FLOAT:case P.DOUBLE:return s("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case P.STRING:return s("string"==typeof t),t;case P.BOOL:return s("boolean"==typeof t),t;case P.UINT64:case P.FIXED64:case P.INT64:case P.SFIXED64:case P.SINT64:return s("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case P.BYTES:return s(t instanceof Uint8Array),z.enc(t)}}const ve=Symbol("@bufbuild/protobuf/unknown-fields"),fe={readUnknownFields:!0,readerFactory:e=>new V(e)},ke={writeUnknownFields:!0,writerFactory:()=>new q};function ye(e){return e?Object.assign(Object.assign({},fe),e):fe}function be(e){return e?Object.assign(Object.assign({},ke),e):ke}function Te(e,t,n,i,r){let s=n.repeated,a=n.localName;switch(n.oneof&&((e=e[n.oneof.localName]).case!=a&&delete e.value,e.case=a,a="value"),n.kind){case"scalar":case"enum":const o="enum"==n.kind?P.INT32:n.T;let c=Ce;if("scalar"==n.kind&&n.L>0&&(c=Ee),s){let n=e[a];if(i==_.LengthDelimited&&o!=P.STRING&&o!=P.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,o))}else n.push(c(t,o))}else e[a]=c(t,o);break;case"message":const d=n.T;s?e[a].push(Se(t,new d,r,n)):$(e[a])?Se(t,e[a],r,n):(e[a]=Se(t,new d,r,n),!d.fieldWrapper||n.oneof||n.repeated||(e[a]=d.fieldWrapper.unwrapField(e[a])));break;case"map":let l=function(e,t,n){const i=t.uint32(),r=t.pos+i;let s,a;for(;t.pos<r;){switch(F(t.tag(),1)[0]){case 1:s=Ce(t,e.K);break;case 2:switch(e.V.kind){case"scalar":a=Ce(t,e.V.T);break;case"enum":a=t.int32();break;case"message":a=Se(t,new e.V.T,n,void 0)}}}void 0===s&&(s=D(e.K,I.BIGINT));"string"!=typeof s&&"number"!=typeof s&&(s=s.toString());if(void 0===a)switch(e.V.kind){case"scalar":a=D(e.V.T,I.BIGINT);break;case"enum":a=e.V.T.values[0].no;break;case"message":a=new e.V.T}return[s,a]}(n,t,r),u=F(l,2),h=u[0],p=u[1];e[a][h]=p}}function Se(e,t,n,i){const r=t.getType().runtime.bin,s=null==i?void 0:i.delimited;return r.readMessage(t,e,s?i.no:e.uint32(),n,s),t}function Ee(e,t){const n=Ce(e,t);return"bigint"==typeof n?n.toString():n}function Ce(e,t){switch(t){case P.STRING:return e.string();case P.BOOL:return e.bool();case P.DOUBLE:return e.double();case P.FLOAT:return e.float();case P.INT32:return e.int32();case P.INT64:return e.int64();case P.UINT64:return e.uint64();case P.FIXED64:return e.fixed64();case P.BYTES:return e.bytes();case P.FIXED32:return e.fixed32();case P.SFIXED32:return e.sfixed32();case P.SFIXED64:return e.sfixed64();case P.SINT64:return e.sint64();case P.UINT32:return e.uint32();case P.SINT32:return e.sint32()}}function we(e,t,n,i){s(void 0!==t);const r=e.repeated;switch(e.kind){case"scalar":case"enum":let o="enum"==e.kind?P.INT32:e.T;if(r)if(s(Array.isArray(t)),e.packed)!function(e,t,n,i){if(!i.length)return;e.tag(n,_.LengthDelimited).fork();let r=F(_e(t),2)[1];for(let s=0;s<i.length;s++)e[r](i[s]);e.join()}(n,o,e.no,t);else for(const i of t)Ie(n,o,e.no,i);else Ie(n,o,e.no,t);break;case"message":if(r){s(Array.isArray(t));for(const r of t)Pe(n,i,e,r)}else Pe(n,i,e,t);break;case"map":s("object"==typeof t&&null!=t);for(const r of Object.entries(t)){var a=F(r,2);Re(n,i,e,a[0],a[1])}}}function Re(e,t,n,i,r){e.tag(n.no,_.LengthDelimited),e.fork();let a=i;switch(n.K){case P.INT32:case P.FIXED32:case P.UINT32:case P.SFIXED32:case P.SINT32:a=Number.parseInt(i);break;case P.BOOL:s("true"==i||"false"==i),a="true"==i}switch(Ie(e,n.K,1,a),n.V.kind){case"scalar":Ie(e,n.V.T,2,r);break;case"enum":Ie(e,P.INT32,2,r);break;case"message":s(void 0!==r),e.tag(2,_.LengthDelimited).bytes(r.toBinary(t))}e.join()}function Pe(e,t,n,i){const r=ee(n.T,i);n.delimited?e.tag(n.no,_.StartGroup).raw(r.toBinary(t)).tag(n.no,_.EndGroup):e.tag(n.no,_.LengthDelimited).bytes(r.toBinary(t))}function Ie(e,t,n,i){s(void 0!==i);let r=F(_e(t),2),a=r[0],o=r[1];e.tag(n,a)[o](i)}function _e(e){let t=_.Varint;switch(e){case P.BYTES:case P.STRING:t=_.LengthDelimited;break;case P.DOUBLE:case P.FIXED64:case P.SFIXED64:t=_.Bit64;break;case P.FIXED32:case P.SFIXED32:case P.FLOAT:t=_.Bit32}return[t,P[e].toLowerCase()]}function Me(e){if(void 0===e)return e;if($(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function De(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class Oe{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 n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}}function Ae(e,t){const n=Le(e);return t?n:je(Be(n))}const Ne=Le;function Le(e){let t=!1;const n=[];for(let i=0;i<e.length;i++){let r=e.charAt(i);switch(r){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n.push(r),t=!1;break;default:t&&(t=!1,r=r.toUpperCase()),n.push(r)}}return n.join("")}const xe=new Set(["constructor","toString","toJSON","valueOf"]),Ue=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Fe=e=>"".concat(e,"$"),Be=e=>Ue.has(e)?Fe(e):e,je=e=>xe.has(e)?Fe(e):e;class qe{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=Ae(e,!1)}addField(e){s(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 Ve=(We=e=>new Oe(e,(e=>function(e){var t,n,i,r,s,a;const o=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=Ae(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:Ne(d.name),e.repeated=null!==(n=d.repeated)&&void 0!==n&&n,"scalar"==d.kind&&(e.L=null!==(i=d.L)&&void 0!==i?i:I.BIGINT),e.delimited=null!==(r=d.delimited)&&void 0!==r&&r,e.req=null!==(s=d.req)&&void 0!==s&&s,e.opt=null!==(a=d.opt)&&void 0!==a&&a,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=P.BYTES&&d.T!=P.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new qe(t)),e.oneof=c,c.addField(e)}o.push(e)}return o}(e))),He=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const n=t.localName,i=e;if(t.repeated)i[n]=[];else switch(t.kind){case"oneof":i[n]={case:void 0};break;case"enum":i[n]=0;break;case"map":i[n]={};break;case"scalar":i[n]=D(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:ie,makeWriteOptions:re,readMessage(e,t,n,i){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(oe(t)));i=null!=i?i:new e;const r=new Map,s=n.typeRegistry;for(const o of Object.entries(t)){var a=F(o,2);const t=a[0],c=a[1],d=e.fields.findJsonName(t);if(d){if(d.oneof){if(null===c&&"scalar"==d.kind)continue;const n=r.get(d.oneof);if(void 0!==n)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(d.oneof.name,'" present: "').concat(n,'", "').concat(t,'"'));r.set(d.oneof,t)}ce(i,c,d,n,e)}else{let r=!1;if((null==s?void 0:s.findExtension)&&t.startsWith("[")&&t.endsWith("]")){const a=s.findExtension(t.substring(1,t.length-1));if(a&&a.extendee.typeName==e.typeName){r=!0;const e=F(W(a),2),t=e[0],s=e[1];ce(t,c,a.field,n,a),J(i,a,s(),n)}}if(!r&&!n.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(t,'" is unknown'))}}return i},writeMessage(e,t){const i=e.getType(),r={};let s;try{for(s of i.fields.byNumber()){if(!X(s,e)){if(s.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!he(s))continue}const n=pe(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t);void 0!==n&&(r[t.useProtoFieldName?s.name:s.jsonName]=n)}const n=t.typeRegistry;if(null==n?void 0:n.findExtensionFor)for(const s of i.runtime.bin.listUnknownFields(e)){const a=n.findExtensionFor(i.typeName,s.no);if(a&&Q(e,a)){const n=G(e,a,t),i=pe(a.field,n,t);void 0!==i&&(r[a.field.jsonName]=i)}}}catch(n){const t=s?"cannot encode field ".concat(i.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(i.typeName," to JSON"),r=n instanceof Error?n.message:String(n);throw new Error(t+(r.length>0?": ".concat(r):""))}return r},readScalar:(e,t,n)=>le(e,t,null!=n?n:I.BIGINT,!0),writeScalar(e,t,n){if(void 0!==t)return n||O(e,t)?ge(e,t):void 0},debug:oe},bin:{makeReadOptions:ye,makeWriteOptions:be,listUnknownFields(e){var t;return null!==(t=e[ve])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[ve]},writeUnknownFields(e,t){const n=e[ve];if(n)for(const i of n)t.tag(i.no,i.wireType).raw(i.data)},onUnknownField(e,t,n,i){const r=e;Array.isArray(r[ve])||(r[ve]=[]),r[ve].push({no:t,wireType:n,data:i})},readMessage(e,t,n,i,r){const s=e.getType(),a=r?t.len:t.pos+n;let o,c;for(;t.pos<a;){var d=F(t.tag(),2);if(o=d[0],c=d[1],!0===r&&c==_.EndGroup)break;const n=s.fields.find(o);if(n)Te(e,t,n,c,i);else{const n=t.skip(c,o);i.readUnknownFields&&this.onUnknownField(e,o,c,n)}}if(r&&(c!=_.EndGroup||o!==n))throw new Error("invalid end group tag")},readField:Te,writeMessage(e,t,n){const i=e.getType();for(const r of i.fields.byNumber())if(X(r,e))we(r,r.oneof?e[r.oneof.localName].value:e[r.localName],t,n);else if(r.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(r.name," to binary: required field not set"));return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,i){void 0!==t&&we(e,t,n,i)}},util:Object.assign(Object.assign({},{setEnumType:u,initPartial(e,t){if(void 0===e)return;const n=t.getType();for(const r of n.fields.byMember()){const n=r.localName,s=t,a=e;if(null!=a[n])switch(r.kind){case"oneof":const e=a[n].case;if(void 0===e)continue;const t=r.findField(e);let o=a[n].value;t&&"message"==t.kind&&!$(o,t.T)?o=new t.T(o):t&&"scalar"===t.kind&&t.T===P.BYTES&&(o=De(o)),s[n]={case:e,value:o};break;case"scalar":case"enum":let c=a[n];r.T===P.BYTES&&(c=r.repeated?c.map(De):De(c)),s[n]=c;break;case"map":switch(r.V.kind){case"scalar":case"enum":if(r.V.T===P.BYTES)for(const t of Object.entries(a[n])){var i=F(t,2);const e=i[0],r=i[1];s[n][e]=De(r)}else Object.assign(s[n],a[n]);break;case"message":const e=r.V.T;for(const t of Object.keys(a[n])){let i=a[n][t];e.fieldWrapper||(i=new e(i)),s[n][t]=i}}break;case"message":const d=r.T;if(r.repeated)s[n]=a[n].map((e=>$(e,d)?e:new d(e)));else{const e=a[n];d.fieldWrapper?"google.protobuf.BytesValue"===d.typeName?s[n]=De(e):s[n]=e:s[n]=$(e,d)?e:new d(e)}}}},equals:(e,t,n)=>t===n||!(!t||!n)&&e.fields.byMember().every((e=>{const i=t[e.localName],r=n[e.localName];if(e.repeated){if(i.length!==r.length)return!1;switch(e.kind){case"message":return i.every(((t,n)=>e.T.equals(t,r[n])));case"scalar":return i.every(((t,n)=>M(e.T,t,r[n])));case"enum":return i.every(((e,t)=>M(P.INT32,e,r[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let t=i,n=r;return e.T.fieldWrapper&&(void 0===t||$(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===n||$(n)||(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case"enum":return M(P.INT32,i,r);case"scalar":return M(e.T,i,r);case"oneof":if(i.case!==r.case)return!1;const s=e.findField(i.case);if(void 0===s)return!0;switch(s.kind){case"message":return s.T.equals(i.value,r.value);case"enum":return M(P.INT32,i.value,r.value);case"scalar":return M(s.T,i.value,r.value)}throw new Error("oneof cannot contain ".concat(s.kind));case"map":const a=Object.keys(i).concat(Object.keys(r));switch(e.V.kind){case"message":const t=e.V.T;return a.every((e=>t.equals(i[e],r[e])));case"enum":return a.every((e=>M(P.INT32,i[e],r[e])));case"scalar":const n=e.V.T;return a.every((e=>M(n,i[e],r[e])))}}})),clone(e){const t=e.getType(),n=new t,i=n;for(const s of t.fields.byMember()){const t=e[s.localName];let n;if(s.repeated)n=t.map(Me);else if("map"==s.kind){n=i[s.localName];for(const e of Object.entries(t)){var r=F(e,2);const t=r[0],i=r[1];n[t]=Me(i)}}else n="oneof"==s.kind?s.findField(t.case)?{case:t.case,value:Me(t.value)}:{case:void 0}:Me(t);i[s.localName]=n}for(const s of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(i,s.no,s.wireType,s.data);return n}}),{newFieldList:We,initFields:He}),makeMessageType(e,t,n){return function(e,t,n,i){var r;const s=null!==(r=null==i?void 0:i.localName)&&void 0!==r?r:t.substring(t.lastIndexOf(".")+1),a={[s]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[s];return Object.setPrototypeOf(a.prototype,new g),Object.assign(a,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary:(e,t)=>(new a).fromBinary(e,t),fromJson:(e,t)=>(new a).fromJson(e,t),fromJsonString:(e,t)=>(new a).fromJsonString(e,t),equals:(t,n)=>e.util.equals(a,t,n)}),a}(this,e,t,n)},makeEnum:p,makeEnumType:h,getEnumType:l,makeExtension(e,t,n){return function(e,t,n,i){let r;return{typeName:t,extendee:n,get field(){if(!r){const n="function"==typeof i?i():i;n.name=t.split(".").pop(),n.jsonName="[".concat(t,"]"),r=e.util.newFieldList([n]).list()[0]}return r},runtime:e}}(this,e,t,n)}});var We,He;class Ke extends g{constructor(e){super(),this.seconds=R.zero,this.nanos=0,Ve.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(Ve.json.debug(e)));const n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(i<Date.parse("0001-01-01T00:00:00Z")||i>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=R.parse(i/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt("1"+n[7]+"0".repeat(9-n[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 n="Z";if(this.nanos>0){const e=(this.nanos+1e9).toString().substring(1);n="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",n)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return Ke.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new Ke({seconds:R.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new Ke).fromBinary(e,t)}static fromJson(e,t){return(new Ke).fromJson(e,t)}static fromJsonString(e,t){return(new Ke).fromJsonString(e,t)}static equals(e,t){return Ve.util.equals(Ke,e,t)}}Ke.runtime=Ve,Ke.typeName="google.protobuf.Timestamp",Ke.fields=Ve.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const ze=Ve.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ke},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Ge,repeated:!0},{no:5,name:"events",kind:"message",T:Qe,repeated:!0}])),Ge=Ve.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:Je,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),Je=Ve.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ke},{no:3,name:"value",kind:"scalar",T:2}])),Qe=Ve.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:Ke},{no:7,name:"normalized_end_timestamp",kind:"message",T:Ke,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),Ye=Ve.makeEnum("livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"},{no:3,name:"AC_MP3"}]),Xe=Ve.makeEnum("livekit.VideoCodec",[{no:0,name:"DEFAULT_VC"},{no:1,name:"H264_BASELINE"},{no:2,name:"H264_MAIN"},{no:3,name:"H264_HIGH"},{no:4,name:"VP8"}]),Ze=Ve.makeEnum("livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]),$e=Ve.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),et=Ve.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),tt=Ve.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"}]),nt=Ve.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),it=Ve.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),rt=Ve.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),st=Ve.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"},{no:16,name:"AGENT_ERROR"}]),at=Ve.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"}]),ot=Ve.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),ct=Ve.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"}]),dt=Ve.makeEnum("livekit.PacketTrailerFeature",[{no:0,name:"PTF_USER_TIMESTAMP"},{no:1,name:"PTF_FRAME_ID"},{no:2,name:"PTF_USER_DATA"}]),lt=Ve.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:ut,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:tn}])),ut=Ve.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),ht=Ve.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:Ve.getEnumType(tt),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},{no:13,name:"can_manage_agent_session",kind:"scalar",T:8}])),pt=Ve.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:Ve.getEnumType(mt)},{no:4,name:"tracks",kind:"message",T:yt,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:ht},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:Ve.getEnumType(gt)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:Ve.getEnumType(st)},{no:18,name:"kind_details",kind:"enum",T:Ve.getEnumType(vt),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:bt,repeated:!0},{no:20,name:"client_protocol",kind:"scalar",T:5},{no:21,name:"capabilities",kind:"enum",T:Ve.getEnumType(Xt),repeated:!0}])),mt=Ve.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),gt=Ve.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"},{no:8,name:"BRIDGE"}]),vt=Ve.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"},{no:2,name:"CONNECTOR_WHATSAPP"},{no:3,name:"CONNECTOR_TWILIO"},{no:4,name:"BRIDGE_RTSP"},{no:5,name:"SIMULATION"}]),ft=Ve.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),kt=Ve.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:_t,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:Ve.getEnumType(Mt)},{no:6,name:"sdp_cid",kind:"scalar",T:9}])),yt=Ve.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:Ve.getEnumType(et)},{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:Ve.getEnumType(tt)},{no:10,name:"layers",kind:"message",T:_t,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:kt,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:Ve.getEnumType(ft)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:tn},{no:19,name:"audio_features",kind:"enum",T:Ve.getEnumType(ct),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:Ve.getEnumType($e)},{no:21,name:"packet_trailer_features",kind:"enum",T:Ve.getEnumType(dt),repeated:!0}])),bt=Ve.makeMessageType("livekit.DataTrackInfo",(()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"sid",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"encryption",kind:"enum",T:Ve.getEnumType(ft)},{no:5,name:"frame_encoding",kind:"message",T:Tt,opt:!0},{no:6,name:"schema",kind:"message",T:wt,opt:!0}])),Tt=Ve.makeMessageType("livekit.DataTrackFrameEncoding",(()=>[{no:1,name:"well_known",kind:"enum",T:Ve.getEnumType(St),oneof:"value"},{no:2,name:"custom",kind:"scalar",T:9,oneof:"value"}])),St=Ve.makeEnum("livekit.DataTrackFrameEncoding.WellKnownFrameEncoding",[{no:0,name:"WELL_KNOWN_FRAME_ENCODING_UNSPECIFIED",localName:"UNSPECIFIED"},{no:1,name:"WELL_KNOWN_FRAME_ENCODING_ROS1",localName:"ROS1"},{no:2,name:"WELL_KNOWN_FRAME_ENCODING_CDR",localName:"CDR"},{no:3,name:"WELL_KNOWN_FRAME_ENCODING_PROTOBUF",localName:"PROTOBUF"},{no:4,name:"WELL_KNOWN_FRAME_ENCODING_FLATBUFFER",localName:"FLATBUFFER"},{no:5,name:"WELL_KNOWN_FRAME_ENCODING_CBOR",localName:"CBOR"},{no:6,name:"WELL_KNOWN_FRAME_ENCODING_MSGPACK",localName:"MSGPACK"},{no:7,name:"WELL_KNOWN_FRAME_ENCODING_JSON",localName:"JSON"}]),Et=Ve.makeMessageType("livekit.DataTrackSchemaEncoding",(()=>[{no:1,name:"well_known",kind:"enum",T:Ve.getEnumType(Ct),oneof:"value"},{no:2,name:"custom",kind:"scalar",T:9,oneof:"value"}])),Ct=Ve.makeEnum("livekit.DataTrackSchemaEncoding.WellKnownSchemaEncoding",[{no:0,name:"WELL_KNOWN_SCHEMA_ENCODING_UNSPECIFIED",localName:"UNSPECIFIED"},{no:1,name:"WELL_KNOWN_SCHEMA_ENCODING_PROTOBUF",localName:"PROTOBUF"},{no:2,name:"WELL_KNOWN_SCHEMA_ENCODING_FLATBUFFER",localName:"FLATBUFFER"},{no:3,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS1_MSG",localName:"ROS1_MSG"},{no:4,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS2_MSG",localName:"ROS2_MSG"},{no:5,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS2_IDL",localName:"ROS2_IDL"},{no:6,name:"WELL_KNOWN_SCHEMA_ENCODING_OMG_IDL",localName:"OMG_IDL"},{no:7,name:"WELL_KNOWN_SCHEMA_ENCODING_JSON_SCHEMA",localName:"JSON_SCHEMA"}]),wt=Ve.makeMessageType("livekit.DataTrackSchemaId",(()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"encoding",kind:"message",T:Et}])),Rt=Ve.makeMessageType("livekit.DataTrackSubscriptionOptions",(()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}])),Pt=Ve.makeMessageType("livekit.DataBlobKey",(()=>[{no:1,name:"generic",kind:"scalar",T:9,oneof:"key"},{no:2,name:"schema_id",kind:"message",T:wt,oneof:"key"}])),It=Ve.makeMessageType("livekit.DataBlob",(()=>[{no:1,name:"key",kind:"message",T:Pt},{no:2,name:"contents",kind:"scalar",T:12}])),_t=Ve.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:Ve.getEnumType(nt)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9},{no:8,name:"repair_ssrc",kind:"scalar",T:13}])),Mt=Ve.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"}]),Dt=Ve.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:Ve.getEnumType(Ot)},{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:Ut,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Lt,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:Ft,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Bt,oneof:"value"},{no:8,name:"metrics",kind:"message",T:ze,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:qt,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Vt,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Wt,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Ht,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:on,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:cn,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:dn,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:At,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}])),Ot=Ve.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),At=Ve.makeMessageType("livekit.EncryptedPacket",(()=>[{no:1,name:"encryption_type",kind:"enum",T:Ve.getEnumType(ft)},{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}])),Nt=Ve.makeMessageType("livekit.EncryptedPacketPayload",(()=>[{no:1,name:"user",kind:"message",T:Ut,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:qt,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:Vt,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:Wt,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:Ht,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:on,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:cn,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:dn,oneof:"value"}])),Lt=Ve.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:xt,repeated:!0}])),xt=Ve.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}])),Ut=Ve.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}])),Ft=Ve.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),Bt=Ve.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:jt,repeated:!0}])),jt=Ve.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}])),qt=Ve.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}])),Vt=Ve.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},{no:6,name:"compressed_payload",kind:"scalar",T:12}])),Wt=Ve.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),Ht=Ve.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:Kt,oneof:"value"},{no:4,name:"compressed_payload",kind:"scalar",T:12,oneof:"value"}])),Kt=Ve.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}])),zt=Ve.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),Gt=Ve.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:Ve.getEnumType(Jt)},{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}])),Jt=Ve.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Qt=Ve.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:Ve.getEnumType(Yt)},{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},{no:12,name:"client_protocol",kind:"scalar",T:5},{no:13,name:"capabilities",kind:"enum",T:Ve.getEnumType(Xt),repeated:!0}])),Yt=Ve.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"}]),Xt=Ve.makeEnum("livekit.ClientInfo.Capability",[{no:0,name:"CAP_UNUSED"},{no:1,name:"CAP_PACKET_TRAILER"},{no:2,name:"CAP_COMPRESSION_DEFLATE_RAW"}]),Zt=Ve.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:$t},{no:2,name:"screen",kind:"message",T:$t},{no:3,name:"resume_connection",kind:"enum",T:Ve.getEnumType(rt)},{no:4,name:"disabled_codecs",kind:"message",T:en},{no:5,name:"force_relay",kind:"enum",T:Ve.getEnumType(rt)}])),$t=Ve.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:Ve.getEnumType(rt)}])),en=Ve.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:ut,repeated:!0},{no:2,name:"publish",kind:"message",T:ut,repeated:!0}])),tn=Ve.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),nn=Ve.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),rn=Ve.makeEnum("livekit.DataStream.CompressionType",[{no:0,name:"NONE"},{no:1,name:"DEFLATE_RAW"}]),sn=Ve.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:Ve.getEnumType(nn)},{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"}),an=Ve.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),on=Ve.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:Ve.getEnumType(ft)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:sn,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:an,oneof:"content_header"},{no:11,name:"inline_content",kind:"scalar",T:12,opt:!0},{no:12,name:"compression",kind:"enum",T:Ve.getEnumType(rn)}]),{localName:"DataStream_Header"}),cn=Ve.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"}),dn=Ve.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"}),ln=Ve.makeMessageType("livekit.FilterParams",(()=>[{no:1,name:"include_events",kind:"scalar",T:9,repeated:!0},{no:2,name:"exclude_events",kind:"scalar",T:9,repeated:!0}])),un=Ve.makeMessageType("livekit.WebhookConfig",(()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"signing_key",kind:"scalar",T:9},{no:3,name:"filter_params",kind:"message",T:ln}])),hn=Ve.makeMessageType("livekit.SubscribedAudioCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}])),pn=Ve.makeEnum("livekit.JobRestartPolicy",[{no:0,name:"JRP_ON_FAILURE"},{no:1,name:"JRP_NEVER"}]),mn=Ve.makeMessageType("livekit.RoomAgentDispatch",(()=>[{no:1,name:"agent_name",kind:"scalar",T:9},{no:2,name:"metadata",kind:"scalar",T:9},{no:3,name:"restart_policy",kind:"enum",T:Ve.getEnumType(pn)},{no:4,name:"deployment",kind:"scalar",T:9},{no:5,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}])),gn=Ve.makeEnum("livekit.EncodingOptionsPreset",[{no:0,name:"H264_720P_30"},{no:1,name:"H264_720P_60"},{no:2,name:"H264_1080P_30"},{no:3,name:"H264_1080P_60"},{no:4,name:"PORTRAIT_H264_720P_30"},{no:5,name:"PORTRAIT_H264_720P_60"},{no:6,name:"PORTRAIT_H264_1080P_30"},{no:7,name:"PORTRAIT_H264_1080P_60"}]),vn=Ve.makeEnum("livekit.EncodedFileType",[{no:0,name:"DEFAULT_FILETYPE"},{no:1,name:"MP4"},{no:2,name:"OGG"},{no:3,name:"MP3"}]),fn=Ve.makeEnum("livekit.StreamProtocol",[{no:0,name:"DEFAULT_PROTOCOL"},{no:1,name:"RTMP"},{no:2,name:"SRT"},{no:3,name:"WEBSOCKET"}]),kn=Ve.makeEnum("livekit.SegmentedFileProtocol",[{no:0,name:"DEFAULT_SEGMENTED_FILE_PROTOCOL"},{no:1,name:"HLS_PROTOCOL"}]),yn=Ve.makeEnum("livekit.SegmentedFileSuffix",[{no:0,name:"INDEX"},{no:1,name:"TIMESTAMP"}]),bn=Ve.makeEnum("livekit.ImageFileSuffix",[{no:0,name:"IMAGE_SUFFIX_INDEX"},{no:1,name:"IMAGE_SUFFIX_TIMESTAMP"},{no:2,name:"IMAGE_SUFFIX_NONE_OVERWRITE"}]),Tn=Ve.makeEnum("livekit.AudioMixing",[{no:0,name:"DEFAULT_MIXING"},{no:1,name:"DUAL_CHANNEL_AGENT"},{no:2,name:"DUAL_CHANNEL_ALTERNATE"}]),Sn=Ve.makeMessageType("livekit.EncodingOptions",(()=>[{no:1,name:"width",kind:"scalar",T:5},{no:2,name:"height",kind:"scalar",T:5},{no:3,name:"depth",kind:"scalar",T:5},{no:4,name:"framerate",kind:"scalar",T:5},{no:5,name:"audio_codec",kind:"enum",T:Ve.getEnumType(Ye)},{no:6,name:"audio_bitrate",kind:"scalar",T:5},{no:7,name:"audio_frequency",kind:"scalar",T:5},{no:8,name:"video_codec",kind:"enum",T:Ve.getEnumType(Xe)},{no:9,name:"video_bitrate",kind:"scalar",T:5},{no:10,name:"key_frame_interval",kind:"scalar",T:1},{no:11,name:"audio_quality",kind:"scalar",T:5},{no:12,name:"video_quality",kind:"scalar",T:5}])),En=Ve.makeMessageType("livekit.StreamOutput",(()=>[{no:1,name:"protocol",kind:"enum",T:Ve.getEnumType(fn)},{no:2,name:"urls",kind:"scalar",T:9,repeated:!0}])),Cn=Ve.makeMessageType("livekit.SegmentedFileOutput",(()=>[{no:1,name:"protocol",kind:"enum",T:Ve.getEnumType(kn)},{no:2,name:"filename_prefix",kind:"scalar",T:9},{no:3,name:"playlist_name",kind:"scalar",T:9},{no:11,name:"live_playlist_name",kind:"scalar",T:9},{no:4,name:"segment_duration",kind:"scalar",T:13},{no:10,name:"filename_suffix",kind:"enum",T:Ve.getEnumType(yn)},{no:8,name:"disable_manifest",kind:"scalar",T:8},{no:5,name:"s3",kind:"message",T:Rn,oneof:"output"},{no:6,name:"gcp",kind:"message",T:Pn,oneof:"output"},{no:7,name:"azure",kind:"message",T:In,oneof:"output"},{no:9,name:"aliOSS",kind:"message",T:_n,oneof:"output"}])),wn=Ve.makeMessageType("livekit.ImageOutput",(()=>[{no:1,name:"capture_interval",kind:"scalar",T:13},{no:2,name:"width",kind:"scalar",T:5},{no:3,name:"height",kind:"scalar",T:5},{no:4,name:"filename_prefix",kind:"scalar",T:9},{no:5,name:"filename_suffix",kind:"enum",T:Ve.getEnumType(bn)},{no:6,name:"image_codec",kind:"enum",T:Ve.getEnumType(Ze)},{no:7,name:"disable_manifest",kind:"scalar",T:8},{no:8,name:"s3",kind:"message",T:Rn,oneof:"output"},{no:9,name:"gcp",kind:"message",T:Pn,oneof:"output"},{no:10,name:"azure",kind:"message",T:In,oneof:"output"},{no:11,name:"aliOSS",kind:"message",T:_n,oneof:"output"}])),Rn=Ve.makeMessageType("livekit.S3Upload",(()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:11,name:"session_token",kind:"scalar",T:9},{no:12,name:"assume_role_arn",kind:"scalar",T:9},{no:13,name:"assume_role_external_id",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9},{no:6,name:"force_path_style",kind:"scalar",T:8},{no:7,name:"metadata",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:8,name:"tagging",kind:"scalar",T:9},{no:9,name:"content_disposition",kind:"scalar",T:9},{no:10,name:"proxy",kind:"message",T:Mn}])),Pn=Ve.makeMessageType("livekit.GCPUpload",(()=>[{no:1,name:"credentials",kind:"scalar",T:9},{no:2,name:"bucket",kind:"scalar",T:9},{no:3,name:"proxy",kind:"message",T:Mn}])),In=Ve.makeMessageType("livekit.AzureBlobUpload",(()=>[{no:1,name:"account_name",kind:"scalar",T:9},{no:2,name:"account_key",kind:"scalar",T:9},{no:3,name:"container_name",kind:"scalar",T:9}])),_n=Ve.makeMessageType("livekit.AliOSSUpload",(()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9}])),Mn=Ve.makeMessageType("livekit.ProxyConfig",(()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"password",kind:"scalar",T:9}])),Dn=Ve.makeMessageType("livekit.AutoParticipantEgress",(()=>[{no:1,name:"preset",kind:"enum",T:Ve.getEnumType(gn),oneof:"options"},{no:2,name:"advanced",kind:"message",T:Sn,oneof:"options"},{no:3,name:"file_outputs",kind:"message",T:Nn,repeated:!0},{no:4,name:"segment_outputs",kind:"message",T:Cn,repeated:!0}])),On=Ve.makeMessageType("livekit.AutoTrackEgress",(()=>[{no:1,name:"filepath",kind:"scalar",T:9},{no:5,name:"disable_manifest",kind:"scalar",T:8},{no:2,name:"s3",kind:"message",T:Rn,oneof:"output"},{no:3,name:"gcp",kind:"message",T:Pn,oneof:"output"},{no:4,name:"azure",kind:"message",T:In,oneof:"output"},{no:6,name:"aliOSS",kind:"message",T:_n,oneof:"output"}])),An=Ve.makeMessageType("livekit.RoomCompositeEgressRequest",(()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"layout",kind:"scalar",T:9},{no:3,name:"audio_only",kind:"scalar",T:8},{no:15,name:"audio_mixing",kind:"enum",T:Ve.getEnumType(Tn)},{no:4,name:"video_only",kind:"scalar",T:8},{no:5,name:"custom_base_url",kind:"scalar",T:9},{no:6,name:"file",kind:"message",T:Nn,oneof:"output"},{no:7,name:"stream",kind:"message",T:En,oneof:"output"},{no:10,name:"segments",kind:"message",T:Cn,oneof:"output"},{no:8,name:"preset",kind:"enum",T:Ve.getEnumType(gn),oneof:"options"},{no:9,name:"advanced",kind:"message",T:Sn,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:Nn,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:En,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:Cn,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:wn,repeated:!0},{no:16,name:"webhooks",kind:"message",T:un,repeated:!0}])),Nn=Ve.makeMessageType("livekit.EncodedFileOutput",(()=>[{no:1,name:"file_type",kind:"enum",T:Ve.getEnumType(vn)},{no:2,name:"filepath",kind:"scalar",T:9},{no:6,name:"disable_manifest",kind:"scalar",T:8},{no:3,name:"s3",kind:"message",T:Rn,oneof:"output"},{no:4,name:"gcp",kind:"message",T:Pn,oneof:"output"},{no:5,name:"azure",kind:"message",T:In,oneof:"output"},{no:7,name:"aliOSS",kind:"message",T:_n,oneof:"output"}])),Ln=Ve.makeMessageType("livekit.RoomEgress",(()=>[{no:1,name:"room",kind:"message",T:An},{no:3,name:"participant",kind:"message",T:Dn},{no:2,name:"tracks",kind:"message",T:On}])),xn=Ve.makeMessageType("livekit.RoomConfiguration",(()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"empty_timeout",kind:"scalar",T:13},{no:3,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:11,name:"metadata",kind:"scalar",T:9},{no:5,name:"egress",kind:"message",T:Ln},{no:7,name:"min_playout_delay",kind:"scalar",T:13},{no:8,name:"max_playout_delay",kind:"scalar",T:13},{no:9,name:"sync_streams",kind:"scalar",T:8},{no:10,name:"agents",kind:"message",T:mn,repeated:!0},{no:12,name:"tags",kind:"map",K:9,V:{kind:"scalar",T:9}}])),Un=Ve.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Fn=Ve.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Bn=Ve.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),jn=Ve.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:ni,oneof:"message"},{no:2,name:"answer",kind:"message",T:ni,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Yn,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Wn,oneof:"message"},{no:5,name:"mute",kind:"message",T:Xn,oneof:"message"},{no:6,name:"subscription",kind:"message",T:ri,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:ui,oneof:"message"},{no:8,name:"leave",kind:"message",T:mi,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:vi,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Mi,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Ai,oneof:"message"},{no:13,name:"simulate",kind:"message",T:xi,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:fi,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Ui,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:hi,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:pi,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:Hn,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:zn,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:si,oneof:"message"},{no:22,name:"store_data_blob_request",kind:"message",T:oi,oneof:"message"},{no:23,name:"get_data_blob_request",kind:"message",T:di,oneof:"message"}])),qn=Ve.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:Zn,oneof:"message"},{no:2,name:"answer",kind:"message",T:ni,oneof:"message"},{no:3,name:"offer",kind:"message",T:ni,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Yn,oneof:"message"},{no:5,name:"update",kind:"message",T:ii,oneof:"message"},{no:6,name:"track_published",kind:"message",T:ei,oneof:"message"},{no:8,name:"leave",kind:"message",T:mi,oneof:"message"},{no:9,name:"mute",kind:"message",T:Xn,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:yi,oneof:"message"},{no:11,name:"room_update",kind:"message",T:bi,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Si,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Ci,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Pi,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Di,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:ti,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:$n,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Fi,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:qi,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Vi,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Hi,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:Oi,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:Qi,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:Ii,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:Kn,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:Gn,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:Jn,oneof:"message"},{no:30,name:"store_data_blob_response",kind:"message",T:ci,oneof:"message"},{no:31,name:"get_data_blob_response",kind:"message",T:li,oneof:"message"}])),Vn=Ve.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:_t,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:Ve.getEnumType(Mt)}])),Wn=Ve.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:Ve.getEnumType(et)},{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:Ve.getEnumType(tt)},{no:9,name:"layers",kind:"message",T:_t,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Vn,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:Ve.getEnumType(ft)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:Ve.getEnumType($e)},{no:17,name:"audio_features",kind:"enum",T:Ve.getEnumType(ct),repeated:!0},{no:18,name:"packet_trailer_features",kind:"enum",T:Ve.getEnumType(dt),repeated:!0}])),Hn=Ve.makeMessageType("livekit.PublishDataTrackRequest",(()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"encryption",kind:"enum",T:Ve.getEnumType(ft)},{no:4,name:"frame_encoding",kind:"message",T:Tt,opt:!0},{no:5,name:"schema",kind:"message",T:wt,opt:!0}])),Kn=Ve.makeMessageType("livekit.PublishDataTrackResponse",(()=>[{no:1,name:"info",kind:"message",T:bt}])),zn=Ve.makeMessageType("livekit.UnpublishDataTrackRequest",(()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}])),Gn=Ve.makeMessageType("livekit.UnpublishDataTrackResponse",(()=>[{no:1,name:"info",kind:"message",T:bt}])),Jn=Ve.makeMessageType("livekit.DataTrackSubscriberHandles",(()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:Qn}}])),Qn=Ve.makeMessageType("livekit.DataTrackSubscriberHandles.PublishedDataTrack",(()=>[{no:1,name:"publisher_identity",kind:"scalar",T:9},{no:2,name:"publisher_sid",kind:"scalar",T:9},{no:3,name:"track_sid",kind:"scalar",T:9}]),{localName:"DataTrackSubscriberHandles_PublishedDataTrack"}),Yn=Ve.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:Ve.getEnumType(Un)},{no:3,name:"final",kind:"scalar",T:8}])),Xn=Ve.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),Zn=Ve.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:lt},{no:2,name:"participant",kind:"message",T:pt},{no:3,name:"other_participants",kind:"message",T:pt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:ki,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:Zt},{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:Gt},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:ut,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),$n=Ve.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:ki,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Zt},{no:3,name:"server_info",kind:"message",T:Gt},{no:4,name:"last_message_seq",kind:"scalar",T:13}])),ei=Ve.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:yt}])),ti=Ve.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),ni=Ve.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}}])),ii=Ve.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:pt,repeated:!0}])),ri=Ve.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:zt,repeated:!0}])),si=Ve.makeMessageType("livekit.UpdateDataSubscription",(()=>[{no:1,name:"updates",kind:"message",T:ai,repeated:!0}])),ai=Ve.makeMessageType("livekit.UpdateDataSubscription.Update",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"options",kind:"message",T:Rt}]),{localName:"UpdateDataSubscription_Update"}),oi=Ve.makeMessageType("livekit.StoreDataBlobRequest",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"blob",kind:"message",T:It}])),ci=Ve.makeMessageType("livekit.StoreDataBlobResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"key",kind:"message",T:Pt}])),di=Ve.makeMessageType("livekit.GetDataBlobRequest",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:9},{no:3,name:"key",kind:"message",T:Pt}])),li=Ve.makeMessageType("livekit.GetDataBlobResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"blob",kind:"message",T:It}])),ui=Ve.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:Ve.getEnumType(nt)},{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}])),hi=Ve.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:Ve.getEnumType(ct),repeated:!0}])),pi=Ve.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}])),mi=Ve.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:Ve.getEnumType(st)},{no:3,name:"action",kind:"enum",T:Ve.getEnumType(gi)},{no:4,name:"regions",kind:"message",T:Bi}])),gi=Ve.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),vi=Ve.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:_t,repeated:!0}])),fi=Ve.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}])),ki=Ve.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}])),yi=Ve.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:xt,repeated:!0}])),bi=Ve.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:lt}])),Ti=Ve.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:Ve.getEnumType(it)},{no:3,name:"score",kind:"scalar",T:2}])),Si=Ve.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:Ti,repeated:!0}])),Ei=Ve.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:Ve.getEnumType(Fn)}])),Ci=Ve.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:Ei,repeated:!0}])),wi=Ve.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:Ve.getEnumType(nt)},{no:2,name:"enabled",kind:"scalar",T:8}])),Ri=Ve.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:wi,repeated:!0}])),Pi=Ve.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:wi,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Ri,repeated:!0}])),Ii=Ve.makeMessageType("livekit.SubscribedAudioCodecUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:hn,repeated:!0}])),_i=Ve.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}])),Mi=Ve.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:_i,repeated:!0}])),Di=Ve.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}])),Oi=Ve.makeMessageType("livekit.RoomMovedResponse",(()=>[{no:1,name:"room",kind:"message",T:lt},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:pt},{no:4,name:"other_participants",kind:"message",T:pt,repeated:!0}])),Ai=Ve.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:ni},{no:2,name:"subscription",kind:"message",T:ri},{no:3,name:"publish_tracks",kind:"message",T:ei,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Li,repeated:!0},{no:5,name:"offer",kind:"message",T:ni},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:Ni,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:Kn,repeated:!0}])),Ni=Ve.makeMessageType("livekit.DataChannelReceiveState",(()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}])),Li=Ve.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:Ve.getEnumType(Un)}])),xi=Ve.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:Ve.getEnumType(Bn),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"}])),Ui=Ve.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),Fi=Ve.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),Bi=Ve.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:ji,repeated:!0}])),ji=Ve.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}])),qi=Ve.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:Ve.getEnumType(ot)}])),Vi=Ve.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:Ve.getEnumType(Wi)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:Yn,oneof:"request"},{no:5,name:"add_track",kind:"message",T:Wn,oneof:"request"},{no:6,name:"mute",kind:"message",T:Xn,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:fi,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:hi,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:pi,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:Hn,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:zn,oneof:"request"}])),Wi=Ve.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"},{no:7,name:"INVALID_HANDLE"},{no:8,name:"INVALID_NAME"},{no:9,name:"DUPLICATE_HANDLE"},{no:10,name:"DUPLICATE_NAME"},{no:11,name:"INVALID_REQUEST"}]),Hi=Ve.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),Ki=Ve.makeMessageType("livekit.ConnectionSettings",(()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8},{no:5,name:"auto_subscribe_data_track",kind:"scalar",T:8,opt:!0}])),zi=Ve.makeMessageType("livekit.JoinRequest",(()=>[{no:1,name:"client_info",kind:"message",T:Qt},{no:2,name:"connection_settings",kind:"message",T:Ki},{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:Wn,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:ni},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:Ve.getEnumType(at)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Ai}])),Gi=Ve.makeMessageType("livekit.WrappedJoinRequest",(()=>[{no:1,name:"compression",kind:"enum",T:Ve.getEnumType(Ji)},{no:2,name:"join_request",kind:"scalar",T:12}])),Ji=Ve.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),Qi=Ve.makeMessageType("livekit.MediaSectionsRequirement",(()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}])),Yi=Ve.makeMessageType("livekit.TokenSourceRequest",(()=>[{no:1,name:"room_name",kind:"scalar",T:9,opt:!0},{no:2,name:"participant_name",kind:"scalar",T:9,opt:!0},{no:3,name:"participant_identity",kind:"scalar",T:9,opt:!0},{no:4,name:"participant_metadata",kind:"scalar",T:9,opt:!0},{no:5,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:6,name:"room_config",kind:"message",T:xn,opt:!0}])),Xi=Ve.makeMessageType("livekit.TokenSourceResponse",(()=>[{no:1,name:"server_url",kind:"scalar",T:9},{no:2,name:"participant_token",kind:"scalar",T:9}]));function Zi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var $i,er={exports:{}},tr=er.exports;var nr,ir,rr=($i||($i=1,function(e){var t,i;t=tr,i=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],s={},a=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 c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function d(){for(var n=this.getLevel(),i=0;i<r.length;i++){var s=r[i];this[s]=i<n?e:this.methodFactory(s,n,this.name)}if(this.log=this.debug,typeof console===t&&n<this.levels.SILENT)return"No console available for logging"}function l(e){return function(){typeof console!==t&&(d.call(this),this[e].apply(this,arguments))}}function u(n,r,s){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?c:void 0!==console[n]?o(console,n):void 0!==console.log?o(console,"log"):e)}(n)||l.apply(this,arguments)}function h(e,n){var i,o,c,l=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(s){}if(typeof e===t)try{var n=window.document.cookie,i=encodeURIComponent(h),r=n.indexOf(i+"=");-1!==r&&(e=/^([^;]+)/.exec(n.slice(r+i.length+1))[1])}catch(s){}return void 0===l.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==l.levels[t.toUpperCase()]&&(t=l.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=l.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),l.name=e,l.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},l.methodFactory=n||u,l.getLevel=function(){return null!=c?c:null!=o?o:i},l.setLevel=function(e,n){return c=m(e),!1!==n&&function(e){var n=(r[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=n)}catch(i){}try{window.document.cookie=encodeURIComponent(h)+"="+n+";"}catch(i){}}}(c),d.call(l)},l.setDefaultLevel=function(e){o=m(e),p()||l.setLevel(e,!1)},l.resetLevel=function(){c=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){}}}(),d.call(l)},l.enableAll=function(e){l.setLevel(l.levels.TRACE,e)},l.disableAll=function(e){l.setLevel(l.levels.SILENT,e)},l.rebuild=function(){if(a!==l&&(i=m(a.getLevel())),d.call(l),a===l)for(var e in s)s[e].rebuild()},i=m(a?a.getLevel():"WARN");var g=p();null!=g&&(c=m(g)),d.call(l)}(a=new h).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 h(e,a.methodFactory)),t};var p=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=p),a},a.getLoggers=function(){return s},a.default=a,a},e.exports?e.exports=i():t.log=i()}(er)),er.exports);e.LogLevel=void 0,(nr=e.LogLevel||(e.LogLevel={}))[nr.trace=0]="trace",nr[nr.debug=1]="debug",nr[nr.info=2]="info",nr[nr.warn=3]="warn",nr[nr.error=4]="error",nr[nr.silent=5]="silent",e.LoggerNames=void 0,(ir=e.LoggerNames||(e.LoggerNames={})).Default="livekit",ir.Room="livekit-room",ir.TokenSource="livekit-token-source",ir.Participant="livekit-participant",ir.Track="livekit-track",ir.Publication="livekit-track-publication",ir.Engine="livekit-engine",ir.Signal="livekit-signal",ir.PCManager="livekit-pc-manager",ir.PCTransport="livekit-pc-transport",ir.E2EE="lk-e2ee",ir.DataTracks="livekit-data-tracks",ir.Region="livekit-region",ir.ICE="livekit-ice",ir.Stats="livekit-stats";let sr=rr.getLogger(e.LoggerNames.Default);const ar=Object.values(e.LoggerNames).map((e=>rr.getLogger(e)));function or(e,t){const n=rr.getLogger(e);return n.setDefaultLevel(sr.getLevel()),t?function(e,t){const n=n=>(i,r)=>{const s=t(),a=s||r?Object.assign(Object.assign({},s),r):void 0;e[n](i,a)},i=Object.create(e);return i.trace=n("trace"),i.debug=n("debug"),i.info=n("info"),i.warn=n("warn"),i.error=n("error"),i}(n,t):n}sr.setDefaultLevel(e.LogLevel.info);const cr=rr.getLogger(e.LoggerNames.E2EE),dr=7e3,lr=[0,300,1200,2700,4800,dr,dr,dr,dr,dr];class ur{constructor(e){this._retryDelays=void 0!==e?[...e]:lr}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()}}function hr(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}function pr(e,t,i,r){return new(i||(i=Promise))((function(s,a){function o(e){try{d(r.next(e))}catch(n){a(n)}}function c(e){try{d(r.throw(e))}catch(n){a(n)}}function d(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,c)}d((r=r.apply(e,t||[])).next())}))}function mr(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function gr(e){return this instanceof gr?(this.v=e,this):new gr(e)}function vr(e,t,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,s=i.apply(e,t||[]),a=[];return r=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",(function(e){return function(t){return Promise.resolve(t).then(e,l)}})),r[Symbol.asyncIterator]=function(){return this},r;function o(e,t){s[e]&&(r[e]=function(t){return new Promise((function(n,i){a.push([e,t,n,i])>1||c(e,t)}))},t&&(r[e]=t(r[e])))}function c(e,t){try{(i=s[e](t)).value instanceof gr?Promise.resolve(i.value.v).then(d,l):u(a[0][2],i)}catch(n){u(a[0][3],n)}var i}function d(e){c("next",e)}function l(e){c("throw",e)}function u(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function fr(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=mr(e),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(n){t[n]=e[n]&&function(t){return new Promise((function(i,r){(function(e,t,n,i){Promise.resolve(i).then((function(t){e({value:t,done:n})}),t)})(i,r,(t=e[n](t)).done,t.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var kr,yr={exports:{}};var br=function(){if(kr)return yr.exports;kr=1;var e,t="object"==typeof Reflect?Reflect:null,n=t&&"function"==typeof t.apply?t.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};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 i=Number.isNaN||function(e){return e!=e};function r(){r.init.call(this)}yr.exports=r,yr.exports.once=function(e,t){return new Promise((function(n,i){function r(n){e.removeListener(t,s),i(n)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",r),n([].slice.call(arguments))}m(e,t,s,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&m(e,"error",t,n)}(e,r,{once:!0})}))},r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var s=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function o(e){return void 0===e._maxListeners?r.defaultMaxListeners:e._maxListeners}function c(e,t,n,i){var r,s,c,d;if(a(n),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),c=s[t]),void 0===c)c=s[t]=n,++e._eventsCount;else if("function"==typeof c?c=s[t]=i?[n,c]:[c,n]:i?c.unshift(n):c.push(n),(r=o(e))>0&&c.length>r&&!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,n){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},r=d.bind(i);return r.listener=n,i.wrapFn=r,r}function u(e,t,n){var i=e._events;if(void 0===i)return[];var r=i[t];return void 0===r?[]:"function"==typeof r?n?[r.listener||r]:[r]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(r):p(r,r.length)}function h(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function p(e,t){for(var n=new Array(t),i=0;i<t;++i)n[i]=e[i];return n}function m(e,t,n,i){if("function"==typeof e.on)i.once?e.once(t,n):e.on(t,n);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 r(s){i.once&&e.removeEventListener(t,r),n(s)}))}}return Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return s},set:function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");s=e}}),r.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},r.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||i(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},r.prototype.getMaxListeners=function(){return o(this)},r.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var r="error"===e,s=this._events;if(void 0!==s)r=r&&void 0===s.error;else if(!r)return!1;if(r){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=s[e];if(void 0===c)return!1;if("function"==typeof c)n(c,this,t);else{var d=c.length,l=p(c,d);for(i=0;i<d;++i)n(l[i],this,t)}return!0},r.prototype.addListener=function(e,t){return c(this,e,t,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(e,t){return c(this,e,t,!0)},r.prototype.once=function(e,t){return a(t),this.on(e,l(this,e,t)),this},r.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,l(this,e,t)),this},r.prototype.removeListener=function(e,t){var n,i,r,s,o;if(a(t),void 0===(i=this._events))return this;if(void 0===(n=i[e]))return this;if(n===t||n.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(r=-1,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){o=n[s].listener,r=s;break}if(r<0)return this;0===r?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,r),1===n.length&&(i[e]=n[0]),void 0!==i.removeListener&&this.emit("removeListener",e,o||t)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(e){var t,n,i;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var r,s=Object.keys(n);for(i=0;i<s.length;++i)"removeListener"!==(r=s[i])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},r.prototype.listeners=function(e){return u(this,e,!0)},r.prototype.rawListeners=function(e){return u(this,e,!1)},r.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},r.prototype.listenerCount=h,r.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},yr.exports}();let Tr=!0,Sr=!0;function Er(e,t,n){const i=e.match(t);return i&&i.length>=n&&parseFloat(i[n],10)}function Cr(e,t,n){if(!e.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,"addEventListener").writable)return void Pr("Unable to polyfill events");const i=e.RTCPeerConnection.prototype,r=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return r.apply(this,arguments);const s=e=>{const t=n(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,s),r.apply(this,[e,s])};const s=i.removeEventListener;i.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(n))return s.apply(this,arguments);const i=this._eventMap[t].get(n);return this._eventMap[t].delete(n),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,i])},Object.defineProperty(i,"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 wr(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Tr=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Rr(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Sr=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Pr(){if("object"==typeof window){if(Tr)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Ir(e,t){Sr&&console.warn(e+" is deprecated, please use "+t+" instead.")}function _r(e){return"[object Object]"===Object.prototype.toString.call(e)}function Mr(e){return _r(e)?Object.keys(e).reduce((function(t,n){const i=_r(e[n]),r=i?Mr(e[n]):e[n],s=i&&!Object.keys(r).length;return void 0===r||s?t:Object.assign(t,{[n]:r})}),{}):e}function Dr(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?Dr(e,e.get(t[i]),n):i.endsWith("Ids")&&t[i].forEach((t=>{Dr(e,e.get(t),n)}))})))}function Or(e,t,n){const i=n?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((n=>{n.type===i&&n.trackId===t.id&&Dr(e,n,r)}))})),r}const Ar=Pr;function Nr(e,t){if(t.version>=64)return;const n=e&&e.navigator;if(!n.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((n=>{if("require"===n||"advanced"===n||"mediaSource"===n)return;const i="object"==typeof e[n]?e[n]:{ideal:e[n]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[r("min",n)]=i.ideal,t.optional.push(e),e={},e[r("max",n)]=i.ideal,t.optional.push(e)):(e[r("",n)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",n)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,n)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const a=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!n.mediaDevices.getSupportedConstraints||!n.mediaDevices.getSupportedConstraints().facingMode||a)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return n.mediaDevices.enumerateDevices().then((n=>{let a=(n=n.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!a&&n.length&&t.includes("back")&&(a=n[n.length-1]),a&&(e.video.deviceId=s.exact?{exact:a.deviceId}:{ideal:a.deviceId}),e.video=i(e.video),Ar("chrome: "+JSON.stringify(e)),r(e)}))}e.video=i(e.video)}return Ar("chrome: "+JSON.stringify(e)),r(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(n.getUserMedia=function(e,t,i){r(e,(e=>{n.webkitGetUserMedia(e,t,(e=>{i&&i(s(e))}))}))}.bind(n),n.mediaDevices.getUserMedia){const e=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(t){return r(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(s(e))))))}}}function Lr(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function xr(e,t){if(!(t.version>102))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",(n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===n.track.id)):{track:n.track};const r=new Event("track");r.track=n.track,r.receiver=i,r.transceiver={receiver:i},r.streams=[t.stream],this.dispatchEvent(r)})),t.stream.getTracks().forEach((n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===n.id)):{track:n};const r=new Event("track");r.track=n,r.receiver=i,r.transceiver={receiver:i},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else Cr(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function Ur(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 n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let r=n.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.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 Fr(e,t){if(t.version>=67)return;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 n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Or(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}),Cr(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Or(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,n,i;return this.getSenders().forEach((n=>{n.track===e&&(t?i=!0:t=n)})),this.getReceivers().forEach((t=>(t.track===e&&(n?i=!0:n=t),t.track===e))),i||t&&n?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():n?n.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return n.apply(this,arguments)}}function Br(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,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?-1===this._shimmedLocalStreams[n.id].indexOf(i)&&this._shimmedLocalStreams[n.id].push(i):this._shimmedLocalStreams[n.id]=[n,i],i};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();n.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const n=this._shimmedLocalStreams[t].indexOf(e);-1!==n&&this._shimmedLocalStreams[t].splice(n,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),r.apply(this,arguments)}}function jr(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Br(e);const n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=n.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=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 n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}i.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],r=e._streams[i.id];n=n.replace(new RegExp(r.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:n})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,n){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[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 r=this._streams[n.id];if(r)r.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[n.id]=i,this._reverseStreams[i.id]=n,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?n.apply(this,[t=>{const n=s(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],r=e._streams[i.id];n=n.replace(new RegExp(i.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:n})}(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const o=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=o.get.apply(this);return""===e.type?e:s(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((n=>{this._streams[n].getTracks().find((t=>e.track===t))&&(t=this._streams[n])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function qr(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function Vr(e,t){t.version>102||Cr(e,"negotiationneeded",(e=>{const n=e.target;if(!(t.version<72||n.getConfiguration&&"plan-b"===n.getConfiguration().sdpSemantics)||"stable"===n.signalingState)return e}))}var Wr=Object.freeze({__proto__:null,fixNegotiationNeeded:Vr,shimAddTrackRemoveTrack:jr,shimAddTrackRemoveTrackWithNative:Br,shimGetSendersWithDtmf:Ur,shimGetUserMedia:Nr,shimMediaStream:Lr,shimOnTrack:xr,shimPeerConnection:qr,shimSenderReceiverGetStats:Fr});function Hr(e,t){const n=e&&e.navigator;if(!n.mediaDevices)return;const i=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,i){Ir("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),n.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in n.mediaDevices.getSupportedConstraints())){const e=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},t=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(n){return"object"==typeof n&&"object"==typeof n.audio&&(n=JSON.parse(JSON.stringify(n)),e(n.audio,"autoGainControl","mozAutoGainControl"),e(n.audio,"noiseSuppression","mozNoiseSuppression")),t(n)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const n=t.apply(this,arguments);return e(n,"mozAutoGainControl","autoGainControl"),e(n,"mozNoiseSuppression","noiseSuppression"),n}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(n){return"audio"===this.kind&&"object"==typeof n&&(n=JSON.parse(JSON.stringify(n)),e(n,"autoGainControl","mozAutoGainControl"),e(n,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[n])}}}}function Kr(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 zr(e,t){"object"==typeof e&&(e.RTCPeerConnection||e.mozRTCPeerConnection)&&(!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]})))}function Gr(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;if(t.version>=151)return;const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const e=Array.prototype.slice.call(arguments),s=e[0],a=e[1],o=e[2];return"closed"===this.signalingState?Promise.resolve(new Map):r.apply(this,[s||null]).then((e=>{if(t.version<53&&!a)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(a,o)}}function Jr(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 n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Qr(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}),Cr(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Yr(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Ir("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Xr(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Zr(e,t){if("object"!=typeof e||!e.RTCPeerConnection)return;if(t.version>=110)return;const n=e.RTCPeerConnection.prototype.addTransceiver;n&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const t=e.length>0;t&&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 i=n.apply(this,arguments);if(t){const t=i.sender,n=t.getParameters();(!("encodings"in n)||1===n.encodings.length&&0===Object.keys(n.encodings[0]).length)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function $r(e,t){if("object"!=typeof e||!e.RTCRtpSender)return;if(t.version>=110)return;const n=e.RTCRtpSender.prototype.getParameters;n&&(e.RTCRtpSender.prototype.getParameters=function(){const e=n.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function es(e,t){if("object"!=typeof e||!e.RTCPeerConnection)return;if(t.version>=110)return;const n=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>n.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):n.apply(this,arguments)}}function ts(e,t){if("object"!=typeof e||!e.RTCPeerConnection)return;if(t.version>=110)return;const n=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>n.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):n.apply(this,arguments)}}var ns=Object.freeze({__proto__:null,shimAddTransceiver:Zr,shimCreateAnswer:ts,shimCreateOffer:es,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&(e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!n||!n.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===n.video?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)}))},shimGetParameters:$r,shimGetStats:Gr,shimGetUserMedia:Hr,shimOnTrack:Kr,shimPeerConnection:zr,shimRTCDataChannel:Xr,shimReceiverGetStats:Qr,shimRemoveStream:Yr,shimSenderGetStats:Jr});function is(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((n=>t.call(this,n,e))),e.getVideoTracks().forEach((n=>t.call(this,n,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return i&&i.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 n=e.getTracks();this.getSenders().forEach((e=>{n.includes(e.track)&&this.removeTrack(e)}))})}}function rs(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 n=new Event("addstream");n.stream=t,e.dispatchEvent(n)}))}),t.apply(e,arguments)}}}function ss(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,n=t.createOffer,i=t.createAnswer,r=t.setLocalDescription,s=t.setRemoteDescription,a=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r};let o=function(e,t,n){const i=r.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i};t.setLocalDescription=o,o=function(e,t,n){const i=s.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i},t.setRemoteDescription=o,o=function(e,t,n){const i=a.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i},t.addIceCandidate=o}function as(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,n=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>n(os(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,i){t.mediaDevices.getUserMedia(e).then(n,i)}.bind(t))}function os(e){return e&&void 0!==e.video?Object.assign({},e,{video:Mr(e.video)}):e}function cs(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){const t=[];for(let n=0;n<e.iceServers.length;n++){let i=e.iceServers[n];void 0===i.urls&&i.url?(Ir("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[n])}e.iceServers=t}return new t(e,n)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function ds(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 ls(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 n=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&n?"sendrecv"===n.direction?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":"recvonly"===n.direction&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):!0!==e.offerToReceiveVideo||n||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function us(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var hs,ps=Object.freeze({__proto__:null,shimAudioContext:us,shimCallbacksAPI:ss,shimConstraints:os,shimCreateOfferLegacy:ls,shimGetUserMedia:as,shimLocalStreamsAPI:is,shimRTCIceServerUrls:cs,shimRemoteStreamsAPI:rs,shimTrackEventTransceiver:ds}),ms={exports:{}};var gs=(hs||(hs=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 n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){const n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter((e=>0===e.indexOf(n)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const n={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let i=8;i<t.length;i+=2)switch(t[i]){case"raddr":n.relatedAddress=t[i+1];break;case"rport":n.relatedPort=parseInt(t[i+1],10);break;case"tcptype":n.tcpType=t[i+1];break;case"ufrag":n.ufrag=t[i+1],n.usernameFragment=t[i+1];break;default:void 0===n[t[i]]&&(n[t[i]]=t[i+1])}return n},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const n=e.component;"rtp"===n?t.push(1):"rtcp"===n?t.push(2):t.push(n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const i=e.type;return t.push("typ"),t.push(i),"host"!==i&&e.relatedAddress&&void 0!==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 n={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),n.name=t[0],n.clockRate=parseInt(t[1],10),n.channels=3===t.length?parseInt(t[2],10):1,n.numChannels=n.channels,n},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const n=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==n?"/"+n:"")+"\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 n;const i=e.substring(e.indexOf(" ")+1).split(";");for(let r=0;r<i.length;r++)n=i[r].trim().split("="),t[n[0].trim()]=n[1];return t},t.writeFmtp=function(e){let t="",n=e.payloadType;if(void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const i=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+n+" "+i.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="",n=e.payloadType;return void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+n+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),n={ssrc:parseInt(e.substring(7,t),10)},i=e.indexOf(":",t);return i>-1?(n.attribute=e.substring(t+1,i),n.value=e.substring(i+1)):n.attribute=e.substring(t+1),n},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 n=t.matchPrefix(e,"a=mid:")[0];if(n)return n.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,n){return{role:"auto",fingerprints:t.matchPrefix(e+n,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let n="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{n+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),n},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,n){return t.matchPrefix(e+n,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,n){const i=t.matchPrefix(e+n,"a=ice-ufrag:")[0],r=t.matchPrefix(e+n,"a=ice-pwd:")[0];return i&&r?{usernameFragment:i.substring(12),password:r.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 n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" ");n.profile=i[2];for(let s=3;s<i.length;s++){const r=i[s],a=t.matchPrefix(e,"a=rtpmap:"+r+" ")[0];if(a){const i=t.parseRtpMap(a),s=t.matchPrefix(e,"a=fmtp:"+r+" ");switch(i.parameters=s.length?t.parseFmtp(s[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+r+" ").map(t.parseRtcpFb),n.codecs.push(i),i.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(i.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{n.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return n.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),n},t.writeRtpDescription=function(e,n){let i="";i+="m="+e+" ",i+=n.codecs.length>0?"9":"0",i+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=n.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",n.codecs.forEach((e=>{i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));let r=0;return n.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(i+="a=maxptime:"+r+"\r\n"),n.headerExtensions&&n.headerExtensions.forEach((e=>{i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){const n=[],i=t.parseRtpParameters(e),r=-1!==i.fecMechanisms.indexOf("RED"),s=-1!==i.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),o=a.length>0&&a[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]===o&&(c=d[0][1]),i.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:o,codecPayloadType:parseInt(e.parameters.apt,10)};o&&c&&(t.rtx={ssrc:c}),n.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:o,mechanism:s?"red+ulpfec":"red"},n.push(t))}})),0===n.length&&o&&n.push({ssrc:o});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,n.forEach((e=>{e.maxBitrate=l}))),n},t.parseRtcpParameters=function(e){const n={},i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];i&&(n.cname=i.value,n.ssrc=i.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");n.reducedSize=r.length>0,n.compound=0===r.length;const s=t.matchPrefix(e,"a=rtcp-mux");return n.mux=s.length>0,n},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 n;const i=t.matchPrefix(e,"a=msid:");if(1===i.length)return n=i[0].substring(7).split(" "),{stream:n[0],track:n[1]};const r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(n=r[0].value.split(" "),{stream:n[0],track:n[1]}):void 0},t.parseSctpDescription=function(e){const n=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");let r;i.length>0&&(r=parseInt(i[0].substring(19),10)),isNaN(r)&&(r=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:n.fmt,maxMessageSize:r};const a=t.matchPrefix(e,"a=sctpmap:");if(a.length>0){const e=a[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){let n=[];return n="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&&n.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),n.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,n,i){let r;const s=void 0!==n?n:2;return r=e||t.generateSessionId(),"v=0\r\no="+(i||"thisisadapterortc")+" "+r+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,n){const i=t.splitLines(e);for(let t=0;t<i.length;t++)switch(i[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[t].substring(2)}return n?t.getDirection(n):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const n=t.splitLines(e)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}},t.parseOLine=function(e){const n=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const n=t.splitLines(e);for(let t=0;t<n.length;t++)if(n[t].length<2||"="!==n[t].charAt(1))return!1;return!0},e.exports=t}(ms)),ms.exports),vs=Zi(gs),fs=t({__proto__:null,default:vs},[gs]);function ks(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 n=new t(e),i=vs.parseCandidate(e.candidate);for(const e in i)e in n||Object.defineProperty(n,e,{value:i[e]});return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,Cr(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function ys(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||Cr(e,"icecandidate",(e=>{if(e.candidate){const t=vs.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function bs(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>102)return;if("firefox"===t.browser&&t.version>=113)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){"plan-b"===this.getConfiguration().sdpSemantics&&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=vs.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=vs.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 n=parseInt(t[1],10);return n!=n?-1:n}(arguments[0]),n=function(e){let n=65536;return"firefox"===t.browser&&(n=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),n}(e),i=function(e,n){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const r=vs.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?i=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==n&&(i=2147483637),i}(arguments[0],e);let r;r=0===n&&0===i?Number.POSITIVE_INFINITY:0===n||0===i?Math.max(n,i):Math.min(n,i);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>r}),this._sctp=s}return n.apply(this,arguments)}}function Ts(e,t){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;if("chrome"===t.browser&&t.version>=149)return;if("firefox"===t.browser&&t.version>60)return;function n(e,t){const n=e.send;e.send=function(){const i=arguments[0],r=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return n.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return n(e,this),e},Cr(e,"datachannel",(e=>(n(e.channel,e.target),e)))}function Ss(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 n=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 n=new Event("connectionstatechange",e);t.dispatchEvent(n)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}}))}function Es(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t._safariVersion>=13.1)return;const n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const n=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:n}):t.sdp=n}return n.apply(this,arguments)}}function Cs(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.addIceCandidate;n&&0!==n.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():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function ws(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.setLocalDescription;n&&0!==n.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return n.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return n.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>n.apply(this,[e])))})}var Rs,Ps,Is=Object.freeze({__proto__:null,removeExtmapAllowMixed:Es,shimAddIceCandidateNullOrEmpty:Cs,shimConnectionState:Ss,shimMaxMessageSize:bs,shimParameterlessSetLocalDescription:ws,shimRTCIceCandidate:ks,shimRTCIceCandidateRelayProtocol:ys,shimSendThrowTypeError:Ts});!function(){let e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).window,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=Pr,i=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 n=e.navigator;if(n.userAgentData&&n.userAgentData.brands){const e=n.userAgentData.brands.find((e=>"Chromium"===e.brand));if(e){const t=parseInt(e.version,10);if(t>=90)return{browser:"chrome",version:t}}}if(n.mozGetUserMedia)t.browser="firefox",t.version=parseInt(Er(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(Er(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else{if(!e.RTCPeerConnection||!n.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt(Er(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=Er(n.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),r={browserDetails:i,commonShim:Is,extractVersion:Er,disableLog:wr,disableWarnings:Rr,sdp:fs};switch(i.browser){case"chrome":if(!Wr||!qr||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),r;if(null===i.version)return n("Chrome shim can not determine version, not shimming."),r;n("adapter.js shimming chrome."),r.browserShim=Wr,Cs(e,i),ws(e),Nr(e,i),Lr(e),qr(e,i),xr(e,i),jr(e,i),Ur(e),Fr(e,i),Vr(e,i),ks(e),ys(e),Ss(e),bs(e,i),Ts(e,i),Es(e,i);break;case"firefox":if(!ns||!zr||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=ns,Cs(e,i),ws(e),Hr(e,i),zr(e,i),Gr(e,i),Kr(e),Yr(e),Jr(e),Qr(e),Xr(e),Zr(e,i),$r(e,i),es(e,i),ts(e,i),ks(e),Ss(e),bs(e,i),Ts(e,i);break;case"safari":if(!ps||!t.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=ps,Cs(e,i),ws(e),cs(e),ls(e),ss(e),is(e),rs(e),ds(e),as(e),us(e),ks(e),ys(e),bs(e,i),Ts(e,i),Es(e,i);break;default:n("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});class _s extends(Ps=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}Rs=_s,_s.resolve=e=>Reflect.get(Ps,"resolve",Rs).call(Rs,e);const Ms=/version\/(\d+(\.?_?\d+)+)/i;let Ds;function Os(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;const n=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===Ds||t){const e=As.find((e=>e.test.test(n)));Ds=null==e?void 0:e.describe(n)}return Ds}const As=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:Ns(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Ls(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:Ns(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Ls(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:Ns(Ms,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:Ls(e)})}];function Ns(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const i=t.match(e);return i&&i.length>=n&&i[n]||""}function Ls(e){return e.includes("mac os")?Ns(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}const xs="2.22.1";class Us extends Error{constructor(e,t,n){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,void 0!==(null==n?void 0:n.cause)&&(this.cause=null==n?void 0:n.cause)}}class Fs extends Us{}var Bs,js,qs,Vs,Ws,Hs,Ks;e.ConnectionErrorReason=void 0,(Bs=e.ConnectionErrorReason||(e.ConnectionErrorReason={}))[Bs.NotAllowed=0]="NotAllowed",Bs[Bs.ServerUnreachable=1]="ServerUnreachable",Bs[Bs.InternalError=2]="InternalError",Bs[Bs.Cancelled=3]="Cancelled",Bs[Bs.LeaveRequest=4]="LeaveRequest",Bs[Bs.Timeout=5]="Timeout",Bs[Bs.WebSocket=6]="WebSocket",Bs[Bs.ServiceNotFound=7]="ServiceNotFound";class zs extends Fs{constructor(t,n,i,r){super(1,t),this.name="ConnectionError",this.status=i,this.reason=n,this.context=r,this.reasonName=e.ConnectionErrorReason[n]}static notAllowed(t,n,i){return new zs(t,e.ConnectionErrorReason.NotAllowed,n,i)}static timeout(t){return new zs(t,e.ConnectionErrorReason.Timeout)}static leaveRequest(t,n){return new zs(t,e.ConnectionErrorReason.LeaveRequest,void 0,n)}static internal(t,n){return new zs(t,e.ConnectionErrorReason.InternalError,void 0,n)}static cancelled(t){return new zs(t,e.ConnectionErrorReason.Cancelled)}static serverUnreachable(t,n){return new zs(t,e.ConnectionErrorReason.ServerUnreachable,n)}static websocket(t,n,i){return new zs(t,e.ConnectionErrorReason.WebSocket,n,i)}static serviceNotFound(t,n){return new zs(t,e.ConnectionErrorReason.ServiceNotFound,void 0,n)}}class Gs extends Us{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class Js extends Us{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class Qs extends Us{constructor(e){super(10,e||"unsupported server"),this.name="UnsupportedServer"}}class Ys extends Us{constructor(e){super(12,e||"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Xs extends Us{constructor(e){super(13,e||"unable to negotiate"),this.name="NegotiationError"}}class Zs extends Us{constructor(e){super(14,e||"unable to publish data"),this.name="PublishDataError"}}class $s extends Us{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class ea extends Fs{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName="string"==typeof t?t:Wi[t]}}e.DataStreamErrorReason=void 0,(js=e.DataStreamErrorReason||(e.DataStreamErrorReason={}))[js.AlreadyOpened=0]="AlreadyOpened",js[js.AbnormalEnd=1]="AbnormalEnd",js[js.DecodeFailed=2]="DecodeFailed",js[js.LengthExceeded=3]="LengthExceeded",js[js.Incomplete=4]="Incomplete",js[js.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",js[js.EncryptionTypeMismatch=8]="EncryptionTypeMismatch",js[js.HeaderTooLarge=9]="HeaderTooLarge",js[js.PayloadTooLarge=10]="PayloadTooLarge";class ta extends Fs{constructor(t,n){super(16,t),this.name="DataStreamError",this.reason=n,this.reasonName=e.DataStreamErrorReason[n]}}class na extends Us{constructor(e){super(18,e),this.name="SignalReconnectError"}}e.MediaDeviceFailure=void 0,(qs=e.MediaDeviceFailure||(e.MediaDeviceFailure={})).PermissionDenied="PermissionDenied",qs.NotFound="NotFound",qs.DeviceInUse="DeviceInUse",qs.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}}(e.MediaDeviceFailure||(e.MediaDeviceFailure={}));class ia{}function ra(e){const t={};for(const i of Object.entries(e)){var n=F(i,2);const e=n[0],r=n[1];void 0!==r&&(t[e]=r)}return t}function sa(e,t){return e&&t?"".concat(e,"x").concat(t):void 0}function aa(e){return Math.round(1e4*e)/1e4}function oa(e){const t=e.jitterBufferDelay,n=e.jitterBufferEmittedCount;return void 0!==t&&n?aa(t/n):void 0}function ca(e,t){if(void 0!==e.playoutDelay)return aa(e.playoutDelay);const n=null==t?void 0:t.totalPlayoutDelay,i=null==t?void 0:t.totalSamplesCount;return void 0!==n&&i?aa(n/i):void 0}function da(e){var t,n;const i=new Map,r=[],s=[],a=[];let o;e.forEach((e=>i.set(e.id,e)));const c=e=>{var t;return e.codecId?null===(t=i.get(e.codecId))||void 0===t?void 0:t.mimeType:void 0},d=(e,t)=>e[t]?i.get(e[t]):void 0;e.forEach((e=>{switch(e.type){case"inbound-rtp":{const t=d(e,"playoutId");s.push(ra({kind:e.kind,ssrc:e.ssrc,mid:e.mid,trackId:e.trackIdentifier,codec:c(e),decoder:e.decoderImplementation,resolution:sa(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,bytesReceived:e.bytesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,packetsDiscarded:e.packetsDiscarded,framesReceived:e.framesReceived,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,keyFramesDecoded:e.keyFramesDecoded,freezeCount:e.freezeCount,totalFreezesDuration:e.totalFreezesDuration,pauseCount:e.pauseCount,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,jitter:e.jitter,jitterBuffer:oa(e),playoutDelay:ca(e,t),audioLevel:e.audioLevel,totalSamplesReceived:e.totalSamplesReceived,concealedSamples:e.concealedSamples}));break}case"outbound-rtp":{const t=d(e,"remoteId"),n=d(e,"mediaSourceId");a.push(ra({kind:e.kind,ssrc:e.ssrc,mid:e.mid,rid:e.rid,trackId:null==n?void 0:n.trackIdentifier,active:e.active,codec:c(e),encoder:e.encoderImplementation,resolution:sa(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,captureResolution:sa(null==n?void 0:n.width,null==n?void 0:n.height),captureFps:null==n?void 0:n.framesPerSecond,audioLevel:null==n?void 0:n.audioLevel,targetBitrate:e.targetBitrate,bytesSent:e.bytesSent,packetsSent:e.packetsSent,retransmittedPacketsSent:e.retransmittedPacketsSent,framesEncoded:e.framesEncoded,keyFramesEncoded:e.keyFramesEncoded,limitedBy:"none"===e.qualityLimitationReason?void 0:e.qualityLimitationReason,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,remotePacketsLost:null==t?void 0:t.packetsLost,remoteFractionLost:null==t?void 0:t.fractionLost,remoteJitter:null==t?void 0:t.jitter,remoteRoundTripTime:null==t?void 0:t.roundTripTime}));break}case"transport":o=e;break;case"candidate-pair":r.push(e)}}));const l=null==o?void 0:o.selectedCandidatePairId,u=null!==(n=null!==(t=l?i.get(l):void 0)&&void 0!==t?t:r.find((e=>e.selected)))&&void 0!==n?n:r.find((e=>e.nominated)),h=(null==u?void 0:u.localCandidateId)?i.get(u.localCandidateId):void 0,p=(null==u?void 0:u.remoteCandidateId)?i.get(u.remoteCandidateId):void 0,m=ra({ice:null==o?void 0:o.iceState,dtls:null==o?void 0:o.dtlsState,route:h&&p?"".concat(h.candidateType,"/").concat(h.protocol," -> ").concat(p.candidateType):void 0,network:null==h?void 0:h.networkType,currentRoundTripTime:null==u?void 0:u.currentRoundTripTime,availableOutgoingBitrate:null==u?void 0:u.availableOutgoingBitrate,availableIncomingBitrate:null==u?void 0:u.availableIncomingBitrate,bytesSent:null==u?void 0:u.bytesSent,bytesReceived:null==u?void 0:u.bytesReceived,candidatePairChanges:null==o?void 0:o.selectedCandidatePairChanges});return{connection:Object.keys(m).length>0?m:void 0,outbound:a.length>0?a:void 0,inbound:s.length>0?s:void 0}}ia.setTimeout=function(){return setTimeout(...arguments)},ia.setInterval=function(){return setInterval(...arguments)},ia.clearTimeout=function(){return clearTimeout(...arguments)},ia.clearInterval=function(){return clearInterval(...arguments)},e.RoomEvent=void 0,(Vs=e.RoomEvent||(e.RoomEvent={})).Connected="connected",Vs.Reconnecting="reconnecting",Vs.SignalReconnecting="signalReconnecting",Vs.Reconnected="reconnected",Vs.Disconnected="disconnected",Vs.ConnectionStateChanged="connectionStateChanged",Vs.Moved="moved",Vs.MediaDevicesChanged="mediaDevicesChanged",Vs.ParticipantConnected="participantConnected",Vs.ParticipantDisconnected="participantDisconnected",Vs.TrackPublished="trackPublished",Vs.TrackSubscribed="trackSubscribed",Vs.TrackSubscriptionFailed="trackSubscriptionFailed",Vs.TrackUnpublished="trackUnpublished",Vs.TrackUnsubscribed="trackUnsubscribed",Vs.TrackMuted="trackMuted",Vs.TrackUnmuted="trackUnmuted",Vs.LocalTrackPublished="localTrackPublished",Vs.LocalTrackUnpublished="localTrackUnpublished",Vs.LocalAudioSilenceDetected="localAudioSilenceDetected",Vs.ActiveSpeakersChanged="activeSpeakersChanged",Vs.ParticipantMetadataChanged="participantMetadataChanged",Vs.ParticipantNameChanged="participantNameChanged",Vs.ParticipantAttributesChanged="participantAttributesChanged",Vs.ParticipantActive="participantActive",Vs.RoomMetadataChanged="roomMetadataChanged",Vs.DataReceived="dataReceived",Vs.SipDTMFReceived="sipDTMFReceived",Vs.TranscriptionReceived="transcriptionReceived",Vs.ConnectionQualityChanged="connectionQualityChanged",Vs.TrackStreamStateChanged="trackStreamStateChanged",Vs.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Vs.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Vs.AudioPlaybackStatusChanged="audioPlaybackChanged",Vs.VideoPlaybackStatusChanged="videoPlaybackChanged",Vs.MediaDevicesError="mediaDevicesError",Vs.ParticipantPermissionsChanged="participantPermissionsChanged",Vs.SignalConnected="signalConnected",Vs.RecordingStatusChanged="recordingStatusChanged",Vs.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Vs.EncryptionError="encryptionError",Vs.DCBufferStatusChanged="dcBufferStatusChanged",Vs.ActiveDeviceChanged="activeDeviceChanged",Vs.ChatMessage="chatMessage",Vs.LocalTrackSubscribed="localTrackSubscribed",Vs.MetricsReceived="metricsReceived",Vs.DataTrackPublished="dataTrackPublished",Vs.DataTrackUnpublished="dataTrackUnpublished",Vs.LocalDataTrackPublished="localDataTrackPublished",Vs.LocalDataTrackUnpublished="localDataTrackUnpublished",e.ParticipantEvent=void 0,(Ws=e.ParticipantEvent||(e.ParticipantEvent={})).TrackPublished="trackPublished",Ws.TrackSubscribed="trackSubscribed",Ws.TrackSubscriptionFailed="trackSubscriptionFailed",Ws.TrackUnpublished="trackUnpublished",Ws.TrackUnsubscribed="trackUnsubscribed",Ws.TrackMuted="trackMuted",Ws.TrackUnmuted="trackUnmuted",Ws.LocalTrackPublished="localTrackPublished",Ws.LocalTrackUnpublished="localTrackUnpublished",Ws.LocalTrackCpuConstrained="localTrackCpuConstrained",Ws.LocalSenderCreated="localSenderCreated",Ws.ParticipantMetadataChanged="participantMetadataChanged",Ws.ParticipantNameChanged="participantNameChanged",Ws.DataReceived="dataReceived",Ws.SipDTMFReceived="sipDTMFReceived",Ws.TranscriptionReceived="transcriptionReceived",Ws.IsSpeakingChanged="isSpeakingChanged",Ws.ConnectionQualityChanged="connectionQualityChanged",Ws.TrackStreamStateChanged="trackStreamStateChanged",Ws.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Ws.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Ws.TrackCpuConstrained="trackCpuConstrained",Ws.MediaDevicesError="mediaDevicesError",Ws.AudioStreamAcquired="audioStreamAcquired",Ws.ParticipantPermissionsChanged="participantPermissionsChanged",Ws.PCTrackAdded="pcTrackAdded",Ws.AttributesChanged="attributesChanged",Ws.LocalTrackSubscribed="localTrackSubscribed",Ws.ChatMessage="chatMessage",Ws.Active="active",e.EngineEvent=void 0,(Hs=e.EngineEvent||(e.EngineEvent={})).TransportsCreated="transportsCreated",Hs.Connected="connected",Hs.Disconnected="disconnected",Hs.Resuming="resuming",Hs.Resumed="resumed",Hs.Restarting="restarting",Hs.Restarted="restarted",Hs.SignalResumed="signalResumed",Hs.SignalRestarted="signalRestarted",Hs.Closing="closing",Hs.MediaTrackAdded="mediaTrackAdded",Hs.ActiveSpeakersUpdate="activeSpeakersUpdate",Hs.DataPacketReceived="dataPacketReceived",Hs.RTPVideoMapUpdate="rtpVideoMapUpdate",Hs.DCBufferStatusChanged="dcBufferStatusChanged",Hs.ParticipantUpdate="participantUpdate",Hs.RoomUpdate="roomUpdate",Hs.SpeakersChanged="speakersChanged",Hs.StreamStateChanged="streamStateChanged",Hs.ConnectionQualityUpdate="connectionQualityUpdate",Hs.SubscriptionError="subscriptionError",Hs.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",Hs.RemoteMute="remoteMute",Hs.SubscribedQualityUpdate="subscribedQualityUpdate",Hs.LocalTrackUnpublished="localTrackUnpublished",Hs.LocalTrackSubscribed="localTrackSubscribed",Hs.Offline="offline",Hs.SignalRequestResponse="signalRequestResponse",Hs.SignalConnected="signalConnected",Hs.RoomMoved="roomMoved",Hs.PublishDataTrackResponse="publishDataTrackResponse",Hs.UnPublishDataTrackResponse="unPublishDataTrackResponse",Hs.DataTrackSubscriberHandles="dataTrackSubscriberHandles",Hs.DataTrackPacketReceived="dataTrackPacketReceived",Hs.Joined="joined",Hs.TokenRefreshed="tokenRefreshed",Hs.ServerRegionsReported="serverRegionsReported",e.TrackEvent=void 0,(Ks=e.TrackEvent||(e.TrackEvent={})).Message="message",Ks.Muted="muted",Ks.Unmuted="unmuted",Ks.Restarted="restarted",Ks.Ended="ended",Ks.Subscribed="subscribed",Ks.Unsubscribed="unsubscribed",Ks.CpuConstrained="cpuConstrained",Ks.UpdateSettings="updateSettings",Ks.UpdateSubscription="updateSubscription",Ks.AudioPlaybackStarted="audioPlaybackStarted",Ks.AudioPlaybackFailed="audioPlaybackFailed",Ks.AudioSilenceDetected="audioSilenceDetected",Ks.VisibilityChanged="visibilityChanged",Ks.VideoDimensionsChanged="videoDimensionsChanged",Ks.VideoPlaybackStarted="videoPlaybackStarted",Ks.VideoPlaybackFailed="videoPlaybackFailed",Ks.ElementAttached="elementAttached",Ks.ElementDetached="elementDetached",Ks.UpstreamPaused="upstreamPaused",Ks.UpstreamResumed="upstreamResumed",Ks.SubscriptionPermissionChanged="subscriptionPermissionChanged",Ks.SubscriptionStatusChanged="subscriptionStatusChanged",Ks.SubscriptionFailed="subscriptionFailed",Ks.TrackProcessorUpdate="trackProcessorUpdate",Ks.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",Ks.TranscriptionReceived="transcriptionReceived",Ks.TimeSyncUpdate="timeSyncUpdate",Ks.PreConnectBufferFlushed="preConnectBufferFlushed";class la{constructor(e,t,n,i,r){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===n)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:n,maxFramerate:i,priority:r}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const ua=["opus","red"],ha=["vp8","h264"],pa=["vp8","h264","vp9","av1","h265"];function ma(e){return!!ha.find((t=>t===e))}const ga=ma;var va,fa;e.BackupCodecPolicy=void 0,(va=e.BackupCodecPolicy||(e.BackupCodecPolicy={}))[va.PREFER_REGRESSION=0]="PREFER_REGRESSION",va[va.SIMULCAST=1]="SIMULCAST",va[va.REGRESSION=2]="REGRESSION",e.AudioPresets=void 0,(fa=e.AudioPresets||(e.AudioPresets={})).telephone={maxBitrate:12e3},fa.speech={maxBitrate:24e3},fa.music={maxBitrate:48e3},fa.musicStereo={maxBitrate:64e3},fa.musicHighQuality={maxBitrate:96e3},fa.musicHighQualityStereo={maxBitrate:128e3};const ka={h90:new la(160,90,9e4,20),h180:new la(320,180,16e4,20),h216:new la(384,216,18e4,20),h360:new la(640,360,45e4,20),h540:new la(960,540,8e5,25),h720:new la(1280,720,17e5,30),h1080:new la(1920,1080,3e6,30),h1440:new la(2560,1440,5e6,30),h2160:new la(3840,2160,8e6,30)},ya={h120:new la(160,120,7e4,20),h180:new la(240,180,125e3,20),h240:new la(320,240,14e4,20),h360:new la(480,360,33e4,20),h480:new la(640,480,5e5,20),h540:new la(720,540,6e5,25),h720:new la(960,720,13e5,30),h1080:new la(1440,1080,23e5,30),h1440:new la(1920,1440,38e5,30)},ba={h360fps3:new la(640,360,2e5,3,"medium"),h360fps15:new la(640,360,4e5,15,"medium"),h720fps5:new la(1280,720,8e5,5,"medium"),h720fps15:new la(1280,720,15e5,15,"medium"),h720fps30:new la(1280,720,2e6,30,"medium"),h1080fps15:new la(1920,1080,25e5,15,"medium"),h1080fps30:new la(1920,1080,5e6,30,"medium"),original:new la(0,0,7e6,30,"medium")};function Ta(e,t,n){var i,r,s,a;const o=Oa(null!=e?e:{}),c=o.optionsWithoutProcessor,d=o.audioProcessor,l=o.videoProcessor,u=null==t?void 0:t.processor,h=null==n?void 0:n.processor,p=null!=c?c:{};return!0===p.audio&&(p.audio={}),!0===p.video&&(p.video={}),p.audio&&(Sa(p.audio,t),null!==(i=(s=p.audio).deviceId)&&void 0!==i||(s.deviceId={ideal:"default"}),(d||u)&&(p.audio.processor=null!=d?d:u)),p.video&&(Sa(p.video,n),null!==(r=(a=p.video).deviceId)&&void 0!==r||(a.deviceId={ideal:"default"}),(l||h)&&(p.video.processor=null!=l?l:h)),p}function Sa(e,t){return Object.keys(t).forEach((n=>{void 0===e[n]&&(e[n]=t[n])})),e}function Ea(e){var t,n,i,r;const s={};if(e.video)if("object"==typeof e.video){const n={},r=n,a=e.video;Object.keys(a).forEach((e=>{if("resolution"===e)Sa(r,a.resolution);else r[e]=a[e]})),s.video=n,null!==(t=(i=s.video).deviceId)&&void 0!==t||(i.deviceId={ideal:"default"})}else s.video=!!e.video&&{deviceId:{ideal:"default"}};else s.video=!1;return e.audio?"object"==typeof e.audio?(s.audio=e.audio,null!==(n=(r=s.audio).deviceId)&&void 0!==n||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function Ca(e){return pr(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const n=wa();if(n){const i=n.createAnalyser();i.fftSize=2048;const r=i.frequencyBinCount,s=new Uint8Array(r);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(i),yield qa(t),i.getByteTimeDomainData(s);const a=s.some((e=>128!==e&&0!==e));return n.close(),!a}return!1}()}))}function wa(){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=()=>pr(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 Ra(e){return"audioinput"===e?xa.Source.Microphone:"videoinput"===e?xa.Source.Camera:xa.Source.Unknown}function Pa(e){return e===xa.Source.Microphone?"audioinput":e===xa.Source.Camera?"videoinput":void 0}function Ia(e){var t,n;let i=null===(t=e.video)||void 0===t||t;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(i="boolean"==typeof i?{}:i,i=Za()?Object.assign(Object.assign({},i),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},i),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:null!==(n=e.audio)&&void 0!==n&&n,video:i,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}function _a(e){return e.split("/")[1].toLowerCase()}function Ma(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new ei({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function Da(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?Da(e.track):{})}}function Oa(e){const t=Object.assign({},e);let n,i;return"object"==typeof t.audio&&t.audio.processor&&(n=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),"object"==typeof t.video&&t.video.processor&&(i=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:n,videoProcessor:i,optionsWithoutProcessor:(r=t,void 0===r?r:"function"==typeof structuredClone?"object"==typeof r&&null!==r?structuredClone(Object.assign({},r)):structuredClone(r):JSON.parse(JSON.stringify(r)))};var r}function Aa(e,t){return e.width*e.height<t.width*t.height}const Na=[];var La;e.VideoQuality=void 0,(La=e.VideoQuality||(e.VideoQuality={}))[La.LOW=0]="LOW",La[La.MEDIUM=1]="MEDIUM",La[La.HIGH=2]="HIGH";class xa extends br.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState!==e&&this.log.debug("stream state changed: ".concat(this._streamState," -> ").concat(e)),this._streamState=e}constructor(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=xa.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.finalStatsLogged=!1,this.log=sr,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.loggerContextCb=i.loggerContextCb,this.log=or(null!==(r=i.loggerName)&&void 0!==r?r:e.LoggerNames.Track,(()=>this.logContext)),this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=xa.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),Da(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let n="audio";this.kind===xa.Kind.Video&&(n="video"),0===this.attachedElements.length&&this.kind===xa.Kind.Video&&this.addAppVisibilityListener(),t||("audio"===n&&(Na.forEach((e=>{null!==e.parentElement||t||(t=e)})),t&&Na.splice(Na.indexOf(t),1)),t||(t=document.createElement(n))),this.attachedElements.includes(t)||this.attachedElements.push(t),Ua(this.mediaStreamTrack,t);const i=t.srcObject.getTracks(),r=i.some((e=>"audio"===e.kind));return t.play().then((()=>{this.emit(r?e.TrackEvent.AudioPlaybackStarted:e.TrackEvent.VideoPlaybackStarted)})).catch((n=>{"NotAllowedError"===n.name?this.emit(r?e.TrackEvent.AudioPlaybackFailed:e.TrackEvent.VideoPlaybackFailed,n):"AbortError"===n.name?this.log.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):this.log.warn("could not playback ".concat(r?"audio":"video"),{error:n}),r&&t&&i.some((e=>"video"===e.kind))&&"NotAllowedError"===n.name&&(t.muted=!0,t.play().catch((()=>{})))})),this.emit(e.TrackEvent.ElementAttached,t),t}detach(t){try{if(t){Fa(this.mediaStreamTrack,t);const n=this.attachedElements.indexOf(t);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)),t}const n=[];return this.attachedElements.forEach((t=>{Fa(this.mediaStreamTrack,t),n.push(t),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)})),this.attachedElements=[],n}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.log.debug("stopping track"),this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),void 0!==this.timeSyncHandle&&(cancelAnimationFrame(this.timeSyncHandle),this.timeSyncHandle=void 0),this.logFinalStats()}logFinalStats(){this.finalStatsLogged||(this.finalStatsLogged=!0,this.getRTCStatsReport().then((e=>{e&&this.log.info("final track stats",da(e))})).catch((e=>this.log.debug("could not collect final track stats",{error:e}))))}updateLoggerOptions(e){e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb),e.loggerName&&(this.log=or(e.loggerName,(()=>this.logContext)))}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Na.forEach((e=>{e.parentElement||(t=!1)})),t&&Na.push(e)}}handleAppVisibilityChanged(){return pr(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==xa.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){no()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){no()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Ua(e,t){let n,i;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,i="audio"===e.kind?n.getAudioTracks():n.getVideoTracks(),i.includes(e)||(i.forEach((e=>{n.removeTrack(e)})),n.addTrack(e)),Za()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===n.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(Za()||Ya())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=n,t.play().catch((()=>{}))}),0))}function Fa(e,t){if(t.srcObject instanceof MediaStream){const n=t.srcObject;n.removeTrack(e),n.getTracks().length>0?t.srcObject=n:t.srcObject=null}}!function(e){let t,n,i;!function(e){e.Audio="audio",e.Video="video",e.Unknown="unknown"}(t=e.Kind||(e.Kind={})),function(e){e.Camera="camera",e.Microphone="microphone",e.ScreenShare="screen_share",e.ScreenShareAudio="screen_share_audio",e.Unknown="unknown"}(n=e.Source||(e.Source={})),function(e){e.Active="active",e.Paused="paused",e.Unknown="unknown"}(i=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return et.AUDIO;case t.Video:return et.VIDEO;default:return et.DATA}},e.kindFromProto=function(e){switch(e){case et.AUDIO:return t.Audio;case et.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return tt.CAMERA;case n.Microphone:return tt.MICROPHONE;case n.ScreenShare:return tt.SCREEN_SHARE;case n.ScreenShareAudio:return tt.SCREEN_SHARE_AUDIO;default:return tt.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case tt.CAMERA:return n.Camera;case tt.MICROPHONE:return n.Microphone;case tt.SCREEN_SHARE:return n.ScreenShare;case tt.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case Fn.ACTIVE:return i.Active;case Fn.PAUSED:return i.Paused;default:return i.Unknown}}}(xa||(xa={}));const Ba="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function ja(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}function qa(e){return new _s((t=>ia.setTimeout(t,e)))}function Va(){return"addTransceiver"in RTCPeerConnection.prototype}function Wa(){return"addTrack"in RTCPeerConnection.prototype}function Ha(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Za()||Ya())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const n of e.codecs)if("video/av1"===n.mimeType.toLowerCase()){t=!0;break}return t}function Ka(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Ya())return!1;if(Za()){const e=Os();if((null==e?void 0:e.version)&&lo(e.version,"16")<0)return!1;if("iOS"===(null==e?void 0:e.os)&&(null==e?void 0:e.osVersion)&&lo(e.osVersion,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const n of e.codecs)if("video/vp9"===n.mimeType.toLowerCase()){t=!0;break}return t}function za(e){return"av1"===e||"vp9"===e}function Ga(e){var t;const i=null===(t=e.getHeaderExtensionsToNegotiate)||void 0===t?void 0:t.call(e);if(!i||!e.setHeaderExtensionsToNegotiate)return!1;const r=i.find((e=>e.uri===Ba));if(!r)return!1;if("stopped"!==r.direction)return!0;r.direction="sendrecv";try{return e.setHeaderExtensionsToNegotiate(i),!0}catch(n){return!1}}function Ja(e){return!(!document||$a())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function Qa(){return"undefined"!=typeof RTCPeerConnection&&(Va()||Wa())}function Ya(){var e;return"Firefox"===(null===(e=Os())||void 0===e?void 0:e.name)}function Xa(){return"undefined"!=typeof window&&void 0!==window.RTCRtpScriptTransform&&!function(){const e=Os();return!!e&&"Chrome"===e.name&&"iOS"!==e.os}()}function Za(){var e;return"Safari"===(null===(e=Os())||void 0===e?void 0:e.name)}function $a(){const e=Os();return"Safari"===(null==e?void 0:e.name)||"iOS"===(null==e?void 0:e.os)}function eo(){const e=Os();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)&&lo(e.osVersion,"17")>=0}function to(){var e,t;return!!no()&&(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 no(){return"undefined"!=typeof document}function io(){return"ReactNative"==navigator.product}function ro(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function so(e){return ro(e)?e.hostname.split(".")[0]:null}function ao(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function oo(){if(!io())return;let e=ao();return e?e.platform:void 0}function co(){if(no())return window.devicePixelRatio;if(io()){let e=ao();if(e)return e.devicePixelRatio}return 1}function lo(e,t){const n=e.split("."),i=t.split("."),r=Math.min(n.length,i.length);for(let s=0;s<r;++s){const e=parseInt(n[s],10),t=parseInt(i[s],10);if(e>t)return 1;if(e<t)return-1;if(s===r-1&&e===t)return 0}return""===e&&""!==t?-1:""===t?1:n.length==i.length?0:n.length<i.length?-1:1}function uo(e){for(const t of e)t.target.handleResize(t)}function ho(e){for(const t of e)t.target.handleVisibilityChanged(t)}let po=null;const mo=()=>(po||(po=new ResizeObserver(uo)),po);let go=null;const vo=()=>(go||(go=new IntersectionObserver(ho,{root:null,rootMargin:"0px"})),go);let fo,ko;function yo(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const r=document.createElement("canvas");r.width=e,r.height=t;const s=r.getContext("2d");null==s||s.fillRect(0,0,r.width,r.height),i&&s&&(s.beginPath(),s.arc(e/2,t/2,50,0,2*Math.PI,!0),s.closePath(),s.fillStyle="grey",s.fill());const a=F(r.captureStream().getTracks(),1)[0];if(!a)throw Error("Could not get empty media stream video track");return a.enabled=n,a}function bo(){if(!ko){const t=new AudioContext,n=t.createOscillator(),i=t.createGain();i.gain.setValueAtTime(0,0);const r=t.createMediaStreamDestination();n.connect(i),i.connect(r),n.start();var e=F(r.stream.getAudioTracks(),1);if(ko=e[0],!ko)throw Error("Could not get empty media stream audio track");ko.enabled=!1}return ko.clone()}class To{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise(((t,n)=>pr(this,void 0,void 0,(function*(){this.resolve=t,this.reject=n,e&&(yield e(t,n))})))).finally((()=>{var e;this._isResolved=!0,null===(e=this.onFinally)||void 0===e||e.call(this)}))}}function So(e){return pa.includes(e)}function Eo(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 Co(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function wo(t){switch(t.reason){case e.ConnectionErrorReason.LeaveRequest:return t.context;case e.ConnectionErrorReason.Cancelled:return st.CLIENT_INITIATED;case e.ConnectionErrorReason.NotAllowed:return st.USER_REJECTED;case e.ConnectionErrorReason.ServerUnreachable:return st.JOIN_FAILURE;default:return st.UNKNOWN_REASON}}function Ro(e){return void 0!==e?Number(e):void 0}function Po(e){return void 0!==e?BigInt(e):void 0}function Io(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function _o(e){return!!e&&e.kind==xa.Kind.Audio}function Mo(e){return!!e&&e.kind==xa.Kind.Video}function Do(e){return Io(e)&&Mo(e)}function Oo(e){return Io(e)&&_o(e)}function Ao(e){return!!e&&!e.isLocal}function No(e){return!!e&&!e.isLocal}function Lo(e){return Ao(e)&&Mo(e)}function xo(e){return e.isLocal}function Uo(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}function Fo(){return"undefined"!=typeof CompressionStream}function Bo(e,t){const n=F(ja(t.id),2)[1];return(null==n?void 0:n.startsWith("TR"))?n:e.id.startsWith("TR")?e.id:void 0}function jo(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const i=function(e,t){const n=new URL(function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e));return t.forEach(((e,t)=>{n.searchParams.set(t,e)})),Vo(n,"rtc")}(e,t);return n?i:Vo(i,"v1")}function qo(e){return e.endsWith("/")?e:"".concat(e,"/")}function Vo(e,t){return e.pathname="".concat(qo(e.pathname)).concat(t),e}function Wo(e){if("string"==typeof e)return qn.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return qn.fromBinary(new Uint8Array(e));throw new Error("could not decode websocket message: ".concat(typeof e))}const Ho="AES-GCM",Ko="lk_e2ee",zo={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16,keySize:128};var Go,Jo;function Qo(){return Xo()||Yo()}function Yo(){return"undefined"!=typeof window&&void 0!==window.RTCRtpScriptTransform}function Xo(){return"undefined"!=typeof window&&void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams}function Zo(e){return pr(this,void 0,void 0,(function*(){let t=new TextEncoder;return yield crypto.subtle.importKey("raw",t.encode(e),{name:"PBKDF2"},!1,["deriveBits","deriveKey"])}))}function $o(e){return pr(this,void 0,void 0,(function*(){return yield crypto.subtle.importKey("raw",e,"HKDF",!1,["deriveBits","deriveKey"])}))}function ec(e,t){const n=(new TextEncoder).encode(t);switch(e){case"HKDF":return{name:"HKDF",salt:n,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:n,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(e," is currently unsupported"))}}e.KeyProviderEvent=void 0,(Go=e.KeyProviderEvent||(e.KeyProviderEvent={})).SetKey="setKey",Go.RatchetRequest="ratchetRequest",Go.KeyRatcheted="keyRatcheted",e.KeyHandlerEvent=void 0,(e.KeyHandlerEvent||(e.KeyHandlerEvent={})).KeyRatcheted="keyRatcheted",e.EncryptionEvent=void 0,(Jo=e.EncryptionEvent||(e.EncryptionEvent={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Jo.EncryptionError="encryptionError",e.CryptorEvent=void 0,(e.CryptorEvent||(e.CryptorEvent={})).Error="cryptorError";function tc(e){var t,n,i,r,s;if("sipDtmf"!==(null===(t=e.value)||void 0===t?void 0:t.case)&&"metrics"!==(null===(n=e.value)||void 0===n?void 0:n.case)&&"speaker"!==(null===(i=e.value)||void 0===i?void 0:i.case)&&"transcription"!==(null===(r=e.value)||void 0===r?void 0:r.case)&&"encryptedPacket"!==(null===(s=e.value)||void 0===s?void 0:s.case))return new Nt({value:e.value})}class nc extends br.EventEmitter{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.latestManuallySetKeyIndex=0,this.onKeyRatcheted=(e,t,n)=>{sr.debug("key ratcheted event received",{ratchetResult:e,participantId:t,keyIndex:n})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},zo),t),this.on(e.KeyProviderEvent.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(t,n,i){const r={key:t,participantIdentity:n,keyIndex:i};if(!this.options.sharedKey&&!n)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(null!=n?n:"shared","-").concat(null!=i?i:0),r),void 0!==i&&(this.latestManuallySetKeyIndex=i),this.emit(e.KeyProviderEvent.SetKey,r,void 0!==i)}getKeys(){return Array.from(this.keyInfoMap.values())}getLatestManuallySetKeyIndex(){return this.latestManuallySetKeyIndex}getOptions(){return this.options}ratchetKey(t,n){this.emit(e.KeyProviderEvent.RatchetRequest,t,n)}}var ic;e.CryptorErrorReason=void 0,(ic=e.CryptorErrorReason||(e.CryptorErrorReason={}))[ic.InvalidKey=0]="InvalidKey",ic[ic.MissingKey=1]="MissingKey",ic[ic.InternalError=2]="InternalError";function rc(){return Xa()}function sc(e){return!!(null==e?void 0:e.worker)&&(Xo()||rc())}function ac(e){return!(!(null==e?void 0:e.timestamp)&&!(null==e?void 0:e.frameId))}function oc(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var i,r;let s;const a=null!==(i=n.isImmediate)&&void 0!==i&&i,o=null!==(r=n.callback)&&void 0!==r&&r,c=n.maxWait;let d=Date.now(),l=[];const u=function(){for(var n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];const u=this;return new Promise(((n,r)=>{const h=a&&void 0===s;if(void 0!==s&&ia.clearTimeout(s),s=ia.setTimeout((function(){if(s=void 0,d=Date.now(),!a){const t=e.apply(u,i);o&&o(t),l.forEach((e=>(0,e.resolve)(t))),l=[]}}),function(){if(void 0!==c){const e=Date.now()-d;if(e+t>=c)return c-e}return t}()),h){const t=e.apply(u,i);return o&&o(t),n(t)}l.push({resolve:n,reject:r})}))};return u.cancel=function(e){void 0!==s&&ia.clearTimeout(s),l.forEach((t=>(0,t.reject)(e))),l=[]},u}const cc=2e3;function dc(e,t){if(!t)return 0;let n,i;return"bytesReceived"in e?(n=e.bytesReceived,i=t.bytesReceived):"bytesSent"in e&&(n=e.bytesSent,i=t.bytesSent),void 0===n||void 0===i||void 0===e.timestamp||void 0===t.timestamp?0:8*(n-i)*1e3/(e.timestamp-t.timestamp)}class lc extends xa{constructor(t,n,i,r,s){super(t,i,s),this.timeSyncLoop=()=>{var t;if(0===this.listenerCount(e.TrackEvent.TimeSyncUpdate))return void(this.timeSyncHandle=void 0);this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop);const n=null===(t=this.receiver)||void 0===t?void 0:t.getSynchronizationSources()[0];if(n){const t=n.timestamp,i=n.rtpTimestamp;i&&this.rtpTimestamp!==i&&(this.emit(e.TrackEvent.TimeSyncUpdate,{timestamp:t,rtpTimestamp:i}),this.rtpTimestamp=i)}},this.onTimeSyncListenerAdded=t=>{t===e.TrackEvent.TimeSyncUpdate&&void 0===this.timeSyncHandle&&(this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop))},this.sid=n,this.receiver=r}get isLocal(){return!1}setMuted(t){this.isMuted!==t&&(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.Unmuted,this))}setMediaStream(t){this.mediaStream=t;const n=i=>{i.track===this._mediaStreamTrack&&(t.removeEventListener("removetrack",n),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(e.TrackEvent.Ended,this))};t.addEventListener("removetrack",n)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return pr(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()),cc)),"undefined"!=typeof RTCRtpReceiver&&"function"==typeof RTCRtpReceiver.prototype.getSynchronizationSources&&this.registerTimeSyncUpdate()}stopMonitor(){super.stopMonitor(),this.off("newListener",this.onTimeSyncListenerAdded)}registerTimeSyncUpdate(){this.off("newListener",this.onTimeSyncListenerAdded),this.on("newListener",this.onTimeSyncListenerAdded),void 0===this.timeSyncHandle&&this.timeSyncLoop()}}class uc extends lc{constructor(e,t,n,i,r){super(e,t,xa.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>pr(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=dc(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=oc((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}lookupFrameMetadata(e){let t=e.rtpTimestamp;var n;return null===(n=this.frameMetadataExtractor)||void 0===n?void 0:n.lookupMetadata(t)}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===xa.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?Fa(this._mediaStreamTrack,t):Ua(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 hc(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 n of t)n.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t!==e)),this.updateVisibility(),this.debouncedHandleResize()}detach(e){if(e)return this.stopObservingElement(e),super.detach(e);const t=super.detach();for(const n of t)this.stopObservingElement(n);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return pr(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,n="",i=new Map;return e.forEach((e=>{"inbound-rtp"===e.type?(n=e.codecId,t={type:"video",streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):"codec"===e.type&&i.set(e.id,e)})),t&&""!==n&&i.get(n)&&(t.mimeType=i.get(n).mimeType),t}))}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const n of t)this.stopObservingElementInfo(n)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return pr(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(t){var n,i;const r=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),s=!(null!==(i=null===(n=this.adaptiveStreamSettings)||void 0===n?void 0:n.pauseVideoInBackground)&&void 0!==i&&!i)&&this.isInBackground,a=this.elementInfos.some((e=>e.pictureInPicture)),o=this.elementInfos.some((e=>e.visible))&&!s||a;(this.lastVisible!==o||t)&&(!o&&Date.now()-r<100?ia.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=o,this.emit(e.TrackEvent.VisibilityChanged,o,this)))}updateDimensions(){var t,n;let i=0,r=0;const s=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*s,n=e.height()*s;t+n>i+r&&(i=t,r=n)}(null===(t=this.lastDimensions)||void 0===t?void 0:t.width)===i&&(null===(n=this.lastDimensions)||void 0===n?void 0:n.height)===r||(this.lastDimensions={width:i,height:r},this.emit(e.TrackEvent.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;if("screen"===t)return co();if(!t){return co()>2?2:1}return t}}class hc{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const n=e.target,i=e.isIntersecting;n===this.element&&(this.isIntersecting=i,this.isPiP=pc(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),queueMicrotask((()=>{requestAnimationFrame((()=>{var e;this.isPiP=pc(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)}))}))},this.onLeavePiP=()=>{var e;this.isPiP=pc(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:mc(e),this.isPiP=no()&&pc(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=mc(this.element),this.isPiP=pc(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,vo().observe(this.element),mo().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===(n=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===n||n.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,n,i,r;null===(e=vo())||void 0===e||e.unobserve(this.element),null===(t=mo())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(n=window.documentPictureInPicture)||void 0===n||n.removeEventListener("enter",this.onEnterPiP),null===(r=null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)||void 0===r||r.removeEventListener("pagehide",this.onLeavePiP)}}function pc(e){var t,n;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&mc(e,null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)}function mc(e,t){const n=t||window;let i=e.offsetTop,r=e.offsetLeft;const s=e.offsetWidth,a=e.offsetHeight,o=e.hidden,c=getComputedStyle(e).display;for(;e.offsetParent;)i+=(e=e.offsetParent).offsetTop,r+=e.offsetLeft;return i<n.pageYOffset+n.innerHeight&&r<n.pageXOffset+n.innerWidth&&i+a>n.pageYOffset&&r+s>n.pageXOffset&&!o&&"none"!==c}class gc extends br.EventEmitter{constructor(t,n){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=t=>{var n,i;const r=t.data,s=r.kind,a=r.data;switch(s){case"error":if(sr.error(a.error.message),a.uuid){const e=this.decryptDataRequests.get(a.uuid);if(null==e?void 0:e.reject){e.reject(a.error);break}const t=this.encryptDataRequests.get(a.uuid);if(null==t?void 0:t.reject){t.reject(a.error);break}}this.emit(e.EncryptionEvent.EncryptionError,a.error,a.participantIdentity);break;case"initAck":a.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e,!1)}));break;case"enable":if(a.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e,!1)})),this.encryptionEnabled!==a.enabled&&a.participantIdentity===(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity))this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,a.enabled,this.room.localParticipant),this.encryptionEnabled=a.enabled;else if(a.participantIdentity){const t=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(a.participantIdentity);if(!t)throw TypeError("couldn't set encryption status, participant not found".concat(a.participantIdentity));this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,a.enabled,t)}break;case"ratchetKey":this.keyProvider.emit(e.KeyProviderEvent.KeyRatcheted,a.ratchetResult,a.participantIdentity,a.keyIndex);break;case"decryptDataResponse":const t=this.decryptDataRequests.get(a.uuid);(null==t?void 0:t.resolve)&&t.resolve(a);break;case"encryptDataResponse":const r=this.encryptDataRequests.get(a.uuid);(null==r?void 0:r.resolve)&&r.resolve(a);break;case"packetTrailerMetadata":this.handleFrameMetadata(a.trackId,a.rtpTimestamp,a.ssrc,a.metadata)}},this.onWorkerError=t=>{sr.error("e2ee worker encountered an error:",{error:t.error}),this.emit(e.EncryptionEvent.EncryptionError,t.error,void 0)},this.keyProvider=t.keyProvider,this.worker=t.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=n}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!Qo())throw new Gs("tried to setup end-to-end encryption on an unsupported browser");if(sr.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:cr.getLevel()}};this.worker&&(sr.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){sr.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):sr.warn("ignoring server sent trailer as it's empty")}handleFrameMetadata(e,t,n,i){if(this.room)for(const r of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(const s of r.trackPublications.values())if(s.track&&s.track.mediaStreamID===e&&s.track instanceof uc&&s.track.frameMetadataExtractor)return void s.track.frameMetadataExtractor.storeMetadata(t,n,i)}setupEngine(t){t.on(e.EngineEvent.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(t,n){t.on(e.RoomEvent.TrackPublished,((e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==ft.NONE,t.identity))),t.on(e.RoomEvent.ConnectionStateChanged,(n=>{n===e.ConnectionState.Connected&&t.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==ft.NONE,e.identity)}))}))})).on(e.RoomEvent.TrackUnsubscribed,((e,t,n)=>{var i;const r={kind:"removeTransform",data:{participantIdentity:n.identity,trackId:e.mediaStreamID}};null===(i=this.worker)||void 0===i||i.postMessage(r)})).on(e.RoomEvent.TrackSubscribed,((e,t,n)=>{this.setupE2EEReceiver(e,n.identity,t.trackInfo)})).on(e.RoomEvent.SignalConnected,(()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");const e=n.getLatestManuallySetKeyIndex();n.getKeys().forEach((t=>{var n;this.postKey(t,e===(null!==(n=t.keyIndex)&&void 0!==n?n:0))})),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)})),t.localParticipant.on(e.ParticipantEvent.LocalSenderCreated,((e,t)=>pr(this,void 0,void 0,(function*(){this.setupE2EESender(t,e)})))),t.localParticipant.on(e.ParticipantEvent.LocalTrackPublished,(e=>{if(!Mo(e.track)||!$a())return;const t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:_a(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1}};this.worker.postMessage(t)})),n.on(e.KeyProviderEvent.SetKey,((e,t)=>this.postKey(e,null==t||t))).on(e.KeyProviderEvent.RatchetRequest,((e,t)=>this.postRatchetRequest(e,t)))}encryptData(e){return pr(this,void 0,void 0,(function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),n={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},i=new To;return i.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,i),this.worker.postMessage(n),i.promise}))}handleEncryptedData(e,t,n,i){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const r=crypto.randomUUID(),s={kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:n,keyIndex:i}},a=new To;return a.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,a),this.worker.postMessage(s),a.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e,t){let n=e.key,i=e.participantIdentity,r=e.keyIndex;var s;if(!this.worker)throw Error("could not set key, worker is missing");const a={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:n,keyIndex:r,updateCurrentKeyIndex:t}};this.worker.postMessage(a)}postEnable(e,t){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const n={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}}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 n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}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,n){if(!e.receiver)return;if(!(null==n?void 0:n.mimeType)||""===n.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");const i="video"===e.kind&&!!n.packetTrailerFeatures&&n.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?_a(n.mimeType):void 0,i)}setupE2EESender(e,t){var n,i,r;Io(e)&&t?this.handleSender(t,e.mediaStreamID,void 0,Mo(e)?null!==(i=null===(n=e.publishOptions)||void 0===n?void 0:n.frameMetadata)&&void 0!==i?i:null===(r=e.publishOptions)||void 0===r?void 0:r.packetTrailer:void 0):t||sr.warn("early return because sender is not ready")}handleReceiver(e,t,n,i,r){return pr(this,void 0,void 0,(function*(){if(this.worker){if(Xa()){const s={kind:"decode",participantIdentity:n,trackId:t,codec:i,hasPacketTrailer:r};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(Ko in e&&i){const e={kind:"updateCodec",data:{trackId:t,codec:i,participantIdentity:n,hasPacketTrailer:r}};return void this.worker.postMessage(e)}let s=e.writableStream,a=e.readableStream;if(!s||!a){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,a=t.readable}const o={kind:"decode",data:{readableStream:a,writableStream:s,trackId:t,codec:i,participantIdentity:n,isReuse:Ko in e,hasPacketTrailer:r}};this.worker.postMessage(o,[a,s])}e[Ko]=!0}}))}handleSender(e,t,n,i){var r;if(!(Ko in e)&&this.worker){if(!(null===(r=this.room)||void 0===r?void 0:r.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Xa()){sr.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n,hasPacketTrailer:ac(i),packetTrailer:i};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{sr.info("initialize encoded streams");const r=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1,hasPacketTrailer:ac(i),packetTrailer:i}};this.worker.postMessage(s,[r.readable,r.writable])}e[Ko]=!0}}}class vc{constructor(){this.metadataMap=new Map,this.activeSsrc=0}storeMetadata(e,t,n){for(0!==this.activeSsrc&&this.activeSsrc!==t&&this.metadataMap.clear(),this.activeSsrc=t;this.metadataMap.size>=300;){const e=this.metadataMap.keys().next().value;this.metadataMap.delete(e)}this.metadataMap.set(e,n)}lookupMetadata(e){return this.metadataMap.get(e)}dispose(){this.metadataMap.clear(),this.activeSsrc=0}}class fc{constructor(e){this.extractors=new Map,this.workerPipelines=new Map,this.onWorkerMessage=e=>{const t=e.data;if("metadata"===t.kind){const e=this.extractors.get(t.data.trackId);e&&e.storeMetadata(t.data.rtpTimestamp,t.data.ssrc,t.data.metadata)}},this.onWorkerError=e=>{sr.error("frame metadata worker encountered an error:",{error:e.error})},this.worker=null==e?void 0:e.worker}setup(t){t!==this.room&&(this.room=t,this.worker&&(this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage({kind:"init"})),t.on(e.RoomEvent.TrackSubscribed,((e,t,n)=>{"video"===e.kind&&this.setupReceiver(e,t.trackInfo)})).on(e.RoomEvent.TrackUnsubscribed,(e=>{this.teardownTrack(e)})).on(e.RoomEvent.Disconnected,(()=>{this.cleanup()})))}setupReceiver(e,t){var n,i,r;const s=e.receiver;if(!s)return;if(!(!!(null==t?void 0:t.packetTrailerFeatures)&&t.packetTrailerFeatures.length>0))return void((null===(n=this.room)||void 0===n?void 0:n.hasE2EESetup)||this.setupPassthroughReceiver(s,e.mediaStreamID));if(!sc(this.worker?{worker:this.worker}:void 0)&&!(null===(i=this.room)||void 0===i?void 0:i.hasE2EESetup))return void sr.warn("frame metadata transform not supported; skipping extraction");const a=new vc,o=e.mediaStreamID;this.extractors.set(o,a),e.frameMetadataExtractor=a,(null===(r=this.room)||void 0===r?void 0:r.hasE2EESetup)||this.setupWorkerReceiver(s,o,!0)}setupPassthroughReceiver(e,t){rc()?"transform"in e&&(e.transform=null):(this.worker&&sc({worker:this.worker})&&!this.workerPipelines.has(e)||this.worker&&this.workerPipelines.has(e))&&this.setupWorkerReceiver(e,t,!1)}setupWorkerReceiver(e,t){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];const i=this.worker;if(!i)return;if(rc())return void(e.transform=new RTCRtpScriptTransform(i,{kind:"decode",trackId:t}));const r=this.workerPipelines.get(e);if(r){const s={kind:"updateTrackId",data:{oldTrackId:r,newTrackId:t,hasPacketTrailer:n}};return i.postMessage(s),void this.workerPipelines.set(e,t)}if(!("createEncodedStreams"in e))return void sr.warn("createEncodedStreams not supported");let s;try{s=e.createEncodedStreams()}catch(o){return void sr.warn("failed to create encoded streams",{error:o})}const a={kind:"decode",data:{readableStream:s.readable,writableStream:s.writable,trackId:t,hasPacketTrailer:n}};i.postMessage(a,[s.readable,s.writable]),this.workerPipelines.set(e,t)}teardownTrack(e){const t=e.mediaStreamID,n=this.extractors.get(t);n&&(n.dispose(),this.extractors.delete(t)),e instanceof uc&&(e.frameMetadataExtractor=void 0)}cleanup(){var e;for(const t of this.extractors.values())t.dispose();this.extractors.clear(),this.workerPipelines.clear(),null===(e=this.worker)||void 0===e||e.terminate()}}const kc=fc;class yc{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new yc),this._instance}addFailedConnectionAttempt(e){var t;const n=so(new URL(e));if(!n)return;let i=null!==(t=this.failedConnectionAttempts.get(n))&&void 0!==t?t:0;this.failedConnectionAttempts.set(n,i+1),this.backOffPromises.set(n,qa(Math.min(500*Math.pow(2,i),15e3)))}getBackOffPromise(e){const t=new URL(e),n=t&&so(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),n=t&&so(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}yc._instance=null;const bc="default";class Tc{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new Tc),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return pr(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var r;if((null===(r=Tc.userMediaPromiseMap)||void 0===r?void 0:r.size)>0){sr.debug("awaiting getUserMedia promise");try{e?yield Tc.userMediaPromiseMap.get(e):yield Promise.all(Tc.userMediaPromiseMap.values())}catch(n){sr.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&(!Za()||!t.hasDeviceInUse(e))){if(0===s.filter((t=>t.kind===e)).length||s.some((t=>{const n=""===t.label,i=!e||t.kind===e;return n&&i}))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}},n=yield navigator.mediaDevices.getUserMedia(t);s=yield navigator.mediaDevices.enumerateDevices(),n.getTracks().forEach((e=>{e.stop()}))}}return t._previousDevices=s,e&&(s=s.filter((t=>t.kind===e))),s}()}))}normalizeDeviceId(e,t,n){return pr(this,void 0,void 0,(function*(){if(t!==bc)return t;const i=yield this.getDevices(e),r=i.find((e=>e.deviceId===bc));if(!r)return void sr.warn("could not reliably determine default device");const s=i.find((e=>e.deviceId!==bc&&e.groupId===(null!=n?n:r.groupId)));if(s)return null==s?void 0:s.deviceId;sr.warn("could not reliably determine default device")}))}hasDeviceInUse(e){return e?Tc.userMediaPromiseMap.has(e):Tc.userMediaPromiseMap.size>0}}Tc.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Tc.userMediaPromiseMap=new Map;const Sc=65535,Ec=4294967295;class Cc{static u16(e){return new Cc(e,Sc)}static u32(e){return new Cc(e,Ec)}constructor(e,t){if(this.value=e,e<0)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0");if(t>Number.MAX_SAFE_INTEGER)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.");this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new Cc(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.update((t=>t+e))}decrement(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.update((t=>t-e))}getThenIncrement(){const e=this.value;return this.increment(),new Cc(e,this.maxSize)}isBefore(e){const t=this.value>>>0,n=(e.value>>>0)-t>>>0;return 0!==n&&n<this.maxSize+1}}class wc{static fromRtpTicks(e){return new wc(e,9e4)}static rtpRandom(){const e=Math.round(Math.random()*Ec);return wc.fromRtpTicks(e)}constructor(e,t){this.timestamp=Cc.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new wc(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}}class Rc{constructor(e,t,n){this.epoch=t,this.base=n,this.previous=n.clone(),this.rateInHz=e}static startingNow(e,t){return new Rc(t,new Date,e)}static startingAtTime(e,t,n){return new Rc(n,e,t)}static rtpStartingNow(e){return Rc.startingNow(e,9e4)}static rtpStartingAtTime(e,t){return Rc.startingAtTime(e,t,9e4)}now(){return this.at(new Date)}at(e){let t=e.getTime()-this.epoch.getTime(),n=Rc.durationInMsToTicks(t,this.rateInHz),i=this.base.clone();return i.wrappingAdd(n),i.isBefore(this.previous)&&(i=this.previous),this.previous=i.clone(),i.clone()}static durationInMsToTicks(e,t){let n=(1e6*e*t+5e8)/1e9;return Math.round(n)}}function Pc(e){if(e instanceof DataView)return e;if(e instanceof ArrayBuffer)return new DataView(e);if(e instanceof Uint8Array)return new DataView(e.buffer,e.byteOffset,e.byteLength);throw new Error("Error coercing ".concat(e," to DataView - input was not DataView, ArrayBuffer, or Uint8Array."))}var Ic;!function(e){e[e.Reserved=0]="Reserved",e[e.TooLarge=1]="TooLarge"}(Ic||(Ic={}));class _c extends Fs{constructor(e,t){super(19,e),this.name="DataTrackHandleError",this.reason=t,this.reasonName=Ic[t]}isReason(e){return this.reason===e}static tooLarge(){return new _c("Value too large to be a valid track handle",Ic.TooLarge)}static reserved(e){return new _c("0x".concat(e.toString(16)," is a reserved value."),Ic.Reserved)}}const Mc={fromNumber(e){if(0===e)throw _c.reserved(e);if(e>Sc)throw _c.tooLarge();return e}};class Dc{constructor(){this.value=0}get(){return this.value+=1,this.value>Sc?null:this.value}reset(){this.value=0}}const Oc={from:e=>({sid:e.sid,pubHandle:e.pubHandle,name:e.name,usesE2ee:e.encryption!==ft.NONE}),toProtobuf:e=>new bt({sid:e.sid,pubHandle:e.pubHandle,name:e.name,encryption:e.usesE2ee?ft.GCM:ft.NONE})};var Ac;!function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(Ac||(Ac={}));class Nc{constructor(){this.pendingTasks=new Map,this.taskMutex=new r,this.nextTaskIndex=0}run(e){return pr(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Ac.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Ac.RUNNING,yield e()}finally{t.status=Ac.COMPLETED,this.pendingTasks.delete(t.id),n()}}))}flush(){return pr(this,void 0,void 0,(function*(){return this.run((()=>pr(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}const Lc=["client"];var xc=class{constructor(){L(this,"listeners",new Map)}on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),{off:()=>{n.delete(t)}}}emit(e,t){const n=this.listeners.get("*");if(n)for(const r of n)r(e,t);const i=this.listeners.get(e);if(i)for(const r of i)r(t)}clear(){this.listeners.clear()}},Uc=class extends Error{constructor(e,t){super("non-serializable value at ".concat(e," (").concat(t,")")),this.path=e,this.label=t}};const Fc=(e,t,n)=>{if(null===e)return null;switch(typeof e){case"string":case"boolean":return e;case"number":if(!Number.isFinite(e))throw new Uc(t,jc(e));return e;case"object":return Bc(e,t,n);default:throw new Uc(t,typeof e)}},Bc=(e,t,n)=>{var i,r;if(n.has(e))throw new Uc(t,"circular reference");if(Array.isArray(e)){if(e.length!==Object.keys(e).length)throw new Uc(t,"sparse array or array with non-index properties");n.add(e);const i=e.map(((e,i)=>Fc(e,"".concat(t,"[").concat(i,"]"),n)));return n.delete(e),i}const s=Object.getPrototypeOf(e);if(s!==Object.prototype&&null!==s)throw new Uc(t,null!==(i=null===(r=e.constructor)||void 0===r?void 0:r.name)&&void 0!==i?i:"object");n.add(e);const a={};for(const o of Object.keys(e)){const i=Fc(e[o],"".concat(t,".").concat(o),n);Object.defineProperty(a,o,{value:i,enumerable:!0,writable:!0,configurable:!0})}return n.delete(e),a},jc=e=>Number.isNaN(e)?"NaN":e>0?"Infinity":"-Infinity",qc=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new Set;if(null===e||"object"!=typeof e)return e;if(t.has(e))return e;if(Array.isArray(e)){t.add(e);const n=e.map((e=>qc(e,t)));return t.delete(e),n}const n=Object.getPrototypeOf(e);if(n!==Object.prototype&&null!==n)return e;t.add(e);const i={};for(const r of Object.keys(e)){const n=qc(e[r],t);Object.defineProperty(i,r,{value:n,enumerable:!0,writable:!0,configurable:!0})}return t.delete(e),i},Vc=Symbol("machina.type");var Wc=class{constructor(e){L(this,"id",void 0),L(this,"initialState",void 0),L(this,Vc,"BehavioralFsm"),L(this,"states",void 0),L(this,"emitter",new xc),L(this,"clients",new WeakMap),L(this,"knownClients",new Set),L(this,"childSubscriptions",[]),L(this,"disposed",!1),L(this,"transitionDepth",0),this.id=e.id,this.initialState=e.initialState,this.states=e.states,this.wrapChildLinks(),this.setupChildSubscriptions()}handle(e,t){var n;if(this.disposed)return;const i=this.getOrCreateClientMeta(e);for(var r=arguments.length,s=new Array(r>2?r-2:0),a=2;a<r;a++)s[a-2]=arguments[a];i.currentActionArgs=s;const o=null===(n=this.states[i.state])||void 0===n?void 0:n._child;if(o&&o.canHandle(e,t))try{o.handle(e,t,...s)}finally{i.currentActionArgs=void 0}else this.handleLocally(e,t,s,i)}canHandle(e,t){var n,i,r;if(this.disposed)return!1;const s=null!==(n=null===(i=this.clients.get(e))||void 0===i?void 0:i.state)&&void 0!==n?n:this.initialState,a=this.states[s];if(null!==(r=null==a?void 0:a[t])&&void 0!==r?r:null==a?void 0:a["*"])return!0;const o=null==a?void 0:a._child;return!!o&&o.canHandle(e,t)}reset(e){this.disposed||this.transition(e,this.initialState)}currentState(e){var t;return null===(t=this.clients.get(e))||void 0===t?void 0:t.state}transition(e,t){if(this.disposed)return;const n=this.getOrCreateClientMeta(e),i=n.state;if(t!==i)if(Object.hasOwn(this.states,t)){if(this.transitionDepth++,this.transitionDepth>20)throw this.transitionDepth=0,new Error("Max transition depth (".concat(20,') exceeded in FSM "').concat(this.id,'". Likely an infinite _onEnter → transition loop.'));try{const r=this.states[i],s=this.states[t];if(null!=r&&r._onExit&&"function"==typeof r._onExit){const t=this.buildHandlerArgs(e,"",n);r._onExit(t)}n.state=t;const a={fromState:i,toState:t,client:e};let o;if(this.emitter.emit("transitioning",a),null!=s&&s._onEnter&&"function"==typeof s._onEnter){const t=this.buildHandlerArgs(e,"",n);o=s._onEnter(t)}this.emitter.emit("transitioned",a);const c=null==s?void 0:s._child;c&&c.reset(e),this.processQueue(e,n),"string"==typeof o&&n.state===t&&this.transition(e,o)}finally{this.transitionDepth--}}else this.emitter.emit("invalidstate",{stateName:t,client:e})}compositeState(e){var t;const n=this.clients.get(e);if(!n)return"";const i=null===(t=this.states[n.state])||void 0===t?void 0:t._child;if(i){const t=i.compositeState(e);if(t)return"".concat(n.state,".").concat(t)}return n.state}rehydrate(e,t){if(this.disposed)return;if("string"==typeof t)return void this.rehydrateCompositePath(e,t);const n=this.planSnapshotWrites(e,t);for(const i of n)i()}dehydrate(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const n=this.clients.get(e);if(!n)return;const i={state:n.state,deferred:n.deferredQueue.map((e=>this.snapshotDeferredInput(e)))},r=this.collectChildSnapshots(e,n.state,t);return r&&(i.children=r),i}planSnapshotWrites(e,t){if(this.disposed)return[];const n=t.state,i=t.deferred,r=t.children;if(!Object.hasOwn(this.states,n))throw new Error('rehydrate: unknown state "'.concat(n,'" in FSM "').concat(this.id,'". Valid states: ').concat(Object.keys(this.states).join(", ")));const s=[];if(r)for(const c of Object.keys(r)){var a;if(!Object.hasOwn(this.states,c))throw new Error('rehydrate: unknown state "'.concat(c,'" in FSM "').concat(this.id,'" referenced by snapshot.children.'));const t=null===(a=this.states[c])||void 0===a?void 0:a._child;if(!t)throw new Error('rehydrate: state "'.concat(c,'" in FSM "').concat(this.id,'" has no _child, but the snapshot has a children["').concat(c,'"] entry.'));s.push(...t.planRehydrate(e,r[c]))}const o=i.map((e=>function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?U(Object(n),!0).forEach((function(t){L(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):U(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({inputName:e.inputName,args:qc(e.args)},void 0!==e.untilState?{untilState:e.untilState}:{})));return s.push((()=>{this.clients.has(e)||this.knownClients.add(new WeakRef(e)),this.clients.set(e,{state:n,deferredQueue:o})})),s}rehydrateCompositePath(e,t){const n=B(t.split(".")),i=n[0],r=A(n).slice(1);if(!Object.hasOwn(this.states,i))throw new Error('rehydrate: unknown state "'.concat(i,'" in FSM "').concat(this.id,'". Valid states: ').concat(Object.keys(this.states).join(", ")));if(r.length>0){var s;const n=r.join("."),a=null===(s=this.states[i])||void 0===s?void 0:s._child;if(!a)throw new Error('rehydrate: state "'.concat(i,'" in FSM "').concat(this.id,'" has no _child, but composite path "').concat(t,'" requires one.'));a.rehydrate(e,n)}this.clients.has(e)||this.knownClients.add(new WeakRef(e)),this.clients.set(e,{state:i,deferredQueue:[]})}collectChildSnapshots(e,t,n){const i=new Map;for(const a of Object.keys(this.states)){var r;const e=null===(r=this.states[a])||void 0===r?void 0:r._child;if(!e)continue;const t=i.get(e.instance);t?t.stateNames.push(a):i.set(e.instance,{childLink:e,stateNames:[a]})}let s;for(const a of i.values()){const i=a.childLink,r=a.stateNames,o=n&&r.includes(t);if("Fsm"===i.instance[Vc]&&!o)continue;const c=i.dehydrate(e,o);if(c){null!=s||(s={});for(const e of r)s[e]=c}}return s}snapshotDeferredInput(e){let t;try{n=e.args,t=Fc(n,"args",new Set)}catch(r){if(!(r instanceof Uc))throw r;const t=e.untilState?' (until "'.concat(e.untilState,'")'):"";throw new Error('dehydrate: deferred input "'.concat(e.inputName,'"').concat(t,' in FSM "').concat(this.id,'" has a non-serializable value at ').concat(r.path," (").concat(r.label,")"))}var n;const i={inputName:e.inputName,args:t};return void 0!==e.untilState&&(i.untilState=e.untilState),i}on(e,t){return this.disposed?{off(){}}:this.emitter.on(e,t)}emit(e,t){this.disposed||this.emitter.emit(e,t)}dispose(e){this.disposed=!0;for(const n of this.childSubscriptions)n.off();if(null==e||!e.preserveChildren){const e=new Set;for(const n of Object.keys(this.states)){var t;const i=null===(t=this.states[n])||void 0===t?void 0:t._child;i&&!e.has(i.instance)&&(e.add(i.instance),i.dispose())}}this.emitter.clear()}wrapChildLinks(){for(const e of Object.keys(this.states)){const t=this.states[e],n=null==t?void 0:t._child;if(n){if("object"!=typeof n)throw new Error('State "'.concat(e,'"._child: expected an Fsm or BehavioralFsm instance, got ').concat(String(n)));if(!(Vc in n))throw new Error('State "'.concat(e,'"._child: expected an Fsm or BehavioralFsm instance, got a plain object'));t._child=Hc(n)}}}setupChildSubscriptions(){const e=new Set;for(const n of Object.keys(this.states)){var t;const i=null===(t=this.states[n])||void 0===t?void 0:t._child;if(!i||e.has(i.instance))continue;e.add(i.instance);const r=i.onAny(((e,t)=>{if("nohandler"===e){var n;const e=t;if(void 0!==e.client)this.bubbleNohandler(e.client,i,e.inputName,null!==(n=e.args)&&void 0!==n?n:[]);else for(const t of this.knownClients){var r;const n=t.deref();void 0!==n?this.bubbleNohandler(n,i,e.inputName,null!==(r=e.args)&&void 0!==r?r:[]):this.knownClients.delete(t)}return}const s=t;if(s&&"object"==typeof s&&"client"in s)this.isChildActiveForClient(s.client,i)&&this.emitter.emit(e,t);else for(const a of this.knownClients){const n=a.deref();if(n){if(this.isChildActiveForClient(n,i)){this.emitter.emit(e,t);break}}else this.knownClients.delete(a)}}));this.childSubscriptions.push(r)}}bubbleNohandler(e,t,n,i){if(!this.isChildActiveForClient(e,t))return;const r=this.clients.get(e);r.currentActionArgs=i,this.handleLocally(e,n,i,r)}isChildActiveForClient(e,t){var n;const i=this.clients.get(e);return!!i&&(null===(n=this.states[i.state])||void 0===n||null===(n=n._child)||void 0===n?void 0:n.instance)===t.instance}handleLocally(e,t,n,i){var r;const s=this.states[i.state],a=null!==(r=null==s?void 0:s[t])&&void 0!==r?r:null==s?void 0:s["*"];if(!a)return this.emitter.emit("nohandler",{inputName:t,args:n,client:e}),void(i.currentActionArgs=void 0);try{this.emitter.emit("handling",{inputName:t,client:e});const r=this.buildHandlerArgs(e,t,i);let s;"string"==typeof a?s=a:"function"==typeof a&&(s=a(r,...n)),this.emitter.emit("handled",{inputName:t,client:e}),"string"==typeof s&&this.transition(e,s)}finally{i.currentActionArgs=void 0}}getOrCreateClientMeta(e){let t=this.clients.get(e);return t||(t={state:void 0,deferredQueue:[]},this.clients.set(e,t),this.knownClients.add(new WeakRef(e)),this.transition(e,this.initialState),t)}buildHandlerArgs(e,t,n){return{ctx:e,inputName:t,defer:i=>{if(!n.currentActionArgs)return;const r={inputName:t,args:[...n.currentActionArgs],untilState:null==i?void 0:i.until};n.deferredQueue.push(r),this.emitter.emit("deferred",{inputName:t,client:e})},emit:(e,t)=>{this.emitter.emit(e,t)}}}processQueue(e,t){const n=[],i=[];for(const r of t.deferredQueue)void 0===r.untilState||r.untilState===t.state?n.push(r):i.push(r);t.deferredQueue=i;for(const r of n)this.handle(e,r.inputName,...r.args)}};function Hc(e){if(!e||"object"!=typeof e)throw new Error("createChildLink: expected an Fsm or BehavioralFsm instance, got ".concat(String(e)));const t=e[Vc];if("BehavioralFsm"===t)return{instance:e,canHandle:(t,n)=>e.canHandle(t,n),handle(t,n){for(var i=arguments.length,r=new Array(i>2?i-2:0),s=2;s<i;s++)r[s-2]=arguments[s];e.handle(t,n,...r)},reset(t){e.transition(t,e.initialState)},onAny:t=>e.on("*",t),compositeState:t=>e.compositeState(t),rehydrate(t,n){e.rehydrate(t,n)},dehydrate:(t,n)=>e.dehydrate(t,n),planRehydrate:(t,n)=>e.planSnapshotWrites(t,n),dispose(){e.dispose()}};if("Fsm"===t)return{instance:e,canHandle:(t,n)=>e.canHandle(n),handle(t,n){for(var i=arguments.length,r=new Array(i>2?i-2:0),s=2;s<i;s++)r[s-2]=arguments[s];e.handle(n,...r)},reset(t){e.reset()},onAny:t=>e.on("*",t),compositeState:t=>e.compositeState(),rehydrate(e,t){throw new Error("rehydrate: cannot rehydrate an Fsm child. Fsm owns its own context; rehydrate is only valid for BehavioralFsm hierarchies.")},dehydrate(e,t){throw new Error("dehydrate: cannot dehydrate an Fsm child. Fsm owns its own context; dehydrate is only valid for BehavioralFsm hierarchies.")},planRehydrate(e,t){throw new Error("rehydrate: cannot rehydrate an Fsm child. Fsm owns its own context; rehydrate is only valid for BehavioralFsm hierarchies.")},dispose(){e.dispose()}};throw new Error("createChildLink: expected an Fsm or BehavioralFsm instance, got [MACHINA_TYPE] = ".concat(String(null!=t?t:"undefined")))}var Kc=class{constructor(e){var t;L(this,"id",void 0),L(this,"initialState",void 0),L(this,Vc,"Fsm"),L(this,"states",void 0),L(this,"bfsm",void 0),L(this,"context",void 0),L(this,"emitter",new xc),L(this,"disposed",!1),this.id=e.id,this.initialState=e.initialState,this.context=null!==(t=e.context)&&void 0!==t?t:{},this.bfsm=new Wc(e),this.states=e.states,this.bfsm.on("*",((e,t)=>{if(t&&"object"==typeof t&&"client"in t){t.client;const n=function(e,t){if(null==e)return{};var n,i,r=function(e,t){if(null==e)return{};var n={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;n[i]=e[i]}return n}(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(i=0;i<s.length;i++)n=s[i],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}(t,Lc);this.emitter.emit(e,n)}else this.emitter.emit(e,t)})),this.bfsm.transition(this.context,e.initialState)}handle(e){if(!this.disposed){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];this.bfsm.handle(this.context,e,...n)}}canHandle(e){return!this.disposed&&this.bfsm.canHandle(this.context,e)}reset(){this.disposed||this.bfsm.reset(this.context)}currentState(){return this.bfsm.currentState(this.context)}transition(e){this.disposed||this.bfsm.transition(this.context,e)}compositeState(){return this.bfsm.compositeState(this.context)}on(e,t){return this.disposed?{off(){}}:this.emitter.on(e,t)}emit(e,t){this.disposed||this.bfsm.emit(e,t)}dispose(e){this.disposed=!0,this.bfsm.dispose(e),this.emitter.clear()}};function zc(e,t){return t.attemptId===e.attemptId}const Gc=(e,t)=>{if(zc(e.ctx,t))return"connected"},Jc=e=>{let t=e.ctx;return t.attemptId+=1,t.lastError=void 0,"connecting"},Qc=e=>{let t=e.ctx;return t.attemptId+=1,t.lastError=void 0,"reconnecting"},Yc=(e,t)=>(e.ctx.closeReason=t.reason,"disconnecting"),Xc={new:{connect:Jc,close:Yc},connecting:{connectComplete:Gc,connectFailed:(e,t)=>(e.ctx.lastError=t.error,"closed"),close:Yc},connected:{reconnect:Qc,transportFailed:(e,t)=>{let n=e.ctx;if(zc(n,t))return n.lastError=t.reason,"offline"},close:Yc},offline:{connect:Jc,reconnect:Qc,close:Yc},reconnecting:{reconnectComplete:Gc,reconnectFailed:(e,t)=>(e.ctx.lastError=t.error,t.recoverable?"offline":"closed"),close:Yc},disconnecting:{closeComplete:"closed"},closed:{connect:Jc,reconnect:Qc}};function Zc(){return new Kc({id:"signal",initialState:arguments.length>0&&void 0!==arguments[0]?arguments[0]:"new",context:{attemptId:0},states:Xc})}class $c{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n,i;if(null===(n=t.signal)||void 0===n?void 0:n.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const r=new WebSocket(e,null!==(i=t.protocols)&&void 0!==i?i:[]);r.binaryType="arraybuffer",this.ws=r;const s=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.closeCode,n=e.reason;return r.close(t,n)};this.opened=new _s(((e,t)=>{const n=()=>{t(zs.websocket("Encountered websocket error during connection establishment"))};r.onopen=()=>{e({readable:new ReadableStream({start(e){r.onmessage=t=>{let n=t.data;return e.enqueue(n)},r.onerror=t=>e.error(zs.websocket(t instanceof Error?"".concat(t.name,": ").concat(t.message):"Encountered unknown websocket error: ".concat(String(t)))),r.onclose=t=>{t.wasClean?e.close():e.error(zs.websocket("WS closed unexpectedly with code ".concat(t.code)))}},cancel:s}),writable:new WritableStream({write(e){r.send(e)},abort(){r.close()},close:s}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",n)},r.addEventListener("error",n)})),this.closed=new _s(((e,t)=>{const n=()=>pr(this,void 0,void 0,(function*(){const n=new _s((e=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",(t=>{e(t)}),{once:!0})})),i=yield _s.race([qa(250),n]);i?e(i):t(zs.websocket("Encountered unspecified websocket error without a timely close event"))}));r.addEventListener("close",(t=>{let i=t.code,s=t.reason;e({closeCode:i,reason:s}),r.removeEventListener("error",n)})),r.addEventListener("error",n)})),t.signal&&(t.signal.onabort=()=>r.close()),this.close=s}}const ed=["syncState","trickle","offer","answer","simulate","leave"];var td;!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTING=3]="DISCONNECTING",e[e.DISCONNECTED=4]="DISCONNECTED"}(td||(td={}));class nd{get currentState(){return function(e){switch(e){case"connected":return td.CONNECTED;case"connecting":return td.CONNECTING;case"reconnecting":return td.RECONNECTING;case"disconnecting":return td.DISCONNECTING;default:return td.DISCONNECTED}}(this.lifecycleState)}get isDisconnected(){const e=this.currentState;return e===td.DISCONNECTING||e===td.DISCONNECTED}get lifecycleState(){return this.machine.currentState()}get attemptId(){return this.machine.context.attemptId}sendLifecycleInput(e){const t=this.lifecycleState;return this.machine.handle(e.type,e),this.lifecycleState!==t}settleInFlightClose(){return pr(this,void 0,void 0,(function*(){this.log.debug("waiting for an in-flight close to settle before establishing a session"),(yield this.closingLock.lock())()}))}get isEstablishingConnection(){return"connecting"===this.lifecycleState||"reconnecting"===this.lifecycleState}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;this.rtt=0,this.log=sr,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.loggerContextCb=n.loggerContextCb,this.log=or(null!==(i=n.loggerName)&&void 0!==i?i:e.LoggerNames.Signal,(()=>this.logContext)),this.useJSON=t,this.requestQueue=new Nc,this.queuedRequests=[],this.closingLock=new r,this.connectionLock=new r,this.machine=Zc(),this.machine.on("transitioned",(e=>{let t=e.fromState,n=e.toState;this.log.debug("signal lifecycle: ".concat(t," -> ").concat(n))})),this.machine.on("nohandler",(e=>{let t=e.inputName;this.log.debug("ignoring signal lifecycle input ".concat(t," in state ").concat(this.lifecycleState))})),this.machine}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,r){return pr(this,arguments,void 0,(function(e,t,i,r){var s=this;let a=arguments.length>4&&void 0!==arguments[4]&&arguments[4],o=arguments.length>5?arguments[5]:void 0;return function*(){if("disconnecting"===s.lifecycleState&&(yield s.settleInFlightClose()),!s.sendLifecycleInput({type:"connect"}))throw zs.internal("cannot establish a signal session from '".concat(s.lifecycleState,"', close the current one first"));s.options=i;try{return yield s.connect(e,t,i,r,a,o)}catch(n){throw s.sendLifecycleInput({type:"connectFailed",error:n}),n}}()}))}reconnect(t,i,r,s){return pr(this,void 0,void 0,(function*(){if(this.options){if("disconnecting"===this.lifecycleState&&(yield this.settleInFlightClose()),!this.sendLifecycleInput({type:"reconnect"}))throw zs.internal("cannot resume the signal session from '".concat(this.lifecycleState,"'"));this.clearPingInterval();try{return yield this.connect(t,i,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:r,reconnectReason:s}),void 0,this.useV0SignalPath)}catch(n){throw this.sendLifecycleInput({type:"reconnectFailed",error:n,recoverable:(a=n,!(a instanceof zs)||a.reason!==e.ConnectionErrorReason.LeaveRequest&&a.reason!==e.ConnectionErrorReason.NotAllowed)}),n}var a}else this.log.warn("attempted to reconnect without signal options being set, ignoring")}))}connect(e,t,i,r){return pr(this,arguments,void 0,(function(e,t,i,r){var s=this;let a=arguments.length>4&&void 0!==arguments[4]&&arguments[4],o=arguments.length>5?arguments[5]:void 0;return function*(){const c=yield s.connectionLock.lock();s.connectOptions=i,s.useV0SignalPath=a;const d=function(e){var t;const n=new Qt({capabilities:e,sdk:Yt.JS,protocol:17,clientProtocol:2,version:xs});return io()&&(n.os=null!==(t=oo())&&void 0!==t?t:""),n}(i.clientInfoCapabilities),l=a?function(e,t,n){var i;const r=new URLSearchParams;r.set("access_token",e),n.reconnect&&(r.set("reconnect","1"),n.sid&&r.set("sid",n.sid));r.set("auto_subscribe",n.autoSubscribe?"1":"0"),r.set("sdk",io()?"reactnative":"js"),r.set("version",t.version),r.set("protocol",t.protocol.toString()),r.set("client_protocol",t.clientProtocol.toString()),t.deviceModel&&r.set("device_model",t.deviceModel);t.os&&r.set("os",t.os);t.osVersion&&r.set("os_version",t.osVersion);t.browser&&r.set("browser",t.browser);t.browserVersion&&r.set("browser_version",t.browserVersion);n.adaptiveStream&&r.set("adaptive_stream","1");n.reconnectReason&&r.set("reconnect_reason",n.reconnectReason.toString());(null===(i=navigator.connection)||void 0===i?void 0:i.type)&&r.set("network",navigator.connection.type);return r}(t,d,i):yield function(e,t,n,i){return pr(this,void 0,void 0,(function*(){const r=new URLSearchParams;r.set("access_token",e);const s=new zi({clientInfo:t,connectionSettings:new Ki({autoSubscribe:!!n.autoSubscribe,adaptiveStream:!!n.adaptiveStream}),reconnect:!!n.reconnect,participantSid:n.sid?n.sid:void 0,publisherOffer:i});n.reconnectReason&&(s.reconnectReason=n.reconnectReason);const a=s.toBinary();let o,c;if(Fo()){const e=new CompressionStream("gzip"),t=e.writable.getWriter();t.write(new Uint8Array(a)),t.close();const n=[],i=e.readable.getReader();for(;;){const e=yield i.read(),t=e.done,r=e.value;if(t)break;n.push(r)}const r=n.reduce(((e,t)=>e+t.length),0),s=new Uint8Array(r);let d=0;for(const a of n)s.set(a,d),d+=a.length;o=s,c=Ji.GZIP}else o=a,c=Ji.NONE;const d=new Gi({joinRequest:o,compression:c}).toBinary(),l=e=>{const t=Array.from(e,(e=>String.fromCodePoint(e))).join("");return btoa(t)};return r.set("join_request",l(d).replace(/\+/g,"-").replace(/\//g,"_")),r}))}(t,d,i,o),u=jo(e,l,a).toString(),h=(p=u,Vo(new URL(Co(p)),"validate")).toString();var p;return new Promise(((e,t)=>pr(s,void 0,void 0,(function*(){var s,a;try{let o=!1;const c=e=>pr(this,void 0,void 0,(function*(){if(o)return;o=!0;const n=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unknown reason";if(e instanceof Error)return e.message;if(!(e instanceof AbortSignal))return t;const n=e.reason;switch(typeof n){case"string":return n;case"object":return n instanceof Error?n.message:t;default:return"toString"in n?n.toString():t}}(e instanceof Event?e.currentTarget:e,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then((()=>this.close(n))).catch((e=>{this.log.error(e),this.close()})):this.close(),d(),t(e instanceof zs?e:zs.cancelled(n))}));null==r||r.addEventListener("abort",c);const d=()=>{clearTimeout(l),null==r||r.removeEventListener("abort",c)},l=setTimeout((()=>{c(zs.timeout("room connection has timed out (signal)"))}),i.websocketTimeout),p=new URL(u);if(p.searchParams.has("access_token")&&p.searchParams.set("access_token","<redacted>"),this.ws){const e=performance.now();yield this.teardownTransport("replaced by a new connection attempt"),this.log.debug("closed previous ws connection in ".concat(performance.now()-e,"ms"))}const m=this.attemptId;this.log.info("signal connecting to ".concat(p),{reconnect:i.reconnect,reconnectReason:i.reconnectReason}),this.ws=new $c(u);let g=!1;this.ws.opened.catch((()=>{g=!0}));try{this.ws.closed.then((e=>{this.isEstablishingConnection&&!g&&t(zs.internal("Websocket got closed during a (re)connection attempt: ".concat(e.reason))),this.log.debug("websocket closed",{reason:e.reason,code:e.closeCode,attemptId:m,state:this.lifecycleState}),this.handleOnClose(e.reason||(1e3===e.closeCode?"server closed the signal connection":"Unexpected WS error"),m)})).catch((e=>{this.isEstablishingConnection&&!g&&t(zs.internal("Websocket error during a (re)connection attempt: ".concat(e)))}));const r=yield this.ws.opened.catch((e=>pr(this,void 0,void 0,(function*(){if("connected"===this.lifecycleState)this.handleWSError(e),t(e);else{clearTimeout(l);const n=yield this.handleConnectionError(e,h);t(n)}}))));if(clearTimeout(l),!r)return;const o=r.readable.getReader();let c,d;this.streamWriter=r.writable.getWriter();try{c=yield Promise.race([o.read(),new Promise(((e,t)=>{d=setTimeout((()=>{t(zs.timeout("signal connection timed out while waiting for the first message"))}),5e3)}))])}catch(n){return o.releaseLock(),t(n),void this.close()}finally{clearTimeout(d)}if(o.releaseLock(),!c.value)throw zs.internal("no message received as first message");const u=Wo(c.value),p=this.validateFirstMessage(u,null!==(s=i.reconnect)&&void 0!==s&&s);if(!p.isValid)return void t(p.error);"join"===(null===(a=u.message)||void 0===a?void 0:a.case)&&(this.pingTimeoutDuration=u.message.value.pingTimeout,this.pingIntervalDuration=u.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.onJoined&&this.onJoined(u.message.value));const v=p.shouldProcessFirstMessage?u:void 0;this.handleSignalConnected(r,l,m,v),e(p.response)}catch(n){t(n)}finally{d()}}finally{c()}}))))}()}))}startReadingLoop(e,t){return pr(this,void 0,void 0,(function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield qa(this.signalLatency));try{const t=yield e.read(),n=t.done,i=t.value;if(n)break;const r=Wo(i);this.handleSignalResponse(r)}catch(n){this.log.error("error reading from signal stream",{error:n}),yield this.close(!1,"error in reading loop");break}}}))}close(){return pr(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Close method called on signal client";return function*(){const i=t&&e.sendLifecycleInput({type:"close",reason:n}),r=yield e.closingLock.lock();try{yield e.teardownTransport(n)}finally{i&&e.sendLifecycleInput({type:"closeComplete"}),r()}}()}))}teardownTransport(e){return pr(this,void 0,void 0,(function*(){try{if(this.clearPingInterval(),this.ws){this.ws.close({closeCode:1e3,reason:e});const t=this.ws.closed;this.ws=void 0,this.streamWriter=void 0,yield Promise.race([t,qa(250)])}}catch(n){this.log.debug("websocket error while closing",{error:n})}}))}sendOffer(e,t){this.log.debug("sending offer",{offerSdp:e.sdp}),this.sendRequest({case:"offer",value:rd(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",{answerSdp:e.sdp}),this.sendRequest({case:"answer",value:rd(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",{candidate:e}),this.sendRequest({case:"trickle",value:new Yn({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Xn({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return pr(this,arguments,void 0,(function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const r=n.getNextRequestId();return yield n.sendRequest({case:"updateMetadata",value:new fi({requestId:r,metadata:e,name:t,attributes:i})}),r}()}))}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 vi({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Mi({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:R.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Ui({timestamp:R.parse(Date.now()),rtt:R.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new hi({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new mi({reason:st.CLIENT_INITIATED,action:gi.DISCONNECT})})}sendPublishDataTrackRequest(e,t,n){return this.sendRequest({case:"publishDataTrackRequest",value:new Hn({pubHandle:e,name:t,encryption:n?ft.GCM:ft.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:"unpublishDataTrackRequest",value:new zn({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:"updateDataSubscription",value:new si({updates:[new ai({trackSid:e,subscribe:t})]})})}sendRequest(e){return pr(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){const r=!i&&!function(e){const t=ed.indexOf(e.case)>=0;return sr.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e),s="reconnecting"===t.lifecycleState||t.queuedRequests.length>0;if(r&&s)return void t.queuedRequests.push((()=>pr(t,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));i||(yield t.requestQueue.flush()),t.signalLatency&&(yield qa(t.signalLatency));const a="leave"===e.case&&!!t.streamWriter;if(t.isDisconnected&&!a)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));const o=new jn({message:e});try{t.useJSON?yield t.streamWriter.write(o.toJsonString()):yield t.streamWriter.write(o.toBinary().buffer)}catch(n){t.log.error("error sending signal message",{error:n})}}()}))}handleSignalResponse(e){var t,n;const i=e.message;if(null==i)return void this.log.debug("received unsupported message");let r=!1;if("answer"===i.case){const e=id(i.value);this.onAnswer&&this.onAnswer(e,i.value.id,i.value.midToTrackId)}else if("offer"===i.case){const e=id(i.value);this.onOffer&&this.onOffer(e,i.value.id,i.value.midToTrackId)}else if("trickle"===i.case){const e=JSON.parse(i.value.candidateInit);this.onTrickle&&this.onTrickle(e,i.value.target)}else"update"===i.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=i.value.participants)&&void 0!==t?t:[]):"trackPublished"===i.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(i.value):"speakersChanged"===i.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(n=i.value.speakers)&&void 0!==n?n:[]):"leave"===i.case?this.onLeave&&this.onLeave(i.value):"mute"===i.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(i.value.sid,i.value.muted):"roomUpdate"===i.case?this.onRoomUpdate&&i.value.room&&this.onRoomUpdate(i.value.room):"connectionQuality"===i.case?this.onConnectionQuality&&this.onConnectionQuality(i.value):"streamStateUpdate"===i.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(i.value):"subscribedQualityUpdate"===i.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(i.value):"subscriptionPermissionUpdate"===i.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(i.value):"refreshToken"===i.case?this.onTokenRefresh&&this.onTokenRefresh(i.value):"trackUnpublished"===i.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(i.value):"subscriptionResponse"===i.case?this.onSubscriptionError&&this.onSubscriptionError(i.value):"pong"===i.case||("pongResp"===i.case?(this.rtt=Date.now()-Number.parseInt(i.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):"requestResponse"===i.case?this.onRequestResponse&&this.onRequestResponse(i.value):"trackSubscribed"===i.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(i.value.trackSid):"roomMoved"===i.case?(this.onTokenRefresh&&this.onTokenRefresh(i.value.token),this.onRoomMoved&&this.onRoomMoved(i.value)):"mediaSectionsRequirement"===i.case?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(i.value):"publishDataTrackResponse"===i.case?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(i.value):"unpublishDataTrackResponse"===i.case?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(i.value):"dataTrackSubscriberHandles"===i.case?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(i.value):this.log.debug("unsupported message",{msgCase:i.case}));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return pr(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.attemptId;return function*(){const i=t.onClose;t.sendLifecycleInput({type:"transportFailed",attemptId:n,reason:e})?(yield t.teardownTransport(e),t.log.info("websocket connection closed: ".concat(e),{reason:e}),i&&i(e)):t.log.debug("ignoring transport close in state ".concat(t.lifecycleState),{reason:e,attemptId:n,currentAttemptId:t.attemptId})}()}))}handleWSError(e){this.log.error("websocket error",{error:e})}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=ia.setTimeout((()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString())),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set")}clearPingTimeout(){this.pingTimeout&&ia.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval"),this.pingInterval=ia.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set")}clearPingInterval(){this.log.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&ia.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n,i){clearTimeout(t);this.sendLifecycleInput("reconnecting"===this.lifecycleState?{type:"reconnectComplete",attemptId:n}:{type:"connectComplete",attemptId:n})?(this.log.info("signal connected"),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)):this.log.debug("discarding a connection whose attempt no longer owns the session",{attemptId:n,currentAttemptId:this.attemptId,state:this.lifecycleState})}validateFirstMessage(e,t){var n,i,r,s,a;return"join"===(null===(n=e.message)||void 0===n?void 0:n.case)?{isValid:!0,response:e.message.value}:"reconnecting"===this.lifecycleState&&"leave"!==(null===(i=e.message)||void 0===i?void 0:i.case)?"reconnect"===(null===(r=e.message)||void 0===r?void 0:r.case)?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received"),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&"leave"===(null===(s=e.message)||void 0===s?void 0:s.case)?{isValid:!1,error:zs.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:zs.internal("Unexpected first message")}:{isValid:!1,error:zs.internal("did not receive join response, got ".concat(null===(a=e.message)||void 0===a?void 0:a.case," instead"))}}handleConnectionError(e,t){return pr(this,void 0,void 0,(function*(){try{const n=yield fetch(t);switch(n.status){case 404:const e=yield n.text();return e.includes("requested room does not exist")?zs.notAllowed(e,n.status):zs.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const t=yield n.text();return zs.notAllowed(t,n.status)}return e instanceof zs?e:zs.internal("Encountered unknown websocket error during connection: ".concat(e),{status:n.status,statusText:n.statusText})}catch(n){return n instanceof zs?n:zs.serverUnreachable(n instanceof Error?n.message:"server was not reachable")}}))}}function id(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 rd(e,t){return new ni({sdp:e.sdp,type:e.type,id:t})}class sd{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const n=Date.now();n-this._lastCleanup>this.ttl/2&&this.cleanup();const i=n+this.ttl;return this._map.set(e,{value:t,expiresAt:i}),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 n of this._map.entries()){var t=F(n,2);const i=t[0];t[1].expiresAt<e&&this._map.delete(i)}this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const n of this._map.entries()){var t=F(n,2);const i=t[0],r=t[1];r.expiresAt>=Date.now()&&e(r.value,i,this.asValueMap())}}map(e){this.cleanup();const t=[],n=this.asValueMap();for(const r of n.entries()){var i=F(r,2);const s=i[0],a=i[1];t.push(e(a,s,n))}return t}asValueMap(){const e=new Map;for(const n of this._map.entries()){var t=F(n,2);const i=t[0],r=t[1];r.expiresAt>=Date.now()&&e.set(i,r.value)}return e}}var ad,od,cd,dd,ld,ud={},hd={},pd={exports:{}};function md(){if(ad)return pd.exports;ad=1;var e=pd.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")}))})),pd.exports}function gd(){return od||(od=1,function(e){var t=function(e){return String(Number(e))===e?Number(e):e},n=function(e,n,i){var r=e.name&&e.names;e.push&&!n[e.push]?n[e.push]=[]:r&&!n[e.name]&&(n[e.name]={});var s=e.push?{}:r?n[e.name]:n;!function(e,n,i,r){if(r&&!i)n[r]=t(e[1]);else for(var s=0;s<i.length;s+=1)null!=e[s+1]&&(n[i[s]]=t(e[s+1]))}(i.match(e.reg),s,e.names,e.name),e.push&&n[e.push].push(s)},i=md(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),a=s[s.length-1]);for(var o=0;o<(i[t]||[]).length;o+=1){var c=i[t][o];if(c.reg.test(r))return n(c,a,r)}})),t.media=s,t};var s=function(e,n){var i=n.split(/=(.+)/,2);return 2===i.length?e[i[0]]=t(i[1]):1===i.length&&n.length>1&&(e[i[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var n=[],i=e.split(" ").map(t),r=0;r<i.length;r+=3)n.push({component:i[r],ip:i[r+1],port:i[r+2]});return n},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var n,i=!1;return"~"!==e[0]?n=t(e):(n=t(e.substring(1,e.length)),i=!0),{scid:n,paused:i}}))}))}}(hd)),hd}function vd(){if(dd)return cd;dd=1;var e=md(),t=/%[sdv%]/g,n=function(e){var n=1,i=arguments,r=i.length;return e.replace(t,(function(e){if(n>=r)return e;var t=i[n];switch(n+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}}))},i=function(e,t,i){var r=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var s=0;s<t.names.length;s+=1){var a=t.names[s];t.name?r.push(i[t.name][a]):r.push(i[t.names[s]])}else r.push(i[t.name]);return n.apply(null,r)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return cd=function(t,n){n=n||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var a=n.outerOrder||r,o=n.innerOrder||s,c=[];return a.forEach((function(n){e[n].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(i(n,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(i(n,e,t))}))}))})),t.media.forEach((function(t){c.push(i("m",e.m[0],t)),o.forEach((function(n){e[n].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(i(n,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(i(n,e,t))}))}))}))})),c.join("\r\n")+"\r\n"},cd}var fd=function(){if(ld)return ud;ld=1;var e=gd(),t=vd(),n=md();return ud.grammar=n,ud.write=t,ud.parse=e.parse,ud.parseParams=e.parseParams,ud.parseFmtpConfig=e.parseFmtpConfig,ud.parsePayloads=e.parsePayloads,ud.parseRemoteCandidates=e.parseRemoteCandidates,ud.parseImageAttributes=e.parseImageAttributes,ud.parseSimulcastStreamList=e.parseSimulcastStreamList,ud}();const kd="negotiationStarted",yd="negotiationComplete",bd="offerAnswered",Td="rtpVideoPayloadTypes";class Sd extends br.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(t){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var s;super(),this.log=sr,this.iceLog=sr,this.ddExtID=0,this.latestOfferId=0,this.latestAcknowledgedOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=oc((e=>pr(this,void 0,void 0,(function*(){this.emit(kd);try{yield this.createAndSendOffer()}catch(n){if(!e)throw n;e(n)}}))),20),this.close=()=>{this._pc&&(this.log.debug("closing peer connection"),this.pendingInitialOffer=void 0,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.loggerOptions=i,this.log=or(null!==(s=i.loggerName)&&void 0!==s?s:e.LoggerNames.PCTransport,(()=>this.logContext)),this.iceLog=or(e.LoggerNames.ICE,(()=>this.logContext)),this.config=t,this._pc=this.createPC(),this.offerLock=new r}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(this.iceLog.debug("local ICE candidate gathered",{candidate:e.candidate.candidate}),null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;this.iceLog.debug("ICE candidate error",{event:e}),null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;this.iceLog.debug("ICE connection state: ".concat(e.iceConnectionState)),null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;this.log.debug("signaling state: ".concat(e.signalingState)),null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;this.log.debug("connection state: ".concat(e.connectionState)),null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;this.log.debug("data channel opened by peer",{label:e.channel.label,id:e.channel.id}),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 pr(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.iceLog.debug("queuing remote ICE candidate until remote description applied",{pendingCount:this.pendingCandidates.length+1}),this.pendingCandidates.push(e)}))}setRemoteDescription(e,t){return pr(this,void 0,void 0,(function*(){var n,i;if("answer"===e.type&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",{offerId:t,latestOfferId:this.latestOfferId}),!1;let r;if("offer"===e.type){let t=function(e){var t;const n=[],i=[],r=fd.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let s=0;return r.media.forEach((e=>{var t;const r=Id(e.mid);"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec.toLowerCase()&&(s=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===s&&"nack"===e.type)))&&i.push(r),e.fmtp.some((e=>e.payload===s&&(Cd(e.config,"sprop-stereo=1")&&n.push(r),!0))))})),{stereoMids:n,nackMids:i}}(e),n=t.stereoMids,i=t.nackMids;this.remoteStereoMids=n,this.remoteNackMids=i}else if("answer"===e.type){if(this.pendingInitialOffer&&this._pc){const e=this.pendingInitialOffer;this.pendingInitialOffer=void 0;const t=fd.parse(null!==(n=e.sdp)&&void 0!==n?n:"");t.media.forEach((e=>{Pd(e)})),this.log.debug("setting pending initial offer before processing answer"),yield this.setMungedSDP(e,fd.write(t))}const t=fd.parse(null!==(i=e.sdp)&&void 0!==i?i:"");t.media.forEach((e=>{const t=Id(e.mid);"audio"===e.type&&this.trackBitrates.some((n=>{if(!n.transceiver||t!=n.transceiver.mid)return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===n.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;let r=!1;for(const t of e.fmtp)if(t.payload===i){t.config=t.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),n.maxbr>0&&(t.config+=";maxaveragebitrate=".concat(1e3*n.maxbr)),r=!0;break}return r||n.maxbr>0&&e.fmtp.push({payload:i,config:"maxaveragebitrate=".concat(1e3*n.maxbr)}),!0}))}));const s=this.getPlaceholderMids();s.size>0&&Rd(t.media,(e=>s.has(Id(e.mid)))),r=fd.write(t)}if(yield this.setMungedSDP(e,r,!0),this.pendingCandidates.length>0&&this.iceLog.debug("flushing queued ICE candidates",{count:this.pendingCandidates.length}),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,"answer"===e.type&&(this.latestAcknowledgedOfferId=t,this.emit(bd,t)),this.renegotiate)this.renegotiate=!1,yield this.createAndSendOffer();else if("answer"===e.type&&(this.emit(yd),e.sdp)){fd.parse(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(Td,e.rtp)}))}return!0}))}createInitialOffer(){return pr(this,void 0,void 0,(function*(){var e;const t=yield this.offerLock.lock();try{if("stable"!==this.pc.signalingState)return void this.log.warn("signaling state is not stable, cannot create initial offer");const t=this.latestOfferId+1;this.latestOfferId=t;const n=yield this.pc.createOffer();this.pendingInitialOffer={sdp:n.sdp,type:n.type};const i=fd.parse(null!==(e=n.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{Pd(e)})),n.sdp=fd.write(i),{offer:n,offerId:t}}finally{t()}}))}createAndSendOffer(e){return pr(this,void 0,void 0,(function*(){var t;const n=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.iceLog.debug("restarting ICE"),this.restartingIce=!0),this._pc&&("have-local-offer"===this._pc.signalingState||this.pendingInitialOffer)){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t){if(null==e?void 0:e.iceRestart)throw new Xs("ICE restart requested without a remote description, peer connection must be recreated");return this.renegotiate=!0,void this.log.debug("requesting renegotiation")}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.log.debug("starting to negotiate");const n=this.latestOfferId+1;this.latestOfferId=n;const i=yield this.pc.createOffer(e);this.log.debug("original offer",{sdp:i.sdp});const r=fd.parse(null!==(t=i.sdp)&&void 0!==t?t:"");r.media.forEach((e=>{Pd(e),"audio"===e.type?wd(e,["all"],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!t.cid)return!1;const n=function(e,t,n,i){let r=arguments.length>4&&void 0!==arguments[4]&&arguments[4];var s,a,o;if(!(null===(s=e.msid)||void 0===s?void 0:s.includes(t)))return;const c=null!==(o=null===(a=e.rtp.find((e=>e.codec.toUpperCase()===n.toUpperCase())))||void 0===a?void 0:a.payload)&&void 0!==o?o:0;if(0===c)return 0;const d=Math.round(.9*i),l=r?d:Math.min(d,1e3),u=e.fmtp.find((e=>e.payload===c));return u?u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(l)):e.fmtp.push({payload:c,config:"x-google-start-bitrate=".concat(l)}),c}(e,t.cid,t.codec,t.maxbr,t.isScreenShare);return void 0!==n&&(n>0&&za(t.codec)&&!Za()&&(this.ddExtID=function(e,t,n){var i,r;const s=function(e,t){const n=function(e,t){var n;for(const i of e.media){const e=null===(n=i.ext)||void 0===n?void 0:n.find((e=>e.uri===t));if(e)return e.value}return}(e,Ba);if(void 0!==n)return Ed(e,n,Ba)?void 0:n;if(0!==t&&!Ed(e,t,Ba))return t;return function(e){let t=0;return e.media.forEach((e=>{var n;null===(n=e.ext)||void 0===n||n.forEach((e=>{e.value>t&&(t=e.value)}))})),t+1===15?16:t+1}(e)}(t,n);if(void 0===s)return n;(null===(i=e.ext)||void 0===i?void 0:i.some((e=>e.uri===Ba)))||(null!==(r=e.ext)&&void 0!==r||(e.ext=[]),e.ext.push({value:s,uri:Ba}));return s}(e,r,this.ddExtID)),!0)}))}));const s=this.getPlaceholderMids();if(s.size>0&&Rd(r.media,(e=>s.has(Id(e.mid)))),this.latestOfferId>n)return void this.log.warn("latestOfferId mismatch",{latestOfferId:this.latestOfferId,offerId:n});yield this.setMungedSDP(i,fd.write(r)),this.onOffer(i,this.latestOfferId)}finally{n()}}))}createAndSetAnswer(){return pr(this,void 0,void 0,(function*(){var e;const t=yield this.pc.createAnswer(),n=fd.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return n.media.forEach((e=>{Pd(e),"audio"===e.type&&wd(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,fd.write(n)),t}))}getPlaceholderMids(){var e,t;return function(e){const t=new Set;for(const n of e)n.mid&&!n.sender.track&&t.add(n.mid);return t}(null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?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 Ys("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 Ys("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(){var e;return null===(e=this._pc)||void 0===e?void 0:e.getStats()}getMaxMessageSize(){var e,t;return null===(t=null===(e=this._pc)||void 0===e?void 0:e.sctp)||void 0===t?void 0:t.maxMessageSize}getConnectedAddress(){return pr(this,void 0,void 0,(function*(){var e;if(!this._pc)return;let t="";const n=new Map,i=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),n.set(e.id,e);break;case"remote-candidate":i.set(e.id,"".concat(e.address,":").concat(e.port))}})),""===t)return;const r=null===(e=n.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==r?i.get(r):void 0}))}setMungedSDP(e,t,i){return pr(this,void 0,void 0,(function*(){var r,s;const a=e.sdp;if(t){e.sdp=t;try{return this.log.debug("setting munged ".concat(i?"remote":"local"," description")),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"),{error:n,mungedSdp:t,originalSdp:a}),e.sdp=a}}try{i?yield null===(r=this._pc)||void 0===r?void 0:r.setRemoteDescription(e):yield null===(s=this._pc)||void 0===s?void 0:s.setLocalDescription(e)}catch(n){let s="unknown error";n instanceof Error?s=n.message:"string"==typeof n&&(s=n);const o={error:s,sdp:e.sdp};throw t&&t!==a&&(o.mungedSdp=t),!i&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),{fields:o}),new Xs(s)}}))}}function Ed(e,t,n){return e.media.some((e=>{var i;return null===(i=e.ext)||void 0===i?void 0:i.some((e=>e.value===t&&e.uri!==n))}))}function Cd(e,t){return e.split(";").some((e=>e.trim()===t))}function wd(e,t,n){const i=Id(e.mid);let r=0;e.rtp.some((e=>"opus"===e.codec.toLowerCase()&&(r=e.payload,!0))),r>0&&(e.rtcpFb||(e.rtcpFb=[]),n.includes(i)&&!e.rtcpFb.some((e=>e.payload===r&&"nack"===e.type))&&e.rtcpFb.push({payload:r,type:"nack"}),(t.includes(i)||1===t.length&&"all"===t[0])&&e.fmtp.some((e=>e.payload===r&&(Cd(e.config,"stereo=1")||(e.config+=";stereo=1"),!0))))}function Rd(e,t){var n,i;const r=new Map,s=new Set;for(const a of e){const e=t(a);for(const t of null!==(n=a.fmtp)&&void 0!==n?n:[])e?r.has(t.payload)||r.set(t.payload,t.config):(r.set(t.payload,t.config),s.add(t.payload))}if(0!==r.size)for(const a of e)if(t(a))for(const e of null!==(i=a.fmtp)&&void 0!==i?i:[]){const t=r.get(e.payload);void 0!==t&&e.config!==t&&(e.config=t)}}function Pd(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 Id(e){return"number"==typeof e?e.toFixed(0):e}const _d="vp8",Md={audioPreset:e.AudioPresets.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:ba.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:_d,backupCodec:!0,preConnectBuffer:!1},Dd={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Od={deviceId:{ideal:"default"},resolution:ka.h720.resolution},Ad={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new ur,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Nd={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Ld,xd;!function(e){e[e.NEW=0]="NEW",e[e.CONNECTING=1]="CONNECTING",e[e.CONNECTED=2]="CONNECTED",e[e.FAILED=3]="FAILED",e[e.CLOSING=4]="CLOSING",e[e.CLOSED=5]="CLOSED"}(Ld||(Ld={}));class Ud{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(t,n,i){var s;this.peerConnectionTimeout=Nd.peerConnectionTimeout,this.log=sr,this.iceLog=sr,this.updateState=()=>{var e,t;const n=this.state,i=this.requiredTransports.map((e=>e.getConnectionState()));i.every((e=>"connected"===e))?this.state=Ld.CONNECTED:i.some((e=>"failed"===e))?this.state=Ld.FAILED:i.some((e=>"connecting"===e))?this.state=Ld.CONNECTING:i.every((e=>"closed"===e))?this.state=Ld.CLOSED:i.some((e=>"closed"===e))?this.state=Ld.CLOSING:i.every((e=>"new"===e))&&(this.state=Ld.NEW),n!==this.state&&(this.log.debug("pc state change: from ".concat(Ld[n]," to ").concat(Ld[this.state])),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.loggerOptions=n,this.log=or(null!==(s=n.loggerName)&&void 0!==s?s:e.LoggerNames.PCManager,(()=>this.logContext)),this.iceLog=or(e.LoggerNames.ICE,(()=>this.logContext)),this.isPublisherConnectionRequired="subscriber-primary"!==t,this.isSubscriberConnectionRequired="subscriber-primary"===t,this.publisher=new Sd(i,n),this._mode=t,"publisher-only"!==t&&(this.subscriber=new Sd(i,n),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,Un.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,Un.PUBLISHER)},this.publisher.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var n;null===(n=this.onPublisherOffer)||void 0===n||n.call(this,e,t)},this.state=Ld.NEW,this.connectionLock=new r,this.remoteOfferLock=new r}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 pr(this,void 0,void 0,(function*(){var e;if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(n){this.log.warn("could not removeTrack",{error:n})}}yield Promise.all([this.publisher.close(),null===(e=this.subscriber)||void 0===e?void 0:e.close()]),this.updateState()}))}triggerIceRestart(){return pr(this,void 0,void 0,(function*(){this.iceLog.warn("triggering ICE restart"),this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return pr(this,void 0,void 0,(function*(){var n;this.iceLog.debug("adding remote ICE candidate",{target:t,candidate:e}),t===Un.PUBLISHER?yield this.publisher.addIceCandidate(e):yield null===(n=this.subscriber)||void 0===n?void 0:n.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e,t){return pr(this,void 0,void 0,(function*(){var n,i,r;this.log.debug("received server offer",{RTCSdpType:e.type,sdp:e.sdp,signalingState:null===(n=this.subscriber)||void 0===n?void 0:n.getSignallingState().toString()});const s=yield this.remoteOfferLock.lock();try{if(!(yield null===(i=this.subscriber)||void 0===i?void 0:i.setRemoteDescription(e,t)))return;return yield null===(r=this.subscriber)||void 0===r?void 0:r.createAndSetAnswer()}finally{s()}}))}updateConfiguration(e,t){var n;this.log.debug("updating rtc configuration",{iceRestart:t}),this.publisher.setConfiguration(e),null===(n=this.subscriber)||void 0===n||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return pr(this,void 0,void 0,(function*(){var n;const i=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating"),this.publisher.negotiate()),yield Promise.all(null===(n=this.requiredTransports)||void 0===n?void 0:n.map((n=>this.ensureTransportConnected(n,e,t))))}finally{i()}}))}negotiate(e){return pr(this,void 0,void 0,(function*(){return new _s(((t,n)=>{const i=this.publisher.latestOfferId;if(this.publisher.latestAcknowledgedOfferId>i)return this.log.debug("negotiation already handled in more recent acknowledged offer",this.logContext),void t();let r=!1;const s=()=>{r||(r=!0,clearTimeout(c),this.publisher.off(bd,a),e.signal.removeEventListener("abort",o))},a=e=>{e>i&&(s(),t())},o=()=>{s(),n(new Xs("negotiation aborted"))},c=setTimeout((()=>{s(),n(new Xs("negotiation timed out"))}),this.peerConnectionTimeout);e.signal.addEventListener("abort",o),this.publisher.on(bd,a),this.publisher.negotiate((e=>{s(),e instanceof Error?n(e):n(new Error(String(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}getMaxPublisherMessageSize(){return this.publisher.getMaxMessageSize()}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Un.PUBLISHER||e===Un.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 pr(this,arguments,void 0,(function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise(((e,r)=>pr(n,void 0,void 0,(function*(){const n=()=>{this.log.warn("abort transport connection"),ia.clearTimeout(s),r(zs.cancelled("room connection has been cancelled"))};(null==t?void 0:t.signal.aborted)&&n(),null==t||t.signal.addEventListener("abort",n);const s=ia.setTimeout((()=>{null==t||t.signal.removeEventListener("abort",n),r(zs.internal("could not establish pc connection"))}),i);for(;this.state!==Ld.CONNECTED;)if(yield qa(50),null==t?void 0:t.signal.aborted)return void r(zs.cancelled("room connection has been cancelled"));ia.clearTimeout(s),null==t||t.signal.removeEventListener("abort",n),e()}))))}()}))}}class Fd{constructor(e){this.bufferStatusLow=!0,this.headroomLock=new r,this.waiterAbortController=new AbortController,this.kind=e.kind,this.lowWaterMark=e.lowWaterMark,this.highWaterMark=e.highWaterMark,this.isEngineClosed=e.isEngineClosed,this.onBufferStatusChanged=e.onBufferStatusChanged}get channelHandle(){return this.handle}attach(e){this.handle&&this.handle!==e&&this.invalidateWaiters("data channel replaced"),this.handle=e}detach(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"data channel torn down";this.handle&&this.invalidateWaiters(e),this.handle=void 0}getChannel(){return this.handle}isBelowHighWaterMark(e){return e.bufferedAmount<=this.highWaterMark}isBelowLowWaterMark(e){return e.bufferedAmount<=e.bufferedAmountLowThreshold}lockHeadroom(){return this.headroomLock.lock()}waitForHeadroomWithLock(){return pr(this,void 0,void 0,(function*(){const e=yield this.lockHeadroom();try{yield this.waitForHeadroomWithoutLock()}finally{e()}}))}waitForHeadroomWithoutLock(){return pr(this,void 0,void 0,(function*(){if(this.isEngineClosed())throw new Ys("engine closed");const e=this.getChannel();if(!e)throw new Ys("DataChannel not found, kind: ".concat(this.kind));if(this.isBelowHighWaterMark(e))return;const t=this.waiterAbortController.signal;yield new _s(((n,i)=>{const r=()=>{o(),n()},s=()=>{o(),i(new Ys("DataChannel ".concat(this.kind," closed while draining the buffer")))},a=()=>{o(),i(new Ys("DataChannel ".concat(this.kind," was replaced or torn down while waiting for headroom")))},o=()=>{e.removeEventListener("bufferedamountlow",r),e.removeEventListener("close",s),t.removeEventListener("abort",a)};t.aborted?a():(e.addEventListener("bufferedamountlow",r),e.addEventListener("close",s),t.addEventListener("abort",a))}))}))}invalidateWaiters(e){this.waiterAbortController.abort(e),this.waiterAbortController=new AbortController}refreshBufferStatus(){var e;const t=this.getChannel();if(!t)return;const n=this.isBelowLowWaterMark(t);n!==this.bufferStatusLow&&(this.bufferStatusLow=n,null===(e=this.onBufferStatusChanged)||void 0===e||e.call(this,n))}}class Bd extends Fd{constructor(e){super(e),this.statCurrentBytes=0,this.statByterate=0,this.dropCount=0,this.bufferFullBehavior=e.bufferFullBehavior,this.shouldSkipSends=e.shouldSkipSends}send(e){return pr(this,void 0,void 0,(function*(){const t=this.getChannel();if(t){switch(this.bufferFullBehavior){case"wait":this.isBelowHighWaterMark(t)||(yield this.waitForHeadroomWithLock());break;case"drop":if(!this.isBelowLowWaterMark(t))return this.dropCount+=1,void(this.dropCount%100==0&&sr.warn("dropping lossy data channel messages, total dropped: ".concat(this.dropCount)))}if(this.statCurrentBytes+=e.byteLength,!this.shouldSkipSends())try{t.send(e),this.refreshBufferStatus()}catch(n){if(!(n instanceof TypeError))throw n;sr.error(n)}}}))}startThresholdTuning(){this.stopThresholdTuning(),this.statInterval=ia.setInterval((()=>{this.statByterate=this.statCurrentBytes,this.statCurrentBytes=0;const e=this.getChannel();if(e){const t=this.statByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,this.lowWaterMark),this.highWaterMark)}}),1e3)}stopThresholdTuning(){this.statByterate=0,this.statCurrentBytes=0,this.statInterval&&(ia.clearInterval(this.statInterval),this.statInterval=void 0),this.dropCount=0}}class jd{constructor(){this.buffer=[],this._totalSize=0,this._sentSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength,e.sent&&(this._sentSize+=e.data.byteLength)}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength,e.sent&&(this._sentSize-=e.data.byteLength)),e}getAll(){return this.buffer.slice()}getUnsent(){return this.buffer.filter((e=>!e.sent))}markSent(e){e.sent||(e.sent=!0,this._sentSize+=e.data.byteLength)}markAllUnsent(){for(const e of this.buffer)e.sent=!1;this._sentSize=0}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(!t.sent)break;if(this._sentSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class qd extends Fd{constructor(e){super(e),this.messageBuffer=new jd,this.sequence=1,this.isDeferringSends=e.isDeferringSends}nextSequence(){const e=this.sequence;return this.sequence+=1,e}send(e,t){return pr(this,void 0,void 0,(function*(){if(this.isDeferringSends())return void this.messageBuffer.push({data:e,sequence:t,sent:!1});const n=this.getChannel();if(n){try{yield this.waitForHeadroomWithLock()}catch(i){if(this.isEngineClosed())throw i;return void this.messageBuffer.push({data:e,sequence:t,sent:!1})}this.isDeferringSends()?this.messageBuffer.push({data:e,sequence:t,sent:!1}):(this.messageBuffer.push({data:e,sequence:t,sent:!0}),n.send(e),this.refreshBufferStatus())}}))}replay(e){return pr(this,void 0,void 0,(function*(){const t=this.getChannel();if(!t)return;this.messageBuffer.popToSequence(e);const n=yield this.lockHeadroom();try{this.messageBuffer.markAllUnsent();for(let e=this.messageBuffer.getUnsent();e.length>0;e=this.messageBuffer.getUnsent())for(const n of e)yield this.waitForHeadroomWithoutLock(),t.send(n.data),this.messageBuffer.markSent(n)}finally{n()}this.refreshBufferStatus()}))}refreshBufferStatus(){const e=this.channelHandle;e&&this.messageBuffer.alignBufferedAmount(e.bufferedAmount),super.refreshBufferStatus()}reset(){this.messageBuffer=new jd,this.sequence=1}}!function(e){e[e.RELIABLE=0]="RELIABLE",e[e.LOSSY=1]="LOSSY",e[e.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY"}(xd||(xd={}));function Vd(e){return e===xd.RELIABLE?65536:8192}function Wd(e){return e===xd.RELIABLE?1048576:262144}const Hd="_lossy",Kd="_reliable",zd="_data_track";class Gd{constructor(e){this.opts=e;const t=t=>({kind:t,lowWaterMark:Vd(t),highWaterMark:Wd(t),isEngineClosed:e.isEngineClosed,onBufferStatusChanged:n=>e.onBufferStatusChanged(t,n)});this.reliable=new qd(Object.assign(Object.assign({},t(xd.RELIABLE)),{isDeferringSends:e.isReconnecting})),this.lossy=new Bd(Object.assign(Object.assign({},t(xd.LOSSY)),{bufferFullBehavior:"drop",shouldSkipSends:e.isReconnecting})),this.dataTrack=new Bd(Object.assign(Object.assign({},t(xd.DATA_TRACK_LOSSY)),{bufferFullBehavior:"wait",shouldSkipSends:e.isReconnecting}))}channelFor(e){switch(e){case xd.RELIABLE:return this.reliable;case xd.LOSSY:return this.lossy;case xd.DATA_TRACK_LOSSY:return this.dataTrack}}getHandle(e){if(!(arguments.length>1&&void 0!==arguments[1]&&arguments[1]))return this.channelFor(e).channelHandle;switch(e){case xd.RELIABLE:return this.reliableSub;case xd.LOSSY:return this.lossySub;case xd.DATA_TRACK_LOSSY:return this.dataTrackSub}}get hasPublisherChannels(){return Boolean(this.reliable.channelHandle||this.lossy.channelHandle||this.dataTrack.channelHandle)}createPublisherChannels(e){for(const n of[this.lossy,this.reliable,this.dataTrack]){const e=n.channelHandle;e&&(e.onmessage=null,e.onerror=null,e.onclose=null)}const t=(e,t,n)=>{t.onmessage=n,t.onerror=this.opts.onDataError,t.onclose=()=>this.opts.onChannelClose(e.kind),t.bufferedAmountLowThreshold=e.lowWaterMark,t.onbufferedamountlow=()=>e.refreshBufferStatus(),e.attach(t)};t(this.lossy,e.createPublisherDataChannel(Hd,{ordered:!1,maxRetransmits:0}),this.opts.onDataMessage),t(this.reliable,e.createPublisherDataChannel(Kd,{ordered:!0}),this.opts.onDataMessage),t(this.dataTrack,e.createPublisherDataChannel(zd,{ordered:!1,maxRetransmits:0}),this.opts.onDataTrackMessage),this.lossy.startThresholdTuning()}adoptSubscriberChannel(e){let t;if(e.label===Kd)this.reliableSub=e,t=this.opts.onDataMessage;else if(e.label===Hd)this.lossySub=e,t=this.opts.onDataMessage;else{if(e.label!==zd)return!1;this.dataTrackSub=e,t=this.opts.onDataTrackMessage}return e.onmessage=t,!0}teardown(){const e=e=>{e&&(e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null,e.close())};for(const t of[this.lossy,this.reliable,this.dataTrack]){const n=t.channelHandle;t.detach("peer connections cleaned up"),e(n)}e(this.lossySub),e(this.reliableSub),e(this.dataTrackSub),this.lossySub=void 0,this.reliableSub=void 0,this.dataTrackSub=void 0,this.reliable.reset()}}const Jd="undefined"!=typeof MediaRecorder;const Qd=Jd?MediaRecorder:class{constructor(){throw new Error("MediaRecorder is not available in this environment")}};class Yd extends Qd{constructor(e,t){if(!Jd)throw new Error("MediaRecorder is not available in this environment");let n,i;super(new MediaStream([e.mediaStreamTrack]),t);const r=()=>{this.removeEventListener("dataavailable",n),this.removeEventListener("stop",r),this.removeEventListener("error",s),null==i||i.close(),i=void 0},s=e=>{null==i||i.error(e),this.removeEventListener("dataavailable",n),this.removeEventListener("stop",r),this.removeEventListener("error",s),i=void 0};this.byteStream=new ReadableStream({start:e=>{i=e,n=t=>pr(this,void 0,void 0,(function*(){let n;if(t.data.arrayBuffer){const e=yield t.data.arrayBuffer();n=new Uint8Array(e)}else{if(!t.data.byteArray)throw new Error("no data available!");n=t.data.byteArray}void 0!==i&&e.enqueue(n)})),this.addEventListener("dataavailable",n)},cancel:()=>{r()}}),this.addEventListener("stop",r),this.addEventListener("error",s)}}class Xd extends xa{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(t,n,i){let s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(t,n,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!1,this.pendingDeviceChange=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch((()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext))),this.debouncedTrackMuteHandler=oc((()=>pr(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>pr(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(e.TrackEvent.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new r,this.pauseUpstreamLock=new r,this.trackChangeLock=new r,this.trackChangeLock.lock().then((e=>pr(this,void 0,void 0,(function*(){try{yield this.setMediaStreamTrack(t,!0)}finally{e()}})))),this._constraints=t.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==xa.Kind.Video)return;const e=this._mediaStreamTrack.getSettings(),t=e.width,n=e.height;return t&&n?{width:t,height:n}: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,n){return pr(this,void 0,void 0,(function*(){var i;if(e===this._mediaStreamTrack&&!t)return;let r;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{Fa(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&&(Ua(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement,localTrack:this}),r=this.processor.processedTrack}this.sender&&"closed"!==(null===(i=this.sender.transport)||void 0===i?void 0:i.state)&&(yield this.sender.replaceTrack(null!=r?r:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!!n||!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{Ua(null!=r?r:e,t)})))}))}waitForDimensions(){return pr(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var n;if(e.kind===xa.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(n=Os())||void 0===n?void 0:n.os)&&(yield qa(10));const i=Date.now();for(;Date.now()-i<t;){const t=e.dimensions;if(t)return t;yield qa(50)}throw new Js("unable to get track dimensions after timeout")}()}))}setDeviceId(e){return pr(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Eo(e)||(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),Eo(e)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return pr(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===xa.Source.ScreenShare)return;const n=e._mediaStreamTrack.getSettings(),i=n.deviceId,r=n.groupId,s=e.kind===xa.Kind.Audio?"audioinput":"videoinput";return t?Tc.getInstance().normalizeDeviceId(s,i,r):i}()}))}mute(){return pr(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return pr(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return pr(this,void 0,void 0,(function*(){const n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Js("unable to replace an unpublished track");let n,i;"boolean"==typeof t?n=t:void 0!==t&&(n=t.userProvidedTrack,i=t.stopProcessor),this.providedByUser=null==n||n,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),i&&this.processor&&(yield this.internalStopProcessor())}finally{n()}return yield this.onSenderTrackSwapped(),this}))}onSenderTrackSwapped(){return pr(this,void 0,void 0,(function*(){}))}restart(t,n){return pr(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const i=yield this.trackChangeLock.lock();try{t||(t=this._constraints);const i=t,r=i.deviceId,s=i.facingMode,a=hr(t,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:t}));const o={audio:!1,video:!1};this.kind===xa.Kind.Video?o.video=!r&&!s||{deviceId:r,facingMode:s}:o.audio=!r||Object.assign({deviceId:r},a),this.attachedElements.forEach((e=>{Fa(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return this.kind===xa.Kind.Video&&(yield c.applyConstraints(a)),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c,!1,n),this._constraints=t,this.pendingDeviceChange=!1,this.emit(e.TrackEvent.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{i()}}))}setTrackMuted(t){this.log.debug("setting ".concat(this.kind," track ").concat(t?"muted":"unmuted"),this.logContext),this.isMuted===t&&this._mediaStreamTrack.enabled!==t||(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.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 pr(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),to()&&(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 pr(this,void 0,void 0,(function*(){var t;const n=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(e.TrackEvent.UpstreamPaused,this);const n=Os();if("Safari"===(null==n?void 0:n.name)&&lo(n.version,"12.0")<0)throw new Gs("pauseUpstream is not supported on Safari < 12.");"closed"!==(null===(t=this.sender.transport)||void 0===t?void 0:t.state)&&(yield this.sender.replaceTrack(null))}finally{n()}}))}resumeUpstream(){return pr(this,void 0,void 0,(function*(){var t;const n=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(e.TrackEvent.UpstreamResumed,this),"closed"!==(null===(t=this.sender.transport)||void 0===t?void 0:t.state)&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{n()}}))}getRTCStatsReport(){return pr(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(t){return pr(this,arguments,void 0,(function(t){var n=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var r;const s=yield n.trackChangeLock.lock();try{n.log.debug("setting up processor",n.logContext);const s=document.createElement(n.kind),a={kind:n.kind,track:n._mediaStreamTrack,element:s,audioContext:n.audioContext,localTrack:n};if(yield t.init(a),n.log.debug("processor initialized",n.logContext),n.processor&&(yield n.internalStopProcessor()),"unknown"===n.kind)throw TypeError("cannot set processor on track of unknown kind");if(Ua(n._mediaStreamTrack,s),s.muted=!0,s.play().catch((e=>{e instanceof DOMException&&"AbortError"===e.name?(n.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},n.logContext),{error:e})),setTimeout((()=>{s.play().catch((e=>{n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{err:e}))}))}),100)):n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:e}))})),n.processor=t,n.processorElement=s,n.processor.processedTrack){for(const e of n.attachedElements)e!==n.processorElement&&i&&(Fa(n._mediaStreamTrack,e),Ua(n.processor.processedTrack,e));yield null===(r=n.sender)||void 0===r?void 0:r.replaceTrack(n.processor.processedTrack)}n.emit(e.TrackEvent.TrackProcessorUpdate,n.processor)}finally{s()}yield n.onSenderTrackSwapped()}()}))}getProcessor(){return this.processor}stopProcessor(){return pr(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}yield e.onSenderTrackSwapped()}()}))}internalStopProcessor(){return pr(this,arguments,void 0,(function(){var t=this;let n=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,r;t.processor&&(t.log.debug("stopping processor",t.logContext),null===(i=t.processor.processedTrack)||void 0===i||i.stop(),yield t.processor.destroy(),t.processor=void 0,n||(null===(r=t.processorElement)||void 0===r||r.remove(),t.processorElement=void 0),yield t._mediaStreamTrack.applyConstraints(t._constraints),yield t.setMediaStreamTrack(t._mediaStreamTrack,!0),t.emit(e.TrackEvent.TrackProcessorUpdate))}()}))}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(Jd)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 Yd(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 Zd extends Xd{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(t,i){let r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],s=arguments.length>3?arguments[3]:void 0,a=arguments.length>4?arguments[4]:void 0;super(t,xa.Kind.Audio,i,r,a),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>pr(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 audio sender stats",Object.assign(Object.assign({},this.logContext),{error:n}))}e&&this.prevStats&&(this._currentBitrate=dc(e,this.prevStats)),this.prevStats=e})),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(e.TrackEvent.AudioTrackFeatureUpdate,this,ct.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(e.TrackEvent.AudioTrackFeatureUpdate,this,ct.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return pr(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===xa.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 pr(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==xa.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!this.pendingDeviceChange||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}restartTrack(e){return pr(this,void 0,void 0,(function*(){let t;if(e){const n=Ea({audio:e});"boolean"!=typeof n.audio&&(t=n.audio)}yield this.restart(t)}))}applyConstraints(e){return pr(this,void 0,void 0,(function*(){const t=yield this.trackChangeLock.lock();try{const t=yield this._mediaStreamTrack.applyConstraints(e);return this._constraints=Object.assign(Object.assign({},this._constraints),e),t}finally{t()}}))}restart(e,t){const n=Object.create(null,{restart:{get:()=>super.restart}});return pr(this,void 0,void 0,(function*(){const i=yield n.restart.call(this,e,t);return this.checkForSilence(),i}))}startMonitor(){no()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),cc)))}setProcessor(t){return pr(this,void 0,void 0,(function*(){var n;const i=yield this.trackChangeLock.lock();try{if(!io()&&!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,localTrack:this};this.log.debug("setting up audio processor ".concat(t.name),this.logContext),yield t.init(i),this.processor=t,this.processor.processedTrack&&(yield null===(n=this.sender)||void 0===n?void 0:n.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(e.TrackEvent.TrackProcessorUpdate,this.processor)}finally{i()}}))}setAudioContext(e){this.audioContext=e}getSenderStats(){return pr(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;const t=yield this.sender.getStats();let n;return t.forEach((e=>{if("outbound-rtp"===e.type){n={type:"audio",streamId:e.id,packetsSent:e.packetsSent,bytesSent:e.bytesSent,timestamp:e.timestamp};const i=t.get(e.remoteId);i&&(n.packetsLost=i.packetsLost,n.jitter=i.jitter,n.roundTripTime=i.roundTripTime)}})),n}))}checkForSilence(){return pr(this,void 0,void 0,(function*(){const t=yield Ca(this);return t&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(e.TrackEvent.AudioSilenceDetected)),t}))}}const $d=Object.values(ka),el=Object.values(ya),tl=Object.values(ba),nl=[ka.h180,ka.h360],il=[ya.h180,ya.h360],rl=["q","h","f"];function sl(e,t,n,i){var r,s;let a=null==i?void 0:i.videoEncoding;e&&(a=null==i?void 0:i.screenShareEncoding);const o=null==i?void 0:i.simulcast,c=null==i?void 0:i.scalabilityMode,d=null==i?void 0:i.videoCodec;if(!a&&!o&&!c||!t||!n)return[{}];a||(a=function(e,t,n,i){const r=function(e,t,n){if(e)return tl;const i=t>n?t/n:n/t;if(Math.abs(i-16/9)<Math.abs(i-4/3))return $d;return el}(e,t,n);let s=r[0].encoding;const a=Math.max(t,n);for(let o=0;o<r.length;o+=1){const e=r[o];if(s=e.encoding,e.width>=a)break}if(i)switch(i){case"av1":case"h265":s=Object.assign({},s),s.maxBitrate=.7*s.maxBitrate;break;case"vp9":s=Object.assign({},s),s.maxBitrate=.85*s.maxBitrate}return s}(e,t,n,d),sr.debug("using video encoding",a));const l=a.maxFramerate,u=new la(t,n,a.maxBitrate,a.maxFramerate,a.priority);if(c&&za(d)){const e=new ll(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const n=Os();if($a()||io()||"Chrome"===(null==n?void 0:n.name)&&lo(null==n?void 0:n.version,"113")<0){const i="h"==e.suffix?2:3,r=function(e){return e||(e=Os()),"Safari"===(null==e?void 0:e.name)&&lo(e.version,"18.3")>0||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&lo(e.osVersion,"18.3")>0}(n);for(let n=0;n<e.spatial;n+=1)t.push({rid:rl[2-n],maxBitrate:a.maxBitrate/Math.pow(i,n),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:r?Math.pow(2,n):void 0});t[0].scalabilityMode=c}else t.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),sr.debug("using svc encoding",{encodings:t}),t}if(!o)return[a];let h,p;if(h=e?null!==(r=dl(null==i?void 0:i.screenShareSimulcastLayers))&&void 0!==r?r:ol(e,u):null!==(s=dl(null==i?void 0:i.videoSimulcastLayers))&&void 0!==s?s:ol(e,u),h.length>0){const e=h[0];if(h.length>1)p=F(h,2)[1];const i=Math.max(t,n);if(i>=960&&p)return cl(t,n,[e,p,u],l);if(i>=480)return cl(t,n,[e,u],l)}return cl(t,n,[u])}function al(e,t,n){var i,r,s,a;if(!n.backupCodec||!0===n.backupCodec||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&sr.warn("requested a different codec than specified as backup",{serverRequested:t,backup:n.backupCodec.codec}),n.videoCodec=t,n.videoEncoding=n.backupCodec.encoding;const o=e.mediaStreamTrack.getSettings(),c=null!==(i=o.width)&&void 0!==i?i:null===(r=e.dimensions)||void 0===r?void 0:r.width,d=null!==(s=o.height)&&void 0!==s?s:null===(a=e.dimensions)||void 0===a?void 0:a.height;e.source===xa.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1);return sl(e.source===xa.Source.ScreenShare,c,d,n)}function ol(e,t){if(e)return[{scaleResolutionDownBy:2,fps:(n=t).encoding.maxFramerate}].map((e=>{var t,i;return new la(Math.floor(n.width/e.scaleResolutionDownBy),Math.floor(n.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!==(t=n.encoding.maxFramerate)&&void 0!==t?t:30)/(null!==(i=e.fps)&&void 0!==i?i:30))))),e.fps,n.encoding.priority)}));var n;const i=t.width,r=t.height,s=i>r?i/r:r/i;return Math.abs(s-16/9)<Math.abs(s-4/3)?nl:il}function cl(e,t,n,i){const r=[];if(n.forEach(((n,s)=>{if(s>=rl.length)return;const a=Math.min(e,t),o={rid:rl[s],scaleResolutionDownBy:Math.max(1,a/Math.min(n.width,n.height)),maxBitrate:n.encoding.maxBitrate},c=i&&n.encoding.maxFramerate?Math.min(i,n.encoding.maxFramerate):n.encoding.maxFramerate;c&&(o.maxFramerate=c);const d=Os(),l="Firefox"===(null==d?void 0:d.name)&&"iOS"!==d.os||0===s;n.encoding.priority&&l&&(o.priority=n.encoding.priority,o.networkPriority=n.encoding.priority),r.push(o)})),io()&&"ios"===oo()){let e;r.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;r.forEach((n=>{var i;n.maxFramerate!=e&&(t&&(t=!1,sr.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),sr.info('Setting framerate of encoding "'.concat(null!==(i=n.rid)&&void 0!==i?i:"",'" to ').concat(e)),n.maxFramerate=e)}))}return r}function dl(e){if(e)return e.slice().sort(((e,t)=>{const n=e.encoding,i=t.encoding;return n.maxBitrate>i.maxBitrate?1:n.maxBitrate<i.maxBitrate?-1:n.maxBitrate===i.maxBitrate&&n.maxFramerate&&i.maxFramerate?n.maxFramerate>i.maxFramerate?1:-1:0}))}class ll{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 ul extends Xd{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(t,i){let s=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],a=arguments.length>3?arguments[3]:void 0;super(t,xa.Kind.Video,i,s,a),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>pr(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let t;try{t=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 i=new Map(t.map((e=>[e.rid,e]))),r=t.some((e=>"cpu"===e.qualityLimitationReason));if(r!==this.isCpuConstrained&&(this.isCpuConstrained=r,this.isCpuConstrained&&this.emit(e.TrackEvent.CpuConstrained)),this.prevStats){let e=0;i.forEach(((t,n)=>{var i;const r=null===(i=this.prevStats)||void 0===i?void 0:i.get(n);e+=dc(t,r)})),this._currentBitrate=e}this.prevStats=i})),this.senderLock=new r}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!no())return;const n=null===(t=this.sender)||void 0===t?void 0:t.getParameters();n&&(this.encodings=n.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),cc))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return pr(this,void 0,void 0,(function*(){var t,n,i,r,s;yield e.pauseUpstream.call(this);try{for(var a,o=!0,c=fr(this.simulcastCodecs.values());!(t=(a=yield c.next()).done);o=!0){r=a.value,o=!1;const e=r;yield null===(s=e.sender)||void 0===s?void 0:s.replaceTrack(null)}}catch(d){n={error:d}}finally{try{o||t||!(i=c.return)||(yield i.call(c))}finally{if(n)throw n.error}}}))}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return pr(this,void 0,void 0,(function*(){var t,n,i,r,s;yield e.resumeUpstream.call(this);try{for(var a,o=!0,c=fr(this.simulcastCodecs.values());!(t=(a=yield c.next()).done);o=!0){r=a.value,o=!1;const e=r;yield null===(s=e.sender)||void 0===s?void 0:s.replaceTrack(e.mediaStreamTrack)}}catch(d){n={error:d}}finally{try{o||t||!(i=c.return)||(yield i.call(c))}finally{if(n)throw n.error}}}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return pr(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!==xa.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 pr(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==xa.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return pr(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],n=yield this.sender.getStats();return n.forEach((e=>{var i;if("outbound-rtp"===e.type){const r={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!==(i=e.rid)&&void 0!==i?i:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},s=n.get(e.remoteId);s&&(r.jitter=s.jitter,r.packetsLost=s.packetsLost,r.roundTripTime=s.roundTripTime),t.push(r)}})),t.sort(((e,t)=>{var n,i;return(null!==(n=t.frameWidth)&&void 0!==n?n:0)-(null!==(i=e.frameWidth)&&void 0!==i?i:0)})),t}))}setPublishingQuality(t){const n=[];for(let i=e.VideoQuality.LOW;i<=e.VideoQuality.HIGH;i+=1)n.push(new wi({quality:i,enabled:i<=t}));this.log.debug("setting publishing quality. max quality ".concat(t),this.logContext),this.setPublishingLayers(za(this.codec),n)}restartTrack(e){return pr(this,void 0,void 0,(function*(){var t,n,i,r,s;let a;if(e){const t=Ea({video:e});"boolean"!=typeof t.video&&(a=t.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var o,c=!0,d=fr(this.simulcastCodecs.values());!(t=(o=yield d.next()).done);c=!0){r=o.value,c=!1;const e=r;e.sender&&"closed"!==(null===(s=e.sender.transport)||void 0===s?void 0:s.state)&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(l){n={error:l}}finally{try{c||t||!(i=d.return)||(yield i.call(d))}finally{if(n)throw n.error}}yield this.onSenderTrackSwapped()}))}onSenderTrackSwapped(){return pr(this,void 0,void 0,(function*(){yield this.refreshSenderEncodings()}))}refreshSenderEncodings(){return pr(this,void 0,void 0,(function*(){var e;if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;const t=yield this.senderLock.lock();try{let t;try{t=yield this.waitForDimensions()}catch(n){return void this.log.warn("could not determine new track dimensions, skipping encoding recompute",Object.assign(Object.assign({},this.logContext),{error:n}))}if(this.lastEncodedDimensions&&this.lastEncodedDimensions.width===t.width&&this.lastEncodedDimensions.height===t.height)return;const r=sl(this.source===xa.Source.ScreenShare,t.width,t.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,r),this.encodings=r,this.lastEncodedDimensions=t;for(const n of this.simulcastCodecs){var i=F(n,2);const t=i[0],r=i[1];if(!r.sender||"closed"===(null===(e=r.sender.transport)||void 0===e?void 0:e.state))continue;if(!ma(t))continue;const s=al(this,t,Object.assign({},this.publishOptions));s&&(yield this.applyEncodingsToSender(r.sender,s),r.encodings=s)}}catch(n){this.log.warn("failed to apply recomputed encodings",Object.assign(Object.assign({},this.logContext),{error:n}))}finally{t()}}))}applyEncodingsToSender(e,t){return pr(this,void 0,void 0,(function*(){const n=e.getParameters();n.encodings&&n.encodings.length===t.length&&(n.encodings.forEach(((e,n)=>{if(!1===e.active)return;const i=t[n];void 0!==i.scaleResolutionDownBy&&(e.scaleResolutionDownBy=i.scaleResolutionDownBy),void 0!==i.maxBitrate&&(e.maxBitrate=i.maxBitrate),void 0!==i.maxFramerate&&(e.maxFramerate=i.maxFramerate),void 0!==i.priority&&(e.priority=i.priority,e.networkPriority=i.priority)})),this.log.debug("updating sender encodings after track restart",Object.assign(Object.assign({},this.logContext),{encodings:n.encodings})),yield e.setParameters(n))}))}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return pr(this,arguments,void 0,(function(e){var n=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var r,s,a,o,c,d;if(yield t.setProcessor.call(n,e,i),null===(c=n.processor)||void 0===c?void 0:c.processedTrack)try{for(var l,u=!0,h=fr(n.simulcastCodecs.values());!(r=(l=yield h.next()).done);u=!0){o=l.value,u=!1;const e=o;yield null===(d=e.sender)||void 0===d?void 0:d.replaceTrack(n.processor.processedTrack)}}catch(p){s={error:p}}finally{try{u||r||!(a=h.return)||(yield a.call(h))}finally{if(s)throw s.error}}}()}))}setDegradationPreference(e){return pr(this,void 0,void 0,(function*(){this.degradationPreference=e,yield this.applyDegradationPreference(this.sender);for(const e of this.simulcastCodecs.values())yield this.applyDegradationPreference(e.sender)}))}applyDegradationPreference(e){return pr(this,void 0,void 0,(function*(){if(e)try{this.log.debug("setting degradationPreference to ".concat(this.degradationPreference),this.logContext);const t=e.getParameters();t.degradationPreference=this.degradationPreference,yield e.setParameters(t)}catch(n){this.log.warn("failed to set degradationPreference",Object.assign({error:n},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 n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){return pr(this,void 0,void 0,(function*(){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,yield this.applyDegradationPreference(t),setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}))}setPublishingCodecs(e){return pr(this,void 0,void 0,(function*(){var t,n,i,r,s,a,o;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(za(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,n=fr(e);!(r=(i=yield n.next()).done);t=!0){o=i.value,t=!1;const e=o;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 hl(t.sender,t.encodings,e.qualities,this.senderLock,za(e.codec),this.log,this.logContext));else for(const n of e.qualities)if(n.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(za(e.codec),e.qualities)}}catch(d){s={error:d}}finally{try{t||r||!(a=n.return)||(yield a.call(n))}finally{if(s)throw s.error}}return c}))}setPublishingLayers(e,t){return pr(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 hl(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))}))}prioritizePerformance(){return pr(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 n;return Object.assign(Object.assign({},e),{active:0===t,scaleResolutionDownBy:Math.max(1,Math.ceil((null!==(n=this.mediaStreamTrack.getSettings().height)&&void 0!==n?n:360)/360)),scalabilityMode:0===t&&za(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(n){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:n})),this.optimizeForPerformance=!1}finally{e()}}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return pr(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),to()&&this.isInBackground&&this.source===xa.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function hl(e,t,n,i,r,s,a){return pr(this,void 0,void 0,(function*(){const o=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},a),{sender:e,qualities:n,senderEncodings:t}));try{const i=e.getParameters(),o=i.encodings;if(!o)return;if(o.length!==t.length)return void s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},a),{encodings:o,senderEncodings:t}));let c=!1;if(!1&&o[0].scalabilityMode);else{if(r){n.some((e=>e.enabled))&&n.forEach((e=>e.enabled=!0))}o.forEach(((e,i)=>{var r;let o=null!==(r=e.rid)&&void 0!==r?r:"";""===o&&(o="q");const d=pl(o),l=n.find((e=>e.quality===d));l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,s.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),a),Ya()&&(l.enabled?(e.scaleResolutionDownBy=t[i].scaleResolutionDownBy,e.maxBitrate=t[i].maxBitrate,e.maxFrameRate=t[i].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}))}c&&(i.encodings=o,s.debug("setting encodings",Object.assign(Object.assign({},a),{encodings:i.encodings})),yield e.setParameters(i))}finally{o()}}))}function pl(t){switch(t){case"f":default:return e.VideoQuality.HIGH;case"h":return e.VideoQuality.MEDIUM;case"q":return e.VideoQuality.LOW}}function ml(t,n,i,r){if(!i)return[new _t({quality:e.VideoQuality.HIGH,width:t,height:n,bitrate:0,ssrc:0})];if(r){const r=i[0].scalabilityMode,s=new ll(r),a=[],o="h"==s.suffix?1.5:2,c="h"==s.suffix?2:3;for(let d=0;d<s.spatial;d+=1)a.push(new _t({quality:Math.min(e.VideoQuality.HIGH,s.spatial-1)-d,width:Math.ceil(t/Math.pow(o,d)),height:Math.ceil(n/Math.pow(o,d)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(c,d)):0,ssrc:0}));return a}return i.map((e=>{var i,r,s;const a=null!==(i=e.scaleResolutionDownBy)&&void 0!==i?i:1;let o=pl(null!==(r=e.rid)&&void 0!==r?r:"");return new _t({quality:o,width:Math.ceil(t/a),height:Math.ceil(n/a),bitrate:null!==(s=e.maxBitrate)&&void 0!==s?s:0,ssrc:0})}))}const gl="leave-reconnect";var vl;!function(e){e[e.New=0]="New",e[e.Connected=1]="Connected",e[e.Disconnected=2]="Disconnected",e[e.Reconnecting=3]="Reconnecting",e[e.Closed=4]="Closed"}(vl||(vl={}));class fl extends br.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}get reliableChannel(){return this.dataChannels.reliable}get lossyChannel(){return this.dataChannels.lossy}get dataTrackChannel(){return this.dataChannels.dataTrack}constructor(t){var i;super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=Nd.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=vl.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.shouldFailOnV1Path=!1,this.log=sr,this.reliableReceivedState=new sd(3e4),this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>pr(this,[e],void 0,(function(e){var t=this;let n=e.channel;return function*(){n&&t.dataChannels.adoptSubscriberChannel(n)&&t.log.debug("on data channel ".concat(n.id,", ").concat(n.label))}()})),this.handleDataMessage=t=>pr(this,void 0,void 0,(function*(){var n,i,r,s,a;const o=yield this.dataProcessLock.lock();try{const o=yield this.decodeDataMessage(t);if(!o)return;const c=Dt.fromBinary(o);if(c.sequence>0&&""!==c.participantSid){const e=this.reliableReceivedState.get(c.participantSid);if(e&&c.sequence<=e)return;this.reliableReceivedState.set(c.participantSid,c.sequence)}if("speaker"===(null===(n=c.value)||void 0===n?void 0:n.case))this.emit(e.EngineEvent.ActiveSpeakersUpdate,c.value.value.speakers);else if("encryptedPacket"===(null===(i=c.value)||void 0===i?void 0:i.case)){if(!this.e2eeManager)return void this.log.error("Received encrypted packet but E2EE not set up");const t=yield null===(r=this.e2eeManager)||void 0===r?void 0:r.handleEncryptedData(c.value.value.encryptedValue,c.value.value.iv,c.participantIdentity,c.value.value.keyIndex),n=Nt.fromBinary(t.payload),i=new Dt({value:n.value,participantIdentity:c.participantIdentity,participantSid:c.participantSid});"user"===(null===(s=i.value)||void 0===s?void 0:s.case)&&kl(i,i.value.value),this.emit(e.EngineEvent.DataPacketReceived,i,c.value.value.encryptionType)}else"user"===(null===(a=c.value)||void 0===a?void 0:a.case)&&kl(c,c.value.value),this.emit(e.EngineEvent.DataPacketReceived,c,ft.NONE)}finally{o()}})),this.handleDataTrackMessage=e=>pr(this,void 0,void 0,(function*(){const t=yield this.decodeDataMessage(e);t&&this.emit("dataTrackPacketReceived",t)})),this.handleDataError=e=>{if(this._isClosed)return;const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if("undefined"!=typeof RTCErrorEvent&&e instanceof RTCErrorEvent&&e.error){const n=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(n.message),{error:n,errorDetail:n.errorDetail,sctpCauseCode:n.sctpCauseCode})}else this.log.error("Unknown DataChannel error on ".concat(t),{event:e})},this.handleDataChannelClose=e=>()=>{var t;this._isClosed||"connected"!==(null===(t=this.pcManager)||void 0===t?void 0:t.publisher.getConnectionState())||this.log.error("publisher data channel '".concat(xd[e],"' closed unexpectedly"),this.logContext)},this.handleDisconnect=(t,n)=>{if(this._isClosed)return;this.log.warn("".concat(t," disconnected")),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const i=t=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(t,"ms. giving up")),this.emit(e.EngineEvent.Disconnected),this.close("gave up reconnecting after ".concat(this.reconnectAttempts," attempts, ").concat(t,"ms"))},r=Date.now()-this.reconnectStart;let s=this.getNextRetryDelay({elapsedMs:r,retryCount:this.reconnectAttempts});null!==s?(t===gl&&(s=0),this.log.debug("reconnecting in ".concat(s,"ms")),this.clearReconnectTimeout(),this.token&&this.emit(e.EngineEvent.TokenRefreshed,this.token),this.reconnectTimeout=ia.setTimeout((()=>this.attemptReconnect(n).finally((()=>this.reconnectTimeout=void 0))),s)):i(r)},this.waitForRestarted=()=>new Promise(((t,n)=>{this.pcState===vl.Connected&&t();const i=()=>{this.off(e.EngineEvent.Disconnected,r),t()},r=()=>{this.off(e.EngineEvent.Restarted,i),n()};this.once(e.EngineEvent.Restarted,i),this.once(e.EngineEvent.Disconnected,r)})),this.onRtpMapAvailable=t=>{const n=new Map;t.forEach((e=>{const t=e.codec.toLowerCase();So(t)&&n.set(e.payload,t)})),this.emit(e.EngineEvent.RTPVideoMapUpdate,n)},this.handleBrowserOnLine=()=>pr(this,void 0,void 0,(function*(){if(!this.url)return;(yield fetch(Co(this.url),{method:"HEAD"}).then((e=>e.ok)).catch((()=>!1)))&&(this.log.info("detected network reconnected"),(this.client.currentState===td.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===td.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(at.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))})),this.handleBrowserOffline=()=>pr(this,void 0,void 0,(function*(){if(this.url)try{yield Promise.race([fetch(Co(this.url),{method:"HEAD"}),qa(4e3).then((()=>Promise.reject()))])}catch(n){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}})),this.log=or(null!==(i=t.loggerName)&&void 0!==i?i:e.LoggerNames.Engine,(()=>this.logContext)),this.loggerOptions={loggerName:t.loggerName,loggerContextCb:()=>this.logContext},this.client=new nd(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new r,this.dataProcessLock=new r,this.dataChannels=new Gd({isEngineClosed:()=>this.isClosed,isReconnecting:()=>this.attemptingReconnect,onDataMessage:e=>this.handleDataMessage(e),onDataTrackMessage:e=>this.handleDataTrackMessage(e),onDataError:e=>this.handleDataError(e),onChannelClose:e=>this.handleDataChannelClose(e)(),onBufferStatusChanged:(t,n)=>this.emit(e.EngineEvent.DCBufferStatusChanged,n,t)}),this.client.onParticipantUpdate=t=>this.emit(e.EngineEvent.ParticipantUpdate,t),this.client.onConnectionQuality=t=>{this.handleLocalConnectionQuality(t),this.emit(e.EngineEvent.ConnectionQualityUpdate,t)},this.client.onRoomUpdate=t=>this.emit(e.EngineEvent.RoomUpdate,t),this.client.onSubscriptionError=t=>this.emit(e.EngineEvent.SubscriptionError,t),this.client.onSubscriptionPermissionUpdate=t=>this.emit(e.EngineEvent.SubscriptionPermissionUpdate,t),this.client.onSpeakersChanged=t=>this.emit(e.EngineEvent.SpeakersChanged,t),this.client.onStreamStateUpdate=t=>this.emit(e.EngineEvent.StreamStateChanged,t),this.client.onRequestResponse=t=>this.emit(e.EngineEvent.SignalRequestResponse,t),this.client.onParticipantUpdate=t=>this.emit(e.EngineEvent.ParticipantUpdate,t),this.client.onJoined=t=>this.emit(e.EngineEvent.Joined,t)}get logContext(){var e,t,n,i,r,s;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(i=null===(n=this.latestJoinResponse)||void 0===n?void 0:n.room)||void 0===i?void 0:i.sid,participant:null===(s=null===(r=this.latestJoinResponse)||void 0===r?void 0:r.participant)||void 0===s?void 0:s.identity,participantID:this.participantSid}}join(t,i,r,s){return pr(this,arguments,void 0,(function(t,i,r,s){var a=this;let o=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){var c,d,l;a._isNewlyCreated=!1,a.url=t,a.token=i,a.signalOpts=r,a.maxJoinAttempts=r.maxRetries;try{a.joinAttempts+=1,a.setupSignalClientCallbacks();const n=!o&&Fo()&&!Ya();let u;if(n){a.pcManager||(yield a.configure(),a.applyInitialPublisherLayout());const e=yield null===(c=a.pcManager)||void 0===c?void 0:c.publisher.createInitialOffer();e&&(u=rd(e.offer,e.offerId))}if(null==s?void 0:s.aborted)throw zs.cancelled("Connection aborted");if(!o&&a.shouldFailOnV1Path)throw a.shouldFailOnV1Path=!1,zs.serviceNotFound("Simulated v1 path failure","v0-rtc");const h=yield a.client.join(t,i,r,s,o,u);a._isClosed=!1,a.latestJoinResponse=h,a.participantSid=null===(d=h.participant)||void 0===d?void 0:d.sid,a.subscriberPrimary=h.subscriberPrimary,n?null===(l=a.pcManager)||void 0===l||l.updateConfiguration(a.makeRTCConfiguration(h)):(a.pcManager||(yield a.configure(h,!o),o||a.applyInitialPublisherLayout()),a.subscriberPrimary&&!h.fastPublish||a.negotiate().catch((e=>{a.log.error(e)}))),a.registerOnLineListener(),a.clientConfiguration=h.clientConfiguration,a.emit(e.EngineEvent.SignalConnected,h);let p=h.serverInfo;return p||(p={version:h.serverVersion,region:h.serverRegion}),a.log.info("connected to Livekit Server ".concat(Object.entries(p).map((e=>{let t=F(e,2),n=t[0],i=t[1];return"".concat(n,": ").concat(i)})).join(", "))),{joinResponse:h,serverInfo:p}}catch(n){if(n instanceof zs)if(n.reason===e.ConnectionErrorReason.ServerUnreachable){if(a.log.warn("Couldn't connect to server, attempt ".concat(a.joinAttempts," of ").concat(a.maxJoinAttempts)),a.joinAttempts<a.maxJoinAttempts)return a.join(t,i,r,s,o)}else if(n.reason===e.ConnectionErrorReason.ServiceNotFound)return a.log.warn("Initial connection failed: ".concat(n.message," – Retrying")),a.pcManager&&(a.pcManager.onStateChange=void 0,yield a.cleanupPeerConnections()),a.join(t,i,r,s,!0);throw n}}()}))}close(t){return pr(this,void 0,void 0,(function*(){const n=yield this.closingLock.lock();if(this.isClosed)n();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(e.EngineEvent.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.clearLostQualityTimeout(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient(t)}finally{n()}}))}cleanupPeerConnections(){return pr(this,void 0,void 0,(function*(){var e;this.dataChannels.teardown(),yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0,this.transportConnectingSince=void 0,this.reliableReceivedState.clear()}))}cleanupLossyDataStats(){this.lossyChannel.stopThresholdTuning()}cleanupClient(e){return pr(this,void 0,void 0,(function*(){yield this.client.close(!0,e),this.client.resetCallbacks();for(const e of Object.keys(this.pendingTrackResolvers))this.pendingTrackResolvers[e].reject();this.pendingTrackResolvers={}}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Js("a track with the same ID has already been published");return new Promise(((t,n)=>{const i=ia.setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],n(zs.timeout("publication of local track timed out, no response from server"))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{ia.clearTimeout(i),t(e)},reject:()=>{ia.clearTimeout(i),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const t=this.pendingTrackResolvers[e.track.id].reject;t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(n){this.log.warn("failed to remove track",{error:n})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.dataChannelForKind(xd.RELIABLE,!0))||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return pr(this,void 0,void 0,(function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()}))}setRegionStrategy(e){this.regionStrategy=e}configure(t,n){return pr(this,void 0,void 0,(function*(){var i;if(!this.pcManager||this.pcManager.currentState===Ld.NEW){if(t){this.participantSid=null===(i=t.participant)||void 0===i?void 0:i.sid;const e=this.makeRTCConfiguration(t);this.pcManager=new Ud(n?"publisher-only":t.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,e)}else{const e=this.makeRTCConfiguration();this.pcManager=new Ud("publisher-only",this.loggerOptions,e)}this.emit(e.EngineEvent.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,n,i)=>pr(this,void 0,void 0,(function*(){if(this.log.debug("primary PC state changed ".concat(t)),t===Ld.CONNECTING?this.transportConnectingSince=Date.now():this.transportConnectingSince=void 0,["closed","disconnected","failed"].includes(n)&&(this.publisherConnectionPromise=void 0),t===Ld.CONNECTED){const t=this.pcState===vl.New;this.pcState=vl.Connected,t&&this.emit(e.EngineEvent.Connected,this.latestJoinResponse)}else t===Ld.FAILED&&(this.pcState!==vl.Connected&&this.pcState!==vl.Reconnecting||(this.pcState=vl.Disconnected,this.handleDisconnect("peerconnection failed","failed"===i?at.RR_SUBSCRIBER_FAILED:at.RR_PUBLISHER_FAILED)));const r=this.client.isDisconnected||this.client.currentState===td.RECONNECTING,s=[Ld.FAILED,Ld.CLOSING,Ld.CLOSED].includes(t);r&&s&&!this._isClosed&&this.emit(e.EngineEvent.Offline)})),this.pcManager.onTrack=t=>{0!==t.streams.length&&this.emit(e.EngineEvent.MediaTrackAdded,t.track,t.streams[0],t.receiver)}}}))}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>pr(this,void 0,void 0,(function*(){this.pcManager&&(this.log.debug("received server answer",{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:n}),this.midToTrackId=n,yield this.pcManager.setPublisherAnswer(e,t))})),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",{candidate:e,target:t}),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,n)=>pr(this,void 0,void 0,(function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;const i=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);i&&this.client.sendAnswer(i,t)})),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",{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),{cid:e.cid});const n=this.pendingTrackResolvers[e.cid].resolve;delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=t=>{this.emit(e.EngineEvent.LocalTrackUnpublished,t)},this.client.onLocalTrackSubscribed=t=>{this.emit(e.EngineEvent.LocalTrackSubscribed,t)},this.client.onTokenRefresh=t=>{this.token=t,this.emit(e.EngineEvent.TokenRefreshed,t)},this.client.onRemoteMuteChanged=(t,n)=>{this.emit(e.EngineEvent.RemoteMute,t,n)},this.client.onSubscribedQualityUpdate=t=>{this.emit(e.EngineEvent.SubscribedQualityUpdate,t)},this.client.onRoomMoved=t=>{var n;this.participantSid=null===(n=t.participant)||void 0===n?void 0:n.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=t.room),this.emit(e.EngineEvent.RoomMoved,t)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=t=>{this.emit(e.EngineEvent.PublishDataTrackResponse,t)},this.client.onUnPublishDataTrackResponse=t=>{this.emit(e.EngineEvent.UnPublishDataTrackResponse,t)},this.client.onDataTrackSubscriberHandles=t=>{this.emit(e.EngineEvent.DataTrackSubscriberHandles,t)},this.client.onClose=()=>{this.handleDisconnect("signal",at.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=t=>{var n;switch(this.log.info("client leave request received (action=".concat(null==t?void 0:t.action,")"),{reason:null==t?void 0:t.reason}),t.regions&&(this.log.debug("updating regions"),this.emit(e.EngineEvent.ServerRegionsReported,t.regions)),t.action){case gi.DISCONNECT:this.emit(e.EngineEvent.Disconnected,null==t?void 0:t.reason),this.close("server leave: ".concat(null!==(n=st[t.reason])&&void 0!==n?n:t.reason));break;case gi.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(gl);break;case gi.RESUME:this.handleDisconnect(gl)}}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if(((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)||this.frameMetadataWorker&&!rc())&&Xo()&&(this.log.debug("E2EE - setting up transports with insertable streams"),n.encodedInsertableStreams=!0),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",!e)return n;if(e.iceServers&&!n.iceServers){const t=[];e.iceServers.forEach((e=>{const n={urls:e.urls};e.username&&(n.username=e.username),e.credential&&(n.credential=e.credential),t.push(n)})),n.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===rt.ENABLED&&(n.iceTransportPolicy="relay"),n}applyInitialPublisherLayout(){this.createDataChannels(),io()||this.addMediaSections(3,3)}addMediaSections(e,t){var n,i,r;const s={direction:"recvonly"};for(let o=0;o<e;o++)null===(n=this.pcManager)||void 0===n||n.addPublisherTransceiverOfKind("audio",s);const a="publisher-only"===(null===(i=this.pcManager)||void 0===i?void 0:i.mode);for(let o=0;o<t;o++){const e=null===(r=this.pcManager)||void 0===r?void 0:r.addPublisherTransceiverOfKind("video",s);if(a&&e){const t=Ga(e);this.log.debug("dependency descriptor negotiated for received video",{negotiated:t})}}}createDataChannels(){this.pcManager&&this.dataChannels.createPublisherChannels(this.pcManager)}decodeDataMessage(e){return pr(this,void 0,void 0,(function*(){return e.data instanceof ArrayBuffer?new Uint8Array(e.data):e.data instanceof Blob?new Uint8Array(yield e.data.arrayBuffer()):void this.log.error("unsupported data type",{data:e.data})}))}createSender(e,t,n){return pr(this,void 0,void 0,(function*(){let i;if(Va())i=yield this.createTransceiverRTCRtpSender(e,t,n);else{if(!Wa())throw new Ys("Required webRTC APIs not supported on this device");this.log.warn("using add-track fallback"),i=yield this.createRTCRtpSender(e.mediaStreamTrack)}return this.setupFrameMetadataSender(i,t),i}))}createSimulcastSender(e,t,n,i){return pr(this,void 0,void 0,(function*(){let r;if(Va())r=yield this.createSimulcastTransceiverSender(e,t,n,i);else{if(!Wa())throw new Ys("Cannot stream on this device");this.log.debug("using add-track fallback"),r=yield this.createRTCRtpSender(e.mediaStreamTrack)}return r&&this.setupFrameMetadataSender(r,n),r}))}get frameMetadataWorker(){var e,t;return null===(t=null!==(e=this.options.frameMetadata)&&void 0!==e?e:this.options.packetTrailer)||void 0===t?void 0:t.worker}setupFrameMetadataSender(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n,i,r;const s=this.frameMetadataWorker;if(!s||(null===(n=this.signalOpts)||void 0===n?void 0:n.e2eeEnabled))return;const a=null!==(i=t.frameMetadata)&&void 0!==i?i:t.packetTrailer,o=ac(a);if(rc())return void(o&&(e.transform=new RTCRtpScriptTransform(s,{kind:"encode",packetTrailer:a})));if(!sc(null!==(r=this.options.frameMetadata)&&void 0!==r?r:this.options.packetTrailer)||!("createEncodedStreams"in e))return void(o&&this.log.warn("frame metadata transform not supported; skipping write",this.logContext));const c=e.createEncodedStreams(),d=c.readable,l=c.writable;o?s.postMessage({kind:"encode",data:{readableStream:d,writableStream:l,packetTrailer:a}},[d,l]):d.pipeTo(l)}createTransceiverRTCRtpSender(e,t,n){return pr(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Ys("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),Mo(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:i};n&&(r.sendEncodings=n);return(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender}))}createSimulcastTransceiverSender(e,t,n,i){return pr(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Ys("publisher is closed");const r={direction:"sendonly"};i&&(r.sendEncodings=i);const s=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return yield e.setSimulcastTrackSender(n.videoCodec,s.sender),s.sender}))}createRTCRtpSender(e){return pr(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Ys("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}handleLocalConnectionQuality(e){if(!this.participantSid)return;const t=e.updates.find((e=>e.participantSid===this.participantSid));t&&(t.quality===it.LOST?this.scheduleLostQualityReconnect():this.clearLostQualityTimeout())}scheduleLostQualityReconnect(){this.lostQualityTimeout||(this.lostQualityTimeout=ia.setTimeout((()=>{this.lostQualityTimeout=void 0,this._isClosed||this.pcState!==vl.Connected||this.attemptingReconnect||this.hasActivePublisherSenders()&&(this.log.warn("local connection quality lost while publishing, triggering full reconnect",this.logContext),this.fullReconnectOnNext=!0,this.handleDisconnect("connection quality lost",at.RR_PUBLISHER_FAILED))}),1e4))}clearLostQualityTimeout(){this.lostQualityTimeout&&(ia.clearTimeout(this.lostQualityTimeout),this.lostQualityTimeout=void 0)}hasActivePublisherSenders(){var e,t;return null!==(t=null===(e=this.pcManager)||void 0===e?void 0:e.publisher.getSenders().some((e=>!!e.track&&"live"===e.track.readyState)))&&void 0!==t&&t}reconnect(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:at.RR_UNKNOWN;this.fullReconnectOnNext=!0,this.handleDisconnect("reconcile",e)}attemptReconnect(t){return pr(this,void 0,void 0,(function*(){var i,r,s;if(this._isClosed)return;if(this.attemptingReconnect)return void this.log.warn("already attempting reconnect, returning early");this.clearLostQualityTimeout(),(null===(i=this.clientConfiguration)||void 0===i?void 0:i.resumeConnection)!==rt.DISABLED&&(null!==(s=null===(r=this.pcManager)||void 0===r?void 0:r.currentState)&&void 0!==s?s:Ld.NEW)!==Ld.NEW||(this.fullReconnectOnNext=!0);const a=this.fullReconnectOnNext;this.fullReconnectOnNext=!1;let o=!1;try{this.attemptingReconnect=!0,a?yield this.restartConnection():yield this.resumeConnection(t),this.clearPendingReconnect(),o=!0}catch(n){this.reconnectAttempts+=1;let i=!0;n instanceof Ys?(this.log.debug("received unrecoverable error",{error:n}),i=!1):!a&&n instanceof na||(this.fullReconnectOnNext=!0),i?this.handleDisconnect("reconnect",at.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(e.EngineEvent.Disconnected),yield this.close("gave up reconnecting after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms")))}finally{this.attemptingReconnect=!1,o&&this.fullReconnectOnNext&&!this._isClosed&&(this.log.debug("full reconnect requested during in-progress attempt, dispatching"),this.handleDisconnect("reconnect"))}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(n){this.log.warn("encountered error in reconnect policy",{error:n})}return null}restartConnection(t){return pr(this,void 0,void 0,(function*(){var i,r,s;try{if(!this.url||!this.token)throw new Ys("could not reconnect, url or token not saved");let r;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(e.EngineEvent.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"),new na;r=(yield this.join(null!=t?t:this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(n){if(n instanceof zs&&n.reason===e.ConnectionErrorReason.NotAllowed)throw new Ys("could not reconnect, token might be expired");throw new na}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(e.EngineEvent.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==td.CONNECTED)throw new na("Signal connection got severed during reconnect");null===(i=this.regionStrategy)||void 0===i||i.resetAttempts(),this.emit(e.EngineEvent.Restarted)}catch(a){const e=yield null===(r=this.regionStrategy)||void 0===r?void 0:r.getNextUrl();if(e)return void(yield this.restartConnection(e));throw null===(s=this.regionStrategy)||void 0===s||s.resetAttempts(),a}}))}resumeConnection(t){return pr(this,void 0,void 0,(function*(){if(!this.url||!this.token)throw new Ys("could not reconnect, url or token not saved");if(!this.pcManager)throw new Ys("publisher and subscriber connections unset");let n;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(e.EngineEvent.Resuming);try{this.setupSignalClientCallbacks(),n=yield this.client.reconnect(this.url,this.token,this.participantSid,t)}catch(r){let t="";if(r instanceof Error&&(t=r.message,this.log.error(r.message,{error:r})),r instanceof zs&&r.reason===e.ConnectionErrorReason.NotAllowed)throw new Ys("could not reconnect, token might be expired");if(r instanceof zs&&r.reason===e.ConnectionErrorReason.LeaveRequest)throw r;throw new na(t)}if(this.emit(e.EngineEvent.SignalResumed),n){const e=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=n.serverInfo)}else this.log.warn("Did not receive reconnect response");if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==td.CONNECTED)throw new na("Signal connection got severed during reconnect");this.client.setReconnected();const i=this.dataChannelForKind(xd.RELIABLE);"open"===(null==i?void 0:i.readyState)&&null===i.id&&this.createDataChannels(),(null==n?void 0:n.lastMessageSeq)&&this.resendReliableMessagesForResume(n.lastMessageSeq).catch((e=>{this.log.warn("failed to resend reliable messages after resume",Object.assign(Object.assign({},this.logContext),{error:e}))})),this.emit(e.EngineEvent.Resumed)}))}waitForPCInitialConnection(e,t){return pr(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Ys("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)}))}waitForPCReconnected(){return pr(this,void 0,void 0,(function*(){this.pcState=vl.Reconnecting,this.log.debug("waiting for peer connection to reconnect");try{if(yield qa(2e3),!this.pcManager)throw new Ys("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=vl.Connected}catch(n){throw this.pcState=vl.Disconnected,zs.internal("could not establish PC connection, ".concat(n.message))}}))}publishRpcAck(e,t){return pr(this,void 0,void 0,(function*(){const n=new Dt({destinationIdentities:[e],kind:Ot.RELIABLE,value:{case:"rpcAck",value:new Wt({requestId:t})}});yield this.sendDataPacket(n,xd.RELIABLE)}))}sendDataPacket(e,t){return pr(this,void 0,void 0,(function*(){var n,i;if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const t=tc(e);if(t){const n=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:"encryptedPacket",value:new At({encryptedValue:n.payload,iv:n.iv,keyIndex:n.keyIndex})}}}t===xd.RELIABLE&&(e.sequence=this.reliableChannel.nextSequence());const r=e.toBinary(),s=Math.min(null!==(i=null===(n=this.pcManager)||void 0===n?void 0:n.getMaxPublisherMessageSize())&&void 0!==i?i:64e3,64e3);if(void 0!==s&&0!==s&&r.byteLength>s)throw new Zs("cannot publish data packet larger than ".concat(s," bytes (got ").concat(r.byteLength,")"));t===xd.RELIABLE?yield this.reliableChannel.send(r,e.sequence):yield this.lossyChannel.send(r)}))}sendDataTrackFrame(e){return pr(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(xd.DATA_TRACK_LOSSY),yield this.dataTrackChannel.send(e)}))}resendReliableMessagesForResume(e){return pr(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(xd.RELIABLE),yield this.reliableChannel.replay(e)}))}flowControlFor(e){return this.dataChannels.channelFor(e)}waitForBufferHeadroom(e){return pr(this,void 0,void 0,(function*(){return this.flowControlFor(e).waitForHeadroomWithLock()}))}ensureDataTransportConnected(e){return pr(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var i;if(!t.pcManager)throw new Ys("PC manager is closed");const r=n?t.pcManager.subscriber:t.pcManager.publisher,s=n?"Subscriber":"Publisher";if(!r)throw zs.internal("".concat(s," connection not set"));let a=!1;n||t.dataChannelForKind(e,n)||(t.createDataChannels(),a=!0),a||n||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(a=!0),a&&t.negotiate().catch((e=>{t.log.error(e)}));const o=t.dataChannelForKind(e,n);if("open"===(null==o?void 0:o.readyState))return;const c=(new Date).getTime()+t.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(r.isICEConnected&&"open"===(null===(i=t.dataChannelForKind(e,n))||void 0===i?void 0:i.readyState))return;yield qa(50)}throw zs.internal("could not establish ".concat(s," connection, state: ").concat(r.getICEConnectionState()))}()}))}ensurePublisherConnected(e){return pr(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){if(!this.pcManager)return!1;const e=this.pcManager.currentState;return!![Ld.CONNECTING,Ld.CONNECTED].includes(e)&&(!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)&&(!(e===Ld.CONNECTING&&void 0!==this.transportConnectingSince&&Date.now()-this.transportConnectingSince>this.peerConnectionTimeout)||(this.log.warn("transport stuck in connecting state",this.logContext),!1)))}negotiate(){return pr(this,void 0,void 0,(function*(){return new _s(((t,i)=>pr(this,void 0,void 0,(function*(){if(!this.pcManager)return void i(new Xs("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.dataChannels.hasPublisherChannels||this.createDataChannels();const r=new AbortController,s=()=>{r.abort(),this.log.debug("engine disconnected while negotiation was ongoing"),t()};this.isClosed&&i(new Xs("cannot negotiate on closed engine")),this.on(e.EngineEvent.Closing,s),this.on(e.EngineEvent.Restarting,s),this.pcManager.publisher.off(Td,this.onRtpMapAvailable),this.pcManager.publisher.once(Td,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(r),t()}catch(n){if(r.signal.aborted)return void t();n instanceof Xs&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",at.RR_UNKNOWN),n instanceof Error?i(n):i(new Error(String(n)))}finally{this.off(e.EngineEvent.Closing,s),this.off(e.EngineEvent.Restarting,s)}}))))}))}dataChannelForKind(e,t){return this.dataChannels.getHandle(e,t)}sendSyncState(e,t,n){var i,r,s,a;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup");const o=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),d=null===(i=this.pcManager.subscriber)||void 0===i?void 0:i.getRemoteDescription(),l=null===(r=this.pcManager.subscriber)||void 0===r?void 0:r.getLocalDescription(),u=null===(a=null===(s=this.signalOpts)||void 0===s?void 0:s.autoSubscribe)||void 0===a||a,h=new Array,p=new Array;e.forEach((e=>{e.isDesired!==u&&h.push(e.trackSid),e.isEnabled||p.push(e.trackSid)})),this.client.sendSyncState(new Ai({answer:"publisher-only"===this.pcManager.mode?c?rd({sdp:c.sdp,type:c.type}):void 0:l?rd({sdp:l.sdp,type:l.type}):void 0,offer:"publisher-only"===this.pcManager.mode?o?rd({sdp:o.sdp,type:o.type}):void 0:d?rd({sdp:d.sdp,type:d.type}):void 0,subscription:new ri({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:Ma(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:p,datachannelReceiveStates:this.reliableReceivedState.map(((e,t)=>new Ni({publisherSid:t,lastSeq:e}))),publishDataTracks:n.map((e=>new Kn({info:Oc.toProtobuf(e)})))}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){const e=[],t=(t,n)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new Li({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(xd.LOSSY),Un.PUBLISHER),t(this.dataChannelForKind(xd.RELIABLE),Un.PUBLISHER),t(this.dataChannelForKind(xd.LOSSY,!0),Un.SUBSCRIBER),t(this.dataChannelForKind(xd.RELIABLE,!0),Un.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&ia.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){no()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){no()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const n=null===(t=this.pcManager)||void 0===t?void 0:t.getMidForReceiver(e);if(n){const e=Object.entries(this.midToTrackId).find((e=>F(e,1)[0]===n));if(e)return e[1]}}}function kl(e,t){const n=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=n,t.participantIdentity=n;const i=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=i,t.destinationIdentities=i}const yl=or(e.LoggerNames.Region),bl=5e3;class Tl{static fetchRegionSettings(e,t,i){return pr(this,void 0,void 0,(function*(){const r=yield Tl.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 n=e.get("Cache-Control");if(n){const e=null===(t=n.match(/(?:^|[,\s])max-age=(\d+)/))||void 0===t?void 0:t[1];if(e)return parseInt(e,10)}}(n.headers),t=e?1e3*e:bl;return{regionSettings:yield n.json(),updatedAtInMs:Date.now(),maxAgeInMs:t}}throw 401===n.status?zs.notAllowed("Could not fetch region settings: ".concat(n.statusText),n.status):zs.internal("Could not fetch region settings: ".concat(n.statusText))}catch(n){throw n instanceof zs?n:(null==i?void 0:i.aborted)?zs.cancelled("Region fetching was aborted"):zs.serverUnreachable("Could not fetch region settings, ".concat(n instanceof Error?"".concat(n.name,": ").concat(n.message):n))}finally{r()}}))}static scheduleRefetch(t,n,i){return pr(this,void 0,void 0,(function*(){const r=Tl.settingsTimeouts.get(t.hostname);clearTimeout(r),Tl.settingsTimeouts.set(t.hostname,setTimeout((()=>pr(this,void 0,void 0,(function*(){try{const e=yield Tl.fetchRegionSettings(t,n);Tl.updateCachedRegionSettings(t,n,e)}catch(r){if(r instanceof zs&&r.reason===e.ConnectionErrorReason.NotAllowed)return void yl.debug("token is not valid, cancelling auto region refresh");yl.debug("auto refetching of region settings failed",{error:r}),Tl.scheduleRefetch(t,n,i)}}))),i))}))}static updateCachedRegionSettings(e,t,n){Tl.cache.set(e.hostname,n),Tl.scheduleRefetch(e,t,n.maxAgeInMs)}static stopRefetch(e){const t=Tl.settingsTimeouts.get(e);t&&(clearTimeout(t),Tl.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=Tl.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout((()=>{const t=Tl.connectionTrackers.get(e);t&&0===t.connectionCount&&(yl.debug("stopping region refetch after disconnect delay",{hostname:e}),Tl.stopRefetch(e)),t&&(t.cleanupTimeout=void 0)}),3e4))}static cancelCleanup(e){const t=Tl.connectionTrackers.get(e);(null==t?void 0:t.cleanupTimeout)&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=Tl.connectionTrackers.get(e);t||(t={connectionCount:0},Tl.connectionTrackers.set(e,t)),t.connectionCount++,Tl.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=Tl.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),0===t.connectionCount&&Tl.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){var t;this.token=e;const n=this.getServerUrl(),i=Tl.cache.get(n.hostname);Tl.scheduleRefetch(this.serverUrl,this.token,null!==(t=null==i?void 0:i.maxAgeInMs)&&void 0!==t?t:bl)}isCloud(){return ro(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return pr(this,void 0,void 0,(function*(){return Tl.fetchRegionSettings(this.serverUrl,this.token,e)}))}getNextBestRegionUrl(e){return pr(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=Tl.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),Tl.updateCachedRegionSettings(this.serverUrl,this.token,t));const n=t.regionSettings.regions.filter((e=>!this.attemptedRegions.find((t=>t.url===e.url))));if(n.length>0){const e=n[0];return this.attemptedRegions.push(e),yl.info("switching to region: ".concat(e.region),{region:e.region}),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){Tl.updateCachedRegionSettings(this.serverUrl,this.token,e)}}function Sl(){return new CompressionStream("deflate-raw")}function El(){return new DecompressionStream("deflate-raw")}function Cl(e,t){return pr(this,void 0,void 0,(function*(){const n=new DecompressionStream("deflate-raw"),i=n.writable.getWriter();return i.write(e).catch((()=>{})),i.close().catch((()=>{})),wl(n.readable,t)}))}function wl(t,n){return pr(this,void 0,void 0,(function*(){const i=t.getReader(),r=[];let s=0;for(;;){const t=yield i.read(),a=t.done,o=t.value;if(a)break;if(r.push(o),s+=o.byteLength,"number"==typeof n&&s>n)throw yield i.cancel(),new ta("Decompressed payload exceeds the maximum payload size of ".concat(n," bytes"),e.DataStreamErrorReason.PayloadTooLarge)}const a=new Uint8Array(s);let o=0;for(const e of r)a.set(e,o),o+=e.byteLength;return a}))}Tl.cache=new Map,Tl.settingsTimeouts=new Map,Tl.connectionTrackers=new Map,Tl.fetchLock=new r;const Rl=15e3;class Pl{get info(){return this._info}validateBytesReceived(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if("number"==typeof this.totalByteSize&&0!==this.totalByteSize){if(t&&this.bytesReceived<this.totalByteSize)throw new ta("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),e.DataStreamErrorReason.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new ta("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),e.DataStreamErrorReason.LengthExceeded)}}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}}class Il extends Pl{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,n)}[Symbol.asyncIterator](){const e=this.reader.getReader();e.closed.catch((()=>{}));const t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>pr(this,void 0,void 0,(function*(){var n;try{const t=this.signal;if(null==t?void 0:t.aborted)throw t.reason;const i=yield new Promise(((n,i)=>{if(t){const r=()=>i(t.reason);t.addEventListener("abort",r,{once:!0}),e.read().then(n,i).finally((()=>{t.removeEventListener("abort",r)}))}else e.read().then(n,i)}));return i.done?(this.validateBytesReceived(!0),"number"==typeof this.totalByteSize&&(null===(n=this.onProgress)||void 0===n||n.call(this,1)),{done:!0,value:void 0}):(this.handleChunkReceived(i.value),{done:!1,value:i.value.content})}catch(i){throw t(),i}})),return(){return pr(this,void 0,void 0,(function*(){return t(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return pr(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var n,i,r,s;let a=new Set;const o=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=fr(o);!(n=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;a.add(e)}}catch(u){i={error:u}}finally{try{d||n||!(r=l.return)||(yield r.call(l))}finally{if(i)throw i.error}}return Array.from(a)}()}))}}class _l extends Pl{constructor(e,t,n){super(e,t,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=Ro(e.chunkIndex),i=this.receivedChunks.get(n);if(i&&i.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,r)}[Symbol.asyncIterator](){const t=this.reader.getReader();t.closed.catch((()=>{}));const n=new TextDecoder("utf-8"),i=this.signal,r=()=>{t.releaseLock(),this.signal=void 0};return{next:()=>pr(this,void 0,void 0,(function*(){var s;try{if(null==i?void 0:i.aborted)throw i.reason;const r=yield new Promise(((e,n)=>{if(i){const r=()=>n(i.reason);i.addEventListener("abort",r,{once:!0}),t.read().then(e,n).finally((()=>{i.removeEventListener("abort",r)}))}else t.read().then(e,n)}));if(r.done)return this.validateBytesReceived(!0),"number"==typeof this.totalByteSize&&(null===(s=this.onProgress)||void 0===s||s.call(this,1)),{done:!0,value:void 0};{let t;this.handleChunkReceived(r.value);try{t=n.decode(r.value.content)}catch(a){throw new ta("Cannot decode datastream chunk ".concat(r.value.chunkIndex," as text: ").concat(a),e.DataStreamErrorReason.DecodeFailed)}return{done:!1,value:t}}}catch(a){throw r(),a}})),return(){return pr(this,void 0,void 0,(function*(){return r(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return pr(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var n,i,r,s;let a="";const o=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=fr(o);!(n=(c=yield l.next()).done);d=!0){s=c.value,d=!1;a+=s}}catch(u){i={error:u}}finally{try{d||n||!(r=l.return)||(yield r.call(l))}finally{if(i)throw i.error}}return a}()}))}}class Ml{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:5e9;this.log=sr,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[],this.maxPayloadByteLength=e}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){const e=this.bufferedPackets;this.bufferedPackets=[];for(const t of e){const e=t.packet,n=t.encryptionType;this.handleDataStreamPacket(e,n)}}registerTextStreamHandler(t,n){if(this.textStreamHandlers.has(t))throw new ta('A text stream handler for topic "'.concat(t,'" has already been set.'),e.DataStreamErrorReason.HandlerAlreadyRegistered);this.textStreamHandlers.set(t,n)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(t,n){if(this.byteStreamHandlers.has(t))throw new ta('A byte stream handler for topic "'.concat(t,'" has already been set.'),e.DataStreamErrorReason.HandlerAlreadyRegistered);this.byteStreamHandlers.set(t,n)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(t){const n=Array.from(this.textStreamControllers.entries()).filter((e=>e[1].sendingParticipantIdentity===t)),i=Array.from(this.byteStreamControllers.entries()).filter((e=>e[1].sendingParticipantIdentity===t));if(n.length>0||i.length>0){const a=new ta("Participant ".concat(t," unexpectedly disconnected in the middle of sending data"),e.DataStreamErrorReason.AbnormalEnd);for(const e of i){var r=F(e,2);const t=r[0];r[1].controller.error(a),this.byteStreamControllers.delete(t)}for(const e of n){var s=F(e,2);const t=s[0];s[1].controller.error(a),this.textStreamControllers.delete(t)}}}handleDataStreamPacket(e,t){if(this.isConnected)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!'))}else this.bufferedPackets.push({packet:e,encryptionType:t})}handleStreamHeader(t,n,i){var r;switch(t.contentHeader.case){case"byteHeader":{const s=this.byteStreamHandlers.get(t.topic);if(!s)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",t.topic);let a;const o={id:t.streamId,name:null!==(r=t.contentHeader.value.name)&&void 0!==r?r:"unknown",mimeType:t.mimeType,size:t.totalLength?Number(t.totalLength):void 0,topic:t.topic,timestamp:Ro(t.timestamp),attributes:t.attributes,encryptionType:i};let c;switch(t.compression){case rn.DEFLATE_RAW:if(!Fo())return void sr.warn("Data stream ".concat(t.streamId," received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping..."));c=!0;break;case rn.NONE:c=!1;break;default:return void sr.warn("Data stream ".concat(t.streamId," received with unknown compression type ").concat(t.compression,", dropping..."))}const d=t.inlineContent;if(void 0!==d)return void s(new Il(o,Dl(t.streamId,c?Cl(d,this.maxPayloadByteLength):d),Ro(t.totalLength)),{identity:n});const l=new ReadableStream({start:i=>{if(a=i,this.byteStreamControllers.has(t.streamId))throw new ta("A data stream read is already in progress for a stream with id ".concat(t.streamId,"."),e.DataStreamErrorReason.AlreadyOpened);this.byteStreamControllers.set(t.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:n})}});return void s(new Il(o,c?function(e,t,n){return e.pipeThrough(Ol(t)).pipeThrough(Al()).pipeThrough(El()).pipeThrough(Nl(t,n)).pipeThrough(function(e){let t=0;return new TransformStream({transform:(n,i)=>{n.byteLength>0&&(i.enqueue(new cn({streamId:e,chunkIndex:Po(t),content:n})),t+=1)}})}(t))}(l,t.streamId,this.maxPayloadByteLength):l,Ro(t.totalLength)),{identity:n})}case"textHeader":{const r=this.textStreamHandlers.get(t.topic);if(!r)return void this.log.debug("ignoring incoming text stream due to no handler for topic",t.topic);let s;const a={id:t.streamId,mimeType:t.mimeType,size:t.totalLength?Number(t.totalLength):void 0,topic:t.topic,timestamp:Number(t.timestamp),attributes:t.attributes,encryptionType:i,attachedStreamIds:t.contentHeader.value.attachedStreamIds};let o;switch(t.compression){case rn.DEFLATE_RAW:if(!Fo())return void sr.warn("Data stream ".concat(t.streamId," received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping..."));o=!0;break;case rn.NONE:o=!1;break;default:return void sr.warn("Data stream ".concat(t.streamId," received with unknown compression type ").concat(t.compression,", dropping..."))}const c=t.inlineContent;if(void 0!==c){const e=o?Cl(c,this.maxPayloadByteLength):c;return void r(new _l(a,Dl(t.streamId,e),Ro(t.totalLength)),{identity:n})}const d=new ReadableStream({start:i=>{if(s=i,this.textStreamControllers.has(t.streamId))throw new ta("A data stream read is already in progress for a stream with id ".concat(t.streamId,"."),e.DataStreamErrorReason.AlreadyOpened);this.textStreamControllers.set(t.streamId,{info:a,controller:s,startTime:Date.now(),sendingParticipantIdentity:n})}});return void r(new _l(a,o?function(t,n,i){return t.pipeThrough(Ol(n)).pipeThrough(Al()).pipeThrough(El()).pipeThrough(Nl(n,i)).pipeThrough(function(t){const n=new TextDecoder("utf-8"),i=new TextEncoder;let r=0;const s=i=>{try{return i?n.decode(i,{stream:!0}):n.decode()}catch(r){throw new ta("Cannot decode compressed data stream ".concat(t," as text: ").concat(r),e.DataStreamErrorReason.DecodeFailed)}};return new TransformStream({transform:(e,n)=>{const a=s(e);a.length>0&&(n.enqueue(new cn({streamId:t,chunkIndex:Po(r),content:i.encode(a)})),r+=1)},flush:e=>{const n=s();n.length>0&&(e.enqueue(new cn({streamId:t,chunkIndex:Po(r),content:i.encode(n)})),r+=1)}})}(n))}(d,t.streamId,this.maxPayloadByteLength):d,Ro(t.totalLength)),{identity:n})}}}handleStreamChunk(t,n){const i=this.byteStreamControllers.get(t.streamId);i&&(i.info.encryptionType!==n?(i.controller.error(new ta("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)),this.byteStreamControllers.delete(t.streamId)):t.content.length>0&&i.controller.enqueue(t));const r=this.textStreamControllers.get(t.streamId);r&&(r.info.encryptionType!==n?(r.controller.error(new ta("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(r.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)),this.textStreamControllers.delete(t.streamId)):t.content.length>0&&r.controller.enqueue(t))}handleStreamTrailer(t,n){const i=this.textStreamControllers.get(t.streamId);i&&(i.info.encryptionType!==n?i.controller.error(new ta("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),t.attributes),t.reason?i.controller.error(new ta("Data stream ".concat(t.streamId," closed abnormally: ").concat(t.reason),e.DataStreamErrorReason.AbnormalEnd)):i.controller.close()),this.textStreamControllers.delete(t.streamId));const r=this.byteStreamControllers.get(t.streamId);r&&(r.info.encryptionType!==n?r.controller.error(new ta("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(r.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)):(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),t.attributes),t.reason?r.controller.error(new ta("Data stream ".concat(t.streamId," closed abnormally: ").concat(t.reason),e.DataStreamErrorReason.AbnormalEnd)):r.controller.close()),this.byteStreamControllers.delete(t.streamId))}}function Dl(e,t){return new ReadableStream({start:n=>pr(this,void 0,void 0,(function*(){try{const i=yield t;n.enqueue(new cn({streamId:e,chunkIndex:BigInt(0),content:i})),n.close()}catch(i){n.error(i)}}))})}function Ol(t){let n=-1;return new TransformStream({transform:(i,r)=>{const s=Ro(i.chunkIndex);if(s<=n)sr.warn("ignoring duplicate chunk ".concat(s," for compressed data stream ").concat(t," (last processed: ").concat(n,")"));else{if(s>n+1)throw new ta("Missing chunk(s) ".concat(n+1,"..").concat(s-1," for compressed data stream ").concat(t," - cannot continue decompressing"),e.DataStreamErrorReason.Incomplete);n=s,r.enqueue(i)}}})}function Al(){return new TransformStream({transform:(e,t)=>{t.enqueue(e.content)}})}function Nl(t,n){let i=0;return new TransformStream({transform:(r,s)=>{if(i+=r.byteLength,i>n)throw new ta("Data stream ".concat(t," exceeds the maximum payload size of ").concat(n," bytes"),e.DataStreamErrorReason.PayloadTooLarge);s.enqueue(r)}})}class Ll{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return pr(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 xl extends Ll{}class Ul extends Ll{}function Fl(e,t,n){var i;return new on({streamId:e.id,mimeType:e.mimeType,topic:e.topic,timestamp:Po(e.timestamp),totalLength:Po(e.size),attributes:e.attributes,compression:null!==(i=null==n?void 0:n.compression)&&void 0!==i?i:rn.NONE,inlineContent:null==n?void 0:n.inlineContent,contentHeader:{case:"textHeader",value:new sn({version:null==t?void 0:t.version,attachedStreamIds:e.attachedStreamIds,replyToStreamId:null==t?void 0:t.replyToStreamId,operationType:"update"===(null==t?void 0:t.type)?nn.UPDATE:nn.CREATE})}})}function Bl(e,t){var n;return new on({streamId:e.id,mimeType:e.mimeType,topic:e.topic,timestamp:Po(e.timestamp),totalLength:Po(e.size),attributes:e.attributes,compression:null!==(n=null==t?void 0:t.compression)&&void 0!==n?n:rn.NONE,inlineContent:null==t?void 0:t.inlineContent,contentHeader:{case:"byteHeader",value:new an({name:e.name})}})}function jl(e,t){return new Dt({destinationIdentities:t,value:{case:"streamHeader",value:e}})}const ql=new TextEncoder;class Vl{constructor(e,t,n,i,r){this.engine=e,this.log=t,this.getRemoteParticipantClientProtocol=n,this.getRemoteParticipantCapabilities=i,this.getAllRemoteParticipantIdentities=r}setupEngine(e){this.engine=e}sendText(e,t){return pr(this,void 0,void 0,(function*(){var n,i,r,s,a;const o=crypto.randomUUID(),c=ql.encode(e),d=c.byteLength,l=null===(n=null==t?void 0:t.compress)||void 0===n||n;let u={id:o,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==t?void 0:t.topic)&&void 0!==i?i:"",size:d,attributes:null==t?void 0:t.attributes,encryptionType:(null===(r=this.engine.e2eeManager)||void 0===r?void 0:r.isDataChannelEncryptionEnabled)?ft.GCM:ft.NONE};let h=l&&Fo()&&this.allRecipientsSupportV2(null==t?void 0:t.destinationIdentities)&&this.allRecipientsSupportCompression(null==t?void 0:t.destinationIdentities)?Wl.fromStream(Uo(c).pipeThrough(Sl())):null;if((!(null==t?void 0:t.attachments)||0===t.attachments.length)&&this.allRecipientsSupportV2(null==t?void 0:t.destinationIdentities)){let e=c,n=rn.NONE;if(h){const t=yield h.collect();t.byteLength<c.byteLength&&(e=t,n=rn.DEFLATE_RAW)}const i=jl(Fl(u,void 0,{compression:n,inlineContent:e}),null==t?void 0:t.destinationIdentities);if(i.toBinary().byteLength<=Rl)return yield this.engine.sendDataPacket(i,xd.RELIABLE),null===(s=null==t?void 0:t.onProgress)||void 0===s||s.call(t,1),u}const p=null===(a=null==t?void 0:t.attachments)||void 0===a?void 0:a.map((()=>crypto.randomUUID())),m=p?p.length+1:1,g=new Array(m).fill(0),v=(e,n)=>{var i;g[n]=e,null===(i=null==t?void 0:t.onProgress)||void 0===i||i.call(t,g.reduce(((e,t)=>e+t),0)/m)};if(h){u.attachedStreamIds=p;const e=jl(Fl(u,void 0,{compression:rn.DEFLATE_RAW}),null==t?void 0:t.destinationIdentities);yield this.sendChunkedByteStream(e,o,null==t?void 0:t.destinationIdentities,h.stream().pipeThrough(Hl(c.length,(e=>v(e,0))))),0===c.length&&v(1,0)}else{const n=yield this.streamText({streamId:o,totalSize:d,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:p,attributes:null==t?void 0:t.attributes});yield n.write(e),v(1,0),yield n.close(),u=n.info}return(null==t?void 0:t.attachments)&&p&&(yield Promise.all(t.attachments.map(((e,n)=>pr(this,void 0,void 0,(function*(){return this._sendFile(p[n],e,{topic:t.topic,mimeType:e.type,destinationIdentities:t.destinationIdentities,compress:t.compress,onProgress:e=>{v(e,n+1)}})})))))),u}))}sendBytes(e,t){return pr(this,void 0,void 0,(function*(){var n,i,r,s,a,o,c;const d=crypto.randomUUID(),l=null==t?void 0:t.destinationIdentities,u=null===(n=null==t?void 0:t.compress)||void 0===n||n,h={id:d,name:null!==(i=null==t?void 0:t.name)&&void 0!==i?i:"unknown",mimeType:null!==(r=null==t?void 0:t.mimeType)&&void 0!==r?r:"application/octet-stream",timestamp:Date.now(),topic:null!==(s=null==t?void 0:t.topic)&&void 0!==s?s:"",size:e.byteLength,attributes:null==t?void 0:t.attributes,encryptionType:(null===(a=this.engine.e2eeManager)||void 0===a?void 0:a.isDataChannelEncryptionEnabled)?ft.GCM:ft.NONE},p=Hl(e.length,null==t?void 0:t.onProgress);let m=u&&Fo()&&this.allRecipientsSupportV2(l)&&this.allRecipientsSupportCompression(l)?Wl.fromStream(Uo(e).pipeThrough(p).pipeThrough(Sl())):null;if(this.allRecipientsSupportV2(l)){let n=e,i=rn.NONE;if(m){const t=yield m.collect();t.byteLength<e.byteLength&&(n=t,i=rn.DEFLATE_RAW)}const r=jl(Bl(h,{compression:i,inlineContent:n}),l);if(r.toBinary().byteLength<=Rl)return yield this.engine.sendDataPacket(r,xd.RELIABLE),null===(o=null==t?void 0:t.onProgress)||void 0===o||o.call(t,1),h}const g=jl(Bl(h,{compression:m?rn.DEFLATE_RAW:rn.NONE}),l),v=m?m.stream():Uo(e).pipeThrough(p);return yield this.sendChunkedByteStream(g,d,l,v),0===e.length&&(null===(c=null==t?void 0:t.onProgress)||void 0===c||c.call(t,1)),h}))}allRecipientsSupportV2(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every((e=>this.getRemoteParticipantClientProtocol(e)>=2))}allRecipientsSupportCompression(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every((e=>this.getRemoteParticipantCapabilities(e).includes(Xt.CAP_COMPRESSION_DEFLATE_RAW)))}sendChunkedByteStream(e,t,n,i){return pr(this,void 0,void 0,(function*(){var r,s,a,o;const c=this.engine;yield Kl(c,e);let d=0;try{for(var l,u=!0,h=fr(function(e,t){return vr(this,arguments,(function*(){const n=e.getReader();let i=new Uint8Array(0);try{for(;;){const e=yield gr(n.read()),r=e.done,s=e.value;if(r)break;if(0===s.byteLength)continue;const a=new Uint8Array(i.byteLength+s.byteLength);for(a.set(i),a.set(s,i.byteLength),i=a;i.byteLength>=t;)yield yield gr(i.slice(0,t)),i=i.slice(t)}i.byteLength>0&&(yield yield gr(i))}finally{n.releaseLock()}}))}(i,Rl));!(r=(l=yield h.next()).done);u=!0){o=l.value,u=!1;const e=new Dt({destinationIdentities:n,value:{case:"streamChunk",value:new cn({content:o,streamId:t,chunkIndex:Po(d)})}});yield c.sendDataPacket(e,xd.RELIABLE),d+=1}}catch(p){s={error:p}}finally{try{u||r||!(a=h.return)||(yield a.call(h))}finally{if(s)throw s.error}}yield zl(t,n,c)}))}streamText(t){return pr(this,void 0,void 0,(function*(){var n,i,r;const s=null!==(n=null==t?void 0:t.streamId)&&void 0!==n?n:crypto.randomUUID(),a=null==t?void 0:t.destinationIdentities,o={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==t?void 0:t.topic)&&void 0!==i?i:"",size:null==t?void 0:t.totalSize,attributes:null==t?void 0:t.attributes,encryptionType:(null===(r=this.engine.e2eeManager)||void 0===r?void 0:r.isDataChannelEncryptionEnabled)?ft.GCM:ft.NONE,attachedStreamIds:null==t?void 0:t.attachedStreamIds},c=jl(Fl(o,t),a);yield Kl(this.engine,c);let d=0;const l=this.engine,u=new WritableStream({write(e){return pr(this,void 0,void 0,(function*(){for(const t of function(e,t){const n=[];let i=(new TextEncoder).encode(e);for(;i.length>t;){let e=t;for(;e>0;){const t=i[e];if(void 0!==t&&128!=(192&t))break;e--}n.push(i.slice(0,e)),i=i.slice(e)}return i.length>0&&n.push(i),n}(e,Rl)){const e=new cn({content:t,streamId:s,chunkIndex:Po(d)}),n=new Dt({destinationIdentities:a,value:{case:"streamChunk",value:e}});yield l.sendDataPacket(n,xd.RELIABLE),d+=1}}))},close(){return pr(this,void 0,void 0,(function*(){yield zl(s,a,l)}))},abort(e){console.log("Sink error:",e)}});let h=()=>pr(this,void 0,void 0,(function*(){yield p.close()}));l.once(e.EngineEvent.Closing,h);const p=new xl(u,o,(()=>this.engine.off(e.EngineEvent.Closing,h)));return p}))}sendFile(e,t){return pr(this,void 0,void 0,(function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}}))}_sendFile(e,t,n){return pr(this,void 0,void 0,(function*(){var i,r,s,a,o;const c=null==n?void 0:n.destinationIdentities,d=(null===(i=null==n?void 0:n.compress)||void 0===i||i)&&Fo()&&this.allRecipientsSupportV2(c)&&this.allRecipientsSupportCompression(c),l={id:e,name:t.name,mimeType:null!==(r=null==n?void 0:n.mimeType)&&void 0!==r?r:t.type,topic:null!==(s=null==n?void 0:n.topic)&&void 0!==s?s:"",timestamp:Date.now(),size:t.size,encryptionType:(null===(a=this.engine.e2eeManager)||void 0===a?void 0:a.isDataChannelEncryptionEnabled)?ft.GCM:ft.NONE},u=jl(Bl(l,{compression:d?rn.DEFLATE_RAW:rn.NONE}),c),h=t.stream().pipeThrough(Hl(t.size,null==n?void 0:n.onProgress)),p=d?h.pipeThrough(Sl()):h;return yield this.sendChunkedByteStream(u,e,c,p),0===t.size&&(null===(o=null==n?void 0:n.onProgress)||void 0===o||o.call(n,1)),l}))}streamBytes(e){return pr(this,void 0,void 0,(function*(){var t,n,i,s,a;const o=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),c=null==e?void 0:e.destinationIdentities,d={id:o,mimeType:null!==(n=null==e?void 0:e.mimeType)&&void 0!==n?n:"application/octet-stream",topic:null!==(i=null==e?void 0:e.topic)&&void 0!==i?i:"",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===(a=this.engine.e2eeManager)||void 0===a?void 0:a.isDataChannelEncryptionEnabled)?ft.GCM:ft.NONE},l=jl(Bl(d),c);yield Kl(this.engine,l);let u=0;const h=new r,p=this.engine,m=this.log,g=new WritableStream({write(e){return pr(this,void 0,void 0,(function*(){const t=yield h.lock();let n=0;try{for(;n<e.byteLength;){const t=e.slice(n,n+Rl),i=new Dt({destinationIdentities:c,value:{case:"streamChunk",value:new cn({content:t,streamId:o,chunkIndex:Po(u)})}});yield p.sendDataPacket(i,xd.RELIABLE),u+=1,n+=t.byteLength}}finally{t()}}))},close(){return pr(this,void 0,void 0,(function*(){yield zl(o,c,p)}))},abort(e){m.error("Sink error:",e)}});return new Ul(g,d)}))}}class Wl{constructor(e){this.state=e}static fromStream(e){return new Wl({type:"stream",stream:e})}collect(){return pr(this,void 0,void 0,(function*(){switch(this.state.type){case"stream":const e=yield wl(this.state.stream);return this.state={type:"collected",bytes:e},e;case"collected":return this.state.bytes}}))}stream(){switch(this.state.type){case"stream":return this.state.stream;case"collected":return Uo(this.state.bytes)}}}function Hl(e,t){let n=0;return new TransformStream({transform(i,r){n+=i.byteLength,t&&"number"==typeof e&&e>0&&t(Math.min(n/e,1)),r.enqueue(i)}})}function Kl(t,n){return pr(this,void 0,void 0,(function*(){if(n.toBinary().byteLength>Rl)throw new ta("data stream header exceeds the ".concat(Rl,"-byte limit; reduce attribute size"),e.DataStreamErrorReason.HeaderTooLarge);yield t.sendDataPacket(n,xd.RELIABLE)}))}function zl(e,t,n){return pr(this,void 0,void 0,(function*(){const i=new Dt({destinationIdentities:t,value:{case:"streamTrailer",value:new dn({streamId:e})}});yield n.sendDataPacket(i,xd.RELIABLE)}))}function Gl(e){if(0===e.length){return(new AbortController).signal}if(1===e.length)return e[0];for(const i of e)if(i.aborted)return i;const t=new AbortController,n=Array(e.length);return e.forEach(((e,i)=>{const r=()=>{t.abort(e.reason),(()=>{for(const e of n)e()})()};e.addEventListener("abort",r),n[i]=()=>e.removeEventListener("abort",r)})),t.signal}function Jl(e){const t=new AbortController;return setTimeout((()=>{t.abort(new DOMException("signal timed out after ".concat(e," ms"),"TimeoutError"))}),e),t.signal}var Ql,Yl,Xl;!function(e){e[e.TooShort=0]="TooShort",e[e.HeaderOverrun=1]="HeaderOverrun",e[e.MissingExtWords=2]="MissingExtWords",e[e.UnsupportedVersion=3]="UnsupportedVersion",e[e.InvalidHandle=4]="InvalidHandle",e[e.MalformedExt=5]="MalformedExt"}(Ql||(Ql={}));class Zl extends Fs{constructor(e,t,n){super(19,e,n),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=Ql[t]}static tooShort(){return new Zl("Too short to contain a valid header",Ql.TooShort)}static headerOverrun(){return new Zl("Header exceeds total packet length",Ql.HeaderOverrun)}static missingExtWords(){return new Zl("Extension word indicator is missing",Ql.MissingExtWords)}static unsupportedVersion(e){return new Zl("Unsupported version ".concat(e),Ql.UnsupportedVersion)}static invalidHandle(e){return new Zl("invalid track handle: ".concat(e.message),Ql.InvalidHandle,{cause:e})}static malformedExt(e){return new Zl("Extension with tag ".concat(e," is malformed"),Ql.MalformedExt)}}!function(e){e[e.TooSmallForHeader=0]="TooSmallForHeader",e[e.TooSmallForPayload=1]="TooSmallForPayload"}(Yl||(Yl={}));class $l extends Fs{constructor(e,t,n){super(19,e,n),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=Yl[t]}static tooSmallForHeader(){return new $l("Buffer cannot fit header",Yl.TooSmallForHeader)}static tooSmallForPayload(){return new $l("Buffer cannot fit payload",Yl.TooSmallForPayload)}}class eu{toBinary(){const e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),n=new DataView(t),i=this.toBinaryInto(n);if(e!==i)throw new Error("".concat(this.constructor.name,".toBinary: written bytes (").concat(i," bytes) not equal to allocated array buffer length (").concat(e," bytes)."));return new Uint8Array(t)}}!function(e){e[e.UserTimestamp=2]="UserTimestamp",e[e.E2ee=1]="E2ee"}(Xl||(Xl={}));class tu extends eu{}class nu extends tu{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return 2+nu.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,nu.tag),t+=1,e.setUint8(t,nu.lengthBytes),t+=1,e.setBigUint64(t,this.timestamp),t+=8;const n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackUserTimestampExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}toJSON(){return{tag:nu.tag,lengthBytes:nu.lengthBytes,timestamp:this.timestamp}}}nu.tag=Xl.UserTimestamp,nu.lengthBytes=8;class iu extends tu{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return 2+iu.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,iu.tag),t+=1,e.setUint8(t,iu.lengthBytes),t+=1,e.setUint8(t,this.keyIndex),t+=1;for(let i=0;i<this.iv.length;i+=1)e.setUint8(t,this.iv[i]),t+=1;const n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackE2eeExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}toJSON(){return{tag:iu.tag,lengthBytes:iu.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}}iu.tag=Xl.E2ee,iu.lengthBytes=13;class ru extends eu{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){t+=this.e2ee.toBinaryInto(e)}if(this.userTimestamp){t+=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t))}const n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackExtensions.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}static fromBinary(e){const t=Pc(e);let n,i,r=0;for(;t.byteLength-r>=2;){const e=t.getUint8(r);r+=1;const s=t.getUint8(r);if(r+=1,0!==e)switch(e){case Xl.UserTimestamp:if(t.byteLength-r<nu.lengthBytes)throw Zl.malformedExt(e);n=new nu(t.getBigUint64(r)),r+=s;break;case Xl.E2ee:if(t.byteLength-r<iu.lengthBytes)throw Zl.malformedExt(e);const a=t.getUint8(r),o=new Uint8Array(12);for(let e=0;e<o.length;e+=1){let n=r;n+=1,n+=1*e,o[e]=t.getUint8(n)}i=new iu(a,o),r+=s;break;default:if(t.byteLength-r<s)throw Zl.malformedExt(e);r+=s}}return[new ru({userTimestamp:n,e2ee:i}),t.byteLength]}toJSON(){var e,t,n,i;return{userTimestamp:null!==(t=null===(e=this.userTimestamp)||void 0===e?void 0:e.toJSON())&&void 0!==t?t:null,e2ee:null!==(i=null===(n=this.e2ee)||void 0===n?void 0:n.toJSON())&&void 0!==i?i:null}}}const su={from:e=>({payload:e.payload,extensions:new ru({userTimestamp:e.userTimestamp?new nu(e.userTimestamp):void 0})}),lossyIntoFrame(e){var t;return{payload:e.payload,userTimestamp:null===(t=e.extensions.userTimestamp)||void 0===t?void 0:t.timestamp}}},au=Symbol.for("lk.track"),ou=Symbol.for("lk.data-track");class cu{constructor(e,t,n){this.trackSymbol=au,this.isLocal=!1,this.typeSymbol=ou,this.info=e,this.manager=t,this.publisherIdentity=n.publisherIdentity}subscribe(e){try{const t=F(this.manager.openSubscriptionStream(this.info.sid,null==e?void 0:e.signal,null==e?void 0:e.bufferSize),2),n=t[0];return t[1].catch((()=>{})),n}catch(t){throw t}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}}class du extends eu{constructor(e){var t;super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=null!==(t=e.extensions)&&void 0!==t?t:new ru}extensionsMetrics(){const e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((2+e)/4);return{lengthBytes:e,lengthWords:t,paddingLengthBytes:4*t-2-e}}toBinaryLengthBytes(){const e=this.extensionsMetrics(),t=e.lengthBytes,n=e.paddingLengthBytes;let i=12;return t>0&&(i+=2+t+n),i}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw $l.tooSmallForHeader();let t,n=0;switch(this.marker){case lu.Inter:t=0;break;case lu.Final:t=1;break;case lu.Start:t=2;break;case lu.Single:t=3}n|=t<<3;const i=this.extensionsMetrics(),r=i.lengthBytes,s=i.lengthWords,a=i.paddingLengthBytes;r>0&&(n|=4);let o=0;if(e.setUint8(o,n),o+=1,e.setUint8(o,0),o+=1,e.setUint16(o,this.trackHandle),o+=2,e.setUint16(o,this.sequence.value),o+=2,e.setUint16(o,this.frameNumber.value),o+=2,e.setUint32(o,this.timestamp.asTicks()),o+=4,r>0){const t=s-1;e.setUint16(o,t),o+=2;o+=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+o));for(let n=0;n<a;n+=1)e.setUint8(o,0),o+=1}const c=this.toBinaryLengthBytes();if(o!==c)throw new Error("DataTrackPacketHeader.toBinaryInto: Wrote ".concat(o," bytes but expected length was ").concat(c," bytes"));return c}static fromBinary(e){const t=Pc(e);if(t.byteLength<12)throw Zl.tooShort();let i=0;const r=t.getUint8(i);i+=1;const s=r>>5&7;if(s>0)throw Zl.unsupportedVersion(s);let a;switch(r>>3&3){case 2:a=lu.Start;break;case 1:a=lu.Final;break;case 3:a=lu.Single;break;default:a=lu.Inter}const o=(r>>2&1)>0;let c;i+=1;try{c=Mc.fromNumber(t.getUint16(i))}catch(n){throw n instanceof _c&&(n.isReason(Ic.Reserved)||n.isReason(Ic.TooLarge))?Zl.invalidHandle(n):n}i+=2;const d=Cc.u16(t.getUint16(i));i+=2;const l=Cc.u16(t.getUint16(i));i+=2;const u=wc.fromRtpTicks(t.getUint32(i));i+=4;let h=new ru;if(o){if(t.byteLength-i<2)throw Zl.missingExtWords();let e=t.getUint16(i);i+=2;let n=4*(e+1)-2;if(i+n>t.byteLength)throw Zl.headerOverrun();let r=new DataView(t.buffer,t.byteOffset+i,n);const s=F(ru.fromBinary(r),2);h=s[0],i+=s[1]}return[new du({marker:a,trackHandle:c,sequence:d,frameNumber:l,timestamp:u,extensions:h}),i]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}}var lu;!function(e){e[e.Start=0]="Start",e[e.Inter=1]="Inter",e[e.Final=2]="Final",e[e.Single=3]="Single"}(lu||(lu={}));class uu extends eu{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0;if(t+=this.header.toBinaryInto(e),e.byteLength-t<this.payload.byteLength)throw $l.tooSmallForPayload();for(let i=0;i<this.payload.length;i+=1)e.setUint8(t,this.payload[i]),t+=1;const n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackPacket.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return n}static fromBinary(e){const t=Pc(e),n=F(du.fromBinary(t),2),i=n[0],r=n[1],s=t.buffer.slice(t.byteOffset+r,t.byteOffset+t.byteLength);return[new uu(i,new Uint8Array(s)),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}}const hu=or(e.LoggerNames.DataTracks);class pu extends Fs{constructor(e,t,n,i){super(19,"Frame ".concat(n," dropped: ").concat(e),i),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=mu[t],this.frameNumber=n}static interrupted(e,t){return new pu("Interrupted by the start of a new frame ".concat(t),mu.Interrupted,e)}static unknownFrame(e){return new pu("Initial packet was never received.",mu.UnknownFrame,e)}static bufferFull(e){return new pu("Reorder buffer is full.",mu.BufferFull,e)}static incomplete(e,t,n){return new pu("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(n," packets."),mu.Incomplete,e)}}var mu,gu;!function(e){e[e.Interrupted=0]="Interrupted",e[e.UnknownFrame=1]="UnknownFrame",e[e.BufferFull=2]="BufferFull",e[e.Incomplete=3]="Incomplete"}(mu||(mu={}));class vu{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case lu.Single:return this.frameFromSingle(e,t);case lu.Start:return this.beginPartial(e,t);case lu.Inter:case lu.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){const e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){var n;if(e.header.marker!==lu.Single)throw new Error("Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ".concat(e.header.marker,"."));const i=null!==(n=null==t?void 0:t.maxPartialFrames)&&void 0!==n?n:1;if(this.partials.size>=i){const n=this.peekOldestPartialFrameNumber();if("number"!=typeof n)throw new Error("Depacketizer.frameFromSingle: no oldest frame number found, but partials.size is ".concat(this.partials.size,"."));if(this.partials.delete(n),null==t?void 0:t.throwOnInterruption)throw pu.interrupted(n,e.header.frameNumber.value);hu.warn("Data track frame ".concat(n," was interrupted by single-packet frame ").concat(e.header.frameNumber.value,", dropping."))}return{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){var n;if(e.header.marker!==lu.Start)throw new Error("Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ".concat(e.header.marker,"."));const i=e.header.sequence,r=e.header.frameNumber.value,s={startSequence:i,extensions:e.header.extensions,payloads:new Map([[i.value,e.payload]])},a=null!==(n=null==t?void 0:t.maxPartialFrames)&&void 0!==n?n:1;for(;this.partials.size>=a;){const e=this.peekOldestPartialFrameNumber();if("number"!=typeof e)break;if(this.partials.delete(e),null==t?void 0:t.throwOnInterruption)throw pu.interrupted(e,r);hu.warn("Data track partials full (max ".concat(a,"), evicted oldest frame ").concat(e," to make room for new frame ").concat(r,"."))}return this.partials.set(r,s),null}pushToPartial(e){if(e.header.marker!==lu.Inter&&e.header.marker!==lu.Final)throw new Error("Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ".concat(e.header.marker,"."));const t=e.header.frameNumber.value,n=this.partials.get(t);if(!n)throw this.partials.delete(t),pu.unknownFrame(t);if(n.payloads.size>=vu.MAX_BUFFER_PACKETS)throw this.partials.delete(t),pu.bufferFull(t);return n.payloads.has(e.header.sequence.value)&&hu.warn("Data track frame ".concat(t," received duplicate packet for sequence ").concat(e.header.sequence.value,", so replacing with newly received packet.")),n.payloads.set(e.header.sequence.value,e.payload),e.header.marker===lu.Final?this.finalize(t,n,e.header.sequence.value):null}finalize(e,t,n){const i=t.payloads.size;let r=0;for(const c of t.payloads.values())r+=c.length;const s=new Uint8Array(r);let a=t.startSequence.clone(),o=0;for(;;){const i=t.payloads.get(a.value);if(!i)break;t.payloads.delete(a.value);const r=s.length-o;if(i.length>r)throw new Error("Depacketizer.finalize: Expected at least ".concat(i.length," more bytes left in the payload buffer, only got ").concat(r," bytes."));if(s.set(i,o),o+=i.length,a.value==n)return this.partials.delete(e),{payload:s,extensions:t.extensions};a.increment()}throw this.partials.delete(e),pu.incomplete(e,i,n-t.startSequence.value+1)}}vu.MAX_BUFFER_PACKETS=128,function(e){e[e.Unpublished=0]="Unpublished",e[e.Timeout=1]="Timeout",e[e.Disconnected=2]="Disconnected",e[e.Cancelled=4]="Cancelled"}(gu||(gu={}));class fu extends Fs{constructor(e,t,n){super(22,e,n),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=gu[t]}static unpublished(){return new fu("The track has been unpublished and is no longer available",gu.Unpublished)}static timeout(){return new fu("Request to subscribe to data track timed-out",gu.Timeout)}static disconnected(){return new fu("Cannot subscribe to data track when disconnected",gu.Disconnected)}static cancelled(){return new fu("Subscription to data track cancelled by caller",gu.Cancelled)}}const ku=or(e.LoggerNames.DataTracks);class yu{constructor(e){var t,n;const i=null!==e.e2eeManager;if(e.info.usesE2ee!==i)throw new Error("IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider");const r=new vu;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=null!==(t=e.e2eeManager)&&void 0!==t?t:null,this.depacketizer=r,this.options=null!==(n=e.pipelineOptions)&&void 0!==n?n:{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return pr(this,void 0,void 0,(function*(){const t=this.depacketize(e);if(!t)return null;const n=yield this.decryptIfNeeded(t);return n||null}))}depacketize(e){let t;try{t=this.depacketizer.push(e,{throwOnInterruption:!1,maxPartialFrames:this.options.maxPartialFrames})}catch(n){return ku.warn("Data frame depacketize error: ".concat(n)),null}return t}decryptIfNeeded(e){return pr(this,void 0,void 0,(function*(){var t,n;const i=this.e2eeManager;if(!i)return e;const r=null!==(n=null===(t=e.extensions)||void 0===t?void 0:t.e2ee)&&void 0!==n?n:null;if(!r)return ku.error("Missing E2EE meta"),null;let s;try{s=yield i.handleEncryptedData(e.payload,r.iv,this.publisherIdentity,r.keyIndex)}catch(a){return ku.error("Error decrypting packet: ".concat(a)),null}return e.payload=s.payload,e}))}}const bu=or(e.LoggerNames.DataTracks);class Tu extends br.EventEmitter{constructor(e){var t;super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=null!==(t=null==e?void 0:e.e2eeManager)&&void 0!==t?t:null}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())"active"===t.subscription.type&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){const n=this.descriptors.get(e);n?(n.pipelineOptions=t,"active"===n.subscription.type&&n.subscription.pipeline.setOptions(t)):bu.warn("Unknown track ".concat(e,", cannot set pipeline options."))}openSubscriptionStream(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16,i=null;const r=new To,s=this.descriptors.get(e),a=()=>{null==t||t.removeEventListener("abort",c)},o=()=>{a(),i?s&&this.descriptors.get(s.info.sid)===s?"active"===s.subscription.type?(s.subscription.streamControllers.delete(i),0===s.subscription.streamControllers.size&&this.unSubscribeRequest(s.info.sid)):bu.warn("Subscription for track ".concat(e," is not active, skipping cancel...")):bu.warn("Unknown track ".concat(e,", skipping cancel...")):bu.warn("ReadableStream subscribed to ".concat(e," was not started."))},c=()=>{var e;i&&("active"===(null==s?void 0:s.subscription.type)&&s.subscription.streamControllers.delete(i),i.error(fu.cancelled()),null===(e=r.reject)||void 0===e||e.call(r,fu.cancelled()),o())},d=new ReadableStream({start:n=>{i=n,this.subscribeRequest(e,t).then((()=>pr(this,void 0,void 0,(function*(){var i,o,d;if(!s||this.descriptors.get(s.info.sid)!==s){bu.error("Unknown track ".concat(e));const t=fu.disconnected();return n.error(t),void(null===(i=r.reject)||void 0===i||i.call(r,t))}if("active"!==s.subscription.type){bu.error("Subscription for track ".concat(e," is not active"));const t=fu.disconnected();return n.error(t),void(null===(o=r.reject)||void 0===o||o.call(r,t))}(null==t?void 0:t.aborted)?c():(null==t||t.addEventListener("abort",c),s.subscription.streamControllers.set(n,a),null===(d=r.resolve)||void 0===d||d.call(r))})))).catch((e=>{var t;n.error(e),null===(t=r.reject)||void 0===t||t.call(r,e)}))},cancel:()=>{o()}},new CountQueuingStrategy({highWaterMark:n}));return[d,r.promise]}subscribeRequest(e,t){return pr(this,void 0,void 0,(function*(){const n=this.descriptors.get(e);if(!n)throw new Error("Cannot subscribe to unknown track");const i=(t,n,i)=>pr(this,void 0,void 0,(function*(){if("active"===t.subscription.type)return;if("pending"!==t.subscription.type)throw new Error("Descriptor for track ".concat(e," is not pending, found ").concat(t.subscription.type));const r=Gl([n,i].filter((e=>void 0!==e))),s=new To;t.subscription.completionFuture.promise.then((()=>{var e;return null===(e=s.resolve)||void 0===e?void 0:e.call(s)})).catch((e=>{var t;return null===(t=s.reject)||void 0===t?void 0:t.call(s,e)}));const a=()=>{var e;"pending"===t.subscription.type&&(t.subscription.pendingRequestCount-=1,(null==i?void 0:i.aborted)||t.subscription.pendingRequestCount<=0?t.subscription.cancel():null===(e=s.reject)||void 0===e||e.call(s,fu.cancelled()))};r.aborted&&a(),r.addEventListener("abort",a),yield s.promise,r.removeEventListener("abort",a)}));switch(n.subscription.type){case"none":{n.subscription={type:"pending",completionFuture:new To,pendingRequestCount:1,cancel:()=>{var e,t;const i=n.subscription;n.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:n.info.sid,subscribe:!1}),"pending"===i.type&&(null===(t=(e=i.completionFuture).reject)||void 0===t||t.call(e,r.aborted?fu.timeout():fu.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});const r=Jl(1e4);return void(yield i(n,t,r))}case"pending":return n.subscription.pendingRequestCount+=1,void(yield i(n,t));case"active":return}}))}querySubscribed(){return pr(this,void 0,void 0,(function*(){return Array.from(this.descriptors.values()).filter((e=>"active"===e.subscription.type)).map((e=>[e.info,e.publisherIdentity]))}))}unSubscribeRequest(e){var t;const n=this.descriptors.get(e);if(!n)throw new Error("Cannot subscribe to unknown track");if("active"!==n.subscription.type)return void bu.warn("Unexpected descriptor state in unSubscribeRequest, expected active, found ".concat(null===(t=n.subscription)||void 0===t?void 0:t.type));this.closeStreamControllers(n.subscription.streamControllers,e);const i=n.subscription;n.subscription={type:"none"},this.subscriptionHandles.delete(i.subcriptionHandle),this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(const r of e){var n=F(r,2);const e=n[0];(0,n[1])();try{e.close()}catch(i){bu.warn("Failed to close readable stream for track ".concat(t,": ").concat(i))}}}receiveSfuPublicationUpdates(e){return pr(this,void 0,void 0,(function*(){if(0===e.size)return;const t=new Map;for(const r of e.entries()){var n=F(r,2);const e=n[0],i=n[1],s=new Set;for(const t of i)s.add(t.sid),this.descriptors.has(t.sid)||this.handleSidReassigned(e,t)||(yield this.handleTrackPublished(e,t));t.set(e,s)}for(const e of t.entries()){var i=F(e,2);const t=i[0],n=i[1];let r=Array.from(this.descriptors.entries()).filter((e=>{let n=F(e,2);return n[0],n[1].publisherIdentity===t})).map((e=>F(e,1)[0])).filter((e=>!n.has(e)));for(const e of r)this.handleTrackUnpublished(e)}}))}queryPublications(){return pr(this,void 0,void 0,(function*(){return Array.from(this.descriptors.values()).map((e=>e.info))}))}handleTrackPublished(e,t){return pr(this,void 0,void 0,(function*(){if(this.descriptors.has(t.sid))return void bu.error("Existing descriptor for track ".concat(t.sid));let n={info:t,publisherIdentity:e,subscription:{type:"none"},pipelineOptions:{}};this.descriptors.set(n.info.sid,n);const i=new cu(n.info,this,{publisherIdentity:e});this.emit("trackPublished",{track:i})}))}handleSidReassigned(e,t){const n=Array.from(this.descriptors.entries()).find((n=>{let i=F(n,2);i[0];let r=i[1];return r.publisherIdentity===e&&r.info.pubHandle===t.pubHandle}));if(!n)return!1;const i=F(n,2),r=i[0],s=i[1],a=s.info,o=a.name,c=a.usesE2ee;if(o!==t.name||c!==t.usesE2ee)return bu.warn("Info mismatch for ".concat(r,", treating as new publication")),!1;const d=t.sid;if(bu.debug("SID reassigned: ".concat(r," -> ").concat(d)),!this.descriptors.delete(r))return!1;switch(s.info.sid=d,s.subscription.type){case"none":break;case"pending":case"active":this.emit("sfuUpdateSubscription",{sid:d,subscribe:!0})}return"active"===s.subscription.type&&this.subscriptionHandles.set(s.subscription.subcriptionHandle,d),this.descriptors.set(d,s),!0}handleTrackUnpublished(e){const t=this.descriptors.get(e);t?(this.descriptors.delete(e),"active"===t.subscription.type&&(this.closeStreamControllers(t.subscription.streamControllers,e),this.subscriptionHandles.delete(t.subscription.subcriptionHandle)),this.emit("trackUnpublished",{sid:e,publisherIdentity:t.publisherIdentity})):bu.error("Unknown track ".concat(e))}receivedSfuSubscriberHandles(e){for(const n of e.entries()){var t=F(n,2);const e=t[0],i=t[1];this.registerSubscriberHandle(e,i)}}registerSubscriberHandle(e,t){var n,i;const r=this.descriptors.get(t);if(r)switch(r.subscription.type){case"none":return void bu.warn("No subscription for ".concat(t));case"active":return this.subscriptionHandles.delete(r.subscription.subcriptionHandle),r.subscription.subcriptionHandle=e,void this.subscriptionHandles.set(e,t);case"pending":{bu.debug("data track subscription activated",{sid:t,handle:e});const s=new yu({info:r.info,publisherIdentity:r.publisherIdentity,e2eeManager:this.e2eeManager,pipelineOptions:r.pipelineOptions}),a=r.subscription;r.subscription={type:"active",subcriptionHandle:e,pipeline:s,streamControllers:new Map},this.subscriptionHandles.set(e,t),null===(i=(n=a.completionFuture).resolve)||void 0===i||i.call(n)}}else bu.error("Unknown track ".concat(t))}packetReceived(e){return pr(this,void 0,void 0,(function*(){let t;try{t=F(uu.fromBinary(e),1)[0]}catch(s){return void bu.error("Failed to deserialize packet: ".concat(s))}const n=this.subscriptionHandles.get(t.header.trackHandle);if(!n)return void bu.warn("Unknown subscriber handle ".concat(t.header.trackHandle));const i=this.descriptors.get(n);if(!i)return void bu.error("Missing descriptor for track ".concat(n));if("active"!==i.subscription.type)return void bu.warn("Received packet for track ".concat(n," without active subscription"));const r=yield i.subscription.pipeline.processPacket(t);if(r)for(const e of i.subscription.streamControllers.keys()){if(null!==e.desiredSize&&e.desiredSize<=0){bu.warn("Cannot send frame to subscribers: readable stream is full (desiredSize is ".concat(e.desiredSize,"). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe()."));continue}const t=su.lossyIntoFrame(r);e.enqueue(t)}}))}resendSubscriptionUpdates(){for(const t of this.descriptors){var e=F(t,2);const n=e[0];"none"!==e[1].subscription.type&&this.emit("sfuUpdateSubscription",{sid:n,subscribe:!0})}}handleRemoteParticipantDisconnected(e){var t,n;for(const i of this.descriptors.values())if(i.publisherIdentity===e)switch(i.subscription.type){case"none":break;case"pending":null===(n=(t=i.subscription.completionFuture).reject)||void 0===n||n.call(t,fu.disconnected());break;case"active":this.unSubscribeRequest(i.info.sid)}}reset(){var e,t;for(const n of this.descriptors.values())this.emit("trackUnpublished",{sid:n.info.sid,publisherIdentity:n.publisherIdentity}),"pending"===n.subscription.type&&(null===(t=(e=n.subscription.completionFuture).reject)||void 0===t||t.call(e,fu.disconnected())),"active"===n.subscription.type&&this.closeStreamControllers(n.subscription.streamControllers,n.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}}class Su extends Fs{constructor(e,t,n){super(19,e,n),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=Eu[t]}static mtuTooShort(){return new Su("MTU is too short to send frame",Eu.MtuTooShort)}}var Eu,Cu,wu,Ru;!function(e){e[e.MtuTooShort=0]="MtuTooShort"}(Eu||(Eu={}));class Pu{constructor(e,t){this.sequence=Cc.u16(0),this.frameNumber=Cc.u16(0),this.clock=Rc.rtpStartingNow(wc.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?lu.Single:0===e?lu.Start:e===t-1?lu.Final:lu.Inter}*packetize(e,t){var n;const i=this.frameNumber.getThenIncrement(),r={marker:lu.Inter,trackHandle:this.handle,sequence:Cc.u16(0),frameNumber:i,timestamp:null!==(n=null==t?void 0:t.now)&&void 0!==n?n:this.clock.now(),extensions:e.extensions},s=new du(r).toBinaryLengthBytes();if(s>=this.mtuSizeBytes)throw Su.mtuTooShort();const a=this.mtuSizeBytes-s,o=Math.ceil(e.payload.byteLength/a);for(let d=0,l=0;l<e.payload.byteLength;d=(c=[d+1,l+a])[0],l=c[1],c){var c;const t=this.sequence.getThenIncrement(),n=new du(Object.assign(Object.assign({},r),{marker:Pu.computeFrameMarker(d,o),sequence:t})),i=Math.min(a,e.payload.byteLength-l),s=new Uint8Array(e.payload.buffer,e.payload.byteOffset+l,i);yield new uu(n,s)}}}!function(e){e[e.NotAllowed=0]="NotAllowed",e[e.DuplicateName=1]="DuplicateName",e[e.Timeout=2]="Timeout",e[e.LimitReached=3]="LimitReached",e[e.Disconnected=4]="Disconnected",e[e.Cancelled=5]="Cancelled",e[e.InvalidName=6]="InvalidName",e[e.Unknown=7]="Unknown"}(Cu||(Cu={}));class Iu extends Fs{constructor(e,t,n){super(21,e,n),this.name="DataTrackPublishError",this.reason=t,this.reasonName=Cu[t],this.rawMessage=null==n?void 0:n.rawMessage}static notAllowed(e){return new Iu("Data track publishing unauthorized",Cu.NotAllowed,{rawMessage:e})}static duplicateName(e){return new Iu("Track name already taken",Cu.DuplicateName,{rawMessage:e})}static invalidName(e){return new Iu("Track name is invalid",Cu.InvalidName,{rawMessage:e})}static timeout(){return new Iu("Publish data track timed-out. Does the LiveKit server support data tracks?",Cu.Timeout)}static limitReached(e){return new Iu("Data track publication limit reached",Cu.LimitReached,{rawMessage:e})}static unknown(e,t){return new Iu("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),Cu.Unknown)}static disconnected(){return new Iu("Room disconnected",Cu.Disconnected)}static cancelled(){return new Iu("Publish data track cancelled by caller",Cu.Cancelled)}}!function(e){e[e.TrackUnpublished=0]="TrackUnpublished",e[e.Dropped=1]="Dropped"}(wu||(wu={}));class _u extends Fs{constructor(e,t,n){super(22,e,n),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=wu[t]}static trackUnpublished(){return new _u("Track is no longer published",wu.TrackUnpublished)}static dropped(e){return new _u("Frame was dropped",wu.Dropped,{cause:e})}}!function(e){e[e.Packetizer=0]="Packetizer",e[e.Encryption=1]="Encryption"}(Ru||(Ru={}));class Mu extends Fs{constructor(e,t,n){super(21,e,n),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=Ru[t]}static packetizer(e){return new Mu("Error packetizing frame",Ru.Packetizer,{cause:e})}static encryption(e){return new Mu("Error encrypting frame",Ru.Encryption,{cause:e})}}class Du{constructor(t,n){this.trackSymbol=au,this.isLocal=!0,this.typeSymbol=ou,this.handle=null,this.log=sr,this.flushedFuture=new To,this.isFlushed=!0,this.handleManagerReset=()=>{var e,t;null===(t=(e=this.flushedFuture).resolve)||void 0===t||t.call(e),this.manager.off("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.off("reset",this.handleManagerReset)},this.handleManagerPacketsFlushedChange=e=>{var t,n;this.isFlushed=e.isFlushed,e.isFlushed&&(null===(n=(t=this.flushedFuture).resolve)||void 0===n||n.call(t),this.flushedFuture=new To)},this.options=t,this.manager=n,this.log=or(e.LoggerNames.DataTracks),this.manager.on("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.on("reset",this.handleManagerReset)}static withExplicitHandle(e,t,n){const i=new Du(e,t);return i.handle=n,i}get info(){const e=this.descriptor;return"active"===(null==e?void 0:e.type)?e.info:void 0}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return pr(this,void 0,void 0,(function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(t){throw t}}))}isPublished(){var e;return"active"===(null===(e=this.descriptor)||void 0===e?void 0:e.type)&&"unpublished"!==this.descriptor.publishState}tryPush(e){if(!this.handle)throw _u.trackUnpublished();const t=su.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(n){throw n}}flush(){return pr(this,void 0,void 0,(function*(){if(!this.isFlushed)return this.flushedFuture.promise}))}unpublish(){return pr(this,void 0,void 0,(function*(){if(this.handle)try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}else sr.warn('Data track "'.concat(this.options.name,'" is not published, so unpublishing has no effect.'))}))}}class Ou{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new Pu(e.info.pubHandle,Ou.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return vr(this,arguments,(function*(){const t=yield gr(this.encryptIfNeeded(e));try{yield gr(yield*function(e){var t,n;return t={},i("next"),i("throw",(function(e){throw e})),i("return"),t[Symbol.iterator]=function(){return this},t;function i(i,r){t[i]=e[i]?function(t){return(n=!n)?{value:gr(e[i](t)),done:!1}:r?r(t):t}:r}}(fr(this.packetizer.packetize(t))))}catch(n){if(n instanceof Su)throw Mu.packetizer(n);throw n}}))}encryptIfNeeded(e){return pr(this,void 0,void 0,(function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(n){throw Mu.encryption(n)}return e.payload=t.payload,e.extensions.e2ee=new iu(t.keyIndex,t.iv),e}))}}Ou.TRANSPORT_MTU_BYTES=16e3;const Au=or(e.LoggerNames.DataTracks),Nu={pending:()=>({type:"pending",completionFuture:new To}),active:(e,t)=>({type:"active",info:e,publishState:"published",pipeline:new Ou({info:e,e2eeManager:t}),unpublishingFuture:new To})};class Lu extends br.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new Dc,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=null!==(t=null==e?void 0:e.e2eeManager)&&void 0!==t?t:null}static withDescriptors(e){const t=new Lu;return t.descriptors=e,t}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())"active"===t.type&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){var t;return null!==(t=this.descriptors.get(e))&&void 0!==t?t:null}tryProcessAndSend(e,t){return pr(this,void 0,void 0,(function*(){var n,i,r,s,a;const o=this.getDescriptor(e);if("active"!==(null==o?void 0:o.type))throw _u.trackUnpublished();if("unpublished"===o.publishState)throw _u.trackUnpublished();if("republishing"===o.publishState)throw _u.dropped("Data track republishing");try{try{for(var c,d=!0,l=fr(o.pipeline.processFrame(t));!(n=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const t=s,n=null!==(a=this.inFlightPacketCounter.get(e))&&void 0!==a?a:0;this.inFlightPacketCounter.set(e,n+1),0===n&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!1}),this.emit("packetAvailable",{handle:e,bytes:t.toBinary()})}}catch(u){i={error:u}}finally{try{d||n||!(r=l.return)||(yield r.call(l))}finally{if(i)throw i.error}}}catch(h){throw _u.dropped(h)}}))}handlePacketSendComplete(e){var t;let n=(null!==(t=this.inFlightPacketCounter.get(e))&&void 0!==t?t:0)-1;n<0&&(Au.warn("OutgoingDataTrackManager.handlePacketSendComplete: inFlightPacketCounter was decremented below 0 (got ".concat(this.inFlightPacketCounter," - resetting to 0. Were more packets send than were emitted?")),n=0),this.inFlightPacketCounter.set(e,n),0===n&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!0})}publishRequest(e,t){return pr(this,void 0,void 0,(function*(){const n=this.handleAllocator.get();if(!n)throw Iu.limitReached();const i=Jl(1e4),r=t?Gl([t,i]):i;if(this.descriptors.has(n))throw new Error("Descriptor for handle already exists");const s=Nu.pending();this.descriptors.set(n,s);const a=()=>{var e,t;const r=this.descriptors.get(n);r?(this.descriptors.delete(n),this.emit("sfuUnpublishRequest",{handle:n}),"pending"===r.type&&(null===(t=(e=r.completionFuture).reject)||void 0===t||t.call(e,i.aborted?Iu.timeout():Iu.cancelled()))):Au.warn("No descriptor for ".concat(n))};return r.aborted?(a(),s.completionFuture.promise.then((()=>n))):(r.addEventListener("abort",a),this.emit("sfuPublishRequest",{handle:n,name:e.name,usesE2ee:null!==this.e2eeManager}),yield s.completionFuture.promise,r.removeEventListener("abort",a),this.emit("trackPublished",{track:Du.withExplicitHandle(e,this,n)}),n)}))}queryPublished(){return Array.from(this.descriptors.values()).filter((e=>"active"===e.type)).map((e=>e.info))}unpublishRequest(e){return pr(this,void 0,void 0,(function*(){const t=this.descriptors.get(e);t?"active"===t.type?(this.emit("sfuUnpublishRequest",{handle:e}),yield t.unpublishingFuture.promise,this.inFlightPacketCounter.delete(e),this.emit("trackUnpublished",{sid:t.info.sid})):Au.warn("Track ".concat(e," not active")):Au.warn("No descriptor for ".concat(e))}))}receivedSfuPublishResponse(e,t){var n,i,r,s;const a=this.descriptors.get(e);if(a)switch(this.descriptors.delete(e),a.type){case"pending":if("ok"===t.type){const r=t.data;Au.debug("SFU accepted publish request for handle ".concat(e),{sid:r.sid});const s=r.usesE2ee?this.e2eeManager:null;this.descriptors.set(r.pubHandle,Nu.active(r,s)),null===(i=(n=a.completionFuture).resolve)||void 0===i||i.call(n)}else Au.debug("SFU rejected publish request for handle ".concat(e),{error:t.error}),null===(s=(r=a.completionFuture).reject)||void 0===s||s.call(r,t.error);return;case"active":if("republishing"!==a.publishState)return void Au.warn("Track ".concat(e," already active"));if("error"===t.type)return void Au.warn("Republish failed for track ".concat(e));Au.debug("Track ".concat(e," republished")),a.info.sid=t.data.sid,a.publishState="published",this.descriptors.set(a.info.pubHandle,a)}else Au.warn("No descriptor for ".concat(e))}receivedSfuUnpublishResponse(e){var t,n;const i=this.descriptors.get(e);i?(this.descriptors.delete(e),"active"===i.type?(i.publishState="unpublished",null===(n=(t=i.unpublishingFuture).resolve)||void 0===n||n.call(t)):Au.warn("Track ".concat(e," not active"))):Au.warn("No descriptor for ".concat(e))}sfuWillRepublishTracks(){var e,t;for(const i of this.descriptors.entries()){var n=F(i,2);const r=n[0],s=n[1];switch(s.type){case"pending":this.descriptors.delete(r),null===(t=(e=s.completionFuture).reject)||void 0===t||t.call(e,Iu.disconnected());break;case"active":s.publishState="republishing",this.emit("sfuPublishRequest",{handle:s.info.pubHandle,name:s.info.name,usesE2ee:s.info.usesE2ee})}}}reset(){return pr(this,void 0,void 0,(function*(){var e,t,n,i;this.handleAllocator.reset();for(const r of this.descriptors.values())switch(r.type){case"pending":null===(t=(e=r.completionFuture).reject)||void 0===t||t.call(e,Iu.disconnected());break;case"active":null===(i=(n=r.unpublishingFuture).resolve)||void 0===i||i.call(n),yield this.unpublishRequest(r.info.pubHandle)}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit("reset")}))}}class xu extends Error{constructor(e,t,n,i){super(t),this.code=e,this.message=qu(t,xu.MAX_MESSAGE_BYTES),this.data=n?qu(n,xu.MAX_DATA_BYTES):void 0,void 0!==(null==i?void 0:i.cause)&&(this.cause=null==i?void 0:i.cause)}static fromProto(e){return new xu(e.code,e.message,e.data)}toProto(){return new Kt({code:this.code,message:this.message,data:this.data})}static builtIn(e,t,n){return new xu(xu.ErrorCode[e],xu.ErrorMessage[e],t,n)}}xu.MAX_MESSAGE_BYTES=256,xu.MAX_DATA_BYTES=15360,xu.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},xu.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"};const Uu="lk.rpc_request",Fu="lk.rpc_response";var Bu;!function(e){e.RPC_REQUEST_ID="lk.rpc_request_id",e.RPC_REQUEST_METHOD="lk.rpc_request_method",e.RPC_REQUEST_RESPONSE_TIMEOUT_MS="lk.rpc_request_response_timeout_ms",e.RPC_REQUEST_VERSION="lk.rpc_request_version"}(Bu||(Bu={}));function ju(e){return(new TextEncoder).encode(e).length}function qu(e,t){if(ju(e)<=t)return e;let n=0,i=e.length;const r=new TextEncoder;for(;n<i;){const s=Math.floor((n+i+1)/2);r.encode(e.slice(0,s)).length<=t?n=s:i=s-1}return e.slice(0,n)}class Vu extends br.EventEmitter{constructor(e,t,n,i){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n,this.getServerVersion=i}performRpc(e){return pr(this,arguments,void 0,(function(e){var t=this;let n=e.destinationIdentity,i=e.method,r=e.payload,s=e.responseTimeout,a=void 0===s?15e3:s;return function*(){const e=t.getRemoteParticipantClientProtocol(n);if(ju(r)>15360&&e<1)throw xu.builtIn("REQUEST_PAYLOAD_TOO_LARGE");const s=t.getServerVersion();if(s&&lo(s,"1.8.0")<0)throw xu.builtIn("UNSUPPORTED_SERVER");const o=Math.max(a,8e3),c=crypto.randomUUID(),d=new To;let l=null;const u=setTimeout((()=>{var e;t.pendingAcks.delete(c),null===(e=d.reject)||void 0===e||e.call(d,xu.builtIn("CONNECTION_TIMEOUT")),t.pendingResponses.delete(c),null!==l&&clearTimeout(l)}),7e3);t.pendingAcks.set(c,{resolve:()=>{clearTimeout(u)},participantIdentity:n}),t.pendingResponses.set(c,{completionFuture:d,participantIdentity:n}),yield t.publishRpcRequest(n,c,i,r,o,e),l=setTimeout((()=>{var e;t.pendingResponses.delete(c),null===(e=d.reject)||void 0===e||e.call(d,xu.builtIn("RESPONSE_TIMEOUT"))}),a);const h=d.promise.finally((()=>{clearTimeout(l),t.pendingAcks.has(c)&&(t.log.warn("RPC response received before ack",c),t.pendingAcks.delete(c),clearTimeout(u))}));return[c,h]}()}))}publishRpcRequest(e,t,n,i,r,s){return pr(this,void 0,void 0,(function*(){s>=1?yield this.outgoingDataStreamManager.sendText(i,{topic:Uu,destinationIdentities:[e],attributes:{[Bu.RPC_REQUEST_ID]:t,[Bu.RPC_REQUEST_METHOD]:n,[Bu.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:"".concat(r),[Bu.RPC_REQUEST_VERSION]:"".concat(2)}}):this.emit("sendDataPacket",{packet:new Dt({destinationIdentities:[e],kind:Ot.RELIABLE,value:{case:"rpcRequest",value:new Vt({id:t,method:n,payload:i,responseTimeoutMs:r,version:1})}})})}))}handleIncomingDataStream(e,t,i){return pr(this,void 0,void 0,(function*(){const r=i[Bu.RPC_REQUEST_ID];if(!r)return void this.log.warn("RPC data stream malformed: ".concat(Bu.RPC_REQUEST_ID," not set."));const s=this.pendingResponses.get(r);if(s&&s.participantIdentity!==t)return void this.log.warn("RPC response stream for ".concat(r," arrived from unexpected sender ").concat(t,", expected ").concat(s.participantIdentity,". Ignoring."));let a;try{a=yield e.readAll()}catch(n){return this.log.warn("Error reading RPC response payload: ".concat(n)),void this.handleIncomingRpcResponseFailure(r,xu.builtIn("APPLICATION_ERROR","Error reading RPC response payload",{cause:n}))}this.handleIncomingRpcResponseSuccess(r,a)}))}handleIncomingRpcResponseSuccess(e,t){var n,i;const r=this.pendingResponses.get(e);r?(null===(i=(n=r.completionFuture).resolve)||void 0===i||i.call(n,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcResponseFailure(e,t){var n,i;const r=this.pendingResponses.get(e);r?(null===(i=(n=r.completionFuture).reject)||void 0===i||i.call(n,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):this.log.error("Ack received for unexpected RPC request: ".concat(e))}handleParticipantDisconnected(e){var t;for(const s of this.pendingAcks){var n=F(s,2);const t=n[0];n[1].participantIdentity===e&&this.pendingAcks.delete(t)}for(const s of this.pendingResponses){var i=F(s,2);const n=i[0];var r=i[1];const a=r.participantIdentity,o=r.completionFuture;a===e&&(null===(t=o.reject)||void 0===t||t.call(o,xu.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(n))}}}class Wu extends br.EventEmitter{constructor(e,t,n){super(),this.rpcHandlers=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n}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)}handleIncomingRpcRequest(e,t){return pr(this,void 0,void 0,(function*(){var n;if(this.publishRpcAck(e,t.id),1!==t.version)return void this.publishRpcResponsePacket(e,t.id,null,xu.builtIn("UNSUPPORTED_VERSION"));const i=this.rpcHandlers.get(t.method);if(!i)return void this.publishRpcResponsePacket(e,t.id,null,xu.builtIn("UNSUPPORTED_METHOD"));let r;try{r=yield i({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(s){let i;return s instanceof xu?i=s:(this.log.warn("Uncaught error returned by RPC handler for ".concat(t.method,". Returning APPLICATION_ERROR instead."),s),i=xu.builtIn("APPLICATION_ERROR","Uncaught error: ".concat(null!==(n=null==s?void 0:s.message)&&void 0!==n?n:s),{cause:s})),void this.publishRpcResponsePacket(e,t.id,null,i)}yield this.publishRpcResponse(e,t.id,null!=r?r:"")}))}handleIncomingDataStream(e,t,i){return pr(this,void 0,void 0,(function*(){const r=i[Bu.RPC_REQUEST_ID],s=i[Bu.RPC_REQUEST_METHOD],a=parseInt(i[Bu.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),o=parseInt(i[Bu.RPC_REQUEST_VERSION],10);if(!r||!s||Number.isNaN(a)||Number.isNaN(o))return this.log.warn("RPC data stream malformed: ".concat(Bu.RPC_REQUEST_ID," / ").concat(Bu.RPC_REQUEST_METHOD," / ").concat(Bu.RPC_REQUEST_RESPONSE_TIMEOUT_MS," / ").concat(Bu.RPC_REQUEST_VERSION," not set.")),void this.publishRpcResponsePacket(t,r,null,xu.builtIn("APPLICATION_ERROR","RPC data stream malformed"));if(this.publishRpcAck(t,r),2!==o)return void this.publishRpcResponsePacket(t,r,null,xu.builtIn("UNSUPPORTED_VERSION"));let c;try{c=yield e.readAll()}catch(n){return this.log.warn("Error reading RPC request payload: ".concat(n)),void this.publishRpcResponsePacket(t,r,null,xu.builtIn("APPLICATION_ERROR","Error reading RPC request payload",{cause:n}))}const d=this.rpcHandlers.get(s);if(!d)return void this.publishRpcResponsePacket(t,r,null,xu.builtIn("UNSUPPORTED_METHOD"));let l;try{l=yield d({requestId:r,callerIdentity:t,payload:c,responseTimeout:a})}catch(u){let e;return u instanceof xu?e=u:(this.log.warn("Uncaught error returned by RPC handler for ".concat(s,". Returning APPLICATION_ERROR instead."),u),e=xu.builtIn("APPLICATION_ERROR")),void this.publishRpcResponsePacket(t,r,null,e)}yield this.publishRpcResponse(t,r,null!=l?l:"")}))}publishRpcAck(e,t){this.emit("sendDataPacket",{packet:new Dt({destinationIdentities:[e],kind:Ot.RELIABLE,value:{case:"rpcAck",value:new Wt({requestId:t})}})})}publishRpcResponsePacket(e,t,n,i){this.emit("sendDataPacket",{packet:new Dt({destinationIdentities:[e],kind:Ot.RELIABLE,value:{case:"rpcResponse",value:new Ht({requestId:t,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:null!=n?n:""}})}})})}publishRpcResponse(e,t,n){return pr(this,void 0,void 0,(function*(){if(this.getRemoteParticipantClientProtocol(e)>=1)return void(yield this.outgoingDataStreamManager.sendText(n,{topic:Fu,destinationIdentities:[e],attributes:{[Bu.RPC_REQUEST_ID]:t}}));if(ju(n)>15360)return this.log.warn("RPC Response payload too large for request ".concat(t,". To send larger responses, consider updating the sending client.")),void this.publishRpcResponsePacket(e,t,null,xu.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"));this.publishRpcResponsePacket(e,t,n,null)}))}}class Hu extends lc{constructor(e,t,n,i,r,s){super(e,t,xa.Kind.Audio,n,s),this.monitorReceiver=()=>pr(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=dc(e,this.prevStats)),this.prevStats=e})),this.audioContext=i,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):n.volume=e;io()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(io())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return pr(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(Ja(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&Ja(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(t,n){this.disconnectWebAudio(),this.sourceNode=t.createMediaStreamSource(n.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach((e=>{i.connect(e),i=e})),this.gainNode=t.createGain(),i.connect(this.gainNode),this.gainNode.connect(t.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==t.state&&t.resume().then((()=>{"running"!==t.state&&this.emit(e.TrackEvent.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((t=>{this.emit(e.TrackEvent.AudioPlaybackFailed,t)}))}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 pr(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 Ku extends br.EventEmitter{constructor(t,n,i,r){var s;super(),this.metadataMuted=!1,this.encryption=ft.NONE,this.log=sr,this.handleMuted=()=>{this.emit(e.TrackEvent.Muted)},this.handleUnmuted=()=>{this.emit(e.TrackEvent.Unmuted)},this.log=or(null!==(s=null==r?void 0:r.loggerName)&&void 0!==s?s:e.LoggerNames.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=t,this.trackSid=n,this.trackName=i,this.source=xa.Source.Unknown}setTrack(t){this.track&&(this.track.off(e.TrackEvent.Muted,this.handleMuted),this.track.off(e.TrackEvent.Unmuted,this.handleUnmuted)),this.track=t,t&&(t.on(e.TrackEvent.Muted,this.handleMuted),t.on(e.TrackEvent.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),Da(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==ft.NONE}get audioTrack(){if(_o(this.track))return this.track}get videoTrack(){if(Mo(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=xa.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===xa.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}!function(e){var t,n;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",(n=e.PermissionStatus||(e.PermissionStatus={})).Allowed="allowed",n.NotAllowed="not_allowed"}(Ku||(Ku={}));class zu extends Ku{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(t,n,i,r){super(t,n.sid,n.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(e.TrackEvent.Ended)},this.handleCpuConstrained=()=>{this.track&&Mo(this.track)&&this.emit(e.TrackEvent.CpuConstrained,this.track)},this.updateInfo(n),this.setTrack(i)}setTrack(t){this.track&&(this.track.off(e.TrackEvent.Ended,this.handleTrackEnded),this.track.off(e.TrackEvent.CpuConstrained,this.handleCpuConstrained)),super.setTrack(t),t&&(t.on(e.TrackEvent.Ended,this.handleTrackEnded),t.on(e.TrackEvent.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 pr(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){return pr(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){return pr(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){return pr(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}getTrackFeatures(){var e;if(_o(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(ct.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(ct.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(ct.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(ct.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||n.add(ct.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(ct.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}return[]}}function Gu(e,t){return pr(this,void 0,void 0,(function*(){null!=e||(e={});let i=!1;const r=Oa(e),s=r.audioProcessor,a=r.videoProcessor,o=r.optionsWithoutProcessor;let c=o.audio,d=o.video;if(s&&"object"==typeof o.audio&&(o.audio.processor=s),a&&"object"==typeof o.video&&(o.video.processor=a),e.audio&&"object"==typeof o.audio&&"string"==typeof o.audio.deviceId){const e=o.audio.deviceId;o.audio.deviceId={exact:e},i=!0,c=Object.assign(Object.assign({},o.audio),{deviceId:{ideal:e}})}if(o.video&&"object"==typeof o.video&&"string"==typeof o.video.deviceId){const e=o.video.deviceId;o.video.deviceId={exact:e},i=!0,d=Object.assign(Object.assign({},o.video),{deviceId:{ideal:e}})}!0===o.audio?o.audio={deviceId:"default"}:"object"==typeof o.audio&&null!==o.audio&&(o.audio=Object.assign(Object.assign({},o.audio),{deviceId:o.audio.deviceId||"default"})),!0===o.video?o.video={deviceId:"default"}:"object"!=typeof o.video||o.video.deviceId||(o.video.deviceId="default");const l=Ea(Ta(o,Dd,Od)),u=navigator.mediaDevices.getUserMedia(l);o.audio&&(Tc.userMediaPromiseMap.set("audioinput",u),u.catch((()=>Tc.userMediaPromiseMap.delete("audioinput")))),o.video&&(Tc.userMediaPromiseMap.set("videoinput",u),u.catch((()=>Tc.userMediaPromiseMap.delete("videoinput"))));try{const e=yield u;return yield Promise.all(e.getTracks().map((n=>pr(this,void 0,void 0,(function*(){let i;const r="audio"===n.kind?l.audio:l.video;"boolean"!=typeof r&&(i=r);const o=n.getSettings().deviceId;(null==i?void 0:i.deviceId)&&Eo(i.deviceId)!==o?i.deviceId=o:i||(i={deviceId:o});const c=function(e,t,n){switch(e.kind){case"audio":return new Zd(e,t,!1,void 0,n);case"video":return new ul(e,t,!1,n);default:throw new Js("unsupported track type: ".concat(e.kind))}}(n,i,t);return c.kind===xa.Kind.Video?c.source=xa.Source.Camera:c.kind===xa.Kind.Audio&&(c.source=xa.Source.Microphone),c.mediaStream=e,_o(c)&&s?yield c.setProcessor(s):Mo(c)&&a&&(yield c.setProcessor(a)),c})))))}catch(n){if(!i)throw n;return Gu(Object.assign(Object.assign({},e),{audio:c,video:d}),t)}}))}function Ju(e){return pr(this,void 0,void 0,(function*(){return(yield Gu({audio:!1,video:null==e||e}))[0]}))}function Qu(e){return pr(this,void 0,void 0,(function*(){return(yield Gu({audio:null==e||e,video:!1}))[0]}))}var Yu,Xu;e.ConnectionQuality=void 0,(Yu=e.ConnectionQuality||(e.ConnectionQuality={})).Excellent="excellent",Yu.Good="good",Yu.Poor="poor",Yu.Lost="lost",Yu.Unknown="unknown";class Zu extends br.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===gt.AGENT}get isActive(){var e;return(null===(e=this.participantInfo)||void 0===e?void 0:e.state)===mt.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(t,n,i,r,s,a){let o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:gt.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=e.ConnectionQuality.Unknown,this.log=sr,this.loggerOptions=a,this.log=or(null!==(c=null==a?void 0:a.loggerName)&&void 0!==c?c:e.LoggerNames.Participant,(()=>this.logContext)),this.setMaxListeners(100),this.sid=t,this.identity=n,this.name=i,this.metadata=r,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){const n=F(t,2)[1];if(n.source===e)return n}}getTrackPublicationByName(e){for(const t of this.trackPublications){const n=F(t,2)[1];if(n.trackName===e)return n}}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new To,this.once(e.ParticipantEvent.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(xa.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(xa.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(xa.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(t){var n;return!(this.participantInfo&&this.participantInfo.sid===t.sid&&this.participantInfo.version>t.version)&&(this.identity=t.identity,this.sid=t.sid,this._setName(t.name),this._setMetadata(t.metadata),this._setAttributes(t.attributes),t.state===mt.ACTIVE&&(null===(n=this.participantInfo)||void 0===n?void 0:n.state)!==mt.ACTIVE&&this.emit(e.ParticipantEvent.Active),t.permission&&this.setPermissions(t.permission),this.participantInfo=t,!0)}_setMetadata(t){const n=this.metadata!==t,i=this.metadata;this.metadata=t,n&&this.emit(e.ParticipantEvent.ParticipantMetadataChanged,i)}_setName(t){const n=this.name!==t;this.name=t,n&&this.emit(e.ParticipantEvent.ParticipantNameChanged,t)}_setAttributes(t){const n=function(e,t){var n;void 0===e&&(e={}),void 0===t&&(t={});const i=[...Object.keys(t),...Object.keys(e)],r={};for(const s of i)e[s]!==t[s]&&(r[s]=null!==(n=t[s])&&void 0!==n?n:"");return r}(this.attributes,t);this._attributes=t,Object.keys(n).length>0&&this.emit(e.ParticipantEvent.AttributesChanged,n)}setPermissions(t){var n,i,r,s,a,o;const c=this.permissions,d=t.canPublish!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublish)||t.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||t.canPublishData!==(null===(r=this.permissions)||void 0===r?void 0:r.canPublishData)||t.hidden!==(null===(s=this.permissions)||void 0===s?void 0:s.hidden)||t.recorder!==(null===(a=this.permissions)||void 0===a?void 0:a.recorder)||t.canPublishSources.length!==this.permissions.canPublishSources.length||t.canPublishSources.some(((e,t)=>{var n;return e!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishSources[t])}))||t.canSubscribeMetrics!==(null===(o=this.permissions)||void 0===o?void 0:o.canSubscribeMetrics);return this.permissions=t,d&&this.emit(e.ParticipantEvent.ParticipantPermissionsChanged,c),d}setIsSpeaking(t){t!==this.isSpeaking&&(this.isSpeaking=t,t&&(this.lastSpokeAt=new Date),this.emit(e.ParticipantEvent.IsSpeakingChanged,t))}setConnectionQuality(t){const n=this._connectionQuality;this._connectionQuality=function(t){switch(t){case it.EXCELLENT:return e.ConnectionQuality.Excellent;case it.GOOD:return e.ConnectionQuality.Good;case it.POOR:return e.ConnectionQuality.Poor;case it.LOST:return e.ConnectionQuality.Lost;default:return e.ConnectionQuality.Unknown}}(t),n!==this._connectionQuality&&this.emit(e.ParticipantEvent.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=>_o(t.track)&&t.track.setAudioContext(e)))}addTrackPublication(t){this.log.debug("adding track publication",{trackSid:t.trackSid,source:t.source,kind:t.kind}),t.on(e.TrackEvent.Muted,(()=>{this.emit(e.ParticipantEvent.TrackMuted,t)})),t.on(e.TrackEvent.Unmuted,(()=>{this.emit(e.ParticipantEvent.TrackUnmuted,t)}));const n=t;switch(n.track&&(n.track.sid=t.trackSid),this.trackPublications.set(t.trackSid,t),t.kind){case xa.Kind.Audio:this.audioTrackPublications.set(t.trackSid,t);break;case xa.Kind.Video:this.videoTrackPublications.set(t.trackSid,t)}}}class $u extends Zu{constructor(t,i,s,a,o,c,d,l){super(t,i,void 0,void 0,void 0,{loggerName:a.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=ft.NONE,this.e2eeStateMutex=new r,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new To)},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,n,i,r,s;this.reconnectFuture&&(this.reconnectFuture.promise.catch((e=>this.log.warn(e.message))),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===(i=(n=this.signalConnectedFuture).reject)||void 0===i||i.call(n,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),null===(s=null===(r=this.activeAgentFuture)||void 0===r?void 0:r.reject)||void 0===s||s.call(r,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,n;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new To),null===(n=(t=this.signalConnectedFuture).resolve)||void 0===n||n.call(t)},this.handleSignalRequestResponse=e=>{const t=e.requestId,n=e.reason,i=e.message,r=this.pendingSignalRequests.get(t);switch(r&&(n!==Wi.OK&&r.reject(new ea(i,n)),this.pendingSignalRequests.delete(t)),e.request.case){case"publishDataTrack":{let t;switch(e.reason){case Wi.NOT_ALLOWED:t=Iu.notAllowed(e.message);break;case Wi.DUPLICATE_NAME:t=Iu.duplicateName(e.message);break;case Wi.INVALID_NAME:t=Iu.invalidName(e.message);break;case Wi.LIMIT_EXCEEDED:t=Iu.limitReached(e.message);break;default:t=Iu.unknown(e.reason,e.message)}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(e.request.value.pubHandle,{type:"error",error:t});break}}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map((e=>function(e){var t,n,i;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new _i({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(n=e.participantSid)&&void 0!==n?n:"",allTracks:null!==(i=e.allowAll)&&void 0!==i&&i,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",Da(e))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Da(e)),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Da(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.onTrackCpuConstrained=(t,n)=>{this.log.debug("track cpu constrained",Da(n)),this.emit(e.ParticipantEvent.LocalTrackCpuConstrained,t,n)},this.handleSubscribedQualityUpdate=e=>pr(this,void 0,void 0,(function*(){var t,n,i,r,s;if(!(null===(s=this.roomOptions)||void 0===s?void 0:s.dynacast))return;const a=this.videoTrackPublications.get(e.trackSid);if(!a)return void this.log.warn("received subscribed quality update for unknown track",{trackSid:e.trackSid});if(!a.videoTrack)return;const o=yield a.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=fr(o);!(t=(c=yield l.next()).done);d=!0){r=c.value,d=!1;const e=r;ga(e)&&(this.log.debug("publish ".concat(e," for ").concat(a.videoTrack.sid),Da(a)),yield this.publishAdditionalCodecForTrack(a.videoTrack,e,a.options))}}catch(u){n={error:u}}finally{try{d||t||!(i=l.return)||(yield i.call(l))}finally{if(n)throw n.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",{trackSid:e.trackSid})},this.handleTrackEnded=e=>pr(this,void 0,void 0,(function*(){if(e.source===xa.Source.ScreenShare||e.source===xa.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Da(e)),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(Oo(e)||Do(e))try{if(no())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===xa.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Da(e)),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(n){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Da(e)),Oo(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(n){this.log.warn("could not restart track, muting instead",Da(e)),yield e.mute()}})),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=s,this.roomOptions=a,this.setupEngine(s),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.roomOutgoingDataStreamManager=o,this.roomOutgoingDataTrackManager=c,this.rpcClientManager=d,this.rpcServerManager=l}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==ft.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(t){var n;this.engine=t,this.engine.on(e.EngineEvent.RemoteMute,((e,t)=>{const n=this.trackPublications.get(e);n&&n.track&&(t?n.mute():n.unmute())})),(null===(n=this.signalConnectedFuture)||void 0===n?void 0:n.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(e.EngineEvent.Connected,this.handleReconnected).on(e.EngineEvent.SignalConnected,this.handleSignalConnected).on(e.EngineEvent.SignalRestarted,this.handleReconnected).on(e.EngineEvent.SignalResumed,this.handleReconnected).on(e.EngineEvent.Restarting,this.handleReconnecting).on(e.EngineEvent.Resuming,this.handleReconnecting).on(e.EngineEvent.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(e.EngineEvent.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(e.EngineEvent.Closing,this.handleClosing).on(e.EngineEvent.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return pr(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:e})}))}setName(e){return pr(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:e})}))}setAttributes(e){return pr(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:e})}))}requestMetadataUpdate(e){return pr(this,arguments,void 0,(function(e){var t=this;let i=e.metadata,r=e.name,s=e.attributes;return function*(){return new _s(((e,a)=>pr(t,void 0,void 0,(function*(){var t,o;try{let n=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(o=null!=r?r:this.name)&&void 0!==o?o:"",s),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{a(e),n=!0},values:{name:r,metadata:i,attributes:s}});performance.now()-d<5e3&&!n;){if((!r||this.name===r)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every((e=>{let t=F(e,2),n=t[0],i=t[1];return this.attributes[n]===i||""===i&&!this.attributes[n]}))))return this.pendingSignalRequests.delete(c),void e();yield qa(50)}a(new ea("Request to update local metadata timed out","TimeoutError"))}catch(n){n instanceof Error?a(n):a(new Error(String(n)))}}))))}()}))}setCameraEnabled(e,t,n){return this.setTrackEnabled(xa.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(xa.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(xa.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return pr(this,void 0,void 0,(function*(){const t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?ft.GCM:ft.NONE,yield Promise.all(this.pendingPublishPromises.values()),0===this.trackPublications.size||Array.from(this.trackPublications.values()).every((t=>t.isEncrypted===e)))return;yield this.republishAllTracks(void 0,!1)}finally{t()}}))}setTrackEnabled(t,i,r,s){return pr(this,void 0,void 0,(function*(){var a,o;this.log.debug("setTrackEnabled",{source:t,enabled:i}),this.republishPromise&&(yield this.republishPromise);let c=this.getTrackPublication(t);if(i)if(c)yield c.unmute();else{let i;if(this.pendingPublishing.has(t)){const e=yield this.waitForPendingPublicationOfSource(t);return e||this.log.info("waiting for pending publication promise timed out",{source:t}),yield null==e?void 0:e.unmute(),e}this.pendingPublishing.add(t);try{switch(t){case xa.Source.Camera:i=yield this.createTracks({video:null===(a=r)||void 0===a||a});break;case xa.Source.Microphone:i=yield this.createTracks({audio:null===(o=r)||void 0===o||o});break;case xa.Source.ScreenShare:i=yield this.createScreenTracks(Object.assign({},r));break;default:throw new Js(t)}}catch(n){throw null==i||i.forEach((e=>{e.stop()})),n instanceof Error&&this.emit(e.ParticipantEvent.MediaDevicesError,n,Pa(t)),this.pendingPublishing.delete(t),n}for(const e of i){const n=Object.assign(Object.assign({},this.roomOptions.publishDefaults),r);t===xa.Source.Microphone&&_o(e)&&n.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone"),e.startPreConnectBuffer())}try{const e=[];for(const t of i)this.log.info("publishing track",Da(t)),e.push(this.publishTrack(t,s));c=F(yield Promise.all(e),1)[0]}catch(n){throw null==i||i.forEach((e=>{e.stop()})),n}finally{this.pendingPublishing.delete(t)}}else if(!(null==c?void 0:c.track)&&this.pendingPublishing.has(t)&&(c=yield this.waitForPendingPublicationOfSource(t),c||this.log.info("waiting for pending publication promise timed out",{source:t})),c&&c.track)if(t===xa.Source.ScreenShare){const e=[this.unpublishTrack(c.track)],t=this.getTrackPublication(xa.Source.ScreenShareAudio);t&&t.track&&e.push(this.unpublishTrack(t.track)),c=F(yield Promise.all(e),1)[0]}else yield c.mute();return c}))}enableCameraAndMicrophone(){return pr(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(xa.Source.Camera)&&!this.pendingPublishing.has(xa.Source.Microphone)){this.pendingPublishing.add(xa.Source.Camera),this.pendingPublishing.add(xa.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(xa.Source.Camera),this.pendingPublishing.delete(xa.Source.Microphone)}}}))}createTracks(t){return pr(this,void 0,void 0,(function*(){var n,i;null!=t||(t={});const r=Ta(t,null===(n=this.roomOptions)||void 0===n?void 0:n.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults);try{const t=yield Gu(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return t.map((t=>(_o(t)&&(this.microphoneError=void 0,t.setAudioContext(this.audioContext),t.source=xa.Source.Microphone,this.emit(e.ParticipantEvent.AudioStreamAcquired)),Mo(t)&&(this.cameraError=void 0,t.source=xa.Source.Camera),t)))}catch(s){throw s instanceof Error&&(t.audio&&(this.microphoneError=s),t.video&&(this.cameraError=s)),s}}))}createScreenTracks(t){return pr(this,void 0,void 0,(function*(){if(void 0===t&&(t={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new Gs("getDisplayMedia not supported");void 0!==t.resolution||eo()||(t.resolution=ba.h1080fps30.resolution);const n=Ia(t),i=yield navigator.mediaDevices.getDisplayMedia(n),r=i.getVideoTracks();if(0===r.length)throw new Js("no video track found");const s=new ul(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=xa.Source.ScreenShare,t.contentHint&&(s.mediaStreamTrack.contentHint=t.contentHint);const a=[s];if(i.getAudioTracks().length>0){this.emit(e.ParticipantEvent.AudioStreamAcquired);const t=new Zd(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});t.source=xa.Source.ScreenShareAudio,a.push(t)}return a}))}publishTrack(e,t){return pr(this,void 0,void 0,(function*(){return this.publishOrRepublishTrack(e,t)}))}waitForNextEngineRestart(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:15e3;return new Promise(((n,i)=>{const r=()=>{clearTimeout(o),this.engine.off(e.EngineEvent.Restarted,s),this.engine.off(e.EngineEvent.Closing,a)},s=()=>{r(),n()},a=()=>{r(),i(new Error("engine closed before restart completed"))},o=setTimeout((()=>{r(),i(new Error("timed out waiting for engine restart"))}),t);this.engine.once(e.EngineEvent.Restarted,s),this.engine.once(e.EngineEvent.Closing,a)}))}publishOrRepublishTrack(e,t){return pr(this,arguments,void 0,(function(e,t){var i=this;let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return function*(){var a,o,c,d;let l,u;if(Oo(e)&&e.setAudioContext(i.audioContext),yield null===(a=i.reconnectFuture)||void 0===a?void 0:a.promise,i.republishPromise&&!r&&(yield i.republishPromise),Io(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)l=e.getConstraints();else{let t;switch(l=e.constraints,e.source){case xa.Source.Microphone:t="audioinput";break;case xa.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(l=Object.assign(Object.assign({},l),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new Zd(e,l,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new ul(e,l,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new Js("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&&(u=t)})),u)return i.log.warn("track has already been published, skipping",Da(u)),u;const h=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t),p="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,m=null!==(o=h.forceStereo)&&void 0!==o?o:p;m&&(void 0===h.dtx&&i.log.debug("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Da(e)),void 0===h.red&&i.log.debug("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(c=h.dtx)&&void 0!==c||(h.dtx=!1),null!==(d=h.red)&&void 0!==d||(h.red=!1)),!function(){const e=Os(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&lo(e.osVersion,t)>=0)||"Safari"===e.name&&lo(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"),h.simulcast=!1),h.source&&(e.source=h.source);const g=new Promise(((t,r)=>pr(i,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==td.CONNECTED){this.log.debug("deferring track publication until signal is connected",{track:Da(e)});let n=!1;const i=setTimeout((()=>{n=!0,e.stop(),r(new $s("publishing rejected as engine not connected within timeout",408))}),15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(i),n)return;const s=yield this.publish(e,h,m);t(s)}else try{const n=yield this.publish(e,h,m);t(n)}catch(n){r(n)}}catch(n){r(n)}}))));i.pendingPublishPromises.set(e,g);try{return yield g}catch(n){if(!s&&n instanceof Xs)return i.log.warn("negotiation due to track publish failed, retrying after reconnect",{error:n}),i.pendingPublishPromises.delete(e),yield i.waitForNextEngineRestart(),yield i.publishOrRepublishTrack(e,t,r,!0);throw n}finally{i.pendingPublishPromises.delete(e)}}()}))}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new To),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Da(e)),!1;const t=this.permissions,n=t.canPublish,i=t.canPublishSources;return!(!n||0!==i.length&&!i.map((e=>function(e){switch(e){case tt.CAMERA:return xa.Source.Camera;case tt.MICROPHONE:return xa.Source.Microphone;case tt.SCREEN_SHARE:return xa.Source.ScreenShare;case tt.SCREEN_SHARE_AUDIO:return xa.Source.ScreenShareAudio;default:return xa.Source.Unknown}}(e))).includes(e.source))||(this.log.warn("insufficient permissions to publish",Da(e)),!1)}publish(t,i,r){return pr(this,void 0,void 0,(function*(){var s,a,o,c,d,l,u,h,p,m;if(!this.hasPermissionsToPublish(t))throw new $s("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((e=>Io(t)&&e.source===t.source))&&t.source!==xa.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(t.source),Da(t)),i.stopMicTrackOnMute&&_o(t)&&(t.stopOnMute=!0),t.source===xa.Source.ScreenShare&&Ya()&&(i.simulcast=!1),"av1"!==i.videoCodec||Ha()||(i.videoCodec=void 0),"vp9"!==i.videoCodec||Ka()||(i.videoCodec=void 0),void 0===i.videoCodec&&(i.videoCodec=_d),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((e=>i.videoCodec===_a(e.mime)))||(i.videoCodec=_a(this.enabledPublishVideoCodecs[0].mime)));const g=i.videoCodec;t.on(e.TrackEvent.Muted,this.onTrackMuted),t.on(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.on(e.TrackEvent.Ended,this.handleTrackEnded),t.on(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.on(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed),t.on(e.TrackEvent.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const v=[],f=!(null===(s=i.dtx)||void 0===s||s),k=t.getSourceTrackSettings();k.autoGainControl&&v.push(ct.TF_AUTO_GAIN_CONTROL),k.echoCancellation&&v.push(ct.TF_ECHO_CANCELLATION),k.noiseSuppression&&v.push(ct.TF_NOISE_SUPPRESSION),k.channelCount&&k.channelCount>1&&v.push(ct.TF_STEREO),f&&v.push(ct.TF_NO_DTX),Oo(t)&&t.hasPreConnectBuffer&&v.push(ct.TF_PRECONNECT_BUFFER);const y=this.normalizeRequestedFrameMetadataOptions(t,i),b=new Wn({cid:t.mediaStreamTrack.id,name:i.name,type:xa.kindToProto(t.kind),muted:t.isMuted,source:xa.sourceToProto(t.source),disableDtx:f,encryption:this.encryptionType,stereo:r,disableRed:this.isE2EEEnabled||!(null===(a=i.red)||void 0===a||a),stream:null==i?void 0:i.stream,backupCodecPolicy:null==i?void 0:i.backupCodecPolicy,audioFeatures:v,packetTrailerFeatures:y});let T;if(t.kind===xa.Kind.Video){let e;try{e=yield t.waitForDimensions()}catch(n){const r=null!==(c=null===(o=this.roomOptions.videoCaptureDefaults)||void 0===o?void 0:o.resolution)&&void 0!==c?c:ka.h720.resolution;e={width:r.width,height:r.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},Da(t)),{dims:e}))}b.width=e.width,b.height=e.height,Do(t)&&(za(g)&&(t.source===xa.Source.ScreenShare&&(i.scalabilityMode="L1T3","contentHint"in t.mediaStreamTrack&&(t.mediaStreamTrack.contentHint="motion",this.log.debug("forcing contentHint to motion for screenshare with SVC codecs",Da(t)))),i.scalabilityMode=null!==(d=i.scalabilityMode)&&void 0!==d?d:"L3T3_KEY"),b.simulcastCodecs=[new Vn({codec:g,cid:t.mediaStreamTrack.id})],!0===i.backupCodec&&(i.backupCodec={codec:_d}),i.backupCodec&&g!==i.backupCodec.codec&&b.encryption===ft.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),b.simulcastCodecs.push(new Vn({codec:i.backupCodec.codec,cid:""})))),T=sl(t.source===xa.Source.ScreenShare,b.width,b.height,i),b.layers=ml(b.width,b.height,T,za(i.videoCodec))}else t.kind===xa.Kind.Audio&&(T=[{maxBitrate:null===(l=i.audioPreset)||void 0===l?void 0:l.maxBitrate,priority:null!==(h=null===(u=i.audioPreset)||void 0===u?void 0:u.priority)&&void 0!==h?h:"high",networkPriority:null!==(m=null===(p=i.audioPreset)||void 0===p?void 0:p.priority)&&void 0!==m?m:"high"}]);if(!this.engine||this.engine.isClosed)throw new Ys("cannot publish track when not connected");const S=()=>pr(this,void 0,void 0,(function*(){var n,r,s,a;if(!this.engine.pcManager)throw new Ys("pcManager is not ready");if(t.sender=yield this.engine.createSender(t,i,T),Do(t)&&(t.publishOptions=i),this.emit(e.ParticipantEvent.LocalSenderCreated,t.sender,t),Do(t)&&(null!==(n=i.degradationPreference)&&void 0!==n||(i.degradationPreference=function(e){switch(e.source){case xa.Source.Camera:return"maintain-framerate";case xa.Source.ScreenShare:return"maintain-resolution";default:return"balanced"}}(t)),t.setDegradationPreference(i.degradationPreference)),T)if(Ya()&&t.kind===xa.Kind.Audio){let e;for(const n of this.engine.pcManager.publisher.getTransceivers())if(n.sender===t.sender){e=n;break}e&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:e,codec:"opus",maxbr:(null===(r=T[0])||void 0===r?void 0:r.maxBitrate)?T[0].maxBitrate/1e3:0})}else if(t.codec&&So(t.codec)){const e=za(t.codec)?null!==(a=null===(s=T[0])||void 0===s?void 0:s.maxBitrate)&&void 0!==a?a:0:T.reduce(((e,t)=>{var n;return e+(null!==(n=t.maxBitrate)&&void 0!==n?n:0)}),0);e>0&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:b.cid,codec:t.codec,maxbr:e/1e3,isScreenShare:t.source===xa.Source.ScreenShare})}yield this.engine.negotiate()}));let E;const C=new Promise(((e,i)=>pr(this,void 0,void 0,(function*(){var r;try{E=yield this.engine.addTrack(b),e(E)}catch(s){if(t.sender&&(null===(r=this.engine.pcManager)||void 0===r?void 0:r.publisher)){try{this.engine.pcManager.publisher.removeTrack(t.sender)}catch(n){this.log.error(n)}yield this.engine.negotiate().catch((e=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign({},Da(t)),{error:e}))}))}i(s)}}))));if(this.enabledPublishVideoCodecs.length>0&&0===y.length){const e=yield Promise.all([C,S()]);E=e[0]}else{let e;if(E=yield C,E.codecs.forEach((t=>{void 0===e&&(e=t.mimeType)})),e&&t.kind===xa.Kind.Video){const n=_a(e);n!==g&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign({},Da(t)),{codec:n})),i.videoCodec=n,T=sl(t.source===xa.Source.ScreenShare,b.width,b.height,i))}yield S()}const w=new zu(t.kind,E,t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(w.on(e.TrackEvent.CpuConstrained,(e=>this.onTrackCpuConstrained(e,w))),w.options=i,t.sid=E.sid,Do(t)&&(t.publishOptions=i,b.width&&b.height&&(t.lastEncodedDimensions={width:b.width,height:b.height})),this.log.debug("publishing ".concat(t.kind," with encodings"),{encodings:T,trackInfo:E}),Do(t)?t.startMonitor(this.engine.client):Oo(t)&&t.startMonitor(),this.addTrackPublication(w),this.emit(e.ParticipantEvent.LocalTrackPublished,w),Oo(t)&&E.audioFeatures.includes(ct.TF_PRECONNECT_BUFFER)){const i=t.getPreConnectBuffer(),r=t.getPreConnectBufferMimeType();if(this.on(e.ParticipantEvent.LocalTrackSubscribed,(e=>{if(e.trackSid===E.sid){if(!t.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed");this.log.debug("finished recording preconnect buffer",Da(t)),t.stopPreConnectBuffer()}})),i){const e=new Promise(((e,s)=>pr(this,void 0,void 0,(function*(){var a,o,c,d,l,u;try{this.log.debug("waiting for agent",Da(t));const n=setTimeout((()=>{s(new Error("agent not active within 10 seconds"))}),1e4),v=yield this.waitUntilActiveAgentPresent();clearTimeout(n),this.log.debug("sending preconnect buffer",Da(t));const f=yield this.streamBytes({name:"preconnect-buffer",mimeType:r,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[v.identity],attributes:{trackId:w.trackSid,sampleRate:String(null!==(l=k.sampleRate)&&void 0!==l?l:"48000"),channels:String(null!==(u=k.channelCount)&&void 0!==u?u:"1")}});try{for(var h,p=!0,m=fr(i);!(a=(h=yield m.next()).done);p=!0){d=h.value,p=!1;const e=d;yield f.write(e)}}catch(g){o={error:g}}finally{try{p||a||!(c=m.return)||(yield c.call(m))}finally{if(o)throw o.error}}yield f.close(),e()}catch(n){s(n)}}))));e.then((()=>{this.log.debug("preconnect buffer sent successfully",Da(t))})).catch((e=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign({},Da(t)),{error:e}))}))}}return w}))}canPublishFrameMetadata(){var e;return!!(this.roomOptions.e2ee||this.roomOptions.encryption||sc(null!==(e=this.roomOptions.frameMetadata)&&void 0!==e?e:this.roomOptions.packetTrailer))}normalizeRequestedFrameMetadataOptions(e,t){var n;const i=null!==(n=t.frameMetadata)&&void 0!==n?n:t.packetTrailer;if(e.kind!==xa.Kind.Video||!ac(i))return t.frameMetadata=void 0,t.packetTrailer=void 0,[];if(!this.canPublishFrameMetadata())return this.log.warn("frame metadata transform not supported; not advertising features",Object.assign(Object.assign({},this.logContext),Da(e))),t.frameMetadata=void 0,t.packetTrailer=void 0,[];const r=function(e){const t=[];return(null==e?void 0:e.timestamp)&&t.push(dt.PTF_USER_TIMESTAMP),(null==e?void 0:e.frameId)&&t.push(dt.PTF_FRAME_ID),t}(i),s=function(e){if(!e||0===e.length)return;const t={};return e.includes(dt.PTF_USER_TIMESTAMP)&&(t.timestamp=!0),e.includes(dt.PTF_FRAME_ID)&&(t.frameId=!0),t.timestamp||t.frameId?t:void 0}(r);return t.frameMetadata=s,t.packetTrailer=s,r}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return pr(this,void 0,void 0,(function*(){var i;if(this.encryptionType!==ft.NONE)return;let r;if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(r=t)})),!r)throw new Js("track is not published");if(!Do(e))throw new Js("track is not a video track");const s=Object.assign(Object.assign({},null===(i=this.roomOptions)||void 0===i?void 0:i.publishDefaults),n),a=al(e,t,s);if(!a)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Da(e));const o=e.addSimulcastTrack(t,a);if(!o)return;const c=this.normalizeRequestedFrameMetadataOptions(e,s),d=new Wn({cid:o.mediaStreamTrack.id,type:xa.kindToProto(e.kind),muted:e.isMuted,source:xa.sourceToProto(e.source),sid:e.sid,packetTrailerFeatures:c,simulcastCodecs:[{codec:s.videoCodec,cid:o.mediaStreamTrack.id}]});if(d.layers=ml(d.width,d.height,a),!this.engine||this.engine.isClosed)throw new Ys("cannot publish track when not connected");const l=(yield Promise.all([this.engine.addTrack(d),(()=>pr(this,void 0,void 0,(function*(){yield this.engine.createSimulcastSender(e,o,s,a),yield this.engine.negotiate()})))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),{encodings:a,trackInfo:l})}))}unpublishTrack(t,i){return pr(this,void 0,void 0,(function*(){var r,s;if(Io(t)){const e=this.pendingPublishPromises.get(t);e&&(this.log.debug("awaiting publish promise before attempting to unpublish",Da(t)),yield e)}const a=this.getPublicationForTrack(t),o=a?Da(a):void 0;if(this.log.info("unpublishing track",o),!a||!a.track)return void this.log.warn("track was not unpublished because no publication was found",o);(t=a.track).off(e.TrackEvent.Muted,this.onTrackMuted),t.off(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.off(e.TrackEvent.Ended,this.handleTrackEnded),t.off(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.off(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed),t.off(e.TrackEvent.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===i&&(i=null===(s=null===(r=this.roomOptions)||void 0===r?void 0:r.stopLocalTrackOnUnpublish)||void 0===s||s),i?t.stop():t.stopMonitor();let c=!1;const d=t.sender;if(t.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Ld.FAILED&&d)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===d&&(e.direction="inactive",c=!0);try{c=this.engine.removeTrack(d)}catch(n){this.log.warn(n),c=!0}if(Do(t)){for(const e of t.simulcastCodecs){const t=F(e,2)[1];if(t.sender){try{c=this.engine.removeTrack(t.sender)}catch(n){this.log.warn(n),c=!0}t.sender=void 0}}t.simulcastCodecs.clear()}}catch(n){this.log.warn("failed to unpublish track",Object.assign(Object.assign({},o),{error:n}))}switch(this.trackPublications.delete(a.trackSid),a.kind){case xa.Kind.Audio:this.audioTrackPublications.delete(a.trackSid);break;case xa.Kind.Video:this.videoTrackPublications.delete(a.trackSid)}return this.emit(e.ParticipantEvent.LocalTrackUnpublished,a),a.setTrack(void 0),c&&(yield this.engine.negotiate()),a}))}unpublishTracks(e){return pr(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>!!e))}))}republishAllTracks(e){return pr(this,arguments,void 0,(function(e){var t=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new _s(((i,r)=>pr(t,void 0,void 0,(function*(){try{const t=[];this.trackPublications.forEach((n=>{n.track&&(e&&(n.options=Object.assign(Object.assign({},n.options),e)),t.push(n))})),yield Promise.all(t.map((e=>pr(this,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),!n||t.isMuted||t.source===xa.Source.ScreenShare||t.source===xa.Source.ScreenShareAudio||!Oo(t)&&!Do(t)||t.isUserProvided||(this.log.debug("restarting existing track",{track:e.trackSid}),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))))),i()}catch(t){t instanceof Error?r(t):r(new Error(String(t)))}finally{this.republishPromise=void 0}})))),yield t.republishPromise}()}))}publishData(e){return pr(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){const i=n.reliable?xd.RELIABLE:xd.LOSSY,r=n.reliable?Ot.RELIABLE:Ot.LOSSY,s=n.destinationIdentities,a=n.topic;let o=new Ut({participantIdentity:t.identity,payload:e,destinationIdentities:s,topic:a});const c=new Dt({kind:r,value:{case:"user",value:o}});yield t.engine.sendDataPacket(c,i)}()}))}publishDtmf(e,t){return pr(this,void 0,void 0,(function*(){const n=new Dt({kind:Ot.RELIABLE,value:{case:"sipDtmf",value:new Ft({code:e,digit:t})}});yield this.engine.sendDataPacket(n,xd.RELIABLE)}))}sendChatMessage(t,n){return pr(this,void 0,void 0,(function*(){const i={id:crypto.randomUUID(),message:t,timestamp:Date.now(),attachedFiles:null==n?void 0:n.attachments},r=new Dt({value:{case:"chatMessage",value:new qt(Object.assign(Object.assign({},i),{timestamp:R.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,xd.RELIABLE),this.emit(e.ParticipantEvent.ChatMessage,i),i}))}editChatMessage(t,n){return pr(this,void 0,void 0,(function*(){const i=Object.assign(Object.assign({},n),{message:t,editTimestamp:Date.now()}),r=new Dt({value:{case:"chatMessage",value:new qt(Object.assign(Object.assign({},i),{timestamp:R.parse(i.timestamp),editTimestamp:R.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,xd.RELIABLE),this.emit(e.ParticipantEvent.ChatMessage,i),i}))}sendText(e,t){return pr(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)}))}streamText(e){return pr(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamText(e)}))}sendFile(e,t){return pr(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)}))}sendBytes(e,t){return pr(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendBytes(e,t)}))}streamBytes(e){return pr(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)}))}performRpc(e){return this.rpcClientManager.performRpc(e).then((e=>{let t=F(e,2);return t[0],t[1]}))}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(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()}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,n;const i=this.trackPublications.get(e.sid);if(i){const r=i.isMuted||null!==(n=null===(t=i.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==n&&n;r!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign({},Da(i)),{mutedOnServer:r})),this.engine.client.sendMuteTrack(e.sid,r))}})),!0)}setActiveAgent(e){var t,n,i,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?null===(n=null===(t=this.activeAgentFuture)||void 0===t?void 0:t.resolve)||void 0===n||n.call(t,e):null===(r=null===(i=this.activeAgentFuture)||void 0===i?void 0:i.reject)||void 0===r||r.call(i,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new To),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach((n=>{const i=n.track;i&&(e instanceof MediaStreamTrack?(Oo(i)||Do(i))&&i.mediaStreamTrack===e&&(t=n):e===i&&(t=n))})),t}waitForPendingPublicationOfSource(e){return pr(this,void 0,void 0,(function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find((t=>F(t,1)[0].source===e));if(t)return t[1];yield qa(20)}}))}publishDataTrack(e){return pr(this,void 0,void 0,(function*(){const t=new Du(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t}))}}class eh extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}}class th extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var n,i;super.set(e,t);const r=null===(n=this.pending)||void 0===n?void 0:n.get(e);if(r){for(const e of r)e.isResolved||null===(i=e.resolve)||void 0===i||i.call(e,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return"DeferrableMap"}getDeferred(e,t){return pr(this,void 0,void 0,(function*(){const n=this.get(e);if(void 0!==n)return n;if(null==t?void 0:t.aborted)throw new eh("The operation was aborted.",t.reason);const i=new To(void 0,(()=>{const t=this.pending.get(e);if(!t)return;const n=t.indexOf(i);-1!==n&&t.splice(n,1),0===t.length&&this.pending.delete(e)})),r=this.pending.get(e);if(r?r.push(i):this.pending.set(e,[i]),t){const e=()=>{var e;i.isResolved||null===(e=i.reject)||void 0===e||e.call(i,new eh("The operation was aborted.",t.reason))};t.addEventListener("abort",e,{once:!0}),i.promise.finally((()=>{t.removeEventListener("abort",e)}))}return i.promise}))}}class nh extends Ku{constructor(t,n,i,r){super(t,n.sid,n.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=t=>{this.setTrack(void 0),this.emit(e.TrackEvent.Ended,t)},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(n)}setSubscribed(t){const n=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=t,t&&(this.allowed=!0);const r=new ri({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new zt({participantSid:"",trackSids:[this.trackSid]})]});this.emit(e.TrackEvent.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?Ku.SubscriptionStatus.Unsubscribed:super.isSubscribed?Ku.SubscriptionStatus.Subscribed:Ku.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Ku.PermissionStatus.Allowed:Ku.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,n;this.isManualOperationAllowed()&&((null===(t=this.requestedVideoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(n=this.requestedVideoDimensions)||void 0===n?void 0:n.height)===e.height||(Lo(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Lo(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var t;return null!==(t=this.requestedMaxQuality)&&void 0!==t?t:e.VideoQuality.HIGH}setTrack(t){const n=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==t&&(r&&(r.off(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),r.off(e.TrackEvent.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(e.TrackEvent.Unsubscribed,r)),super.setTrack(t),t&&(t.sid=this.trackSid,t.on(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),t.on(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),t.on(e.TrackEvent.Ended,this.handleEnded),this.emit(e.TrackEvent.Subscribed,t)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(t){this.emit(e.TrackEvent.SubscriptionFailed,t)}updateInfo(t){super.updateInfo(t);const n=this.metadataMuted;this.metadataMuted=t.muted,this.track?this.track.setMuted(t.muted):n!==t.muted&&this.emit(t.muted?e.TrackEvent.Muted:e.TrackEvent.Unmuted)}emitSubscriptionUpdateIfChanged(t){const n=this.subscriptionStatus;t!==n&&this.emit(e.TrackEvent.SubscriptionStatusChanged,n,t)}emitPermissionUpdateIfChanged(t){this.permissionStatus!==t&&this.emit(e.TrackEvent.SubscriptionPermissionChanged,this.permissionStatus,t)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Lo(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=new ui({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===xa.Kind.Video){let n=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(n){Aa(this.videoDimensionsAdaptiveStream,n)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream)}else if(void 0!==this.requestedMaxQuality&&this.trackInfo){const e=function(e,t){var n;return null===(n=e.layers)||void 0===n?void 0:n.find((e=>e.quality===t))}(this.trackInfo,this.requestedMaxQuality);e&&Aa(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream;n?(t.width=Math.ceil(n.width),t.height=Math.ceil(n.height)):void 0!==this.requestedMaxQuality?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),t.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:e.VideoQuality.HIGH})),t.quality=e.VideoQuality.HIGH)}this.emit(e.TrackEvent.UpdateSettings,t)}}class ih extends Zu{static fromParticipantInfo(e,t,n,i){return new ih(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind,t.dataTracks.map((e=>{const n=Oc.from(e);return new cu(n,i,{publisherIdentity:t.identity})})),t.clientProtocol,t.capabilities)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,i,r,s,a){let o=arguments.length>7&&void 0!==arguments[7]?arguments[7]:gt.STANDARD,c=arguments.length>8&&void 0!==arguments[8]?arguments[8]:[],d=arguments.length>9&&void 0!==arguments[9]?arguments[9]:0,l=arguments.length>10&&void 0!==arguments[10]?arguments[10]:[];super(t,n||"",i,r,s,a,o),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new th(c.map((e=>[e.info.name,e]))),this.volumeMap=new Map,this.clientProtocol=d,this.capabilities=l}addTrackPublication(t){super.addTrackPublication(t),t.on(e.TrackEvent.UpdateSettings,(e=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),Da(t)),{settings:e})),this.signalClient.sendUpdateTrackSettings(e)})),t.on(e.TrackEvent.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),t.on(e.TrackEvent.SubscriptionPermissionChanged,(n=>{this.emit(e.ParticipantEvent.TrackSubscriptionPermissionChanged,t,n)})),t.on(e.TrackEvent.SubscriptionStatusChanged,(n=>{this.emit(e.ParticipantEvent.TrackSubscriptionStatusChanged,t,n)})),t.on(e.TrackEvent.Subscribed,(n=>{this.emit(e.ParticipantEvent.TrackSubscribed,n,t)})),t.on(e.TrackEvent.Unsubscribed,(n=>{this.emit(e.ParticipantEvent.TrackUnsubscribed,n,t)})),t.on(e.TrackEvent.SubscriptionFailed,(n=>{this.emit(e.ParticipantEvent.TrackSubscriptionFailed,t.trackSid,n)}))}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]:xa.Source.Microphone;this.volumeMap.set(t,e);const n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:xa.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(t,n,i,r,s,a){let o=this.getTrackPublicationBySid(n);if(o||n.startsWith("TR")||this.trackPublications.forEach((e=>{o||t.kind!==e.kind.toString()||(o=e)})),!o)return 0===a?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:n})),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,n)):(void 0===a&&(a=20),void setTimeout((()=>{this.addSubscribedMediaTrack(t,n,i,r,s,a-1)}),150));if("ended"===t.readyState)return this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),Da(o))),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,n);let c;return c="video"===t.kind?new uc(t,n,r,s):new Hu(t,n,r,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(i),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&Ao(c)&&_o(c)&&c.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(t){if(!super.updateInfo(t))return!1;const n=new Map,i=new Map;return t.tracks.forEach((e=>{var t,r;let s=this.getTrackPublicationBySid(e.sid);if(s)s.updateInfo(e);else{const n=xa.kindFromProto(e.type);if(!n)return;s=new nh(n,e,null===(t=this.signalClient.connectOptions)||void 0===t?void 0:t.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(r=this.loggerOptions)||void 0===r?void 0:r.loggerName}),s.updateInfo(e),i.set(e.sid,s);const a=Array.from(this.trackPublications.values()).find((e=>e.source===(null==s?void 0:s.source)));a&&s.source!==xa.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(s.source),Object.assign(Object.assign({},this.logContext),{oldTrack:Da(a),newTrack:Da(s)})),this.addTrackPublication(s)}n.set(e.sid,s)})),this.trackPublications.forEach((e=>{n.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),Da(e))),this.unpublishTrack(e.trackSid,!0))})),i.forEach((t=>{this.emit(e.ParticipantEvent.TrackPublished,t)})),!0}unpublishTrack(t,n){const i=this.trackPublications.get(t);if(!i)return;const r=i.track;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(t),i.kind){case xa.Kind.Audio:this.audioTrackPublications.delete(t);break;case xa.Kind.Video:this.videoTrackPublications.delete(t)}n&&this.emit(e.ParticipantEvent.TrackUnpublished,i)}setAudioOutput(e){return pr(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((n=>{var i;_o(n.track)&&Ao(n.track)&&t.push(n.track.setSinkId(null!==(i=e.deviceId)&&void 0!==i?i:"default"))})),yield Promise.all(t)}))}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(const n of this.dataTracks.entries()){var t=F(n,2);const i=t[0];e===t[1].info.sid&&this.dataTracks.delete(i)}}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}e.ConnectionState=void 0,(Xu=e.ConnectionState||(e.ConnectionState={})).Disconnected="disconnected",Xu.Connecting="connecting",Xu.Connected="connected",Xu.Reconnecting="reconnecting",Xu.SignalReconnecting="signalReconnecting";class rh extends br.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(t){var i,s,a,o,c,d,l,u;if(super(),i=this,this.state=e.ConnectionState.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new r,this.isVideoPlaybackBlocked=!1,this.log=sr,this.statsLog=sr,this.bufferedEvents=[],this.isResuming=!1,this.pendingTrackAddedCallbacks=new Map,this.connect=(t,n,i)=>pr(this,void 0,void 0,(function*(){var r;if(!Qa())throw io()?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===e.ConnectionState.Connected)return this.log.info("already connected to room ".concat(this.name)),s(),Promise.resolve();if(this.connectFuture)return s(),this.connectFuture.promise;this.setAndEmitConnectionState(e.ConnectionState.Connecting),(null===(r=this.regionUrlProvider)||void 0===r?void 0:r.getServerUrl().toString())!==qo(t)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),ro(new URL(t))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new Tl(t,n):this.regionUrlProvider.updateToken(n),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",{error:e})})));const a=(r,o,c)=>pr(this,void 0,void 0,(function*(){var d,l;this.abortController&&this.abortController.abort();const u=new AbortController;this.abortController=u,null==s||s();try{if(yield yc.getInstance().getBackOffPromise(t),u.signal.aborted)throw zs.cancelled("Connection attempt aborted");yield this.attemptConnection(null!=c?c:t,n,i,u),this.abortController=void 0,r()}catch(h){if(this.regionUrlProvider&&h instanceof zs&&h.reason!==e.ConnectionErrorReason.Cancelled&&h.reason!==e.ConnectionErrorReason.NotAllowed){let n=null;try{this.log.debug("Fetching next region"),n=yield this.regionUrlProvider.getNextBestRegionUrl(null===(d=this.abortController)||void 0===d?void 0:d.signal)}catch(p){if(p instanceof zs&&(401===p.status||p.reason===e.ConnectionErrorReason.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void o(p)}[e.ConnectionErrorReason.InternalError,e.ConnectionErrorReason.ServerUnreachable,e.ConnectionErrorReason.Timeout].includes(h.reason)&&(this.log.debug("Adding failed connection attempt to back off"),yc.getInstance().addFailedConnectionAttempt(t)),n&&!(null===(l=this.abortController)||void 0===l?void 0:l.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(h.message,". Retrying with another region: ").concat(n)),this.recreateEngine(!0),yield a(r,o,n)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,wo(h)),o(h))}else{let e=st.UNKNOWN_REASON;h instanceof zs&&(e=wo(h)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),o(h)}}})),o=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new To(((e,t)=>{a(e,t,o)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,n,i,r,s)=>pr(this,void 0,void 0,(function*(){const a=yield n.join(e,t,{autoSubscribe:i.autoSubscribe,adaptiveStream:"object"==typeof r.adaptiveStream||r.adaptiveStream,clientInfoCapabilities:this.getClientInfoCapabilities(r),maxRetries:i.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:i.websocketTimeout},s.signal,!r.singlePeerConnection),o=a.joinResponse,c=a.serverInfo;if(this.serverInfo=c,!c.version)throw new Qs("unknown server version");return"0.15.1"===c.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version"),r.dynacast=!1),o})),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(n){this.log.error(n instanceof Error?n.message:"Could not set SifTrailer",{error:n})}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(t,i,r,s)=>pr(this,void 0,void 0,(function*(){var a,o;this.state===e.ConnectionState.Reconnecting||this.isResuming||(null===(a=this.engine)||void 0===a?void 0:a.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine(!0)):this.maybeCreateEngine(),(null===(o=this.regionUrlProvider)||void 0===o?void 0:o.isCloud())&&this.engine.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Nd),r),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const n=yield this.connectSignal(t,i,this.engine,this.connOptions,this.options,s);this.applyJoinResponse(n),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected)}catch(c){yield this.engine.close(),this.recreateEngine();const e=s.signal.aborted?zs.cancelled("Signal connection aborted"):zs.serverUnreachable("could not establish signal connection");throw c instanceof Error&&(e.message="".concat(e.message,": ").concat(c.message)),c instanceof zs&&(e.reason=c.reason,e.status=c.status),this.log.debug("error trying to establish signal connection",{error:c}),e}if(s.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),zs.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,s)}catch(n){throw yield this.engine.close(),this.recreateEngine(),n}no()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),no()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Connected),yc.getInstance().resetFailedConnectionAttempts(t),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()})),this.disconnect=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return pr(i,[...n],void 0,(function(){var t=this;let n=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,r,s;const a=yield t.disconnectLock.lock();try{if(t.state===e.ConnectionState.Disconnected)return void t.log.debug("already disconnected");if(t.log.info("disconnect from room"),t.state===e.ConnectionState.Connecting||t.state===e.ConnectionState.Reconnecting||t.isResuming){const e="Abort connection attempt due to user initiated disconnect";t.log.warn(e),null===(i=t.abortController)||void 0===i||i.abort(e),null===(s=null===(r=t.connectFuture)||void 0===r?void 0:r.reject)||void 0===s||s.call(r,zs.cancelled("Client initiated disconnect")),t.connectFuture=void 0}t.engine&&(t.engine.client.isDisconnected||(yield t.engine.client.sendLeave()),yield t.engine.close()),t.handleDisconnect(n,st.CLIENT_INITIATED),t.engine=void 0}finally{a()}}()}))},this.onPageLeave=()=>pr(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting"),yield this.disconnect()})),this.startAudio=()=>pr(this,void 0,void 0,(function*(){const t=[],n=Os();if(n&&"iOS"===n.os){const n="livekit-dummy-audio-el";let i=document.getElementById(n);if(!i){i=document.createElement("audio"),i.id=n,i.autoplay=!0,i.hidden=!0;const t=bo();t.enabled=!0;const r=new MediaStream([t]);i.srcObject=r,document.addEventListener("visibilitychange",(()=>{i&&(i.srcObject=document.hidden?null:r,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status"),this.startAudio()))})),document.body.append(i),this.once(e.RoomEvent.Disconnected,(()=>{null==i||i.remove(),i=null}))}t.push(i)}this.remoteParticipants.forEach((e=>{e.audioTrackPublications.forEach((e=>{e.track&&e.track.attachedElements.forEach((e=>{t.push(e)}))}))}));try{yield Promise.all([this.acquireAudioContext(),...t.map((e=>(this.options.webAudioMix||(e.muted=!1),e.play())))]),this.handleAudioPlaybackStarted()}catch(i){throw this.handleAudioPlaybackFailed(i),i}})),this.startVideo=()=>pr(this,void 0,void 0,(function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach((t=>{var n;null===(n=t.track)||void 0===n||n.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.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=t=>pr(this,void 0,void 0,(function*(){this.log.debug("signal reconnected to server, region ".concat(t.serverRegion),{region:t.serverRegion}),this.bufferedEvents=[],this.applyJoinResponse(t);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(n){this.log.error("error trying to re-publish tracks after reconnection",{error:n})}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",{region:t.serverRegion})}catch(s){return}this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()})),this.handleParticipantUpdates=e=>{var t;for(const i of e){if(i.identity===this.localParticipant.identity){this.localParticipant.updateInfo(i);continue}""===i.identity&&(i.identity=null!==(t=this.sidToIdentity.get(i.sid))&&void 0!==t?t:"");let e=this.remoteParticipants.get(i.identity);i.state===mt.DISCONNECTED?this.handleParticipantDisconnected(i.identity,e,i.disconnectReason===st.UNKNOWN_REASON?void 0:i.disconnectReason):this.getOrCreateParticipant(i.identity,i)}const n=new Map(e.filter((e=>e.identity!==this.localParticipant.identity)).map((e=>[e.identity,e.dataTracks.map((e=>Oc.from(e)))])));this.incomingDataTrackManager.receiveSfuPublicationUpdates(n)},this.handleActiveSpeakersUpdate=t=>{const n=[],i={};t.forEach((e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),n.push(this.localParticipant);else{const t=this.getRemoteParticipantBySid(e.sid);t&&(t.audioLevel=e.level,t.setIsSpeaking(!0),n.push(t))}})),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=n,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,n)},this.handleSpeakersChanged=t=>{const n=new Map;this.activeSpeakers.forEach((e=>{const t=this.remoteParticipants.get(e.identity);t&&t.sid!==e.sid||n.set(e.sid,e)})),t.forEach((e=>{let t=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(t=this.localParticipant),t&&(t.audioLevel=e.level,t.setIsSpeaking(e.active),e.active?n.set(e.sid,t):n.delete(e.sid))}));const i=Array.from(n.values());i.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=i,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=t=>{t.streamStates.forEach((t=>{const n=this.getRemoteParticipantBySid(t.participantSid);if(!n)return;const i=n.getTrackPublicationBySid(t.trackSid);if(!i||!i.track)return;const r=xa.streamStateFromProto(t.state),s=i.track.streamState;i.track.setStreamState(r),r!==s&&(n.emit(e.ParticipantEvent.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(e.RoomEvent.TrackStreamStateChanged,i,i.track.streamState,n))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const n=t.getTrackPublicationBySid(e.trackSid);n&&n.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{this.cancelPendingTrackAdded(e.trackSid);const t=Array.from(this.remoteParticipants.values()).find((t=>t.trackPublications.has(e.trackSid)));if(!t)return;const n=t.getTrackPublicationBySid(e.trackSid);n&&n.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{const n=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(n,e.value.value,e.kind,t);else if("transcription"===e.value.case)this.handleTranscription(n,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(n,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(n,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,n);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.rpcServerManager.handleIncomingRpcRequest(e.participantIdentity,t)}else if("rpcResponse"===e.value.case){const t=e.value.value;switch(t.value.case){case"payload":this.rpcClientManager.handleIncomingRpcResponseSuccess(t.requestId,t.value.value);break;case"error":this.rpcClientManager.handleIncomingRpcResponseFailure(t.requestId,xu.fromProto(t.value.value));break;default:this.log.warn("Unknown rpcResponse.value.case: ".concat(t.value.case),this.logContext)}}else"rpcAck"===e.value.case&&this.rpcClientManager.handleIncomingRpcAck(e.value.value.requestId)},this.handleUserPacket=(t,n,i,r)=>{this.emit(e.RoomEvent.DataReceived,n.payload,t,i,n.topic,r),null==t||t.emit(e.ParticipantEvent.DataReceived,n.payload,i,r)},this.handleSipDtmf=(t,n)=>{this.emit(e.RoomEvent.SipDTMFReceived,n,t),null==t||t.emit(e.ParticipantEvent.SipDTMFReceived,n)},this.handleTranscription=(t,n)=>{const i=n.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(n.transcribedParticipantIdentity),r=null==i?void 0:i.trackPublications.get(n.trackId),s=function(e,t){return e.segments.map((e=>{let n=e.id,i=e.text,r=e.language,s=e.startTime,a=e.endTime,o=e.final;var c;const d=null!==(c=t.get(n))&&void 0!==c?c:Date.now(),l=Date.now();return o?t.delete(n):t.set(n,d),{id:n,text:i,startTime:Number.parseInt(s.toString()),endTime:Number.parseInt(a.toString()),final:o,language:r,firstReceivedTime:d,lastReceivedTime:l}}))}(n,this.transcriptionReceivedTimes);null==r||r.emit(e.TrackEvent.TranscriptionReceived,s),null==i||i.emit(e.ParticipantEvent.TranscriptionReceived,s,r),this.emit(e.RoomEvent.TranscriptionReceived,s,i,r)},this.handleChatMessage=(t,n)=>{const i=function(e){const t=e.id,n=e.timestamp,i=e.message,r=e.editTimestamp;return{id:t,timestamp:Number.parseInt(n.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:i}}(n);this.emit(e.RoomEvent.ChatMessage,i,t)},this.handleMetrics=(t,n)=>{this.emit(e.RoomEvent.MetricsReceived,t,n)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=t=>{this.log.warn("could not playback audio",{error:t}),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(e.RoomEvent.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(e.RoomEvent.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>pr(this,void 0,void 0,(function*(){var t;"iOS"!==(null===(t=Os())||void 0===t?void 0:t.os)&&(yield this.selectDefaultDevices()),this.emit(e.RoomEvent.MediaDevicesChanged)})),this.handleRoomUpdate=t=>{const n=this.roomInfo;this.roomInfo=t,n&&n.metadata!==t.metadata&&this.emitWhenConnected(e.RoomEvent.RoomMetadataChanged,t.metadata),(null==n?void 0:n.activeRecording)!==t.activeRecording&&this.emitWhenConnected(e.RoomEvent.RecordingStatusChanged,t.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.getRemoteParticipantClientProtocol=e=>{var t,n;return null!==(n=null===(t=this.remoteParticipants.get(e))||void 0===t?void 0:t.clientProtocol)&&void 0!==n?n:0},this.getRemoteParticipantCapabilities=e=>{var t,n;return null!==(n=null===(t=this.remoteParticipants.get(e))||void 0===t?void 0:t.capabilities)&&void 0!==n?n:[]},this.getAllRemoteParticipantIdentities=()=>Array.from(this.remoteParticipants.keys()),this.logWebRTCStats=()=>pr(this,void 0,void 0,(function*(){var e,t,n,i;const r=null===(e=this.engine)||void 0===e?void 0:e.pcManager;if(r)try{const e=F(yield Promise.all([r.publisher.getStats(),null===(t=r.subscriber)||void 0===t?void 0:t.getStats()]),2),s=e[0],a=e[1],o=s&&da(s),c=a&&da(a);this.statsLog.info("webrtc stats",{publisher:null==o?void 0:o.connection,subscriber:null==c?void 0:c.connection,inbound:[...null!==(n=null==o?void 0:o.inbound)&&void 0!==n?n:[],...null!==(i=null==c?void 0:c.inbound)&&void 0!==i?i:[]],outbound:null==o?void 0:o.outbound})}catch(s){this.statsLog.debug("could not collect webrtc stats",{error:s})}})),this.onLocalParticipantMetadataChanged=t=>{this.emit(e.RoomEvent.ParticipantMetadataChanged,t,this.localParticipant)},this.onLocalParticipantNameChanged=t=>{this.emit(e.RoomEvent.ParticipantNameChanged,t,this.localParticipant)},this.onLocalAttributesChanged=t=>{this.emit(e.RoomEvent.ParticipantAttributesChanged,t,this.localParticipant)},this.onLocalTrackMuted=t=>{this.emit(e.RoomEvent.TrackMuted,t,this.localParticipant)},this.onLocalTrackUnmuted=t=>{this.emit(e.RoomEvent.TrackUnmuted,t,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=t=>pr(this,void 0,void 0,(function*(){var n,i,r,s,a,o;if(null===(n=t.track)||void 0===n||n.on(e.TrackEvent.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=t.track)||void 0===i||i.on(e.TrackEvent.Restarted,this.onLocalTrackRestarted),null===(a=null===(s=null===(r=t.track)||void 0===r?void 0:r.getProcessor())||void 0===s?void 0:s.onPublish)||void 0===a||a.call(s,this),this.emit(e.RoomEvent.LocalTrackPublished,t,this.localParticipant),Oo(t.track)){(yield t.track.checkForSilence())&&this.emit(e.RoomEvent.LocalAudioSilenceDetected,t)}const c=yield null===(o=t.track)||void 0===o?void 0:o.getDeviceId(!1),d=Pa(t.source);d&&c&&c!==this.localParticipant.activeDeviceMap.get(d)&&(this.localParticipant.activeDeviceMap.set(d,c),this.emit(e.RoomEvent.ActiveDeviceChanged,d,c))})),this.onLocalTrackUnpublished=t=>{var n,i;null===(n=t.track)||void 0===n||n.off(e.TrackEvent.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=t.track)||void 0===i||i.off(e.TrackEvent.Restarted,this.onLocalTrackRestarted),this.emit(e.RoomEvent.LocalTrackUnpublished,t,this.localParticipant)},this.onLocalTrackRestarted=t=>pr(this,void 0,void 0,(function*(){const n=yield t.getDeviceId(!1),i=Pa(t.source);i&&n&&n!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(n," active")),this.localParticipant.activeDeviceMap.set(i,n),this.emit(e.RoomEvent.ActiveDeviceChanged,i,n))})),this.onLocalConnectionQualityChanged=t=>{this.emit(e.RoomEvent.ConnectionQualityChanged,t,this.localParticipant)},this.onMediaDevicesError=(t,n)=>{this.emit(e.RoomEvent.MediaDevicesError,t,n)},this.onLocalParticipantPermissionsChanged=t=>{this.emit(e.RoomEvent.ParticipantPermissionsChanged,t,this.localParticipant)},this.onLocalChatMessageSent=t=>{this.emit(e.RoomEvent.ChatMessage,t,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Ad),t),this.log=or(null!==(s=this.options.loggerName)&&void 0!==s?s:e.LoggerNames.Room,(()=>this.logContext)),this.statsLog=or(e.LoggerNames.Stats,(()=>this.logContext)),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Dd),null==t?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Od),null==t?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Md),null==t?void 0:t.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Ml(null===(a=this.options.dataStream)||void 0===a?void 0:a.maxPayloadByteLength),this.outgoingDataStreamManager=new Vl(this.engine,this.log,this.getRemoteParticipantClientProtocol,this.getRemoteParticipantCapabilities,this.getAllRemoteParticipantIdentities),this.incomingDataTrackManager=new Tu({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on("sfuUpdateSubscription",(e=>{this.engine.client.sendUpdateDataSubscription(e.sid,e.subscribe)})).on("trackPublished",(t=>{var n;t.track.publisherIdentity!==this.localParticipant.identity&&(this.emit(e.RoomEvent.DataTrackPublished,t.track),null===(n=this.remoteParticipants.get(t.track.publisherIdentity))||void 0===n||n.addRemoteDataTrack(t.track))})).on("trackUnpublished",(t=>{var n;t.publisherIdentity!==this.localParticipant.identity&&(this.emit(e.RoomEvent.DataTrackUnpublished,t.sid),null===(n=this.remoteParticipants.get(t.publisherIdentity))||void 0===n||n.removeRemoteDataTrack(t.sid))})),this.outgoingDataTrackManager=new Lu({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on("sfuPublishRequest",(e=>{this.engine.client.sendPublishDataTrackRequest(e.handle,e.name,e.usesE2ee)})).on("sfuUnpublishRequest",(e=>{this.engine.client.sendUnPublishDataTrackRequest(e.handle)})).on("trackPublished",(t=>{this.emit(e.RoomEvent.LocalDataTrackPublished,t.track)})).on("trackUnpublished",(t=>{this.emit(e.RoomEvent.LocalDataTrackUnpublished,t.sid)})).on("packetAvailable",(e=>{let t=e.handle,n=e.bytes;this.engine.sendDataTrackFrame(n).finally((()=>this.outgoingDataTrackManager.handlePacketSendComplete(t)))})),this.registerRpcDataStreamHandler(),this.rpcClientManager=new Vu(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol,(()=>{var e,t;return null===(t=null===(e=this.engine.latestJoinResponse)||void 0===e?void 0:e.serverInfo)||void 0===t?void 0:t.version})),this.rpcClientManager.on("sendDataPacket",(e=>{let t=e.packet;var n;null===(n=this.engine)||void 0===n||n.sendDataPacket(t,xd.RELIABLE)})),this.rpcServerManager=new Wu(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol),this.rpcServerManager.on("sendDataPacket",(e=>{let t=e.packet;var n;null===(n=this.engine)||void 0===n||n.sendDataPacket(t,xd.RELIABLE)})),this.disconnectLock=new r,this.localParticipant=new $u("","",this.engine,this.options,this.outgoingDataStreamManager,this.outgoingDataTrackManager,this.rpcClientManager,this.rpcServerManager),this.setupFrameMetadata(),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager(null!==(o=this.e2eeManager)&&void 0!==o?o:null),this.outgoingDataTrackManager.updateE2eeManager(null!==(c=this.e2eeManager)&&void 0!==c?c:null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Eo(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Eo(this.options.audioCaptureDefaults.deviceId)),(null===(d=this.options.audioOutput)||void 0===d?void 0:d.deviceId)&&this.switchActiveDevice("audiooutput",Eo(this.options.audioOutput.deviceId)).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message)))),no()){const e=new AbortController;let t;if(rh.cleanupRegistry){const n=new WeakRef(this);t=()=>{const e=n.deref();e&&e.handleDeviceChange()},rh.cleanupRegistry.register(this,(()=>{e.abort()}))}else t=this.handleDeviceChange;null===(u=null===(l=navigator.mediaDevices)||void 0===l?void 0:l.addEventListener)||void 0===u||u.call(l,"devicechange",t,{signal:e.signal})}}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){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setE2EEEnabled(e){return pr(this,void 0,void 0,(function*(){const t=yield this.e2eeStateMutex.lock();try{if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");this.isE2EEEnabled!==e&&(yield this.localParticipant.setE2EEEnabled(e),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity))}finally{t()}}))}setupE2EE(){var t,n;const i=!!this.options.encryption,r=this.options.encryption||this.options.e2ee;r&&("e2eeManager"in r?(this.e2eeManager=r.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=i):this.e2eeManager=new gc(r,i),this.e2eeManager.on(e.EncryptionEvent.ParticipantEncryptionStatusChanged,((t,n)=>{xo(n)&&(this.isE2EEEnabled=t),this.emit(e.RoomEvent.ParticipantEncryptionStatusChanged,t,n)})),this.e2eeManager.on(e.EncryptionEvent.EncryptionError,((t,n)=>{const i=n?this.getParticipantByIdentity(n):void 0;this.emit(e.RoomEvent.EncryptionError,t,i)})),null===(t=this.e2eeManager)||void 0===t||t.setup(this),null===(n=this.e2eeManager)||void 0===n||n.setupEngine(this.engine))}setupFrameMetadata(){var e;const t=null!==(e=this.options.frameMetadata)&&void 0!==e?e:this.options.packetTrailer;this.frameMetadataManager=new fc(t),this.frameMetadataManager.setup(this)}get logContext(){var e,t,n;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:null===(t=this.localParticipant)||void 0===t?void 0:t.identity,participantID:null===(n=this.localParticipant)||void 0===n?void 0:n.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 this.state===e.ConnectionState.Disconnected?_s.resolve(""):this.roomInfo&&""!==this.roomInfo.sid?_s.resolve(this.roomInfo.sid):new _s(((t,n)=>{const i=n=>{""!==n.sid&&(this.engine.off(e.EngineEvent.RoomUpdate,i),t(n.sid))};this.engine.on(e.EngineEvent.RoomUpdate,i),this.once(e.RoomEvent.Disconnected,(()=>{this.engine.off(e.EngineEvent.RoomUpdate,i),n(new Ys("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.isNewlyCreated&&this.engine.isClosed)&&(this.engine=new fl(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(e.EngineEvent.ParticipantUpdate,this.handleParticipantUpdates).on(e.EngineEvent.RoomUpdate,this.handleRoomUpdate).on(e.EngineEvent.SpeakersChanged,this.handleSpeakersChanged).on(e.EngineEvent.StreamStateChanged,this.handleStreamStateUpdate).on(e.EngineEvent.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(e.EngineEvent.SubscriptionError,this.handleSubscriptionError).on(e.EngineEvent.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(e.EngineEvent.MediaTrackAdded,((e,t,n)=>{this.onTrackAdded(e,t,n)})).on(e.EngineEvent.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(e.EngineEvent.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(e.EngineEvent.DataPacketReceived,this.handleDataPacket).on(e.EngineEvent.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.debug("Resuming signal connection"),this.setAndEmitConnectionState(e.ConnectionState.SignalReconnecting)&&this.emit(e.RoomEvent.SignalReconnecting)})).on(e.EngineEvent.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug("Resumed signal connection"),this.updateSubscriptions(),this.setAndEmitConnectionState(e.ConnectionState.Connected)&&this.emit(e.RoomEvent.Reconnected),this.emitBufferedEvents()})).on(e.EngineEvent.SignalResumed,(()=>{(this.state===e.ConnectionState.Reconnecting||this.isResuming)&&this.sendSyncState(),this.emitBufferedEvents()})).on(e.EngineEvent.Restarting,this.handleRestarting).on(e.EngineEvent.Restarted,this.handleRestarted).on(e.EngineEvent.SignalRestarted,this.handleSignalRestarted).on(e.EngineEvent.Offline,(()=>{this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting)})).on(e.EngineEvent.DCBufferStatusChanged,((t,n)=>{this.emit(e.RoomEvent.DCBufferStatusChanged,t,n)})).on(e.EngineEvent.LocalTrackSubscribed,(e=>{this.handleLocalTrackSubscribed(e)})).on(e.EngineEvent.RoomMoved,(t=>{this.log.debug("room moved",t),t.room&&this.handleRoomUpdate(t.room),this.remoteParticipants.forEach(((e,t)=>{this.handleParticipantDisconnected(t,e)})),this.emit(e.RoomEvent.Moved,t.room.name),t.participant?this.handleParticipantUpdates([t.participant,...t.otherParticipants]):this.handleParticipantUpdates(t.otherParticipants)})).on(e.EngineEvent.PublishDataTrackResponse,(e=>{e.info?this.outgoingDataTrackManager.receivedSfuPublishResponse(e.info.pubHandle,{type:"ok",data:{sid:e.info.sid,pubHandle:e.info.pubHandle,name:e.info.name,usesE2ee:e.info.encryption!==ft.NONE}}):this.log.warn("received PublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."))})).on(e.EngineEvent.UnPublishDataTrackResponse,(e=>{e.info?this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle):this.log.warn("received UnPublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."))})).on(e.EngineEvent.DataTrackSubscriberHandles,(e=>{const t=new Map(Object.entries(e.subHandles).map((e=>{let t=F(e,2),n=t[0],i=t[1];return[parseInt(n,10),i.trackSid]})));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)})).on(e.EngineEvent.DataTrackPacketReceived,(e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(t){throw t}})).on(e.EngineEvent.Joined,(e=>{const t=new Map(e.otherParticipants.map((e=>[e.identity,e.dataTracks.map((e=>Oc.from(e)))])));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)})).on(e.EngineEvent.TokenRefreshed,(e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.updateToken(e)})).on(e.EngineEvent.ServerRegionsReported,(e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions({regionSettings:e,updatedAtInMs:Date.now(),maxAgeInMs:bl})})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}createRegionStrategy(){return{getNextUrl:e=>pr(this,void 0,void 0,(function*(){return this.regionUrlProvider?this.regionUrlProvider.getNextBestRegionUrl(e):null})),resetAttempts:()=>{var e;return null===(e=this.regionUrlProvider)||void 0===e?void 0:e.resetAttempts()}}}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Tc.getInstance().getDevices(e,t)}prepareConnection(t,i){return pr(this,void 0,void 0,(function*(){if(this.state===e.ConnectionState.Disconnected){this.log.debug("prepareConnection to ".concat(t));try{if(ro(new URL(t))&&i){this.regionUrlProvider=new Tl(t,i);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===e.ConnectionState.Disconnected&&(this.regionUrl=n,yield fetch(Co(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n)))}else yield fetch(Co(t),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",{error:n})}}}))}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return pr(this,void 0,void 0,(function*(){let n,i=()=>pr(this,void 0,void 0,(function*(){}));switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"fail-on-v1-path":this.engine.failNextV1Path();break;case"speaker":n=new xi({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":n=new xi({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":n=new xi({scenario:{case:"serverLeave",value:!0}});break;case"migration":n=new xi({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":i=()=>pr(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),n=new xi({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>pr(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),n=new xi({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":n=new xi({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),i=()=>pr(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new mi({reason:st.CLIENT_INITIATED,action:gi.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");n=new xi({scenario:{case:"subscriberBandwidth",value:Po(t)}});break;case"leave-full-reconnect":n=new xi({scenario:{case:"leaveRequestFullReconnect",value:!0}})}n&&(yield this.engine.client.sendSimulateScenario(n),yield i())}))}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(t,i){return pr(this,arguments,void 0,(function(t,i){var r=this;let s=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var a,o,c,d,l,u,h;let p=!0,m=!1;const g=s?{exact:i}:i;if("audioinput"===t){m=0===r.localParticipant.audioTrackPublications.size;const e=null!==(a=r.getActiveDevice(t))&&void 0!==a?a:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=g;const i=Array.from(r.localParticipant.audioTrackPublications.values()).filter((e=>e.source===xa.Source.Microphone));try{p=(yield Promise.all(i.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(g)})))).every((e=>!0===e))}catch(n){throw r.options.audioCaptureDefaults.deviceId=e,n}const s=i.some((e=>{var t,n;return null!==(n=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==n&&n}));p&&s&&(m=!0)}else if("videoinput"===t){m=0===r.localParticipant.videoTrackPublications.size;const e=null!==(o=r.getActiveDevice(t))&&void 0!==o?o:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=g;const i=Array.from(r.localParticipant.videoTrackPublications.values()).filter((e=>e.source===xa.Source.Camera));try{p=(yield Promise.all(i.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(g)})))).every((e=>!0===e))}catch(n){throw r.options.videoCaptureDefaults.deviceId=e,n}const s=i.some((e=>{var t,n;return null!==(n=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==n&&n}));p&&s&&(m=!0)}else if("audiooutput"===t){if(m=!0,!Ja()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");r.options.webAudioMix&&(i=null!==(c=yield Tc.getInstance().normalizeDeviceId("audiooutput",i))&&void 0!==c?c:""),null!==(d=(h=r.options).audioOutput)&&void 0!==d||(h.audioOutput={});const e=null!==(l=r.getActiveDevice(t))&&void 0!==l?l:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=i;try{r.options.webAudioMix&&(null===(u=r.audioContext)||void 0===u||u.setSinkId(i)),yield Promise.all(Array.from(r.remoteParticipants.values()).map((e=>e.setAudioOutput({deviceId:i}))))}catch(n){throw r.options.audioOutput.deviceId=e,n}}return m&&(r.localParticipant.activeDeviceMap.set(t,i),r.emit(e.RoomEvent.ActiveDeviceChanged,t,i)),p}()}))}setupLocalParticipantEvents(){this.localParticipant.on(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(e.ParticipantEvent.AttributesChanged,this.onLocalAttributesChanged).on(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).on(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).on(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).on(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).on(e.ParticipantEvent.AudioStreamAcquired,this.startAudio).on(e.ParticipantEvent.ChatMessage,this.onLocalChatMessageSent).on(e.ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){const t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally((()=>t.close())):null==t||t.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(t,n,i){var r,s;if([e.ConnectionState.Connecting,e.ConnectionState.Reconnecting].includes(this.state)){const s=Bo(t,n);this.log.debug("deferring on track for later",{mediaTrackId:t.id,mediaStreamId:n.id,tracksInStream:n.getTracks().map((e=>e.id))});const a=()=>{o(),this.onTrackAdded(t,n,i)},o=()=>{if(this.off(e.RoomEvent.Reconnected,a),this.off(e.RoomEvent.Connected,a),this.off(e.RoomEvent.Disconnected,o),s){const e=this.pendingTrackAddedCallbacks.get(s);null==e||e.delete(o),0===(null==e?void 0:e.size)&&this.pendingTrackAddedCallbacks.delete(s)}};if(this.once(e.RoomEvent.Reconnected,a),this.once(e.RoomEvent.Connected,a),this.once(e.RoomEvent.Disconnected,o),s){const e=null!==(r=this.pendingTrackAddedCallbacks.get(s))&&void 0!==r?r:new Set;e.add(o),this.pendingTrackAddedCallbacks.set(s,e)}return}if(this.state===e.ConnectionState.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected");if("ended"===t.readyState)return void this.log.debug("skipping incoming track as it already ended");const a=ja(n.id),o=a[0],c=a[1];let d=null!==(s=Bo(t,n))&&void 0!==s?s:t.id;if(o===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant");const l=Array.from(this.remoteParticipants.values()).find((e=>e.sid===o));if(!l)return void(o.startsWith("PA")&&this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(o)));if(!d.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(o));d=e}let u;d.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(o,", streamId: ").concat(c,", trackId: ").concat(d),{remoteParticipantID:o,streamId:c,trackId:d}),this.options.adaptiveStream&&(u="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});const h=l.addSubscribedMediaTrack(t,d,n,i,u);(null==h?void 0:h.isEncrypted)&&!this.e2eeManager&&this.emit(e.RoomEvent.EncryptionError,new Error("Encrypted ".concat(h.source," track received from participant ").concat(l.sid,", but room does not have encryption enabled!")))}cancelPendingTrackAdded(e){var t;null===(t=this.pendingTrackAddedCallbacks.get(e))||void 0===t||t.forEach((e=>e()))}handleLocalTrackSubscribed(t){const n=()=>this.localParticipant.getTrackPublications().find((e=>e.trackSid===t)),i=n();if(i)return void this.emitLocalTrackSubscribed(i);this.log.debug("deferring LocalTrackSubscribed, publication not yet available",{subscribedSid:t});let r;const s=e=>{e.trackSid===t&&(a(),this.emitLocalTrackSubscribed(e))},a=()=>{clearTimeout(r),this.localParticipant.off(e.ParticipantEvent.LocalTrackPublished,s),this.off(e.RoomEvent.Disconnected,a)};this.localParticipant.on(e.ParticipantEvent.LocalTrackPublished,s),this.once(e.RoomEvent.Disconnected,a),r=setTimeout((()=>{a();const e=n();e?this.emitLocalTrackSubscribed(e):this.log.warn("could not find local track publication for LocalTrackSubscribed event after timeout",{subscribedSid:t})}),1e4)}emitLocalTrackSubscribed(t){this.localParticipant.emit(e.ParticipantEvent.LocalTrackSubscribed,t),this.emitWhenConnected(e.RoomEvent.LocalTrackSubscribed,t,this.localParticipant)}handleDisconnect(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],n=arguments.length>1?arguments[1]:void 0;var i,r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.incomingDataTrackManager.reset(),this.outgoingDataTrackManager.reset(),this.state!==e.ConnectionState.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((e=>{var n,i,r;e.track&&this.localParticipant.unpublishTrack(e.track,t),t?(null===(n=e.track)||void 0===n||n.detach(),null===(i=e.track)||void 0===i||i.stop()):null===(r=e.track)||void 0===r||r.stopMonitor()})),this.localParticipant.off(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(e.ParticipantEvent.AttributesChanged,this.onLocalAttributesChanged).off(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).off(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).off(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).off(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).off(e.ParticipantEvent.AudioStreamAcquired,this.startAudio).off(e.ParticipantEvent.ChatMessage,this.onLocalChatMessageSent).off(e.ParticipantEvent.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),no()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(r=null===(i=navigator.mediaDevices)||void 0===i?void 0:i.removeEventListener)||void 0===r||r.call(i,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(e.ConnectionState.Disconnected),this.emit(e.RoomEvent.Disconnected,n)}}}handleParticipantDisconnected(t,n,i){this.remoteParticipants.delete(t),n&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(t),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(t),n.trackPublications.forEach((e=>{n.unpublishTrack(e.trackSid,!0)})),this.emit(e.RoomEvent.ParticipantDisconnected,n,i),n.setDisconnected(),this.rpcClientManager.handleParticipantDisconnected(n.identity))}selectDefaultDevices(){return pr(this,void 0,void 0,(function*(){var t,n,i;const r=Tc.getInstance().previousDevices,s=yield Tc.getInstance().getDevices(void 0,!1),a=Os();if("Chrome"===(null==a?void 0:a.name)&&"iOS"!==a.os)for(let c of s){const t=r.find((e=>e.deviceId===c.deviceId));t&&""!==t.label&&t.kind===c.kind&&t.label!==c.label&&"default"===this.getActiveDevice(c.kind)&&this.emit(e.RoomEvent.ActiveDeviceChanged,c.kind,c.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let e of o){const a=Ra(e),o=this.localParticipant.getTrackPublication(a);if(o&&(null===(t=o.track)||void 0===t?void 0:t.isUserProvided))continue;const c=s.filter((t=>t.kind===e)),d=this.getActiveDevice(e);d===(null===(n=r.filter((t=>t.kind===e))[0])||void 0===n?void 0:n.deviceId)&&c.length>0&&(null===(i=c[0])||void 0===i?void 0:i.deviceId)!==d?yield this.switchActiveDevice(e,c[0].deviceId):"audioinput"===e&&!$a()||"videoinput"===e||!(c.length>0)||c.find((t=>t.deviceId===this.getActiveDevice(e)))||"audiooutput"===e&&$a()||(yield this.switchActiveDevice(e,c[0].deviceId))}}))}acquireAudioContext(){return pr(this,void 0,void 0,(function*(){var t,i;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!==(t=wa())&&void 0!==t?t: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(),qa(200)])}catch(n){this.log.warn("Could not resume audio context",{error:n})}const r="running"===(null===(i=this.audioContext)||void 0===i?void 0:i.state);r!==this.canPlaybackAudio&&(this.audioEnabled=r,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,r))}))}createParticipant(e,t){var n;let i;return i=t?ih.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):new ih(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&i.setAudioOutput(this.options.audioOutput).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message)))),i}getOrCreateParticipant(t,n){if(this.remoteParticipants.has(t)){const e=this.remoteParticipants.get(t);if(n){e.updateInfo(n)&&this.sidToIdentity.set(n.sid,n.identity)}return e}const i=this.createParticipant(t,n);return this.remoteParticipants.set(t,i),this.sidToIdentity.set(n.sid,n.identity),this.emitWhenConnected(e.RoomEvent.ParticipantConnected,i),i.on(e.ParticipantEvent.TrackPublished,(t=>{this.emitWhenConnected(e.RoomEvent.TrackPublished,t,i)})).on(e.ParticipantEvent.TrackSubscribed,((t,n)=>{t.kind===xa.Kind.Audio?(t.on(e.TrackEvent.AudioPlaybackStarted,this.handleAudioPlaybackStarted),t.on(e.TrackEvent.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):t.kind===xa.Kind.Video&&(t.on(e.TrackEvent.VideoPlaybackFailed,this.handleVideoPlaybackFailed),t.on(e.TrackEvent.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(e.RoomEvent.TrackSubscribed,t,n,i)})).on(e.ParticipantEvent.TrackUnpublished,(t=>{this.cancelPendingTrackAdded(t.trackSid),this.emit(e.RoomEvent.TrackUnpublished,t,i)})).on(e.ParticipantEvent.TrackUnsubscribed,((t,n)=>{this.emit(e.RoomEvent.TrackUnsubscribed,t,n,i)})).on(e.ParticipantEvent.TrackMuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackMuted,t,i)})).on(e.ParticipantEvent.TrackUnmuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackUnmuted,t,i)})).on(e.ParticipantEvent.ParticipantMetadataChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantMetadataChanged,t,i)})).on(e.ParticipantEvent.ParticipantNameChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantNameChanged,t,i)})).on(e.ParticipantEvent.AttributesChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantAttributesChanged,t,i)})).on(e.ParticipantEvent.ConnectionQualityChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ConnectionQualityChanged,t,i)})).on(e.ParticipantEvent.ParticipantPermissionsChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantPermissionsChanged,t,i)})).on(e.ParticipantEvent.TrackSubscriptionStatusChanged,((t,n)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionStatusChanged,t,n,i)})).on(e.ParticipantEvent.TrackSubscriptionFailed,((t,n)=>{this.emit(e.RoomEvent.TrackSubscriptionFailed,t,i,n)})).on(e.ParticipantEvent.TrackSubscriptionPermissionChanged,((t,n)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionPermissionChanged,t,n,i)})).on(e.ParticipantEvent.Active,(()=>{this.emitWhenConnected(e.RoomEvent.ParticipantActive,i),i.kind===gt.AGENT&&this.localParticipant.setActiveAgent(i)})),n&&i.updateInfo(n),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce(((e,t)=>(e.push(...t.getTrackPublications()),e)),[]),t=this.localParticipant.getTrackPublications(),n=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,n)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&No(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}getClientInfoCapabilities(e){var t;const n=[];return(sc(null!==(t=e.frameMetadata)&&void 0!==t?t:e.packetTrailer)||this.e2eeManager)&&n.push(Xt.CAP_PACKET_TRAILER),Fo()&&n.push(Xt.CAP_COMPRESSION_DEFLATE_RAW),n}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(Uu,((e,t)=>pr(this,[e,t],void 0,(function(e,t){var n=this;let i=t.identity;return function*(){var t;const r=null!==(t=e.info.attributes)&&void 0!==t?t:{};yield n.rpcServerManager.handleIncomingDataStream(e,i,r)}()})))),this.incomingDataStreamManager.registerTextStreamHandler(Fu,((e,t)=>pr(this,[e,t],void 0,(function(e,t){var n=this;let i=t.identity;return function*(){var t;const r=null!==(t=e.info.attributes)&&void 0!==t?t:{};yield n.rpcClientManager.handleIncomingDataStream(e,i,r)}()}))))}setStatsLogging(e){e?this.statsLogInterval||(this.statsLogInterval=ia.setInterval((()=>{this.logWebRTCStats()}),3e4)):this.statsLogInterval&&(ia.clearInterval(this.statsLogInterval),this.statsLogInterval=void 0)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=ia.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0}),e>=3&&(this.clearConnectionReconcile(),this.engine&&!this.engine.isClosed?(this.log.warn("detected connection state mismatch, attempting full reconnect"),this.engine.reconnect()):(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,st.STATE_MISMATCH))))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&ia.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(t){return t!==this.state&&(this.log.info("connection state changed: ".concat(this.state," -> ").concat(t)),this.state=t,this.incomingDataStreamManager.setConnected(t===e.ConnectionState.Connected),this.setStatsLogging(t===e.ConnectionState.Connected),this.emit(e.RoomEvent.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach((e=>{let t=F(e,2),n=t[0],i=t[1];this.emit(n,...i)})),this.bufferedEvents=[]}emitWhenConnected(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(this.state===e.ConnectionState.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([t,i]);else if(this.state===e.ConnectionState.Connected)return this.emit(t,...i);return!1}simulateParticipants(t){return pr(this,void 0,void 0,(function*(){var n,i,r,s;const a=Object.assign({audio:!0,video:!0,useRealTracks:!1},t.publish),o=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},t.participants);if(this.handleDisconnect(),this.roomInfo=new lt({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:R.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new pt({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected),this.emit(e.RoomEvent.Connected),this.setAndEmitConnectionState(e.ConnectionState.Connected),a.video){const t=new zu(xa.Kind.Video,new yt({source:tt.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:et.AUDIO,name:"video-dummy"}),new ul(a.useRealTracks&&(null===(n=window.navigator.mediaDevices)||void 0===n?void 0:n.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:yo(160*(null!==(i=o.aspectRatios[0])&&void 0!==i?i:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}if(a.audio){const t=new zu(xa.Kind.Audio,new yt({source:tt.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:et.AUDIO}),new Zd(a.useRealTracks&&(null===(r=navigator.mediaDevices)||void 0===r?void 0:r.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:bo(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}for(let e=0;e<o.count-1;e+=1){let t=new pt({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:mt.ACTIVE,tracks:[],joinedAt:R.parse(Date.now())});const n=this.getOrCreateParticipant(t.identity,t);if(o.video){const i=yo(160*(null!==(s=o.aspectRatios[e%o.aspectRatios.length])&&void 0!==s?s:1),160,!1,!0),r=new yt({source:tt.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:et.AUDIO});n.addSubscribedMediaTrack(i,r.sid,new MediaStream([i]),new RTCRtpReceiver),t.tracks=[...t.tracks,r]}if(o.audio){const e=bo(),i=new yt({source:tt.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:et.AUDIO});n.addSubscribedMediaTrack(e,i.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,i]}n.updateInfo(t)}}))}emit(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(t!==e.RoomEvent.ActiveSpeakersChanged&&t!==e.RoomEvent.TranscriptionReceived){const n=sh(i).filter((e=>void 0!==e));t!==e.RoomEvent.TrackSubscribed&&t!==e.RoomEvent.TrackUnsubscribed||this.log.trace("subscribe trace: ".concat(t),{event:t,args:n}),this.log.debug("room event ".concat(t),{event:t,args:n})}return super.emit(t,...i)}}function sh(e){return e.map((e=>{if(e)return Array.isArray(e)?sh(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e}))}rh.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&"undefined"!=typeof WeakRef&&new FinalizationRegistry((e=>{e()}));var ah,oh=Object.freeze({__proto__:null,Convert:class{static toAgentAttributes(e){return JSON.parse(e)}static agentAttributesToJson(e){return JSON.stringify(e)}static toTranscriptionAttributes(e){return JSON.parse(e)}static transcriptionAttributesToJson(e){return JSON.stringify(e)}}});e.CheckStatus=void 0,(ah=e.CheckStatus||(e.CheckStatus={}))[ah.IDLE=0]="IDLE",ah[ah.RUNNING=1]="RUNNING",ah[ah.SKIPPED=2]="SKIPPED",ah[ah.SUCCESS=3]="SUCCESS",ah[ah.FAILED=4]="FAILED";class ch extends br.EventEmitter{constructor(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.status=e.CheckStatus.IDLE,this.logs=[],this.options={},this.url=t,this.token=n,this.name=this.constructor.name,this.room=new rh(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(t){return pr(this,void 0,void 0,(function*(){if(this.status!==e.CheckStatus.IDLE)throw Error("check is running already");this.setStatus(e.CheckStatus.RUNNING);try{yield this.perform()}catch(n){n instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(n.message):this.appendError(n.message))}return yield this.disconnect(),yield new Promise((e=>setTimeout(e,500))),this.status!==e.CheckStatus.SKIPPED&&this.setStatus(this.isSuccess()?e.CheckStatus.SUCCESS:e.CheckStatus.FAILED),t&&t(),this.getInfo()}))}isSuccess(){return!this.logs.some((e=>"error"===e.level))}connect(t){return pr(this,void 0,void 0,(function*(){return this.room.state===e.ConnectionState.Connected||(t||(t=this.url),yield this.room.connect(t,this.token,this.connectOptions)),this.room}))}disconnect(){return pr(this,void 0,void 0,(function*(){this.room&&this.room.state!==e.ConnectionState.Disconnected&&(yield this.room.disconnect(),yield new Promise((e=>setTimeout(e,500))))}))}skip(){this.setStatus(e.CheckStatus.SKIPPED)}switchProtocol(t){return pr(this,void 0,void 0,(function*(){let n=!1,i=!1;if(this.room.on(e.RoomEvent.Reconnecting,(()=>{n=!0})),this.room.once(e.RoomEvent.Reconnected,(()=>{i=!0})),this.room.simulateScenario("force-".concat(t)),yield new Promise((e=>setTimeout(e,1e3))),!n)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield qa(100)}throw new Error("Could not reconnect using ".concat(t," protocol after 10 seconds"))}))}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return null===(e=this.room)||void 0===e?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class dh extends ch{get description(){return"Cloud regions"}perform(){return pr(this,void 0,void 0,(function*(){const e=new Tl(this.url,this.token);if(!e.isCloud())return void this.skip();const t=[],n=new Set;for(let r=0;r<3;r++){const i=yield e.getNextBestRegionUrl();if(!i)break;if(n.has(i))continue;n.add(i);const r=yield this.checkCloudRegion(i);this.appendMessage("".concat(r.region," RTT: ").concat(r.rtt,"ms, duration: ").concat(r.duration,"ms")),t.push(r)}t.sort(((e,t)=>.5*(e.duration-t.duration)+.5*(e.rtt-t.rtt)));const i=t[0];this.bestStats=i,this.appendMessage("best Cloud region: ".concat(i.region))}))}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return pr(this,void 0,void 0,(function*(){var t,n;yield this.connect(e),"tcp"===this.options.protocol&&(yield this.switchProtocol("tcp"));const i=null===(t=this.room.serverInfo)||void 0===t?void 0:t.region;if(!i)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),s="A".repeat(1e3),a=Date.now();for(let e=0;e<1e3;e++)yield r.write(s);yield r.close();const o=Date.now(),c=yield null===(n=this.room.engine.pcManager)||void 0===n?void 0:n.publisher.getStats(),d={region:i,rtt:1e4,duration:o-a};return null==c||c.forEach((e=>{"candidate-pair"===e.type&&e.nominated&&(d.rtt=1e3*e.currentRoundTripTime)})),yield this.disconnect(),d}))}}const lh=1e4;class uh extends ch{get description(){return"Connection via UDP vs TCP"}perform(){return pr(this,void 0,void 0,(function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const n=this.bestStats;this.appendMessage("upstream bitrate: ".concat((n.bitrateTotal/n.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((n.rttTotal/n.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((n.jitterTotal/n.count*1e3).toFixed(2)," ms")),n.packetsLost>0&&this.appendWarning("packets lost: ".concat((n.packetsLost/n.packetsSent*100).toFixed(2),"%")),n.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((n.qualityLimitationDurations.bandwidth/10*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/10*100).toFixed(2),"%"))}))}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return pr(this,void 0,void 0,(function*(){yield this.connect(),"tcp"===e?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const n=t.getContext("2d");if(!n)throw new Error("Could not get canvas context");let i=0;const r=()=>{i=(i+1)%360,n.fillStyle="hsl(".concat(i,", 100%, 50%)"),n.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const s=t.captureStream(30).getVideoTracks()[0],a=(yield this.room.localParticipant.publishTrack(s,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,o={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},c=setInterval((()=>pr(this,void 0,void 0,(function*(){const e=yield a.getRTCStatsReport();null==e||e.forEach((e=>{"outbound-rtp"===e.type?(o.packetsSent=e.packetsSent,o.qualityLimitationDurations=e.qualityLimitationDurations,o.bitrateTotal+=e.targetBitrate,o.count++):"remote-inbound-rtp"===e.type&&(o.packetsLost=e.packetsLost,o.rttTotal+=e.roundTripTime,o.jitterTotal+=e.jitter)}))}))),1e3);return yield new Promise((e=>setTimeout(e,lh))),clearInterval(c),s.stop(),t.remove(),yield this.disconnect(),o}))}}class hh extends ch{get description(){return"Can publish audio"}perform(){return pr(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),n=yield Qu();if(yield Ca(n,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(n),yield new Promise((e=>setTimeout(e,3e3)));const i=yield null===(e=n.sender)||void 0===e?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let r=0;if(i.forEach((e=>{"outbound-rtp"!==e.type||"audio"!==e.kind&&(e.kind||"audio"!==e.mediaType)||(r=e.packetsSent)})),0===r)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," audio packets"))}))}}class ph extends ch{get description(){return"Can publish video"}perform(){return pr(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),n=yield Ju();yield this.checkForVideo(n.mediaStreamTrack),t.localParticipant.publishTrack(n),yield new Promise((e=>setTimeout(e,5e3)));const i=yield null===(e=n.sender)||void 0===e?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let r=0;if(i.forEach((e=>{"outbound-rtp"!==e.type||"video"!==e.kind&&(e.kind||"video"!==e.mediaType)||(r+=e.packetsSent)})),0===r)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))}))}checkForVideo(e){return pr(this,void 0,void 0,(function*(){const t=new MediaStream;t.addTrack(e.clone());const n=document.createElement("video");n.srcObject=t,n.muted=!0,n.autoplay=!0,n.playsInline=!0,n.setAttribute("playsinline","true"),document.body.appendChild(n),yield new Promise((t=>{n.onplay=()=>{setTimeout((()=>{var i,r,s,a;const o=document.createElement("canvas"),c=e.getSettings(),d=null!==(r=null!==(i=c.width)&&void 0!==i?i:n.videoWidth)&&void 0!==r?r:1280,l=null!==(a=null!==(s=c.height)&&void 0!==s?s:n.videoHeight)&&void 0!==a?a:720;o.width=d,o.height=l;const u=o.getContext("2d");u.drawImage(n,0,0);const h=u.getImageData(0,0,o.width,o.height).data;let p=!0;for(let e=0;e<h.length;e+=4)if(0!==h[e]||0!==h[e+1]||0!==h[e+2]){p=!1;break}p?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),t()}),1e3)},n.play()})),t.getTracks().forEach((e=>e.stop())),n.remove()}))}}class mh extends ch{get description(){return"Resuming connection after interruption"}perform(){return pr(this,void 0,void 0,(function*(){var t;const n=yield this.connect();let i,r=!1,s=!1;const a=new Promise((e=>{setTimeout(e,5e3),i=e})),o=()=>{r=!0};n.on(e.RoomEvent.SignalReconnecting,o).on(e.RoomEvent.Reconnecting,o).on(e.RoomEvent.Reconnected,(()=>{s=!0,i(!0)})),null===(t=n.engine.client.ws)||void 0===t||t.close();const c=n.engine.client.onClose;if(c&&c(""),yield a,!r)throw new Error("Did not attempt to reconnect");if(!s||n.state!==e.ConnectionState.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}))}}class gh extends ch{get description(){return"Can connect via TURN"}perform(){return pr(this,void 0,void 0,(function*(){var e,t,n;ro(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=null!==(e=yield new Tl(this.url,this.token).getNextBestRegionUrl())&&void 0!==e?e:this.url);const i=new nd,r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let s=!1,a=!1,o=!1;for(let c of r.iceServers)for(let e of c.urls)e.startsWith("turn:")?(a=!0,o=!0):e.startsWith("turns:")&&(a=!0,o=!0,s=!0),e.startsWith("stun:")&&(o=!0);o?a&&!s&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),(null===(n=null===(t=this.connectOptions)||void 0===t?void 0:t.rtcConfig)||void 0===n?void 0:n.iceServers)||a?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise((e=>setTimeout(e,0))))}))}}class vh extends ch{get description(){return"Establishing WebRTC connection"}perform(){return pr(this,void 0,void 0,(function*(){let t=!1,n=!1;this.room.on(e.RoomEvent.SignalConnected,(()=>{var e;const i=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(e,r)=>{if(e.candidate){const i=new RTCIceCandidate(e);let r="".concat(i.protocol," ").concat(i.address,":").concat(i.port," ").concat(i.type);i.address&&(!function(e){const t=e.split(".");if(4===t.length){if("10"===t[0])return!0;if("192"===t[0]&&"168"===t[1])return!0;if("172"===t[0]){const e=parseInt(t[1],10);if(e>=16&&e<=31)return!0}}return!1}(i.address)?"tcp"===i.protocol&&"passive"===i.tcpType?(t=!0,r+=" (passive)"):"udp"===i.protocol&&(n=!0):r+=" (private)"),this.appendMessage(r)}i&&i(e,r)},(null===(e=this.room.engine.pcManager)||void 0===e?void 0:e.subscriber)&&(this.room.engine.pcManager.subscriber.onIceCandidateError=e=>{e instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(e.errorCode," ").concat(e.errorText," ").concat(e.url))})}));try{yield this.connect(),sr.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}t||this.appendWarning("Server is not configured for ICE/TCP"),n||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")}))}}class fh extends ch{get description(){return"Connecting to signal connection via WebSocket"}perform(){return pr(this,void 0,void 0,(function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r,s=new nd;try{r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(n){if(ro(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(n.message,". Retrying with region fallback"));const t=new Tl(this.url,this.token),i=yield t.getNextBestRegionUrl();i&&(r=yield s.join(i,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}r?(this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),(null===(e=r.serverInfo)||void 0===e?void 0:e.edition)===Jt.Cloud&&(null===(t=r.serverInfo)||void 0===t?void 0:t.region)&&this.appendMessage("LiveKit Cloud: ".concat(null===(i=r.serverInfo)||void 0===i?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield s.close()}))}}class kh extends br.EventEmitter{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=n}getNextCheckId(){const t=this.checkResults.size;return this.checkResults.set(t,{logs:[],status:e.CheckStatus.IDLE,name:"",description:""}),t}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every((t=>t.status!==e.CheckStatus.FAILED))}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return pr(this,void 0,void 0,(function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token,this.options),i=e=>{this.updateCheck(t,e)};n.on("update",i);const r=yield n.run();return n.off("update",i),r}))}checkWebsocket(){return pr(this,void 0,void 0,(function*(){return this.createAndRunCheck(fh)}))}checkWebRTC(){return pr(this,void 0,void 0,(function*(){return this.createAndRunCheck(vh)}))}checkTURN(){return pr(this,void 0,void 0,(function*(){return this.createAndRunCheck(gh)}))}checkReconnect(){return pr(this,void 0,void 0,(function*(){return this.createAndRunCheck(mh)}))}checkPublishAudio(){return pr(this,void 0,void 0,(function*(){return this.createAndRunCheck(hh)}))}checkPublishVideo(){return pr(this,void 0,void 0,(function*(){return this.createAndRunCheck(ph)}))}checkConnectionProtocol(){return pr(this,void 0,void 0,(function*(){const e=yield this.createAndRunCheck(uh);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e}))}checkCloudRegion(){return pr(this,void 0,void 0,(function*(){return this.createAndRunCheck(dh)}))}}class yh{}class bh{}new TextEncoder;const Th=new TextDecoder;function Sh(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:Th.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=Th.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return function(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);const t=atob(e),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return n}(t)}catch(n){throw new TypeError("The input to be decoded is not correctly encoded.")}}class Eh extends Error{constructor(e,t){var n;super(e,t),L(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor)}}L(Eh,"code","ERR_JOSE_GENERIC");L(class extends Eh{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:i,payload:t}}),L(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),L(this,"claim",void 0),L(this,"reason",void 0),L(this,"payload",void 0),this.claim=n,this.reason=i,this.payload=t}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED");L(class extends Eh{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:i,payload:t}}),L(this,"code","ERR_JWT_EXPIRED"),L(this,"claim",void 0),L(this,"reason",void 0),L(this,"payload",void 0),this.claim=n,this.reason=i,this.payload=t}},"code","ERR_JWT_EXPIRED");L(class extends Eh{constructor(){super(...arguments),L(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED");L(class extends Eh{constructor(){super(...arguments),L(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED");L(class extends Eh{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),L(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED");L(class extends Eh{constructor(){super(...arguments),L(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID");L(class extends Eh{constructor(){super(...arguments),L(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID");class Ch extends Eh{constructor(){super(...arguments),L(this,"code","ERR_JWT_INVALID")}}L(Ch,"code","ERR_JWT_INVALID");L(class extends Eh{constructor(){super(...arguments),L(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID");L(class extends Eh{constructor(){super(...arguments),L(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID");L(class extends Eh{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),L(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY");L(class extends Eh{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),L(this,Symbol.asyncIterator,void 0),L(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");L(class extends Eh{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),L(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT");L(class extends Eh{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),L(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");function wh(e){if("string"!=typeof e)throw new Ch("JWTs must use Compact JWS serialization, JWT must be a string");const t=e.split("."),n=t[1],i=t.length;if(5===i)throw new Ch("Only JWTs using Compact JWS serialization can be decoded");if(3!==i)throw new Ch("Invalid JWT");if(!n)throw new Ch("JWTs must contain a payload");let r,s;try{r=Sh(n)}catch(a){throw new Ch("Failed to base64url decode the payload")}try{s=JSON.parse(Th.decode(r))}catch(o){throw new Ch("Failed to parse the decoded payload as JSON")}if(!function(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let n=e;for(;null!==Object.getPrototypeOf(n);)n=Object.getPrototypeOf(n);return Object.getPrototypeOf(e)===n}(s))throw new Ch("Invalid JWT Claims Set");return s}const Rh=1e3;function Ph(e){const t=wh(e);t.roomConfig;const n=hr(t,["roomConfig"]);return Object.assign(Object.assign({},n),{roomConfig:t.roomConfig?xn.fromJson(t.roomConfig,{ignoreUnknownFields:!0}):void 0})}function Ih(e,t){const n=new Set([...Object.keys(e),...Object.keys(t)]);for(const i of n)switch(i){case"roomName":case"participantName":case"participantIdentity":case"participantMetadata":case"participantAttributes":case"agentName":case"agentMetadata":case"deployment":if(e[i]!==t[i])return!1;break;default:throw new Error("Options key ".concat(i," not being checked for equality!"))}return!0}class _h extends bh{constructor(){super(...arguments),this.cachedFetchOptions=null,this.cachedResponse=null,this.fetchMutex=new r}isSameAsCachedFetchOptions(e){return!!this.cachedFetchOptions&&Ih(e,this.cachedFetchOptions)}shouldReturnCachedValueFromFetch(e){return!!this.cachedResponse&&(!!function(e){const t=Ph(e.participantToken);if(!(null==t?void 0:t.exp))return!1;const n=new Date;if(t.nbf){const e=t.nbf*Rh;if(new Date(e)>n)return!1}const i=t.exp*Rh;return new Date(i-6e4)>n}(this.cachedResponse)&&!!this.isSameAsCachedFetchOptions(e))}getCachedResponseJwtPayload(){return this.cachedResponse?Ph(this.cachedResponse.participantToken):null}fetch(e,t){return pr(this,void 0,void 0,(function*(){const n=yield this.fetchMutex.lock();try{if(t&&(this.cachedResponse=null),this.shouldReturnCachedValueFromFetch(e))return this.cachedResponse.toJson();this.cachedFetchOptions=e;const n=yield this.update(e);return this.cachedResponse=n,n.toJson()}finally{n()}}))}}class Mh extends yh{constructor(e){super(),this.literalOrFn=e}fetch(){return pr(this,void 0,void 0,(function*(){return"function"==typeof this.literalOrFn?this.literalOrFn():this.literalOrFn}))}}class Dh extends _h{constructor(e){super(),this.customFn=e}update(e){return pr(this,void 0,void 0,(function*(){const t=this.customFn(e);let n;return n=t instanceof Promise?yield t:t,Xi.fromJson(n,{ignoreUnknownFields:!0})}))}}class Oh extends _h{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),this.url=e,this.endpointOptions=t}createRequestFromOptions(e){var t,n,i,r;const s=new Yi;for(const a of Object.keys(e))switch(a){case"roomName":case"participantName":case"participantIdentity":case"participantMetadata":s[a]=e[a];break;case"participantAttributes":s.participantAttributes=null!==(t=e.participantAttributes)&&void 0!==t?t:{};break;case"agentName":s.roomConfig=null!==(n=s.roomConfig)&&void 0!==n?n:new xn,0===s.roomConfig.agents.length&&s.roomConfig.agents.push(new mn),s.roomConfig.agents[0].agentName=e.agentName;break;case"agentMetadata":s.roomConfig=null!==(i=s.roomConfig)&&void 0!==i?i:new xn,0===s.roomConfig.agents.length&&s.roomConfig.agents.push(new mn),s.roomConfig.agents[0].metadata=e.agentMetadata;break;case"deployment":s.roomConfig=null!==(r=s.roomConfig)&&void 0!==r?r:new xn,0===s.roomConfig.agents.length&&s.roomConfig.agents.push(new mn),s.roomConfig.agents[0].deployment=e.deployment;break;default:throw new Error("Options key ".concat(a," not being included in forming request!"))}return s}update(e){return pr(this,void 0,void 0,(function*(){var t;const n=this.createRequestFromOptions(e),i=yield fetch(this.url,Object.assign(Object.assign({},this.endpointOptions),{method:null!==(t=this.endpointOptions.method)&&void 0!==t?t:"POST",headers:Object.assign({"Content-Type":"application/json"},this.endpointOptions.headers),body:n.toJsonString({useProtoFieldName:!0})}));if(!i.ok)throw new Error("Error generating token from endpoint ".concat(this.url,": received ").concat(i.status," / ").concat(yield i.text()));const r=yield i.json();return Xi.fromJson(r,{ignoreUnknownFields:!0})}))}}class Ah extends Oh{constructor(e,t){const n=t.baseUrl,i=void 0===n?"https://cloud-api.livekit.io":n,r=hr(t,["baseUrl"]);super("".concat(i,"/api/v2/sandbox/connection-details"),Object.assign(Object.assign({},r),{headers:{"X-Sandbox-ID":e}}))}}class Nh extends Ah{}const Lh={literal:e=>new Mh(e),custom:e=>new Dh(e),endpoint(e){return new Oh(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})},sandboxTokenServer(e){return new Nh(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})},developmentTokenServer(e){return new Ah(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}};const xh=new Map([["obs virtual camera",{facingMode:"environment",confidence:"medium"}]]),Uh=new Map([["iphone",{facingMode:"environment",confidence:"medium"}],["ipad",{facingMode:"environment",confidence:"medium"}]]);function Fh(e){var t;const n=e.trim().toLowerCase();if(""!==n)return xh.has(n)?xh.get(n):null===(t=Array.from(Uh.entries()).find((e=>{let t=F(e,1)[0];return n.includes(t)})))||void 0===t?void 0:t[1]}const Bh=Symbol.for("lk.serializer");function jh(e){return Object.assign(Object.assign({},e),{symbol:Bh})}const qh={json:function(){return jh({parse:e=>JSON.parse(e),serialize:e=>JSON.stringify(e)})},raw:function(){return jh({parse:e=>e,serialize:e=>e})},custom:function(e){return jh(e)}};e.BaseKeyProvider=nc,e.CLIENT_PROTOCOL_DATA_STREAM_RPC=1,e.CLIENT_PROTOCOL_DATA_STREAM_V2=2,e.CLIENT_PROTOCOL_DEFAULT=0,e.Checker=ch,e.ConnectionCheck=kh,e.ConnectionError=zs,e.CriticalTimers=ia,e.CryptorError=class extends Us{constructor(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.CryptorErrorReason.InternalError,i=arguments.length>2?arguments[2]:void 0;super(40,t),this.reason=n,this.participantIdentity=i}},e.DataPacket_Kind=Ot,e.DataStreamError=ta,e.DataTrackPacket=uu,e.DefaultReconnectPolicy=ur,e.DeviceUnsupportedError=Gs,e.DisconnectReason=st,e.Encryption_Type=ft,e.ExternalE2EEKeyProvider=class extends nc{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(Object.assign(Object.assign({},e),{sharedKey:!0,ratchetWindowSize:0,failureTolerance:-1}))}setKey(e){return pr(this,void 0,void 0,(function*(){const t="string"==typeof e?yield Zo(e):yield $o(e);this.onSetEncryptionKey(t)}))}},e.FrameMetadataManager=fc,e.LivekitError=Us,e.LivekitReasonedError=Fs,e.LocalAudioTrack=Zd,e.LocalDataTrack=Du,e.LocalParticipant=$u,e.LocalTrack=Xd,e.LocalTrackPublication=zu,e.LocalTrackRecorder=Yd,e.LocalVideoTrack=ul,e.Mutex=r,e.NegotiationError=Xs,e.PacketTrailerManager=kc,e.Participant=Zu,e.ParticipantKind=gt,e.PublishDataError=Zs,e.PublishTrackError=$s,e.RemoteAudioTrack=Hu,e.RemoteDataTrack=cu,e.RemoteParticipant=ih,e.RemoteTrack=lc,e.RemoteTrackPublication=nh,e.RemoteVideoTrack=uc,e.Room=rh,e.RpcError=xu,e.ScreenSharePresets=ba,e.SignalReconnectError=na,e.SignalRequestError=ea,e.SimulatedError=class extends Us{constructor(){super(-1,arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Simulated failure"),this.name="simulated"}},e.SubscriptionError=ot,e.TokenSource=Lh,e.TokenSourceConfigurable=bh,e.TokenSourceFixed=yh,e.Track=xa,e.TrackInvalidError=Js,e.TrackPublication=Ku,e.TrackType=et,e.UnexpectedConnectionState=Ys,e.UnsupportedServer=Qs,e.VideoPreset=la,e.VideoPresets=ka,e.VideoPresets43=ya,e.areTokenSourceFetchOptionsEqual=Ih,e.asEncryptablePacket=tc,e.attachToElement=Ua,e.attributes=oh,e.audioCodecs=ua,e.clientProtocol=2,e.compareVersions=lo,e.createAudioAnalyser=function(e,t){const n=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),i=wa();if(!i)throw new Error("Audio Context not supported on this browser");const r=n.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,s=i.createMediaStreamSource(new MediaStream([r])),a=i.createAnalyser();a.minDecibels=n.minDecibels,a.maxDecibels=n.maxDecibels,a.fftSize=n.fftSize,a.smoothingTimeConstant=n.smoothingTimeConstant,s.connect(a);const o=new Uint8Array(a.frequencyBinCount);return{calculateVolume:()=>{a.getByteFrequencyData(o);let e=0;for(const t of o)e+=Math.pow(t/255,2);return Math.sqrt(e/o.length)},analyser:a,cleanup:()=>pr(this,void 0,void 0,(function*(){yield i.close(),n.cloneTrack&&r.stop()}))}},e.createE2EEKey=function(){return window.crypto.getRandomValues(new Uint8Array(32))},e.createKeyMaterialFromBuffer=$o,e.createKeyMaterialFromString=Zo,e.createLocalAudioTrack=Qu,e.createLocalScreenTracks=function(e){return pr(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0!==e.resolution||eo()||(e.resolution=ba.h1080fps30.resolution),void 0===navigator.mediaDevices.getDisplayMedia)throw new Gs("getDisplayMedia not supported");const t=Ia(e),n=yield navigator.mediaDevices.getDisplayMedia(t),i=n.getVideoTracks();if(0===i.length)throw new Js("no video track found");const r=new ul(i[0],void 0,!1);r.source=xa.Source.ScreenShare;const s=[r];if(n.getAudioTracks().length>0){const e=new Zd(n.getAudioTracks()[0],void 0,!1);e.source=xa.Source.ScreenShareAudio,s.push(e)}return s}))},e.createLocalTracks=Gu,e.createLocalVideoTrack=Ju,e.decodeTokenPayload=Ph,e.deriveKeys=function(e,t){return pr(this,void 0,void 0,(function*(){const n=ec(e.algorithm.name,t.ratchetSalt),i=yield crypto.subtle.deriveKey(n,e,{name:Ho,length:t.keySize},!1,["encrypt","decrypt"]);return{material:e,encryptionKey:i}}))},e.detachTrack=Fa,e.facingModeFromDeviceLabel=Fh,e.facingModeFromLocalTrack=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;const i=Io(e)?e.mediaStreamTrack:e,r=i.getSettings();let s={facingMode:null!==(n=t.defaultFacingMode)&&void 0!==n?n:"user",confidence:"low"};if("facingMode"in r){const e=r.facingMode;sr.trace("rawFacingMode",{rawFacingMode:e}),e&&"string"==typeof e&&function(e){const t=["user","environment","left","right"];return void 0===e||t.includes(e)}(e)&&(s={facingMode:e,confidence:"high"})}if(["low","medium"].includes(s.confidence)){sr.trace("Try to get facing mode from device label: (".concat(i.label,")"));const e=Fh(i.label);void 0!==e&&(s=e)}return s},e.getBrowser=Os,e.getEmptyAudioStreamTrack=bo,e.getEmptyVideoStreamTrack=function(){return fo||(fo=yo()),fo.clone()},e.getLogger=or,e.importKey=function(e){return pr(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:Ho},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return function*(){return crypto.subtle.importKey("raw",e,t,!1,"derive"===n?["deriveBits","deriveKey"]:["encrypt","decrypt"])}()}))},e.isAudioCodec=function(e){return ua.includes(e)},e.isAudioTrack=_o,e.isBackupCodec=ga,e.isBackupVideoCodec=ma,e.isBrowserSupported=Qa,e.isE2EESupported=Qo,e.isInsertableStreamSupported=Xo,e.isLocalParticipant=xo,e.isLocalTrack=Io,e.isRemoteParticipant=function(e){return!e.isLocal},e.isRemoteTrack=Ao,e.isSVCCodec=za,e.isScriptTransformSupported=Yo,e.isSerializer=function(e){return"object"==typeof e&&null!==e&&"symbol"in e&&e.symbol===Bh},e.isVideoCodec=So,e.isVideoFrame=function(e){return"type"in e},e.isVideoTrack=Mo,e.needsRbspUnescaping=function(e){for(var t=0;t<e.length-3;t++)if(0==e[t]&&0==e[t+1]&&3==e[t+2])return!0;return!1},e.parseRbsp=function(e){const t=[];for(var n=e.length,i=0;i<e.length;)n-i>=3&&!e[i]&&!e[i+1]&&3==e[i+2]?(t.push(e[i++]),t.push(e[i++]),i++):t.push(e[i++]);return new Uint8Array(t)},e.protocolVersion=17,e.ratchet=function(e,t){return pr(this,void 0,void 0,(function*(){const n=ec(e.algorithm.name,t);return crypto.subtle.deriveBits(n,e,256)}))},e.serializers=qh,e.setLogExtension=function(t,n){(n?[n]:ar).forEach((n=>{const i=n.methodFactory;n.methodFactory=(n,r,s)=>{const a=i(n,r,s),o=e.LogLevel[n],c=o>=r&&o<e.LogLevel.silent;return(e,n)=>{n?a(e,n):a(e),c&&t(o,e,n)}},n.setLevel(n.getLevel())}))},e.setLogLevel=function(e,t){if(t)rr.getLogger(t).setLevel(e);else for(const n of ar)n.setLevel(e)},e.supportsAV1=Ha,e.supportsAdaptiveStream=function(){return"undefined"!=typeof ResizeObserver&&"undefined"!=typeof IntersectionObserver},e.supportsAudioOutputSelection=function(){return Ja()},e.supportsDynacast=function(){return Va()},e.supportsH265=function(){if(!("getCapabilities"in RTCRtpSender))return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const n of e.codecs)if("video/h265"===n.mimeType.toLowerCase()){t=!0;break}return t},e.supportsVP9=Ka,e.version=xs,e.videoCodecs=pa,e.writeRbsp=function(e){const t=[];for(var n=0,i=0;i<e.length;++i){var r=e[i];r<=3&&n>=2&&(t.push(3),n=0),t.push(r),0==r?++n:n=0}return new Uint8Array(t)}}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LivekitClient={})}(this,(function(e){"use strict";function t(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(n){if("default"!==n&&!(n in e)){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}}))})),Object.freeze(e)}var n=Object.defineProperty,i=(e,t,i)=>((e,t,i)=>t in e?n(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class r{constructor(){i(this,"_locking"),i(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()})),n=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),n}}function a(e,t){if(!e)throw new Error(t)}function s(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 o(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 c(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 d=Symbol("@bufbuild/protobuf/enum-type");function l(e){const t=e[d];return a(t,"missing enum type on enum object"),t}function u(e,t,n,i){e[d]=h(t,n.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function h(e,t,n){const i=Object.create(null),r=Object.create(null),a=[];for(const s of t){const e=m(s);a.push(e),i[s.name]=e,r[s.no]=e}return{typeName:e,values:a,findName:e=>i[e],findNumber:e=>r[e]}}function p(e,t,n){const i={};for(const r of t){const e=m(r);i[e.localName]=e.no,i[e.no]=e.localName}return u(i,e,t),i}function m(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class g{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const n=this.getType().runtime.bin,i=n.makeReadOptions(t);return n.readMessage(this,i.readerFactory(e),e.byteLength,i),this}fromJson(e,t){const n=this.getType(),i=n.runtime.json,r=i.makeReadOptions(t);return i.readMessage(n,e,r,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,n=t.makeWriteOptions(e),i=n.writerFactory();return t.writeMessage(this,i,n),i.finish()}toJson(e){const t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,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 v(){let e=0,t=0;for(let i=0;i<28;i+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<i,!(128&n))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(15&n)<<28,t=(112&n)>>4,!(128&n))return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,!(128&n))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function f(e,t,n){for(let a=0;a<28;a+=7){const i=e>>>a,r=!(i>>>7==0&&0==t),s=255&(r?128|i:i);if(n.push(s),!r)return}const i=e>>>28&15|(7&t)<<4,r=!!(t>>3);if(n.push(255&(r?128|i:i)),r){for(let e=3;e<31;e+=7){const i=t>>>e,r=!(i>>>7==0),a=255&(r?128|i:i);if(n.push(a),!r)return}n.push(t>>>31&1)}}const k=4294967296;function y(e){const t="-"===e[0];t&&(e=e.slice(1));const n=1e6;let i=0,r=0;function a(t,a){const s=Number(e.slice(t,a));r*=n,i=i*n+s,i>=k&&(r+=i/k|0,i%=k)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?S(i,r):T(i,r)}function b(e,t){var n=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t);if(e=n.lo,(t=n.hi)<=2097151)return String(k*t+e);const i=16777215&(e>>>24|t<<8),r=t>>16&65535;let a=(16777215&e)+6777216*i+6710656*r,s=i+8147497*r,o=2*r;const c=1e7;return a>=c&&(s+=Math.floor(a/c),a%=c),s>=c&&(o+=Math.floor(s/c),s%=c),o.toString()+E(s)+E(a)}function T(e,t){return{lo:0|e,hi:0|t}}function S(e,t){return t=~t,e?e=1+~e:t+=1,T(e,t)}const E=e=>{const t=String(e);return"0000000".slice(t.length)+t};function C(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(127&e|128),e>>=7;t.push(1)}}function w(){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 n=5;128&e&&n<10;n++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const R=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"),n=BigInt("9223372036854775807"),i=BigInt("0"),r=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const i="bigint"==typeof e?e:BigInt(e);if(i>n||i<t)throw new Error("int64 invalid: ".concat(e));return i},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>r||t<i)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,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)),uDec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0))}}const t=e=>a(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),n=e=>a(/^[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()),n(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),y(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),n(e),y(e)),dec:(e,t)=>function(e,t){let n=T(e,t);const i=2147483648&n.hi;i&&(n=S(n.lo,n.hi));const r=b(n.lo,n.hi);return i?"-"+r:r}(e,t),uDec:(e,t)=>b(e,t)}}();var P,I,_;function M(e,t,n){if(t===n)return!0;if(e==P.BYTES){if(!(t instanceof Uint8Array&&n instanceof Uint8Array))return!1;if(t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}switch(e){case P.UINT64:case P.FIXED64:case P.INT64:case P.SFIXED64:case P.SINT64:return t==n}return!1}function D(e,t){switch(e){case P.BOOL:return!1;case P.UINT64:case P.FIXED64:case P.INT64:case P.SFIXED64:case P.SINT64:return 0==t?R.zero:"0";case P.DOUBLE:case P.FLOAT:return 0;case P.BYTES:return new Uint8Array(0);case P.STRING:return"";default:return 0}}function O(e,t){switch(e){case P.BOOL:return!1===t;case P.STRING:return""===t;case P.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}function A(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function L(e){if(Array.isArray(e))return e}function N(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t);if("object"!=typeof i)return i;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:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function x(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function U(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function F(e,t){return L(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,r,a,s,o=[],c=!0,d=!1;try{if(a=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=a.call(n)).done)&&(o.push(i.value),o.length!==t);c=!0);}catch(e){d=!0,r=e}finally{try{if(!c&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw r}}return o}}(e,t)||j(e,t)||x()}function B(e){return L(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||j(e)||x()}function j(e,t){if(e){if("string"==typeof e)return A(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?A(e,t):void 0}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(P||(P={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(I||(I={})),function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(_||(_={}));class q{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 i=0;i<this.chunks.length;i++)e+=this.chunks[i].length;let t=new Uint8Array(e),n=0;for(let i=0;i<this.chunks.length;i++)t.set(this.chunks[i],n),n+=this.chunks[i].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(o(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return s(e),C(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){c(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){o(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){s(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return s(e),C(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=R.enc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=R.uEnc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}int64(e){let t=R.enc(e);return f(t.lo,t.hi,this.buf),this}sint64(e){let t=R.enc(e),n=t.hi>>31;return f(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=R.uEnc(e);return f(t.lo,t.hi,this.buf),this}}class V{constructor(e,t){this.varint64=v,this.uint32=w,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,n=7&e;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case _.Varint:for(;128&this.buf[this.pos++];);break;case _.Bit64:this.pos+=4;case _.Bit32:this.pos+=4;break;case _.LengthDelimited:let n=this.uint32();this.pos+=n;break;case _.StartGroup:for(;;){const e=F(this.tag(),2),n=e[0],i=e[1];if(i===_.EndGroup){if(void 0!==t&&n!==t)throw new Error("invalid end group tag");break}this.skip(i,n)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,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 R.dec(...this.varint64())}uint64(){return R.uDec(...this.varint64())}sint64(){let e=F(this.varint64(),2),t=e[0],n=e[1],i=-(1&t);return t=(t>>>1|(1&n)<<31)^i,n=n>>>1^i,R.dec(t,n)}bool(){let e=F(this.varint64(),2),t=e[0],n=e[1];return 0!==t||0!==n}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return R.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return R.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 W(e){const t=e.field.localName,n=Object.create(null);return n[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 D(t.T,t.L);case"message":const e=t.T,n=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}(e),[n,()=>n[t]]}let H="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),K=[];for(let Wh=0;Wh<H.length;Wh++)K[H[Wh].charCodeAt(0)]=Wh;K["-".charCodeAt(0)]=H.indexOf("+"),K["_".charCodeAt(0)]=H.indexOf("/");const z={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let n,i=new Uint8Array(t),r=0,a=0,s=0;for(let o=0;o<e.length;o++){if(n=K[e.charCodeAt(o)],void 0===n)switch(e[o]){case"=":a=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(a){case 0:s=n,a=1;break;case 1:i[r++]=s<<2|(48&n)>>4,s=n,a=2;break;case 2:i[r++]=(15&s)<<4|(60&n)>>2,s=n,a=3;break;case 3:i[r++]=(3&s)<<6|n,a=0}}if(1==a)throw Error("invalid base64 string.");return i.subarray(0,r)},enc(e){let t,n="",i=0,r=0;for(let a=0;a<e.length;a++)switch(t=e[a],i){case 0:n+=H[t>>2],r=(3&t)<<4,i=1;break;case 1:n+=H[r|t>>4],r=(15&t)<<2,i=2;break;case 2:n+=H[r|t>>6],n+=H[63&t],i=0}return i&&(n+=H[r],n+="=",1==i&&(n+="=")),n}};function G(e,t,n){Y(t,e);const i=t.runtime.bin.makeReadOptions(n),r=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter((e=>e.no===t.no))}(e.getType().runtime.bin.listUnknownFields(e),t.field),a=F(W(t),2),s=a[0],o=a[1];for(const c of r)t.runtime.bin.readField(s,i.readerFactory(c.data),t.field,c.wireType,i);return o()}function J(e,t,n,i){Y(t,e);const r=t.runtime.bin.makeReadOptions(i),a=t.runtime.bin.makeWriteOptions(i);if(Q(e,t)){const n=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of n)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const s=a.writerFactory();let o=t.field;o.opt||o.repeated||"enum"!=o.kind&&"scalar"!=o.kind||(o=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(o,n,s,a);const c=r.readerFactory(s.finish());for(;c.pos<c.len;){const t=F(c.tag(),2),n=t[0],i=t[1],r=c.skip(i,n);e.getType().runtime.bin.onUnknownField(e,n,i,r)}}function Q(e,t){const n=e.getType();return t.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(e).find((e=>e.no==t.field.no))}function Y(e,t){a(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function X(e,t){const n=e.localName;if(e.repeated)return t[n].length>0;if(e.oneof)return t[e.oneof.localName].case===n;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?void 0!==t[n]:"enum"==e.kind?t[n]!==e.T.values[0].no:!O(e.T,t[n]);case"message":return void 0!==t[n];case"map":return Object.keys(t[n]).length>0}}function Z(e,t){const n=e.localName,i=!e.opt&&!e.req;if(e.repeated)t[n]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[n]={};break;case"enum":t[n]=i?e.T.values[0].no:void 0;break;case"scalar":t[n]=i?D(e.T,e.L):void 0;break;case"message":t[n]=void 0}}function $(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(g.prototype).every((t=>t in e&&"function"==typeof e[t])))return!1;const n=e.getType();return null!==n&&"function"==typeof n&&"typeName"in n&&"string"==typeof n.typeName&&(void 0===t||n.typeName==t.typeName)}function ee(e,t){return $(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}P.DOUBLE,P.FLOAT,P.INT64,P.UINT64,P.INT32,P.UINT32,P.BOOL,P.STRING,P.BYTES;const te={ignoreUnknownFields:!1},ne={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function ie(e){return e?Object.assign(Object.assign({},te),e):te}function re(e){return e?Object.assign(Object.assign({},ne),e):ne}const ae=Symbol(),se=Symbol();function oe(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 ce(e,t,i,r,s){let o=i.localName;if(i.repeated){if(a("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(oe(t)));const c=e[o];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(oe(e)));switch(i.kind){case"message":c.push(i.T.fromJson(e,r));break;case"enum":const t=ue(i.T,e,r.ignoreUnknownFields,!0);t!==se&&c.push(t);break;case"scalar":try{c.push(le(i.T,e,i.L,!0))}catch(n){let r="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(oe(e));throw n instanceof Error&&n.message.length>0&&(r+=": ".concat(n.message)),new Error(r)}}}}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(oe(t)));const a=e[o];for(const e of Object.entries(t)){var c=F(e,2);const o=c[0],d=c[1];if(null===d)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: map value null"));let l;try{l=de(i.K,o)}catch(n){let r="cannot decode map key for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(oe(t));throw n instanceof Error&&n.message.length>0&&(r+=": ".concat(n.message)),new Error(r)}switch(i.V.kind){case"message":a[l]=i.V.T.fromJson(d,r);break;case"enum":const e=ue(i.V.T,d,r.ignoreUnknownFields,!0);e!==se&&(a[l]=e);break;case"scalar":try{a[l]=le(i.V.T,d,I.BIGINT,!0)}catch(n){let r="cannot decode map value for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(oe(t));throw n instanceof Error&&n.message.length>0&&(r+=": ".concat(n.message)),new Error(r)}}}}else switch(i.oneof&&(e=e[i.oneof.localName]={case:o},o="value"),i.kind){case"message":const a=i.T;if(null===t&&"google.protobuf.Value"!=a.typeName)return;let c=e[o];$(c)?c.fromJson(t,r):(e[o]=c=a.fromJson(t,r),a.fieldWrapper&&!i.oneof&&(e[o]=a.fieldWrapper.unwrapField(c)));break;case"enum":const d=ue(i.T,t,r.ignoreUnknownFields,!1);switch(d){case ae:Z(i,e);break;case se:break;default:e[o]=d}break;case"scalar":try{const n=le(i.T,t,i.L,!1);if(n===ae)Z(i,e);else e[o]=n}catch(n){let r="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(oe(t));throw n instanceof Error&&n.message.length>0&&(r+=": ".concat(n.message)),new Error(r)}}}function de(e,t){if(e===P.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return le(e,t,I.BIGINT,!0).toString()}function le(e,t,i,r){if(null===t)return r?D(e,i):ae;switch(e){case P.DOUBLE:case P.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 r=Number(t);if(Number.isNaN(r))break;if(!Number.isFinite(r))break;return e==P.FLOAT&&c(r),r;case P.INT32:case P.FIXED32:case P.SFIXED32:case P.SINT32:case P.UINT32:let a;if("number"==typeof t?a=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(a=Number(t)),void 0===a)break;return e==P.UINT32||e==P.FIXED32?o(a):s(a),a;case P.INT64:case P.SFIXED64:case P.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const d=R.parse(t);return i?d.toString():d;case P.FIXED64:case P.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const l=R.uParse(t);return i?l.toString():l;case P.BOOL:if("boolean"!=typeof t)break;return t;case P.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(n){throw new Error("invalid UTF8")}return t;case P.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return z.dec(t)}throw new Error}function ue(e,t,n,i){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:i?e.values[0].no:ae;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const i=e.findName(t);if(void 0!==i)return i.no;if(n)return se}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(oe(t)))}function he(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function pe(e,t,n){if("map"==e.kind){a("object"==typeof t&&null!=t);const o={},c=Object.entries(t);switch(e.V.kind){case"scalar":for(const n of c){var i=F(n,2);const t=i[0],r=i[1];o[t.toString()]=ge(e.V.T,r)}break;case"message":for(const e of c){var r=F(e,2);const t=r[0],i=r[1];o[t.toString()]=i.toJson(n)}break;case"enum":const t=e.V.T;for(const e of c){var s=F(e,2);const i=s[0],r=s[1];o[i.toString()]=me(t,r,n.enumAsInteger)}}return n.emitDefaultValues||c.length>0?o:void 0}if(e.repeated){a(Array.isArray(t));const i=[];switch(e.kind){case"scalar":for(let n=0;n<t.length;n++)i.push(ge(e.T,t[n]));break;case"enum":for(let r=0;r<t.length;r++)i.push(me(e.T,t[r],n.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)i.push(t[e].toJson(n))}return n.emitDefaultValues||i.length>0?i:void 0}switch(e.kind){case"scalar":return ge(e.T,t);case"enum":return me(e.T,t,n.enumAsInteger);case"message":return ee(e.T,t).toJson(n)}}function me(e,t,n){var i;if(a("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(n)return t;const r=e.findNumber(t);return null!==(i=null==r?void 0:r.name)&&void 0!==i?i:t}function ge(e,t){switch(e){case P.INT32:case P.SFIXED32:case P.SINT32:case P.FIXED32:case P.UINT32:return a("number"==typeof t),t;case P.FLOAT:case P.DOUBLE:return a("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case P.STRING:return a("string"==typeof t),t;case P.BOOL:return a("boolean"==typeof t),t;case P.UINT64:case P.FIXED64:case P.INT64:case P.SFIXED64:case P.SINT64:return a("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case P.BYTES:return a(t instanceof Uint8Array),z.enc(t)}}const ve=Symbol("@bufbuild/protobuf/unknown-fields"),fe={readUnknownFields:!0,readerFactory:e=>new V(e)},ke={writeUnknownFields:!0,writerFactory:()=>new q};function ye(e){return e?Object.assign(Object.assign({},fe),e):fe}function be(e){return e?Object.assign(Object.assign({},ke),e):ke}function Te(e,t,n,i,r){let a=n.repeated,s=n.localName;switch(n.oneof&&((e=e[n.oneof.localName]).case!=s&&delete e.value,e.case=s,s="value"),n.kind){case"scalar":case"enum":const o="enum"==n.kind?P.INT32:n.T;let c=Ce;if("scalar"==n.kind&&n.L>0&&(c=Ee),a){let n=e[s];if(i==_.LengthDelimited&&o!=P.STRING&&o!=P.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,o))}else n.push(c(t,o))}else e[s]=c(t,o);break;case"message":const d=n.T;a?e[s].push(Se(t,new d,r,n)):$(e[s])?Se(t,e[s],r,n):(e[s]=Se(t,new d,r,n),!d.fieldWrapper||n.oneof||n.repeated||(e[s]=d.fieldWrapper.unwrapField(e[s])));break;case"map":let l=function(e,t,n){const i=t.uint32(),r=t.pos+i;let a,s;for(;t.pos<r;){switch(F(t.tag(),1)[0]){case 1:a=Ce(t,e.K);break;case 2:switch(e.V.kind){case"scalar":s=Ce(t,e.V.T);break;case"enum":s=t.int32();break;case"message":s=Se(t,new e.V.T,n,void 0)}}}void 0===a&&(a=D(e.K,I.BIGINT));"string"!=typeof a&&"number"!=typeof a&&(a=a.toString());if(void 0===s)switch(e.V.kind){case"scalar":s=D(e.V.T,I.BIGINT);break;case"enum":s=e.V.T.values[0].no;break;case"message":s=new e.V.T}return[a,s]}(n,t,r),u=F(l,2),h=u[0],p=u[1];e[s][h]=p}}function Se(e,t,n,i){const r=t.getType().runtime.bin,a=null==i?void 0:i.delimited;return r.readMessage(t,e,a?i.no:e.uint32(),n,a),t}function Ee(e,t){const n=Ce(e,t);return"bigint"==typeof n?n.toString():n}function Ce(e,t){switch(t){case P.STRING:return e.string();case P.BOOL:return e.bool();case P.DOUBLE:return e.double();case P.FLOAT:return e.float();case P.INT32:return e.int32();case P.INT64:return e.int64();case P.UINT64:return e.uint64();case P.FIXED64:return e.fixed64();case P.BYTES:return e.bytes();case P.FIXED32:return e.fixed32();case P.SFIXED32:return e.sfixed32();case P.SFIXED64:return e.sfixed64();case P.SINT64:return e.sint64();case P.UINT32:return e.uint32();case P.SINT32:return e.sint32()}}function we(e,t,n,i){a(void 0!==t);const r=e.repeated;switch(e.kind){case"scalar":case"enum":let o="enum"==e.kind?P.INT32:e.T;if(r)if(a(Array.isArray(t)),e.packed)!function(e,t,n,i){if(!i.length)return;e.tag(n,_.LengthDelimited).fork();let r=F(_e(t),2)[1];for(let a=0;a<i.length;a++)e[r](i[a]);e.join()}(n,o,e.no,t);else for(const i of t)Ie(n,o,e.no,i);else Ie(n,o,e.no,t);break;case"message":if(r){a(Array.isArray(t));for(const r of t)Pe(n,i,e,r)}else Pe(n,i,e,t);break;case"map":a("object"==typeof t&&null!=t);for(const r of Object.entries(t)){var s=F(r,2);Re(n,i,e,s[0],s[1])}}}function Re(e,t,n,i,r){e.tag(n.no,_.LengthDelimited),e.fork();let s=i;switch(n.K){case P.INT32:case P.FIXED32:case P.UINT32:case P.SFIXED32:case P.SINT32:s=Number.parseInt(i);break;case P.BOOL:a("true"==i||"false"==i),s="true"==i}switch(Ie(e,n.K,1,s),n.V.kind){case"scalar":Ie(e,n.V.T,2,r);break;case"enum":Ie(e,P.INT32,2,r);break;case"message":a(void 0!==r),e.tag(2,_.LengthDelimited).bytes(r.toBinary(t))}e.join()}function Pe(e,t,n,i){const r=ee(n.T,i);n.delimited?e.tag(n.no,_.StartGroup).raw(r.toBinary(t)).tag(n.no,_.EndGroup):e.tag(n.no,_.LengthDelimited).bytes(r.toBinary(t))}function Ie(e,t,n,i){a(void 0!==i);let r=F(_e(t),2),s=r[0],o=r[1];e.tag(n,s)[o](i)}function _e(e){let t=_.Varint;switch(e){case P.BYTES:case P.STRING:t=_.LengthDelimited;break;case P.DOUBLE:case P.FIXED64:case P.SFIXED64:t=_.Bit64;break;case P.FIXED32:case P.SFIXED32:case P.FLOAT:t=_.Bit32}return[t,P[e].toLowerCase()]}function Me(e){if(void 0===e)return e;if($(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function De(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class Oe{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 n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}}function Ae(e,t){const n=Ne(e);return t?n:je(Be(n))}const Le=Ne;function Ne(e){let t=!1;const n=[];for(let i=0;i<e.length;i++){let r=e.charAt(i);switch(r){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n.push(r),t=!1;break;default:t&&(t=!1,r=r.toUpperCase()),n.push(r)}}return n.join("")}const xe=new Set(["constructor","toString","toJSON","valueOf"]),Ue=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Fe=e=>"".concat(e,"$"),Be=e=>Ue.has(e)?Fe(e):e,je=e=>xe.has(e)?Fe(e):e;class qe{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=Ae(e,!1)}addField(e){a(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 Ve=(We=e=>new Oe(e,(e=>function(e){var t,n,i,r,a,s;const o=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=Ae(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:Le(d.name),e.repeated=null!==(n=d.repeated)&&void 0!==n&&n,"scalar"==d.kind&&(e.L=null!==(i=d.L)&&void 0!==i?i:I.BIGINT),e.delimited=null!==(r=d.delimited)&&void 0!==r&&r,e.req=null!==(a=d.req)&&void 0!==a&&a,e.opt=null!==(s=d.opt)&&void 0!==s&&s,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=P.BYTES&&d.T!=P.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new qe(t)),e.oneof=c,c.addField(e)}o.push(e)}return o}(e))),He=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const n=t.localName,i=e;if(t.repeated)i[n]=[];else switch(t.kind){case"oneof":i[n]={case:void 0};break;case"enum":i[n]=0;break;case"map":i[n]={};break;case"scalar":i[n]=D(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:ie,makeWriteOptions:re,readMessage(e,t,n,i){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(oe(t)));i=null!=i?i:new e;const r=new Map,a=n.typeRegistry;for(const o of Object.entries(t)){var s=F(o,2);const t=s[0],c=s[1],d=e.fields.findJsonName(t);if(d){if(d.oneof){if(null===c&&"scalar"==d.kind)continue;const n=r.get(d.oneof);if(void 0!==n)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(d.oneof.name,'" present: "').concat(n,'", "').concat(t,'"'));r.set(d.oneof,t)}ce(i,c,d,n,e)}else{let r=!1;if((null==a?void 0:a.findExtension)&&t.startsWith("[")&&t.endsWith("]")){const s=a.findExtension(t.substring(1,t.length-1));if(s&&s.extendee.typeName==e.typeName){r=!0;const e=F(W(s),2),t=e[0],a=e[1];ce(t,c,s.field,n,s),J(i,s,a(),n)}}if(!r&&!n.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(t,'" is unknown'))}}return i},writeMessage(e,t){const i=e.getType(),r={};let a;try{for(a of i.fields.byNumber()){if(!X(a,e)){if(a.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!he(a))continue}const n=pe(a,a.oneof?e[a.oneof.localName].value:e[a.localName],t);void 0!==n&&(r[t.useProtoFieldName?a.name:a.jsonName]=n)}const n=t.typeRegistry;if(null==n?void 0:n.findExtensionFor)for(const a of i.runtime.bin.listUnknownFields(e)){const s=n.findExtensionFor(i.typeName,a.no);if(s&&Q(e,s)){const n=G(e,s,t),i=pe(s.field,n,t);void 0!==i&&(r[s.field.jsonName]=i)}}}catch(n){const t=a?"cannot encode field ".concat(i.typeName,".").concat(a.name," to JSON"):"cannot encode message ".concat(i.typeName," to JSON"),r=n instanceof Error?n.message:String(n);throw new Error(t+(r.length>0?": ".concat(r):""))}return r},readScalar:(e,t,n)=>le(e,t,null!=n?n:I.BIGINT,!0),writeScalar(e,t,n){if(void 0!==t)return n||O(e,t)?ge(e,t):void 0},debug:oe},bin:{makeReadOptions:ye,makeWriteOptions:be,listUnknownFields(e){var t;return null!==(t=e[ve])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[ve]},writeUnknownFields(e,t){const n=e[ve];if(n)for(const i of n)t.tag(i.no,i.wireType).raw(i.data)},onUnknownField(e,t,n,i){const r=e;Array.isArray(r[ve])||(r[ve]=[]),r[ve].push({no:t,wireType:n,data:i})},readMessage(e,t,n,i,r){const a=e.getType(),s=r?t.len:t.pos+n;let o,c;for(;t.pos<s;){var d=F(t.tag(),2);if(o=d[0],c=d[1],!0===r&&c==_.EndGroup)break;const n=a.fields.find(o);if(n)Te(e,t,n,c,i);else{const n=t.skip(c,o);i.readUnknownFields&&this.onUnknownField(e,o,c,n)}}if(r&&(c!=_.EndGroup||o!==n))throw new Error("invalid end group tag")},readField:Te,writeMessage(e,t,n){const i=e.getType();for(const r of i.fields.byNumber())if(X(r,e))we(r,r.oneof?e[r.oneof.localName].value:e[r.localName],t,n);else if(r.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(r.name," to binary: required field not set"));return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,i){void 0!==t&&we(e,t,n,i)}},util:Object.assign(Object.assign({},{setEnumType:u,initPartial(e,t){if(void 0===e)return;const n=t.getType();for(const r of n.fields.byMember()){const n=r.localName,a=t,s=e;if(null!=s[n])switch(r.kind){case"oneof":const e=s[n].case;if(void 0===e)continue;const t=r.findField(e);let o=s[n].value;t&&"message"==t.kind&&!$(o,t.T)?o=new t.T(o):t&&"scalar"===t.kind&&t.T===P.BYTES&&(o=De(o)),a[n]={case:e,value:o};break;case"scalar":case"enum":let c=s[n];r.T===P.BYTES&&(c=r.repeated?c.map(De):De(c)),a[n]=c;break;case"map":switch(r.V.kind){case"scalar":case"enum":if(r.V.T===P.BYTES)for(const t of Object.entries(s[n])){var i=F(t,2);const e=i[0],r=i[1];a[n][e]=De(r)}else Object.assign(a[n],s[n]);break;case"message":const e=r.V.T;for(const t of Object.keys(s[n])){let i=s[n][t];e.fieldWrapper||(i=new e(i)),a[n][t]=i}}break;case"message":const d=r.T;if(r.repeated)a[n]=s[n].map((e=>$(e,d)?e:new d(e)));else{const e=s[n];d.fieldWrapper?"google.protobuf.BytesValue"===d.typeName?a[n]=De(e):a[n]=e:a[n]=$(e,d)?e:new d(e)}}}},equals:(e,t,n)=>t===n||!(!t||!n)&&e.fields.byMember().every((e=>{const i=t[e.localName],r=n[e.localName];if(e.repeated){if(i.length!==r.length)return!1;switch(e.kind){case"message":return i.every(((t,n)=>e.T.equals(t,r[n])));case"scalar":return i.every(((t,n)=>M(e.T,t,r[n])));case"enum":return i.every(((e,t)=>M(P.INT32,e,r[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let t=i,n=r;return e.T.fieldWrapper&&(void 0===t||$(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===n||$(n)||(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case"enum":return M(P.INT32,i,r);case"scalar":return M(e.T,i,r);case"oneof":if(i.case!==r.case)return!1;const a=e.findField(i.case);if(void 0===a)return!0;switch(a.kind){case"message":return a.T.equals(i.value,r.value);case"enum":return M(P.INT32,i.value,r.value);case"scalar":return M(a.T,i.value,r.value)}throw new Error("oneof cannot contain ".concat(a.kind));case"map":const s=Object.keys(i).concat(Object.keys(r));switch(e.V.kind){case"message":const t=e.V.T;return s.every((e=>t.equals(i[e],r[e])));case"enum":return s.every((e=>M(P.INT32,i[e],r[e])));case"scalar":const n=e.V.T;return s.every((e=>M(n,i[e],r[e])))}}})),clone(e){const t=e.getType(),n=new t,i=n;for(const a of t.fields.byMember()){const t=e[a.localName];let n;if(a.repeated)n=t.map(Me);else if("map"==a.kind){n=i[a.localName];for(const e of Object.entries(t)){var r=F(e,2);const t=r[0],i=r[1];n[t]=Me(i)}}else n="oneof"==a.kind?a.findField(t.case)?{case:t.case,value:Me(t.value)}:{case:void 0}:Me(t);i[a.localName]=n}for(const a of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(i,a.no,a.wireType,a.data);return n}}),{newFieldList:We,initFields:He}),makeMessageType(e,t,n){return function(e,t,n,i){var r;const a=null!==(r=null==i?void 0:i.localName)&&void 0!==r?r:t.substring(t.lastIndexOf(".")+1),s={[a]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[a];return Object.setPrototypeOf(s.prototype,new g),Object.assign(s,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary:(e,t)=>(new s).fromBinary(e,t),fromJson:(e,t)=>(new s).fromJson(e,t),fromJsonString:(e,t)=>(new s).fromJsonString(e,t),equals:(t,n)=>e.util.equals(s,t,n)}),s}(this,e,t,n)},makeEnum:p,makeEnumType:h,getEnumType:l,makeExtension(e,t,n){return function(e,t,n,i){let r;return{typeName:t,extendee:n,get field(){if(!r){const n="function"==typeof i?i():i;n.name=t.split(".").pop(),n.jsonName="[".concat(t,"]"),r=e.util.newFieldList([n]).list()[0]}return r},runtime:e}}(this,e,t,n)}});var We,He;class Ke extends g{constructor(e){super(),this.seconds=R.zero,this.nanos=0,Ve.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(Ve.json.debug(e)));const n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(i<Date.parse("0001-01-01T00:00:00Z")||i>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=R.parse(i/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt("1"+n[7]+"0".repeat(9-n[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 n="Z";if(this.nanos>0){const e=(this.nanos+1e9).toString().substring(1);n="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",n)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return Ke.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new Ke({seconds:R.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new Ke).fromBinary(e,t)}static fromJson(e,t){return(new Ke).fromJson(e,t)}static fromJsonString(e,t){return(new Ke).fromJsonString(e,t)}static equals(e,t){return Ve.util.equals(Ke,e,t)}}Ke.runtime=Ve,Ke.typeName="google.protobuf.Timestamp",Ke.fields=Ve.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const ze=Ve.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ke},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Ge,repeated:!0},{no:5,name:"events",kind:"message",T:Qe,repeated:!0}])),Ge=Ve.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:Je,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),Je=Ve.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ke},{no:3,name:"value",kind:"scalar",T:2}])),Qe=Ve.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:Ke},{no:7,name:"normalized_end_timestamp",kind:"message",T:Ke,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),Ye=Ve.makeEnum("livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"},{no:3,name:"AC_MP3"}]),Xe=Ve.makeEnum("livekit.VideoCodec",[{no:0,name:"DEFAULT_VC"},{no:1,name:"H264_BASELINE"},{no:2,name:"H264_MAIN"},{no:3,name:"H264_HIGH"},{no:4,name:"VP8"}]),Ze=Ve.makeEnum("livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]),$e=Ve.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),et=Ve.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),tt=Ve.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"}]),nt=Ve.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),it=Ve.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),rt=Ve.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),at=Ve.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"},{no:16,name:"AGENT_ERROR"}]),st=Ve.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"}]),ot=Ve.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),ct=Ve.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"}]),dt=Ve.makeEnum("livekit.PacketTrailerFeature",[{no:0,name:"PTF_USER_TIMESTAMP"},{no:1,name:"PTF_FRAME_ID"},{no:2,name:"PTF_USER_DATA"}]),lt=Ve.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:ut,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:tn}])),ut=Ve.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),ht=Ve.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:Ve.getEnumType(tt),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},{no:13,name:"can_manage_agent_session",kind:"scalar",T:8}])),pt=Ve.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:Ve.getEnumType(mt)},{no:4,name:"tracks",kind:"message",T:yt,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:ht},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:Ve.getEnumType(gt)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:Ve.getEnumType(at)},{no:18,name:"kind_details",kind:"enum",T:Ve.getEnumType(vt),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:bt,repeated:!0},{no:20,name:"client_protocol",kind:"scalar",T:5},{no:21,name:"capabilities",kind:"enum",T:Ve.getEnumType(Xt),repeated:!0}])),mt=Ve.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),gt=Ve.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"},{no:8,name:"BRIDGE"}]),vt=Ve.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"},{no:2,name:"CONNECTOR_WHATSAPP"},{no:3,name:"CONNECTOR_TWILIO"},{no:4,name:"BRIDGE_RTSP"},{no:5,name:"SIMULATION"}]),ft=Ve.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),kt=Ve.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:_t,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:Ve.getEnumType(Mt)},{no:6,name:"sdp_cid",kind:"scalar",T:9}])),yt=Ve.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:Ve.getEnumType(et)},{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:Ve.getEnumType(tt)},{no:10,name:"layers",kind:"message",T:_t,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:kt,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:Ve.getEnumType(ft)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:tn},{no:19,name:"audio_features",kind:"enum",T:Ve.getEnumType(ct),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:Ve.getEnumType($e)},{no:21,name:"packet_trailer_features",kind:"enum",T:Ve.getEnumType(dt),repeated:!0}])),bt=Ve.makeMessageType("livekit.DataTrackInfo",(()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"sid",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"encryption",kind:"enum",T:Ve.getEnumType(ft)},{no:5,name:"frame_encoding",kind:"message",T:Tt,opt:!0},{no:6,name:"schema",kind:"message",T:wt,opt:!0}])),Tt=Ve.makeMessageType("livekit.DataTrackFrameEncoding",(()=>[{no:1,name:"well_known",kind:"enum",T:Ve.getEnumType(St),oneof:"value"},{no:2,name:"custom",kind:"scalar",T:9,oneof:"value"}])),St=Ve.makeEnum("livekit.DataTrackFrameEncoding.WellKnownFrameEncoding",[{no:0,name:"WELL_KNOWN_FRAME_ENCODING_UNSPECIFIED",localName:"UNSPECIFIED"},{no:1,name:"WELL_KNOWN_FRAME_ENCODING_ROS1",localName:"ROS1"},{no:2,name:"WELL_KNOWN_FRAME_ENCODING_CDR",localName:"CDR"},{no:3,name:"WELL_KNOWN_FRAME_ENCODING_PROTOBUF",localName:"PROTOBUF"},{no:4,name:"WELL_KNOWN_FRAME_ENCODING_FLATBUFFER",localName:"FLATBUFFER"},{no:5,name:"WELL_KNOWN_FRAME_ENCODING_CBOR",localName:"CBOR"},{no:6,name:"WELL_KNOWN_FRAME_ENCODING_MSGPACK",localName:"MSGPACK"},{no:7,name:"WELL_KNOWN_FRAME_ENCODING_JSON",localName:"JSON"}]),Et=Ve.makeMessageType("livekit.DataTrackSchemaEncoding",(()=>[{no:1,name:"well_known",kind:"enum",T:Ve.getEnumType(Ct),oneof:"value"},{no:2,name:"custom",kind:"scalar",T:9,oneof:"value"}])),Ct=Ve.makeEnum("livekit.DataTrackSchemaEncoding.WellKnownSchemaEncoding",[{no:0,name:"WELL_KNOWN_SCHEMA_ENCODING_UNSPECIFIED",localName:"UNSPECIFIED"},{no:1,name:"WELL_KNOWN_SCHEMA_ENCODING_PROTOBUF",localName:"PROTOBUF"},{no:2,name:"WELL_KNOWN_SCHEMA_ENCODING_FLATBUFFER",localName:"FLATBUFFER"},{no:3,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS1_MSG",localName:"ROS1_MSG"},{no:4,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS2_MSG",localName:"ROS2_MSG"},{no:5,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS2_IDL",localName:"ROS2_IDL"},{no:6,name:"WELL_KNOWN_SCHEMA_ENCODING_OMG_IDL",localName:"OMG_IDL"},{no:7,name:"WELL_KNOWN_SCHEMA_ENCODING_JSON_SCHEMA",localName:"JSON_SCHEMA"}]),wt=Ve.makeMessageType("livekit.DataTrackSchemaId",(()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"encoding",kind:"message",T:Et}])),Rt=Ve.makeMessageType("livekit.DataTrackSubscriptionOptions",(()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}])),Pt=Ve.makeMessageType("livekit.DataBlobKey",(()=>[{no:1,name:"generic",kind:"scalar",T:9,oneof:"key"},{no:2,name:"schema_id",kind:"message",T:wt,oneof:"key"}])),It=Ve.makeMessageType("livekit.DataBlob",(()=>[{no:1,name:"key",kind:"message",T:Pt},{no:2,name:"contents",kind:"scalar",T:12}])),_t=Ve.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:Ve.getEnumType(nt)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9},{no:8,name:"repair_ssrc",kind:"scalar",T:13}])),Mt=Ve.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"}]),Dt=Ve.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:Ve.getEnumType(Ot)},{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:Ut,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Nt,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:Ft,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Bt,oneof:"value"},{no:8,name:"metrics",kind:"message",T:ze,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:qt,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Vt,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Wt,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Ht,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:on,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:cn,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:dn,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:At,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}])),Ot=Ve.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),At=Ve.makeMessageType("livekit.EncryptedPacket",(()=>[{no:1,name:"encryption_type",kind:"enum",T:Ve.getEnumType(ft)},{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}])),Lt=Ve.makeMessageType("livekit.EncryptedPacketPayload",(()=>[{no:1,name:"user",kind:"message",T:Ut,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:qt,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:Vt,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:Wt,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:Ht,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:on,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:cn,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:dn,oneof:"value"}])),Nt=Ve.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:xt,repeated:!0}])),xt=Ve.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}])),Ut=Ve.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}])),Ft=Ve.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),Bt=Ve.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:jt,repeated:!0}])),jt=Ve.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}])),qt=Ve.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}])),Vt=Ve.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},{no:6,name:"compressed_payload",kind:"scalar",T:12}])),Wt=Ve.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),Ht=Ve.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:Kt,oneof:"value"},{no:4,name:"compressed_payload",kind:"scalar",T:12,oneof:"value"}])),Kt=Ve.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}])),zt=Ve.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),Gt=Ve.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:Ve.getEnumType(Jt)},{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}])),Jt=Ve.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Qt=Ve.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:Ve.getEnumType(Yt)},{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},{no:12,name:"client_protocol",kind:"scalar",T:5},{no:13,name:"capabilities",kind:"enum",T:Ve.getEnumType(Xt),repeated:!0}])),Yt=Ve.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"}]),Xt=Ve.makeEnum("livekit.ClientInfo.Capability",[{no:0,name:"CAP_UNUSED"},{no:1,name:"CAP_PACKET_TRAILER"},{no:2,name:"CAP_COMPRESSION_DEFLATE_RAW"}]),Zt=Ve.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:$t},{no:2,name:"screen",kind:"message",T:$t},{no:3,name:"resume_connection",kind:"enum",T:Ve.getEnumType(rt)},{no:4,name:"disabled_codecs",kind:"message",T:en},{no:5,name:"force_relay",kind:"enum",T:Ve.getEnumType(rt)}])),$t=Ve.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:Ve.getEnumType(rt)}])),en=Ve.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:ut,repeated:!0},{no:2,name:"publish",kind:"message",T:ut,repeated:!0}])),tn=Ve.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),nn=Ve.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),rn=Ve.makeEnum("livekit.DataStream.CompressionType",[{no:0,name:"NONE"},{no:1,name:"DEFLATE_RAW"}]),an=Ve.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:Ve.getEnumType(nn)},{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=Ve.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),on=Ve.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:Ve.getEnumType(ft)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:an,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:sn,oneof:"content_header"},{no:11,name:"inline_content",kind:"scalar",T:12,opt:!0},{no:12,name:"compression",kind:"enum",T:Ve.getEnumType(rn)}]),{localName:"DataStream_Header"}),cn=Ve.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"}),dn=Ve.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"}),ln=Ve.makeMessageType("livekit.FilterParams",(()=>[{no:1,name:"include_events",kind:"scalar",T:9,repeated:!0},{no:2,name:"exclude_events",kind:"scalar",T:9,repeated:!0}])),un=Ve.makeMessageType("livekit.WebhookConfig",(()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"signing_key",kind:"scalar",T:9},{no:3,name:"filter_params",kind:"message",T:ln}])),hn=Ve.makeMessageType("livekit.SubscribedAudioCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}])),pn=Ve.makeEnum("livekit.JobRestartPolicy",[{no:0,name:"JRP_ON_FAILURE"},{no:1,name:"JRP_NEVER"}]),mn=Ve.makeMessageType("livekit.RoomAgentDispatch",(()=>[{no:1,name:"agent_name",kind:"scalar",T:9},{no:2,name:"metadata",kind:"scalar",T:9},{no:3,name:"restart_policy",kind:"enum",T:Ve.getEnumType(pn)},{no:4,name:"deployment",kind:"scalar",T:9},{no:5,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}])),gn=Ve.makeEnum("livekit.EncodingOptionsPreset",[{no:0,name:"H264_720P_30"},{no:1,name:"H264_720P_60"},{no:2,name:"H264_1080P_30"},{no:3,name:"H264_1080P_60"},{no:4,name:"PORTRAIT_H264_720P_30"},{no:5,name:"PORTRAIT_H264_720P_60"},{no:6,name:"PORTRAIT_H264_1080P_30"},{no:7,name:"PORTRAIT_H264_1080P_60"}]),vn=Ve.makeEnum("livekit.EncodedFileType",[{no:0,name:"DEFAULT_FILETYPE"},{no:1,name:"MP4"},{no:2,name:"OGG"},{no:3,name:"MP3"}]),fn=Ve.makeEnum("livekit.StreamProtocol",[{no:0,name:"DEFAULT_PROTOCOL"},{no:1,name:"RTMP"},{no:2,name:"SRT"},{no:3,name:"WEBSOCKET"}]),kn=Ve.makeEnum("livekit.SegmentedFileProtocol",[{no:0,name:"DEFAULT_SEGMENTED_FILE_PROTOCOL"},{no:1,name:"HLS_PROTOCOL"}]),yn=Ve.makeEnum("livekit.SegmentedFileSuffix",[{no:0,name:"INDEX"},{no:1,name:"TIMESTAMP"}]),bn=Ve.makeEnum("livekit.ImageFileSuffix",[{no:0,name:"IMAGE_SUFFIX_INDEX"},{no:1,name:"IMAGE_SUFFIX_TIMESTAMP"},{no:2,name:"IMAGE_SUFFIX_NONE_OVERWRITE"}]),Tn=Ve.makeEnum("livekit.AudioMixing",[{no:0,name:"DEFAULT_MIXING"},{no:1,name:"DUAL_CHANNEL_AGENT"},{no:2,name:"DUAL_CHANNEL_ALTERNATE"}]),Sn=Ve.makeMessageType("livekit.EncodingOptions",(()=>[{no:1,name:"width",kind:"scalar",T:5},{no:2,name:"height",kind:"scalar",T:5},{no:3,name:"depth",kind:"scalar",T:5},{no:4,name:"framerate",kind:"scalar",T:5},{no:5,name:"audio_codec",kind:"enum",T:Ve.getEnumType(Ye)},{no:6,name:"audio_bitrate",kind:"scalar",T:5},{no:7,name:"audio_frequency",kind:"scalar",T:5},{no:8,name:"video_codec",kind:"enum",T:Ve.getEnumType(Xe)},{no:9,name:"video_bitrate",kind:"scalar",T:5},{no:10,name:"key_frame_interval",kind:"scalar",T:1},{no:11,name:"audio_quality",kind:"scalar",T:5},{no:12,name:"video_quality",kind:"scalar",T:5}])),En=Ve.makeMessageType("livekit.StreamOutput",(()=>[{no:1,name:"protocol",kind:"enum",T:Ve.getEnumType(fn)},{no:2,name:"urls",kind:"scalar",T:9,repeated:!0}])),Cn=Ve.makeMessageType("livekit.SegmentedFileOutput",(()=>[{no:1,name:"protocol",kind:"enum",T:Ve.getEnumType(kn)},{no:2,name:"filename_prefix",kind:"scalar",T:9},{no:3,name:"playlist_name",kind:"scalar",T:9},{no:11,name:"live_playlist_name",kind:"scalar",T:9},{no:4,name:"segment_duration",kind:"scalar",T:13},{no:10,name:"filename_suffix",kind:"enum",T:Ve.getEnumType(yn)},{no:8,name:"disable_manifest",kind:"scalar",T:8},{no:5,name:"s3",kind:"message",T:Rn,oneof:"output"},{no:6,name:"gcp",kind:"message",T:Pn,oneof:"output"},{no:7,name:"azure",kind:"message",T:In,oneof:"output"},{no:9,name:"aliOSS",kind:"message",T:_n,oneof:"output"}])),wn=Ve.makeMessageType("livekit.ImageOutput",(()=>[{no:1,name:"capture_interval",kind:"scalar",T:13},{no:2,name:"width",kind:"scalar",T:5},{no:3,name:"height",kind:"scalar",T:5},{no:4,name:"filename_prefix",kind:"scalar",T:9},{no:5,name:"filename_suffix",kind:"enum",T:Ve.getEnumType(bn)},{no:6,name:"image_codec",kind:"enum",T:Ve.getEnumType(Ze)},{no:7,name:"disable_manifest",kind:"scalar",T:8},{no:8,name:"s3",kind:"message",T:Rn,oneof:"output"},{no:9,name:"gcp",kind:"message",T:Pn,oneof:"output"},{no:10,name:"azure",kind:"message",T:In,oneof:"output"},{no:11,name:"aliOSS",kind:"message",T:_n,oneof:"output"}])),Rn=Ve.makeMessageType("livekit.S3Upload",(()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:11,name:"session_token",kind:"scalar",T:9},{no:12,name:"assume_role_arn",kind:"scalar",T:9},{no:13,name:"assume_role_external_id",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9},{no:6,name:"force_path_style",kind:"scalar",T:8},{no:7,name:"metadata",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:8,name:"tagging",kind:"scalar",T:9},{no:9,name:"content_disposition",kind:"scalar",T:9},{no:10,name:"proxy",kind:"message",T:Mn}])),Pn=Ve.makeMessageType("livekit.GCPUpload",(()=>[{no:1,name:"credentials",kind:"scalar",T:9},{no:2,name:"bucket",kind:"scalar",T:9},{no:3,name:"proxy",kind:"message",T:Mn}])),In=Ve.makeMessageType("livekit.AzureBlobUpload",(()=>[{no:1,name:"account_name",kind:"scalar",T:9},{no:2,name:"account_key",kind:"scalar",T:9},{no:3,name:"container_name",kind:"scalar",T:9}])),_n=Ve.makeMessageType("livekit.AliOSSUpload",(()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9}])),Mn=Ve.makeMessageType("livekit.ProxyConfig",(()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"password",kind:"scalar",T:9}])),Dn=Ve.makeMessageType("livekit.AutoParticipantEgress",(()=>[{no:1,name:"preset",kind:"enum",T:Ve.getEnumType(gn),oneof:"options"},{no:2,name:"advanced",kind:"message",T:Sn,oneof:"options"},{no:3,name:"file_outputs",kind:"message",T:Ln,repeated:!0},{no:4,name:"segment_outputs",kind:"message",T:Cn,repeated:!0}])),On=Ve.makeMessageType("livekit.AutoTrackEgress",(()=>[{no:1,name:"filepath",kind:"scalar",T:9},{no:5,name:"disable_manifest",kind:"scalar",T:8},{no:2,name:"s3",kind:"message",T:Rn,oneof:"output"},{no:3,name:"gcp",kind:"message",T:Pn,oneof:"output"},{no:4,name:"azure",kind:"message",T:In,oneof:"output"},{no:6,name:"aliOSS",kind:"message",T:_n,oneof:"output"}])),An=Ve.makeMessageType("livekit.RoomCompositeEgressRequest",(()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"layout",kind:"scalar",T:9},{no:3,name:"audio_only",kind:"scalar",T:8},{no:15,name:"audio_mixing",kind:"enum",T:Ve.getEnumType(Tn)},{no:4,name:"video_only",kind:"scalar",T:8},{no:5,name:"custom_base_url",kind:"scalar",T:9},{no:6,name:"file",kind:"message",T:Ln,oneof:"output"},{no:7,name:"stream",kind:"message",T:En,oneof:"output"},{no:10,name:"segments",kind:"message",T:Cn,oneof:"output"},{no:8,name:"preset",kind:"enum",T:Ve.getEnumType(gn),oneof:"options"},{no:9,name:"advanced",kind:"message",T:Sn,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:Ln,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:En,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:Cn,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:wn,repeated:!0},{no:16,name:"webhooks",kind:"message",T:un,repeated:!0}])),Ln=Ve.makeMessageType("livekit.EncodedFileOutput",(()=>[{no:1,name:"file_type",kind:"enum",T:Ve.getEnumType(vn)},{no:2,name:"filepath",kind:"scalar",T:9},{no:6,name:"disable_manifest",kind:"scalar",T:8},{no:3,name:"s3",kind:"message",T:Rn,oneof:"output"},{no:4,name:"gcp",kind:"message",T:Pn,oneof:"output"},{no:5,name:"azure",kind:"message",T:In,oneof:"output"},{no:7,name:"aliOSS",kind:"message",T:_n,oneof:"output"}])),Nn=Ve.makeMessageType("livekit.RoomEgress",(()=>[{no:1,name:"room",kind:"message",T:An},{no:3,name:"participant",kind:"message",T:Dn},{no:2,name:"tracks",kind:"message",T:On}])),xn=Ve.makeMessageType("livekit.RoomConfiguration",(()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"empty_timeout",kind:"scalar",T:13},{no:3,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:11,name:"metadata",kind:"scalar",T:9},{no:5,name:"egress",kind:"message",T:Nn},{no:7,name:"min_playout_delay",kind:"scalar",T:13},{no:8,name:"max_playout_delay",kind:"scalar",T:13},{no:9,name:"sync_streams",kind:"scalar",T:8},{no:10,name:"agents",kind:"message",T:mn,repeated:!0},{no:12,name:"tags",kind:"map",K:9,V:{kind:"scalar",T:9}}])),Un=Ve.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Fn=Ve.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Bn=Ve.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),jn=Ve.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:ni,oneof:"message"},{no:2,name:"answer",kind:"message",T:ni,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Yn,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Wn,oneof:"message"},{no:5,name:"mute",kind:"message",T:Xn,oneof:"message"},{no:6,name:"subscription",kind:"message",T:ri,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:ui,oneof:"message"},{no:8,name:"leave",kind:"message",T:mi,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:vi,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Mi,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Ai,oneof:"message"},{no:13,name:"simulate",kind:"message",T:xi,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:fi,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Ui,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:hi,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:pi,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:Hn,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:zn,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:ai,oneof:"message"},{no:22,name:"store_data_blob_request",kind:"message",T:oi,oneof:"message"},{no:23,name:"get_data_blob_request",kind:"message",T:di,oneof:"message"}])),qn=Ve.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:Zn,oneof:"message"},{no:2,name:"answer",kind:"message",T:ni,oneof:"message"},{no:3,name:"offer",kind:"message",T:ni,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Yn,oneof:"message"},{no:5,name:"update",kind:"message",T:ii,oneof:"message"},{no:6,name:"track_published",kind:"message",T:ei,oneof:"message"},{no:8,name:"leave",kind:"message",T:mi,oneof:"message"},{no:9,name:"mute",kind:"message",T:Xn,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:yi,oneof:"message"},{no:11,name:"room_update",kind:"message",T:bi,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Si,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Ci,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Pi,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Di,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:ti,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:$n,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Fi,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:qi,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Vi,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Hi,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:Oi,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:Qi,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:Ii,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:Kn,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:Gn,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:Jn,oneof:"message"},{no:30,name:"store_data_blob_response",kind:"message",T:ci,oneof:"message"},{no:31,name:"get_data_blob_response",kind:"message",T:li,oneof:"message"}])),Vn=Ve.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:_t,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:Ve.getEnumType(Mt)}])),Wn=Ve.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:Ve.getEnumType(et)},{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:Ve.getEnumType(tt)},{no:9,name:"layers",kind:"message",T:_t,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Vn,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:Ve.getEnumType(ft)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:Ve.getEnumType($e)},{no:17,name:"audio_features",kind:"enum",T:Ve.getEnumType(ct),repeated:!0},{no:18,name:"packet_trailer_features",kind:"enum",T:Ve.getEnumType(dt),repeated:!0}])),Hn=Ve.makeMessageType("livekit.PublishDataTrackRequest",(()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"encryption",kind:"enum",T:Ve.getEnumType(ft)},{no:4,name:"frame_encoding",kind:"message",T:Tt,opt:!0},{no:5,name:"schema",kind:"message",T:wt,opt:!0}])),Kn=Ve.makeMessageType("livekit.PublishDataTrackResponse",(()=>[{no:1,name:"info",kind:"message",T:bt}])),zn=Ve.makeMessageType("livekit.UnpublishDataTrackRequest",(()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}])),Gn=Ve.makeMessageType("livekit.UnpublishDataTrackResponse",(()=>[{no:1,name:"info",kind:"message",T:bt}])),Jn=Ve.makeMessageType("livekit.DataTrackSubscriberHandles",(()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:Qn}}])),Qn=Ve.makeMessageType("livekit.DataTrackSubscriberHandles.PublishedDataTrack",(()=>[{no:1,name:"publisher_identity",kind:"scalar",T:9},{no:2,name:"publisher_sid",kind:"scalar",T:9},{no:3,name:"track_sid",kind:"scalar",T:9}]),{localName:"DataTrackSubscriberHandles_PublishedDataTrack"}),Yn=Ve.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:Ve.getEnumType(Un)},{no:3,name:"final",kind:"scalar",T:8}])),Xn=Ve.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),Zn=Ve.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:lt},{no:2,name:"participant",kind:"message",T:pt},{no:3,name:"other_participants",kind:"message",T:pt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:ki,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:Zt},{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:Gt},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:ut,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),$n=Ve.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:ki,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Zt},{no:3,name:"server_info",kind:"message",T:Gt},{no:4,name:"last_message_seq",kind:"scalar",T:13}])),ei=Ve.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:yt}])),ti=Ve.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),ni=Ve.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}}])),ii=Ve.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:pt,repeated:!0}])),ri=Ve.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:zt,repeated:!0}])),ai=Ve.makeMessageType("livekit.UpdateDataSubscription",(()=>[{no:1,name:"updates",kind:"message",T:si,repeated:!0}])),si=Ve.makeMessageType("livekit.UpdateDataSubscription.Update",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"options",kind:"message",T:Rt}]),{localName:"UpdateDataSubscription_Update"}),oi=Ve.makeMessageType("livekit.StoreDataBlobRequest",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"blob",kind:"message",T:It}])),ci=Ve.makeMessageType("livekit.StoreDataBlobResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"key",kind:"message",T:Pt}])),di=Ve.makeMessageType("livekit.GetDataBlobRequest",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:9},{no:3,name:"key",kind:"message",T:Pt}])),li=Ve.makeMessageType("livekit.GetDataBlobResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"blob",kind:"message",T:It}])),ui=Ve.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:Ve.getEnumType(nt)},{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}])),hi=Ve.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:Ve.getEnumType(ct),repeated:!0}])),pi=Ve.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}])),mi=Ve.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:Ve.getEnumType(at)},{no:3,name:"action",kind:"enum",T:Ve.getEnumType(gi)},{no:4,name:"regions",kind:"message",T:Bi}])),gi=Ve.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),vi=Ve.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:_t,repeated:!0}])),fi=Ve.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}])),ki=Ve.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}])),yi=Ve.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:xt,repeated:!0}])),bi=Ve.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:lt}])),Ti=Ve.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:Ve.getEnumType(it)},{no:3,name:"score",kind:"scalar",T:2}])),Si=Ve.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:Ti,repeated:!0}])),Ei=Ve.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:Ve.getEnumType(Fn)}])),Ci=Ve.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:Ei,repeated:!0}])),wi=Ve.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:Ve.getEnumType(nt)},{no:2,name:"enabled",kind:"scalar",T:8}])),Ri=Ve.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:wi,repeated:!0}])),Pi=Ve.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:wi,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Ri,repeated:!0}])),Ii=Ve.makeMessageType("livekit.SubscribedAudioCodecUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:hn,repeated:!0}])),_i=Ve.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}])),Mi=Ve.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:_i,repeated:!0}])),Di=Ve.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}])),Oi=Ve.makeMessageType("livekit.RoomMovedResponse",(()=>[{no:1,name:"room",kind:"message",T:lt},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:pt},{no:4,name:"other_participants",kind:"message",T:pt,repeated:!0}])),Ai=Ve.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:ni},{no:2,name:"subscription",kind:"message",T:ri},{no:3,name:"publish_tracks",kind:"message",T:ei,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Ni,repeated:!0},{no:5,name:"offer",kind:"message",T:ni},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:Li,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:Kn,repeated:!0}])),Li=Ve.makeMessageType("livekit.DataChannelReceiveState",(()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}])),Ni=Ve.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:Ve.getEnumType(Un)}])),xi=Ve.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:Ve.getEnumType(Bn),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"}])),Ui=Ve.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),Fi=Ve.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),Bi=Ve.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:ji,repeated:!0}])),ji=Ve.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}])),qi=Ve.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:Ve.getEnumType(ot)}])),Vi=Ve.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:Ve.getEnumType(Wi)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:Yn,oneof:"request"},{no:5,name:"add_track",kind:"message",T:Wn,oneof:"request"},{no:6,name:"mute",kind:"message",T:Xn,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:fi,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:hi,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:pi,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:Hn,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:zn,oneof:"request"}])),Wi=Ve.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"},{no:7,name:"INVALID_HANDLE"},{no:8,name:"INVALID_NAME"},{no:9,name:"DUPLICATE_HANDLE"},{no:10,name:"DUPLICATE_NAME"},{no:11,name:"INVALID_REQUEST"}]),Hi=Ve.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),Ki=Ve.makeMessageType("livekit.ConnectionSettings",(()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8},{no:5,name:"auto_subscribe_data_track",kind:"scalar",T:8,opt:!0}])),zi=Ve.makeMessageType("livekit.JoinRequest",(()=>[{no:1,name:"client_info",kind:"message",T:Qt},{no:2,name:"connection_settings",kind:"message",T:Ki},{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:Wn,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:ni},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:Ve.getEnumType(st)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Ai}])),Gi=Ve.makeMessageType("livekit.WrappedJoinRequest",(()=>[{no:1,name:"compression",kind:"enum",T:Ve.getEnumType(Ji)},{no:2,name:"join_request",kind:"scalar",T:12}])),Ji=Ve.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),Qi=Ve.makeMessageType("livekit.MediaSectionsRequirement",(()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}])),Yi=Ve.makeMessageType("livekit.TokenSourceRequest",(()=>[{no:1,name:"room_name",kind:"scalar",T:9,opt:!0},{no:2,name:"participant_name",kind:"scalar",T:9,opt:!0},{no:3,name:"participant_identity",kind:"scalar",T:9,opt:!0},{no:4,name:"participant_metadata",kind:"scalar",T:9,opt:!0},{no:5,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:6,name:"room_config",kind:"message",T:xn,opt:!0}])),Xi=Ve.makeMessageType("livekit.TokenSourceResponse",(()=>[{no:1,name:"server_url",kind:"scalar",T:9},{no:2,name:"participant_token",kind:"scalar",T:9}]));function Zi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var $i,er={exports:{}},tr=er.exports;var nr,ir,rr=($i||($i=1,function(e){var t,i;t=tr,i=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],a={},s=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 c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function d(){for(var n=this.getLevel(),i=0;i<r.length;i++){var a=r[i];this[a]=i<n?e:this.methodFactory(a,n,this.name)}if(this.log=this.debug,typeof console===t&&n<this.levels.SILENT)return"No console available for logging"}function l(e){return function(){typeof console!==t&&(d.call(this),this[e].apply(this,arguments))}}function u(n,r,a){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?c:void 0!==console[n]?o(console,n):void 0!==console.log?o(console,"log"):e)}(n)||l.apply(this,arguments)}function h(e,n){var i,o,c,l=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(a){}if(typeof e===t)try{var n=window.document.cookie,i=encodeURIComponent(h),r=n.indexOf(i+"=");-1!==r&&(e=/^([^;]+)/.exec(n.slice(r+i.length+1))[1])}catch(a){}return void 0===l.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==l.levels[t.toUpperCase()]&&(t=l.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=l.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),l.name=e,l.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},l.methodFactory=n||u,l.getLevel=function(){return null!=c?c:null!=o?o:i},l.setLevel=function(e,n){return c=m(e),!1!==n&&function(e){var n=(r[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=n)}catch(i){}try{window.document.cookie=encodeURIComponent(h)+"="+n+";"}catch(i){}}}(c),d.call(l)},l.setDefaultLevel=function(e){o=m(e),p()||l.setLevel(e,!1)},l.resetLevel=function(){c=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){}}}(),d.call(l)},l.enableAll=function(e){l.setLevel(l.levels.TRACE,e)},l.disableAll=function(e){l.setLevel(l.levels.SILENT,e)},l.rebuild=function(){if(s!==l&&(i=m(s.getLevel())),d.call(l),s===l)for(var e in a)a[e].rebuild()},i=m(s?s.getLevel():"WARN");var g=p();null!=g&&(c=m(g)),d.call(l)}(s=new h).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=a[e];return t||(t=a[e]=new h(e,s.methodFactory)),t};var p=typeof window!==t?window.log:void 0;return s.noConflict=function(){return typeof window!==t&&window.log===s&&(window.log=p),s},s.getLoggers=function(){return a},s.default=s,s},e.exports?e.exports=i():t.log=i()}(er)),er.exports);e.LogLevel=void 0,(nr=e.LogLevel||(e.LogLevel={}))[nr.trace=0]="trace",nr[nr.debug=1]="debug",nr[nr.info=2]="info",nr[nr.warn=3]="warn",nr[nr.error=4]="error",nr[nr.silent=5]="silent",e.LoggerNames=void 0,(ir=e.LoggerNames||(e.LoggerNames={})).Default="livekit",ir.Room="livekit-room",ir.TokenSource="livekit-token-source",ir.Participant="livekit-participant",ir.Track="livekit-track",ir.Publication="livekit-track-publication",ir.Engine="livekit-engine",ir.Signal="livekit-signal",ir.PCManager="livekit-pc-manager",ir.PCTransport="livekit-pc-transport",ir.E2EE="lk-e2ee",ir.DataTracks="livekit-data-tracks",ir.Region="livekit-region",ir.ICE="livekit-ice",ir.Stats="livekit-stats";let ar=rr.getLogger(e.LoggerNames.Default);const sr=Object.values(e.LoggerNames).map((e=>rr.getLogger(e)));function or(e,t){const n=rr.getLogger(e);return n.setDefaultLevel(ar.getLevel()),t?function(e,t){const n=n=>(i,r)=>{const a=t(),s=a||r?Object.assign(Object.assign({},a),r):void 0;e[n](i,s)},i=Object.create(e);return i.trace=n("trace"),i.debug=n("debug"),i.info=n("info"),i.warn=n("warn"),i.error=n("error"),i}(n,t):n}ar.setDefaultLevel(e.LogLevel.info);const cr=rr.getLogger(e.LoggerNames.E2EE),dr=7e3,lr=[0,300,1200,2700,4800,dr,dr,dr,dr,dr];class ur{constructor(e){this._retryDelays=void 0!==e?[...e]:lr}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()}}function hr(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}function pr(e,t,i,r){return new(i||(i=Promise))((function(a,s){function o(e){try{d(r.next(e))}catch(n){s(n)}}function c(e){try{d(r.throw(e))}catch(n){s(n)}}function d(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,c)}d((r=r.apply(e,t||[])).next())}))}function mr(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function gr(e){return this instanceof gr?(this.v=e,this):new gr(e)}function vr(e,t,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,a=i.apply(e,t||[]),s=[];return r=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",(function(e){return function(t){return Promise.resolve(t).then(e,l)}})),r[Symbol.asyncIterator]=function(){return this},r;function o(e,t){a[e]&&(r[e]=function(t){return new Promise((function(n,i){s.push([e,t,n,i])>1||c(e,t)}))},t&&(r[e]=t(r[e])))}function c(e,t){try{(i=a[e](t)).value instanceof gr?Promise.resolve(i.value.v).then(d,l):u(s[0][2],i)}catch(n){u(s[0][3],n)}var i}function d(e){c("next",e)}function l(e){c("throw",e)}function u(e,t){e(t),s.shift(),s.length&&c(s[0][0],s[0][1])}}function fr(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=mr(e),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(n){t[n]=e[n]&&function(t){return new Promise((function(i,r){(function(e,t,n,i){Promise.resolve(i).then((function(t){e({value:t,done:n})}),t)})(i,r,(t=e[n](t)).done,t.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var kr,yr={exports:{}};var br=function(){if(kr)return yr.exports;kr=1;var e,t="object"==typeof Reflect?Reflect:null,n=t&&"function"==typeof t.apply?t.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};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 i=Number.isNaN||function(e){return e!=e};function r(){r.init.call(this)}yr.exports=r,yr.exports.once=function(e,t){return new Promise((function(n,i){function r(n){e.removeListener(t,a),i(n)}function a(){"function"==typeof e.removeListener&&e.removeListener("error",r),n([].slice.call(arguments))}m(e,t,a,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&m(e,"error",t,n)}(e,r,{once:!0})}))},r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var a=10;function s(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function o(e){return void 0===e._maxListeners?r.defaultMaxListeners:e._maxListeners}function c(e,t,n,i){var r,a,c,d;if(s(n),void 0===(a=e._events)?(a=e._events=Object.create(null),e._eventsCount=0):(void 0!==a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),c=a[t]),void 0===c)c=a[t]=n,++e._eventsCount;else if("function"==typeof c?c=a[t]=i?[n,c]:[c,n]:i?c.unshift(n):c.push(n),(r=o(e))>0&&c.length>r&&!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,n){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},r=d.bind(i);return r.listener=n,i.wrapFn=r,r}function u(e,t,n){var i=e._events;if(void 0===i)return[];var r=i[t];return void 0===r?[]:"function"==typeof r?n?[r.listener||r]:[r]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(r):p(r,r.length)}function h(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function p(e,t){for(var n=new Array(t),i=0;i<t;++i)n[i]=e[i];return n}function m(e,t,n,i){if("function"==typeof e.on)i.once?e.once(t,n):e.on(t,n);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 r(a){i.once&&e.removeEventListener(t,r),n(a)}))}}return Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),r.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},r.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||i(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},r.prototype.getMaxListeners=function(){return o(this)},r.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var r="error"===e,a=this._events;if(void 0!==a)r=r&&void 0===a.error;else if(!r)return!1;if(r){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var c=a[e];if(void 0===c)return!1;if("function"==typeof c)n(c,this,t);else{var d=c.length,l=p(c,d);for(i=0;i<d;++i)n(l[i],this,t)}return!0},r.prototype.addListener=function(e,t){return c(this,e,t,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(e,t){return c(this,e,t,!0)},r.prototype.once=function(e,t){return s(t),this.on(e,l(this,e,t)),this},r.prototype.prependOnceListener=function(e,t){return s(t),this.prependListener(e,l(this,e,t)),this},r.prototype.removeListener=function(e,t){var n,i,r,a,o;if(s(t),void 0===(i=this._events))return this;if(void 0===(n=i[e]))return this;if(n===t||n.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(r=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,r=a;break}if(r<0)return this;0===r?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,r),1===n.length&&(i[e]=n[0]),void 0!==i.removeListener&&this.emit("removeListener",e,o||t)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(e){var t,n,i;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var r,a=Object.keys(n);for(i=0;i<a.length;++i)"removeListener"!==(r=a[i])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},r.prototype.listeners=function(e){return u(this,e,!0)},r.prototype.rawListeners=function(e){return u(this,e,!1)},r.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},r.prototype.listenerCount=h,r.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},yr.exports}();let Tr=!0,Sr=!0;function Er(e,t,n){const i=e.match(t);return i&&i.length>=n&&parseFloat(i[n],10)}function Cr(e,t,n){if(!e.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,"addEventListener").writable)return void Pr("Unable to polyfill events");const i=e.RTCPeerConnection.prototype,r=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return r.apply(this,arguments);const a=e=>{const t=n(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,a),r.apply(this,[e,a])};const a=i.removeEventListener;i.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t])return a.apply(this,arguments);if(!this._eventMap[t].has(n))return a.apply(this,arguments);const i=this._eventMap[t].get(n);return this._eventMap[t].delete(n),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,a.apply(this,[e,i])},Object.defineProperty(i,"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 wr(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Tr=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Rr(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Sr=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Pr(){if("object"==typeof window){if(Tr)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Ir(e,t){Sr&&console.warn(e+" is deprecated, please use "+t+" instead.")}function _r(e){return"[object Object]"===Object.prototype.toString.call(e)}function Mr(e){return _r(e)?Object.keys(e).reduce((function(t,n){const i=_r(e[n]),r=i?Mr(e[n]):e[n],a=i&&!Object.keys(r).length;return void 0===r||a?t:Object.assign(t,{[n]:r})}),{}):e}function Dr(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?Dr(e,e.get(t[i]),n):i.endsWith("Ids")&&t[i].forEach((t=>{Dr(e,e.get(t),n)}))})))}function Or(e,t,n){const i=n?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const a=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&a.push(e)})),a.forEach((t=>{e.forEach((n=>{n.type===i&&n.trackId===t.id&&Dr(e,n,r)}))})),r}const Ar=Pr;function Lr(e,t){if(t.version>=64)return;const n=e&&e.navigator;if(!n.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((n=>{if("require"===n||"advanced"===n||"mediaSource"===n)return;const i="object"==typeof e[n]?e[n]:{ideal:e[n]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[r("min",n)]=i.ideal,t.optional.push(e),e={},e[r("max",n)]=i.ideal,t.optional.push(e)):(e[r("",n)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",n)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,n)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let a=e.video.facingMode;a=a&&("object"==typeof a?a:{ideal:a});const s=t.version<66;if(a&&("user"===a.exact||"environment"===a.exact||"user"===a.ideal||"environment"===a.ideal)&&(!n.mediaDevices.getSupportedConstraints||!n.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===a.exact||"environment"===a.ideal?t=["back","rear"]:"user"!==a.exact&&"user"!==a.ideal||(t=["front"]),t)return n.mediaDevices.enumerateDevices().then((n=>{let s=(n=n.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!s&&n.length&&t.includes("back")&&(s=n[n.length-1]),s&&(e.video.deviceId=a.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=i(e.video),Ar("chrome: "+JSON.stringify(e)),r(e)}))}e.video=i(e.video)}return Ar("chrome: "+JSON.stringify(e)),r(e)},a=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(n.getUserMedia=function(e,t,i){r(e,(e=>{n.webkitGetUserMedia(e,t,(e=>{i&&i(a(e))}))}))}.bind(n),n.mediaDevices.getUserMedia){const e=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(t){return r(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(a(e))))))}}}function Nr(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function xr(e,t){if(!(t.version>102))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",(n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===n.track.id)):{track:n.track};const r=new Event("track");r.track=n.track,r.receiver=i,r.transceiver={receiver:i},r.streams=[t.stream],this.dispatchEvent(r)})),t.stream.getTracks().forEach((n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===n.id)):{track:n};const r=new Event("track");r.track=n,r.receiver=i,r.transceiver={receiver:i},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else Cr(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function Ur(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 n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let r=n.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.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 Fr(e,t){if(t.version>=67)return;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 n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Or(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}),Cr(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Or(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,n,i;return this.getSenders().forEach((n=>{n.track===e&&(t?i=!0:t=n)})),this.getReceivers().forEach((t=>(t.track===e&&(n?i=!0:n=t),t.track===e))),i||t&&n?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():n?n.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return n.apply(this,arguments)}}function Br(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,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?-1===this._shimmedLocalStreams[n.id].indexOf(i)&&this._shimmedLocalStreams[n.id].push(i):this._shimmedLocalStreams[n.id]=[n,i],i};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();n.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const n=this._shimmedLocalStreams[t].indexOf(e);-1!==n&&this._shimmedLocalStreams[t].splice(n,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),r.apply(this,arguments)}}function jr(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Br(e);const n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=n.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=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 n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}i.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function a(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],r=e._streams[i.id];n=n.replace(new RegExp(r.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:n})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,n){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[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 r=this._streams[n.id];if(r)r.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[n.id]=i,this._reverseStreams[i.id]=n,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?n.apply(this,[t=>{const n=a(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then((e=>a(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],r=e._streams[i.id];n=n.replace(new RegExp(i.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:n})}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments)};const o=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=o.get.apply(this);return""===e.type?e:a(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((n=>{this._streams[n].getTracks().find((t=>e.track===t))&&(t=this._streams[n])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function qr(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function Vr(e,t){t.version>102||Cr(e,"negotiationneeded",(e=>{const n=e.target;if(!(t.version<72||n.getConfiguration&&"plan-b"===n.getConfiguration().sdpSemantics)||"stable"===n.signalingState)return e}))}var Wr=Object.freeze({__proto__:null,fixNegotiationNeeded:Vr,shimAddTrackRemoveTrack:jr,shimAddTrackRemoveTrackWithNative:Br,shimGetSendersWithDtmf:Ur,shimGetUserMedia:Lr,shimMediaStream:Nr,shimOnTrack:xr,shimPeerConnection:qr,shimSenderReceiverGetStats:Fr});function Hr(e,t){const n=e&&e.navigator;if(!n.mediaDevices)return;const i=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,i){Ir("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),n.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in n.mediaDevices.getSupportedConstraints())){const e=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},t=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(n){return"object"==typeof n&&"object"==typeof n.audio&&(n=JSON.parse(JSON.stringify(n)),e(n.audio,"autoGainControl","mozAutoGainControl"),e(n.audio,"noiseSuppression","mozNoiseSuppression")),t(n)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const n=t.apply(this,arguments);return e(n,"mozAutoGainControl","autoGainControl"),e(n,"mozNoiseSuppression","noiseSuppression"),n}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(n){return"audio"===this.kind&&"object"==typeof n&&(n=JSON.parse(JSON.stringify(n)),e(n,"autoGainControl","mozAutoGainControl"),e(n,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[n])}}}}function Kr(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 zr(e,t){"object"==typeof e&&(e.RTCPeerConnection||e.mozRTCPeerConnection)&&(!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]})))}function Gr(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;if(t.version>=151)return;const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const e=Array.prototype.slice.call(arguments),a=e[0],s=e[1],o=e[2];return"closed"===this.signalingState?Promise.resolve(new Map):r.apply(this,[a||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,o)}}function Jr(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 n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Qr(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}),Cr(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Yr(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Ir("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Xr(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Zr(e,t){if("object"!=typeof e||!e.RTCPeerConnection)return;if(t.version>=110)return;const n=e.RTCPeerConnection.prototype.addTransceiver;n&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const t=e.length>0;t&&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 i=n.apply(this,arguments);if(t){const t=i.sender,n=t.getParameters();(!("encodings"in n)||1===n.encodings.length&&0===Object.keys(n.encodings[0]).length)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function $r(e,t){if("object"!=typeof e||!e.RTCRtpSender)return;if(t.version>=110)return;const n=e.RTCRtpSender.prototype.getParameters;n&&(e.RTCRtpSender.prototype.getParameters=function(){const e=n.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function ea(e,t){if("object"!=typeof e||!e.RTCPeerConnection)return;if(t.version>=110)return;const n=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>n.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):n.apply(this,arguments)}}function ta(e,t){if("object"!=typeof e||!e.RTCPeerConnection)return;if(t.version>=110)return;const n=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>n.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):n.apply(this,arguments)}}var na=Object.freeze({__proto__:null,shimAddTransceiver:Zr,shimCreateAnswer:ta,shimCreateOffer:ea,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&(e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!n||!n.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===n.video?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)}))},shimGetParameters:$r,shimGetStats:Gr,shimGetUserMedia:Hr,shimOnTrack:Kr,shimPeerConnection:zr,shimRTCDataChannel:Xr,shimReceiverGetStats:Qr,shimRemoveStream:Yr,shimSenderGetStats:Jr});function ia(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((n=>t.call(this,n,e))),e.getVideoTracks().forEach((n=>t.call(this,n,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return i&&i.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 n=e.getTracks();this.getSenders().forEach((e=>{n.includes(e.track)&&this.removeTrack(e)}))})}}function ra(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 n=new Event("addstream");n.stream=t,e.dispatchEvent(n)}))}),t.apply(e,arguments)}}}function aa(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,n=t.createOffer,i=t.createAnswer,r=t.setLocalDescription,a=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r};let o=function(e,t,n){const i=r.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i};t.setLocalDescription=o,o=function(e,t,n){const i=a.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i},t.setRemoteDescription=o,o=function(e,t,n){const i=s.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i},t.addIceCandidate=o}function sa(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,n=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>n(oa(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,i){t.mediaDevices.getUserMedia(e).then(n,i)}.bind(t))}function oa(e){return e&&void 0!==e.video?Object.assign({},e,{video:Mr(e.video)}):e}function ca(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){const t=[];for(let n=0;n<e.iceServers.length;n++){let i=e.iceServers[n];void 0===i.urls&&i.url?(Ir("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[n])}e.iceServers=t}return new t(e,n)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function da(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 la(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 n=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&n?"sendrecv"===n.direction?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":"recvonly"===n.direction&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):!0!==e.offerToReceiveVideo||n||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function ua(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var ha,pa=Object.freeze({__proto__:null,shimAudioContext:ua,shimCallbacksAPI:aa,shimConstraints:oa,shimCreateOfferLegacy:la,shimGetUserMedia:sa,shimLocalStreamsAPI:ia,shimRTCIceServerUrls:ca,shimRemoteStreamsAPI:ra,shimTrackEventTransceiver:da}),ma={exports:{}};var ga=(ha||(ha=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 n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){const n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter((e=>0===e.indexOf(n)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const n={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let i=8;i<t.length;i+=2)switch(t[i]){case"raddr":n.relatedAddress=t[i+1];break;case"rport":n.relatedPort=parseInt(t[i+1],10);break;case"tcptype":n.tcpType=t[i+1];break;case"ufrag":n.ufrag=t[i+1],n.usernameFragment=t[i+1];break;default:void 0===n[t[i]]&&(n[t[i]]=t[i+1])}return n},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const n=e.component;"rtp"===n?t.push(1):"rtcp"===n?t.push(2):t.push(n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const i=e.type;return t.push("typ"),t.push(i),"host"!==i&&e.relatedAddress&&void 0!==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 n={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),n.name=t[0],n.clockRate=parseInt(t[1],10),n.channels=3===t.length?parseInt(t[2],10):1,n.numChannels=n.channels,n},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const n=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==n?"/"+n:"")+"\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 n;const i=e.substring(e.indexOf(" ")+1).split(";");for(let r=0;r<i.length;r++)n=i[r].trim().split("="),t[n[0].trim()]=n[1];return t},t.writeFmtp=function(e){let t="",n=e.payloadType;if(void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const i=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+n+" "+i.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="",n=e.payloadType;return void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+n+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),n={ssrc:parseInt(e.substring(7,t),10)},i=e.indexOf(":",t);return i>-1?(n.attribute=e.substring(t+1,i),n.value=e.substring(i+1)):n.attribute=e.substring(t+1),n},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 n=t.matchPrefix(e,"a=mid:")[0];if(n)return n.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,n){return{role:"auto",fingerprints:t.matchPrefix(e+n,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let n="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{n+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),n},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,n){return t.matchPrefix(e+n,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,n){const i=t.matchPrefix(e+n,"a=ice-ufrag:")[0],r=t.matchPrefix(e+n,"a=ice-pwd:")[0];return i&&r?{usernameFragment:i.substring(12),password:r.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 n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" ");n.profile=i[2];for(let a=3;a<i.length;a++){const r=i[a],s=t.matchPrefix(e,"a=rtpmap:"+r+" ")[0];if(s){const i=t.parseRtpMap(s),a=t.matchPrefix(e,"a=fmtp:"+r+" ");switch(i.parameters=a.length?t.parseFmtp(a[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+r+" ").map(t.parseRtcpFb),n.codecs.push(i),i.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(i.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{n.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return n.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),n},t.writeRtpDescription=function(e,n){let i="";i+="m="+e+" ",i+=n.codecs.length>0?"9":"0",i+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=n.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",n.codecs.forEach((e=>{i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));let r=0;return n.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(i+="a=maxptime:"+r+"\r\n"),n.headerExtensions&&n.headerExtensions.forEach((e=>{i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){const n=[],i=t.parseRtpParameters(e),r=-1!==i.fecMechanisms.indexOf("RED"),a=-1!==i.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),o=s.length>0&&s[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]===o&&(c=d[0][1]),i.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:o,codecPayloadType:parseInt(e.parameters.apt,10)};o&&c&&(t.rtx={ssrc:c}),n.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:o,mechanism:a?"red+ulpfec":"red"},n.push(t))}})),0===n.length&&o&&n.push({ssrc:o});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,n.forEach((e=>{e.maxBitrate=l}))),n},t.parseRtcpParameters=function(e){const n={},i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];i&&(n.cname=i.value,n.ssrc=i.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");n.reducedSize=r.length>0,n.compound=0===r.length;const a=t.matchPrefix(e,"a=rtcp-mux");return n.mux=a.length>0,n},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 n;const i=t.matchPrefix(e,"a=msid:");if(1===i.length)return n=i[0].substring(7).split(" "),{stream:n[0],track:n[1]};const r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(n=r[0].value.split(" "),{stream:n[0],track:n[1]}):void 0},t.parseSctpDescription=function(e){const n=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");let r;i.length>0&&(r=parseInt(i[0].substring(19),10)),isNaN(r)&&(r=65536);const a=t.matchPrefix(e,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:n.fmt,maxMessageSize:r};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){let n=[];return n="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&&n.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),n.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,n,i){let r;const a=void 0!==n?n:2;return r=e||t.generateSessionId(),"v=0\r\no="+(i||"thisisadapterortc")+" "+r+" "+a+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,n){const i=t.splitLines(e);for(let t=0;t<i.length;t++)switch(i[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[t].substring(2)}return n?t.getDirection(n):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const n=t.splitLines(e)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}},t.parseOLine=function(e){const n=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const n=t.splitLines(e);for(let t=0;t<n.length;t++)if(n[t].length<2||"="!==n[t].charAt(1))return!1;return!0},e.exports=t}(ma)),ma.exports),va=Zi(ga),fa=t({__proto__:null,default:va},[ga]);function ka(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 n=new t(e),i=va.parseCandidate(e.candidate);for(const e in i)e in n||Object.defineProperty(n,e,{value:i[e]});return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,Cr(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function ya(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||Cr(e,"icecandidate",(e=>{if(e.candidate){const t=va.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function ba(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>102)return;if("firefox"===t.browser&&t.version>=113)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){"plan-b"===this.getConfiguration().sdpSemantics&&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=va.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=va.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 n=parseInt(t[1],10);return n!=n?-1:n}(arguments[0]),n=function(e){let n=65536;return"firefox"===t.browser&&(n=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),n}(e),i=function(e,n){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const r=va.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?i=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==n&&(i=2147483637),i}(arguments[0],e);let r;r=0===n&&0===i?Number.POSITIVE_INFINITY:0===n||0===i?Math.max(n,i):Math.min(n,i);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>r}),this._sctp=a}return n.apply(this,arguments)}}function Ta(e,t){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;if("chrome"===t.browser&&t.version>=149)return;if("firefox"===t.browser&&t.version>60)return;function n(e,t){const n=e.send;e.send=function(){const i=arguments[0],r=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return n.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return n(e,this),e},Cr(e,"datachannel",(e=>(n(e.channel,e.target),e)))}function Sa(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 n=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 n=new Event("connectionstatechange",e);t.dispatchEvent(n)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}}))}function Ea(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t._safariVersion>=13.1)return;const n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const n=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:n}):t.sdp=n}return n.apply(this,arguments)}}function Ca(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.addIceCandidate;n&&0!==n.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():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function wa(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.setLocalDescription;n&&0!==n.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return n.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return n.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>n.apply(this,[e])))})}var Ra,Pa,Ia=Object.freeze({__proto__:null,removeExtmapAllowMixed:Ea,shimAddIceCandidateNullOrEmpty:Ca,shimConnectionState:Sa,shimMaxMessageSize:ba,shimParameterlessSetLocalDescription:wa,shimRTCIceCandidate:ka,shimRTCIceCandidateRelayProtocol:ya,shimSendThrowTypeError:Ta});!function(){let e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).window,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=Pr,i=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 n=e.navigator;if(n.userAgentData&&n.userAgentData.brands){const e=n.userAgentData.brands.find((e=>"Chromium"===e.brand));if(e){const t=parseInt(e.version,10);if(t>=90)return{browser:"chrome",version:t}}}if(n.mozGetUserMedia)t.browser="firefox",t.version=parseInt(Er(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(Er(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else{if(!e.RTCPeerConnection||!n.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt(Er(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=Er(n.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),r={browserDetails:i,commonShim:Ia,extractVersion:Er,disableLog:wr,disableWarnings:Rr,sdp:fa};switch(i.browser){case"chrome":if(!Wr||!qr||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),r;if(null===i.version)return n("Chrome shim can not determine version, not shimming."),r;n("adapter.js shimming chrome."),r.browserShim=Wr,Ca(e,i),wa(e),Lr(e,i),Nr(e),qr(e,i),xr(e,i),jr(e,i),Ur(e),Fr(e,i),Vr(e,i),ka(e),ya(e),Sa(e),ba(e,i),Ta(e,i),Ea(e,i);break;case"firefox":if(!na||!zr||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=na,Ca(e,i),wa(e),Hr(e,i),zr(e,i),Gr(e,i),Kr(e),Yr(e),Jr(e),Qr(e),Xr(e),Zr(e,i),$r(e,i),ea(e,i),ta(e,i),ka(e),Sa(e),ba(e,i),Ta(e,i);break;case"safari":if(!pa||!t.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=pa,Ca(e,i),wa(e),ca(e),la(e),aa(e),ia(e),ra(e),da(e),sa(e),ua(e),ka(e),ya(e),ba(e,i),Ta(e,i),Ea(e,i);break;default:n("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});class _a extends(Pa=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}Ra=_a,_a.resolve=e=>Reflect.get(Pa,"resolve",Ra).call(Ra,e);const Ma=/version\/(\d+(\.?_?\d+)+)/i;let Da;function Oa(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;const n=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===Da||t){const e=Aa.find((e=>e.test.test(n)));Da=null==e?void 0:e.describe(n)}return Da}const Aa=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:La(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Na(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:La(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Na(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:La(Ma,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:Na(e)})}];function La(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const i=t.match(e);return i&&i.length>=n&&i[n]||""}function Na(e){return e.includes("mac os")?La(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}const xa="2.22.2";class Ua extends Error{constructor(e,t,n){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,void 0!==(null==n?void 0:n.cause)&&(this.cause=null==n?void 0:n.cause)}}class Fa extends Ua{}var Ba,ja,qa,Va,Wa,Ha,Ka;e.ConnectionErrorReason=void 0,(Ba=e.ConnectionErrorReason||(e.ConnectionErrorReason={}))[Ba.NotAllowed=0]="NotAllowed",Ba[Ba.ServerUnreachable=1]="ServerUnreachable",Ba[Ba.InternalError=2]="InternalError",Ba[Ba.Cancelled=3]="Cancelled",Ba[Ba.LeaveRequest=4]="LeaveRequest",Ba[Ba.Timeout=5]="Timeout",Ba[Ba.WebSocket=6]="WebSocket",Ba[Ba.ServiceNotFound=7]="ServiceNotFound";class za extends Fa{constructor(t,n,i,r){super(1,t),this.name="ConnectionError",this.status=i,this.reason=n,this.context=r,this.reasonName=e.ConnectionErrorReason[n]}static notAllowed(t,n,i){return new za(t,e.ConnectionErrorReason.NotAllowed,n,i)}static timeout(t){return new za(t,e.ConnectionErrorReason.Timeout)}static leaveRequest(t,n){return new za(t,e.ConnectionErrorReason.LeaveRequest,void 0,n)}static internal(t,n){return new za(t,e.ConnectionErrorReason.InternalError,void 0,n)}static cancelled(t){return new za(t,e.ConnectionErrorReason.Cancelled)}static serverUnreachable(t,n){return new za(t,e.ConnectionErrorReason.ServerUnreachable,n)}static websocket(t,n,i){return new za(t,e.ConnectionErrorReason.WebSocket,n,i)}static serviceNotFound(t,n){return new za(t,e.ConnectionErrorReason.ServiceNotFound,void 0,n)}}class Ga extends Ua{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class Ja extends Ua{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class Qa extends Ua{constructor(e){super(10,e||"unsupported server"),this.name="UnsupportedServer"}}class Ya extends Ua{constructor(e){super(12,e||"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Xa extends Ua{constructor(e){super(13,e||"unable to negotiate"),this.name="NegotiationError"}}class Za extends Ua{constructor(e){super(14,e||"unable to publish data"),this.name="PublishDataError"}}class $a extends Ua{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class es extends Fa{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName="string"==typeof t?t:Wi[t]}}e.DataStreamErrorReason=void 0,(ja=e.DataStreamErrorReason||(e.DataStreamErrorReason={}))[ja.AlreadyOpened=0]="AlreadyOpened",ja[ja.AbnormalEnd=1]="AbnormalEnd",ja[ja.DecodeFailed=2]="DecodeFailed",ja[ja.LengthExceeded=3]="LengthExceeded",ja[ja.Incomplete=4]="Incomplete",ja[ja.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",ja[ja.EncryptionTypeMismatch=8]="EncryptionTypeMismatch",ja[ja.HeaderTooLarge=9]="HeaderTooLarge",ja[ja.PayloadTooLarge=10]="PayloadTooLarge";class ts extends Fa{constructor(t,n){super(16,t),this.name="DataStreamError",this.reason=n,this.reasonName=e.DataStreamErrorReason[n]}}class ns extends Ua{constructor(e){super(18,e),this.name="SignalReconnectError"}}e.MediaDeviceFailure=void 0,(qa=e.MediaDeviceFailure||(e.MediaDeviceFailure={})).PermissionDenied="PermissionDenied",qa.NotFound="NotFound",qa.DeviceInUse="DeviceInUse",qa.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}}(e.MediaDeviceFailure||(e.MediaDeviceFailure={}));class is{}function rs(e){const t={};for(const i of Object.entries(e)){var n=F(i,2);const e=n[0],r=n[1];void 0!==r&&(t[e]=r)}return t}function as(e,t){return e&&t?"".concat(e,"x").concat(t):void 0}function ss(e){return Math.round(1e4*e)/1e4}function os(e){const t=e.jitterBufferDelay,n=e.jitterBufferEmittedCount;return void 0!==t&&n?ss(t/n):void 0}function cs(e,t){if(void 0!==e.playoutDelay)return ss(e.playoutDelay);const n=null==t?void 0:t.totalPlayoutDelay,i=null==t?void 0:t.totalSamplesCount;return void 0!==n&&i?ss(n/i):void 0}function ds(e){var t,n;const i=new Map,r=[],a=[],s=[];let o;e.forEach((e=>i.set(e.id,e)));const c=e=>{var t;return e.codecId?null===(t=i.get(e.codecId))||void 0===t?void 0:t.mimeType:void 0},d=(e,t)=>e[t]?i.get(e[t]):void 0;e.forEach((e=>{switch(e.type){case"inbound-rtp":{const t=d(e,"playoutId");a.push(rs({kind:e.kind,ssrc:e.ssrc,mid:e.mid,trackId:e.trackIdentifier,codec:c(e),decoder:e.decoderImplementation,resolution:as(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,bytesReceived:e.bytesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,packetsDiscarded:e.packetsDiscarded,framesReceived:e.framesReceived,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,keyFramesDecoded:e.keyFramesDecoded,freezeCount:e.freezeCount,totalFreezesDuration:e.totalFreezesDuration,pauseCount:e.pauseCount,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,jitter:e.jitter,jitterBuffer:os(e),playoutDelay:cs(e,t),audioLevel:e.audioLevel,totalSamplesReceived:e.totalSamplesReceived,concealedSamples:e.concealedSamples}));break}case"outbound-rtp":{const t=d(e,"remoteId"),n=d(e,"mediaSourceId");s.push(rs({kind:e.kind,ssrc:e.ssrc,mid:e.mid,rid:e.rid,trackId:null==n?void 0:n.trackIdentifier,active:e.active,codec:c(e),encoder:e.encoderImplementation,resolution:as(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,captureResolution:as(null==n?void 0:n.width,null==n?void 0:n.height),captureFps:null==n?void 0:n.framesPerSecond,audioLevel:null==n?void 0:n.audioLevel,targetBitrate:e.targetBitrate,bytesSent:e.bytesSent,packetsSent:e.packetsSent,retransmittedPacketsSent:e.retransmittedPacketsSent,framesEncoded:e.framesEncoded,keyFramesEncoded:e.keyFramesEncoded,limitedBy:"none"===e.qualityLimitationReason?void 0:e.qualityLimitationReason,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,remotePacketsLost:null==t?void 0:t.packetsLost,remoteFractionLost:null==t?void 0:t.fractionLost,remoteJitter:null==t?void 0:t.jitter,remoteRoundTripTime:null==t?void 0:t.roundTripTime}));break}case"transport":o=e;break;case"candidate-pair":r.push(e)}}));const l=null==o?void 0:o.selectedCandidatePairId,u=null!==(n=null!==(t=l?i.get(l):void 0)&&void 0!==t?t:r.find((e=>e.selected)))&&void 0!==n?n:r.find((e=>e.nominated)),h=(null==u?void 0:u.localCandidateId)?i.get(u.localCandidateId):void 0,p=(null==u?void 0:u.remoteCandidateId)?i.get(u.remoteCandidateId):void 0,m=rs({ice:null==o?void 0:o.iceState,dtls:null==o?void 0:o.dtlsState,route:h&&p?"".concat(h.candidateType,"/").concat(h.protocol," -> ").concat(p.candidateType):void 0,network:null==h?void 0:h.networkType,currentRoundTripTime:null==u?void 0:u.currentRoundTripTime,availableOutgoingBitrate:null==u?void 0:u.availableOutgoingBitrate,availableIncomingBitrate:null==u?void 0:u.availableIncomingBitrate,bytesSent:null==u?void 0:u.bytesSent,bytesReceived:null==u?void 0:u.bytesReceived,candidatePairChanges:null==o?void 0:o.selectedCandidatePairChanges});return{connection:Object.keys(m).length>0?m:void 0,outbound:s.length>0?s:void 0,inbound:a.length>0?a:void 0}}is.setTimeout=function(){return setTimeout(...arguments)},is.setInterval=function(){return setInterval(...arguments)},is.clearTimeout=function(){return clearTimeout(...arguments)},is.clearInterval=function(){return clearInterval(...arguments)},e.RoomEvent=void 0,(Va=e.RoomEvent||(e.RoomEvent={})).Connected="connected",Va.Reconnecting="reconnecting",Va.SignalReconnecting="signalReconnecting",Va.Reconnected="reconnected",Va.Disconnected="disconnected",Va.ConnectionStateChanged="connectionStateChanged",Va.Moved="moved",Va.MediaDevicesChanged="mediaDevicesChanged",Va.ParticipantConnected="participantConnected",Va.ParticipantDisconnected="participantDisconnected",Va.TrackPublished="trackPublished",Va.TrackSubscribed="trackSubscribed",Va.TrackSubscriptionFailed="trackSubscriptionFailed",Va.TrackUnpublished="trackUnpublished",Va.TrackUnsubscribed="trackUnsubscribed",Va.TrackMuted="trackMuted",Va.TrackUnmuted="trackUnmuted",Va.LocalTrackPublished="localTrackPublished",Va.LocalTrackUnpublished="localTrackUnpublished",Va.LocalAudioSilenceDetected="localAudioSilenceDetected",Va.ActiveSpeakersChanged="activeSpeakersChanged",Va.ParticipantMetadataChanged="participantMetadataChanged",Va.ParticipantNameChanged="participantNameChanged",Va.ParticipantAttributesChanged="participantAttributesChanged",Va.ParticipantActive="participantActive",Va.RoomMetadataChanged="roomMetadataChanged",Va.DataReceived="dataReceived",Va.SipDTMFReceived="sipDTMFReceived",Va.TranscriptionReceived="transcriptionReceived",Va.ConnectionQualityChanged="connectionQualityChanged",Va.TrackStreamStateChanged="trackStreamStateChanged",Va.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Va.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Va.AudioPlaybackStatusChanged="audioPlaybackChanged",Va.VideoPlaybackStatusChanged="videoPlaybackChanged",Va.MediaDevicesError="mediaDevicesError",Va.ParticipantPermissionsChanged="participantPermissionsChanged",Va.SignalConnected="signalConnected",Va.RecordingStatusChanged="recordingStatusChanged",Va.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Va.EncryptionError="encryptionError",Va.DCBufferStatusChanged="dcBufferStatusChanged",Va.ActiveDeviceChanged="activeDeviceChanged",Va.ChatMessage="chatMessage",Va.LocalTrackSubscribed="localTrackSubscribed",Va.MetricsReceived="metricsReceived",Va.DataTrackPublished="dataTrackPublished",Va.DataTrackUnpublished="dataTrackUnpublished",Va.LocalDataTrackPublished="localDataTrackPublished",Va.LocalDataTrackUnpublished="localDataTrackUnpublished",e.ParticipantEvent=void 0,(Wa=e.ParticipantEvent||(e.ParticipantEvent={})).TrackPublished="trackPublished",Wa.TrackSubscribed="trackSubscribed",Wa.TrackSubscriptionFailed="trackSubscriptionFailed",Wa.TrackUnpublished="trackUnpublished",Wa.TrackUnsubscribed="trackUnsubscribed",Wa.TrackMuted="trackMuted",Wa.TrackUnmuted="trackUnmuted",Wa.LocalTrackPublished="localTrackPublished",Wa.LocalTrackUnpublished="localTrackUnpublished",Wa.LocalTrackCpuConstrained="localTrackCpuConstrained",Wa.LocalSenderCreated="localSenderCreated",Wa.ParticipantMetadataChanged="participantMetadataChanged",Wa.ParticipantNameChanged="participantNameChanged",Wa.DataReceived="dataReceived",Wa.SipDTMFReceived="sipDTMFReceived",Wa.TranscriptionReceived="transcriptionReceived",Wa.IsSpeakingChanged="isSpeakingChanged",Wa.ConnectionQualityChanged="connectionQualityChanged",Wa.TrackStreamStateChanged="trackStreamStateChanged",Wa.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Wa.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Wa.TrackCpuConstrained="trackCpuConstrained",Wa.MediaDevicesError="mediaDevicesError",Wa.AudioStreamAcquired="audioStreamAcquired",Wa.ParticipantPermissionsChanged="participantPermissionsChanged",Wa.PCTrackAdded="pcTrackAdded",Wa.AttributesChanged="attributesChanged",Wa.LocalTrackSubscribed="localTrackSubscribed",Wa.ChatMessage="chatMessage",Wa.Active="active",e.EngineEvent=void 0,(Ha=e.EngineEvent||(e.EngineEvent={})).TransportsCreated="transportsCreated",Ha.Connected="connected",Ha.Disconnected="disconnected",Ha.Resuming="resuming",Ha.Resumed="resumed",Ha.Restarting="restarting",Ha.Restarted="restarted",Ha.SignalResumed="signalResumed",Ha.SignalRestarted="signalRestarted",Ha.Closing="closing",Ha.MediaTrackAdded="mediaTrackAdded",Ha.ActiveSpeakersUpdate="activeSpeakersUpdate",Ha.DataPacketReceived="dataPacketReceived",Ha.RTPVideoMapUpdate="rtpVideoMapUpdate",Ha.DCBufferStatusChanged="dcBufferStatusChanged",Ha.ParticipantUpdate="participantUpdate",Ha.RoomUpdate="roomUpdate",Ha.SpeakersChanged="speakersChanged",Ha.StreamStateChanged="streamStateChanged",Ha.ConnectionQualityUpdate="connectionQualityUpdate",Ha.SubscriptionError="subscriptionError",Ha.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",Ha.RemoteMute="remoteMute",Ha.SubscribedQualityUpdate="subscribedQualityUpdate",Ha.LocalTrackUnpublished="localTrackUnpublished",Ha.LocalTrackSubscribed="localTrackSubscribed",Ha.Offline="offline",Ha.SignalRequestResponse="signalRequestResponse",Ha.SignalConnected="signalConnected",Ha.RoomMoved="roomMoved",Ha.PublishDataTrackResponse="publishDataTrackResponse",Ha.UnPublishDataTrackResponse="unPublishDataTrackResponse",Ha.DataTrackSubscriberHandles="dataTrackSubscriberHandles",Ha.DataTrackPacketReceived="dataTrackPacketReceived",Ha.Joined="joined",Ha.TokenRefreshed="tokenRefreshed",Ha.ServerRegionsReported="serverRegionsReported",e.TrackEvent=void 0,(Ka=e.TrackEvent||(e.TrackEvent={})).Message="message",Ka.Muted="muted",Ka.Unmuted="unmuted",Ka.Restarted="restarted",Ka.Ended="ended",Ka.Subscribed="subscribed",Ka.Unsubscribed="unsubscribed",Ka.CpuConstrained="cpuConstrained",Ka.UpdateSettings="updateSettings",Ka.UpdateSubscription="updateSubscription",Ka.AudioPlaybackStarted="audioPlaybackStarted",Ka.AudioPlaybackFailed="audioPlaybackFailed",Ka.AudioSilenceDetected="audioSilenceDetected",Ka.VisibilityChanged="visibilityChanged",Ka.VideoDimensionsChanged="videoDimensionsChanged",Ka.VideoPlaybackStarted="videoPlaybackStarted",Ka.VideoPlaybackFailed="videoPlaybackFailed",Ka.ElementAttached="elementAttached",Ka.ElementDetached="elementDetached",Ka.UpstreamPaused="upstreamPaused",Ka.UpstreamResumed="upstreamResumed",Ka.SubscriptionPermissionChanged="subscriptionPermissionChanged",Ka.SubscriptionStatusChanged="subscriptionStatusChanged",Ka.SubscriptionFailed="subscriptionFailed",Ka.TrackProcessorUpdate="trackProcessorUpdate",Ka.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",Ka.TranscriptionReceived="transcriptionReceived",Ka.TimeSyncUpdate="timeSyncUpdate",Ka.PreConnectBufferFlushed="preConnectBufferFlushed";class ls{constructor(e,t,n,i,r){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===n)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:n,maxFramerate:i,priority:r}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const us=["opus","red"],hs=["vp8","h264"],ps=["vp8","h264","vp9","av1","h265"];function ms(e){return!!hs.find((t=>t===e))}const gs=ms;var vs,fs;e.BackupCodecPolicy=void 0,(vs=e.BackupCodecPolicy||(e.BackupCodecPolicy={}))[vs.PREFER_REGRESSION=0]="PREFER_REGRESSION",vs[vs.SIMULCAST=1]="SIMULCAST",vs[vs.REGRESSION=2]="REGRESSION",e.AudioPresets=void 0,(fs=e.AudioPresets||(e.AudioPresets={})).telephone={maxBitrate:12e3},fs.speech={maxBitrate:24e3},fs.music={maxBitrate:48e3},fs.musicStereo={maxBitrate:64e3},fs.musicHighQuality={maxBitrate:96e3},fs.musicHighQualityStereo={maxBitrate:128e3};const ks={h90:new ls(160,90,9e4,20),h180:new ls(320,180,16e4,20),h216:new ls(384,216,18e4,20),h360:new ls(640,360,45e4,20),h540:new ls(960,540,8e5,25),h720:new ls(1280,720,17e5,30),h1080:new ls(1920,1080,3e6,30),h1440:new ls(2560,1440,5e6,30),h2160:new ls(3840,2160,8e6,30)},ys={h120:new ls(160,120,7e4,20),h180:new ls(240,180,125e3,20),h240:new ls(320,240,14e4,20),h360:new ls(480,360,33e4,20),h480:new ls(640,480,5e5,20),h540:new ls(720,540,6e5,25),h720:new ls(960,720,13e5,30),h1080:new ls(1440,1080,23e5,30),h1440:new ls(1920,1440,38e5,30)},bs={h360fps3:new ls(640,360,2e5,3,"medium"),h360fps15:new ls(640,360,4e5,15,"medium"),h720fps5:new ls(1280,720,8e5,5,"medium"),h720fps15:new ls(1280,720,15e5,15,"medium"),h720fps30:new ls(1280,720,2e6,30,"medium"),h1080fps15:new ls(1920,1080,25e5,15,"medium"),h1080fps30:new ls(1920,1080,5e6,30,"medium"),original:new ls(0,0,7e6,30,"medium")};function Ts(e,t,n){var i,r,a,s;const o=Os(null!=e?e:{}),c=o.optionsWithoutProcessor,d=o.audioProcessor,l=o.videoProcessor,u=null==t?void 0:t.processor,h=null==n?void 0:n.processor,p=null!=c?c:{};return!0===p.audio&&(p.audio={}),!0===p.video&&(p.video={}),p.audio&&(Ss(p.audio,t),null!==(i=(a=p.audio).deviceId)&&void 0!==i||(a.deviceId={ideal:"default"}),(d||u)&&(p.audio.processor=null!=d?d:u)),p.video&&(Ss(p.video,n),null!==(r=(s=p.video).deviceId)&&void 0!==r||(s.deviceId={ideal:"default"}),(l||h)&&(p.video.processor=null!=l?l:h)),p}function Ss(e,t){return Object.keys(t).forEach((n=>{void 0===e[n]&&(e[n]=t[n])})),e}function Es(e){var t,n,i,r;const a={};if(e.video)if("object"==typeof e.video){const n={},r=n,s=e.video;Object.keys(s).forEach((e=>{if("resolution"===e)Ss(r,s.resolution);else r[e]=s[e]})),a.video=n,null!==(t=(i=a.video).deviceId)&&void 0!==t||(i.deviceId={ideal:"default"})}else a.video=!!e.video&&{deviceId:{ideal:"default"}};else a.video=!1;return e.audio?"object"==typeof e.audio?(a.audio=e.audio,null!==(n=(r=a.audio).deviceId)&&void 0!==n||(r.deviceId={ideal:"default"})):a.audio={deviceId:{ideal:"default"}}:a.audio=!1,a}function Cs(e){return pr(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const n=ws();if(n){const i=n.createAnalyser();i.fftSize=2048;const r=i.frequencyBinCount,a=new Uint8Array(r);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(i),yield qs(t),i.getByteTimeDomainData(a);const s=a.some((e=>128!==e&&0!==e));return n.close(),!s}return!1}()}))}function ws(){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=()=>pr(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 Rs(e){return"audioinput"===e?xs.Source.Microphone:"videoinput"===e?xs.Source.Camera:xs.Source.Unknown}function Ps(e){return e===xs.Source.Microphone?"audioinput":e===xs.Source.Camera?"videoinput":void 0}function Is(e){var t,n;let i=null===(t=e.video)||void 0===t||t;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(i="boolean"==typeof i?{}:i,i=Zs()?Object.assign(Object.assign({},i),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},i),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:null!==(n=e.audio)&&void 0!==n&&n,video:i,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}function _s(e){return e.split("/")[1].toLowerCase()}function Ms(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new ei({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function Ds(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?Ds(e.track):{})}}function Os(e){const t=Object.assign({},e);let n,i;return"object"==typeof t.audio&&t.audio.processor&&(n=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),"object"==typeof t.video&&t.video.processor&&(i=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:n,videoProcessor:i,optionsWithoutProcessor:(r=t,void 0===r?r:"function"==typeof structuredClone?"object"==typeof r&&null!==r?structuredClone(Object.assign({},r)):structuredClone(r):JSON.parse(JSON.stringify(r)))};var r}function As(e,t){return e.width*e.height<t.width*t.height}const Ls=[];var Ns;e.VideoQuality=void 0,(Ns=e.VideoQuality||(e.VideoQuality={}))[Ns.LOW=0]="LOW",Ns[Ns.MEDIUM=1]="MEDIUM",Ns[Ns.HIGH=2]="HIGH";class xs extends br.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState!==e&&this.log.debug("stream state changed: ".concat(this._streamState," -> ").concat(e)),this._streamState=e}constructor(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=xs.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.finalStatsLogged=!1,this.log=ar,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.loggerContextCb=i.loggerContextCb,this.log=or(null!==(r=i.loggerName)&&void 0!==r?r:e.LoggerNames.Track,(()=>this.logContext)),this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=xs.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),Ds(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let n="audio";this.kind===xs.Kind.Video&&(n="video"),0===this.attachedElements.length&&this.kind===xs.Kind.Video&&this.addAppVisibilityListener(),t||("audio"===n&&(Ls.forEach((e=>{null!==e.parentElement||t||(t=e)})),t&&Ls.splice(Ls.indexOf(t),1)),t||(t=document.createElement(n))),this.attachedElements.includes(t)||this.attachedElements.push(t),Us(this.mediaStreamTrack,t);const i=t.srcObject.getTracks(),r=i.some((e=>"audio"===e.kind));return t.play().then((()=>{this.emit(r?e.TrackEvent.AudioPlaybackStarted:e.TrackEvent.VideoPlaybackStarted)})).catch((n=>{"NotAllowedError"===n.name?this.emit(r?e.TrackEvent.AudioPlaybackFailed:e.TrackEvent.VideoPlaybackFailed,n):"AbortError"===n.name?this.log.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):this.log.warn("could not playback ".concat(r?"audio":"video"),{error:n}),r&&t&&i.some((e=>"video"===e.kind))&&"NotAllowedError"===n.name&&(t.muted=!0,t.play().catch((()=>{})))})),this.emit(e.TrackEvent.ElementAttached,t),t}detach(t){try{if(t){Fs(this.mediaStreamTrack,t);const n=this.attachedElements.indexOf(t);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)),t}const n=[];return this.attachedElements.forEach((t=>{Fs(this.mediaStreamTrack,t),n.push(t),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)})),this.attachedElements=[],n}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.log.debug("stopping track"),this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),void 0!==this.timeSyncHandle&&(cancelAnimationFrame(this.timeSyncHandle),this.timeSyncHandle=void 0),this.logFinalStats()}logFinalStats(){this.finalStatsLogged||(this.finalStatsLogged=!0,this.getRTCStatsReport().then((e=>{e&&this.log.info("final track stats",ds(e))})).catch((e=>this.log.debug("could not collect final track stats",{error:e}))))}updateLoggerOptions(e){e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb),e.loggerName&&(this.log=or(e.loggerName,(()=>this.logContext)))}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Ls.forEach((e=>{e.parentElement||(t=!1)})),t&&Ls.push(e)}}handleAppVisibilityChanged(){return pr(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==xs.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){no()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){no()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Us(e,t){let n,i;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,i="audio"===e.kind?n.getAudioTracks():n.getVideoTracks(),i.includes(e)||(i.forEach((e=>{n.removeTrack(e)})),n.addTrack(e)),Zs()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===n.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(Zs()||Ys())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=n,t.play().catch((()=>{}))}),0))}function Fs(e,t){if(t.srcObject instanceof MediaStream){const n=t.srcObject;n.removeTrack(e),n.getTracks().length>0?t.srcObject=n:t.srcObject=null}}!function(e){let t,n,i;!function(e){e.Audio="audio",e.Video="video",e.Unknown="unknown"}(t=e.Kind||(e.Kind={})),function(e){e.Camera="camera",e.Microphone="microphone",e.ScreenShare="screen_share",e.ScreenShareAudio="screen_share_audio",e.Unknown="unknown"}(n=e.Source||(e.Source={})),function(e){e.Active="active",e.Paused="paused",e.Unknown="unknown"}(i=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return et.AUDIO;case t.Video:return et.VIDEO;default:return et.DATA}},e.kindFromProto=function(e){switch(e){case et.AUDIO:return t.Audio;case et.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return tt.CAMERA;case n.Microphone:return tt.MICROPHONE;case n.ScreenShare:return tt.SCREEN_SHARE;case n.ScreenShareAudio:return tt.SCREEN_SHARE_AUDIO;default:return tt.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case tt.CAMERA:return n.Camera;case tt.MICROPHONE:return n.Microphone;case tt.SCREEN_SHARE:return n.ScreenShare;case tt.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case Fn.ACTIVE:return i.Active;case Fn.PAUSED:return i.Paused;default:return i.Unknown}}}(xs||(xs={}));const Bs="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function js(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}function qs(e){return new _a((t=>is.setTimeout(t,e)))}function Vs(){return"addTransceiver"in RTCPeerConnection.prototype}function Ws(){return"addTrack"in RTCPeerConnection.prototype}function Hs(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Zs()||Ys())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const n of e.codecs)if("video/av1"===n.mimeType.toLowerCase()){t=!0;break}return t}function Ks(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Ys())return!1;if(Zs()){const e=Oa();if((null==e?void 0:e.version)&&lo(e.version,"16")<0)return!1;if("iOS"===(null==e?void 0:e.os)&&(null==e?void 0:e.osVersion)&&lo(e.osVersion,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const n of e.codecs)if("video/vp9"===n.mimeType.toLowerCase()){t=!0;break}return t}function zs(e){return"av1"===e||"vp9"===e}function Gs(e){var t;const i=null===(t=e.getHeaderExtensionsToNegotiate)||void 0===t?void 0:t.call(e);if(!i||!e.setHeaderExtensionsToNegotiate)return!1;const r=i.find((e=>e.uri===Bs));if(!r)return!1;if("stopped"!==r.direction)return!0;r.direction="sendrecv";try{return e.setHeaderExtensionsToNegotiate(i),!0}catch(n){return!1}}function Js(e){return!(!document||$s())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function Qs(){return"undefined"!=typeof RTCPeerConnection&&(Vs()||Ws())}function Ys(){var e;return"Firefox"===(null===(e=Oa())||void 0===e?void 0:e.name)}function Xs(){return"undefined"!=typeof window&&void 0!==window.RTCRtpScriptTransform&&!function(){const e=Oa();return!!e&&"Chrome"===e.name&&"iOS"!==e.os}()}function Zs(){var e;return"Safari"===(null===(e=Oa())||void 0===e?void 0:e.name)}function $s(){const e=Oa();return"Safari"===(null==e?void 0:e.name)||"iOS"===(null==e?void 0:e.os)}function eo(){const e=Oa();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)&&lo(e.osVersion,"17")>=0}function to(){var e,t;return!!no()&&(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 no(){return"undefined"!=typeof document}function io(){return"ReactNative"==navigator.product}function ro(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function ao(e){return ro(e)?e.hostname.split(".")[0]:null}function so(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function oo(){if(!io())return;let e=so();return e?e.platform:void 0}function co(){if(no())return window.devicePixelRatio;if(io()){let e=so();if(e)return e.devicePixelRatio}return 1}function lo(e,t){const n=e.split("."),i=t.split("."),r=Math.min(n.length,i.length);for(let a=0;a<r;++a){const e=parseInt(n[a],10),t=parseInt(i[a],10);if(e>t)return 1;if(e<t)return-1;if(a===r-1&&e===t)return 0}return""===e&&""!==t?-1:""===t?1:n.length==i.length?0:n.length<i.length?-1:1}function uo(e){for(const t of e)t.target.handleResize(t)}function ho(e){for(const t of e)t.target.handleVisibilityChanged(t)}let po=null;const mo=()=>(po||(po=new ResizeObserver(uo)),po);let go=null;const vo=()=>(go||(go=new IntersectionObserver(ho,{root:null,rootMargin:"0px"})),go);let fo,ko;function yo(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const r=document.createElement("canvas");r.width=e,r.height=t;const a=r.getContext("2d");null==a||a.fillRect(0,0,r.width,r.height),i&&a&&(a.beginPath(),a.arc(e/2,t/2,50,0,2*Math.PI,!0),a.closePath(),a.fillStyle="grey",a.fill());const s=F(r.captureStream().getTracks(),1)[0];if(!s)throw Error("Could not get empty media stream video track");return s.enabled=n,s}function bo(){if(!ko){const t=new AudioContext,n=t.createOscillator(),i=t.createGain();i.gain.setValueAtTime(0,0);const r=t.createMediaStreamDestination();n.connect(i),i.connect(r),n.start();var e=F(r.stream.getAudioTracks(),1);if(ko=e[0],!ko)throw Error("Could not get empty media stream audio track");ko.enabled=!1}return ko.clone()}class To{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise(((t,n)=>pr(this,void 0,void 0,(function*(){this.resolve=t,this.reject=n,e&&(yield e(t,n))})))).finally((()=>{var e;this._isResolved=!0,null===(e=this.onFinally)||void 0===e||e.call(this)}))}}function So(e){return ps.includes(e)}function Eo(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 Co(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function wo(t){switch(t.reason){case e.ConnectionErrorReason.LeaveRequest:return t.context;case e.ConnectionErrorReason.Cancelled:return at.CLIENT_INITIATED;case e.ConnectionErrorReason.NotAllowed:return at.USER_REJECTED;case e.ConnectionErrorReason.ServerUnreachable:return at.JOIN_FAILURE;default:return at.UNKNOWN_REASON}}function Ro(e){return void 0!==e?Number(e):void 0}function Po(e){return void 0!==e?BigInt(e):void 0}function Io(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function _o(e){return!!e&&e.kind==xs.Kind.Audio}function Mo(e){return!!e&&e.kind==xs.Kind.Video}function Do(e){return Io(e)&&Mo(e)}function Oo(e){return Io(e)&&_o(e)}function Ao(e){return!!e&&!e.isLocal}function Lo(e){return!!e&&!e.isLocal}function No(e){return Ao(e)&&Mo(e)}function xo(e){return e.isLocal}function Uo(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}function Fo(){return"undefined"!=typeof CompressionStream}function Bo(e,t){const n=F(js(t.id),2)[1];return(null==n?void 0:n.startsWith("TR"))?n:e.id.startsWith("TR")?e.id:void 0}function jo(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const i=function(e,t){const n=new URL(function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e));return t.forEach(((e,t)=>{n.searchParams.set(t,e)})),Vo(n,"rtc")}(e,t);return n?i:Vo(i,"v1")}function qo(e){return e.endsWith("/")?e:"".concat(e,"/")}function Vo(e,t){return e.pathname="".concat(qo(e.pathname)).concat(t),e}function Wo(e){if("string"==typeof e)return qn.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return qn.fromBinary(new Uint8Array(e));throw new Error("could not decode websocket message: ".concat(typeof e))}const Ho="AES-GCM",Ko="lk_e2ee",zo="lk_e2ee_track_id",Go={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16,keySize:128};var Jo,Qo;function Yo(){return Zo()||Xo()}function Xo(){return"undefined"!=typeof window&&void 0!==window.RTCRtpScriptTransform}function Zo(){return"undefined"!=typeof window&&void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams}function $o(e){return pr(this,void 0,void 0,(function*(){let t=new TextEncoder;return yield crypto.subtle.importKey("raw",t.encode(e),{name:"PBKDF2"},!1,["deriveBits","deriveKey"])}))}function ec(e){return pr(this,void 0,void 0,(function*(){return yield crypto.subtle.importKey("raw",e,"HKDF",!1,["deriveBits","deriveKey"])}))}function tc(e,t){const n=(new TextEncoder).encode(t);switch(e){case"HKDF":return{name:"HKDF",salt:n,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:n,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(e," is currently unsupported"))}}e.KeyProviderEvent=void 0,(Jo=e.KeyProviderEvent||(e.KeyProviderEvent={})).SetKey="setKey",Jo.RatchetRequest="ratchetRequest",Jo.KeyRatcheted="keyRatcheted",e.KeyHandlerEvent=void 0,(e.KeyHandlerEvent||(e.KeyHandlerEvent={})).KeyRatcheted="keyRatcheted",e.EncryptionEvent=void 0,(Qo=e.EncryptionEvent||(e.EncryptionEvent={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Qo.EncryptionError="encryptionError",e.CryptorEvent=void 0,(e.CryptorEvent||(e.CryptorEvent={})).Error="cryptorError";function nc(e){var t,n,i,r,a;if("sipDtmf"!==(null===(t=e.value)||void 0===t?void 0:t.case)&&"metrics"!==(null===(n=e.value)||void 0===n?void 0:n.case)&&"speaker"!==(null===(i=e.value)||void 0===i?void 0:i.case)&&"transcription"!==(null===(r=e.value)||void 0===r?void 0:r.case)&&"encryptedPacket"!==(null===(a=e.value)||void 0===a?void 0:a.case))return new Lt({value:e.value})}class ic extends br.EventEmitter{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.latestManuallySetKeyIndex=0,this.onKeyRatcheted=(e,t,n)=>{ar.debug("key ratcheted event received",{ratchetResult:e,participantId:t,keyIndex:n})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Go),t),this.on(e.KeyProviderEvent.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(t,n,i){const r={key:t,participantIdentity:n,keyIndex:i};if(!this.options.sharedKey&&!n)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(null!=n?n:"shared","-").concat(null!=i?i:0),r),void 0!==i&&(this.latestManuallySetKeyIndex=i),this.emit(e.KeyProviderEvent.SetKey,r,void 0!==i)}getKeys(){return Array.from(this.keyInfoMap.values())}getLatestManuallySetKeyIndex(){return this.latestManuallySetKeyIndex}getOptions(){return this.options}ratchetKey(t,n){this.emit(e.KeyProviderEvent.RatchetRequest,t,n)}}var rc;e.CryptorErrorReason=void 0,(rc=e.CryptorErrorReason||(e.CryptorErrorReason={}))[rc.InvalidKey=0]="InvalidKey",rc[rc.MissingKey=1]="MissingKey",rc[rc.InternalError=2]="InternalError";function ac(){return Xs()}function sc(e){return!!(null==e?void 0:e.worker)&&(Zo()||ac())}function oc(e){return!(!(null==e?void 0:e.timestamp)&&!(null==e?void 0:e.frameId))}function cc(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var i,r;let a;const s=null!==(i=n.isImmediate)&&void 0!==i&&i,o=null!==(r=n.callback)&&void 0!==r&&r,c=n.maxWait;let d=Date.now(),l=[];const u=function(){for(var n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];const u=this;return new Promise(((n,r)=>{const h=s&&void 0===a;if(void 0!==a&&is.clearTimeout(a),a=is.setTimeout((function(){if(a=void 0,d=Date.now(),!s){const t=e.apply(u,i);o&&o(t),l.forEach((e=>(0,e.resolve)(t))),l=[]}}),function(){if(void 0!==c){const e=Date.now()-d;if(e+t>=c)return c-e}return t}()),h){const t=e.apply(u,i);return o&&o(t),n(t)}l.push({resolve:n,reject:r})}))};return u.cancel=function(e){void 0!==a&&is.clearTimeout(a),l.forEach((t=>(0,t.reject)(e))),l=[]},u}const dc=2e3;function lc(e,t){if(!t)return 0;let n,i;return"bytesReceived"in e?(n=e.bytesReceived,i=t.bytesReceived):"bytesSent"in e&&(n=e.bytesSent,i=t.bytesSent),void 0===n||void 0===i||void 0===e.timestamp||void 0===t.timestamp?0:8*(n-i)*1e3/(e.timestamp-t.timestamp)}class uc extends xs{constructor(t,n,i,r,a){super(t,i,a),this.timeSyncLoop=()=>{var t;if(0===this.listenerCount(e.TrackEvent.TimeSyncUpdate))return void(this.timeSyncHandle=void 0);this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop);const n=null===(t=this.receiver)||void 0===t?void 0:t.getSynchronizationSources()[0];if(n){const t=n.timestamp,i=n.rtpTimestamp;i&&this.rtpTimestamp!==i&&(this.emit(e.TrackEvent.TimeSyncUpdate,{timestamp:t,rtpTimestamp:i}),this.rtpTimestamp=i)}},this.onTimeSyncListenerAdded=t=>{t===e.TrackEvent.TimeSyncUpdate&&void 0===this.timeSyncHandle&&(this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop))},this.sid=n,this.receiver=r}get isLocal(){return!1}setMuted(t){this.isMuted!==t&&(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.Unmuted,this))}setMediaStream(t){this.mediaStream=t;const n=i=>{i.track===this._mediaStreamTrack&&(t.removeEventListener("removetrack",n),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(e.TrackEvent.Ended,this))};t.addEventListener("removetrack",n)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return pr(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()),dc)),"undefined"!=typeof RTCRtpReceiver&&"function"==typeof RTCRtpReceiver.prototype.getSynchronizationSources&&this.registerTimeSyncUpdate()}stopMonitor(){super.stopMonitor(),this.off("newListener",this.onTimeSyncListenerAdded)}registerTimeSyncUpdate(){this.off("newListener",this.onTimeSyncListenerAdded),this.on("newListener",this.onTimeSyncListenerAdded),void 0===this.timeSyncHandle&&this.timeSyncLoop()}}class hc extends uc{constructor(e,t,n,i,r){super(e,t,xs.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>pr(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=lc(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=cc((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}lookupFrameMetadata(e){let t=e.rtpTimestamp;var n;return null===(n=this.frameMetadataExtractor)||void 0===n?void 0:n.lookupMetadata(t)}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===xs.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?Fs(this._mediaStreamTrack,t):Us(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 pc(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 n of t)n.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t!==e)),this.updateVisibility(),this.debouncedHandleResize()}detach(e){if(e)return this.stopObservingElement(e),super.detach(e);const t=super.detach();for(const n of t)this.stopObservingElement(n);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return pr(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,n="",i=new Map;return e.forEach((e=>{"inbound-rtp"===e.type?(n=e.codecId,t={type:"video",streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):"codec"===e.type&&i.set(e.id,e)})),t&&""!==n&&i.get(n)&&(t.mimeType=i.get(n).mimeType),t}))}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const n of t)this.stopObservingElementInfo(n)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return pr(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(t){var n,i;const r=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),a=!(null!==(i=null===(n=this.adaptiveStreamSettings)||void 0===n?void 0:n.pauseVideoInBackground)&&void 0!==i&&!i)&&this.isInBackground,s=this.elementInfos.some((e=>e.pictureInPicture)),o=this.elementInfos.some((e=>e.visible))&&!a||s;(this.lastVisible!==o||t)&&(!o&&Date.now()-r<100?is.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=o,this.emit(e.TrackEvent.VisibilityChanged,o,this)))}updateDimensions(){var t,n;let i=0,r=0;const a=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*a,n=e.height()*a;t+n>i+r&&(i=t,r=n)}(null===(t=this.lastDimensions)||void 0===t?void 0:t.width)===i&&(null===(n=this.lastDimensions)||void 0===n?void 0:n.height)===r||(this.lastDimensions={width:i,height:r},this.emit(e.TrackEvent.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;if("screen"===t)return co();if(!t){return co()>2?2:1}return t}}class pc{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const n=e.target,i=e.isIntersecting;n===this.element&&(this.isIntersecting=i,this.isPiP=mc(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),queueMicrotask((()=>{requestAnimationFrame((()=>{var e;this.isPiP=mc(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)}))}))},this.onLeavePiP=()=>{var e;this.isPiP=mc(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:gc(e),this.isPiP=no()&&mc(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=gc(this.element),this.isPiP=mc(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,vo().observe(this.element),mo().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===(n=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===n||n.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,n,i,r;null===(e=vo())||void 0===e||e.unobserve(this.element),null===(t=mo())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(n=window.documentPictureInPicture)||void 0===n||n.removeEventListener("enter",this.onEnterPiP),null===(r=null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)||void 0===r||r.removeEventListener("pagehide",this.onLeavePiP)}}function mc(e){var t,n;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&gc(e,null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)}function gc(e,t){const n=t||window;let i=e.offsetTop,r=e.offsetLeft;const a=e.offsetWidth,s=e.offsetHeight,o=e.hidden,c=getComputedStyle(e).display;for(;e.offsetParent;)i+=(e=e.offsetParent).offsetTop,r+=e.offsetLeft;return i<n.pageYOffset+n.innerHeight&&r<n.pageXOffset+n.innerWidth&&i+s>n.pageYOffset&&r+a>n.pageXOffset&&!o&&"none"!==c}class vc extends br.EventEmitter{constructor(t,n){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=t=>{var n,i;const r=t.data,a=r.kind,s=r.data;switch(a){case"error":if(ar.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(e.EncryptionEvent.EncryptionError,s.error,s.participantIdentity);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e,!1)}));break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e,!1)})),this.encryptionEnabled!==s.enabled&&s.participantIdentity===(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity))this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const t=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!t)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,s.enabled,t)}break;case"ratchetKey":this.keyProvider.emit(e.KeyProviderEvent.KeyRatcheted,s.ratchetResult,s.participantIdentity,s.keyIndex);break;case"decryptDataResponse":const t=this.decryptDataRequests.get(s.uuid);(null==t?void 0:t.resolve)&&t.resolve(s);break;case"encryptDataResponse":const r=this.encryptDataRequests.get(s.uuid);(null==r?void 0:r.resolve)&&r.resolve(s);break;case"packetTrailerMetadata":this.handleFrameMetadata(s.trackId,s.rtpTimestamp,s.ssrc,s.metadata)}},this.onWorkerError=t=>{ar.error("e2ee worker encountered an error:",{error:t.error}),this.emit(e.EncryptionEvent.EncryptionError,t.error,void 0)},this.keyProvider=t.keyProvider,this.worker=t.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=n}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!Yo())throw new Ga("tried to setup end-to-end encryption on an unsupported browser");if(ar.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:cr.getLevel()}};this.worker&&(ar.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){ar.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):ar.warn("ignoring server sent trailer as it's empty")}handleFrameMetadata(e,t,n,i){if(this.room)for(const r of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(const a of r.trackPublications.values())if(a.track&&a.track.mediaStreamID===e&&a.track instanceof hc&&a.track.frameMetadataExtractor)return void a.track.frameMetadataExtractor.storeMetadata(t,n,i)}setupEngine(t){t.on(e.EngineEvent.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(t,n){t.on(e.RoomEvent.TrackPublished,((e,t)=>this.setParticipantCryptorEnabledForPublication(e,t.identity))),t.on(e.RoomEvent.ConnectionStateChanged,(n=>{n===e.ConnectionState.Connected&&t.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{this.setParticipantCryptorEnabledForPublication(t,e.identity)}))}))})).on(e.RoomEvent.TrackUnsubscribed,((e,t,n)=>{var i;const r={kind:"removeTransform",data:{participantIdentity:n.identity,trackId:e.mediaStreamID}};null===(i=this.worker)||void 0===i||i.postMessage(r)})).on(e.RoomEvent.TrackSubscribed,((e,t,n)=>{this.setupE2EEReceiver(e,n.identity,t.trackInfo)})).on(e.RoomEvent.SignalConnected,(()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");const e=n.getLatestManuallySetKeyIndex();n.getKeys().forEach((t=>{var n;this.postKey(t,e===(null!==(n=t.keyIndex)&&void 0!==n?n:0))})),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)})),t.localParticipant.on(e.ParticipantEvent.LocalSenderCreated,((e,t)=>pr(this,void 0,void 0,(function*(){this.setupE2EESender(t,e)})))),t.localParticipant.on(e.ParticipantEvent.LocalTrackPublished,(e=>{if(!Mo(e.track)||!$s())return;const t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:_s(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1}};this.worker.postMessage(t)})),n.on(e.KeyProviderEvent.SetKey,((e,t)=>this.postKey(e,null==t||t))).on(e.KeyProviderEvent.RatchetRequest,((e,t)=>this.postRatchetRequest(e,t)))}encryptData(e){return pr(this,void 0,void 0,(function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),n={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},i=new To;return i.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,i),this.worker.postMessage(n),i.promise}))}handleEncryptedData(e,t,n,i){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const r=crypto.randomUUID(),a={kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:n,keyIndex:i}},s=new To;return s.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,s),this.worker.postMessage(a),s.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e,t){let n=e.key,i=e.participantIdentity,r=e.keyIndex;var a;if(!this.worker)throw Error("could not set key, worker is missing");const s={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(a=this.room)||void 0===a?void 0:a.localParticipant.identity),key:n,keyIndex:r,updateCurrentKeyIndex:t}};this.worker.postMessage(s)}postEnable(e,t){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const n={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}}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 n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}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)}setParticipantCryptorEnabledForPublication(e,t){e.trackInfo?this.setParticipantCryptorEnabled(e.trackInfo.encryption!==ft.NONE,t):ar.warn("skipping e2ee enabled update for publication without trackInfo",{participant:t,trackSid:e.trackSid})}setupE2EEReceiver(e,t,n){if(!e.receiver)return;if(!(null==n?void 0:n.mimeType)||""===n.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");const i="video"===e.kind&&!!n.packetTrailerFeatures&&n.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?_s(n.mimeType):void 0,i)}setupE2EESender(e,t){var n,i,r;Io(e)&&t?this.handleSender(t,e.mediaStreamID,void 0,Mo(e)?null!==(i=null===(n=e.publishOptions)||void 0===n?void 0:n.frameMetadata)&&void 0!==i?i:null===(r=e.publishOptions)||void 0===r?void 0:r.packetTrailer:void 0):t||ar.warn("early return because sender is not ready")}handleReceiver(e,t,n,i,r){return pr(this,void 0,void 0,(function*(){if(this.worker){if(Xs()){const a={kind:"decode",participantIdentity:n,trackId:t,codec:i,hasPacketTrailer:r};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{if(Ko in e&&zo in e){const a={kind:"updateCodec",data:{trackId:t,previousTrackId:e[zo],codec:i,participantIdentity:n,hasPacketTrailer:r}};return this.worker.postMessage(a),void(e[zo]=t)}let a=e.writableStream,s=e.readableStream;if(!a||!s){const t=e.createEncodedStreams();e.writableStream=t.writable,a=t.writable,e.readableStream=t.readable,s=t.readable}const o={kind:"decode",data:{readableStream:s,writableStream:a,trackId:t,codec:i,participantIdentity:n,hasPacketTrailer:r}};this.worker.postMessage(o,[s,a])}e[Ko]=!0,e[zo]=t}}))}handleSender(e,t,n,i){var r;if(!(Ko in e)&&this.worker){if(!(null===(r=this.room)||void 0===r?void 0:r.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Xs()){ar.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n,hasPacketTrailer:oc(i),packetTrailer:i};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{ar.info("initialize encoded streams");const r=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:oc(i),packetTrailer:i}};this.worker.postMessage(a,[r.readable,r.writable])}e[Ko]=!0}}}class fc{constructor(){this.metadataMap=new Map,this.activeSsrc=0}storeMetadata(e,t,n){for(0!==this.activeSsrc&&this.activeSsrc!==t&&this.metadataMap.clear(),this.activeSsrc=t;this.metadataMap.size>=300;){const e=this.metadataMap.keys().next().value;this.metadataMap.delete(e)}this.metadataMap.set(e,n)}lookupMetadata(e){return this.metadataMap.get(e)}dispose(){this.metadataMap.clear(),this.activeSsrc=0}}class kc{constructor(e){this.extractors=new Map,this.workerPipelines=new Map,this.onWorkerMessage=e=>{const t=e.data;if("metadata"===t.kind){const e=this.extractors.get(t.data.trackId);e&&e.storeMetadata(t.data.rtpTimestamp,t.data.ssrc,t.data.metadata)}},this.onWorkerError=e=>{ar.error("frame metadata worker encountered an error:",{error:e.error})},this.worker=null==e?void 0:e.worker}setup(t){t!==this.room&&(this.room=t,this.worker&&(this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage({kind:"init"})),t.on(e.RoomEvent.TrackSubscribed,((e,t,n)=>{"video"===e.kind&&this.setupReceiver(e,t.trackInfo)})).on(e.RoomEvent.TrackUnsubscribed,(e=>{this.teardownTrack(e)})).on(e.RoomEvent.Disconnected,(()=>{this.cleanup()})))}setupReceiver(e,t){var n,i,r;const a=e.receiver;if(!a)return;if(!(!!(null==t?void 0:t.packetTrailerFeatures)&&t.packetTrailerFeatures.length>0))return void((null===(n=this.room)||void 0===n?void 0:n.hasE2EESetup)||this.setupPassthroughReceiver(a,e.mediaStreamID));if(!sc(this.worker?{worker:this.worker}:void 0)&&!(null===(i=this.room)||void 0===i?void 0:i.hasE2EESetup))return void ar.warn("frame metadata transform not supported; skipping extraction");const s=new fc,o=e.mediaStreamID;this.extractors.set(o,s),e.frameMetadataExtractor=s,(null===(r=this.room)||void 0===r?void 0:r.hasE2EESetup)||this.setupWorkerReceiver(a,o,!0)}setupPassthroughReceiver(e,t){ac()?"transform"in e&&(e.transform=null):(this.worker&&sc({worker:this.worker})&&!this.workerPipelines.has(e)||this.worker&&this.workerPipelines.has(e))&&this.setupWorkerReceiver(e,t,!1)}setupWorkerReceiver(e,t){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];const i=this.worker;if(!i)return;if(ac())return void(e.transform=new RTCRtpScriptTransform(i,{kind:"decode",trackId:t}));const r=this.workerPipelines.get(e);if(r){const a={kind:"updateTrackId",data:{oldTrackId:r,newTrackId:t,hasPacketTrailer:n}};return i.postMessage(a),void this.workerPipelines.set(e,t)}if(!("createEncodedStreams"in e))return void ar.warn("createEncodedStreams not supported");let a;try{a=e.createEncodedStreams()}catch(o){return void ar.warn("failed to create encoded streams",{error:o})}const s={kind:"decode",data:{readableStream:a.readable,writableStream:a.writable,trackId:t,hasPacketTrailer:n}};i.postMessage(s,[a.readable,a.writable]),this.workerPipelines.set(e,t)}teardownTrack(e){const t=e.mediaStreamID,n=this.extractors.get(t);n&&(n.dispose(),this.extractors.delete(t)),e instanceof hc&&(e.frameMetadataExtractor=void 0)}cleanup(){var e;for(const t of this.extractors.values())t.dispose();this.extractors.clear(),this.workerPipelines.clear(),null===(e=this.worker)||void 0===e||e.terminate()}}const yc=kc;class bc{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new bc),this._instance}addFailedConnectionAttempt(e){var t;const n=ao(new URL(e));if(!n)return;let i=null!==(t=this.failedConnectionAttempts.get(n))&&void 0!==t?t:0;this.failedConnectionAttempts.set(n,i+1),this.backOffPromises.set(n,qs(Math.min(500*Math.pow(2,i),15e3)))}getBackOffPromise(e){const t=new URL(e),n=t&&ao(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),n=t&&ao(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}bc._instance=null;const Tc="default";class Sc{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new Sc),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return pr(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var r;if((null===(r=Sc.userMediaPromiseMap)||void 0===r?void 0:r.size)>0){ar.debug("awaiting getUserMedia promise");try{e?yield Sc.userMediaPromiseMap.get(e):yield Promise.all(Sc.userMediaPromiseMap.values())}catch(n){ar.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(i&&(!Zs()||!t.hasDeviceInUse(e))){if(0===a.filter((t=>t.kind===e)).length||a.some((t=>{const n=""===t.label,i=!e||t.kind===e;return n&&i}))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}},n=yield navigator.mediaDevices.getUserMedia(t);a=yield navigator.mediaDevices.enumerateDevices(),n.getTracks().forEach((e=>{e.stop()}))}}return t._previousDevices=a,e&&(a=a.filter((t=>t.kind===e))),a}()}))}normalizeDeviceId(e,t,n){return pr(this,void 0,void 0,(function*(){if(t!==Tc)return t;const i=yield this.getDevices(e),r=i.find((e=>e.deviceId===Tc));if(!r)return void ar.warn("could not reliably determine default device");const a=i.find((e=>e.deviceId!==Tc&&e.groupId===(null!=n?n:r.groupId)));if(a)return null==a?void 0:a.deviceId;ar.warn("could not reliably determine default device")}))}hasDeviceInUse(e){return e?Sc.userMediaPromiseMap.has(e):Sc.userMediaPromiseMap.size>0}}Sc.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Sc.userMediaPromiseMap=new Map;const Ec=65535,Cc=4294967295;class wc{static u16(e){return new wc(e,Ec)}static u32(e){return new wc(e,Cc)}constructor(e,t){if(this.value=e,e<0)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0");if(t>Number.MAX_SAFE_INTEGER)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.");this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new wc(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.update((t=>t+e))}decrement(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.update((t=>t-e))}getThenIncrement(){const e=this.value;return this.increment(),new wc(e,this.maxSize)}isBefore(e){const t=this.value>>>0,n=(e.value>>>0)-t>>>0;return 0!==n&&n<this.maxSize+1}}class Rc{static fromRtpTicks(e){return new Rc(e,9e4)}static rtpRandom(){const e=Math.round(Math.random()*Cc);return Rc.fromRtpTicks(e)}constructor(e,t){this.timestamp=wc.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new Rc(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}}class Pc{constructor(e,t,n){this.epoch=t,this.base=n,this.previous=n.clone(),this.rateInHz=e}static startingNow(e,t){return new Pc(t,new Date,e)}static startingAtTime(e,t,n){return new Pc(n,e,t)}static rtpStartingNow(e){return Pc.startingNow(e,9e4)}static rtpStartingAtTime(e,t){return Pc.startingAtTime(e,t,9e4)}now(){return this.at(new Date)}at(e){let t=e.getTime()-this.epoch.getTime(),n=Pc.durationInMsToTicks(t,this.rateInHz),i=this.base.clone();return i.wrappingAdd(n),i.isBefore(this.previous)&&(i=this.previous),this.previous=i.clone(),i.clone()}static durationInMsToTicks(e,t){let n=(1e6*e*t+5e8)/1e9;return Math.round(n)}}function Ic(e){if(e instanceof DataView)return e;if(e instanceof ArrayBuffer)return new DataView(e);if(e instanceof Uint8Array)return new DataView(e.buffer,e.byteOffset,e.byteLength);throw new Error("Error coercing ".concat(e," to DataView - input was not DataView, ArrayBuffer, or Uint8Array."))}var _c;!function(e){e[e.Reserved=0]="Reserved",e[e.TooLarge=1]="TooLarge"}(_c||(_c={}));class Mc extends Fa{constructor(e,t){super(19,e),this.name="DataTrackHandleError",this.reason=t,this.reasonName=_c[t]}isReason(e){return this.reason===e}static tooLarge(){return new Mc("Value too large to be a valid track handle",_c.TooLarge)}static reserved(e){return new Mc("0x".concat(e.toString(16)," is a reserved value."),_c.Reserved)}}const Dc={fromNumber(e){if(0===e)throw Mc.reserved(e);if(e>Ec)throw Mc.tooLarge();return e}};class Oc{constructor(){this.value=0}get(){return this.value+=1,this.value>Ec?null:this.value}reset(){this.value=0}}const Ac={from:e=>({sid:e.sid,pubHandle:e.pubHandle,name:e.name,usesE2ee:e.encryption!==ft.NONE}),toProtobuf:e=>new bt({sid:e.sid,pubHandle:e.pubHandle,name:e.name,encryption:e.usesE2ee?ft.GCM:ft.NONE})};var Lc;!function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(Lc||(Lc={}));class Nc{constructor(){this.pendingTasks=new Map,this.taskMutex=new r,this.nextTaskIndex=0}run(e){return pr(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Lc.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Lc.RUNNING,yield e()}finally{t.status=Lc.COMPLETED,this.pendingTasks.delete(t.id),n()}}))}flush(){return pr(this,void 0,void 0,(function*(){return this.run((()=>pr(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}const xc=["client"];var Uc=class{constructor(){N(this,"listeners",new Map)}on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),{off:()=>{n.delete(t)}}}emit(e,t){const n=this.listeners.get("*");if(n)for(const r of n)r(e,t);const i=this.listeners.get(e);if(i)for(const r of i)r(t)}clear(){this.listeners.clear()}},Fc=class extends Error{constructor(e,t){super("non-serializable value at ".concat(e," (").concat(t,")")),this.path=e,this.label=t}};const Bc=(e,t,n)=>{if(null===e)return null;switch(typeof e){case"string":case"boolean":return e;case"number":if(!Number.isFinite(e))throw new Fc(t,qc(e));return e;case"object":return jc(e,t,n);default:throw new Fc(t,typeof e)}},jc=(e,t,n)=>{var i,r;if(n.has(e))throw new Fc(t,"circular reference");if(Array.isArray(e)){if(e.length!==Object.keys(e).length)throw new Fc(t,"sparse array or array with non-index properties");n.add(e);const i=e.map(((e,i)=>Bc(e,"".concat(t,"[").concat(i,"]"),n)));return n.delete(e),i}const a=Object.getPrototypeOf(e);if(a!==Object.prototype&&null!==a)throw new Fc(t,null!==(i=null===(r=e.constructor)||void 0===r?void 0:r.name)&&void 0!==i?i:"object");n.add(e);const s={};for(const o of Object.keys(e)){const i=Bc(e[o],"".concat(t,".").concat(o),n);Object.defineProperty(s,o,{value:i,enumerable:!0,writable:!0,configurable:!0})}return n.delete(e),s},qc=e=>Number.isNaN(e)?"NaN":e>0?"Infinity":"-Infinity",Vc=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new Set;if(null===e||"object"!=typeof e)return e;if(t.has(e))return e;if(Array.isArray(e)){t.add(e);const n=e.map((e=>Vc(e,t)));return t.delete(e),n}const n=Object.getPrototypeOf(e);if(n!==Object.prototype&&null!==n)return e;t.add(e);const i={};for(const r of Object.keys(e)){const n=Vc(e[r],t);Object.defineProperty(i,r,{value:n,enumerable:!0,writable:!0,configurable:!0})}return t.delete(e),i},Wc=Symbol("machina.type");var Hc=class{constructor(e){N(this,"id",void 0),N(this,"initialState",void 0),N(this,Wc,"BehavioralFsm"),N(this,"states",void 0),N(this,"emitter",new Uc),N(this,"clients",new WeakMap),N(this,"knownClients",new Set),N(this,"childSubscriptions",[]),N(this,"disposed",!1),N(this,"transitionDepth",0),this.id=e.id,this.initialState=e.initialState,this.states=e.states,this.wrapChildLinks(),this.setupChildSubscriptions()}handle(e,t){var n;if(this.disposed)return;const i=this.getOrCreateClientMeta(e);for(var r=arguments.length,a=new Array(r>2?r-2:0),s=2;s<r;s++)a[s-2]=arguments[s];i.currentActionArgs=a;const o=null===(n=this.states[i.state])||void 0===n?void 0:n._child;if(o&&o.canHandle(e,t))try{o.handle(e,t,...a)}finally{i.currentActionArgs=void 0}else this.handleLocally(e,t,a,i)}canHandle(e,t){var n,i,r;if(this.disposed)return!1;const a=null!==(n=null===(i=this.clients.get(e))||void 0===i?void 0:i.state)&&void 0!==n?n:this.initialState,s=this.states[a];if(null!==(r=null==s?void 0:s[t])&&void 0!==r?r:null==s?void 0:s["*"])return!0;const o=null==s?void 0:s._child;return!!o&&o.canHandle(e,t)}reset(e){this.disposed||this.transition(e,this.initialState)}currentState(e){var t;return null===(t=this.clients.get(e))||void 0===t?void 0:t.state}transition(e,t){if(this.disposed)return;const n=this.getOrCreateClientMeta(e),i=n.state;if(t!==i)if(Object.hasOwn(this.states,t)){if(this.transitionDepth++,this.transitionDepth>20)throw this.transitionDepth=0,new Error("Max transition depth (".concat(20,') exceeded in FSM "').concat(this.id,'". Likely an infinite _onEnter → transition loop.'));try{const r=this.states[i],a=this.states[t];if(null!=r&&r._onExit&&"function"==typeof r._onExit){const t=this.buildHandlerArgs(e,"",n);r._onExit(t)}n.state=t;const s={fromState:i,toState:t,client:e};let o;if(this.emitter.emit("transitioning",s),null!=a&&a._onEnter&&"function"==typeof a._onEnter){const t=this.buildHandlerArgs(e,"",n);o=a._onEnter(t)}this.emitter.emit("transitioned",s);const c=null==a?void 0:a._child;c&&c.reset(e),this.processQueue(e,n),"string"==typeof o&&n.state===t&&this.transition(e,o)}finally{this.transitionDepth--}}else this.emitter.emit("invalidstate",{stateName:t,client:e})}compositeState(e){var t;const n=this.clients.get(e);if(!n)return"";const i=null===(t=this.states[n.state])||void 0===t?void 0:t._child;if(i){const t=i.compositeState(e);if(t)return"".concat(n.state,".").concat(t)}return n.state}rehydrate(e,t){if(this.disposed)return;if("string"==typeof t)return void this.rehydrateCompositePath(e,t);const n=this.planSnapshotWrites(e,t);for(const i of n)i()}dehydrate(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const n=this.clients.get(e);if(!n)return;const i={state:n.state,deferred:n.deferredQueue.map((e=>this.snapshotDeferredInput(e)))},r=this.collectChildSnapshots(e,n.state,t);return r&&(i.children=r),i}planSnapshotWrites(e,t){if(this.disposed)return[];const n=t.state,i=t.deferred,r=t.children;if(!Object.hasOwn(this.states,n))throw new Error('rehydrate: unknown state "'.concat(n,'" in FSM "').concat(this.id,'". Valid states: ').concat(Object.keys(this.states).join(", ")));const a=[];if(r)for(const c of Object.keys(r)){var s;if(!Object.hasOwn(this.states,c))throw new Error('rehydrate: unknown state "'.concat(c,'" in FSM "').concat(this.id,'" referenced by snapshot.children.'));const t=null===(s=this.states[c])||void 0===s?void 0:s._child;if(!t)throw new Error('rehydrate: state "'.concat(c,'" in FSM "').concat(this.id,'" has no _child, but the snapshot has a children["').concat(c,'"] entry.'));a.push(...t.planRehydrate(e,r[c]))}const o=i.map((e=>function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?U(Object(n),!0).forEach((function(t){N(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):U(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({inputName:e.inputName,args:Vc(e.args)},void 0!==e.untilState?{untilState:e.untilState}:{})));return a.push((()=>{this.clients.has(e)||this.knownClients.add(new WeakRef(e)),this.clients.set(e,{state:n,deferredQueue:o})})),a}rehydrateCompositePath(e,t){const n=B(t.split(".")),i=n[0],r=A(n).slice(1);if(!Object.hasOwn(this.states,i))throw new Error('rehydrate: unknown state "'.concat(i,'" in FSM "').concat(this.id,'". Valid states: ').concat(Object.keys(this.states).join(", ")));if(r.length>0){var a;const n=r.join("."),s=null===(a=this.states[i])||void 0===a?void 0:a._child;if(!s)throw new Error('rehydrate: state "'.concat(i,'" in FSM "').concat(this.id,'" has no _child, but composite path "').concat(t,'" requires one.'));s.rehydrate(e,n)}this.clients.has(e)||this.knownClients.add(new WeakRef(e)),this.clients.set(e,{state:i,deferredQueue:[]})}collectChildSnapshots(e,t,n){const i=new Map;for(const s of Object.keys(this.states)){var r;const e=null===(r=this.states[s])||void 0===r?void 0:r._child;if(!e)continue;const t=i.get(e.instance);t?t.stateNames.push(s):i.set(e.instance,{childLink:e,stateNames:[s]})}let a;for(const s of i.values()){const i=s.childLink,r=s.stateNames,o=n&&r.includes(t);if("Fsm"===i.instance[Wc]&&!o)continue;const c=i.dehydrate(e,o);if(c){null!=a||(a={});for(const e of r)a[e]=c}}return a}snapshotDeferredInput(e){let t;try{n=e.args,t=Bc(n,"args",new Set)}catch(r){if(!(r instanceof Fc))throw r;const t=e.untilState?' (until "'.concat(e.untilState,'")'):"";throw new Error('dehydrate: deferred input "'.concat(e.inputName,'"').concat(t,' in FSM "').concat(this.id,'" has a non-serializable value at ').concat(r.path," (").concat(r.label,")"))}var n;const i={inputName:e.inputName,args:t};return void 0!==e.untilState&&(i.untilState=e.untilState),i}on(e,t){return this.disposed?{off(){}}:this.emitter.on(e,t)}emit(e,t){this.disposed||this.emitter.emit(e,t)}dispose(e){this.disposed=!0;for(const n of this.childSubscriptions)n.off();if(null==e||!e.preserveChildren){const e=new Set;for(const n of Object.keys(this.states)){var t;const i=null===(t=this.states[n])||void 0===t?void 0:t._child;i&&!e.has(i.instance)&&(e.add(i.instance),i.dispose())}}this.emitter.clear()}wrapChildLinks(){for(const e of Object.keys(this.states)){const t=this.states[e],n=null==t?void 0:t._child;if(n){if("object"!=typeof n)throw new Error('State "'.concat(e,'"._child: expected an Fsm or BehavioralFsm instance, got ').concat(String(n)));if(!(Wc in n))throw new Error('State "'.concat(e,'"._child: expected an Fsm or BehavioralFsm instance, got a plain object'));t._child=Kc(n)}}}setupChildSubscriptions(){const e=new Set;for(const n of Object.keys(this.states)){var t;const i=null===(t=this.states[n])||void 0===t?void 0:t._child;if(!i||e.has(i.instance))continue;e.add(i.instance);const r=i.onAny(((e,t)=>{if("nohandler"===e){var n;const e=t;if(void 0!==e.client)this.bubbleNohandler(e.client,i,e.inputName,null!==(n=e.args)&&void 0!==n?n:[]);else for(const t of this.knownClients){var r;const n=t.deref();void 0!==n?this.bubbleNohandler(n,i,e.inputName,null!==(r=e.args)&&void 0!==r?r:[]):this.knownClients.delete(t)}return}const a=t;if(a&&"object"==typeof a&&"client"in a)this.isChildActiveForClient(a.client,i)&&this.emitter.emit(e,t);else for(const s of this.knownClients){const n=s.deref();if(n){if(this.isChildActiveForClient(n,i)){this.emitter.emit(e,t);break}}else this.knownClients.delete(s)}}));this.childSubscriptions.push(r)}}bubbleNohandler(e,t,n,i){if(!this.isChildActiveForClient(e,t))return;const r=this.clients.get(e);r.currentActionArgs=i,this.handleLocally(e,n,i,r)}isChildActiveForClient(e,t){var n;const i=this.clients.get(e);return!!i&&(null===(n=this.states[i.state])||void 0===n||null===(n=n._child)||void 0===n?void 0:n.instance)===t.instance}handleLocally(e,t,n,i){var r;const a=this.states[i.state],s=null!==(r=null==a?void 0:a[t])&&void 0!==r?r:null==a?void 0:a["*"];if(!s)return this.emitter.emit("nohandler",{inputName:t,args:n,client:e}),void(i.currentActionArgs=void 0);try{this.emitter.emit("handling",{inputName:t,client:e});const r=this.buildHandlerArgs(e,t,i);let a;"string"==typeof s?a=s:"function"==typeof s&&(a=s(r,...n)),this.emitter.emit("handled",{inputName:t,client:e}),"string"==typeof a&&this.transition(e,a)}finally{i.currentActionArgs=void 0}}getOrCreateClientMeta(e){let t=this.clients.get(e);return t||(t={state:void 0,deferredQueue:[]},this.clients.set(e,t),this.knownClients.add(new WeakRef(e)),this.transition(e,this.initialState),t)}buildHandlerArgs(e,t,n){return{ctx:e,inputName:t,defer:i=>{if(!n.currentActionArgs)return;const r={inputName:t,args:[...n.currentActionArgs],untilState:null==i?void 0:i.until};n.deferredQueue.push(r),this.emitter.emit("deferred",{inputName:t,client:e})},emit:(e,t)=>{this.emitter.emit(e,t)}}}processQueue(e,t){const n=[],i=[];for(const r of t.deferredQueue)void 0===r.untilState||r.untilState===t.state?n.push(r):i.push(r);t.deferredQueue=i;for(const r of n)this.handle(e,r.inputName,...r.args)}};function Kc(e){if(!e||"object"!=typeof e)throw new Error("createChildLink: expected an Fsm or BehavioralFsm instance, got ".concat(String(e)));const t=e[Wc];if("BehavioralFsm"===t)return{instance:e,canHandle:(t,n)=>e.canHandle(t,n),handle(t,n){for(var i=arguments.length,r=new Array(i>2?i-2:0),a=2;a<i;a++)r[a-2]=arguments[a];e.handle(t,n,...r)},reset(t){e.transition(t,e.initialState)},onAny:t=>e.on("*",t),compositeState:t=>e.compositeState(t),rehydrate(t,n){e.rehydrate(t,n)},dehydrate:(t,n)=>e.dehydrate(t,n),planRehydrate:(t,n)=>e.planSnapshotWrites(t,n),dispose(){e.dispose()}};if("Fsm"===t)return{instance:e,canHandle:(t,n)=>e.canHandle(n),handle(t,n){for(var i=arguments.length,r=new Array(i>2?i-2:0),a=2;a<i;a++)r[a-2]=arguments[a];e.handle(n,...r)},reset(t){e.reset()},onAny:t=>e.on("*",t),compositeState:t=>e.compositeState(),rehydrate(e,t){throw new Error("rehydrate: cannot rehydrate an Fsm child. Fsm owns its own context; rehydrate is only valid for BehavioralFsm hierarchies.")},dehydrate(e,t){throw new Error("dehydrate: cannot dehydrate an Fsm child. Fsm owns its own context; dehydrate is only valid for BehavioralFsm hierarchies.")},planRehydrate(e,t){throw new Error("rehydrate: cannot rehydrate an Fsm child. Fsm owns its own context; rehydrate is only valid for BehavioralFsm hierarchies.")},dispose(){e.dispose()}};throw new Error("createChildLink: expected an Fsm or BehavioralFsm instance, got [MACHINA_TYPE] = ".concat(String(null!=t?t:"undefined")))}var zc=class{constructor(e){var t;N(this,"id",void 0),N(this,"initialState",void 0),N(this,Wc,"Fsm"),N(this,"states",void 0),N(this,"bfsm",void 0),N(this,"context",void 0),N(this,"emitter",new Uc),N(this,"disposed",!1),this.id=e.id,this.initialState=e.initialState,this.context=null!==(t=e.context)&&void 0!==t?t:{},this.bfsm=new Hc(e),this.states=e.states,this.bfsm.on("*",((e,t)=>{if(t&&"object"==typeof t&&"client"in t){t.client;const n=function(e,t){if(null==e)return{};var n,i,r=function(e,t){if(null==e)return{};var n={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;n[i]=e[i]}return n}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}(t,xc);this.emitter.emit(e,n)}else this.emitter.emit(e,t)})),this.bfsm.transition(this.context,e.initialState)}handle(e){if(!this.disposed){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];this.bfsm.handle(this.context,e,...n)}}canHandle(e){return!this.disposed&&this.bfsm.canHandle(this.context,e)}reset(){this.disposed||this.bfsm.reset(this.context)}currentState(){return this.bfsm.currentState(this.context)}transition(e){this.disposed||this.bfsm.transition(this.context,e)}compositeState(){return this.bfsm.compositeState(this.context)}on(e,t){return this.disposed?{off(){}}:this.emitter.on(e,t)}emit(e,t){this.disposed||this.bfsm.emit(e,t)}dispose(e){this.disposed=!0,this.bfsm.dispose(e),this.emitter.clear()}};function Gc(e,t){return t.attemptId===e.attemptId}const Jc=(e,t)=>{if(Gc(e.ctx,t))return"connected"},Qc=e=>{let t=e.ctx;return t.attemptId+=1,t.lastError=void 0,"connecting"},Yc=e=>{let t=e.ctx;return t.attemptId+=1,t.lastError=void 0,"reconnecting"},Xc=(e,t)=>(e.ctx.closeReason=t.reason,"disconnecting"),Zc={new:{connect:Qc,close:Xc},connecting:{connectComplete:Jc,connectFailed:(e,t)=>(e.ctx.lastError=t.error,"closed"),close:Xc},connected:{reconnect:Yc,transportFailed:(e,t)=>{let n=e.ctx;if(Gc(n,t))return n.lastError=t.reason,"offline"},close:Xc},offline:{connect:Qc,reconnect:Yc,close:Xc},reconnecting:{reconnectComplete:Jc,reconnectFailed:(e,t)=>(e.ctx.lastError=t.error,t.recoverable?"offline":"closed"),close:Xc},disconnecting:{closeComplete:"closed"},closed:{connect:Qc,reconnect:Yc}};function $c(){return new zc({id:"signal",initialState:arguments.length>0&&void 0!==arguments[0]?arguments[0]:"new",context:{attemptId:0},states:Zc})}class ed{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n,i;if(null===(n=t.signal)||void 0===n?void 0:n.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const r=new WebSocket(e,null!==(i=t.protocols)&&void 0!==i?i:[]);r.binaryType="arraybuffer",this.ws=r;const a=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.closeCode,n=e.reason;return r.close(t,n)};this.opened=new _a(((e,t)=>{const n=()=>{t(za.websocket("Encountered websocket error during connection establishment"))};r.onopen=()=>{e({readable:new ReadableStream({start(e){r.onmessage=t=>{let n=t.data;return e.enqueue(n)},r.onerror=t=>e.error(za.websocket(t instanceof Error?"".concat(t.name,": ").concat(t.message):"Encountered unknown websocket error: ".concat(String(t)))),r.onclose=t=>{t.wasClean?e.close():e.error(za.websocket("WS closed unexpectedly with code ".concat(t.code)))}},cancel:a}),writable:new WritableStream({write(e){r.send(e)},abort(){r.close()},close:a}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",n)},r.addEventListener("error",n)})),this.closed=new _a(((e,t)=>{const n=()=>pr(this,void 0,void 0,(function*(){const n=new _a((e=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",(t=>{e(t)}),{once:!0})})),i=yield _a.race([qs(250),n]);i?e(i):t(za.websocket("Encountered unspecified websocket error without a timely close event"))}));r.addEventListener("close",(t=>{let i=t.code,a=t.reason;e({closeCode:i,reason:a}),r.removeEventListener("error",n)})),r.addEventListener("error",n)})),t.signal&&(t.signal.onabort=()=>r.close()),this.close=a}}const td=["syncState","trickle","offer","answer","simulate","leave"];var nd;!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTING=3]="DISCONNECTING",e[e.DISCONNECTED=4]="DISCONNECTED"}(nd||(nd={}));class id{get currentState(){return function(e){switch(e){case"connected":return nd.CONNECTED;case"connecting":return nd.CONNECTING;case"reconnecting":return nd.RECONNECTING;case"disconnecting":return nd.DISCONNECTING;default:return nd.DISCONNECTED}}(this.lifecycleState)}get isDisconnected(){const e=this.currentState;return e===nd.DISCONNECTING||e===nd.DISCONNECTED}get lifecycleState(){return this.machine.currentState()}get attemptId(){return this.machine.context.attemptId}sendLifecycleInput(e){const t=this.lifecycleState;return this.machine.handle(e.type,e),this.lifecycleState!==t}settleInFlightClose(){return pr(this,void 0,void 0,(function*(){this.log.debug("waiting for an in-flight close to settle before establishing a session"),(yield this.closingLock.lock())()}))}get isEstablishingConnection(){return"connecting"===this.lifecycleState||"reconnecting"===this.lifecycleState}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;this.rtt=0,this.log=ar,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.loggerContextCb=n.loggerContextCb,this.log=or(null!==(i=n.loggerName)&&void 0!==i?i:e.LoggerNames.Signal,(()=>this.logContext)),this.useJSON=t,this.requestQueue=new Nc,this.queuedRequests=[],this.closingLock=new r,this.connectionLock=new r,this.machine=$c(),this.machine.on("transitioned",(e=>{let t=e.fromState,n=e.toState;this.log.debug("signal lifecycle: ".concat(t," -> ").concat(n))})),this.machine.on("nohandler",(e=>{let t=e.inputName;this.log.debug("ignoring signal lifecycle input ".concat(t," in state ").concat(this.lifecycleState))})),this.machine}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,r){return pr(this,arguments,void 0,(function(e,t,i,r){var a=this;let s=arguments.length>4&&void 0!==arguments[4]&&arguments[4],o=arguments.length>5?arguments[5]:void 0;return function*(){if("disconnecting"===a.lifecycleState&&(yield a.settleInFlightClose()),!a.sendLifecycleInput({type:"connect"}))throw za.internal("cannot establish a signal session from '".concat(a.lifecycleState,"', close the current one first"));a.options=i;try{return yield a.connect(e,t,i,r,s,o)}catch(n){throw a.sendLifecycleInput({type:"connectFailed",error:n}),n}}()}))}reconnect(t,i,r,a){return pr(this,void 0,void 0,(function*(){if(this.options){if("disconnecting"===this.lifecycleState&&(yield this.settleInFlightClose()),!this.sendLifecycleInput({type:"reconnect"}))throw za.internal("cannot resume the signal session from '".concat(this.lifecycleState,"'"));this.clearPingInterval();try{return yield this.connect(t,i,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:r,reconnectReason:a}),void 0,this.useV0SignalPath)}catch(n){throw this.sendLifecycleInput({type:"reconnectFailed",error:n,recoverable:(s=n,!(s instanceof za)||s.reason!==e.ConnectionErrorReason.LeaveRequest&&s.reason!==e.ConnectionErrorReason.NotAllowed)}),n}var s}else this.log.warn("attempted to reconnect without signal options being set, ignoring")}))}connect(e,t,i,r){return pr(this,arguments,void 0,(function(e,t,i,r){var a=this;let s=arguments.length>4&&void 0!==arguments[4]&&arguments[4],o=arguments.length>5?arguments[5]:void 0;return function*(){const c=yield a.connectionLock.lock();a.connectOptions=i,a.useV0SignalPath=s;const d=function(e){var t;const n=new Qt({capabilities:e,sdk:Yt.JS,protocol:17,clientProtocol:2,version:xa});return io()&&(n.os=null!==(t=oo())&&void 0!==t?t:""),n}(i.clientInfoCapabilities),l=s?function(e,t,n){var i;const r=new URLSearchParams;r.set("access_token",e),n.reconnect&&(r.set("reconnect","1"),n.sid&&r.set("sid",n.sid));r.set("auto_subscribe",n.autoSubscribe?"1":"0"),r.set("sdk",io()?"reactnative":"js"),r.set("version",t.version),r.set("protocol",t.protocol.toString()),r.set("client_protocol",t.clientProtocol.toString()),t.deviceModel&&r.set("device_model",t.deviceModel);t.os&&r.set("os",t.os);t.osVersion&&r.set("os_version",t.osVersion);t.browser&&r.set("browser",t.browser);t.browserVersion&&r.set("browser_version",t.browserVersion);n.adaptiveStream&&r.set("adaptive_stream","1");n.reconnectReason&&r.set("reconnect_reason",n.reconnectReason.toString());(null===(i=navigator.connection)||void 0===i?void 0:i.type)&&r.set("network",navigator.connection.type);return r}(t,d,i):yield function(e,t,n,i){return pr(this,void 0,void 0,(function*(){const r=new URLSearchParams;r.set("access_token",e);const a=new zi({clientInfo:t,connectionSettings:new Ki({autoSubscribe:!!n.autoSubscribe,adaptiveStream:!!n.adaptiveStream}),reconnect:!!n.reconnect,participantSid:n.sid?n.sid:void 0,publisherOffer:i});n.reconnectReason&&(a.reconnectReason=n.reconnectReason);const s=a.toBinary();let o,c;if(Fo()){const e=new CompressionStream("gzip"),t=e.writable.getWriter();t.write(new Uint8Array(s)),t.close();const n=[],i=e.readable.getReader();for(;;){const e=yield i.read(),t=e.done,r=e.value;if(t)break;n.push(r)}const r=n.reduce(((e,t)=>e+t.length),0),a=new Uint8Array(r);let d=0;for(const s of n)a.set(s,d),d+=s.length;o=a,c=Ji.GZIP}else o=s,c=Ji.NONE;const d=new Gi({joinRequest:o,compression:c}).toBinary(),l=e=>{const t=Array.from(e,(e=>String.fromCodePoint(e))).join("");return btoa(t)};return r.set("join_request",l(d).replace(/\+/g,"-").replace(/\//g,"_")),r}))}(t,d,i,o),u=jo(e,l,s).toString(),h=(p=u,Vo(new URL(Co(p)),"validate")).toString();var p;return new Promise(((e,t)=>pr(a,void 0,void 0,(function*(){var a,s;try{let o=!1;const c=e=>pr(this,void 0,void 0,(function*(){if(o)return;o=!0;const n=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unknown reason";if(e instanceof Error)return e.message;if(!(e instanceof AbortSignal))return t;const n=e.reason;switch(typeof n){case"string":return n;case"object":return n instanceof Error?n.message:t;default:return"toString"in n?n.toString():t}}(e instanceof Event?e.currentTarget:e,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then((()=>this.close(n))).catch((e=>{this.log.error(e),this.close()})):this.close(),d(),t(e instanceof za?e:za.cancelled(n))}));null==r||r.addEventListener("abort",c);const d=()=>{clearTimeout(l),null==r||r.removeEventListener("abort",c)},l=setTimeout((()=>{c(za.timeout("room connection has timed out (signal)"))}),i.websocketTimeout),p=new URL(u);if(p.searchParams.has("access_token")&&p.searchParams.set("access_token","<redacted>"),this.ws){const e=performance.now();yield this.teardownTransport("replaced by a new connection attempt"),this.log.debug("closed previous ws connection in ".concat(performance.now()-e,"ms"))}const m=this.attemptId;this.log.info("signal connecting to ".concat(p),{reconnect:i.reconnect,reconnectReason:i.reconnectReason}),this.ws=new ed(u);let g=!1;this.ws.opened.catch((()=>{g=!0}));try{this.ws.closed.then((e=>{this.isEstablishingConnection&&!g&&t(za.internal("Websocket got closed during a (re)connection attempt: ".concat(e.reason))),this.log.debug("websocket closed",{reason:e.reason,code:e.closeCode,attemptId:m,state:this.lifecycleState}),this.handleOnClose(e.reason||(1e3===e.closeCode?"server closed the signal connection":"Unexpected WS error"),m)})).catch((e=>{this.isEstablishingConnection&&!g&&t(za.internal("Websocket error during a (re)connection attempt: ".concat(e)))}));const r=yield this.ws.opened.catch((e=>pr(this,void 0,void 0,(function*(){if("connected"===this.lifecycleState)this.handleWSError(e),t(e);else{clearTimeout(l);const n=yield this.handleConnectionError(e,h);t(n)}}))));if(clearTimeout(l),!r)return;const o=r.readable.getReader();let c,d;this.streamWriter=r.writable.getWriter();try{c=yield Promise.race([o.read(),new Promise(((e,t)=>{d=setTimeout((()=>{t(za.timeout("signal connection timed out while waiting for the first message"))}),5e3)}))])}catch(n){return o.releaseLock(),t(n),void this.close()}finally{clearTimeout(d)}if(o.releaseLock(),!c.value)throw za.internal("no message received as first message");const u=Wo(c.value),p=this.validateFirstMessage(u,null!==(a=i.reconnect)&&void 0!==a&&a);if(!p.isValid)return void t(p.error);"join"===(null===(s=u.message)||void 0===s?void 0:s.case)&&(this.pingTimeoutDuration=u.message.value.pingTimeout,this.pingIntervalDuration=u.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.onJoined&&this.onJoined(u.message.value));const v=p.shouldProcessFirstMessage?u:void 0;this.handleSignalConnected(r,l,m,v),e(p.response)}catch(n){t(n)}finally{d()}}finally{c()}}))))}()}))}startReadingLoop(e,t){return pr(this,void 0,void 0,(function*(){t&&this.handleSignalResponse(t);const i=this.attemptId;for(;;){this.signalLatency&&(yield qs(this.signalLatency));try{const t=yield e.read(),n=t.done,i=t.value;if(n)break;const r=Wo(i);this.handleSignalResponse(r)}catch(n){this.log.error("error reading from signal stream",{error:n}),yield this.handleOnClose("error in reading loop",i);break}}}))}close(){return pr(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Close method called on signal client";return function*(){const i=t&&e.sendLifecycleInput({type:"close",reason:n}),r=yield e.closingLock.lock();try{yield e.teardownTransport(n)}finally{i&&e.sendLifecycleInput({type:"closeComplete"}),r()}}()}))}teardownTransport(e){return pr(this,void 0,void 0,(function*(){try{if(this.clearPingInterval(),this.ws){this.ws.close({closeCode:1e3,reason:e});const t=this.ws.closed;this.ws=void 0,this.streamWriter=void 0,yield Promise.race([t,qs(250)])}}catch(n){this.log.debug("websocket error while closing",{error:n})}}))}sendOffer(e,t){this.log.debug("sending offer",{offerSdp:e.sdp}),this.sendRequest({case:"offer",value:ad(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",{answerSdp:e.sdp}),this.sendRequest({case:"answer",value:ad(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",{candidate:e}),this.sendRequest({case:"trickle",value:new Yn({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Xn({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return pr(this,arguments,void 0,(function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const r=n.getNextRequestId();return yield n.sendRequest({case:"updateMetadata",value:new fi({requestId:r,metadata:e,name:t,attributes:i})}),r}()}))}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 vi({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Mi({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:R.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Ui({timestamp:R.parse(Date.now()),rtt:R.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new hi({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new mi({reason:at.CLIENT_INITIATED,action:gi.DISCONNECT})})}sendPublishDataTrackRequest(e,t,n){return this.sendRequest({case:"publishDataTrackRequest",value:new Hn({pubHandle:e,name:t,encryption:n?ft.GCM:ft.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:"unpublishDataTrackRequest",value:new zn({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:"updateDataSubscription",value:new ai({updates:[new si({trackSid:e,subscribe:t})]})})}sendRequest(e){return pr(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){const r=!i&&!function(e){const t=td.indexOf(e.case)>=0;return ar.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e),a="reconnecting"===t.lifecycleState||t.queuedRequests.length>0;if(r&&a)return void t.queuedRequests.push((()=>pr(t,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));i||(yield t.requestQueue.flush()),t.signalLatency&&(yield qs(t.signalLatency));const s="leave"===e.case&&!!t.streamWriter;if(t.isDisconnected&&!s)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));const o=new jn({message:e});try{t.useJSON?yield t.streamWriter.write(o.toJsonString()):yield t.streamWriter.write(o.toBinary().buffer)}catch(n){t.log.error("error sending signal message",{error:n})}}()}))}handleSignalResponse(e){var t,n;const i=e.message;if(null==i)return void this.log.debug("received unsupported message");let r=!1;if("answer"===i.case){const e=rd(i.value);this.onAnswer&&this.onAnswer(e,i.value.id,i.value.midToTrackId)}else if("offer"===i.case){const e=rd(i.value);this.onOffer&&this.onOffer(e,i.value.id,i.value.midToTrackId)}else if("trickle"===i.case){const e=JSON.parse(i.value.candidateInit);this.onTrickle&&this.onTrickle(e,i.value.target)}else"update"===i.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=i.value.participants)&&void 0!==t?t:[]):"trackPublished"===i.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(i.value):"speakersChanged"===i.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(n=i.value.speakers)&&void 0!==n?n:[]):"leave"===i.case?this.onLeave&&this.onLeave(i.value):"mute"===i.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(i.value.sid,i.value.muted):"roomUpdate"===i.case?this.onRoomUpdate&&i.value.room&&this.onRoomUpdate(i.value.room):"connectionQuality"===i.case?this.onConnectionQuality&&this.onConnectionQuality(i.value):"streamStateUpdate"===i.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(i.value):"subscribedQualityUpdate"===i.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(i.value):"subscriptionPermissionUpdate"===i.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(i.value):"refreshToken"===i.case?this.onTokenRefresh&&this.onTokenRefresh(i.value):"trackUnpublished"===i.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(i.value):"subscriptionResponse"===i.case?this.onSubscriptionError&&this.onSubscriptionError(i.value):"pong"===i.case||("pongResp"===i.case?(this.rtt=Date.now()-Number.parseInt(i.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):"requestResponse"===i.case?this.onRequestResponse&&this.onRequestResponse(i.value):"trackSubscribed"===i.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(i.value.trackSid):"roomMoved"===i.case?(this.onTokenRefresh&&this.onTokenRefresh(i.value.token),this.onRoomMoved&&this.onRoomMoved(i.value)):"mediaSectionsRequirement"===i.case?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(i.value):"publishDataTrackResponse"===i.case?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(i.value):"unpublishDataTrackResponse"===i.case?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(i.value):"dataTrackSubscriberHandles"===i.case?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(i.value):this.log.debug("unsupported message",{msgCase:i.case}));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return pr(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.attemptId;return function*(){const i=t.onClose;t.sendLifecycleInput({type:"transportFailed",attemptId:n,reason:e})?(yield t.teardownTransport(e),t.log.info("websocket connection closed: ".concat(e),{reason:e}),i&&i(e)):t.log.debug("ignoring transport close in state ".concat(t.lifecycleState),{reason:e,attemptId:n,currentAttemptId:t.attemptId})}()}))}handleWSError(e){this.log.error("websocket error",{error:e})}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=is.setTimeout((()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString())),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set")}clearPingTimeout(){this.pingTimeout&&is.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval"),this.pingInterval=is.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set")}clearPingInterval(){this.log.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&is.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n,i){clearTimeout(t);this.sendLifecycleInput("reconnecting"===this.lifecycleState?{type:"reconnectComplete",attemptId:n}:{type:"connectComplete",attemptId:n})?(this.log.info("signal connected"),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)):this.log.debug("discarding a connection whose attempt no longer owns the session",{attemptId:n,currentAttemptId:this.attemptId,state:this.lifecycleState})}validateFirstMessage(e,t){var n,i,r,a,s;return"join"===(null===(n=e.message)||void 0===n?void 0:n.case)?{isValid:!0,response:e.message.value}:"reconnecting"===this.lifecycleState&&"leave"!==(null===(i=e.message)||void 0===i?void 0:i.case)?"reconnect"===(null===(r=e.message)||void 0===r?void 0:r.case)?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received"),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&"leave"===(null===(a=e.message)||void 0===a?void 0:a.case)?{isValid:!1,error:za.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:za.internal("Unexpected first message")}:{isValid:!1,error:za.internal("did not receive join response, got ".concat(null===(s=e.message)||void 0===s?void 0:s.case," instead"))}}handleConnectionError(e,t){return pr(this,void 0,void 0,(function*(){try{const n=yield fetch(t);switch(n.status){case 404:const e=yield n.text();return e.includes("requested room does not exist")?za.notAllowed(e,n.status):za.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const t=yield n.text();return za.notAllowed(t,n.status)}return e instanceof za?e:za.internal("Encountered unknown websocket error during connection: ".concat(e),{status:n.status,statusText:n.statusText})}catch(n){return n instanceof za?n:za.serverUnreachable(n instanceof Error?n.message:"server was not reachable")}}))}}function rd(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 ad(e,t){return new ni({sdp:e.sdp,type:e.type,id:t})}class sd{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const n=Date.now();n-this._lastCleanup>this.ttl/2&&this.cleanup();const i=n+this.ttl;return this._map.set(e,{value:t,expiresAt:i}),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 n of this._map.entries()){var t=F(n,2);const i=t[0];t[1].expiresAt<e&&this._map.delete(i)}this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const n of this._map.entries()){var t=F(n,2);const i=t[0],r=t[1];r.expiresAt>=Date.now()&&e(r.value,i,this.asValueMap())}}map(e){this.cleanup();const t=[],n=this.asValueMap();for(const r of n.entries()){var i=F(r,2);const a=i[0],s=i[1];t.push(e(s,a,n))}return t}asValueMap(){const e=new Map;for(const n of this._map.entries()){var t=F(n,2);const i=t[0],r=t[1];r.expiresAt>=Date.now()&&e.set(i,r.value)}return e}}var od,cd,dd,ld,ud,hd={},pd={},md={exports:{}};function gd(){if(od)return md.exports;od=1;var e=md.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")}))})),md.exports}function vd(){return cd||(cd=1,function(e){var t=function(e){return String(Number(e))===e?Number(e):e},n=function(e,n,i){var r=e.name&&e.names;e.push&&!n[e.push]?n[e.push]=[]:r&&!n[e.name]&&(n[e.name]={});var a=e.push?{}:r?n[e.name]:n;!function(e,n,i,r){if(r&&!i)n[r]=t(e[1]);else for(var a=0;a<i.length;a+=1)null!=e[a+1]&&(n[i[a]]=t(e[a+1]))}(i.match(e.reg),a,e.names,e.name),e.push&&n[e.push].push(a)},i=gd(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},a=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(a.push({rtp:[],fmtp:[]}),s=a[a.length-1]);for(var o=0;o<(i[t]||[]).length;o+=1){var c=i[t][o];if(c.reg.test(r))return n(c,s,r)}})),t.media=a,t};var a=function(e,n){var i=n.split(/=(.+)/,2);return 2===i.length?e[i[0]]=t(i[1]):1===i.length&&n.length>1&&(e[i[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(a,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var n=[],i=e.split(" ").map(t),r=0;r<i.length;r+=3)n.push({component:i[r],ip:i[r+1],port:i[r+2]});return n},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(a,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var n,i=!1;return"~"!==e[0]?n=t(e):(n=t(e.substring(1,e.length)),i=!0),{scid:n,paused:i}}))}))}}(pd)),pd}function fd(){if(ld)return dd;ld=1;var e=gd(),t=/%[sdv%]/g,n=function(e){var n=1,i=arguments,r=i.length;return e.replace(t,(function(e){if(n>=r)return e;var t=i[n];switch(n+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}}))},i=function(e,t,i){var r=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var a=0;a<t.names.length;a+=1){var s=t.names[a];t.name?r.push(i[t.name][s]):r.push(i[t.names[a]])}else r.push(i[t.name]);return n.apply(null,r)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];return dd=function(t,n){n=n||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var s=n.outerOrder||r,o=n.innerOrder||a,c=[];return s.forEach((function(n){e[n].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(i(n,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(i(n,e,t))}))}))})),t.media.forEach((function(t){c.push(i("m",e.m[0],t)),o.forEach((function(n){e[n].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(i(n,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(i(n,e,t))}))}))}))})),c.join("\r\n")+"\r\n"},dd}var kd=function(){if(ud)return hd;ud=1;var e=vd(),t=fd(),n=gd();return hd.grammar=n,hd.write=t,hd.parse=e.parse,hd.parseParams=e.parseParams,hd.parseFmtpConfig=e.parseFmtpConfig,hd.parsePayloads=e.parsePayloads,hd.parseRemoteCandidates=e.parseRemoteCandidates,hd.parseImageAttributes=e.parseImageAttributes,hd.parseSimulcastStreamList=e.parseSimulcastStreamList,hd}();const yd="negotiationStarted",bd="negotiationComplete",Td="offerAnswered",Sd="rtpVideoPayloadTypes";class Ed extends br.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(t){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var a;super(),this.log=ar,this.iceLog=ar,this.ddExtID=0,this.latestOfferId=0,this.latestAcknowledgedOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=cc((e=>pr(this,void 0,void 0,(function*(){this.emit(yd);try{yield this.createAndSendOffer()}catch(n){if(!e)throw n;e(n)}}))),20),this.close=()=>{this._pc&&(this.log.debug("closing peer connection"),this.pendingInitialOffer=void 0,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.loggerOptions=i,this.log=or(null!==(a=i.loggerName)&&void 0!==a?a:e.LoggerNames.PCTransport,(()=>this.logContext)),this.iceLog=or(e.LoggerNames.ICE,(()=>this.logContext)),this.config=t,this._pc=this.createPC(),this.offerLock=new r}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(this.iceLog.debug("local ICE candidate gathered",{candidate:e.candidate.candidate}),null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;this.iceLog.debug("ICE candidate error",{event:e}),null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;this.iceLog.debug("ICE connection state: ".concat(e.iceConnectionState)),null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;this.log.debug("signaling state: ".concat(e.signalingState)),null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;this.log.debug("connection state: ".concat(e.connectionState)),null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;this.log.debug("data channel opened by peer",{label:e.channel.label,id:e.channel.id}),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 pr(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.iceLog.debug("queuing remote ICE candidate until remote description applied",{pendingCount:this.pendingCandidates.length+1}),this.pendingCandidates.push(e)}))}setRemoteDescription(e,t){return pr(this,void 0,void 0,(function*(){var n,i;if("answer"===e.type&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",{offerId:t,latestOfferId:this.latestOfferId}),!1;let r;if("offer"===e.type){let t=function(e){var t;const n=[],i=[],r=kd.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let a=0;return r.media.forEach((e=>{var t;const r=_d(e.mid);"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec.toLowerCase()&&(a=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===a&&"nack"===e.type)))&&i.push(r),e.fmtp.some((e=>e.payload===a&&(wd(e.config,"sprop-stereo=1")&&n.push(r),!0))))})),{stereoMids:n,nackMids:i}}(e),n=t.stereoMids,i=t.nackMids;this.remoteStereoMids=n,this.remoteNackMids=i}else if("answer"===e.type){if(this.pendingInitialOffer&&this._pc){const e=this.pendingInitialOffer;this.pendingInitialOffer=void 0;const t=kd.parse(null!==(n=e.sdp)&&void 0!==n?n:"");t.media.forEach((e=>{Id(e)})),this.log.debug("setting pending initial offer before processing answer"),yield this.setMungedSDP(e,kd.write(t))}const t=kd.parse(null!==(i=e.sdp)&&void 0!==i?i:"");t.media.forEach((e=>{const t=_d(e.mid);"audio"===e.type&&this.trackBitrates.some((n=>{if(!n.transceiver||t!=n.transceiver.mid)return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===n.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;let r=!1;for(const t of e.fmtp)if(t.payload===i){t.config=t.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),n.maxbr>0&&(t.config+=";maxaveragebitrate=".concat(1e3*n.maxbr)),r=!0;break}return r||n.maxbr>0&&e.fmtp.push({payload:i,config:"maxaveragebitrate=".concat(1e3*n.maxbr)}),!0}))}));const a=this.getPlaceholderMids();a.size>0&&Pd(t.media,(e=>a.has(_d(e.mid)))),r=kd.write(t)}if(yield this.setMungedSDP(e,r,!0),this.pendingCandidates.length>0&&this.iceLog.debug("flushing queued ICE candidates",{count:this.pendingCandidates.length}),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,"answer"===e.type&&(this.latestAcknowledgedOfferId=t,this.emit(Td,t)),this.renegotiate)this.renegotiate=!1,yield this.createAndSendOffer();else if("answer"===e.type&&(this.emit(bd),e.sdp)){kd.parse(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(Sd,e.rtp)}))}return!0}))}createInitialOffer(){return pr(this,void 0,void 0,(function*(){var e;const t=yield this.offerLock.lock();try{if("stable"!==this.pc.signalingState)return void this.log.warn("signaling state is not stable, cannot create initial offer");const t=this.latestOfferId+1;this.latestOfferId=t;const n=yield this.pc.createOffer();this.pendingInitialOffer={sdp:n.sdp,type:n.type};const i=kd.parse(null!==(e=n.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{Id(e)})),n.sdp=kd.write(i),{offer:n,offerId:t}}finally{t()}}))}createAndSendOffer(e){return pr(this,void 0,void 0,(function*(){var t;const n=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.iceLog.debug("restarting ICE"),this.restartingIce=!0),this._pc&&("have-local-offer"===this._pc.signalingState||this.pendingInitialOffer)){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t){if(null==e?void 0:e.iceRestart)throw new Xa("ICE restart requested without a remote description, peer connection must be recreated");return this.renegotiate=!0,void this.log.debug("requesting renegotiation")}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.log.debug("starting to negotiate");const n=this.latestOfferId+1;this.latestOfferId=n;const i=yield this.pc.createOffer(e);this.log.debug("original offer",{sdp:i.sdp});const r=kd.parse(null!==(t=i.sdp)&&void 0!==t?t:"");r.media.forEach((e=>{Id(e),"audio"===e.type?Rd(e,["all"],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!t.cid)return!1;const n=function(e,t,n,i){let r=arguments.length>4&&void 0!==arguments[4]&&arguments[4];var a,s,o;if(!(null===(a=e.msid)||void 0===a?void 0:a.includes(t)))return;const c=null!==(o=null===(s=e.rtp.find((e=>e.codec.toUpperCase()===n.toUpperCase())))||void 0===s?void 0:s.payload)&&void 0!==o?o:0;if(0===c)return 0;const d=Math.round(.9*i),l=r?d:Math.min(d,1e3),u=e.fmtp.find((e=>e.payload===c));return u?u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(l)):e.fmtp.push({payload:c,config:"x-google-start-bitrate=".concat(l)}),c}(e,t.cid,t.codec,t.maxbr,t.isScreenShare);return void 0!==n&&(n>0&&zs(t.codec)&&!Zs()&&(this.ddExtID=function(e,t,n){var i,r;const a=function(e,t){const n=function(e,t){var n;for(const i of e.media){const e=null===(n=i.ext)||void 0===n?void 0:n.find((e=>e.uri===t));if(e)return e.value}return}(e,Bs);if(void 0!==n)return Cd(e,n,Bs)?void 0:n;if(0!==t&&!Cd(e,t,Bs))return t;return function(e){let t=0;return e.media.forEach((e=>{var n;null===(n=e.ext)||void 0===n||n.forEach((e=>{e.value>t&&(t=e.value)}))})),t+1===15?16:t+1}(e)}(t,n);if(void 0===a)return n;(null===(i=e.ext)||void 0===i?void 0:i.some((e=>e.uri===Bs)))||(null!==(r=e.ext)&&void 0!==r||(e.ext=[]),e.ext.push({value:a,uri:Bs}));return a}(e,r,this.ddExtID)),!0)}))}));const a=this.getPlaceholderMids();if(a.size>0&&Pd(r.media,(e=>a.has(_d(e.mid)))),this.latestOfferId>n)return void this.log.warn("latestOfferId mismatch",{latestOfferId:this.latestOfferId,offerId:n});yield this.setMungedSDP(i,kd.write(r)),this.onOffer(i,this.latestOfferId)}finally{n()}}))}createAndSetAnswer(){return pr(this,void 0,void 0,(function*(){var e;const t=yield this.pc.createAnswer(),n=kd.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return n.media.forEach((e=>{Id(e),"audio"===e.type&&Rd(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,kd.write(n)),t}))}getPlaceholderMids(){var e,t;return function(e){const t=new Set;for(const n of e)n.mid&&!n.sender.track&&t.add(n.mid);return t}(null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?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 Ya("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 Ya("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(){var e;return null===(e=this._pc)||void 0===e?void 0:e.getStats()}getMaxMessageSize(){var e,t;return null===(t=null===(e=this._pc)||void 0===e?void 0:e.sctp)||void 0===t?void 0:t.maxMessageSize}getConnectedAddress(){return pr(this,void 0,void 0,(function*(){var e;if(!this._pc)return;let t="";const n=new Map,i=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),n.set(e.id,e);break;case"remote-candidate":i.set(e.id,"".concat(e.address,":").concat(e.port))}})),""===t)return;const r=null===(e=n.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==r?i.get(r):void 0}))}setMungedSDP(e,t,i){return pr(this,void 0,void 0,(function*(){var r,a;const s=e.sdp;if(t){e.sdp=t;try{return this.log.debug("setting munged ".concat(i?"remote":"local"," description")),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"),{error:n,mungedSdp:t,originalSdp:s}),e.sdp=s}}try{i?yield null===(r=this._pc)||void 0===r?void 0:r.setRemoteDescription(e):yield null===(a=this._pc)||void 0===a?void 0:a.setLocalDescription(e)}catch(n){let a="unknown error";n instanceof Error?a=n.message:"string"==typeof n&&(a=n);const o={error:a,sdp:e.sdp};throw t&&t!==s&&(o.mungedSdp=t),!i&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),{fields:o}),new Xa(a)}}))}}function Cd(e,t,n){return e.media.some((e=>{var i;return null===(i=e.ext)||void 0===i?void 0:i.some((e=>e.value===t&&e.uri!==n))}))}function wd(e,t){return e.split(";").some((e=>e.trim()===t))}function Rd(e,t,n){const i=_d(e.mid);let r=0;e.rtp.some((e=>"opus"===e.codec.toLowerCase()&&(r=e.payload,!0))),r>0&&(e.rtcpFb||(e.rtcpFb=[]),n.includes(i)&&!e.rtcpFb.some((e=>e.payload===r&&"nack"===e.type))&&e.rtcpFb.push({payload:r,type:"nack"}),(t.includes(i)||1===t.length&&"all"===t[0])&&e.fmtp.some((e=>e.payload===r&&(wd(e.config,"stereo=1")||(e.config+=";stereo=1"),!0))))}function Pd(e,t){var n,i;const r=new Map,a=new Set;for(const s of e){const e=t(s);for(const t of null!==(n=s.fmtp)&&void 0!==n?n:[])e?r.has(t.payload)||r.set(t.payload,t.config):(r.set(t.payload,t.config),a.add(t.payload))}if(0!==r.size)for(const s of e)if(t(s))for(const e of null!==(i=s.fmtp)&&void 0!==i?i:[]){const t=r.get(e.payload);void 0!==t&&e.config!==t&&(e.config=t)}}function Id(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 _d(e){return"number"==typeof e?e.toFixed(0):e}const Md="vp8",Dd={audioPreset:e.AudioPresets.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:bs.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Md,backupCodec:!0,preConnectBuffer:!1},Od={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Ad={deviceId:{ideal:"default"},resolution:ks.h720.resolution},Ld={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new ur,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Nd={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var xd,Ud;!function(e){e[e.NEW=0]="NEW",e[e.CONNECTING=1]="CONNECTING",e[e.CONNECTED=2]="CONNECTED",e[e.FAILED=3]="FAILED",e[e.CLOSING=4]="CLOSING",e[e.CLOSED=5]="CLOSED"}(xd||(xd={}));class Fd{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(t,n,i){var a;this.peerConnectionTimeout=Nd.peerConnectionTimeout,this.log=ar,this.iceLog=ar,this.updateState=()=>{var e,t;const n=this.state,i=this.requiredTransports.map((e=>e.getConnectionState()));i.every((e=>"connected"===e))?this.state=xd.CONNECTED:i.some((e=>"failed"===e))?this.state=xd.FAILED:i.some((e=>"connecting"===e))?this.state=xd.CONNECTING:i.every((e=>"closed"===e))?this.state=xd.CLOSED:i.some((e=>"closed"===e))?this.state=xd.CLOSING:i.every((e=>"new"===e))&&(this.state=xd.NEW),n!==this.state&&(this.log.debug("pc state change: from ".concat(xd[n]," to ").concat(xd[this.state])),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.loggerOptions=n,this.log=or(null!==(a=n.loggerName)&&void 0!==a?a:e.LoggerNames.PCManager,(()=>this.logContext)),this.iceLog=or(e.LoggerNames.ICE,(()=>this.logContext)),this.isPublisherConnectionRequired="subscriber-primary"!==t,this.isSubscriberConnectionRequired="subscriber-primary"===t,this.publisher=new Ed(i,n),this._mode=t,"publisher-only"!==t&&(this.subscriber=new Ed(i,n),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,Un.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,Un.PUBLISHER)},this.publisher.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var n;null===(n=this.onPublisherOffer)||void 0===n||n.call(this,e,t)},this.state=xd.NEW,this.connectionLock=new r,this.remoteOfferLock=new r}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 pr(this,void 0,void 0,(function*(){var e;if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(n){this.log.warn("could not removeTrack",{error:n})}}yield Promise.all([this.publisher.close(),null===(e=this.subscriber)||void 0===e?void 0:e.close()]),this.updateState()}))}triggerIceRestart(){return pr(this,void 0,void 0,(function*(){this.iceLog.warn("triggering ICE restart"),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return pr(this,void 0,void 0,(function*(){var n;this.iceLog.debug("adding remote ICE candidate",{target:t,candidate:e}),t===Un.PUBLISHER?yield this.publisher.addIceCandidate(e):yield null===(n=this.subscriber)||void 0===n?void 0:n.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e,t){return pr(this,void 0,void 0,(function*(){var n,i,r;this.log.debug("received server offer",{RTCSdpType:e.type,sdp:e.sdp,signalingState:null===(n=this.subscriber)||void 0===n?void 0:n.getSignallingState().toString()});const a=yield this.remoteOfferLock.lock();try{if(!(yield null===(i=this.subscriber)||void 0===i?void 0:i.setRemoteDescription(e,t)))return;return yield null===(r=this.subscriber)||void 0===r?void 0:r.createAndSetAnswer()}finally{a()}}))}updateConfiguration(e,t){var n;this.log.debug("updating rtc configuration",{iceRestart:t}),this.publisher.setConfiguration(e),null===(n=this.subscriber)||void 0===n||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return pr(this,void 0,void 0,(function*(){var n;const i=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating"),this.publisher.negotiate()),yield Promise.all(null===(n=this.requiredTransports)||void 0===n?void 0:n.map((n=>this.ensureTransportConnected(n,e,t))))}finally{i()}}))}negotiate(e){return pr(this,void 0,void 0,(function*(){return new _a(((t,n)=>{const i=this.publisher.latestOfferId;if(this.publisher.latestAcknowledgedOfferId>i)return this.log.debug("negotiation already handled in more recent acknowledged offer",this.logContext),void t();let r=!1;const a=()=>{r||(r=!0,clearTimeout(c),this.publisher.off(Td,s),e.signal.removeEventListener("abort",o))},s=e=>{e>i&&(a(),t())},o=()=>{a(),n(new Xa("negotiation aborted"))},c=setTimeout((()=>{a(),n(new Xa("negotiation timed out"))}),this.peerConnectionTimeout);e.signal.addEventListener("abort",o),this.publisher.on(Td,s),this.publisher.negotiate((e=>{a(),e instanceof Error?n(e):n(new Error(String(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}getMaxPublisherMessageSize(){return this.publisher.getMaxMessageSize()}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Un.PUBLISHER||e===Un.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 pr(this,arguments,void 0,(function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise(((e,r)=>pr(n,void 0,void 0,(function*(){const n=()=>{this.log.warn("abort transport connection"),is.clearTimeout(a),r(za.cancelled("room connection has been cancelled"))};(null==t?void 0:t.signal.aborted)&&n(),null==t||t.signal.addEventListener("abort",n);const a=is.setTimeout((()=>{null==t||t.signal.removeEventListener("abort",n),r(za.internal("could not establish pc connection"))}),i);for(;this.state!==xd.CONNECTED;)if(yield qs(50),null==t?void 0:t.signal.aborted)return void r(za.cancelled("room connection has been cancelled"));is.clearTimeout(a),null==t||t.signal.removeEventListener("abort",n),e()}))))}()}))}}class Bd{constructor(e){this.bufferStatusLow=!0,this.headroomLock=new r,this.waiterAbortController=new AbortController,this.kind=e.kind,this.lowWaterMark=e.lowWaterMark,this.highWaterMark=e.highWaterMark,this.isEngineClosed=e.isEngineClosed,this.onBufferStatusChanged=e.onBufferStatusChanged}get channelHandle(){return this.handle}attach(e){this.handle&&this.handle!==e&&this.invalidateWaiters("data channel replaced"),this.handle=e}detach(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"data channel torn down";this.handle&&this.invalidateWaiters(e),this.handle=void 0}getChannel(){return this.handle}isBelowHighWaterMark(e){return e.bufferedAmount<=this.highWaterMark}isBelowLowWaterMark(e){return e.bufferedAmount<=e.bufferedAmountLowThreshold}lockHeadroom(){return this.headroomLock.lock()}waitForHeadroomWithLock(){return pr(this,void 0,void 0,(function*(){const e=yield this.lockHeadroom();try{yield this.waitForHeadroomWithoutLock()}finally{e()}}))}waitForHeadroomWithoutLock(){return pr(this,void 0,void 0,(function*(){if(this.isEngineClosed())throw new Ya("engine closed");const e=this.getChannel();if(!e)throw new Ya("DataChannel not found, kind: ".concat(this.kind));if(this.isBelowHighWaterMark(e))return;const t=this.waiterAbortController.signal;yield new _a(((n,i)=>{const r=()=>{o(),n()},a=()=>{o(),i(new Ya("DataChannel ".concat(this.kind," closed while draining the buffer")))},s=()=>{o(),i(new Ya("DataChannel ".concat(this.kind," was replaced or torn down while waiting for headroom")))},o=()=>{e.removeEventListener("bufferedamountlow",r),e.removeEventListener("close",a),t.removeEventListener("abort",s)};t.aborted?s():(e.addEventListener("bufferedamountlow",r),e.addEventListener("close",a),t.addEventListener("abort",s))}))}))}invalidateWaiters(e){this.waiterAbortController.abort(e),this.waiterAbortController=new AbortController}refreshBufferStatus(){var e;const t=this.getChannel();if(!t)return;const n=this.isBelowLowWaterMark(t);n!==this.bufferStatusLow&&(this.bufferStatusLow=n,null===(e=this.onBufferStatusChanged)||void 0===e||e.call(this,n))}}class jd extends Bd{constructor(e){super(e),this.statCurrentBytes=0,this.statByterate=0,this.dropCount=0,this.bufferFullBehavior=e.bufferFullBehavior,this.shouldSkipSends=e.shouldSkipSends}send(e){return pr(this,void 0,void 0,(function*(){const t=this.getChannel();if(t){switch(this.bufferFullBehavior){case"wait":this.isBelowHighWaterMark(t)||(yield this.waitForHeadroomWithLock());break;case"drop":if(!this.isBelowLowWaterMark(t))return this.dropCount+=1,void(this.dropCount%100==0&&ar.warn("dropping lossy data channel messages, total dropped: ".concat(this.dropCount)))}if(this.statCurrentBytes+=e.byteLength,!this.shouldSkipSends())try{t.send(e),this.refreshBufferStatus()}catch(n){if(!(n instanceof TypeError))throw n;ar.error(n)}}}))}startThresholdTuning(){this.stopThresholdTuning(),this.statInterval=is.setInterval((()=>{this.statByterate=this.statCurrentBytes,this.statCurrentBytes=0;const e=this.getChannel();if(e){const t=this.statByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,this.lowWaterMark),this.highWaterMark)}}),1e3)}stopThresholdTuning(){this.statByterate=0,this.statCurrentBytes=0,this.statInterval&&(is.clearInterval(this.statInterval),this.statInterval=void 0),this.dropCount=0}}class qd{constructor(){this.buffer=[],this._totalSize=0,this._sentSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength,e.sent&&(this._sentSize+=e.data.byteLength)}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength,e.sent&&(this._sentSize-=e.data.byteLength)),e}getAll(){return this.buffer.slice()}getUnsent(){return this.buffer.filter((e=>!e.sent))}markSent(e){e.sent||(e.sent=!0,this._sentSize+=e.data.byteLength)}markAllUnsent(){for(const e of this.buffer)e.sent=!1;this._sentSize=0}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(!t.sent)break;if(this._sentSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class Vd extends Bd{constructor(e){super(e),this.messageBuffer=new qd,this.sequence=1,this.isDeferringSends=e.isDeferringSends}nextSequence(){const e=this.sequence;return this.sequence+=1,e}send(e,t){return pr(this,void 0,void 0,(function*(){if(this.isDeferringSends())return void this.messageBuffer.push({data:e,sequence:t,sent:!1});const n=this.getChannel();if(n){try{yield this.waitForHeadroomWithLock()}catch(i){if(this.isEngineClosed())throw i;return void this.messageBuffer.push({data:e,sequence:t,sent:!1})}this.isDeferringSends()?this.messageBuffer.push({data:e,sequence:t,sent:!1}):(this.messageBuffer.push({data:e,sequence:t,sent:!0}),n.send(e),this.refreshBufferStatus())}}))}replay(e){return pr(this,void 0,void 0,(function*(){const t=this.getChannel();if(!t)return;this.messageBuffer.popToSequence(e);const n=yield this.lockHeadroom();try{this.messageBuffer.markAllUnsent();for(let e=this.messageBuffer.getUnsent();e.length>0;e=this.messageBuffer.getUnsent())for(const n of e)yield this.waitForHeadroomWithoutLock(),t.send(n.data),this.messageBuffer.markSent(n)}finally{n()}this.refreshBufferStatus()}))}refreshBufferStatus(){const e=this.channelHandle;e&&this.messageBuffer.alignBufferedAmount(e.bufferedAmount),super.refreshBufferStatus()}reset(){this.messageBuffer=new qd,this.sequence=1}}!function(e){e[e.RELIABLE=0]="RELIABLE",e[e.LOSSY=1]="LOSSY",e[e.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY"}(Ud||(Ud={}));function Wd(e){return e===Ud.RELIABLE?65536:8192}function Hd(e){return e===Ud.RELIABLE?1048576:262144}const Kd="_lossy",zd="_reliable",Gd="_data_track";class Jd{constructor(e){this.opts=e;const t=t=>({kind:t,lowWaterMark:Wd(t),highWaterMark:Hd(t),isEngineClosed:e.isEngineClosed,onBufferStatusChanged:n=>e.onBufferStatusChanged(t,n)});this.reliable=new Vd(Object.assign(Object.assign({},t(Ud.RELIABLE)),{isDeferringSends:e.isReconnecting})),this.lossy=new jd(Object.assign(Object.assign({},t(Ud.LOSSY)),{bufferFullBehavior:"drop",shouldSkipSends:e.isReconnecting})),this.dataTrack=new jd(Object.assign(Object.assign({},t(Ud.DATA_TRACK_LOSSY)),{bufferFullBehavior:"wait",shouldSkipSends:e.isReconnecting}))}channelFor(e){switch(e){case Ud.RELIABLE:return this.reliable;case Ud.LOSSY:return this.lossy;case Ud.DATA_TRACK_LOSSY:return this.dataTrack}}getHandle(e){if(!(arguments.length>1&&void 0!==arguments[1]&&arguments[1]))return this.channelFor(e).channelHandle;switch(e){case Ud.RELIABLE:return this.reliableSub;case Ud.LOSSY:return this.lossySub;case Ud.DATA_TRACK_LOSSY:return this.dataTrackSub}}get hasPublisherChannels(){return Boolean(this.reliable.channelHandle||this.lossy.channelHandle||this.dataTrack.channelHandle)}createPublisherChannels(e){for(const n of[this.lossy,this.reliable,this.dataTrack]){const e=n.channelHandle;e&&(e.onmessage=null,e.onerror=null,e.onclose=null)}const t=(e,t,n)=>{t.onmessage=n,t.onerror=this.opts.onDataError,t.onclose=()=>this.opts.onChannelClose(e.kind),t.bufferedAmountLowThreshold=e.lowWaterMark,t.onbufferedamountlow=()=>e.refreshBufferStatus(),e.attach(t)};t(this.lossy,e.createPublisherDataChannel(Kd,{ordered:!1,maxRetransmits:0}),this.opts.onDataMessage),t(this.reliable,e.createPublisherDataChannel(zd,{ordered:!0}),this.opts.onDataMessage),t(this.dataTrack,e.createPublisherDataChannel(Gd,{ordered:!1,maxRetransmits:0}),this.opts.onDataTrackMessage),this.lossy.startThresholdTuning()}adoptSubscriberChannel(e){let t;if(e.label===zd)this.reliableSub=e,t=this.opts.onDataMessage;else if(e.label===Kd)this.lossySub=e,t=this.opts.onDataMessage;else{if(e.label!==Gd)return!1;this.dataTrackSub=e,t=this.opts.onDataTrackMessage}return e.onmessage=t,!0}teardown(){const e=e=>{e&&(e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null,e.close())};for(const t of[this.lossy,this.reliable,this.dataTrack]){const n=t.channelHandle;t.detach("peer connections cleaned up"),e(n)}e(this.lossySub),e(this.reliableSub),e(this.dataTrackSub),this.lossySub=void 0,this.reliableSub=void 0,this.dataTrackSub=void 0,this.reliable.reset()}}const Qd="undefined"!=typeof MediaRecorder;const Yd=Qd?MediaRecorder:class{constructor(){throw new Error("MediaRecorder is not available in this environment")}};class Xd extends Yd{constructor(e,t){if(!Qd)throw new Error("MediaRecorder is not available in this environment");let n,i;super(new MediaStream([e.mediaStreamTrack]),t);const r=()=>{this.removeEventListener("dataavailable",n),this.removeEventListener("stop",r),this.removeEventListener("error",a),null==i||i.close(),i=void 0},a=e=>{null==i||i.error(e),this.removeEventListener("dataavailable",n),this.removeEventListener("stop",r),this.removeEventListener("error",a),i=void 0};this.byteStream=new ReadableStream({start:e=>{i=e,n=t=>pr(this,void 0,void 0,(function*(){let n;if(t.data.arrayBuffer){const e=yield t.data.arrayBuffer();n=new Uint8Array(e)}else{if(!t.data.byteArray)throw new Error("no data available!");n=t.data.byteArray}void 0!==i&&e.enqueue(n)})),this.addEventListener("dataavailable",n)},cancel:()=>{r()}}),this.addEventListener("stop",r),this.addEventListener("error",a)}}class Zd extends xs{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(t,n,i){let a=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(t,n,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!1,this.pendingDeviceChange=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch((()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext))),this.debouncedTrackMuteHandler=cc((()=>pr(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>pr(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(e.TrackEvent.Ended,this)},this.reacquireTrack=!1,this.providedByUser=a,this.muteLock=new r,this.pauseUpstreamLock=new r,this.trackChangeLock=new r,this.trackChangeLock.lock().then((e=>pr(this,void 0,void 0,(function*(){try{yield this.setMediaStreamTrack(t,!0)}finally{e()}})))),this._constraints=t.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==xs.Kind.Video)return;const e=this._mediaStreamTrack.getSettings(),t=e.width,n=e.height;return t&&n?{width:t,height:n}: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,n){return pr(this,void 0,void 0,(function*(){var i;if(e===this._mediaStreamTrack&&!t)return;let r;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{Fs(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&&(Us(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement,localTrack:this}),r=this.processor.processedTrack}this.sender&&"closed"!==(null===(i=this.sender.transport)||void 0===i?void 0:i.state)&&(yield this.sender.replaceTrack(null!=r?r:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!!n||!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{Us(null!=r?r:e,t)})))}))}waitForDimensions(){return pr(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var n;if(e.kind===xs.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(n=Oa())||void 0===n?void 0:n.os)&&(yield qs(10));const i=Date.now();for(;Date.now()-i<t;){const t=e.dimensions;if(t)return t;yield qs(50)}throw new Ja("unable to get track dimensions after timeout")}()}))}setDeviceId(e){return pr(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Eo(e)||(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),Eo(e)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return pr(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===xs.Source.ScreenShare)return;const n=e._mediaStreamTrack.getSettings(),i=n.deviceId,r=n.groupId,a=e.kind===xs.Kind.Audio?"audioinput":"videoinput";return t?Sc.getInstance().normalizeDeviceId(a,i,r):i}()}))}mute(){return pr(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return pr(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return pr(this,void 0,void 0,(function*(){const n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Ja("unable to replace an unpublished track");let n,i;"boolean"==typeof t?n=t:void 0!==t&&(n=t.userProvidedTrack,i=t.stopProcessor),this.providedByUser=null==n||n,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),i&&this.processor&&(yield this.internalStopProcessor())}finally{n()}return yield this.onSenderTrackSwapped(),this}))}onSenderTrackSwapped(){return pr(this,void 0,void 0,(function*(){}))}restart(t,n){return pr(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const i=yield this.trackChangeLock.lock();try{t||(t=this._constraints);const i=t,r=i.deviceId,a=i.facingMode,s=hr(t,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:t}));const o={audio:!1,video:!1};this.kind===xs.Kind.Video?o.video=!r&&!a||{deviceId:r,facingMode:a}:o.audio=!r||Object.assign({deviceId:r},s),this.attachedElements.forEach((e=>{Fs(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return this.kind===xs.Kind.Video&&(yield c.applyConstraints(s)),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c,!1,n),this._constraints=t,this.pendingDeviceChange=!1,this.emit(e.TrackEvent.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{i()}}))}setTrackMuted(t){this.log.debug("setting ".concat(this.kind," track ").concat(t?"muted":"unmuted"),this.logContext),this.isMuted===t&&this._mediaStreamTrack.enabled!==t||(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.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 pr(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),to()&&(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 pr(this,void 0,void 0,(function*(){var t;const n=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(e.TrackEvent.UpstreamPaused,this);const n=Oa();if("Safari"===(null==n?void 0:n.name)&&lo(n.version,"12.0")<0)throw new Ga("pauseUpstream is not supported on Safari < 12.");"closed"!==(null===(t=this.sender.transport)||void 0===t?void 0:t.state)&&(yield this.sender.replaceTrack(null))}finally{n()}}))}resumeUpstream(){return pr(this,void 0,void 0,(function*(){var t;const n=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(e.TrackEvent.UpstreamResumed,this),"closed"!==(null===(t=this.sender.transport)||void 0===t?void 0:t.state)&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{n()}}))}getRTCStatsReport(){return pr(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(t){return pr(this,arguments,void 0,(function(t){var n=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var r;const a=yield n.trackChangeLock.lock();try{n.log.debug("setting up processor",n.logContext);const a=document.createElement(n.kind),s={kind:n.kind,track:n._mediaStreamTrack,element:a,audioContext:n.audioContext,localTrack:n};if(yield t.init(s),n.log.debug("processor initialized",n.logContext),n.processor&&(yield n.internalStopProcessor()),"unknown"===n.kind)throw TypeError("cannot set processor on track of unknown kind");if(Us(n._mediaStreamTrack,a),a.muted=!0,a.play().catch((e=>{e instanceof DOMException&&"AbortError"===e.name?(n.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},n.logContext),{error:e})),setTimeout((()=>{a.play().catch((e=>{n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{err:e}))}))}),100)):n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:e}))})),n.processor=t,n.processorElement=a,n.processor.processedTrack){for(const e of n.attachedElements)e!==n.processorElement&&i&&(Fs(n._mediaStreamTrack,e),Us(n.processor.processedTrack,e));yield null===(r=n.sender)||void 0===r?void 0:r.replaceTrack(n.processor.processedTrack)}n.emit(e.TrackEvent.TrackProcessorUpdate,n.processor)}finally{a()}yield n.onSenderTrackSwapped()}()}))}getProcessor(){return this.processor}stopProcessor(){return pr(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}yield e.onSenderTrackSwapped()}()}))}internalStopProcessor(){return pr(this,arguments,void 0,(function(){var t=this;let n=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,r;t.processor&&(t.log.debug("stopping processor",t.logContext),null===(i=t.processor.processedTrack)||void 0===i||i.stop(),yield t.processor.destroy(),t.processor=void 0,n||(null===(r=t.processorElement)||void 0===r||r.remove(),t.processorElement=void 0),yield t._mediaStreamTrack.applyConstraints(t._constraints),yield t.setMediaStreamTrack(t._mediaStreamTrack,!0),t.emit(e.TrackEvent.TrackProcessorUpdate))}()}))}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(Qd)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 Xd(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 $d extends Zd{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(t,i){let r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],a=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(t,xs.Kind.Audio,i,r,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>pr(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 audio sender stats",Object.assign(Object.assign({},this.logContext),{error:n}))}e&&this.prevStats&&(this._currentBitrate=lc(e,this.prevStats)),this.prevStats=e})),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(e.TrackEvent.AudioTrackFeatureUpdate,this,ct.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(e.TrackEvent.AudioTrackFeatureUpdate,this,ct.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=a,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return pr(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===xs.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 pr(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==xs.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!this.pendingDeviceChange||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}restartTrack(e){return pr(this,void 0,void 0,(function*(){let t;if(e){const n=Es({audio:e});"boolean"!=typeof n.audio&&(t=n.audio)}yield this.restart(t)}))}applyConstraints(e){return pr(this,void 0,void 0,(function*(){const t=yield this.trackChangeLock.lock();try{const t=yield this._mediaStreamTrack.applyConstraints(e);return this._constraints=Object.assign(Object.assign({},this._constraints),e),t}finally{t()}}))}restart(e,t){const n=Object.create(null,{restart:{get:()=>super.restart}});return pr(this,void 0,void 0,(function*(){const i=yield n.restart.call(this,e,t);return this.checkForSilence(),i}))}startMonitor(){no()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),dc)))}setProcessor(t){return pr(this,void 0,void 0,(function*(){var n;const i=yield this.trackChangeLock.lock();try{if(!io()&&!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,localTrack:this};this.log.debug("setting up audio processor ".concat(t.name),this.logContext),yield t.init(i),this.processor=t,this.processor.processedTrack&&(yield null===(n=this.sender)||void 0===n?void 0:n.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(e.TrackEvent.TrackProcessorUpdate,this.processor)}finally{i()}}))}setAudioContext(e){this.audioContext=e}getSenderStats(){return pr(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;const t=yield this.sender.getStats();let n;return t.forEach((e=>{if("outbound-rtp"===e.type){n={type:"audio",streamId:e.id,packetsSent:e.packetsSent,bytesSent:e.bytesSent,timestamp:e.timestamp};const i=t.get(e.remoteId);i&&(n.packetsLost=i.packetsLost,n.jitter=i.jitter,n.roundTripTime=i.roundTripTime)}})),n}))}checkForSilence(){return pr(this,void 0,void 0,(function*(){const t=yield Cs(this);return t&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(e.TrackEvent.AudioSilenceDetected)),t}))}}const el=Object.values(ks),tl=Object.values(ys),nl=Object.values(bs),il=[ks.h180,ks.h360],rl=[ys.h180,ys.h360],al=["q","h","f"];function sl(e,t,n,i){var r,a;let s=null==i?void 0:i.videoEncoding;e&&(s=null==i?void 0:i.screenShareEncoding);const o=null==i?void 0:i.simulcast,c=null==i?void 0:i.scalabilityMode,d=null==i?void 0:i.videoCodec;if(!s&&!o&&!c||!t||!n)return[{}];s||(s=function(e,t,n,i){const r=function(e,t,n){if(e)return nl;const i=t>n?t/n:n/t;if(Math.abs(i-16/9)<Math.abs(i-4/3))return el;return tl}(e,t,n);let a=r[0].encoding;const s=Math.max(t,n);for(let o=0;o<r.length;o+=1){const e=r[o];if(a=e.encoding,e.width>=s)break}if(i)switch(i){case"av1":case"h265":a=Object.assign({},a),a.maxBitrate=.7*a.maxBitrate;break;case"vp9":a=Object.assign({},a),a.maxBitrate=.85*a.maxBitrate}return a}(e,t,n,d),ar.debug("using video encoding",s));const l=s.maxFramerate,u=new ls(t,n,s.maxBitrate,s.maxFramerate,s.priority);if(c&&zs(d)){const e=new ul(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const n=Oa();if($s()||io()||"Chrome"===(null==n?void 0:n.name)&&lo(null==n?void 0:n.version,"113")<0){const i="h"==e.suffix?2:3,r=function(e){return e||(e=Oa()),"Safari"===(null==e?void 0:e.name)&&lo(e.version,"18.3")>0||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&lo(e.osVersion,"18.3")>0}(n);for(let n=0;n<e.spatial;n+=1)t.push({rid:al[2-n],maxBitrate:s.maxBitrate/Math.pow(i,n),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:r?Math.pow(2,n):void 0});t[0].scalabilityMode=c}else t.push({maxBitrate:s.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),ar.debug("using svc encoding",{encodings:t}),t}if(!o)return[s];let h,p;if(h=e?null!==(r=ll(null==i?void 0:i.screenShareSimulcastLayers))&&void 0!==r?r:cl(e,u):null!==(a=ll(null==i?void 0:i.videoSimulcastLayers))&&void 0!==a?a:cl(e,u),h.length>0){const e=h[0];if(h.length>1)p=F(h,2)[1];const i=Math.max(t,n);if(i>=960&&p)return dl(t,n,[e,p,u],l);if(i>=480)return dl(t,n,[e,u],l)}return dl(t,n,[u])}function ol(e,t,n){var i,r,a,s;if(!n.backupCodec||!0===n.backupCodec||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&ar.warn("requested a different codec than specified as backup",{serverRequested:t,backup:n.backupCodec.codec}),n.videoCodec=t,n.videoEncoding=n.backupCodec.encoding;const o=e.mediaStreamTrack.getSettings(),c=null!==(i=o.width)&&void 0!==i?i:null===(r=e.dimensions)||void 0===r?void 0:r.width,d=null!==(a=o.height)&&void 0!==a?a:null===(s=e.dimensions)||void 0===s?void 0:s.height;e.source===xs.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1);return sl(e.source===xs.Source.ScreenShare,c,d,n)}function cl(e,t){if(e)return[{scaleResolutionDownBy:2,fps:(n=t).encoding.maxFramerate}].map((e=>{var t,i;return new ls(Math.floor(n.width/e.scaleResolutionDownBy),Math.floor(n.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!==(t=n.encoding.maxFramerate)&&void 0!==t?t:30)/(null!==(i=e.fps)&&void 0!==i?i:30))))),e.fps,n.encoding.priority)}));var n;const i=t.width,r=t.height,a=i>r?i/r:r/i;return Math.abs(a-16/9)<Math.abs(a-4/3)?il:rl}function dl(e,t,n,i){const r=[];if(n.forEach(((n,a)=>{if(a>=al.length)return;const s=Math.min(e,t),o={rid:al[a],scaleResolutionDownBy:Math.max(1,s/Math.min(n.width,n.height)),maxBitrate:n.encoding.maxBitrate},c=i&&n.encoding.maxFramerate?Math.min(i,n.encoding.maxFramerate):n.encoding.maxFramerate;c&&(o.maxFramerate=c);const d=Oa(),l="Firefox"===(null==d?void 0:d.name)&&"iOS"!==d.os||0===a;n.encoding.priority&&l&&(o.priority=n.encoding.priority,o.networkPriority=n.encoding.priority),r.push(o)})),io()&&"ios"===oo()){let e;r.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;r.forEach((n=>{var i;n.maxFramerate!=e&&(t&&(t=!1,ar.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),ar.info('Setting framerate of encoding "'.concat(null!==(i=n.rid)&&void 0!==i?i:"",'" to ').concat(e)),n.maxFramerate=e)}))}return r}function ll(e){if(e)return e.slice().sort(((e,t)=>{const n=e.encoding,i=t.encoding;return n.maxBitrate>i.maxBitrate?1:n.maxBitrate<i.maxBitrate?-1:n.maxBitrate===i.maxBitrate&&n.maxFramerate&&i.maxFramerate?n.maxFramerate>i.maxFramerate?1:-1:0}))}class ul{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 hl extends Zd{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(t,i){let a=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],s=arguments.length>3?arguments[3]:void 0;super(t,xs.Kind.Video,i,a,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>pr(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let t;try{t=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 i=new Map(t.map((e=>[e.rid,e]))),r=t.some((e=>"cpu"===e.qualityLimitationReason));if(r!==this.isCpuConstrained&&(this.isCpuConstrained=r,this.isCpuConstrained&&this.emit(e.TrackEvent.CpuConstrained)),this.prevStats){let e=0;i.forEach(((t,n)=>{var i;const r=null===(i=this.prevStats)||void 0===i?void 0:i.get(n);e+=lc(t,r)})),this._currentBitrate=e}this.prevStats=i})),this.senderLock=new r}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!no())return;const n=null===(t=this.sender)||void 0===t?void 0:t.getParameters();n&&(this.encodings=n.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),dc))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return pr(this,void 0,void 0,(function*(){var t,n,i,r,a;yield e.pauseUpstream.call(this);try{for(var s,o=!0,c=fr(this.simulcastCodecs.values());!(t=(s=yield c.next()).done);o=!0){r=s.value,o=!1;const e=r;yield null===(a=e.sender)||void 0===a?void 0:a.replaceTrack(null)}}catch(d){n={error:d}}finally{try{o||t||!(i=c.return)||(yield i.call(c))}finally{if(n)throw n.error}}}))}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return pr(this,void 0,void 0,(function*(){var t,n,i,r,a;yield e.resumeUpstream.call(this);try{for(var s,o=!0,c=fr(this.simulcastCodecs.values());!(t=(s=yield c.next()).done);o=!0){r=s.value,o=!1;const e=r;yield null===(a=e.sender)||void 0===a?void 0:a.replaceTrack(e.mediaStreamTrack)}}catch(d){n={error:d}}finally{try{o||t||!(i=c.return)||(yield i.call(c))}finally{if(n)throw n.error}}}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return pr(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!==xs.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 pr(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==xs.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return pr(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],n=yield this.sender.getStats();return n.forEach((e=>{var i;if("outbound-rtp"===e.type){const r={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!==(i=e.rid)&&void 0!==i?i:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},a=n.get(e.remoteId);a&&(r.jitter=a.jitter,r.packetsLost=a.packetsLost,r.roundTripTime=a.roundTripTime),t.push(r)}})),t.sort(((e,t)=>{var n,i;return(null!==(n=t.frameWidth)&&void 0!==n?n:0)-(null!==(i=e.frameWidth)&&void 0!==i?i:0)})),t}))}setPublishingQuality(t){const n=[];for(let i=e.VideoQuality.LOW;i<=e.VideoQuality.HIGH;i+=1)n.push(new wi({quality:i,enabled:i<=t}));this.log.debug("setting publishing quality. max quality ".concat(t),this.logContext),this.setPublishingLayers(zs(this.codec),n)}restartTrack(e){return pr(this,void 0,void 0,(function*(){var t,n,i,r,a;let s;if(e){const t=Es({video:e});"boolean"!=typeof t.video&&(s=t.video)}yield this.restart(s),this.isCpuConstrained=!1;try{for(var o,c=!0,d=fr(this.simulcastCodecs.values());!(t=(o=yield d.next()).done);c=!0){r=o.value,c=!1;const e=r;e.sender&&"closed"!==(null===(a=e.sender.transport)||void 0===a?void 0:a.state)&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(l){n={error:l}}finally{try{c||t||!(i=d.return)||(yield i.call(d))}finally{if(n)throw n.error}}yield this.onSenderTrackSwapped()}))}onSenderTrackSwapped(){return pr(this,void 0,void 0,(function*(){yield this.refreshSenderEncodings()}))}refreshSenderEncodings(){return pr(this,void 0,void 0,(function*(){var e;if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;const t=yield this.senderLock.lock();try{let t;try{t=yield this.waitForDimensions()}catch(n){return void this.log.warn("could not determine new track dimensions, skipping encoding recompute",Object.assign(Object.assign({},this.logContext),{error:n}))}if(this.lastEncodedDimensions&&this.lastEncodedDimensions.width===t.width&&this.lastEncodedDimensions.height===t.height)return;const r=sl(this.source===xs.Source.ScreenShare,t.width,t.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,r),this.encodings=r,this.lastEncodedDimensions=t;for(const n of this.simulcastCodecs){var i=F(n,2);const t=i[0],r=i[1];if(!r.sender||"closed"===(null===(e=r.sender.transport)||void 0===e?void 0:e.state))continue;if(!ms(t))continue;const a=ol(this,t,Object.assign({},this.publishOptions));a&&(yield this.applyEncodingsToSender(r.sender,a),r.encodings=a)}}catch(n){this.log.warn("failed to apply recomputed encodings",Object.assign(Object.assign({},this.logContext),{error:n}))}finally{t()}}))}applyEncodingsToSender(e,t){return pr(this,void 0,void 0,(function*(){const n=e.getParameters();n.encodings&&n.encodings.length===t.length&&(n.encodings.forEach(((e,n)=>{if(!1===e.active)return;const i=t[n];void 0!==i.scaleResolutionDownBy&&(e.scaleResolutionDownBy=i.scaleResolutionDownBy),void 0!==i.maxBitrate&&(e.maxBitrate=i.maxBitrate),void 0!==i.maxFramerate&&(e.maxFramerate=i.maxFramerate),void 0!==i.priority&&(e.priority=i.priority,e.networkPriority=i.priority)})),this.log.debug("updating sender encodings after track restart",Object.assign(Object.assign({},this.logContext),{encodings:n.encodings})),yield e.setParameters(n))}))}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return pr(this,arguments,void 0,(function(e){var n=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var r,a,s,o,c,d;if(yield t.setProcessor.call(n,e,i),null===(c=n.processor)||void 0===c?void 0:c.processedTrack)try{for(var l,u=!0,h=fr(n.simulcastCodecs.values());!(r=(l=yield h.next()).done);u=!0){o=l.value,u=!1;const e=o;yield null===(d=e.sender)||void 0===d?void 0:d.replaceTrack(n.processor.processedTrack)}}catch(p){a={error:p}}finally{try{u||r||!(s=h.return)||(yield s.call(h))}finally{if(a)throw a.error}}}()}))}setDegradationPreference(e){return pr(this,void 0,void 0,(function*(){this.degradationPreference=e,yield this.applyDegradationPreference(this.sender);for(const e of this.simulcastCodecs.values())yield this.applyDegradationPreference(e.sender)}))}applyDegradationPreference(e){return pr(this,void 0,void 0,(function*(){if(e)try{this.log.debug("setting degradationPreference to ".concat(this.degradationPreference),this.logContext);const t=e.getParameters();t.degradationPreference=this.degradationPreference,yield e.setParameters(t)}catch(n){this.log.warn("failed to set degradationPreference",Object.assign({error:n},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 n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){return pr(this,void 0,void 0,(function*(){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,yield this.applyDegradationPreference(t),setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}))}setPublishingCodecs(e){return pr(this,void 0,void 0,(function*(){var t,n,i,r,a,s,o;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(zs(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,n=fr(e);!(r=(i=yield n.next()).done);t=!0){o=i.value,t=!1;const e=o;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 pl(t.sender,t.encodings,e.qualities,this.senderLock,zs(e.codec),this.log,this.logContext));else for(const n of e.qualities)if(n.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(zs(e.codec),e.qualities)}}catch(d){a={error:d}}finally{try{t||r||!(s=n.return)||(yield s.call(n))}finally{if(a)throw a.error}}return c}))}setPublishingLayers(e,t){return pr(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 pl(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))}))}prioritizePerformance(){return pr(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 n;return Object.assign(Object.assign({},e),{active:0===t,scaleResolutionDownBy:Math.max(1,Math.ceil((null!==(n=this.mediaStreamTrack.getSettings().height)&&void 0!==n?n:360)/360)),scalabilityMode:0===t&&zs(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(n){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:n})),this.optimizeForPerformance=!1}finally{e()}}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return pr(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),to()&&this.isInBackground&&this.source===xs.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function pl(e,t,n,i,r,a,s){return pr(this,void 0,void 0,(function*(){const o=yield i.lock();a.debug("setPublishingLayersForSender",Object.assign(Object.assign({},s),{sender:e,qualities:n,senderEncodings:t}));try{const i=e.getParameters(),o=i.encodings;if(!o)return;if(o.length!==t.length)return void a.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},s),{encodings:o,senderEncodings:t}));let c=!1;if(!1&&o[0].scalabilityMode);else{if(r){n.some((e=>e.enabled))&&n.forEach((e=>e.enabled=!0))}o.forEach(((e,i)=>{var r;let o=null!==(r=e.rid)&&void 0!==r?r:"";""===o&&(o="q");const d=ml(o),l=n.find((e=>e.quality===d));l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,a.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),s),Ys()&&(l.enabled?(e.scaleResolutionDownBy=t[i].scaleResolutionDownBy,e.maxBitrate=t[i].maxBitrate,e.maxFrameRate=t[i].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}))}c&&(i.encodings=o,a.debug("setting encodings",Object.assign(Object.assign({},s),{encodings:i.encodings})),yield e.setParameters(i))}finally{o()}}))}function ml(t){switch(t){case"f":default:return e.VideoQuality.HIGH;case"h":return e.VideoQuality.MEDIUM;case"q":return e.VideoQuality.LOW}}function gl(t,n,i,r){if(!i)return[new _t({quality:e.VideoQuality.HIGH,width:t,height:n,bitrate:0,ssrc:0})];if(r){const r=i[0].scalabilityMode,a=new ul(r),s=[],o="h"==a.suffix?1.5:2,c="h"==a.suffix?2:3;for(let d=0;d<a.spatial;d+=1)s.push(new _t({quality:Math.min(e.VideoQuality.HIGH,a.spatial-1)-d,width:Math.ceil(t/Math.pow(o,d)),height:Math.ceil(n/Math.pow(o,d)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(c,d)):0,ssrc:0}));return s}return i.map((e=>{var i,r,a;const s=null!==(i=e.scaleResolutionDownBy)&&void 0!==i?i:1;let o=ml(null!==(r=e.rid)&&void 0!==r?r:"");return new _t({quality:o,width:Math.ceil(t/s),height:Math.ceil(n/s),bitrate:null!==(a=e.maxBitrate)&&void 0!==a?a:0,ssrc:0})}))}const vl="leave-reconnect";var fl;!function(e){e[e.New=0]="New",e[e.Connected=1]="Connected",e[e.Disconnected=2]="Disconnected",e[e.Reconnecting=3]="Reconnecting",e[e.Closed=4]="Closed"}(fl||(fl={}));class kl extends br.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}get reliableChannel(){return this.dataChannels.reliable}get lossyChannel(){return this.dataChannels.lossy}get dataTrackChannel(){return this.dataChannels.dataTrack}constructor(t){var i;super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=Nd.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=fl.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.shouldFailOnV1Path=!1,this.log=ar,this.reliableReceivedState=new sd(3e4),this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>pr(this,[e],void 0,(function(e){var t=this;let n=e.channel;return function*(){n&&t.dataChannels.adoptSubscriberChannel(n)&&t.log.debug("on data channel ".concat(n.id,", ").concat(n.label))}()})),this.handleDataMessage=t=>pr(this,void 0,void 0,(function*(){var n,i,r,a,s;const o=yield this.dataProcessLock.lock();try{const o=yield this.decodeDataMessage(t);if(!o)return;const c=Dt.fromBinary(o);if(c.sequence>0&&""!==c.participantSid){const e=this.reliableReceivedState.get(c.participantSid);if(e&&c.sequence<=e)return;this.reliableReceivedState.set(c.participantSid,c.sequence)}if("speaker"===(null===(n=c.value)||void 0===n?void 0:n.case))this.emit(e.EngineEvent.ActiveSpeakersUpdate,c.value.value.speakers);else if("encryptedPacket"===(null===(i=c.value)||void 0===i?void 0:i.case)){if(!this.e2eeManager)return void this.log.error("Received encrypted packet but E2EE not set up");const t=yield null===(r=this.e2eeManager)||void 0===r?void 0:r.handleEncryptedData(c.value.value.encryptedValue,c.value.value.iv,c.participantIdentity,c.value.value.keyIndex),n=Lt.fromBinary(t.payload),i=new Dt({value:n.value,participantIdentity:c.participantIdentity,participantSid:c.participantSid});"user"===(null===(a=i.value)||void 0===a?void 0:a.case)&&yl(i,i.value.value),this.emit(e.EngineEvent.DataPacketReceived,i,c.value.value.encryptionType)}else"user"===(null===(s=c.value)||void 0===s?void 0:s.case)&&yl(c,c.value.value),this.emit(e.EngineEvent.DataPacketReceived,c,ft.NONE)}finally{o()}})),this.handleDataTrackMessage=e=>pr(this,void 0,void 0,(function*(){const t=yield this.decodeDataMessage(e);t&&this.emit("dataTrackPacketReceived",t)})),this.handleDataError=e=>{if(this._isClosed)return;const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if("undefined"!=typeof RTCErrorEvent&&e instanceof RTCErrorEvent&&e.error){const n=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(n.message),{error:n,errorDetail:n.errorDetail,sctpCauseCode:n.sctpCauseCode})}else this.log.error("Unknown DataChannel error on ".concat(t),{event:e})},this.handleDataChannelClose=e=>()=>{var t;this._isClosed||"connected"!==(null===(t=this.pcManager)||void 0===t?void 0:t.publisher.getConnectionState())||this.log.error("publisher data channel '".concat(Ud[e],"' closed unexpectedly"),this.logContext)},this.handleDisconnect=(t,n)=>{if(this._isClosed)return;this.log.warn("".concat(t," disconnected")),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const i=t=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(t,"ms. giving up")),this.emit(e.EngineEvent.Disconnected),this.close("gave up reconnecting after ".concat(this.reconnectAttempts," attempts, ").concat(t,"ms"))},r=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:r,retryCount:this.reconnectAttempts});null!==a?(t===vl&&(a=0),this.log.debug("reconnecting in ".concat(a,"ms")),this.clearReconnectTimeout(),this.token&&this.emit(e.EngineEvent.TokenRefreshed,this.token),this.reconnectTimeout=is.setTimeout((()=>this.attemptReconnect(n).finally((()=>this.reconnectTimeout=void 0))),a)):i(r)},this.waitForRestarted=()=>new Promise(((t,n)=>{this.pcState===fl.Connected&&t();const i=()=>{this.off(e.EngineEvent.Disconnected,r),t()},r=()=>{this.off(e.EngineEvent.Restarted,i),n()};this.once(e.EngineEvent.Restarted,i),this.once(e.EngineEvent.Disconnected,r)})),this.onRtpMapAvailable=t=>{const n=new Map;t.forEach((e=>{const t=e.codec.toLowerCase();So(t)&&n.set(e.payload,t)})),this.emit(e.EngineEvent.RTPVideoMapUpdate,n)},this.handleBrowserOnLine=()=>pr(this,void 0,void 0,(function*(){if(!this.url)return;(yield fetch(Co(this.url),{method:"HEAD"}).then((e=>e.ok)).catch((()=>!1)))&&(this.log.info("detected network reconnected"),(this.client.currentState===nd.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===nd.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(st.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))})),this.handleBrowserOffline=()=>pr(this,void 0,void 0,(function*(){if(this.url)try{yield Promise.race([fetch(Co(this.url),{method:"HEAD"}),qs(4e3).then((()=>Promise.reject()))])}catch(n){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}})),this.log=or(null!==(i=t.loggerName)&&void 0!==i?i:e.LoggerNames.Engine,(()=>this.logContext)),this.loggerOptions={loggerName:t.loggerName,loggerContextCb:()=>this.logContext},this.client=new id(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new r,this.dataProcessLock=new r,this.dataChannels=new Jd({isEngineClosed:()=>this.isClosed,isReconnecting:()=>this.attemptingReconnect,onDataMessage:e=>this.handleDataMessage(e),onDataTrackMessage:e=>this.handleDataTrackMessage(e),onDataError:e=>this.handleDataError(e),onChannelClose:e=>this.handleDataChannelClose(e)(),onBufferStatusChanged:(t,n)=>this.emit(e.EngineEvent.DCBufferStatusChanged,n,t)}),this.client.onParticipantUpdate=t=>this.emit(e.EngineEvent.ParticipantUpdate,t),this.client.onConnectionQuality=t=>{this.handleLocalConnectionQuality(t),this.emit(e.EngineEvent.ConnectionQualityUpdate,t)},this.client.onRoomUpdate=t=>this.emit(e.EngineEvent.RoomUpdate,t),this.client.onSubscriptionError=t=>this.emit(e.EngineEvent.SubscriptionError,t),this.client.onSubscriptionPermissionUpdate=t=>this.emit(e.EngineEvent.SubscriptionPermissionUpdate,t),this.client.onSpeakersChanged=t=>this.emit(e.EngineEvent.SpeakersChanged,t),this.client.onStreamStateUpdate=t=>this.emit(e.EngineEvent.StreamStateChanged,t),this.client.onRequestResponse=t=>this.emit(e.EngineEvent.SignalRequestResponse,t),this.client.onParticipantUpdate=t=>this.emit(e.EngineEvent.ParticipantUpdate,t),this.client.onJoined=t=>this.emit(e.EngineEvent.Joined,t)}get logContext(){var e,t,n,i,r,a;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(i=null===(n=this.latestJoinResponse)||void 0===n?void 0:n.room)||void 0===i?void 0:i.sid,participant:null===(a=null===(r=this.latestJoinResponse)||void 0===r?void 0:r.participant)||void 0===a?void 0:a.identity,participantID:this.participantSid}}join(t,i,r,a){return pr(this,arguments,void 0,(function(t,i,r,a){var s=this;let o=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){var c,d,l;s._isNewlyCreated=!1,s.url=t,s.token=i,s.signalOpts=r,s.maxJoinAttempts=r.maxRetries;try{s.joinAttempts+=1,s.setupSignalClientCallbacks();const n=!o&&Fo()&&!Ys();let u;if(n){s.pcManager||(yield s.configure(),s.applyInitialPublisherLayout());const e=yield null===(c=s.pcManager)||void 0===c?void 0:c.publisher.createInitialOffer();e&&(u=ad(e.offer,e.offerId))}if(null==a?void 0:a.aborted)throw za.cancelled("Connection aborted");if(!o&&s.shouldFailOnV1Path)throw s.shouldFailOnV1Path=!1,za.serviceNotFound("Simulated v1 path failure","v0-rtc");const h=yield s.client.join(t,i,r,a,o,u);s._isClosed=!1,s.latestJoinResponse=h,s.participantSid=null===(d=h.participant)||void 0===d?void 0:d.sid,s.subscriberPrimary=h.subscriberPrimary,n?null===(l=s.pcManager)||void 0===l||l.updateConfiguration(s.makeRTCConfiguration(h)):(s.pcManager||(yield s.configure(h,!o),o||s.applyInitialPublisherLayout()),s.subscriberPrimary&&!h.fastPublish||s.negotiate().catch((e=>{s.log.error(e)}))),s.registerOnLineListener(),s.clientConfiguration=h.clientConfiguration,s.emit(e.EngineEvent.SignalConnected,h);let p=h.serverInfo;return p||(p={version:h.serverVersion,region:h.serverRegion}),s.log.info("connected to Livekit Server ".concat(Object.entries(p).map((e=>{let t=F(e,2),n=t[0],i=t[1];return"".concat(n,": ").concat(i)})).join(", "))),{joinResponse:h,serverInfo:p}}catch(n){if(n instanceof za)if(n.reason===e.ConnectionErrorReason.ServerUnreachable){if(s.log.warn("Couldn't connect to server, attempt ".concat(s.joinAttempts," of ").concat(s.maxJoinAttempts)),s.joinAttempts<s.maxJoinAttempts)return s.join(t,i,r,a,o)}else if(n.reason===e.ConnectionErrorReason.ServiceNotFound)return s.log.warn("Initial connection failed: ".concat(n.message," – Retrying")),s.pcManager&&(s.pcManager.onStateChange=void 0,yield s.cleanupPeerConnections()),s.join(t,i,r,a,!0);throw n}}()}))}close(t){return pr(this,void 0,void 0,(function*(){const n=yield this.closingLock.lock();if(this.isClosed)n();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(e.EngineEvent.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.clearLostQualityTimeout(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient(t)}finally{n()}}))}cleanupPeerConnections(){return pr(this,void 0,void 0,(function*(){var e;this.dataChannels.teardown(),yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0,this.transportConnectingSince=void 0,this.reliableReceivedState.clear()}))}cleanupLossyDataStats(){this.lossyChannel.stopThresholdTuning()}cleanupClient(e){return pr(this,void 0,void 0,(function*(){yield this.client.close(!0,e),this.client.resetCallbacks();for(const e of Object.keys(this.pendingTrackResolvers))this.pendingTrackResolvers[e].reject();this.pendingTrackResolvers={}}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Ja("a track with the same ID has already been published");return new Promise(((t,n)=>{const i=is.setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],n(za.timeout("publication of local track timed out, no response from server"))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{is.clearTimeout(i),t(e)},reject:()=>{is.clearTimeout(i),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const t=this.pendingTrackResolvers[e.track.id].reject;t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(n){this.log.warn("failed to remove track",{error:n})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.dataChannelForKind(Ud.RELIABLE,!0))||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return pr(this,void 0,void 0,(function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()}))}setRegionStrategy(e){this.regionStrategy=e}configure(t,n){return pr(this,void 0,void 0,(function*(){var i;if(!this.pcManager||this.pcManager.currentState===xd.NEW){if(t){this.participantSid=null===(i=t.participant)||void 0===i?void 0:i.sid;const e=this.makeRTCConfiguration(t);this.pcManager=new Fd(n?"publisher-only":t.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,e)}else{const e=this.makeRTCConfiguration();this.pcManager=new Fd("publisher-only",this.loggerOptions,e)}this.emit(e.EngineEvent.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,n,i)=>pr(this,void 0,void 0,(function*(){if(this.log.debug("primary PC state changed ".concat(t)),t===xd.CONNECTING?this.transportConnectingSince=Date.now():this.transportConnectingSince=void 0,["closed","disconnected","failed"].includes(n)&&(this.publisherConnectionPromise=void 0),t===xd.CONNECTED){const t=this.pcState===fl.New;this.pcState=fl.Connected,t&&this.emit(e.EngineEvent.Connected,this.latestJoinResponse)}else t===xd.FAILED&&(this.pcState!==fl.Connected&&this.pcState!==fl.Reconnecting||(this.pcState=fl.Disconnected,this.handleDisconnect("peerconnection failed","failed"===i?st.RR_SUBSCRIBER_FAILED:st.RR_PUBLISHER_FAILED)));const r=this.client.isDisconnected||this.client.currentState===nd.RECONNECTING,a=[xd.FAILED,xd.CLOSING,xd.CLOSED].includes(t);r&&a&&!this._isClosed&&this.emit(e.EngineEvent.Offline)})),this.pcManager.onTrack=t=>{0!==t.streams.length&&this.emit(e.EngineEvent.MediaTrackAdded,t.track,t.streams[0],t.receiver)}}}))}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>pr(this,void 0,void 0,(function*(){this.pcManager&&(this.log.debug("received server answer",{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:n}),this.midToTrackId=n,yield this.pcManager.setPublisherAnswer(e,t))})),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",{candidate:e,target:t}),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,n)=>pr(this,void 0,void 0,(function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;const i=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);i&&this.client.sendAnswer(i,t)})),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",{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),{cid:e.cid});const n=this.pendingTrackResolvers[e.cid].resolve;delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=t=>{this.emit(e.EngineEvent.LocalTrackUnpublished,t)},this.client.onLocalTrackSubscribed=t=>{this.emit(e.EngineEvent.LocalTrackSubscribed,t)},this.client.onTokenRefresh=t=>{this.token=t,this.emit(e.EngineEvent.TokenRefreshed,t)},this.client.onRemoteMuteChanged=(t,n)=>{this.emit(e.EngineEvent.RemoteMute,t,n)},this.client.onSubscribedQualityUpdate=t=>{this.emit(e.EngineEvent.SubscribedQualityUpdate,t)},this.client.onRoomMoved=t=>{var n;this.participantSid=null===(n=t.participant)||void 0===n?void 0:n.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=t.room),this.emit(e.EngineEvent.RoomMoved,t)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=t=>{this.emit(e.EngineEvent.PublishDataTrackResponse,t)},this.client.onUnPublishDataTrackResponse=t=>{this.emit(e.EngineEvent.UnPublishDataTrackResponse,t)},this.client.onDataTrackSubscriberHandles=t=>{this.emit(e.EngineEvent.DataTrackSubscriberHandles,t)},this.client.onClose=()=>{this.handleDisconnect("signal",st.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=t=>{var n;switch(this.log.info("client leave request received (action=".concat(null==t?void 0:t.action,")"),{reason:null==t?void 0:t.reason}),t.regions&&(this.log.debug("updating regions"),this.emit(e.EngineEvent.ServerRegionsReported,t.regions)),t.action){case gi.DISCONNECT:this.emit(e.EngineEvent.Disconnected,null==t?void 0:t.reason),this.close("server leave: ".concat(null!==(n=at[t.reason])&&void 0!==n?n:t.reason));break;case gi.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(vl);break;case gi.RESUME:this.handleDisconnect(vl)}}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if(((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)||this.frameMetadataWorker&&!ac())&&Zo()&&(this.log.debug("E2EE - setting up transports with insertable streams"),n.encodedInsertableStreams=!0),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",!e)return n;if(e.iceServers&&!n.iceServers){const t=[];e.iceServers.forEach((e=>{const n={urls:e.urls};e.username&&(n.username=e.username),e.credential&&(n.credential=e.credential),t.push(n)})),n.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===rt.ENABLED&&(n.iceTransportPolicy="relay"),n}applyInitialPublisherLayout(){this.createDataChannels(),io()||this.addMediaSections(3,3)}addMediaSections(e,t){var n,i,r;const a={direction:"recvonly"};for(let o=0;o<e;o++)null===(n=this.pcManager)||void 0===n||n.addPublisherTransceiverOfKind("audio",a);const s="publisher-only"===(null===(i=this.pcManager)||void 0===i?void 0:i.mode);for(let o=0;o<t;o++){const e=null===(r=this.pcManager)||void 0===r?void 0:r.addPublisherTransceiverOfKind("video",a);if(s&&e){const t=Gs(e);this.log.debug("dependency descriptor negotiated for received video",{negotiated:t})}}}createDataChannels(){this.pcManager&&this.dataChannels.createPublisherChannels(this.pcManager)}decodeDataMessage(e){return pr(this,void 0,void 0,(function*(){return e.data instanceof ArrayBuffer?new Uint8Array(e.data):e.data instanceof Blob?new Uint8Array(yield e.data.arrayBuffer()):void this.log.error("unsupported data type",{data:e.data})}))}createSender(e,t,n){return pr(this,void 0,void 0,(function*(){let i;if(Vs())i=yield this.createTransceiverRTCRtpSender(e,t,n);else{if(!Ws())throw new Ya("Required webRTC APIs not supported on this device");this.log.warn("using add-track fallback"),i=yield this.createRTCRtpSender(e.mediaStreamTrack)}return this.setupFrameMetadataSender(i,t),i}))}createSimulcastSender(e,t,n,i){return pr(this,void 0,void 0,(function*(){let r;if(Vs())r=yield this.createSimulcastTransceiverSender(e,t,n,i);else{if(!Ws())throw new Ya("Cannot stream on this device");this.log.debug("using add-track fallback"),r=yield this.createRTCRtpSender(e.mediaStreamTrack)}return r&&this.setupFrameMetadataSender(r,n),r}))}get frameMetadataWorker(){var e,t;return null===(t=null!==(e=this.options.frameMetadata)&&void 0!==e?e:this.options.packetTrailer)||void 0===t?void 0:t.worker}setupFrameMetadataSender(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n,i,r;const a=this.frameMetadataWorker;if(!a||(null===(n=this.signalOpts)||void 0===n?void 0:n.e2eeEnabled))return;const s=null!==(i=t.frameMetadata)&&void 0!==i?i:t.packetTrailer,o=oc(s);if(ac())return void(o&&(e.transform=new RTCRtpScriptTransform(a,{kind:"encode",packetTrailer:s})));if(!sc(null!==(r=this.options.frameMetadata)&&void 0!==r?r:this.options.packetTrailer)||!("createEncodedStreams"in e))return void(o&&this.log.warn("frame metadata transform not supported; skipping write",this.logContext));const c=e.createEncodedStreams(),d=c.readable,l=c.writable;o?a.postMessage({kind:"encode",data:{readableStream:d,writableStream:l,packetTrailer:s}},[d,l]):d.pipeTo(l)}createTransceiverRTCRtpSender(e,t,n){return pr(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Ya("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),Mo(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:i};n&&(r.sendEncodings=n);return(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender}))}createSimulcastTransceiverSender(e,t,n,i){return pr(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Ya("publisher is closed");const r={direction:"sendonly"};i&&(r.sendEncodings=i);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return yield e.setSimulcastTrackSender(n.videoCodec,a.sender),a.sender}))}createRTCRtpSender(e){return pr(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Ya("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}handleLocalConnectionQuality(e){if(!this.participantSid)return;const t=e.updates.find((e=>e.participantSid===this.participantSid));t&&(t.quality===it.LOST?this.scheduleLostQualityReconnect():this.clearLostQualityTimeout())}scheduleLostQualityReconnect(){this.lostQualityTimeout||(this.lostQualityTimeout=is.setTimeout((()=>{this.lostQualityTimeout=void 0,this._isClosed||this.pcState!==fl.Connected||this.attemptingReconnect||this.hasActivePublisherSenders()&&(this.log.warn("local connection quality lost while publishing, triggering full reconnect",this.logContext),this.fullReconnectOnNext=!0,this.handleDisconnect("connection quality lost",st.RR_PUBLISHER_FAILED))}),1e4))}clearLostQualityTimeout(){this.lostQualityTimeout&&(is.clearTimeout(this.lostQualityTimeout),this.lostQualityTimeout=void 0)}hasActivePublisherSenders(){var e,t;return null!==(t=null===(e=this.pcManager)||void 0===e?void 0:e.publisher.getSenders().some((e=>!!e.track&&"live"===e.track.readyState)))&&void 0!==t&&t}reconnect(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:st.RR_UNKNOWN;this.fullReconnectOnNext=!0,this.handleDisconnect("reconcile",e)}attemptReconnect(t){return pr(this,void 0,void 0,(function*(){var i,r,a;if(this._isClosed)return;if(this.attemptingReconnect)return void this.log.warn("already attempting reconnect, returning early");this.clearLostQualityTimeout(),(null===(i=this.clientConfiguration)||void 0===i?void 0:i.resumeConnection)!==rt.DISABLED&&(null!==(a=null===(r=this.pcManager)||void 0===r?void 0:r.currentState)&&void 0!==a?a:xd.NEW)!==xd.NEW||(this.fullReconnectOnNext=!0);const s=this.fullReconnectOnNext;this.fullReconnectOnNext=!1;let o=!1;try{this.attemptingReconnect=!0,s?yield this.restartConnection():yield this.resumeConnection(t),this.clearPendingReconnect(),o=!0}catch(n){this.reconnectAttempts+=1;let i=!0;n instanceof Ya?(this.log.debug("received unrecoverable error",{error:n}),i=!1):!s&&n instanceof ns||(this.fullReconnectOnNext=!0),i?this.handleDisconnect("reconnect",st.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(e.EngineEvent.Disconnected),yield this.close("gave up reconnecting after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms")))}finally{this.attemptingReconnect=!1,o&&this.fullReconnectOnNext&&!this._isClosed&&(this.log.debug("full reconnect requested during in-progress attempt, dispatching"),this.handleDisconnect("reconnect"))}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(n){this.log.warn("encountered error in reconnect policy",{error:n})}return null}restartConnection(t){return pr(this,void 0,void 0,(function*(){var i,r,a;try{if(!this.url||!this.token)throw new Ya("could not reconnect, url or token not saved");let r;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(e.EngineEvent.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"),new ns;r=(yield this.join(null!=t?t:this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(n){if(n instanceof za&&n.reason===e.ConnectionErrorReason.NotAllowed)throw new Ya("could not reconnect, token might be expired");throw new ns}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(e.EngineEvent.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==nd.CONNECTED)throw new ns("Signal connection got severed during reconnect");null===(i=this.regionStrategy)||void 0===i||i.resetAttempts(),this.emit(e.EngineEvent.Restarted)}catch(s){const e=yield null===(r=this.regionStrategy)||void 0===r?void 0:r.getNextUrl();if(e)return void(yield this.restartConnection(e));throw null===(a=this.regionStrategy)||void 0===a||a.resetAttempts(),s}}))}resumeConnection(t){return pr(this,void 0,void 0,(function*(){if(!this.url||!this.token)throw new Ya("could not reconnect, url or token not saved");if(!this.pcManager)throw new Ya("publisher and subscriber connections unset");let n;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(e.EngineEvent.Resuming);try{this.setupSignalClientCallbacks(),n=yield this.client.reconnect(this.url,this.token,this.participantSid,t)}catch(r){let t="";if(r instanceof Error&&(t=r.message,this.log.error(r.message,{error:r})),r instanceof za&&r.reason===e.ConnectionErrorReason.NotAllowed)throw new Ya("could not reconnect, token might be expired");if(r instanceof za&&r.reason===e.ConnectionErrorReason.LeaveRequest)throw r;throw new ns(t)}if(this.emit(e.EngineEvent.SignalResumed),n){const e=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=n.serverInfo)}else this.log.warn("Did not receive reconnect response");if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==nd.CONNECTED)throw new ns("Signal connection got severed during reconnect");this.client.setReconnected();const i=this.dataChannelForKind(Ud.RELIABLE);"open"===(null==i?void 0:i.readyState)&&null===i.id&&this.createDataChannels(),(null==n?void 0:n.lastMessageSeq)&&this.resendReliableMessagesForResume(n.lastMessageSeq).catch((e=>{this.log.warn("failed to resend reliable messages after resume",Object.assign(Object.assign({},this.logContext),{error:e}))})),this.emit(e.EngineEvent.Resumed)}))}waitForPCInitialConnection(e,t){return pr(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Ya("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)}))}waitForPCReconnected(){return pr(this,void 0,void 0,(function*(){this.pcState=fl.Reconnecting,this.log.debug("waiting for peer connection to reconnect");try{if(yield qs(2e3),!this.pcManager)throw new Ya("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=fl.Connected}catch(n){throw this.pcState=fl.Disconnected,za.internal("could not establish PC connection, ".concat(n.message))}}))}publishRpcAck(e,t){return pr(this,void 0,void 0,(function*(){const n=new Dt({destinationIdentities:[e],kind:Ot.RELIABLE,value:{case:"rpcAck",value:new Wt({requestId:t})}});yield this.sendDataPacket(n,Ud.RELIABLE)}))}sendDataPacket(e,t){return pr(this,void 0,void 0,(function*(){var n,i;if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const t=nc(e);if(t){const n=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:"encryptedPacket",value:new At({encryptedValue:n.payload,iv:n.iv,keyIndex:n.keyIndex})}}}t===Ud.RELIABLE&&(e.sequence=this.reliableChannel.nextSequence());const r=e.toBinary(),a=Math.min(null!==(i=null===(n=this.pcManager)||void 0===n?void 0:n.getMaxPublisherMessageSize())&&void 0!==i?i:64e3,64e3);if(void 0!==a&&0!==a&&r.byteLength>a)throw new Za("cannot publish data packet larger than ".concat(a," bytes (got ").concat(r.byteLength,")"));t===Ud.RELIABLE?yield this.reliableChannel.send(r,e.sequence):yield this.lossyChannel.send(r)}))}sendDataTrackFrame(e){return pr(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(Ud.DATA_TRACK_LOSSY),yield this.dataTrackChannel.send(e)}))}resendReliableMessagesForResume(e){return pr(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(Ud.RELIABLE),yield this.reliableChannel.replay(e)}))}flowControlFor(e){return this.dataChannels.channelFor(e)}waitForBufferHeadroom(e){return pr(this,void 0,void 0,(function*(){return this.flowControlFor(e).waitForHeadroomWithLock()}))}ensureDataTransportConnected(e){return pr(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var i;if(!t.pcManager)throw new Ya("PC manager is closed");const r=n?t.pcManager.subscriber:t.pcManager.publisher,a=n?"Subscriber":"Publisher";if(!r)throw za.internal("".concat(a," connection not set"));let s=!1;n||t.dataChannelForKind(e,n)||(t.createDataChannels(),s=!0),s||n||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(s=!0),s&&t.negotiate().catch((e=>{t.log.error(e)}));const o=t.dataChannelForKind(e,n);if("open"===(null==o?void 0:o.readyState))return;const c=(new Date).getTime()+t.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(r.isICEConnected&&"open"===(null===(i=t.dataChannelForKind(e,n))||void 0===i?void 0:i.readyState))return;yield qs(50)}throw za.internal("could not establish ".concat(a," connection, state: ").concat(r.getICEConnectionState()))}()}))}ensurePublisherConnected(e){return pr(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){if(!this.pcManager)return!1;const e=this.pcManager.currentState;return!![xd.CONNECTING,xd.CONNECTED].includes(e)&&(!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)&&(!(e===xd.CONNECTING&&void 0!==this.transportConnectingSince&&Date.now()-this.transportConnectingSince>this.peerConnectionTimeout)||(this.log.warn("transport stuck in connecting state",this.logContext),!1)))}negotiate(){return pr(this,void 0,void 0,(function*(){return new _a(((t,i)=>pr(this,void 0,void 0,(function*(){if(!this.pcManager)return void i(new Xa("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.dataChannels.hasPublisherChannels||this.createDataChannels();const r=new AbortController,a=()=>{r.abort(),this.log.debug("engine disconnected while negotiation was ongoing"),t()};this.isClosed&&i(new Xa("cannot negotiate on closed engine")),this.on(e.EngineEvent.Closing,a),this.on(e.EngineEvent.Restarting,a),this.pcManager.publisher.off(Sd,this.onRtpMapAvailable),this.pcManager.publisher.once(Sd,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(r),t()}catch(n){if(r.signal.aborted)return void t();n instanceof Xa&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",st.RR_UNKNOWN),n instanceof Error?i(n):i(new Error(String(n)))}finally{this.off(e.EngineEvent.Closing,a),this.off(e.EngineEvent.Restarting,a)}}))))}))}dataChannelForKind(e,t){return this.dataChannels.getHandle(e,t)}sendSyncState(e,t,n){var i,r,a,s;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup");const o=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),d=null===(i=this.pcManager.subscriber)||void 0===i?void 0:i.getRemoteDescription(),l=null===(r=this.pcManager.subscriber)||void 0===r?void 0:r.getLocalDescription(),u=null===(s=null===(a=this.signalOpts)||void 0===a?void 0:a.autoSubscribe)||void 0===s||s,h=new Array,p=new Array;e.forEach((e=>{e.isDesired!==u&&h.push(e.trackSid),e.isEnabled||p.push(e.trackSid)})),this.client.sendSyncState(new Ai({answer:"publisher-only"===this.pcManager.mode?c?ad({sdp:c.sdp,type:c.type}):void 0:l?ad({sdp:l.sdp,type:l.type}):void 0,offer:"publisher-only"===this.pcManager.mode?o?ad({sdp:o.sdp,type:o.type}):void 0:d?ad({sdp:d.sdp,type:d.type}):void 0,subscription:new ri({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:Ms(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:p,datachannelReceiveStates:this.reliableReceivedState.map(((e,t)=>new Li({publisherSid:t,lastSeq:e}))),publishDataTracks:n.map((e=>new Kn({info:Ac.toProtobuf(e)})))}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){const e=[],t=(t,n)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new Ni({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(Ud.LOSSY),Un.PUBLISHER),t(this.dataChannelForKind(Ud.RELIABLE),Un.PUBLISHER),t(this.dataChannelForKind(Ud.LOSSY,!0),Un.SUBSCRIBER),t(this.dataChannelForKind(Ud.RELIABLE,!0),Un.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&is.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){no()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){no()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const n=null===(t=this.pcManager)||void 0===t?void 0:t.getMidForReceiver(e);if(n){const e=Object.entries(this.midToTrackId).find((e=>F(e,1)[0]===n));if(e)return e[1]}}}function yl(e,t){const n=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=n,t.participantIdentity=n;const i=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=i,t.destinationIdentities=i}const bl=or(e.LoggerNames.Region),Tl=5e3;class Sl{static fetchRegionSettings(e,t,i){return pr(this,void 0,void 0,(function*(){const r=yield Sl.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 n=e.get("Cache-Control");if(n){const e=null===(t=n.match(/(?:^|[,\s])max-age=(\d+)/))||void 0===t?void 0:t[1];if(e)return parseInt(e,10)}}(n.headers),t=e?1e3*e:Tl;return{regionSettings:yield n.json(),updatedAtInMs:Date.now(),maxAgeInMs:t}}throw 401===n.status?za.notAllowed("Could not fetch region settings: ".concat(n.statusText),n.status):za.internal("Could not fetch region settings: ".concat(n.statusText))}catch(n){throw n instanceof za?n:(null==i?void 0:i.aborted)?za.cancelled("Region fetching was aborted"):za.serverUnreachable("Could not fetch region settings, ".concat(n instanceof Error?"".concat(n.name,": ").concat(n.message):n))}finally{r()}}))}static scheduleRefetch(t,n,i){return pr(this,void 0,void 0,(function*(){const r=Sl.settingsTimeouts.get(t.hostname);clearTimeout(r),Sl.settingsTimeouts.set(t.hostname,setTimeout((()=>pr(this,void 0,void 0,(function*(){try{const e=yield Sl.fetchRegionSettings(t,n);Sl.updateCachedRegionSettings(t,n,e)}catch(r){if(r instanceof za&&r.reason===e.ConnectionErrorReason.NotAllowed)return void bl.debug("token is not valid, cancelling auto region refresh");bl.debug("auto refetching of region settings failed",{error:r}),Sl.scheduleRefetch(t,n,i)}}))),i))}))}static updateCachedRegionSettings(e,t,n){Sl.cache.set(e.hostname,n),Sl.scheduleRefetch(e,t,n.maxAgeInMs)}static stopRefetch(e){const t=Sl.settingsTimeouts.get(e);t&&(clearTimeout(t),Sl.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=Sl.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout((()=>{const t=Sl.connectionTrackers.get(e);t&&0===t.connectionCount&&(bl.debug("stopping region refetch after disconnect delay",{hostname:e}),Sl.stopRefetch(e)),t&&(t.cleanupTimeout=void 0)}),3e4))}static cancelCleanup(e){const t=Sl.connectionTrackers.get(e);(null==t?void 0:t.cleanupTimeout)&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=Sl.connectionTrackers.get(e);t||(t={connectionCount:0},Sl.connectionTrackers.set(e,t)),t.connectionCount++,Sl.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=Sl.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),0===t.connectionCount&&Sl.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){var t;this.token=e;const n=this.getServerUrl(),i=Sl.cache.get(n.hostname);Sl.scheduleRefetch(this.serverUrl,this.token,null!==(t=null==i?void 0:i.maxAgeInMs)&&void 0!==t?t:Tl)}isCloud(){return ro(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return pr(this,void 0,void 0,(function*(){return Sl.fetchRegionSettings(this.serverUrl,this.token,e)}))}getNextBestRegionUrl(e){return pr(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=Sl.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),Sl.updateCachedRegionSettings(this.serverUrl,this.token,t));const n=t.regionSettings.regions.filter((e=>!this.attemptedRegions.find((t=>t.url===e.url))));if(n.length>0){const e=n[0];return this.attemptedRegions.push(e),bl.info("switching to region: ".concat(e.region),{region:e.region}),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){Sl.updateCachedRegionSettings(this.serverUrl,this.token,e)}}function El(){return new CompressionStream("deflate-raw")}function Cl(){return new DecompressionStream("deflate-raw")}function wl(e,t){return pr(this,void 0,void 0,(function*(){const n=new DecompressionStream("deflate-raw"),i=n.writable.getWriter();return i.write(e).catch((()=>{})),i.close().catch((()=>{})),Rl(n.readable,t)}))}function Rl(t,n){return pr(this,void 0,void 0,(function*(){const i=t.getReader(),r=[];let a=0;for(;;){const t=yield i.read(),s=t.done,o=t.value;if(s)break;if(r.push(o),a+=o.byteLength,"number"==typeof n&&a>n)throw yield i.cancel(),new ts("Decompressed payload exceeds the maximum payload size of ".concat(n," bytes"),e.DataStreamErrorReason.PayloadTooLarge)}const s=new Uint8Array(a);let o=0;for(const e of r)s.set(e,o),o+=e.byteLength;return s}))}Sl.cache=new Map,Sl.settingsTimeouts=new Map,Sl.connectionTrackers=new Map,Sl.fetchLock=new r;const Pl=15e3;class Il{get info(){return this._info}validateBytesReceived(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if("number"==typeof this.totalByteSize&&0!==this.totalByteSize){if(t&&this.bytesReceived<this.totalByteSize)throw new ts("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),e.DataStreamErrorReason.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new ts("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),e.DataStreamErrorReason.LengthExceeded)}}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,n)}}class _l extends Il{[Symbol.asyncIterator](){const e=this.reader.getReader();e.closed.catch((()=>{}));const t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>pr(this,void 0,void 0,(function*(){var n;try{const t=this.signal;if(null==t?void 0:t.aborted)throw t.reason;const i=yield new Promise(((n,i)=>{if(t){const r=()=>i(t.reason);t.addEventListener("abort",r,{once:!0}),e.read().then(n,i).finally((()=>{t.removeEventListener("abort",r)}))}else e.read().then(n,i)}));return i.done?(this.validateBytesReceived(!0),"number"==typeof this.totalByteSize&&(null===(n=this.onProgress)||void 0===n||n.call(this,1)),{done:!0,value:void 0}):(this.handleChunkReceived(i.value),{done:!1,value:i.value.content})}catch(i){throw t(),i}})),return(){return pr(this,void 0,void 0,(function*(){return t(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return pr(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var n,i,r,a;let s=new Set;const o=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=fr(o);!(n=(c=yield l.next()).done);d=!0){a=c.value,d=!1;const e=a;s.add(e)}}catch(u){i={error:u}}finally{try{d||n||!(r=l.return)||(yield r.call(l))}finally{if(i)throw i.error}}return Array.from(s)}()}))}}class Ml extends Il{[Symbol.asyncIterator](){const t=this.reader.getReader();t.closed.catch((()=>{}));const n=new TextDecoder("utf-8"),i=this.signal,r=()=>{t.releaseLock(),this.signal=void 0};return{next:()=>pr(this,void 0,void 0,(function*(){var a;try{if(null==i?void 0:i.aborted)throw i.reason;const r=yield new Promise(((e,n)=>{if(i){const r=()=>n(i.reason);i.addEventListener("abort",r,{once:!0}),t.read().then(e,n).finally((()=>{i.removeEventListener("abort",r)}))}else t.read().then(e,n)}));if(r.done)return this.validateBytesReceived(!0),"number"==typeof this.totalByteSize&&(null===(a=this.onProgress)||void 0===a||a.call(this,1)),{done:!0,value:void 0};{let t;this.handleChunkReceived(r.value);try{t=n.decode(r.value.content)}catch(s){throw new ts("Cannot decode datastream chunk ".concat(r.value.chunkIndex," as text: ").concat(s),e.DataStreamErrorReason.DecodeFailed)}return{done:!1,value:t}}}catch(s){throw r(),s}})),return(){return pr(this,void 0,void 0,(function*(){return r(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return pr(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var n,i,r,a;let s="";const o=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=fr(o);!(n=(c=yield l.next()).done);d=!0){a=c.value,d=!1;s+=a}}catch(u){i={error:u}}finally{try{d||n||!(r=l.return)||(yield r.call(l))}finally{if(i)throw i.error}}return s}()}))}}class Dl{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:5e9;this.log=ar,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[],this.maxPayloadByteLength=e}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){const e=this.bufferedPackets;this.bufferedPackets=[];for(const t of e){const e=t.packet,n=t.encryptionType;this.handleDataStreamPacket(e,n)}}registerTextStreamHandler(t,n){if(this.textStreamHandlers.has(t))throw new ts('A text stream handler for topic "'.concat(t,'" has already been set.'),e.DataStreamErrorReason.HandlerAlreadyRegistered);this.textStreamHandlers.set(t,n)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(t,n){if(this.byteStreamHandlers.has(t))throw new ts('A byte stream handler for topic "'.concat(t,'" has already been set.'),e.DataStreamErrorReason.HandlerAlreadyRegistered);this.byteStreamHandlers.set(t,n)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(t){const n=Array.from(this.textStreamControllers.entries()).filter((e=>e[1].sendingParticipantIdentity===t)),i=Array.from(this.byteStreamControllers.entries()).filter((e=>e[1].sendingParticipantIdentity===t));if(n.length>0||i.length>0){const s=new ts("Participant ".concat(t," unexpectedly disconnected in the middle of sending data"),e.DataStreamErrorReason.AbnormalEnd);for(const e of i){var r=F(e,2);const t=r[0];r[1].controller.error(s),this.byteStreamControllers.delete(t)}for(const e of n){var a=F(e,2);const t=a[0];a[1].controller.error(s),this.textStreamControllers.delete(t)}}}handleDataStreamPacket(e,t){if(this.isConnected)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!'))}else this.bufferedPackets.push({packet:e,encryptionType:t})}handleStreamHeader(t,n,i){var r;switch(t.contentHeader.case){case"byteHeader":{const a=this.byteStreamHandlers.get(t.topic);if(!a)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",t.topic);let s;const o={id:t.streamId,name:null!==(r=t.contentHeader.value.name)&&void 0!==r?r:"unknown",mimeType:t.mimeType,size:t.totalLength?Number(t.totalLength):void 0,topic:t.topic,timestamp:Ro(t.timestamp),attributes:t.attributes,encryptionType:i};let c;switch(t.compression){case rn.DEFLATE_RAW:if(!Fo())return void ar.warn("Data stream ".concat(t.streamId," received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping..."));c=!0;break;case rn.NONE:c=!1;break;default:return void ar.warn("Data stream ".concat(t.streamId," received with unknown compression type ").concat(t.compression,", dropping..."))}const d=t.inlineContent;if(void 0!==d)return void a(new _l(o,Ol(t.streamId,c?wl(d,this.maxPayloadByteLength):d),Ro(t.totalLength)),{identity:n});const l=new ReadableStream({start:i=>{if(s=i,this.byteStreamControllers.has(t.streamId))throw new ts("A data stream read is already in progress for a stream with id ".concat(t.streamId,"."),e.DataStreamErrorReason.AlreadyOpened);this.byteStreamControllers.set(t.streamId,{info:o,controller:s,startTime:Date.now(),sendingParticipantIdentity:n})}});return void a(new _l(o,c?function(e,t,n){return e.pipeThrough(Al(t)).pipeThrough(Ll()).pipeThrough(Cl()).pipeThrough(Nl(t,n)).pipeThrough(function(e){let t=0;return new TransformStream({transform:(n,i)=>{n.byteLength>0&&(i.enqueue(new cn({streamId:e,chunkIndex:Po(t),content:n})),t+=1)}})}(t))}(l,t.streamId,this.maxPayloadByteLength):l.pipeThrough(Al(t.streamId)),Ro(t.totalLength)),{identity:n})}case"textHeader":{const r=this.textStreamHandlers.get(t.topic);if(!r)return void this.log.debug("ignoring incoming text stream due to no handler for topic",t.topic);let a;const s={id:t.streamId,mimeType:t.mimeType,size:t.totalLength?Number(t.totalLength):void 0,topic:t.topic,timestamp:Number(t.timestamp),attributes:t.attributes,encryptionType:i,attachedStreamIds:t.contentHeader.value.attachedStreamIds};let o;switch(t.compression){case rn.DEFLATE_RAW:if(!Fo())return void ar.warn("Data stream ".concat(t.streamId," received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping..."));o=!0;break;case rn.NONE:o=!1;break;default:return void ar.warn("Data stream ".concat(t.streamId," received with unknown compression type ").concat(t.compression,", dropping..."))}const c=t.inlineContent;if(void 0!==c){const e=o?wl(c,this.maxPayloadByteLength):c;return void r(new Ml(s,Ol(t.streamId,e),Ro(t.totalLength)),{identity:n})}const d=new ReadableStream({start:i=>{if(a=i,this.textStreamControllers.has(t.streamId))throw new ts("A data stream read is already in progress for a stream with id ".concat(t.streamId,"."),e.DataStreamErrorReason.AlreadyOpened);this.textStreamControllers.set(t.streamId,{info:s,controller:a,startTime:Date.now(),sendingParticipantIdentity:n})}});return void r(new Ml(s,o?function(t,n,i){return t.pipeThrough(Al(n)).pipeThrough(Ll()).pipeThrough(Cl()).pipeThrough(Nl(n,i)).pipeThrough(function(t){const n=new TextDecoder("utf-8"),i=new TextEncoder;let r=0;const a=i=>{try{return i?n.decode(i,{stream:!0}):n.decode()}catch(r){throw new ts("Cannot decode compressed data stream ".concat(t," as text: ").concat(r),e.DataStreamErrorReason.DecodeFailed)}};return new TransformStream({transform:(e,n)=>{const s=a(e);s.length>0&&(n.enqueue(new cn({streamId:t,chunkIndex:Po(r),content:i.encode(s)})),r+=1)},flush:e=>{const n=a();n.length>0&&(e.enqueue(new cn({streamId:t,chunkIndex:Po(r),content:i.encode(n)})),r+=1)}})}(n))}(d,t.streamId,this.maxPayloadByteLength):d.pipeThrough(Al(t.streamId)),Ro(t.totalLength)),{identity:n})}}}handleStreamChunk(t,n){const i=this.byteStreamControllers.get(t.streamId);i&&(i.info.encryptionType!==n?(i.controller.error(new ts("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)),this.byteStreamControllers.delete(t.streamId)):i.controller.enqueue(t));const r=this.textStreamControllers.get(t.streamId);r&&(r.info.encryptionType!==n?(r.controller.error(new ts("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(r.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)),this.textStreamControllers.delete(t.streamId)):r.controller.enqueue(t))}handleStreamTrailer(t,n){const i=this.textStreamControllers.get(t.streamId);i&&(i.info.encryptionType!==n?i.controller.error(new ts("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),t.attributes),t.reason?i.controller.error(new ts("Data stream ".concat(t.streamId," closed abnormally: ").concat(t.reason),e.DataStreamErrorReason.AbnormalEnd)):i.controller.close()),this.textStreamControllers.delete(t.streamId));const r=this.byteStreamControllers.get(t.streamId);r&&(r.info.encryptionType!==n?r.controller.error(new ts("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(r.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)):(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),t.attributes),t.reason?r.controller.error(new ts("Data stream ".concat(t.streamId," closed abnormally: ").concat(t.reason),e.DataStreamErrorReason.AbnormalEnd)):r.controller.close()),this.byteStreamControllers.delete(t.streamId))}}function Ol(e,t){return new ReadableStream({start:n=>pr(this,void 0,void 0,(function*(){const i=yield t;n.enqueue(new cn({streamId:e,chunkIndex:BigInt(0),content:i})),n.close()}))})}function Al(t){let n=-1;return new TransformStream({transform:(i,r)=>{const a=Ro(i.chunkIndex);if(a<=n)ar.warn("ignoring duplicate chunk ".concat(a," ").concat(i.version>0?"(version ".concat(i.version,")"):""," for data stream ").concat(t," (last processed: ").concat(n,")"));else{if(a>n+1)throw new ts("Missing chunk(s) ".concat(n+1,"..").concat(a-1," for data stream ").concat(t," - cannot reassemble payload"),e.DataStreamErrorReason.Incomplete);n=a,0!==i.content.length&&r.enqueue(i)}}})}function Ll(){return new TransformStream({transform:(e,t)=>{t.enqueue(e.content)}})}function Nl(t,n){let i=0;return new TransformStream({transform:(r,a)=>{if(i+=r.byteLength,i>n)throw new ts("Data stream ".concat(t," exceeds the maximum payload size of ").concat(n," bytes"),e.DataStreamErrorReason.PayloadTooLarge);a.enqueue(r)}})}class xl{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return pr(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 Ul extends xl{}class Fl extends xl{}function Bl(e,t,n){var i;return new on({streamId:e.id,mimeType:e.mimeType,topic:e.topic,timestamp:Po(e.timestamp),totalLength:Po(e.size),attributes:e.attributes,compression:null!==(i=null==n?void 0:n.compression)&&void 0!==i?i:rn.NONE,inlineContent:null==n?void 0:n.inlineContent,contentHeader:{case:"textHeader",value:new an({version:null==t?void 0:t.version,attachedStreamIds:e.attachedStreamIds,replyToStreamId:null==t?void 0:t.replyToStreamId,operationType:"update"===(null==t?void 0:t.type)?nn.UPDATE:nn.CREATE})}})}function jl(e,t){var n;return new on({streamId:e.id,mimeType:e.mimeType,topic:e.topic,timestamp:Po(e.timestamp),totalLength:Po(e.size),attributes:e.attributes,compression:null!==(n=null==t?void 0:t.compression)&&void 0!==n?n:rn.NONE,inlineContent:null==t?void 0:t.inlineContent,contentHeader:{case:"byteHeader",value:new sn({name:e.name})}})}function ql(e,t){return new Dt({destinationIdentities:t,value:{case:"streamHeader",value:e}})}const Vl=new TextEncoder;class Wl{constructor(e,t,n,i,r){this.engine=e,this.log=t,this.getRemoteParticipantClientProtocol=n,this.getRemoteParticipantCapabilities=i,this.getAllRemoteParticipantIdentities=r}setupEngine(e){this.engine=e}sendText(e,t){return pr(this,void 0,void 0,(function*(){var n,i,r,a,s;const o=crypto.randomUUID(),c=Vl.encode(e),d=c.byteLength,l=null===(n=null==t?void 0:t.compress)||void 0===n||n;let u={id:o,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==t?void 0:t.topic)&&void 0!==i?i:"",size:d,attributes:null==t?void 0:t.attributes,encryptionType:(null===(r=this.engine.e2eeManager)||void 0===r?void 0:r.isDataChannelEncryptionEnabled)?ft.GCM:ft.NONE};let h=l&&Fo()&&this.allRecipientsSupportV2(null==t?void 0:t.destinationIdentities)&&this.allRecipientsSupportCompression(null==t?void 0:t.destinationIdentities)?Hl.fromStream(Uo(c).pipeThrough(El())):null;if((!(null==t?void 0:t.attachments)||0===t.attachments.length)&&this.allRecipientsSupportV2(null==t?void 0:t.destinationIdentities)){let e=c,n=rn.NONE;if(h){const t=yield h.collect();t.byteLength<c.byteLength&&(e=t,n=rn.DEFLATE_RAW)}const i=ql(Bl(u,void 0,{compression:n,inlineContent:e}),null==t?void 0:t.destinationIdentities);if(i.toBinary().byteLength<=Pl)return yield this.engine.sendDataPacket(i,Ud.RELIABLE),null===(a=null==t?void 0:t.onProgress)||void 0===a||a.call(t,1),u}const p=null===(s=null==t?void 0:t.attachments)||void 0===s?void 0:s.map((()=>crypto.randomUUID())),m=p?p.length+1:1,g=new Array(m).fill(0),v=(e,n)=>{var i;g[n]=e,null===(i=null==t?void 0:t.onProgress)||void 0===i||i.call(t,g.reduce(((e,t)=>e+t),0)/m)};if(h){u.attachedStreamIds=p;const e=ql(Bl(u,void 0,{compression:rn.DEFLATE_RAW}),null==t?void 0:t.destinationIdentities);yield this.sendChunkedByteStream(e,o,null==t?void 0:t.destinationIdentities,h.stream().pipeThrough(Kl(c.length,(e=>v(e,0))))),0===c.length&&v(1,0)}else{const n=yield this.streamText({streamId:o,totalSize:d,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:p,attributes:null==t?void 0:t.attributes});yield n.write(e),v(1,0),yield n.close(),u=n.info}return(null==t?void 0:t.attachments)&&p&&(yield Promise.all(t.attachments.map(((e,n)=>pr(this,void 0,void 0,(function*(){return this._sendFile(p[n],e,{topic:t.topic,mimeType:e.type,destinationIdentities:t.destinationIdentities,compress:t.compress,onProgress:e=>{v(e,n+1)}})})))))),u}))}sendBytes(e,t){return pr(this,void 0,void 0,(function*(){var n,i,r,a,s,o,c;const d=crypto.randomUUID(),l=null==t?void 0:t.destinationIdentities,u=null===(n=null==t?void 0:t.compress)||void 0===n||n,h={id:d,name:null!==(i=null==t?void 0:t.name)&&void 0!==i?i:"unknown",mimeType:null!==(r=null==t?void 0:t.mimeType)&&void 0!==r?r:"application/octet-stream",timestamp:Date.now(),topic:null!==(a=null==t?void 0:t.topic)&&void 0!==a?a:"",size:e.byteLength,attributes:null==t?void 0:t.attributes,encryptionType:(null===(s=this.engine.e2eeManager)||void 0===s?void 0:s.isDataChannelEncryptionEnabled)?ft.GCM:ft.NONE},p=Kl(e.length,null==t?void 0:t.onProgress);let m=u&&Fo()&&this.allRecipientsSupportV2(l)&&this.allRecipientsSupportCompression(l)?Hl.fromStream(Uo(e).pipeThrough(p).pipeThrough(El())):null;if(this.allRecipientsSupportV2(l)){let n=e,i=rn.NONE;if(m){const t=yield m.collect();t.byteLength<e.byteLength&&(n=t,i=rn.DEFLATE_RAW)}const r=ql(jl(h,{compression:i,inlineContent:n}),l);if(r.toBinary().byteLength<=Pl)return yield this.engine.sendDataPacket(r,Ud.RELIABLE),null===(o=null==t?void 0:t.onProgress)||void 0===o||o.call(t,1),h}const g=ql(jl(h,{compression:m?rn.DEFLATE_RAW:rn.NONE}),l),v=m?m.stream():Uo(e).pipeThrough(p);return yield this.sendChunkedByteStream(g,d,l,v),0===e.length&&(null===(c=null==t?void 0:t.onProgress)||void 0===c||c.call(t,1)),h}))}allRecipientsSupportV2(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every((e=>this.getRemoteParticipantClientProtocol(e)>=2))}allRecipientsSupportCompression(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every((e=>this.getRemoteParticipantCapabilities(e).includes(Xt.CAP_COMPRESSION_DEFLATE_RAW)))}sendChunkedByteStream(e,t,n,i){return pr(this,void 0,void 0,(function*(){var r,a,s,o;const c=this.engine;yield zl(c,e);let d=0;try{for(var l,u=!0,h=fr(function(e,t){return vr(this,arguments,(function*(){const n=e.getReader();let i=new Uint8Array(0);try{for(;;){const e=yield gr(n.read()),r=e.done,a=e.value;if(r)break;if(0===a.byteLength)continue;const s=new Uint8Array(i.byteLength+a.byteLength);for(s.set(i),s.set(a,i.byteLength),i=s;i.byteLength>=t;)yield yield gr(i.slice(0,t)),i=i.slice(t)}i.byteLength>0&&(yield yield gr(i))}finally{n.releaseLock()}}))}(i,Pl));!(r=(l=yield h.next()).done);u=!0){o=l.value,u=!1;const e=new Dt({destinationIdentities:n,value:{case:"streamChunk",value:new cn({content:o,streamId:t,chunkIndex:Po(d)})}});yield c.sendDataPacket(e,Ud.RELIABLE),d+=1}}catch(p){a={error:p}}finally{try{u||r||!(s=h.return)||(yield s.call(h))}finally{if(a)throw a.error}}yield Gl(t,n,c)}))}streamText(t){return pr(this,void 0,void 0,(function*(){var n,i,r;const a=null!==(n=null==t?void 0:t.streamId)&&void 0!==n?n:crypto.randomUUID(),s=null==t?void 0:t.destinationIdentities,o={id:a,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==t?void 0:t.topic)&&void 0!==i?i:"",size:null==t?void 0:t.totalSize,attributes:null==t?void 0:t.attributes,encryptionType:(null===(r=this.engine.e2eeManager)||void 0===r?void 0:r.isDataChannelEncryptionEnabled)?ft.GCM:ft.NONE,attachedStreamIds:null==t?void 0:t.attachedStreamIds},c=ql(Bl(o,t),s);yield zl(this.engine,c);let d=0;const l=this.engine,u=new WritableStream({write(e){return pr(this,void 0,void 0,(function*(){for(const t of function(e,t){const n=[];let i=(new TextEncoder).encode(e);for(;i.length>t;){let e=t;for(;e>0;){const t=i[e];if(void 0!==t&&128!=(192&t))break;e--}n.push(i.slice(0,e)),i=i.slice(e)}return i.length>0&&n.push(i),n}(e,Pl)){const e=new cn({content:t,streamId:a,chunkIndex:Po(d)}),n=new Dt({destinationIdentities:s,value:{case:"streamChunk",value:e}});yield l.sendDataPacket(n,Ud.RELIABLE),d+=1}}))},close(){return pr(this,void 0,void 0,(function*(){yield Gl(a,s,l)}))},abort(e){console.log("Sink error:",e)}});let h=()=>pr(this,void 0,void 0,(function*(){yield p.close()}));l.once(e.EngineEvent.Closing,h);const p=new Ul(u,o,(()=>this.engine.off(e.EngineEvent.Closing,h)));return p}))}sendFile(e,t){return pr(this,void 0,void 0,(function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}}))}_sendFile(e,t,n){return pr(this,void 0,void 0,(function*(){var i,r,a,s,o;const c=null==n?void 0:n.destinationIdentities,d=(null===(i=null==n?void 0:n.compress)||void 0===i||i)&&Fo()&&this.allRecipientsSupportV2(c)&&this.allRecipientsSupportCompression(c),l={id:e,name:t.name,mimeType:null!==(r=null==n?void 0:n.mimeType)&&void 0!==r?r:t.type,topic:null!==(a=null==n?void 0:n.topic)&&void 0!==a?a:"",timestamp:Date.now(),size:t.size,encryptionType:(null===(s=this.engine.e2eeManager)||void 0===s?void 0:s.isDataChannelEncryptionEnabled)?ft.GCM:ft.NONE},u=ql(jl(l,{compression:d?rn.DEFLATE_RAW:rn.NONE}),c),h=t.stream().pipeThrough(Kl(t.size,null==n?void 0:n.onProgress)),p=d?h.pipeThrough(El()):h;return yield this.sendChunkedByteStream(u,e,c,p),0===t.size&&(null===(o=null==n?void 0:n.onProgress)||void 0===o||o.call(n,1)),l}))}streamBytes(e){return pr(this,void 0,void 0,(function*(){var t,n,i,a,s;const o=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),c=null==e?void 0:e.destinationIdentities,d={id:o,mimeType:null!==(n=null==e?void 0:e.mimeType)&&void 0!==n?n:"application/octet-stream",topic:null!==(i=null==e?void 0:e.topic)&&void 0!==i?i:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!==(a=null==e?void 0:e.name)&&void 0!==a?a:"unknown",encryptionType:(null===(s=this.engine.e2eeManager)||void 0===s?void 0:s.isDataChannelEncryptionEnabled)?ft.GCM:ft.NONE},l=ql(jl(d),c);yield zl(this.engine,l);let u=0;const h=new r,p=this.engine,m=this.log,g=new WritableStream({write(e){return pr(this,void 0,void 0,(function*(){const t=yield h.lock();let n=0;try{for(;n<e.byteLength;){const t=e.slice(n,n+Pl),i=new Dt({destinationIdentities:c,value:{case:"streamChunk",value:new cn({content:t,streamId:o,chunkIndex:Po(u)})}});yield p.sendDataPacket(i,Ud.RELIABLE),u+=1,n+=t.byteLength}}finally{t()}}))},close(){return pr(this,void 0,void 0,(function*(){yield Gl(o,c,p)}))},abort(e){m.error("Sink error:",e)}});return new Fl(g,d)}))}}class Hl{constructor(e){this.state=e}static fromStream(e){return new Hl({type:"stream",stream:e})}collect(){return pr(this,void 0,void 0,(function*(){switch(this.state.type){case"stream":const e=yield Rl(this.state.stream);return this.state={type:"collected",bytes:e},e;case"collected":return this.state.bytes}}))}stream(){switch(this.state.type){case"stream":return this.state.stream;case"collected":return Uo(this.state.bytes)}}}function Kl(e,t){let n=0;return new TransformStream({transform(i,r){n+=i.byteLength,t&&"number"==typeof e&&e>0&&t(Math.min(n/e,1)),r.enqueue(i)}})}function zl(t,n){return pr(this,void 0,void 0,(function*(){if(n.toBinary().byteLength>Pl)throw new ts("data stream header exceeds the ".concat(Pl,"-byte limit; reduce attribute size"),e.DataStreamErrorReason.HeaderTooLarge);yield t.sendDataPacket(n,Ud.RELIABLE)}))}function Gl(e,t,n){return pr(this,void 0,void 0,(function*(){const i=new Dt({destinationIdentities:t,value:{case:"streamTrailer",value:new dn({streamId:e})}});yield n.sendDataPacket(i,Ud.RELIABLE)}))}function Jl(e){if(0===e.length){return(new AbortController).signal}if(1===e.length)return e[0];for(const i of e)if(i.aborted)return i;const t=new AbortController,n=Array(e.length);return e.forEach(((e,i)=>{const r=()=>{t.abort(e.reason),(()=>{for(const e of n)e()})()};e.addEventListener("abort",r),n[i]=()=>e.removeEventListener("abort",r)})),t.signal}function Ql(e){const t=new AbortController;return setTimeout((()=>{t.abort(new DOMException("signal timed out after ".concat(e," ms"),"TimeoutError"))}),e),t.signal}var Yl,Xl,Zl;!function(e){e[e.TooShort=0]="TooShort",e[e.HeaderOverrun=1]="HeaderOverrun",e[e.MissingExtWords=2]="MissingExtWords",e[e.UnsupportedVersion=3]="UnsupportedVersion",e[e.InvalidHandle=4]="InvalidHandle",e[e.MalformedExt=5]="MalformedExt"}(Yl||(Yl={}));class $l extends Fa{constructor(e,t,n){super(19,e,n),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=Yl[t]}static tooShort(){return new $l("Too short to contain a valid header",Yl.TooShort)}static headerOverrun(){return new $l("Header exceeds total packet length",Yl.HeaderOverrun)}static missingExtWords(){return new $l("Extension word indicator is missing",Yl.MissingExtWords)}static unsupportedVersion(e){return new $l("Unsupported version ".concat(e),Yl.UnsupportedVersion)}static invalidHandle(e){return new $l("invalid track handle: ".concat(e.message),Yl.InvalidHandle,{cause:e})}static malformedExt(e){return new $l("Extension with tag ".concat(e," is malformed"),Yl.MalformedExt)}}!function(e){e[e.TooSmallForHeader=0]="TooSmallForHeader",e[e.TooSmallForPayload=1]="TooSmallForPayload"}(Xl||(Xl={}));class eu extends Fa{constructor(e,t,n){super(19,e,n),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=Xl[t]}static tooSmallForHeader(){return new eu("Buffer cannot fit header",Xl.TooSmallForHeader)}static tooSmallForPayload(){return new eu("Buffer cannot fit payload",Xl.TooSmallForPayload)}}class tu{toBinary(){const e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),n=new DataView(t),i=this.toBinaryInto(n);if(e!==i)throw new Error("".concat(this.constructor.name,".toBinary: written bytes (").concat(i," bytes) not equal to allocated array buffer length (").concat(e," bytes)."));return new Uint8Array(t)}}!function(e){e[e.UserTimestamp=2]="UserTimestamp",e[e.E2ee=1]="E2ee"}(Zl||(Zl={}));class nu extends tu{}class iu extends nu{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return 2+iu.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,iu.tag),t+=1,e.setUint8(t,iu.lengthBytes),t+=1,e.setBigUint64(t,this.timestamp),t+=8;const n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackUserTimestampExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}toJSON(){return{tag:iu.tag,lengthBytes:iu.lengthBytes,timestamp:this.timestamp}}}iu.tag=Zl.UserTimestamp,iu.lengthBytes=8;class ru extends nu{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return 2+ru.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,ru.tag),t+=1,e.setUint8(t,ru.lengthBytes),t+=1,e.setUint8(t,this.keyIndex),t+=1;for(let i=0;i<this.iv.length;i+=1)e.setUint8(t,this.iv[i]),t+=1;const n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackE2eeExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}toJSON(){return{tag:ru.tag,lengthBytes:ru.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}}ru.tag=Zl.E2ee,ru.lengthBytes=13;class au extends tu{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){t+=this.e2ee.toBinaryInto(e)}if(this.userTimestamp){t+=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t))}const n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackExtensions.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}static fromBinary(e){const t=Ic(e);let n,i,r=0;for(;t.byteLength-r>=2;){const e=t.getUint8(r);r+=1;const a=t.getUint8(r);if(r+=1,0!==e)switch(e){case Zl.UserTimestamp:if(t.byteLength-r<iu.lengthBytes)throw $l.malformedExt(e);n=new iu(t.getBigUint64(r)),r+=a;break;case Zl.E2ee:if(t.byteLength-r<ru.lengthBytes)throw $l.malformedExt(e);const s=t.getUint8(r),o=new Uint8Array(12);for(let e=0;e<o.length;e+=1){let n=r;n+=1,n+=1*e,o[e]=t.getUint8(n)}i=new ru(s,o),r+=a;break;default:if(t.byteLength-r<a)throw $l.malformedExt(e);r+=a}}return[new au({userTimestamp:n,e2ee:i}),t.byteLength]}toJSON(){var e,t,n,i;return{userTimestamp:null!==(t=null===(e=this.userTimestamp)||void 0===e?void 0:e.toJSON())&&void 0!==t?t:null,e2ee:null!==(i=null===(n=this.e2ee)||void 0===n?void 0:n.toJSON())&&void 0!==i?i:null}}}const su={from:e=>({payload:e.payload,extensions:new au({userTimestamp:e.userTimestamp?new iu(e.userTimestamp):void 0})}),lossyIntoFrame(e){var t;return{payload:e.payload,userTimestamp:null===(t=e.extensions.userTimestamp)||void 0===t?void 0:t.timestamp}}},ou=Symbol.for("lk.track"),cu=Symbol.for("lk.data-track");class du{constructor(e,t,n){this.trackSymbol=ou,this.isLocal=!1,this.typeSymbol=cu,this.info=e,this.manager=t,this.publisherIdentity=n.publisherIdentity}subscribe(e){try{const t=F(this.manager.openSubscriptionStream(this.info.sid,null==e?void 0:e.signal,null==e?void 0:e.bufferSize),2),n=t[0];return t[1].catch((()=>{})),n}catch(t){throw t}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}}class lu extends tu{constructor(e){var t;super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=null!==(t=e.extensions)&&void 0!==t?t:new au}extensionsMetrics(){const e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((2+e)/4);return{lengthBytes:e,lengthWords:t,paddingLengthBytes:4*t-2-e}}toBinaryLengthBytes(){const e=this.extensionsMetrics(),t=e.lengthBytes,n=e.paddingLengthBytes;let i=12;return t>0&&(i+=2+t+n),i}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw eu.tooSmallForHeader();let t,n=0;switch(this.marker){case uu.Inter:t=0;break;case uu.Final:t=1;break;case uu.Start:t=2;break;case uu.Single:t=3}n|=t<<3;const i=this.extensionsMetrics(),r=i.lengthBytes,a=i.lengthWords,s=i.paddingLengthBytes;r>0&&(n|=4);let o=0;if(e.setUint8(o,n),o+=1,e.setUint8(o,0),o+=1,e.setUint16(o,this.trackHandle),o+=2,e.setUint16(o,this.sequence.value),o+=2,e.setUint16(o,this.frameNumber.value),o+=2,e.setUint32(o,this.timestamp.asTicks()),o+=4,r>0){const t=a-1;e.setUint16(o,t),o+=2;o+=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+o));for(let n=0;n<s;n+=1)e.setUint8(o,0),o+=1}const c=this.toBinaryLengthBytes();if(o!==c)throw new Error("DataTrackPacketHeader.toBinaryInto: Wrote ".concat(o," bytes but expected length was ").concat(c," bytes"));return c}static fromBinary(e){const t=Ic(e);if(t.byteLength<12)throw $l.tooShort();let i=0;const r=t.getUint8(i);i+=1;const a=r>>5&7;if(a>0)throw $l.unsupportedVersion(a);let s;switch(r>>3&3){case 2:s=uu.Start;break;case 1:s=uu.Final;break;case 3:s=uu.Single;break;default:s=uu.Inter}const o=(r>>2&1)>0;let c;i+=1;try{c=Dc.fromNumber(t.getUint16(i))}catch(n){throw n instanceof Mc&&(n.isReason(_c.Reserved)||n.isReason(_c.TooLarge))?$l.invalidHandle(n):n}i+=2;const d=wc.u16(t.getUint16(i));i+=2;const l=wc.u16(t.getUint16(i));i+=2;const u=Rc.fromRtpTicks(t.getUint32(i));i+=4;let h=new au;if(o){if(t.byteLength-i<2)throw $l.missingExtWords();let e=t.getUint16(i);i+=2;let n=4*(e+1)-2;if(i+n>t.byteLength)throw $l.headerOverrun();let r=new DataView(t.buffer,t.byteOffset+i,n);const a=F(au.fromBinary(r),2);h=a[0],i+=a[1]}return[new lu({marker:s,trackHandle:c,sequence:d,frameNumber:l,timestamp:u,extensions:h}),i]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}}var uu;!function(e){e[e.Start=0]="Start",e[e.Inter=1]="Inter",e[e.Final=2]="Final",e[e.Single=3]="Single"}(uu||(uu={}));class hu extends tu{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0;if(t+=this.header.toBinaryInto(e),e.byteLength-t<this.payload.byteLength)throw eu.tooSmallForPayload();for(let i=0;i<this.payload.length;i+=1)e.setUint8(t,this.payload[i]),t+=1;const n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackPacket.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return n}static fromBinary(e){const t=Ic(e),n=F(lu.fromBinary(t),2),i=n[0],r=n[1],a=t.buffer.slice(t.byteOffset+r,t.byteOffset+t.byteLength);return[new hu(i,new Uint8Array(a)),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}}const pu=or(e.LoggerNames.DataTracks);class mu extends Fa{constructor(e,t,n,i){super(19,"Frame ".concat(n," dropped: ").concat(e),i),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=gu[t],this.frameNumber=n}static interrupted(e,t){return new mu("Interrupted by the start of a new frame ".concat(t),gu.Interrupted,e)}static unknownFrame(e){return new mu("Initial packet was never received.",gu.UnknownFrame,e)}static bufferFull(e){return new mu("Reorder buffer is full.",gu.BufferFull,e)}static incomplete(e,t,n){return new mu("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(n," packets."),gu.Incomplete,e)}}var gu,vu;!function(e){e[e.Interrupted=0]="Interrupted",e[e.UnknownFrame=1]="UnknownFrame",e[e.BufferFull=2]="BufferFull",e[e.Incomplete=3]="Incomplete"}(gu||(gu={}));class fu{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case uu.Single:return this.frameFromSingle(e,t);case uu.Start:return this.beginPartial(e,t);case uu.Inter:case uu.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){const e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){var n;if(e.header.marker!==uu.Single)throw new Error("Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ".concat(e.header.marker,"."));const i=null!==(n=null==t?void 0:t.maxPartialFrames)&&void 0!==n?n:1;if(this.partials.size>=i){const n=this.peekOldestPartialFrameNumber();if("number"!=typeof n)throw new Error("Depacketizer.frameFromSingle: no oldest frame number found, but partials.size is ".concat(this.partials.size,"."));if(this.partials.delete(n),null==t?void 0:t.throwOnInterruption)throw mu.interrupted(n,e.header.frameNumber.value);pu.warn("Data track frame ".concat(n," was interrupted by single-packet frame ").concat(e.header.frameNumber.value,", dropping."))}return{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){var n;if(e.header.marker!==uu.Start)throw new Error("Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ".concat(e.header.marker,"."));const i=e.header.sequence,r=e.header.frameNumber.value,a={startSequence:i,extensions:e.header.extensions,payloads:new Map([[i.value,e.payload]])},s=null!==(n=null==t?void 0:t.maxPartialFrames)&&void 0!==n?n:1;for(;this.partials.size>=s;){const e=this.peekOldestPartialFrameNumber();if("number"!=typeof e)break;if(this.partials.delete(e),null==t?void 0:t.throwOnInterruption)throw mu.interrupted(e,r);pu.warn("Data track partials full (max ".concat(s,"), evicted oldest frame ").concat(e," to make room for new frame ").concat(r,"."))}return this.partials.set(r,a),null}pushToPartial(e){if(e.header.marker!==uu.Inter&&e.header.marker!==uu.Final)throw new Error("Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ".concat(e.header.marker,"."));const t=e.header.frameNumber.value,n=this.partials.get(t);if(!n)throw this.partials.delete(t),mu.unknownFrame(t);if(n.payloads.size>=fu.MAX_BUFFER_PACKETS)throw this.partials.delete(t),mu.bufferFull(t);return n.payloads.has(e.header.sequence.value)&&pu.warn("Data track frame ".concat(t," received duplicate packet for sequence ").concat(e.header.sequence.value,", so replacing with newly received packet.")),n.payloads.set(e.header.sequence.value,e.payload),e.header.marker===uu.Final?this.finalize(t,n,e.header.sequence.value):null}finalize(e,t,n){const i=t.payloads.size;let r=0;for(const c of t.payloads.values())r+=c.length;const a=new Uint8Array(r);let s=t.startSequence.clone(),o=0;for(;;){const i=t.payloads.get(s.value);if(!i)break;t.payloads.delete(s.value);const r=a.length-o;if(i.length>r)throw new Error("Depacketizer.finalize: Expected at least ".concat(i.length," more bytes left in the payload buffer, only got ").concat(r," bytes."));if(a.set(i,o),o+=i.length,s.value==n)return this.partials.delete(e),{payload:a,extensions:t.extensions};s.increment()}throw this.partials.delete(e),mu.incomplete(e,i,n-t.startSequence.value+1)}}fu.MAX_BUFFER_PACKETS=128,function(e){e[e.Unpublished=0]="Unpublished",e[e.Timeout=1]="Timeout",e[e.Disconnected=2]="Disconnected",e[e.Cancelled=4]="Cancelled"}(vu||(vu={}));class ku extends Fa{constructor(e,t,n){super(22,e,n),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=vu[t]}static unpublished(){return new ku("The track has been unpublished and is no longer available",vu.Unpublished)}static timeout(){return new ku("Request to subscribe to data track timed-out",vu.Timeout)}static disconnected(){return new ku("Cannot subscribe to data track when disconnected",vu.Disconnected)}static cancelled(){return new ku("Subscription to data track cancelled by caller",vu.Cancelled)}}const yu=or(e.LoggerNames.DataTracks);class bu{constructor(e){var t,n;const i=null!==e.e2eeManager;if(e.info.usesE2ee!==i)throw new Error("IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider");const r=new fu;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=null!==(t=e.e2eeManager)&&void 0!==t?t:null,this.depacketizer=r,this.options=null!==(n=e.pipelineOptions)&&void 0!==n?n:{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return pr(this,void 0,void 0,(function*(){const t=this.depacketize(e);if(!t)return null;const n=yield this.decryptIfNeeded(t);return n||null}))}depacketize(e){let t;try{t=this.depacketizer.push(e,{throwOnInterruption:!1,maxPartialFrames:this.options.maxPartialFrames})}catch(n){return yu.warn("Data frame depacketize error: ".concat(n)),null}return t}decryptIfNeeded(e){return pr(this,void 0,void 0,(function*(){var t,n;const i=this.e2eeManager;if(!i)return e;const r=null!==(n=null===(t=e.extensions)||void 0===t?void 0:t.e2ee)&&void 0!==n?n:null;if(!r)return yu.error("Missing E2EE meta"),null;let a;try{a=yield i.handleEncryptedData(e.payload,r.iv,this.publisherIdentity,r.keyIndex)}catch(s){return yu.error("Error decrypting packet: ".concat(s)),null}return e.payload=a.payload,e}))}}const Tu=or(e.LoggerNames.DataTracks);class Su extends br.EventEmitter{constructor(e){var t;super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=null!==(t=null==e?void 0:e.e2eeManager)&&void 0!==t?t:null}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())"active"===t.subscription.type&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){const n=this.descriptors.get(e);n?(n.pipelineOptions=t,"active"===n.subscription.type&&n.subscription.pipeline.setOptions(t)):Tu.warn("Unknown track ".concat(e,", cannot set pipeline options."))}openSubscriptionStream(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16,i=null;const r=new To,a=this.descriptors.get(e),s=()=>{null==t||t.removeEventListener("abort",c)},o=()=>{s(),i?a&&this.descriptors.get(a.info.sid)===a?"active"===a.subscription.type?(a.subscription.streamControllers.delete(i),0===a.subscription.streamControllers.size&&this.unSubscribeRequest(a.info.sid)):Tu.warn("Subscription for track ".concat(e," is not active, skipping cancel...")):Tu.warn("Unknown track ".concat(e,", skipping cancel...")):Tu.warn("ReadableStream subscribed to ".concat(e," was not started."))},c=()=>{var e;i&&("active"===(null==a?void 0:a.subscription.type)&&a.subscription.streamControllers.delete(i),i.error(ku.cancelled()),null===(e=r.reject)||void 0===e||e.call(r,ku.cancelled()),o())},d=new ReadableStream({start:n=>{i=n,this.subscribeRequest(e,t).then((()=>pr(this,void 0,void 0,(function*(){var i,o,d;if(!a||this.descriptors.get(a.info.sid)!==a){Tu.error("Unknown track ".concat(e));const t=ku.disconnected();return n.error(t),void(null===(i=r.reject)||void 0===i||i.call(r,t))}if("active"!==a.subscription.type){Tu.error("Subscription for track ".concat(e," is not active"));const t=ku.disconnected();return n.error(t),void(null===(o=r.reject)||void 0===o||o.call(r,t))}(null==t?void 0:t.aborted)?c():(null==t||t.addEventListener("abort",c),a.subscription.streamControllers.set(n,s),null===(d=r.resolve)||void 0===d||d.call(r))})))).catch((e=>{var t;n.error(e),null===(t=r.reject)||void 0===t||t.call(r,e)}))},cancel:()=>{o()}},new CountQueuingStrategy({highWaterMark:n}));return[d,r.promise]}subscribeRequest(e,t){return pr(this,void 0,void 0,(function*(){const n=this.descriptors.get(e);if(!n)throw new Error("Cannot subscribe to unknown track");const i=(t,n,i)=>pr(this,void 0,void 0,(function*(){if("active"===t.subscription.type)return;if("pending"!==t.subscription.type)throw new Error("Descriptor for track ".concat(e," is not pending, found ").concat(t.subscription.type));const r=Jl([n,i].filter((e=>void 0!==e))),a=new To;t.subscription.completionFuture.promise.then((()=>{var e;return null===(e=a.resolve)||void 0===e?void 0:e.call(a)})).catch((e=>{var t;return null===(t=a.reject)||void 0===t?void 0:t.call(a,e)}));const s=()=>{var e;"pending"===t.subscription.type&&(t.subscription.pendingRequestCount-=1,(null==i?void 0:i.aborted)||t.subscription.pendingRequestCount<=0?t.subscription.cancel():null===(e=a.reject)||void 0===e||e.call(a,ku.cancelled()))};r.aborted&&s(),r.addEventListener("abort",s),yield a.promise,r.removeEventListener("abort",s)}));switch(n.subscription.type){case"none":{n.subscription={type:"pending",completionFuture:new To,pendingRequestCount:1,cancel:()=>{var e,t;const i=n.subscription;n.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:n.info.sid,subscribe:!1}),"pending"===i.type&&(null===(t=(e=i.completionFuture).reject)||void 0===t||t.call(e,r.aborted?ku.timeout():ku.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});const r=Ql(1e4);return void(yield i(n,t,r))}case"pending":return n.subscription.pendingRequestCount+=1,void(yield i(n,t));case"active":return}}))}querySubscribed(){return pr(this,void 0,void 0,(function*(){return Array.from(this.descriptors.values()).filter((e=>"active"===e.subscription.type)).map((e=>[e.info,e.publisherIdentity]))}))}unSubscribeRequest(e){var t;const n=this.descriptors.get(e);if(!n)throw new Error("Cannot subscribe to unknown track");if("active"!==n.subscription.type)return void Tu.warn("Unexpected descriptor state in unSubscribeRequest, expected active, found ".concat(null===(t=n.subscription)||void 0===t?void 0:t.type));this.closeStreamControllers(n.subscription.streamControllers,e);const i=n.subscription;n.subscription={type:"none"},this.subscriptionHandles.delete(i.subcriptionHandle),this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(const r of e){var n=F(r,2);const e=n[0];(0,n[1])();try{e.close()}catch(i){Tu.warn("Failed to close readable stream for track ".concat(t,": ").concat(i))}}}receiveSfuPublicationUpdates(e){return pr(this,void 0,void 0,(function*(){if(0===e.size)return;const t=new Map;for(const r of e.entries()){var n=F(r,2);const e=n[0],i=n[1],a=new Set;for(const t of i)a.add(t.sid),this.descriptors.has(t.sid)||this.handleSidReassigned(e,t)||(yield this.handleTrackPublished(e,t));t.set(e,a)}for(const e of t.entries()){var i=F(e,2);const t=i[0],n=i[1];let r=Array.from(this.descriptors.entries()).filter((e=>{let n=F(e,2);return n[0],n[1].publisherIdentity===t})).map((e=>F(e,1)[0])).filter((e=>!n.has(e)));for(const e of r)this.handleTrackUnpublished(e)}}))}queryPublications(){return pr(this,void 0,void 0,(function*(){return Array.from(this.descriptors.values()).map((e=>e.info))}))}handleTrackPublished(e,t){return pr(this,void 0,void 0,(function*(){if(this.descriptors.has(t.sid))return void Tu.error("Existing descriptor for track ".concat(t.sid));let n={info:t,publisherIdentity:e,subscription:{type:"none"},pipelineOptions:{}};this.descriptors.set(n.info.sid,n);const i=new du(n.info,this,{publisherIdentity:e});this.emit("trackPublished",{track:i})}))}handleSidReassigned(e,t){const n=Array.from(this.descriptors.entries()).find((n=>{let i=F(n,2);i[0];let r=i[1];return r.publisherIdentity===e&&r.info.pubHandle===t.pubHandle}));if(!n)return!1;const i=F(n,2),r=i[0],a=i[1],s=a.info,o=s.name,c=s.usesE2ee;if(o!==t.name||c!==t.usesE2ee)return Tu.warn("Info mismatch for ".concat(r,", treating as new publication")),!1;const d=t.sid;if(Tu.debug("SID reassigned: ".concat(r," -> ").concat(d)),!this.descriptors.delete(r))return!1;switch(a.info.sid=d,a.subscription.type){case"none":break;case"pending":case"active":this.emit("sfuUpdateSubscription",{sid:d,subscribe:!0})}return"active"===a.subscription.type&&this.subscriptionHandles.set(a.subscription.subcriptionHandle,d),this.descriptors.set(d,a),!0}handleTrackUnpublished(e){const t=this.descriptors.get(e);t?(this.descriptors.delete(e),"active"===t.subscription.type&&(this.closeStreamControllers(t.subscription.streamControllers,e),this.subscriptionHandles.delete(t.subscription.subcriptionHandle)),this.emit("trackUnpublished",{sid:e,publisherIdentity:t.publisherIdentity})):Tu.error("Unknown track ".concat(e))}receivedSfuSubscriberHandles(e){for(const n of e.entries()){var t=F(n,2);const e=t[0],i=t[1];this.registerSubscriberHandle(e,i)}}registerSubscriberHandle(e,t){var n,i;const r=this.descriptors.get(t);if(r)switch(r.subscription.type){case"none":return void Tu.warn("No subscription for ".concat(t));case"active":return this.subscriptionHandles.delete(r.subscription.subcriptionHandle),r.subscription.subcriptionHandle=e,void this.subscriptionHandles.set(e,t);case"pending":{Tu.debug("data track subscription activated",{sid:t,handle:e});const a=new bu({info:r.info,publisherIdentity:r.publisherIdentity,e2eeManager:this.e2eeManager,pipelineOptions:r.pipelineOptions}),s=r.subscription;r.subscription={type:"active",subcriptionHandle:e,pipeline:a,streamControllers:new Map},this.subscriptionHandles.set(e,t),null===(i=(n=s.completionFuture).resolve)||void 0===i||i.call(n)}}else Tu.error("Unknown track ".concat(t))}packetReceived(e){return pr(this,void 0,void 0,(function*(){let t;try{t=F(hu.fromBinary(e),1)[0]}catch(a){return void Tu.error("Failed to deserialize packet: ".concat(a))}const n=this.subscriptionHandles.get(t.header.trackHandle);if(!n)return void Tu.warn("Unknown subscriber handle ".concat(t.header.trackHandle));const i=this.descriptors.get(n);if(!i)return void Tu.error("Missing descriptor for track ".concat(n));if("active"!==i.subscription.type)return void Tu.warn("Received packet for track ".concat(n," without active subscription"));const r=yield i.subscription.pipeline.processPacket(t);if(r)for(const e of i.subscription.streamControllers.keys()){if(null!==e.desiredSize&&e.desiredSize<=0){Tu.warn("Cannot send frame to subscribers: readable stream is full (desiredSize is ".concat(e.desiredSize,"). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe()."));continue}const t=su.lossyIntoFrame(r);e.enqueue(t)}}))}resendSubscriptionUpdates(){for(const t of this.descriptors){var e=F(t,2);const n=e[0];"none"!==e[1].subscription.type&&this.emit("sfuUpdateSubscription",{sid:n,subscribe:!0})}}handleRemoteParticipantDisconnected(e){var t,n;for(const i of this.descriptors.values())if(i.publisherIdentity===e)switch(i.subscription.type){case"none":break;case"pending":null===(n=(t=i.subscription.completionFuture).reject)||void 0===n||n.call(t,ku.disconnected());break;case"active":this.unSubscribeRequest(i.info.sid)}}reset(){var e,t;for(const n of this.descriptors.values())this.emit("trackUnpublished",{sid:n.info.sid,publisherIdentity:n.publisherIdentity}),"pending"===n.subscription.type&&(null===(t=(e=n.subscription.completionFuture).reject)||void 0===t||t.call(e,ku.disconnected())),"active"===n.subscription.type&&this.closeStreamControllers(n.subscription.streamControllers,n.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}}class Eu extends Fa{constructor(e,t,n){super(19,e,n),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=Cu[t]}static mtuTooShort(){return new Eu("MTU is too short to send frame",Cu.MtuTooShort)}}var Cu,wu,Ru,Pu;!function(e){e[e.MtuTooShort=0]="MtuTooShort"}(Cu||(Cu={}));class Iu{constructor(e,t){this.sequence=wc.u16(0),this.frameNumber=wc.u16(0),this.clock=Pc.rtpStartingNow(Rc.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?uu.Single:0===e?uu.Start:e===t-1?uu.Final:uu.Inter}*packetize(e,t){var n;const i=this.frameNumber.getThenIncrement(),r={marker:uu.Inter,trackHandle:this.handle,sequence:wc.u16(0),frameNumber:i,timestamp:null!==(n=null==t?void 0:t.now)&&void 0!==n?n:this.clock.now(),extensions:e.extensions},a=new lu(r).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw Eu.mtuTooShort();const s=this.mtuSizeBytes-a,o=Math.ceil(e.payload.byteLength/s);for(let d=0,l=0;l<e.payload.byteLength;d=(c=[d+1,l+s])[0],l=c[1],c){var c;const t=this.sequence.getThenIncrement(),n=new lu(Object.assign(Object.assign({},r),{marker:Iu.computeFrameMarker(d,o),sequence:t})),i=Math.min(s,e.payload.byteLength-l),a=new Uint8Array(e.payload.buffer,e.payload.byteOffset+l,i);yield new hu(n,a)}}}!function(e){e[e.NotAllowed=0]="NotAllowed",e[e.DuplicateName=1]="DuplicateName",e[e.Timeout=2]="Timeout",e[e.LimitReached=3]="LimitReached",e[e.Disconnected=4]="Disconnected",e[e.Cancelled=5]="Cancelled",e[e.InvalidName=6]="InvalidName",e[e.Unknown=7]="Unknown"}(wu||(wu={}));class _u extends Fa{constructor(e,t,n){super(21,e,n),this.name="DataTrackPublishError",this.reason=t,this.reasonName=wu[t],this.rawMessage=null==n?void 0:n.rawMessage}static notAllowed(e){return new _u("Data track publishing unauthorized",wu.NotAllowed,{rawMessage:e})}static duplicateName(e){return new _u("Track name already taken",wu.DuplicateName,{rawMessage:e})}static invalidName(e){return new _u("Track name is invalid",wu.InvalidName,{rawMessage:e})}static timeout(){return new _u("Publish data track timed-out. Does the LiveKit server support data tracks?",wu.Timeout)}static limitReached(e){return new _u("Data track publication limit reached",wu.LimitReached,{rawMessage:e})}static unknown(e,t){return new _u("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),wu.Unknown)}static disconnected(){return new _u("Room disconnected",wu.Disconnected)}static cancelled(){return new _u("Publish data track cancelled by caller",wu.Cancelled)}}!function(e){e[e.TrackUnpublished=0]="TrackUnpublished",e[e.Dropped=1]="Dropped"}(Ru||(Ru={}));class Mu extends Fa{constructor(e,t,n){super(22,e,n),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=Ru[t]}static trackUnpublished(){return new Mu("Track is no longer published",Ru.TrackUnpublished)}static dropped(e){return new Mu("Frame was dropped",Ru.Dropped,{cause:e})}}!function(e){e[e.Packetizer=0]="Packetizer",e[e.Encryption=1]="Encryption"}(Pu||(Pu={}));class Du extends Fa{constructor(e,t,n){super(21,e,n),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=Pu[t]}static packetizer(e){return new Du("Error packetizing frame",Pu.Packetizer,{cause:e})}static encryption(e){return new Du("Error encrypting frame",Pu.Encryption,{cause:e})}}class Ou{constructor(t,n){this.trackSymbol=ou,this.isLocal=!0,this.typeSymbol=cu,this.handle=null,this.log=ar,this.flushedFuture=new To,this.isFlushed=!0,this.handleManagerReset=()=>{var e,t;null===(t=(e=this.flushedFuture).resolve)||void 0===t||t.call(e),this.manager.off("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.off("reset",this.handleManagerReset)},this.handleManagerPacketsFlushedChange=e=>{var t,n;this.isFlushed=e.isFlushed,e.isFlushed&&(null===(n=(t=this.flushedFuture).resolve)||void 0===n||n.call(t),this.flushedFuture=new To)},this.options=t,this.manager=n,this.log=or(e.LoggerNames.DataTracks),this.manager.on("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.on("reset",this.handleManagerReset)}static withExplicitHandle(e,t,n){const i=new Ou(e,t);return i.handle=n,i}get info(){const e=this.descriptor;return"active"===(null==e?void 0:e.type)?e.info:void 0}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return pr(this,void 0,void 0,(function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(t){throw t}}))}isPublished(){var e;return"active"===(null===(e=this.descriptor)||void 0===e?void 0:e.type)&&"unpublished"!==this.descriptor.publishState}tryPush(e){if(!this.handle)throw Mu.trackUnpublished();const t=su.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(n){throw n}}flush(){return pr(this,void 0,void 0,(function*(){if(!this.isFlushed)return this.flushedFuture.promise}))}unpublish(){return pr(this,void 0,void 0,(function*(){if(this.handle)try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}else ar.warn('Data track "'.concat(this.options.name,'" is not published, so unpublishing has no effect.'))}))}}class Au{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new Iu(e.info.pubHandle,Au.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return vr(this,arguments,(function*(){const t=yield gr(this.encryptIfNeeded(e));try{yield gr(yield*function(e){var t,n;return t={},i("next"),i("throw",(function(e){throw e})),i("return"),t[Symbol.iterator]=function(){return this},t;function i(i,r){t[i]=e[i]?function(t){return(n=!n)?{value:gr(e[i](t)),done:!1}:r?r(t):t}:r}}(fr(this.packetizer.packetize(t))))}catch(n){if(n instanceof Eu)throw Du.packetizer(n);throw n}}))}encryptIfNeeded(e){return pr(this,void 0,void 0,(function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(n){throw Du.encryption(n)}return e.payload=t.payload,e.extensions.e2ee=new ru(t.keyIndex,t.iv),e}))}}Au.TRANSPORT_MTU_BYTES=16e3;const Lu=or(e.LoggerNames.DataTracks),Nu={pending:()=>({type:"pending",completionFuture:new To}),active:(e,t)=>({type:"active",info:e,publishState:"published",pipeline:new Au({info:e,e2eeManager:t}),unpublishingFuture:new To})};class xu extends br.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new Oc,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=null!==(t=null==e?void 0:e.e2eeManager)&&void 0!==t?t:null}static withDescriptors(e){const t=new xu;return t.descriptors=e,t}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())"active"===t.type&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){var t;return null!==(t=this.descriptors.get(e))&&void 0!==t?t:null}tryProcessAndSend(e,t){return pr(this,void 0,void 0,(function*(){var n,i,r,a,s;const o=this.getDescriptor(e);if("active"!==(null==o?void 0:o.type))throw Mu.trackUnpublished();if("unpublished"===o.publishState)throw Mu.trackUnpublished();if("republishing"===o.publishState)throw Mu.dropped("Data track republishing");try{try{for(var c,d=!0,l=fr(o.pipeline.processFrame(t));!(n=(c=yield l.next()).done);d=!0){a=c.value,d=!1;const t=a,n=null!==(s=this.inFlightPacketCounter.get(e))&&void 0!==s?s:0;this.inFlightPacketCounter.set(e,n+1),0===n&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!1}),this.emit("packetAvailable",{handle:e,bytes:t.toBinary()})}}catch(u){i={error:u}}finally{try{d||n||!(r=l.return)||(yield r.call(l))}finally{if(i)throw i.error}}}catch(h){throw Mu.dropped(h)}}))}handlePacketSendComplete(e){var t;let n=(null!==(t=this.inFlightPacketCounter.get(e))&&void 0!==t?t:0)-1;n<0&&(Lu.warn("OutgoingDataTrackManager.handlePacketSendComplete: inFlightPacketCounter was decremented below 0 (got ".concat(this.inFlightPacketCounter," - resetting to 0. Were more packets send than were emitted?")),n=0),this.inFlightPacketCounter.set(e,n),0===n&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!0})}publishRequest(e,t){return pr(this,void 0,void 0,(function*(){const n=this.handleAllocator.get();if(!n)throw _u.limitReached();const i=Ql(1e4),r=t?Jl([t,i]):i;if(this.descriptors.has(n))throw new Error("Descriptor for handle already exists");const a=Nu.pending();this.descriptors.set(n,a);const s=()=>{var e,t;const r=this.descriptors.get(n);r?(this.descriptors.delete(n),this.emit("sfuUnpublishRequest",{handle:n}),"pending"===r.type&&(null===(t=(e=r.completionFuture).reject)||void 0===t||t.call(e,i.aborted?_u.timeout():_u.cancelled()))):Lu.warn("No descriptor for ".concat(n))};return r.aborted?(s(),a.completionFuture.promise.then((()=>n))):(r.addEventListener("abort",s),this.emit("sfuPublishRequest",{handle:n,name:e.name,usesE2ee:null!==this.e2eeManager}),yield a.completionFuture.promise,r.removeEventListener("abort",s),this.emit("trackPublished",{track:Ou.withExplicitHandle(e,this,n)}),n)}))}queryPublished(){return Array.from(this.descriptors.values()).filter((e=>"active"===e.type)).map((e=>e.info))}unpublishRequest(e){return pr(this,void 0,void 0,(function*(){const t=this.descriptors.get(e);t?"active"===t.type?(this.emit("sfuUnpublishRequest",{handle:e}),yield t.unpublishingFuture.promise,this.inFlightPacketCounter.delete(e),this.emit("trackUnpublished",{sid:t.info.sid})):Lu.warn("Track ".concat(e," not active")):Lu.warn("No descriptor for ".concat(e))}))}receivedSfuPublishResponse(e,t){var n,i,r,a;const s=this.descriptors.get(e);if(s)switch(this.descriptors.delete(e),s.type){case"pending":if("ok"===t.type){const r=t.data;Lu.debug("SFU accepted publish request for handle ".concat(e),{sid:r.sid});const a=r.usesE2ee?this.e2eeManager:null;this.descriptors.set(r.pubHandle,Nu.active(r,a)),null===(i=(n=s.completionFuture).resolve)||void 0===i||i.call(n)}else Lu.debug("SFU rejected publish request for handle ".concat(e),{error:t.error}),null===(a=(r=s.completionFuture).reject)||void 0===a||a.call(r,t.error);return;case"active":if("republishing"!==s.publishState)return void Lu.warn("Track ".concat(e," already active"));if("error"===t.type)return void Lu.warn("Republish failed for track ".concat(e));Lu.debug("Track ".concat(e," republished")),s.info.sid=t.data.sid,s.publishState="published",this.descriptors.set(s.info.pubHandle,s)}else Lu.warn("No descriptor for ".concat(e))}receivedSfuUnpublishResponse(e){var t,n;const i=this.descriptors.get(e);i?(this.descriptors.delete(e),"active"===i.type?(i.publishState="unpublished",null===(n=(t=i.unpublishingFuture).resolve)||void 0===n||n.call(t)):Lu.warn("Track ".concat(e," not active"))):Lu.warn("No descriptor for ".concat(e))}sfuWillRepublishTracks(){var e,t;for(const i of this.descriptors.entries()){var n=F(i,2);const r=n[0],a=n[1];switch(a.type){case"pending":this.descriptors.delete(r),null===(t=(e=a.completionFuture).reject)||void 0===t||t.call(e,_u.disconnected());break;case"active":a.publishState="republishing",this.emit("sfuPublishRequest",{handle:a.info.pubHandle,name:a.info.name,usesE2ee:a.info.usesE2ee})}}}reset(){return pr(this,void 0,void 0,(function*(){var e,t,n,i;this.handleAllocator.reset();for(const r of this.descriptors.values())switch(r.type){case"pending":null===(t=(e=r.completionFuture).reject)||void 0===t||t.call(e,_u.disconnected());break;case"active":null===(i=(n=r.unpublishingFuture).resolve)||void 0===i||i.call(n),yield this.unpublishRequest(r.info.pubHandle)}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit("reset")}))}}class Uu extends Error{constructor(e,t,n,i){super(t),this.code=e,this.message=Vu(t,Uu.MAX_MESSAGE_BYTES),this.data=n?Vu(n,Uu.MAX_DATA_BYTES):void 0,void 0!==(null==i?void 0:i.cause)&&(this.cause=null==i?void 0:i.cause)}static fromProto(e){return new Uu(e.code,e.message,e.data)}toProto(){return new Kt({code:this.code,message:this.message,data:this.data})}static builtIn(e,t,n){return new Uu(Uu.ErrorCode[e],Uu.ErrorMessage[e],t,n)}}Uu.MAX_MESSAGE_BYTES=256,Uu.MAX_DATA_BYTES=15360,Uu.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},Uu.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"};const Fu="lk.rpc_request",Bu="lk.rpc_response";var ju;!function(e){e.RPC_REQUEST_ID="lk.rpc_request_id",e.RPC_REQUEST_METHOD="lk.rpc_request_method",e.RPC_REQUEST_RESPONSE_TIMEOUT_MS="lk.rpc_request_response_timeout_ms",e.RPC_REQUEST_VERSION="lk.rpc_request_version"}(ju||(ju={}));function qu(e){return(new TextEncoder).encode(e).length}function Vu(e,t){if(qu(e)<=t)return e;let n=0,i=e.length;const r=new TextEncoder;for(;n<i;){const a=Math.floor((n+i+1)/2);r.encode(e.slice(0,a)).length<=t?n=a:i=a-1}return e.slice(0,n)}class Wu extends br.EventEmitter{constructor(e,t,n,i){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n,this.getServerVersion=i}performRpc(e){return pr(this,arguments,void 0,(function(e){var t=this;let n=e.destinationIdentity,i=e.method,r=e.payload,a=e.responseTimeout,s=void 0===a?15e3:a;return function*(){const e=t.getRemoteParticipantClientProtocol(n);if(qu(r)>15360&&e<1)throw Uu.builtIn("REQUEST_PAYLOAD_TOO_LARGE");const a=t.getServerVersion();if(a&&lo(a,"1.8.0")<0)throw Uu.builtIn("UNSUPPORTED_SERVER");const o=Math.max(s,8e3),c=crypto.randomUUID(),d=new To;let l=null;const u=setTimeout((()=>{var e;t.pendingAcks.delete(c),null===(e=d.reject)||void 0===e||e.call(d,Uu.builtIn("CONNECTION_TIMEOUT")),t.pendingResponses.delete(c),null!==l&&clearTimeout(l)}),7e3);t.pendingAcks.set(c,{resolve:()=>{clearTimeout(u)},participantIdentity:n}),t.pendingResponses.set(c,{completionFuture:d,participantIdentity:n}),yield t.publishRpcRequest(n,c,i,r,o,e),l=setTimeout((()=>{var e;t.pendingResponses.delete(c),null===(e=d.reject)||void 0===e||e.call(d,Uu.builtIn("RESPONSE_TIMEOUT"))}),s);const h=d.promise.finally((()=>{clearTimeout(l),t.pendingAcks.has(c)&&(t.log.warn("RPC response received before ack",c),t.pendingAcks.delete(c),clearTimeout(u))}));return[c,h]}()}))}publishRpcRequest(e,t,n,i,r,a){return pr(this,void 0,void 0,(function*(){a>=1?yield this.outgoingDataStreamManager.sendText(i,{topic:Fu,destinationIdentities:[e],attributes:{[ju.RPC_REQUEST_ID]:t,[ju.RPC_REQUEST_METHOD]:n,[ju.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:"".concat(r),[ju.RPC_REQUEST_VERSION]:"".concat(2)}}):this.emit("sendDataPacket",{packet:new Dt({destinationIdentities:[e],kind:Ot.RELIABLE,value:{case:"rpcRequest",value:new Vt({id:t,method:n,payload:i,responseTimeoutMs:r,version:1})}})})}))}handleIncomingDataStream(e,t,i){return pr(this,void 0,void 0,(function*(){const r=i[ju.RPC_REQUEST_ID];if(!r)return void this.log.warn("RPC data stream malformed: ".concat(ju.RPC_REQUEST_ID," not set."));const a=this.pendingResponses.get(r);if(a&&a.participantIdentity!==t)return void this.log.warn("RPC response stream for ".concat(r," arrived from unexpected sender ").concat(t,", expected ").concat(a.participantIdentity,". Ignoring."));let s;try{s=yield e.readAll()}catch(n){return this.log.warn("Error reading RPC response payload: ".concat(n)),void this.handleIncomingRpcResponseFailure(r,Uu.builtIn("APPLICATION_ERROR","Error reading RPC response payload",{cause:n}))}this.handleIncomingRpcResponseSuccess(r,s)}))}handleIncomingRpcResponseSuccess(e,t){var n,i;const r=this.pendingResponses.get(e);r?(null===(i=(n=r.completionFuture).resolve)||void 0===i||i.call(n,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcResponseFailure(e,t){var n,i;const r=this.pendingResponses.get(e);r?(null===(i=(n=r.completionFuture).reject)||void 0===i||i.call(n,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):this.log.error("Ack received for unexpected RPC request: ".concat(e))}handleParticipantDisconnected(e){var t;for(const a of this.pendingAcks){var n=F(a,2);const t=n[0];n[1].participantIdentity===e&&this.pendingAcks.delete(t)}for(const a of this.pendingResponses){var i=F(a,2);const n=i[0];var r=i[1];const s=r.participantIdentity,o=r.completionFuture;s===e&&(null===(t=o.reject)||void 0===t||t.call(o,Uu.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(n))}}}class Hu extends br.EventEmitter{constructor(e,t,n){super(),this.rpcHandlers=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n}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)}handleIncomingRpcRequest(e,t){return pr(this,void 0,void 0,(function*(){var n;if(this.publishRpcAck(e,t.id),1!==t.version)return void this.publishRpcResponsePacket(e,t.id,null,Uu.builtIn("UNSUPPORTED_VERSION"));const i=this.rpcHandlers.get(t.method);if(!i)return void this.publishRpcResponsePacket(e,t.id,null,Uu.builtIn("UNSUPPORTED_METHOD"));let r;try{r=yield i({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(a){let i;return a instanceof Uu?i=a:(this.log.warn("Uncaught error returned by RPC handler for ".concat(t.method,". Returning APPLICATION_ERROR instead."),a),i=Uu.builtIn("APPLICATION_ERROR","Uncaught error: ".concat(null!==(n=null==a?void 0:a.message)&&void 0!==n?n:a),{cause:a})),void this.publishRpcResponsePacket(e,t.id,null,i)}yield this.publishRpcResponse(e,t.id,null!=r?r:"")}))}handleIncomingDataStream(e,t,i){return pr(this,void 0,void 0,(function*(){const r=i[ju.RPC_REQUEST_ID],a=i[ju.RPC_REQUEST_METHOD],s=parseInt(i[ju.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),o=parseInt(i[ju.RPC_REQUEST_VERSION],10);if(!r||!a||Number.isNaN(s)||Number.isNaN(o))return this.log.warn("RPC data stream malformed: ".concat(ju.RPC_REQUEST_ID," / ").concat(ju.RPC_REQUEST_METHOD," / ").concat(ju.RPC_REQUEST_RESPONSE_TIMEOUT_MS," / ").concat(ju.RPC_REQUEST_VERSION," not set.")),void this.publishRpcResponsePacket(t,r,null,Uu.builtIn("APPLICATION_ERROR","RPC data stream malformed"));if(this.publishRpcAck(t,r),2!==o)return void this.publishRpcResponsePacket(t,r,null,Uu.builtIn("UNSUPPORTED_VERSION"));let c;try{c=yield e.readAll()}catch(n){return this.log.warn("Error reading RPC request payload: ".concat(n)),void this.publishRpcResponsePacket(t,r,null,Uu.builtIn("APPLICATION_ERROR","Error reading RPC request payload",{cause:n}))}const d=this.rpcHandlers.get(a);if(!d)return void this.publishRpcResponsePacket(t,r,null,Uu.builtIn("UNSUPPORTED_METHOD"));let l;try{l=yield d({requestId:r,callerIdentity:t,payload:c,responseTimeout:s})}catch(u){let e;return u instanceof Uu?e=u:(this.log.warn("Uncaught error returned by RPC handler for ".concat(a,". Returning APPLICATION_ERROR instead."),u),e=Uu.builtIn("APPLICATION_ERROR")),void this.publishRpcResponsePacket(t,r,null,e)}yield this.publishRpcResponse(t,r,null!=l?l:"")}))}publishRpcAck(e,t){this.emit("sendDataPacket",{packet:new Dt({destinationIdentities:[e],kind:Ot.RELIABLE,value:{case:"rpcAck",value:new Wt({requestId:t})}})})}publishRpcResponsePacket(e,t,n,i){this.emit("sendDataPacket",{packet:new Dt({destinationIdentities:[e],kind:Ot.RELIABLE,value:{case:"rpcResponse",value:new Ht({requestId:t,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:null!=n?n:""}})}})})}publishRpcResponse(e,t,n){return pr(this,void 0,void 0,(function*(){if(this.getRemoteParticipantClientProtocol(e)>=1)return void(yield this.outgoingDataStreamManager.sendText(n,{topic:Bu,destinationIdentities:[e],attributes:{[ju.RPC_REQUEST_ID]:t}}));if(qu(n)>15360)return this.log.warn("RPC Response payload too large for request ".concat(t,". To send larger responses, consider updating the sending client.")),void this.publishRpcResponsePacket(e,t,null,Uu.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"));this.publishRpcResponsePacket(e,t,n,null)}))}}class Ku extends uc{constructor(e,t,n,i,r,a){super(e,t,xs.Kind.Audio,n,a),this.monitorReceiver=()=>pr(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=lc(e,this.prevStats)),this.prevStats=e})),this.audioContext=i,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):n.volume=e;io()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(io())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return pr(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(Js(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&Js(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(t,n){this.disconnectWebAudio(),this.sourceNode=t.createMediaStreamSource(n.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach((e=>{i.connect(e),i=e})),this.gainNode=t.createGain(),i.connect(this.gainNode),this.gainNode.connect(t.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==t.state&&t.resume().then((()=>{"running"!==t.state&&this.emit(e.TrackEvent.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((t=>{this.emit(e.TrackEvent.AudioPlaybackFailed,t)}))}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 pr(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 zu extends br.EventEmitter{constructor(t,n,i,r){var a;super(),this.metadataMuted=!1,this.encryption=ft.NONE,this.log=ar,this.handleMuted=()=>{this.emit(e.TrackEvent.Muted)},this.handleUnmuted=()=>{this.emit(e.TrackEvent.Unmuted)},this.log=or(null!==(a=null==r?void 0:r.loggerName)&&void 0!==a?a:e.LoggerNames.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=t,this.trackSid=n,this.trackName=i,this.source=xs.Source.Unknown}setTrack(t){this.track&&(this.track.off(e.TrackEvent.Muted,this.handleMuted),this.track.off(e.TrackEvent.Unmuted,this.handleUnmuted)),this.track=t,t&&(t.on(e.TrackEvent.Muted,this.handleMuted),t.on(e.TrackEvent.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),Ds(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==ft.NONE}get audioTrack(){if(_o(this.track))return this.track}get videoTrack(){if(Mo(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=xs.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===xs.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}!function(e){var t,n;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",(n=e.PermissionStatus||(e.PermissionStatus={})).Allowed="allowed",n.NotAllowed="not_allowed"}(zu||(zu={}));class Gu extends zu{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(t,n,i,r){super(t,n.sid,n.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(e.TrackEvent.Ended)},this.handleCpuConstrained=()=>{this.track&&Mo(this.track)&&this.emit(e.TrackEvent.CpuConstrained,this.track)},this.updateInfo(n),this.setTrack(i)}setTrack(t){this.track&&(this.track.off(e.TrackEvent.Ended,this.handleTrackEnded),this.track.off(e.TrackEvent.CpuConstrained,this.handleCpuConstrained)),super.setTrack(t),t&&(t.on(e.TrackEvent.Ended,this.handleTrackEnded),t.on(e.TrackEvent.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 pr(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){return pr(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){return pr(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){return pr(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}getTrackFeatures(){var e;if(_o(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(ct.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(ct.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(ct.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(ct.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||n.add(ct.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(ct.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}return[]}}function Ju(e,t){return pr(this,void 0,void 0,(function*(){null!=e||(e={});let i=!1;const r=Os(e),a=r.audioProcessor,s=r.videoProcessor,o=r.optionsWithoutProcessor;let c=o.audio,d=o.video;if(a&&"object"==typeof o.audio&&(o.audio.processor=a),s&&"object"==typeof o.video&&(o.video.processor=s),e.audio&&"object"==typeof o.audio&&"string"==typeof o.audio.deviceId){const e=o.audio.deviceId;o.audio.deviceId={exact:e},i=!0,c=Object.assign(Object.assign({},o.audio),{deviceId:{ideal:e}})}if(o.video&&"object"==typeof o.video&&"string"==typeof o.video.deviceId){const e=o.video.deviceId;o.video.deviceId={exact:e},i=!0,d=Object.assign(Object.assign({},o.video),{deviceId:{ideal:e}})}!0===o.audio?o.audio={deviceId:"default"}:"object"==typeof o.audio&&null!==o.audio&&(o.audio=Object.assign(Object.assign({},o.audio),{deviceId:o.audio.deviceId||"default"})),!0===o.video?o.video={deviceId:"default"}:"object"!=typeof o.video||o.video.deviceId||(o.video.deviceId="default");const l=Es(Ts(o,Od,Ad)),u=navigator.mediaDevices.getUserMedia(l);o.audio&&(Sc.userMediaPromiseMap.set("audioinput",u),u.catch((()=>Sc.userMediaPromiseMap.delete("audioinput")))),o.video&&(Sc.userMediaPromiseMap.set("videoinput",u),u.catch((()=>Sc.userMediaPromiseMap.delete("videoinput"))));try{const e=yield u;return yield Promise.all(e.getTracks().map((n=>pr(this,void 0,void 0,(function*(){let i;const r="audio"===n.kind?l.audio:l.video;"boolean"!=typeof r&&(i=r);const o=n.getSettings().deviceId;(null==i?void 0:i.deviceId)&&Eo(i.deviceId)!==o?i.deviceId=o:i||(i={deviceId:o});const c=function(e,t,n){switch(e.kind){case"audio":return new $d(e,t,!1,void 0,n);case"video":return new hl(e,t,!1,n);default:throw new Ja("unsupported track type: ".concat(e.kind))}}(n,i,t);return c.kind===xs.Kind.Video?c.source=xs.Source.Camera:c.kind===xs.Kind.Audio&&(c.source=xs.Source.Microphone),c.mediaStream=e,_o(c)&&a?yield c.setProcessor(a):Mo(c)&&s&&(yield c.setProcessor(s)),c})))))}catch(n){if(!i)throw n;return Ju(Object.assign(Object.assign({},e),{audio:c,video:d}),t)}}))}function Qu(e){return pr(this,void 0,void 0,(function*(){return(yield Ju({audio:!1,video:null==e||e}))[0]}))}function Yu(e){return pr(this,void 0,void 0,(function*(){return(yield Ju({audio:null==e||e,video:!1}))[0]}))}var Xu,Zu;e.ConnectionQuality=void 0,(Xu=e.ConnectionQuality||(e.ConnectionQuality={})).Excellent="excellent",Xu.Good="good",Xu.Poor="poor",Xu.Lost="lost",Xu.Unknown="unknown";class $u extends br.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===gt.AGENT}get isActive(){var e;return(null===(e=this.participantInfo)||void 0===e?void 0:e.state)===mt.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(t,n,i,r,a,s){let o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:gt.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=e.ConnectionQuality.Unknown,this.log=ar,this.loggerOptions=s,this.log=or(null!==(c=null==s?void 0:s.loggerName)&&void 0!==c?c:e.LoggerNames.Participant,(()=>this.logContext)),this.setMaxListeners(100),this.sid=t,this.identity=n,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=null!=a?a:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const t of this.trackPublications){const n=F(t,2)[1];if(n.source===e)return n}}getTrackPublicationByName(e){for(const t of this.trackPublications){const n=F(t,2)[1];if(n.trackName===e)return n}}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new To,this.once(e.ParticipantEvent.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(xs.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(xs.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(xs.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(t){var n;return!(this.participantInfo&&this.participantInfo.sid===t.sid&&this.participantInfo.version>t.version)&&(this.identity=t.identity,this.sid=t.sid,this._setName(t.name),this._setMetadata(t.metadata),this._setAttributes(t.attributes),t.state===mt.ACTIVE&&(null===(n=this.participantInfo)||void 0===n?void 0:n.state)!==mt.ACTIVE&&this.emit(e.ParticipantEvent.Active),t.permission&&this.setPermissions(t.permission),this.participantInfo=t,!0)}_setMetadata(t){const n=this.metadata!==t,i=this.metadata;this.metadata=t,n&&this.emit(e.ParticipantEvent.ParticipantMetadataChanged,i)}_setName(t){const n=this.name!==t;this.name=t,n&&this.emit(e.ParticipantEvent.ParticipantNameChanged,t)}_setAttributes(t){const n=function(e,t){var n;void 0===e&&(e={}),void 0===t&&(t={});const i=[...Object.keys(t),...Object.keys(e)],r={};for(const a of i)e[a]!==t[a]&&(r[a]=null!==(n=t[a])&&void 0!==n?n:"");return r}(this.attributes,t);this._attributes=t,Object.keys(n).length>0&&this.emit(e.ParticipantEvent.AttributesChanged,n)}setPermissions(t){var n,i,r,a,s,o;const c=this.permissions,d=t.canPublish!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublish)||t.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||t.canPublishData!==(null===(r=this.permissions)||void 0===r?void 0:r.canPublishData)||t.hidden!==(null===(a=this.permissions)||void 0===a?void 0:a.hidden)||t.recorder!==(null===(s=this.permissions)||void 0===s?void 0:s.recorder)||t.canPublishSources.length!==this.permissions.canPublishSources.length||t.canPublishSources.some(((e,t)=>{var n;return e!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishSources[t])}))||t.canSubscribeMetrics!==(null===(o=this.permissions)||void 0===o?void 0:o.canSubscribeMetrics);return this.permissions=t,d&&this.emit(e.ParticipantEvent.ParticipantPermissionsChanged,c),d}setIsSpeaking(t){t!==this.isSpeaking&&(this.isSpeaking=t,t&&(this.lastSpokeAt=new Date),this.emit(e.ParticipantEvent.IsSpeakingChanged,t))}setConnectionQuality(t){const n=this._connectionQuality;this._connectionQuality=function(t){switch(t){case it.EXCELLENT:return e.ConnectionQuality.Excellent;case it.GOOD:return e.ConnectionQuality.Good;case it.POOR:return e.ConnectionQuality.Poor;case it.LOST:return e.ConnectionQuality.Lost;default:return e.ConnectionQuality.Unknown}}(t),n!==this._connectionQuality&&this.emit(e.ParticipantEvent.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=>_o(t.track)&&t.track.setAudioContext(e)))}addTrackPublication(t){this.log.debug("adding track publication",{trackSid:t.trackSid,source:t.source,kind:t.kind}),t.on(e.TrackEvent.Muted,(()=>{this.emit(e.ParticipantEvent.TrackMuted,t)})),t.on(e.TrackEvent.Unmuted,(()=>{this.emit(e.ParticipantEvent.TrackUnmuted,t)}));const n=t;switch(n.track&&(n.track.sid=t.trackSid),this.trackPublications.set(t.trackSid,t),t.kind){case xs.Kind.Audio:this.audioTrackPublications.set(t.trackSid,t);break;case xs.Kind.Video:this.videoTrackPublications.set(t.trackSid,t)}}}class eh extends $u{constructor(t,i,a,s,o,c,d,l){super(t,i,void 0,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=ft.NONE,this.e2eeStateMutex=new r,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new To)},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,n,i,r,a;this.reconnectFuture&&(this.reconnectFuture.promise.catch((e=>this.log.warn(e.message))),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===(i=(n=this.signalConnectedFuture).reject)||void 0===i||i.call(n,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),null===(a=null===(r=this.activeAgentFuture)||void 0===r?void 0:r.reject)||void 0===a||a.call(r,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,n;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new To),null===(n=(t=this.signalConnectedFuture).resolve)||void 0===n||n.call(t)},this.handleSignalRequestResponse=e=>{const t=e.requestId,n=e.reason,i=e.message,r=this.pendingSignalRequests.get(t);switch(r&&(n!==Wi.OK&&r.reject(new es(i,n)),this.pendingSignalRequests.delete(t)),e.request.case){case"publishDataTrack":{let t;switch(e.reason){case Wi.NOT_ALLOWED:t=_u.notAllowed(e.message);break;case Wi.DUPLICATE_NAME:t=_u.duplicateName(e.message);break;case Wi.INVALID_NAME:t=_u.invalidName(e.message);break;case Wi.LIMIT_EXCEEDED:t=_u.limitReached(e.message);break;default:t=_u.unknown(e.reason,e.message)}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(e.request.value.pubHandle,{type:"error",error:t});break}}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map((e=>function(e){var t,n,i;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new _i({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(n=e.participantSid)&&void 0!==n?n:"",allTracks:null!==(i=e.allowAll)&&void 0!==i&&i,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",Ds(e))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Ds(e)),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Ds(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.onTrackCpuConstrained=(t,n)=>{this.log.debug("track cpu constrained",Ds(n)),this.emit(e.ParticipantEvent.LocalTrackCpuConstrained,t,n)},this.handleSubscribedQualityUpdate=e=>pr(this,void 0,void 0,(function*(){var t,n,i,r,a;if(!(null===(a=this.roomOptions)||void 0===a?void 0:a.dynacast))return;const s=this.videoTrackPublications.get(e.trackSid);if(!s)return void this.log.warn("received subscribed quality update for unknown track",{trackSid:e.trackSid});if(!s.videoTrack)return;const o=yield s.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=fr(o);!(t=(c=yield l.next()).done);d=!0){r=c.value,d=!1;const e=r;gs(e)&&(this.log.debug("publish ".concat(e," for ").concat(s.videoTrack.sid),Ds(s)),yield this.publishAdditionalCodecForTrack(s.videoTrack,e,s.options))}}catch(u){n={error:u}}finally{try{d||t||!(i=l.return)||(yield i.call(l))}finally{if(n)throw n.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",{trackSid:e.trackSid})},this.handleTrackEnded=e=>pr(this,void 0,void 0,(function*(){if(e.source===xs.Source.ScreenShare||e.source===xs.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Ds(e)),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(Oo(e)||Do(e))try{if(no())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===xs.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Ds(e)),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(n){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Ds(e)),Oo(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(n){this.log.warn("could not restart track, muting instead",Ds(e)),yield e.mute()}})),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=a,this.roomOptions=s,this.setupEngine(a),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.roomOutgoingDataStreamManager=o,this.roomOutgoingDataTrackManager=c,this.rpcClientManager=d,this.rpcServerManager=l}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==ft.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(t){var n;this.engine=t,this.engine.on(e.EngineEvent.RemoteMute,((e,t)=>{const n=this.trackPublications.get(e);n&&n.track&&(t?n.mute():n.unmute())})),(null===(n=this.signalConnectedFuture)||void 0===n?void 0:n.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(e.EngineEvent.Connected,this.handleReconnected).on(e.EngineEvent.SignalConnected,this.handleSignalConnected).on(e.EngineEvent.SignalRestarted,this.handleReconnected).on(e.EngineEvent.SignalResumed,this.handleReconnected).on(e.EngineEvent.Restarting,this.handleReconnecting).on(e.EngineEvent.Resuming,this.handleReconnecting).on(e.EngineEvent.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(e.EngineEvent.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(e.EngineEvent.Closing,this.handleClosing).on(e.EngineEvent.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return pr(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:e})}))}setName(e){return pr(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:e})}))}setAttributes(e){return pr(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:e})}))}requestMetadataUpdate(e){return pr(this,arguments,void 0,(function(e){var t=this;let i=e.metadata,r=e.name,a=e.attributes;return function*(){return new _a(((e,s)=>pr(t,void 0,void 0,(function*(){var t,o;try{let n=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(o=null!=r?r:this.name)&&void 0!==o?o:"",a),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{s(e),n=!0},values:{name:r,metadata:i,attributes:a}});performance.now()-d<5e3&&!n;){if((!r||this.name===r)&&(!i||this.metadata===i)&&(!a||Object.entries(a).every((e=>{let t=F(e,2),n=t[0],i=t[1];return this.attributes[n]===i||""===i&&!this.attributes[n]}))))return this.pendingSignalRequests.delete(c),void e();yield qs(50)}s(new es("Request to update local metadata timed out","TimeoutError"))}catch(n){n instanceof Error?s(n):s(new Error(String(n)))}}))))}()}))}setCameraEnabled(e,t,n){return this.setTrackEnabled(xs.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(xs.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(xs.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return pr(this,void 0,void 0,(function*(){const t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?ft.GCM:ft.NONE,yield Promise.all(this.pendingPublishPromises.values()),0===this.trackPublications.size||Array.from(this.trackPublications.values()).every((t=>t.isEncrypted===e)))return;yield this.republishAllTracks(void 0,!1)}finally{t()}}))}setTrackEnabled(t,i,r,a){return pr(this,void 0,void 0,(function*(){var s,o;this.log.debug("setTrackEnabled",{source:t,enabled:i}),this.republishPromise&&(yield this.republishPromise);let c=this.getTrackPublication(t);if(i)if(c)yield c.unmute();else{let i;if(this.pendingPublishing.has(t)){const e=yield this.waitForPendingPublicationOfSource(t);return e||this.log.info("waiting for pending publication promise timed out",{source:t}),yield null==e?void 0:e.unmute(),e}this.pendingPublishing.add(t);try{switch(t){case xs.Source.Camera:i=yield this.createTracks({video:null===(s=r)||void 0===s||s});break;case xs.Source.Microphone:i=yield this.createTracks({audio:null===(o=r)||void 0===o||o});break;case xs.Source.ScreenShare:i=yield this.createScreenTracks(Object.assign({},r));break;default:throw new Ja(t)}}catch(n){throw null==i||i.forEach((e=>{e.stop()})),n instanceof Error&&this.emit(e.ParticipantEvent.MediaDevicesError,n,Ps(t)),this.pendingPublishing.delete(t),n}for(const e of i){const n=Object.assign(Object.assign({},this.roomOptions.publishDefaults),r);t===xs.Source.Microphone&&_o(e)&&n.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone"),e.startPreConnectBuffer())}try{const e=[];for(const t of i)this.log.info("publishing track",Ds(t)),e.push(this.publishTrack(t,a));c=F(yield Promise.all(e),1)[0]}catch(n){throw null==i||i.forEach((e=>{e.stop()})),n}finally{this.pendingPublishing.delete(t)}}else if(!(null==c?void 0:c.track)&&this.pendingPublishing.has(t)&&(c=yield this.waitForPendingPublicationOfSource(t),c||this.log.info("waiting for pending publication promise timed out",{source:t})),c&&c.track)if(t===xs.Source.ScreenShare){const e=[this.unpublishTrack(c.track)],t=this.getTrackPublication(xs.Source.ScreenShareAudio);t&&t.track&&e.push(this.unpublishTrack(t.track)),c=F(yield Promise.all(e),1)[0]}else yield c.mute();return c}))}enableCameraAndMicrophone(){return pr(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(xs.Source.Camera)&&!this.pendingPublishing.has(xs.Source.Microphone)){this.pendingPublishing.add(xs.Source.Camera),this.pendingPublishing.add(xs.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(xs.Source.Camera),this.pendingPublishing.delete(xs.Source.Microphone)}}}))}createTracks(t){return pr(this,void 0,void 0,(function*(){var n,i;null!=t||(t={});const r=Ts(t,null===(n=this.roomOptions)||void 0===n?void 0:n.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults);try{const t=yield Ju(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return t.map((t=>(_o(t)&&(this.microphoneError=void 0,t.setAudioContext(this.audioContext),t.source=xs.Source.Microphone,this.emit(e.ParticipantEvent.AudioStreamAcquired)),Mo(t)&&(this.cameraError=void 0,t.source=xs.Source.Camera),t)))}catch(a){throw a instanceof Error&&(t.audio&&(this.microphoneError=a),t.video&&(this.cameraError=a)),a}}))}createScreenTracks(t){return pr(this,void 0,void 0,(function*(){if(void 0===t&&(t={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new Ga("getDisplayMedia not supported");void 0!==t.resolution||eo()||(t.resolution=bs.h1080fps30.resolution);const n=Is(t),i=yield navigator.mediaDevices.getDisplayMedia(n),r=i.getVideoTracks();if(0===r.length)throw new Ja("no video track found");const a=new hl(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=xs.Source.ScreenShare,t.contentHint&&(a.mediaStreamTrack.contentHint=t.contentHint);const s=[a];if(i.getAudioTracks().length>0){this.emit(e.ParticipantEvent.AudioStreamAcquired);const t=new $d(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});t.source=xs.Source.ScreenShareAudio,s.push(t)}return s}))}publishTrack(e,t){return pr(this,void 0,void 0,(function*(){return this.publishOrRepublishTrack(e,t)}))}waitForNextEngineRestart(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:15e3;return new Promise(((n,i)=>{const r=()=>{clearTimeout(o),this.engine.off(e.EngineEvent.Restarted,a),this.engine.off(e.EngineEvent.Closing,s)},a=()=>{r(),n()},s=()=>{r(),i(new Error("engine closed before restart completed"))},o=setTimeout((()=>{r(),i(new Error("timed out waiting for engine restart"))}),t);this.engine.once(e.EngineEvent.Restarted,a),this.engine.once(e.EngineEvent.Closing,s)}))}publishOrRepublishTrack(e,t){return pr(this,arguments,void 0,(function(e,t){var i=this;let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],a=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return function*(){var s,o,c,d;let l,u;if(Oo(e)&&e.setAudioContext(i.audioContext),yield null===(s=i.reconnectFuture)||void 0===s?void 0:s.promise,i.republishPromise&&!r&&(yield i.republishPromise),Io(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)l=e.getConstraints();else{let t;switch(l=e.constraints,e.source){case xs.Source.Microphone:t="audioinput";break;case xs.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(l=Object.assign(Object.assign({},l),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new $d(e,l,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new hl(e,l,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new Ja("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&&(u=t)})),u)return i.log.warn("track has already been published, skipping",Ds(u)),u;const h=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t),p="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,m=null!==(o=h.forceStereo)&&void 0!==o?o:p;m&&(void 0===h.dtx&&i.log.debug("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Ds(e)),void 0===h.red&&i.log.debug("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(c=h.dtx)&&void 0!==c||(h.dtx=!1),null!==(d=h.red)&&void 0!==d||(h.red=!1)),!function(){const e=Oa(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&lo(e.osVersion,t)>=0)||"Safari"===e.name&&lo(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"),h.simulcast=!1),h.source&&(e.source=h.source);const g=new Promise(((t,r)=>pr(i,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==nd.CONNECTED){this.log.debug("deferring track publication until signal is connected",{track:Ds(e)});let n=!1;const i=setTimeout((()=>{n=!0,e.stop(),r(new $a("publishing rejected as engine not connected within timeout",408))}),15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(i),n)return;const a=yield this.publish(e,h,m);t(a)}else try{const n=yield this.publish(e,h,m);t(n)}catch(n){r(n)}}catch(n){r(n)}}))));i.pendingPublishPromises.set(e,g);try{return yield g}catch(n){if(!a&&n instanceof Xa)return i.log.warn("negotiation due to track publish failed, retrying after reconnect",{error:n}),i.pendingPublishPromises.delete(e),yield i.waitForNextEngineRestart(),yield i.publishOrRepublishTrack(e,t,r,!0);throw n}finally{i.pendingPublishPromises.delete(e)}}()}))}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new To),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Ds(e)),!1;const t=this.permissions,n=t.canPublish,i=t.canPublishSources;return!(!n||0!==i.length&&!i.map((e=>function(e){switch(e){case tt.CAMERA:return xs.Source.Camera;case tt.MICROPHONE:return xs.Source.Microphone;case tt.SCREEN_SHARE:return xs.Source.ScreenShare;case tt.SCREEN_SHARE_AUDIO:return xs.Source.ScreenShareAudio;default:return xs.Source.Unknown}}(e))).includes(e.source))||(this.log.warn("insufficient permissions to publish",Ds(e)),!1)}publish(t,i,r){return pr(this,void 0,void 0,(function*(){var a,s,o,c,d,l,u,h,p,m;if(!this.hasPermissionsToPublish(t))throw new $a("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((e=>Io(t)&&e.source===t.source))&&t.source!==xs.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(t.source),Ds(t)),i.stopMicTrackOnMute&&_o(t)&&(t.stopOnMute=!0),t.source===xs.Source.ScreenShare&&Ys()&&(i.simulcast=!1),"av1"!==i.videoCodec||Hs()||(i.videoCodec=void 0),"vp9"!==i.videoCodec||Ks()||(i.videoCodec=void 0),void 0===i.videoCodec&&(i.videoCodec=Md),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((e=>i.videoCodec===_s(e.mime)))||(i.videoCodec=_s(this.enabledPublishVideoCodecs[0].mime)));const g=i.videoCodec;t.on(e.TrackEvent.Muted,this.onTrackMuted),t.on(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.on(e.TrackEvent.Ended,this.handleTrackEnded),t.on(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.on(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed),t.on(e.TrackEvent.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const v=[],f=!(null===(a=i.dtx)||void 0===a||a),k=t.getSourceTrackSettings();k.autoGainControl&&v.push(ct.TF_AUTO_GAIN_CONTROL),k.echoCancellation&&v.push(ct.TF_ECHO_CANCELLATION),k.noiseSuppression&&v.push(ct.TF_NOISE_SUPPRESSION),k.channelCount&&k.channelCount>1&&v.push(ct.TF_STEREO),f&&v.push(ct.TF_NO_DTX),Oo(t)&&t.hasPreConnectBuffer&&v.push(ct.TF_PRECONNECT_BUFFER);const y=this.normalizeRequestedFrameMetadataOptions(t,i),b=new Wn({cid:t.mediaStreamTrack.id,name:i.name,type:xs.kindToProto(t.kind),muted:t.isMuted,source:xs.sourceToProto(t.source),disableDtx:f,encryption:this.encryptionType,stereo:r,disableRed:this.isE2EEEnabled||!(null===(s=i.red)||void 0===s||s),stream:null==i?void 0:i.stream,backupCodecPolicy:null==i?void 0:i.backupCodecPolicy,audioFeatures:v,packetTrailerFeatures:y});let T;if(t.kind===xs.Kind.Video){let e;try{e=yield t.waitForDimensions()}catch(n){const r=null!==(c=null===(o=this.roomOptions.videoCaptureDefaults)||void 0===o?void 0:o.resolution)&&void 0!==c?c:ks.h720.resolution;e={width:r.width,height:r.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},Ds(t)),{dims:e}))}b.width=e.width,b.height=e.height,Do(t)&&(zs(g)&&(t.source===xs.Source.ScreenShare&&(i.scalabilityMode="L1T3","contentHint"in t.mediaStreamTrack&&(t.mediaStreamTrack.contentHint="motion",this.log.debug("forcing contentHint to motion for screenshare with SVC codecs",Ds(t)))),i.scalabilityMode=null!==(d=i.scalabilityMode)&&void 0!==d?d:"L3T3_KEY"),b.simulcastCodecs=[new Vn({codec:g,cid:t.mediaStreamTrack.id})],!0===i.backupCodec&&(i.backupCodec={codec:Md}),i.backupCodec&&g!==i.backupCodec.codec&&b.encryption===ft.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),b.simulcastCodecs.push(new Vn({codec:i.backupCodec.codec,cid:""})))),T=sl(t.source===xs.Source.ScreenShare,b.width,b.height,i),b.layers=gl(b.width,b.height,T,zs(i.videoCodec))}else t.kind===xs.Kind.Audio&&(T=[{maxBitrate:null===(l=i.audioPreset)||void 0===l?void 0:l.maxBitrate,priority:null!==(h=null===(u=i.audioPreset)||void 0===u?void 0:u.priority)&&void 0!==h?h:"high",networkPriority:null!==(m=null===(p=i.audioPreset)||void 0===p?void 0:p.priority)&&void 0!==m?m:"high"}]);if(!this.engine||this.engine.isClosed)throw new Ya("cannot publish track when not connected");const S=()=>pr(this,void 0,void 0,(function*(){var n,r,a,s;if(!this.engine.pcManager)throw new Ya("pcManager is not ready");if(t.sender=yield this.engine.createSender(t,i,T),Do(t)&&(t.publishOptions=i),this.emit(e.ParticipantEvent.LocalSenderCreated,t.sender,t),Do(t)&&(null!==(n=i.degradationPreference)&&void 0!==n||(i.degradationPreference=function(e){switch(e.source){case xs.Source.Camera:return"maintain-framerate";case xs.Source.ScreenShare:return"maintain-resolution";default:return"balanced"}}(t)),t.setDegradationPreference(i.degradationPreference)),T)if(Ys()&&t.kind===xs.Kind.Audio){let e;for(const n of this.engine.pcManager.publisher.getTransceivers())if(n.sender===t.sender){e=n;break}e&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:e,codec:"opus",maxbr:(null===(r=T[0])||void 0===r?void 0:r.maxBitrate)?T[0].maxBitrate/1e3:0})}else if(t.codec&&So(t.codec)){const e=zs(t.codec)?null!==(s=null===(a=T[0])||void 0===a?void 0:a.maxBitrate)&&void 0!==s?s:0:T.reduce(((e,t)=>{var n;return e+(null!==(n=t.maxBitrate)&&void 0!==n?n:0)}),0);e>0&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:b.cid,codec:t.codec,maxbr:e/1e3,isScreenShare:t.source===xs.Source.ScreenShare})}yield this.engine.negotiate()}));let E;const C=new Promise(((e,i)=>pr(this,void 0,void 0,(function*(){var r;try{E=yield this.engine.addTrack(b),e(E)}catch(a){if(t.sender&&(null===(r=this.engine.pcManager)||void 0===r?void 0:r.publisher)){try{this.engine.pcManager.publisher.removeTrack(t.sender)}catch(n){this.log.error(n)}yield this.engine.negotiate().catch((e=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign({},Ds(t)),{error:e}))}))}i(a)}}))));if(this.enabledPublishVideoCodecs.length>0&&0===y.length){const e=yield Promise.all([C,S()]);E=e[0]}else{let e;if(E=yield C,E.codecs.forEach((t=>{void 0===e&&(e=t.mimeType)})),e&&t.kind===xs.Kind.Video){const n=_s(e);n!==g&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign({},Ds(t)),{codec:n})),i.videoCodec=n,T=sl(t.source===xs.Source.ScreenShare,b.width,b.height,i))}yield S()}const w=new Gu(t.kind,E,t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(w.on(e.TrackEvent.CpuConstrained,(e=>this.onTrackCpuConstrained(e,w))),w.options=i,t.sid=E.sid,Do(t)&&(t.publishOptions=i,b.width&&b.height&&(t.lastEncodedDimensions={width:b.width,height:b.height})),this.log.debug("publishing ".concat(t.kind," with encodings"),{encodings:T,trackInfo:E}),Do(t)?t.startMonitor(this.engine.client):Oo(t)&&t.startMonitor(),this.addTrackPublication(w),this.emit(e.ParticipantEvent.LocalTrackPublished,w),Oo(t)&&E.audioFeatures.includes(ct.TF_PRECONNECT_BUFFER)){const i=t.getPreConnectBuffer(),r=t.getPreConnectBufferMimeType();if(this.on(e.ParticipantEvent.LocalTrackSubscribed,(e=>{if(e.trackSid===E.sid){if(!t.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed");this.log.debug("finished recording preconnect buffer",Ds(t)),t.stopPreConnectBuffer()}})),i){const e=new Promise(((e,a)=>pr(this,void 0,void 0,(function*(){var s,o,c,d,l,u;try{this.log.debug("waiting for agent",Ds(t));const n=setTimeout((()=>{a(new Error("agent not active within 10 seconds"))}),1e4),v=yield this.waitUntilActiveAgentPresent();clearTimeout(n),this.log.debug("sending preconnect buffer",Ds(t));const f=yield this.streamBytes({name:"preconnect-buffer",mimeType:r,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[v.identity],attributes:{trackId:w.trackSid,sampleRate:String(null!==(l=k.sampleRate)&&void 0!==l?l:"48000"),channels:String(null!==(u=k.channelCount)&&void 0!==u?u:"1")}});try{for(var h,p=!0,m=fr(i);!(s=(h=yield m.next()).done);p=!0){d=h.value,p=!1;const e=d;yield f.write(e)}}catch(g){o={error:g}}finally{try{p||s||!(c=m.return)||(yield c.call(m))}finally{if(o)throw o.error}}yield f.close(),e()}catch(n){a(n)}}))));e.then((()=>{this.log.debug("preconnect buffer sent successfully",Ds(t))})).catch((e=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign({},Ds(t)),{error:e}))}))}}return w}))}canPublishFrameMetadata(){var e;return!!(this.roomOptions.e2ee||this.roomOptions.encryption||sc(null!==(e=this.roomOptions.frameMetadata)&&void 0!==e?e:this.roomOptions.packetTrailer))}normalizeRequestedFrameMetadataOptions(e,t){var n;const i=null!==(n=t.frameMetadata)&&void 0!==n?n:t.packetTrailer;if(e.kind!==xs.Kind.Video||!oc(i))return t.frameMetadata=void 0,t.packetTrailer=void 0,[];if(!this.canPublishFrameMetadata())return this.log.warn("frame metadata transform not supported; not advertising features",Object.assign(Object.assign({},this.logContext),Ds(e))),t.frameMetadata=void 0,t.packetTrailer=void 0,[];const r=function(e){const t=[];return(null==e?void 0:e.timestamp)&&t.push(dt.PTF_USER_TIMESTAMP),(null==e?void 0:e.frameId)&&t.push(dt.PTF_FRAME_ID),t}(i),a=function(e){if(!e||0===e.length)return;const t={};return e.includes(dt.PTF_USER_TIMESTAMP)&&(t.timestamp=!0),e.includes(dt.PTF_FRAME_ID)&&(t.frameId=!0),t.timestamp||t.frameId?t:void 0}(r);return t.frameMetadata=a,t.packetTrailer=a,r}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return pr(this,void 0,void 0,(function*(){var i;if(this.encryptionType!==ft.NONE)return;let r;if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(r=t)})),!r)throw new Ja("track is not published");if(!Do(e))throw new Ja("track is not a video track");const a=Object.assign(Object.assign({},null===(i=this.roomOptions)||void 0===i?void 0:i.publishDefaults),n),s=ol(e,t,a);if(!s)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Ds(e));const o=e.addSimulcastTrack(t,s);if(!o)return;const c=this.normalizeRequestedFrameMetadataOptions(e,a),d=new Wn({cid:o.mediaStreamTrack.id,type:xs.kindToProto(e.kind),muted:e.isMuted,source:xs.sourceToProto(e.source),sid:e.sid,packetTrailerFeatures:c,simulcastCodecs:[{codec:a.videoCodec,cid:o.mediaStreamTrack.id}]});if(d.layers=gl(d.width,d.height,s),!this.engine||this.engine.isClosed)throw new Ya("cannot publish track when not connected");const l=(yield Promise.all([this.engine.addTrack(d),(()=>pr(this,void 0,void 0,(function*(){yield this.engine.createSimulcastSender(e,o,a,s),yield this.engine.negotiate()})))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),{encodings:s,trackInfo:l})}))}unpublishTrack(t,i){return pr(this,void 0,void 0,(function*(){var r,a;if(Io(t)){const e=this.pendingPublishPromises.get(t);e&&(this.log.debug("awaiting publish promise before attempting to unpublish",Ds(t)),yield e)}const s=this.getPublicationForTrack(t),o=s?Ds(s):void 0;if(this.log.info("unpublishing track",o),!s||!s.track)return void this.log.warn("track was not unpublished because no publication was found",o);(t=s.track).off(e.TrackEvent.Muted,this.onTrackMuted),t.off(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.off(e.TrackEvent.Ended,this.handleTrackEnded),t.off(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.off(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed),t.off(e.TrackEvent.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===i&&(i=null===(a=null===(r=this.roomOptions)||void 0===r?void 0:r.stopLocalTrackOnUnpublish)||void 0===a||a),i?t.stop():t.stopMonitor();let c=!1;const d=t.sender;if(t.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<xd.FAILED&&d)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===d&&(e.direction="inactive",c=!0);try{c=this.engine.removeTrack(d)}catch(n){this.log.warn(n),c=!0}if(Do(t)){for(const e of t.simulcastCodecs){const t=F(e,2)[1];if(t.sender){try{c=this.engine.removeTrack(t.sender)}catch(n){this.log.warn(n),c=!0}t.sender=void 0}}t.simulcastCodecs.clear()}}catch(n){this.log.warn("failed to unpublish track",Object.assign(Object.assign({},o),{error:n}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case xs.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case xs.Kind.Video:this.videoTrackPublications.delete(s.trackSid)}return this.emit(e.ParticipantEvent.LocalTrackUnpublished,s),s.setTrack(void 0),c&&(yield this.engine.negotiate()),s}))}unpublishTracks(e){return pr(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>!!e))}))}republishAllTracks(e){return pr(this,arguments,void 0,(function(e){var t=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new _a(((i,r)=>pr(t,void 0,void 0,(function*(){try{const t=[];this.trackPublications.forEach((n=>{n.track&&(e&&(n.options=Object.assign(Object.assign({},n.options),e)),t.push(n))})),yield Promise.all(t.map((e=>pr(this,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),!n||t.isMuted||t.source===xs.Source.ScreenShare||t.source===xs.Source.ScreenShareAudio||!Oo(t)&&!Do(t)||t.isUserProvided||(this.log.debug("restarting existing track",{track:e.trackSid}),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))))),i()}catch(t){t instanceof Error?r(t):r(new Error(String(t)))}finally{this.republishPromise=void 0}})))),yield t.republishPromise}()}))}publishData(e){return pr(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){const i=n.reliable?Ud.RELIABLE:Ud.LOSSY,r=n.reliable?Ot.RELIABLE:Ot.LOSSY,a=n.destinationIdentities,s=n.topic;let o=new Ut({participantIdentity:t.identity,payload:e,destinationIdentities:a,topic:s});const c=new Dt({kind:r,value:{case:"user",value:o}});yield t.engine.sendDataPacket(c,i)}()}))}publishDtmf(e,t){return pr(this,void 0,void 0,(function*(){const n=new Dt({kind:Ot.RELIABLE,value:{case:"sipDtmf",value:new Ft({code:e,digit:t})}});yield this.engine.sendDataPacket(n,Ud.RELIABLE)}))}sendChatMessage(t,n){return pr(this,void 0,void 0,(function*(){const i={id:crypto.randomUUID(),message:t,timestamp:Date.now(),attachedFiles:null==n?void 0:n.attachments},r=new Dt({value:{case:"chatMessage",value:new qt(Object.assign(Object.assign({},i),{timestamp:R.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,Ud.RELIABLE),this.emit(e.ParticipantEvent.ChatMessage,i),i}))}editChatMessage(t,n){return pr(this,void 0,void 0,(function*(){const i=Object.assign(Object.assign({},n),{message:t,editTimestamp:Date.now()}),r=new Dt({value:{case:"chatMessage",value:new qt(Object.assign(Object.assign({},i),{timestamp:R.parse(i.timestamp),editTimestamp:R.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,Ud.RELIABLE),this.emit(e.ParticipantEvent.ChatMessage,i),i}))}sendText(e,t){return pr(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)}))}streamText(e){return pr(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamText(e)}))}sendFile(e,t){return pr(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)}))}sendBytes(e,t){return pr(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendBytes(e,t)}))}streamBytes(e){return pr(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)}))}performRpc(e){return this.rpcClientManager.performRpc(e).then((e=>{let t=F(e,2);return t[0],t[1]}))}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(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()}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,n;const i=this.trackPublications.get(e.sid);if(i){const r=i.isMuted||null!==(n=null===(t=i.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==n&&n;r!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign({},Ds(i)),{mutedOnServer:r})),this.engine.client.sendMuteTrack(e.sid,r))}})),!0)}setActiveAgent(e){var t,n,i,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?null===(n=null===(t=this.activeAgentFuture)||void 0===t?void 0:t.resolve)||void 0===n||n.call(t,e):null===(r=null===(i=this.activeAgentFuture)||void 0===i?void 0:i.reject)||void 0===r||r.call(i,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new To),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach((n=>{const i=n.track;i&&(e instanceof MediaStreamTrack?(Oo(i)||Do(i))&&i.mediaStreamTrack===e&&(t=n):e===i&&(t=n))})),t}waitForPendingPublicationOfSource(e){return pr(this,void 0,void 0,(function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find((t=>F(t,1)[0].source===e));if(t)return t[1];yield qs(20)}}))}publishDataTrack(e){return pr(this,void 0,void 0,(function*(){const t=new Ou(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t}))}}class th extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}}class nh extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var n,i;super.set(e,t);const r=null===(n=this.pending)||void 0===n?void 0:n.get(e);if(r){for(const e of r)e.isResolved||null===(i=e.resolve)||void 0===i||i.call(e,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return"DeferrableMap"}getDeferred(e,t){return pr(this,void 0,void 0,(function*(){const n=this.get(e);if(void 0!==n)return n;if(null==t?void 0:t.aborted)throw new th("The operation was aborted.",t.reason);const i=new To(void 0,(()=>{const t=this.pending.get(e);if(!t)return;const n=t.indexOf(i);-1!==n&&t.splice(n,1),0===t.length&&this.pending.delete(e)})),r=this.pending.get(e);if(r?r.push(i):this.pending.set(e,[i]),t){const e=()=>{var e;i.isResolved||null===(e=i.reject)||void 0===e||e.call(i,new th("The operation was aborted.",t.reason))};t.addEventListener("abort",e,{once:!0}),i.promise.finally((()=>{t.removeEventListener("abort",e)}))}return i.promise}))}}class ih extends zu{constructor(t,n,i,r){super(t,n.sid,n.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=t=>{this.setTrack(void 0),this.emit(e.TrackEvent.Ended,t)},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(n)}setSubscribed(t){const n=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=t,t&&(this.allowed=!0);const r=new ri({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new zt({participantSid:"",trackSids:[this.trackSid]})]});this.emit(e.TrackEvent.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?zu.SubscriptionStatus.Unsubscribed:super.isSubscribed?zu.SubscriptionStatus.Subscribed:zu.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?zu.PermissionStatus.Allowed:zu.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,n;this.isManualOperationAllowed()&&((null===(t=this.requestedVideoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(n=this.requestedVideoDimensions)||void 0===n?void 0:n.height)===e.height||(No(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&No(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var t;return null!==(t=this.requestedMaxQuality)&&void 0!==t?t:e.VideoQuality.HIGH}setTrack(t){const n=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==t&&(r&&(r.off(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),r.off(e.TrackEvent.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(e.TrackEvent.Unsubscribed,r)),super.setTrack(t),t&&(t.sid=this.trackSid,t.on(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),t.on(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),t.on(e.TrackEvent.Ended,this.handleEnded),this.emit(e.TrackEvent.Subscribed,t)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(t){this.emit(e.TrackEvent.SubscriptionFailed,t)}updateInfo(t){super.updateInfo(t);const n=this.metadataMuted;this.metadataMuted=t.muted,this.track?this.track.setMuted(t.muted):n!==t.muted&&this.emit(t.muted?e.TrackEvent.Muted:e.TrackEvent.Unmuted)}emitSubscriptionUpdateIfChanged(t){const n=this.subscriptionStatus;t!==n&&this.emit(e.TrackEvent.SubscriptionStatusChanged,n,t)}emitPermissionUpdateIfChanged(t){this.permissionStatus!==t&&this.emit(e.TrackEvent.SubscriptionPermissionChanged,this.permissionStatus,t)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return No(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=new ui({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===xs.Kind.Video){let n=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(n){As(this.videoDimensionsAdaptiveStream,n)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream)}else if(void 0!==this.requestedMaxQuality&&this.trackInfo){const e=function(e,t){var n;return null===(n=e.layers)||void 0===n?void 0:n.find((e=>e.quality===t))}(this.trackInfo,this.requestedMaxQuality);e&&As(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream;n?(t.width=Math.ceil(n.width),t.height=Math.ceil(n.height)):void 0!==this.requestedMaxQuality?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),t.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:e.VideoQuality.HIGH})),t.quality=e.VideoQuality.HIGH)}this.emit(e.TrackEvent.UpdateSettings,t)}}class rh extends $u{static fromParticipantInfo(e,t,n,i){return new rh(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind,t.dataTracks.map((e=>{const n=Ac.from(e);return new du(n,i,{publisherIdentity:t.identity})})),t.clientProtocol,t.capabilities)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,i,r,a,s){let o=arguments.length>7&&void 0!==arguments[7]?arguments[7]:gt.STANDARD,c=arguments.length>8&&void 0!==arguments[8]?arguments[8]:[],d=arguments.length>9&&void 0!==arguments[9]?arguments[9]:0,l=arguments.length>10&&void 0!==arguments[10]?arguments[10]:[];super(t,n||"",i,r,a,s,o),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new nh(c.map((e=>[e.info.name,e]))),this.volumeMap=new Map,this.clientProtocol=d,this.capabilities=l}addTrackPublication(t){super.addTrackPublication(t),t.on(e.TrackEvent.UpdateSettings,(e=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),Ds(t)),{settings:e})),this.signalClient.sendUpdateTrackSettings(e)})),t.on(e.TrackEvent.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),t.on(e.TrackEvent.SubscriptionPermissionChanged,(n=>{this.emit(e.ParticipantEvent.TrackSubscriptionPermissionChanged,t,n)})),t.on(e.TrackEvent.SubscriptionStatusChanged,(n=>{this.emit(e.ParticipantEvent.TrackSubscriptionStatusChanged,t,n)})),t.on(e.TrackEvent.Subscribed,(n=>{this.emit(e.ParticipantEvent.TrackSubscribed,n,t)})),t.on(e.TrackEvent.Unsubscribed,(n=>{this.emit(e.ParticipantEvent.TrackUnsubscribed,n,t)})),t.on(e.TrackEvent.SubscriptionFailed,(n=>{this.emit(e.ParticipantEvent.TrackSubscriptionFailed,t.trackSid,n)}))}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]:xs.Source.Microphone;this.volumeMap.set(t,e);const n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:xs.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(t,n,i,r,a,s){let o=this.getTrackPublicationBySid(n);if(o||n.startsWith("TR")||this.trackPublications.forEach((e=>{o||t.kind!==e.kind.toString()||(o=e)})),!o)return 0===s?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:n})),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,n)):(void 0===s&&(s=20),void setTimeout((()=>{this.addSubscribedMediaTrack(t,n,i,r,a,s-1)}),150));if("ended"===t.readyState)return this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),Ds(o))),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,n);let c;return c="video"===t.kind?new hc(t,n,r,a):new Ku(t,n,r,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(i),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&Ao(c)&&_o(c)&&c.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(t){if(!super.updateInfo(t))return!1;const n=new Map,i=new Map;return t.tracks.forEach((e=>{var t,r;let a=this.getTrackPublicationBySid(e.sid);if(a)a.updateInfo(e);else{const n=xs.kindFromProto(e.type);if(!n)return;a=new ih(n,e,null===(t=this.signalClient.connectOptions)||void 0===t?void 0:t.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(r=this.loggerOptions)||void 0===r?void 0:r.loggerName}),a.updateInfo(e),i.set(e.sid,a);const s=Array.from(this.trackPublications.values()).find((e=>e.source===(null==a?void 0:a.source)));s&&a.source!==xs.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),Object.assign(Object.assign({},this.logContext),{oldTrack:Ds(s),newTrack:Ds(a)})),this.addTrackPublication(a)}n.set(e.sid,a)})),this.trackPublications.forEach((e=>{n.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),Ds(e))),this.unpublishTrack(e.trackSid,!0))})),i.forEach((t=>{this.emit(e.ParticipantEvent.TrackPublished,t)})),!0}unpublishTrack(t,n){const i=this.trackPublications.get(t);if(!i)return;const r=i.track;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(t),i.kind){case xs.Kind.Audio:this.audioTrackPublications.delete(t);break;case xs.Kind.Video:this.videoTrackPublications.delete(t)}n&&this.emit(e.ParticipantEvent.TrackUnpublished,i)}setAudioOutput(e){return pr(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((n=>{var i;_o(n.track)&&Ao(n.track)&&t.push(n.track.setSinkId(null!==(i=e.deviceId)&&void 0!==i?i:"default"))})),yield Promise.all(t)}))}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(const n of this.dataTracks.entries()){var t=F(n,2);const i=t[0];e===t[1].info.sid&&this.dataTracks.delete(i)}}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}e.ConnectionState=void 0,(Zu=e.ConnectionState||(e.ConnectionState={})).Disconnected="disconnected",Zu.Connecting="connecting",Zu.Connected="connected",Zu.Reconnecting="reconnecting",Zu.SignalReconnecting="signalReconnecting";class ah extends br.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(t){var i,a,s,o,c,d,l,u;if(super(),i=this,this.state=e.ConnectionState.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new r,this.isVideoPlaybackBlocked=!1,this.log=ar,this.statsLog=ar,this.bufferedEvents=[],this.isResuming=!1,this.pendingTrackAddedCallbacks=new Map,this.connect=(t,n,i)=>pr(this,void 0,void 0,(function*(){var r;if(!Qs())throw io()?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 a=yield this.disconnectLock.lock();if(this.state===e.ConnectionState.Connected)return this.log.info("already connected to room ".concat(this.name)),a(),Promise.resolve();if(this.connectFuture)return a(),this.connectFuture.promise;this.setAndEmitConnectionState(e.ConnectionState.Connecting),(null===(r=this.regionUrlProvider)||void 0===r?void 0:r.getServerUrl().toString())!==qo(t)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),ro(new URL(t))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new Sl(t,n):this.regionUrlProvider.updateToken(n),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",{error:e})})));const s=(r,o,c)=>pr(this,void 0,void 0,(function*(){var d,l;this.abortController&&this.abortController.abort();const u=new AbortController;this.abortController=u,null==a||a();try{if(yield bc.getInstance().getBackOffPromise(t),u.signal.aborted)throw za.cancelled("Connection attempt aborted");yield this.attemptConnection(null!=c?c:t,n,i,u),this.abortController=void 0,r()}catch(h){if(this.regionUrlProvider&&h instanceof za&&h.reason!==e.ConnectionErrorReason.Cancelled&&h.reason!==e.ConnectionErrorReason.NotAllowed){let n=null;try{this.log.debug("Fetching next region"),n=yield this.regionUrlProvider.getNextBestRegionUrl(null===(d=this.abortController)||void 0===d?void 0:d.signal)}catch(p){if(p instanceof za&&(401===p.status||p.reason===e.ConnectionErrorReason.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void o(p)}[e.ConnectionErrorReason.InternalError,e.ConnectionErrorReason.ServerUnreachable,e.ConnectionErrorReason.Timeout].includes(h.reason)&&(this.log.debug("Adding failed connection attempt to back off"),bc.getInstance().addFailedConnectionAttempt(t)),n&&!(null===(l=this.abortController)||void 0===l?void 0:l.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(h.message,". Retrying with another region: ").concat(n)),this.recreateEngine(!0),yield s(r,o,n)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,wo(h)),o(h))}else{let e=at.UNKNOWN_REASON;h instanceof za&&(e=wo(h)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),o(h)}}})),o=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new To(((e,t)=>{s(e,t,o)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,n,i,r,a)=>pr(this,void 0,void 0,(function*(){const s=yield n.join(e,t,{autoSubscribe:i.autoSubscribe,adaptiveStream:"object"==typeof r.adaptiveStream||r.adaptiveStream,clientInfoCapabilities:this.getClientInfoCapabilities(r),maxRetries:i.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:i.websocketTimeout},a.signal,!r.singlePeerConnection),o=s.joinResponse,c=s.serverInfo;if(this.serverInfo=c,!c.version)throw new Qa("unknown server version");return"0.15.1"===c.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version"),r.dynacast=!1),o})),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(n){this.log.error(n instanceof Error?n.message:"Could not set SifTrailer",{error:n})}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(t,i,r,a)=>pr(this,void 0,void 0,(function*(){var s,o;this.state===e.ConnectionState.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.recreateEngine(!0)):this.maybeCreateEngine(),(null===(o=this.regionUrlProvider)||void 0===o?void 0:o.isCloud())&&this.engine.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Nd),r),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const n=yield this.connectSignal(t,i,this.engine,this.connOptions,this.options,a);this.applyJoinResponse(n),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected)}catch(c){yield this.engine.close(),this.recreateEngine();const e=a.signal.aborted?za.cancelled("Signal connection aborted"):za.serverUnreachable("could not establish signal connection");throw c instanceof Error&&(e.message="".concat(e.message,": ").concat(c.message)),c instanceof za&&(e.reason=c.reason,e.status=c.status),this.log.debug("error trying to establish signal connection",{error:c}),e}if(a.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),za.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,a)}catch(n){throw yield this.engine.close(),this.recreateEngine(),n}no()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),no()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Connected),bc.getInstance().resetFailedConnectionAttempts(t),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()})),this.disconnect=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return pr(i,[...n],void 0,(function(){var t=this;let n=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,r,a;const s=yield t.disconnectLock.lock();try{if(t.state===e.ConnectionState.Disconnected)return void t.log.debug("already disconnected");if(t.log.info("disconnect from room"),t.state===e.ConnectionState.Connecting||t.state===e.ConnectionState.Reconnecting||t.isResuming){const e="Abort connection attempt due to user initiated disconnect";t.log.warn(e),null===(i=t.abortController)||void 0===i||i.abort(e),null===(a=null===(r=t.connectFuture)||void 0===r?void 0:r.reject)||void 0===a||a.call(r,za.cancelled("Client initiated disconnect")),t.connectFuture=void 0}t.engine&&(t.engine.client.isDisconnected||(yield t.engine.client.sendLeave()),yield t.engine.close()),t.handleDisconnect(n,at.CLIENT_INITIATED),t.engine=void 0}finally{s()}}()}))},this.onPageLeave=()=>pr(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting"),yield this.disconnect()})),this.startAudio=()=>pr(this,void 0,void 0,(function*(){const t=[],n=Oa();if(n&&"iOS"===n.os){const n="livekit-dummy-audio-el";let i=document.getElementById(n);if(!i){i=document.createElement("audio"),i.id=n,i.autoplay=!0,i.hidden=!0;const t=bo();t.enabled=!0;const r=new MediaStream([t]);i.srcObject=r,document.addEventListener("visibilitychange",(()=>{i&&(i.srcObject=document.hidden?null:r,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status"),this.startAudio()))})),document.body.append(i),this.once(e.RoomEvent.Disconnected,(()=>{null==i||i.remove(),i=null}))}t.push(i)}this.remoteParticipants.forEach((e=>{e.audioTrackPublications.forEach((e=>{e.track&&e.track.attachedElements.forEach((e=>{t.push(e)}))}))}));try{yield Promise.all([this.acquireAudioContext(),...t.map((e=>(this.options.webAudioMix||(e.muted=!1),e.play())))]),this.handleAudioPlaybackStarted()}catch(i){throw this.handleAudioPlaybackFailed(i),i}})),this.startVideo=()=>pr(this,void 0,void 0,(function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach((t=>{var n;null===(n=t.track)||void 0===n||n.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.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=t=>pr(this,void 0,void 0,(function*(){this.log.debug("signal reconnected to server, region ".concat(t.serverRegion),{region:t.serverRegion}),this.bufferedEvents=[],this.applyJoinResponse(t);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(n){this.log.error("error trying to re-publish tracks after reconnection",{error:n})}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",{region:t.serverRegion})}catch(a){return}this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()})),this.handleParticipantUpdates=e=>{var t;for(const i of e){if(i.identity===this.localParticipant.identity){this.localParticipant.updateInfo(i);continue}""===i.identity&&(i.identity=null!==(t=this.sidToIdentity.get(i.sid))&&void 0!==t?t:"");let e=this.remoteParticipants.get(i.identity);i.state===mt.DISCONNECTED?this.handleParticipantDisconnected(i.identity,e,i.disconnectReason===at.UNKNOWN_REASON?void 0:i.disconnectReason):this.getOrCreateParticipant(i.identity,i)}const n=new Map(e.filter((e=>e.identity!==this.localParticipant.identity)).map((e=>[e.identity,e.dataTracks.map((e=>Ac.from(e)))])));this.incomingDataTrackManager.receiveSfuPublicationUpdates(n)},this.handleActiveSpeakersUpdate=t=>{const n=[],i={};t.forEach((e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),n.push(this.localParticipant);else{const t=this.getRemoteParticipantBySid(e.sid);t&&(t.audioLevel=e.level,t.setIsSpeaking(!0),n.push(t))}})),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=n,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,n)},this.handleSpeakersChanged=t=>{const n=new Map;this.activeSpeakers.forEach((e=>{const t=this.remoteParticipants.get(e.identity);t&&t.sid!==e.sid||n.set(e.sid,e)})),t.forEach((e=>{let t=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(t=this.localParticipant),t&&(t.audioLevel=e.level,t.setIsSpeaking(e.active),e.active?n.set(e.sid,t):n.delete(e.sid))}));const i=Array.from(n.values());i.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=i,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=t=>{t.streamStates.forEach((t=>{const n=this.getRemoteParticipantBySid(t.participantSid);if(!n)return;const i=n.getTrackPublicationBySid(t.trackSid);if(!i||!i.track)return;const r=xs.streamStateFromProto(t.state),a=i.track.streamState;i.track.setStreamState(r),r!==a&&(n.emit(e.ParticipantEvent.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(e.RoomEvent.TrackStreamStateChanged,i,i.track.streamState,n))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const n=t.getTrackPublicationBySid(e.trackSid);n&&n.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{this.cancelPendingTrackAdded(e.trackSid);const t=Array.from(this.remoteParticipants.values()).find((t=>t.trackPublications.has(e.trackSid)));if(!t)return;const n=t.getTrackPublicationBySid(e.trackSid);n&&n.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{const n=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(n,e.value.value,e.kind,t);else if("transcription"===e.value.case)this.handleTranscription(n,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(n,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(n,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,n);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.rpcServerManager.handleIncomingRpcRequest(e.participantIdentity,t)}else if("rpcResponse"===e.value.case){const t=e.value.value;switch(t.value.case){case"payload":this.rpcClientManager.handleIncomingRpcResponseSuccess(t.requestId,t.value.value);break;case"error":this.rpcClientManager.handleIncomingRpcResponseFailure(t.requestId,Uu.fromProto(t.value.value));break;default:this.log.warn("Unknown rpcResponse.value.case: ".concat(t.value.case),this.logContext)}}else"rpcAck"===e.value.case&&this.rpcClientManager.handleIncomingRpcAck(e.value.value.requestId)},this.handleUserPacket=(t,n,i,r)=>{this.emit(e.RoomEvent.DataReceived,n.payload,t,i,n.topic,r),null==t||t.emit(e.ParticipantEvent.DataReceived,n.payload,i,r)},this.handleSipDtmf=(t,n)=>{this.emit(e.RoomEvent.SipDTMFReceived,n,t),null==t||t.emit(e.ParticipantEvent.SipDTMFReceived,n)},this.handleTranscription=(t,n)=>{const i=n.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(n.transcribedParticipantIdentity),r=null==i?void 0:i.trackPublications.get(n.trackId),a=function(e,t){return e.segments.map((e=>{let n=e.id,i=e.text,r=e.language,a=e.startTime,s=e.endTime,o=e.final;var c;const d=null!==(c=t.get(n))&&void 0!==c?c:Date.now(),l=Date.now();return o?t.delete(n):t.set(n,d),{id:n,text:i,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(s.toString()),final:o,language:r,firstReceivedTime:d,lastReceivedTime:l}}))}(n,this.transcriptionReceivedTimes);null==r||r.emit(e.TrackEvent.TranscriptionReceived,a),null==i||i.emit(e.ParticipantEvent.TranscriptionReceived,a,r),this.emit(e.RoomEvent.TranscriptionReceived,a,i,r)},this.handleChatMessage=(t,n)=>{const i=function(e){const t=e.id,n=e.timestamp,i=e.message,r=e.editTimestamp;return{id:t,timestamp:Number.parseInt(n.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:i}}(n);this.emit(e.RoomEvent.ChatMessage,i,t)},this.handleMetrics=(t,n)=>{this.emit(e.RoomEvent.MetricsReceived,t,n)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=t=>{this.log.warn("could not playback audio",{error:t}),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(e.RoomEvent.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(e.RoomEvent.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>pr(this,void 0,void 0,(function*(){var t;"iOS"!==(null===(t=Oa())||void 0===t?void 0:t.os)&&(yield this.selectDefaultDevices()),this.emit(e.RoomEvent.MediaDevicesChanged)})),this.handleRoomUpdate=t=>{const n=this.roomInfo;this.roomInfo=t,n&&n.metadata!==t.metadata&&this.emitWhenConnected(e.RoomEvent.RoomMetadataChanged,t.metadata),(null==n?void 0:n.activeRecording)!==t.activeRecording&&this.emitWhenConnected(e.RoomEvent.RecordingStatusChanged,t.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.getRemoteParticipantClientProtocol=e=>{var t,n;return null!==(n=null===(t=this.remoteParticipants.get(e))||void 0===t?void 0:t.clientProtocol)&&void 0!==n?n:0},this.getRemoteParticipantCapabilities=e=>{var t,n;return null!==(n=null===(t=this.remoteParticipants.get(e))||void 0===t?void 0:t.capabilities)&&void 0!==n?n:[]},this.getAllRemoteParticipantIdentities=()=>Array.from(this.remoteParticipants.keys()),this.logWebRTCStats=()=>pr(this,void 0,void 0,(function*(){var e,t,n,i;const r=null===(e=this.engine)||void 0===e?void 0:e.pcManager;if(r)try{const e=F(yield Promise.all([r.publisher.getStats(),null===(t=r.subscriber)||void 0===t?void 0:t.getStats()]),2),a=e[0],s=e[1],o=a&&ds(a),c=s&&ds(s);this.statsLog.info("webrtc stats",{publisher:null==o?void 0:o.connection,subscriber:null==c?void 0:c.connection,inbound:[...null!==(n=null==o?void 0:o.inbound)&&void 0!==n?n:[],...null!==(i=null==c?void 0:c.inbound)&&void 0!==i?i:[]],outbound:null==o?void 0:o.outbound})}catch(a){this.statsLog.debug("could not collect webrtc stats",{error:a})}})),this.onLocalParticipantMetadataChanged=t=>{this.emit(e.RoomEvent.ParticipantMetadataChanged,t,this.localParticipant)},this.onLocalParticipantNameChanged=t=>{this.emit(e.RoomEvent.ParticipantNameChanged,t,this.localParticipant)},this.onLocalAttributesChanged=t=>{this.emit(e.RoomEvent.ParticipantAttributesChanged,t,this.localParticipant)},this.onLocalTrackMuted=t=>{this.emit(e.RoomEvent.TrackMuted,t,this.localParticipant)},this.onLocalTrackUnmuted=t=>{this.emit(e.RoomEvent.TrackUnmuted,t,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=t=>pr(this,void 0,void 0,(function*(){var n,i,r,a,s,o;if(null===(n=t.track)||void 0===n||n.on(e.TrackEvent.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=t.track)||void 0===i||i.on(e.TrackEvent.Restarted,this.onLocalTrackRestarted),null===(s=null===(a=null===(r=t.track)||void 0===r?void 0:r.getProcessor())||void 0===a?void 0:a.onPublish)||void 0===s||s.call(a,this),this.emit(e.RoomEvent.LocalTrackPublished,t,this.localParticipant),Oo(t.track)){(yield t.track.checkForSilence())&&this.emit(e.RoomEvent.LocalAudioSilenceDetected,t)}const c=yield null===(o=t.track)||void 0===o?void 0:o.getDeviceId(!1),d=Ps(t.source);d&&c&&c!==this.localParticipant.activeDeviceMap.get(d)&&(this.localParticipant.activeDeviceMap.set(d,c),this.emit(e.RoomEvent.ActiveDeviceChanged,d,c))})),this.onLocalTrackUnpublished=t=>{var n,i;null===(n=t.track)||void 0===n||n.off(e.TrackEvent.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=t.track)||void 0===i||i.off(e.TrackEvent.Restarted,this.onLocalTrackRestarted),this.emit(e.RoomEvent.LocalTrackUnpublished,t,this.localParticipant)},this.onLocalTrackRestarted=t=>pr(this,void 0,void 0,(function*(){const n=yield t.getDeviceId(!1),i=Ps(t.source);i&&n&&n!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(n," active")),this.localParticipant.activeDeviceMap.set(i,n),this.emit(e.RoomEvent.ActiveDeviceChanged,i,n))})),this.onLocalConnectionQualityChanged=t=>{this.emit(e.RoomEvent.ConnectionQualityChanged,t,this.localParticipant)},this.onMediaDevicesError=(t,n)=>{this.emit(e.RoomEvent.MediaDevicesError,t,n)},this.onLocalParticipantPermissionsChanged=t=>{this.emit(e.RoomEvent.ParticipantPermissionsChanged,t,this.localParticipant)},this.onLocalChatMessageSent=t=>{this.emit(e.RoomEvent.ChatMessage,t,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Ld),t),this.log=or(null!==(a=this.options.loggerName)&&void 0!==a?a:e.LoggerNames.Room,(()=>this.logContext)),this.statsLog=or(e.LoggerNames.Stats,(()=>this.logContext)),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Od),null==t?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Ad),null==t?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Dd),null==t?void 0:t.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Dl(null===(s=this.options.dataStream)||void 0===s?void 0:s.maxPayloadByteLength),this.outgoingDataStreamManager=new Wl(this.engine,this.log,this.getRemoteParticipantClientProtocol,this.getRemoteParticipantCapabilities,this.getAllRemoteParticipantIdentities),this.incomingDataTrackManager=new Su({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on("sfuUpdateSubscription",(e=>{this.engine.client.sendUpdateDataSubscription(e.sid,e.subscribe)})).on("trackPublished",(t=>{var n;t.track.publisherIdentity!==this.localParticipant.identity&&(this.emit(e.RoomEvent.DataTrackPublished,t.track),null===(n=this.remoteParticipants.get(t.track.publisherIdentity))||void 0===n||n.addRemoteDataTrack(t.track))})).on("trackUnpublished",(t=>{var n;t.publisherIdentity!==this.localParticipant.identity&&(this.emit(e.RoomEvent.DataTrackUnpublished,t.sid),null===(n=this.remoteParticipants.get(t.publisherIdentity))||void 0===n||n.removeRemoteDataTrack(t.sid))})),this.outgoingDataTrackManager=new xu({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on("sfuPublishRequest",(e=>{this.engine.client.sendPublishDataTrackRequest(e.handle,e.name,e.usesE2ee)})).on("sfuUnpublishRequest",(e=>{this.engine.client.sendUnPublishDataTrackRequest(e.handle)})).on("trackPublished",(t=>{this.emit(e.RoomEvent.LocalDataTrackPublished,t.track)})).on("trackUnpublished",(t=>{this.emit(e.RoomEvent.LocalDataTrackUnpublished,t.sid)})).on("packetAvailable",(e=>{let t=e.handle,n=e.bytes;this.engine.sendDataTrackFrame(n).finally((()=>this.outgoingDataTrackManager.handlePacketSendComplete(t)))})),this.registerRpcDataStreamHandler(),this.rpcClientManager=new Wu(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol,(()=>{var e,t;return null===(t=null===(e=this.engine.latestJoinResponse)||void 0===e?void 0:e.serverInfo)||void 0===t?void 0:t.version})),this.rpcClientManager.on("sendDataPacket",(e=>{let t=e.packet;var n;null===(n=this.engine)||void 0===n||n.sendDataPacket(t,Ud.RELIABLE)})),this.rpcServerManager=new Hu(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol),this.rpcServerManager.on("sendDataPacket",(e=>{let t=e.packet;var n;null===(n=this.engine)||void 0===n||n.sendDataPacket(t,Ud.RELIABLE)})),this.disconnectLock=new r,this.localParticipant=new eh("","",this.engine,this.options,this.outgoingDataStreamManager,this.outgoingDataTrackManager,this.rpcClientManager,this.rpcServerManager),this.setupFrameMetadata(),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager(null!==(o=this.e2eeManager)&&void 0!==o?o:null),this.outgoingDataTrackManager.updateE2eeManager(null!==(c=this.e2eeManager)&&void 0!==c?c:null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Eo(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Eo(this.options.audioCaptureDefaults.deviceId)),(null===(d=this.options.audioOutput)||void 0===d?void 0:d.deviceId)&&this.switchActiveDevice("audiooutput",Eo(this.options.audioOutput.deviceId)).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message)))),no()){const e=new AbortController;let t;if(ah.cleanupRegistry){const n=new WeakRef(this);t=()=>{const e=n.deref();e&&e.handleDeviceChange()},ah.cleanupRegistry.register(this,(()=>{e.abort()}))}else t=this.handleDeviceChange;null===(u=null===(l=navigator.mediaDevices)||void 0===l?void 0:l.addEventListener)||void 0===u||u.call(l,"devicechange",t,{signal:e.signal})}}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){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setE2EEEnabled(e){return pr(this,void 0,void 0,(function*(){const t=yield this.e2eeStateMutex.lock();try{if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");this.isE2EEEnabled!==e&&(yield this.localParticipant.setE2EEEnabled(e),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity))}finally{t()}}))}setupE2EE(){var t,n;const i=!!this.options.encryption,r=this.options.encryption||this.options.e2ee;r&&("e2eeManager"in r?(this.e2eeManager=r.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=i):this.e2eeManager=new vc(r,i),this.e2eeManager.on(e.EncryptionEvent.ParticipantEncryptionStatusChanged,((t,n)=>{xo(n)&&(this.isE2EEEnabled=t),this.emit(e.RoomEvent.ParticipantEncryptionStatusChanged,t,n)})),this.e2eeManager.on(e.EncryptionEvent.EncryptionError,((t,n)=>{const i=n?this.getParticipantByIdentity(n):void 0;this.emit(e.RoomEvent.EncryptionError,t,i)})),null===(t=this.e2eeManager)||void 0===t||t.setup(this),null===(n=this.e2eeManager)||void 0===n||n.setupEngine(this.engine))}setupFrameMetadata(){var e;const t=null!==(e=this.options.frameMetadata)&&void 0!==e?e:this.options.packetTrailer;this.frameMetadataManager=new kc(t),this.frameMetadataManager.setup(this)}get logContext(){var e,t,n;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:null===(t=this.localParticipant)||void 0===t?void 0:t.identity,participantID:null===(n=this.localParticipant)||void 0===n?void 0:n.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 this.state===e.ConnectionState.Disconnected?_a.resolve(""):this.roomInfo&&""!==this.roomInfo.sid?_a.resolve(this.roomInfo.sid):new _a(((t,n)=>{const i=n=>{""!==n.sid&&(this.engine.off(e.EngineEvent.RoomUpdate,i),t(n.sid))};this.engine.on(e.EngineEvent.RoomUpdate,i),this.once(e.RoomEvent.Disconnected,(()=>{this.engine.off(e.EngineEvent.RoomUpdate,i),n(new Ya("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.isNewlyCreated&&this.engine.isClosed)&&(this.engine=new kl(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(e.EngineEvent.ParticipantUpdate,this.handleParticipantUpdates).on(e.EngineEvent.RoomUpdate,this.handleRoomUpdate).on(e.EngineEvent.SpeakersChanged,this.handleSpeakersChanged).on(e.EngineEvent.StreamStateChanged,this.handleStreamStateUpdate).on(e.EngineEvent.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(e.EngineEvent.SubscriptionError,this.handleSubscriptionError).on(e.EngineEvent.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(e.EngineEvent.MediaTrackAdded,((e,t,n)=>{this.onTrackAdded(e,t,n)})).on(e.EngineEvent.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(e.EngineEvent.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(e.EngineEvent.DataPacketReceived,this.handleDataPacket).on(e.EngineEvent.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.debug("Resuming signal connection"),this.setAndEmitConnectionState(e.ConnectionState.SignalReconnecting)&&this.emit(e.RoomEvent.SignalReconnecting)})).on(e.EngineEvent.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug("Resumed signal connection"),this.updateSubscriptions(),this.setAndEmitConnectionState(e.ConnectionState.Connected)&&this.emit(e.RoomEvent.Reconnected),this.emitBufferedEvents()})).on(e.EngineEvent.SignalResumed,(()=>{(this.state===e.ConnectionState.Reconnecting||this.isResuming)&&this.sendSyncState(),this.emitBufferedEvents()})).on(e.EngineEvent.Restarting,this.handleRestarting).on(e.EngineEvent.Restarted,this.handleRestarted).on(e.EngineEvent.SignalRestarted,this.handleSignalRestarted).on(e.EngineEvent.Offline,(()=>{this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting)})).on(e.EngineEvent.DCBufferStatusChanged,((t,n)=>{this.emit(e.RoomEvent.DCBufferStatusChanged,t,n)})).on(e.EngineEvent.LocalTrackSubscribed,(e=>{this.handleLocalTrackSubscribed(e)})).on(e.EngineEvent.RoomMoved,(t=>{this.log.debug("room moved",t),t.room&&this.handleRoomUpdate(t.room),this.remoteParticipants.forEach(((e,t)=>{this.handleParticipantDisconnected(t,e)})),this.emit(e.RoomEvent.Moved,t.room.name),t.participant?this.handleParticipantUpdates([t.participant,...t.otherParticipants]):this.handleParticipantUpdates(t.otherParticipants)})).on(e.EngineEvent.PublishDataTrackResponse,(e=>{e.info?this.outgoingDataTrackManager.receivedSfuPublishResponse(e.info.pubHandle,{type:"ok",data:{sid:e.info.sid,pubHandle:e.info.pubHandle,name:e.info.name,usesE2ee:e.info.encryption!==ft.NONE}}):this.log.warn("received PublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."))})).on(e.EngineEvent.UnPublishDataTrackResponse,(e=>{e.info?this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle):this.log.warn("received UnPublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."))})).on(e.EngineEvent.DataTrackSubscriberHandles,(e=>{const t=new Map(Object.entries(e.subHandles).map((e=>{let t=F(e,2),n=t[0],i=t[1];return[parseInt(n,10),i.trackSid]})));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)})).on(e.EngineEvent.DataTrackPacketReceived,(e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(t){throw t}})).on(e.EngineEvent.Joined,(e=>{const t=new Map(e.otherParticipants.map((e=>[e.identity,e.dataTracks.map((e=>Ac.from(e)))])));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)})).on(e.EngineEvent.TokenRefreshed,(e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.updateToken(e)})).on(e.EngineEvent.ServerRegionsReported,(e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions({regionSettings:e,updatedAtInMs:Date.now(),maxAgeInMs:Tl})})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}createRegionStrategy(){return{getNextUrl:e=>pr(this,void 0,void 0,(function*(){return this.regionUrlProvider?this.regionUrlProvider.getNextBestRegionUrl(e):null})),resetAttempts:()=>{var e;return null===(e=this.regionUrlProvider)||void 0===e?void 0:e.resetAttempts()}}}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Sc.getInstance().getDevices(e,t)}prepareConnection(t,i){return pr(this,void 0,void 0,(function*(){if(this.state===e.ConnectionState.Disconnected){this.log.debug("prepareConnection to ".concat(t));try{if(ro(new URL(t))&&i){this.regionUrlProvider=new Sl(t,i);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===e.ConnectionState.Disconnected&&(this.regionUrl=n,yield fetch(Co(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n)))}else yield fetch(Co(t),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",{error:n})}}}))}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return pr(this,void 0,void 0,(function*(){let n,i=()=>pr(this,void 0,void 0,(function*(){}));switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"fail-on-v1-path":this.engine.failNextV1Path();break;case"speaker":n=new xi({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":n=new xi({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":n=new xi({scenario:{case:"serverLeave",value:!0}});break;case"migration":n=new xi({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":i=()=>pr(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),n=new xi({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>pr(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),n=new xi({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":n=new xi({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),i=()=>pr(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new mi({reason:at.CLIENT_INITIATED,action:gi.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");n=new xi({scenario:{case:"subscriberBandwidth",value:Po(t)}});break;case"leave-full-reconnect":n=new xi({scenario:{case:"leaveRequestFullReconnect",value:!0}})}n&&(yield this.engine.client.sendSimulateScenario(n),yield i())}))}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(t,i){return pr(this,arguments,void 0,(function(t,i){var r=this;let a=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var s,o,c,d,l,u,h;let p=!0,m=!1;const g=a?{exact:i}:i;if("audioinput"===t){m=0===r.localParticipant.audioTrackPublications.size;const e=null!==(s=r.getActiveDevice(t))&&void 0!==s?s:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=g;const i=Array.from(r.localParticipant.audioTrackPublications.values()).filter((e=>e.source===xs.Source.Microphone));try{p=(yield Promise.all(i.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(g)})))).every((e=>!0===e))}catch(n){throw r.options.audioCaptureDefaults.deviceId=e,n}const a=i.some((e=>{var t,n;return null!==(n=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==n&&n}));p&&a&&(m=!0)}else if("videoinput"===t){m=0===r.localParticipant.videoTrackPublications.size;const e=null!==(o=r.getActiveDevice(t))&&void 0!==o?o:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=g;const i=Array.from(r.localParticipant.videoTrackPublications.values()).filter((e=>e.source===xs.Source.Camera));try{p=(yield Promise.all(i.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(g)})))).every((e=>!0===e))}catch(n){throw r.options.videoCaptureDefaults.deviceId=e,n}const a=i.some((e=>{var t,n;return null!==(n=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==n&&n}));p&&a&&(m=!0)}else if("audiooutput"===t){if(m=!0,!Js()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");r.options.webAudioMix&&(i=null!==(c=yield Sc.getInstance().normalizeDeviceId("audiooutput",i))&&void 0!==c?c:""),null!==(d=(h=r.options).audioOutput)&&void 0!==d||(h.audioOutput={});const e=null!==(l=r.getActiveDevice(t))&&void 0!==l?l:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=i;try{r.options.webAudioMix&&(null===(u=r.audioContext)||void 0===u||u.setSinkId(i)),yield Promise.all(Array.from(r.remoteParticipants.values()).map((e=>e.setAudioOutput({deviceId:i}))))}catch(n){throw r.options.audioOutput.deviceId=e,n}}return m&&(r.localParticipant.activeDeviceMap.set(t,i),r.emit(e.RoomEvent.ActiveDeviceChanged,t,i)),p}()}))}setupLocalParticipantEvents(){this.localParticipant.on(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(e.ParticipantEvent.AttributesChanged,this.onLocalAttributesChanged).on(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).on(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).on(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).on(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).on(e.ParticipantEvent.AudioStreamAcquired,this.startAudio).on(e.ParticipantEvent.ChatMessage,this.onLocalChatMessageSent).on(e.ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){const t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally((()=>t.close())):null==t||t.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(t,n,i){var r,a;if([e.ConnectionState.Connecting,e.ConnectionState.Reconnecting].includes(this.state)){const a=Bo(t,n);this.log.debug("deferring on track for later",{mediaTrackId:t.id,mediaStreamId:n.id,tracksInStream:n.getTracks().map((e=>e.id))});const s=()=>{o(),this.onTrackAdded(t,n,i)},o=()=>{if(this.off(e.RoomEvent.Reconnected,s),this.off(e.RoomEvent.Connected,s),this.off(e.RoomEvent.Disconnected,o),a){const e=this.pendingTrackAddedCallbacks.get(a);null==e||e.delete(o),0===(null==e?void 0:e.size)&&this.pendingTrackAddedCallbacks.delete(a)}};if(this.once(e.RoomEvent.Reconnected,s),this.once(e.RoomEvent.Connected,s),this.once(e.RoomEvent.Disconnected,o),a){const e=null!==(r=this.pendingTrackAddedCallbacks.get(a))&&void 0!==r?r:new Set;e.add(o),this.pendingTrackAddedCallbacks.set(a,e)}return}if(this.state===e.ConnectionState.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected");if("ended"===t.readyState)return void this.log.debug("skipping incoming track as it already ended");const s=js(n.id),o=s[0],c=s[1];let d=null!==(a=Bo(t,n))&&void 0!==a?a:t.id;if(o===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant");const l=Array.from(this.remoteParticipants.values()).find((e=>e.sid===o));if(!l)return void(o.startsWith("PA")&&this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(o)));if(!d.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(o));d=e}let u;d.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(o,", streamId: ").concat(c,", trackId: ").concat(d),{remoteParticipantID:o,streamId:c,trackId:d}),this.options.adaptiveStream&&(u="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});const h=l.addSubscribedMediaTrack(t,d,n,i,u);(null==h?void 0:h.isEncrypted)&&!this.e2eeManager&&this.emit(e.RoomEvent.EncryptionError,new Error("Encrypted ".concat(h.source," track received from participant ").concat(l.sid,", but room does not have encryption enabled!")))}cancelPendingTrackAdded(e){var t;null===(t=this.pendingTrackAddedCallbacks.get(e))||void 0===t||t.forEach((e=>e()))}handleLocalTrackSubscribed(t){const n=()=>this.localParticipant.getTrackPublications().find((e=>e.trackSid===t)),i=n();if(i)return void this.emitLocalTrackSubscribed(i);this.log.debug("deferring LocalTrackSubscribed, publication not yet available",{subscribedSid:t});let r;const a=e=>{e.trackSid===t&&(s(),this.emitLocalTrackSubscribed(e))},s=()=>{clearTimeout(r),this.localParticipant.off(e.ParticipantEvent.LocalTrackPublished,a),this.off(e.RoomEvent.Disconnected,s)};this.localParticipant.on(e.ParticipantEvent.LocalTrackPublished,a),this.once(e.RoomEvent.Disconnected,s),r=setTimeout((()=>{s();const e=n();e?this.emitLocalTrackSubscribed(e):this.log.warn("could not find local track publication for LocalTrackSubscribed event after timeout",{subscribedSid:t})}),1e4)}emitLocalTrackSubscribed(t){this.localParticipant.emit(e.ParticipantEvent.LocalTrackSubscribed,t),this.emitWhenConnected(e.RoomEvent.LocalTrackSubscribed,t,this.localParticipant)}handleDisconnect(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],n=arguments.length>1?arguments[1]:void 0;var i,r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.incomingDataTrackManager.reset(),this.outgoingDataTrackManager.reset(),this.state!==e.ConnectionState.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((e=>{var n,i,r;e.track&&this.localParticipant.unpublishTrack(e.track,t),t?(null===(n=e.track)||void 0===n||n.detach(),null===(i=e.track)||void 0===i||i.stop()):null===(r=e.track)||void 0===r||r.stopMonitor()})),this.localParticipant.off(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(e.ParticipantEvent.AttributesChanged,this.onLocalAttributesChanged).off(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).off(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).off(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).off(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).off(e.ParticipantEvent.AudioStreamAcquired,this.startAudio).off(e.ParticipantEvent.ChatMessage,this.onLocalChatMessageSent).off(e.ParticipantEvent.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),no()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(r=null===(i=navigator.mediaDevices)||void 0===i?void 0:i.removeEventListener)||void 0===r||r.call(i,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(e.ConnectionState.Disconnected),this.emit(e.RoomEvent.Disconnected,n)}}}handleParticipantDisconnected(t,n,i){this.remoteParticipants.delete(t),n&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(t),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(t),n.trackPublications.forEach((e=>{n.unpublishTrack(e.trackSid,!0)})),this.emit(e.RoomEvent.ParticipantDisconnected,n,i),n.setDisconnected(),this.rpcClientManager.handleParticipantDisconnected(n.identity))}selectDefaultDevices(){return pr(this,void 0,void 0,(function*(){var t,n,i;const r=Sc.getInstance().previousDevices,a=yield Sc.getInstance().getDevices(void 0,!1),s=Oa();if("Chrome"===(null==s?void 0:s.name)&&"iOS"!==s.os)for(let c of a){const t=r.find((e=>e.deviceId===c.deviceId));t&&""!==t.label&&t.kind===c.kind&&t.label!==c.label&&"default"===this.getActiveDevice(c.kind)&&this.emit(e.RoomEvent.ActiveDeviceChanged,c.kind,c.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let e of o){const s=Rs(e),o=this.localParticipant.getTrackPublication(s);if(o&&(null===(t=o.track)||void 0===t?void 0:t.isUserProvided))continue;const c=a.filter((t=>t.kind===e)),d=this.getActiveDevice(e);d===(null===(n=r.filter((t=>t.kind===e))[0])||void 0===n?void 0:n.deviceId)&&c.length>0&&(null===(i=c[0])||void 0===i?void 0:i.deviceId)!==d?yield this.switchActiveDevice(e,c[0].deviceId):"audioinput"===e&&!$s()||"videoinput"===e||!(c.length>0)||c.find((t=>t.deviceId===this.getActiveDevice(e)))||"audiooutput"===e&&$s()||(yield this.switchActiveDevice(e,c[0].deviceId))}}))}acquireAudioContext(){return pr(this,void 0,void 0,(function*(){var t,i;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!==(t=ws())&&void 0!==t?t: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(),qs(200)])}catch(n){this.log.warn("Could not resume audio context",{error:n})}const r="running"===(null===(i=this.audioContext)||void 0===i?void 0:i.state);r!==this.canPlaybackAudio&&(this.audioEnabled=r,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,r))}))}createParticipant(e,t){var n;let i;return i=t?rh.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):new rh(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&i.setAudioOutput(this.options.audioOutput).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message)))),i}getOrCreateParticipant(t,n){if(this.remoteParticipants.has(t)){const e=this.remoteParticipants.get(t);if(n){e.updateInfo(n)&&this.sidToIdentity.set(n.sid,n.identity)}return e}const i=this.createParticipant(t,n);return this.remoteParticipants.set(t,i),this.sidToIdentity.set(n.sid,n.identity),this.emitWhenConnected(e.RoomEvent.ParticipantConnected,i),i.on(e.ParticipantEvent.TrackPublished,(t=>{this.emitWhenConnected(e.RoomEvent.TrackPublished,t,i)})).on(e.ParticipantEvent.TrackSubscribed,((t,n)=>{t.kind===xs.Kind.Audio?(t.on(e.TrackEvent.AudioPlaybackStarted,this.handleAudioPlaybackStarted),t.on(e.TrackEvent.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):t.kind===xs.Kind.Video&&(t.on(e.TrackEvent.VideoPlaybackFailed,this.handleVideoPlaybackFailed),t.on(e.TrackEvent.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(e.RoomEvent.TrackSubscribed,t,n,i)})).on(e.ParticipantEvent.TrackUnpublished,(t=>{this.cancelPendingTrackAdded(t.trackSid),this.emit(e.RoomEvent.TrackUnpublished,t,i)})).on(e.ParticipantEvent.TrackUnsubscribed,((t,n)=>{this.emit(e.RoomEvent.TrackUnsubscribed,t,n,i)})).on(e.ParticipantEvent.TrackMuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackMuted,t,i)})).on(e.ParticipantEvent.TrackUnmuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackUnmuted,t,i)})).on(e.ParticipantEvent.ParticipantMetadataChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantMetadataChanged,t,i)})).on(e.ParticipantEvent.ParticipantNameChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantNameChanged,t,i)})).on(e.ParticipantEvent.AttributesChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantAttributesChanged,t,i)})).on(e.ParticipantEvent.ConnectionQualityChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ConnectionQualityChanged,t,i)})).on(e.ParticipantEvent.ParticipantPermissionsChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantPermissionsChanged,t,i)})).on(e.ParticipantEvent.TrackSubscriptionStatusChanged,((t,n)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionStatusChanged,t,n,i)})).on(e.ParticipantEvent.TrackSubscriptionFailed,((t,n)=>{this.emit(e.RoomEvent.TrackSubscriptionFailed,t,i,n)})).on(e.ParticipantEvent.TrackSubscriptionPermissionChanged,((t,n)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionPermissionChanged,t,n,i)})).on(e.ParticipantEvent.Active,(()=>{this.emitWhenConnected(e.RoomEvent.ParticipantActive,i),i.kind===gt.AGENT&&this.localParticipant.setActiveAgent(i)})),n&&i.updateInfo(n),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce(((e,t)=>(e.push(...t.getTrackPublications()),e)),[]),t=this.localParticipant.getTrackPublications(),n=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,n)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&Lo(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}getClientInfoCapabilities(e){var t;const n=[];return(sc(null!==(t=e.frameMetadata)&&void 0!==t?t:e.packetTrailer)||this.e2eeManager)&&n.push(Xt.CAP_PACKET_TRAILER),Fo()&&n.push(Xt.CAP_COMPRESSION_DEFLATE_RAW),n}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(Fu,((e,t)=>pr(this,[e,t],void 0,(function(e,t){var n=this;let i=t.identity;return function*(){var t;const r=null!==(t=e.info.attributes)&&void 0!==t?t:{};yield n.rpcServerManager.handleIncomingDataStream(e,i,r)}()})))),this.incomingDataStreamManager.registerTextStreamHandler(Bu,((e,t)=>pr(this,[e,t],void 0,(function(e,t){var n=this;let i=t.identity;return function*(){var t;const r=null!==(t=e.info.attributes)&&void 0!==t?t:{};yield n.rpcClientManager.handleIncomingDataStream(e,i,r)}()}))))}setStatsLogging(e){e?this.statsLogInterval||(this.statsLogInterval=is.setInterval((()=>{this.logWebRTCStats()}),3e4)):this.statsLogInterval&&(is.clearInterval(this.statsLogInterval),this.statsLogInterval=void 0)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=is.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0}),e>=3&&(this.clearConnectionReconcile(),this.engine&&!this.engine.isClosed?(this.log.warn("detected connection state mismatch, attempting full reconnect"),this.engine.reconnect()):(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,at.STATE_MISMATCH))))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&is.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(t){return t!==this.state&&(this.log.info("connection state changed: ".concat(this.state," -> ").concat(t)),this.state=t,this.incomingDataStreamManager.setConnected(t===e.ConnectionState.Connected),this.setStatsLogging(t===e.ConnectionState.Connected),this.emit(e.RoomEvent.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach((e=>{let t=F(e,2),n=t[0],i=t[1];this.emit(n,...i)})),this.bufferedEvents=[]}emitWhenConnected(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(this.state===e.ConnectionState.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([t,i]);else if(this.state===e.ConnectionState.Connected)return this.emit(t,...i);return!1}simulateParticipants(t){return pr(this,void 0,void 0,(function*(){var n,i,r,a;const s=Object.assign({audio:!0,video:!0,useRealTracks:!1},t.publish),o=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},t.participants);if(this.handleDisconnect(),this.roomInfo=new lt({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:R.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new pt({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected),this.emit(e.RoomEvent.Connected),this.setAndEmitConnectionState(e.ConnectionState.Connected),s.video){const t=new Gu(xs.Kind.Video,new yt({source:tt.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:et.AUDIO,name:"video-dummy"}),new hl(s.useRealTracks&&(null===(n=window.navigator.mediaDevices)||void 0===n?void 0:n.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:yo(160*(null!==(i=o.aspectRatios[0])&&void 0!==i?i:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}if(s.audio){const t=new Gu(xs.Kind.Audio,new yt({source:tt.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:et.AUDIO}),new $d(s.useRealTracks&&(null===(r=navigator.mediaDevices)||void 0===r?void 0:r.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:bo(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}for(let e=0;e<o.count-1;e+=1){let t=new pt({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:mt.ACTIVE,tracks:[],joinedAt:R.parse(Date.now())});const n=this.getOrCreateParticipant(t.identity,t);if(o.video){const i=yo(160*(null!==(a=o.aspectRatios[e%o.aspectRatios.length])&&void 0!==a?a:1),160,!1,!0),r=new yt({source:tt.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:et.AUDIO});n.addSubscribedMediaTrack(i,r.sid,new MediaStream([i]),new RTCRtpReceiver),t.tracks=[...t.tracks,r]}if(o.audio){const e=bo(),i=new yt({source:tt.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:et.AUDIO});n.addSubscribedMediaTrack(e,i.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,i]}n.updateInfo(t)}}))}emit(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(t!==e.RoomEvent.ActiveSpeakersChanged&&t!==e.RoomEvent.TranscriptionReceived){const n=sh(i).filter((e=>void 0!==e));t!==e.RoomEvent.TrackSubscribed&&t!==e.RoomEvent.TrackUnsubscribed||this.log.trace("subscribe trace: ".concat(t),{event:t,args:n}),this.log.debug("room event ".concat(t),{event:t,args:n})}return super.emit(t,...i)}}function sh(e){return e.map((e=>{if(e)return Array.isArray(e)?sh(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e}))}ah.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&"undefined"!=typeof WeakRef&&new FinalizationRegistry((e=>{e()}));var oh,ch=Object.freeze({__proto__:null,Convert:class{static toAgentAttributes(e){return JSON.parse(e)}static agentAttributesToJson(e){return JSON.stringify(e)}static toTranscriptionAttributes(e){return JSON.parse(e)}static transcriptionAttributesToJson(e){return JSON.stringify(e)}}});e.CheckStatus=void 0,(oh=e.CheckStatus||(e.CheckStatus={}))[oh.IDLE=0]="IDLE",oh[oh.RUNNING=1]="RUNNING",oh[oh.SKIPPED=2]="SKIPPED",oh[oh.SUCCESS=3]="SUCCESS",oh[oh.FAILED=4]="FAILED";class dh extends br.EventEmitter{constructor(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.status=e.CheckStatus.IDLE,this.logs=[],this.options={},this.url=t,this.token=n,this.name=this.constructor.name,this.room=new ah(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(t){return pr(this,void 0,void 0,(function*(){if(this.status!==e.CheckStatus.IDLE)throw Error("check is running already");this.setStatus(e.CheckStatus.RUNNING);try{yield this.perform()}catch(n){n instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(n.message):this.appendError(n.message))}return yield this.disconnect(),yield new Promise((e=>setTimeout(e,500))),this.status!==e.CheckStatus.SKIPPED&&this.setStatus(this.isSuccess()?e.CheckStatus.SUCCESS:e.CheckStatus.FAILED),t&&t(),this.getInfo()}))}isSuccess(){return!this.logs.some((e=>"error"===e.level))}connect(t){return pr(this,void 0,void 0,(function*(){return this.room.state===e.ConnectionState.Connected||(t||(t=this.url),yield this.room.connect(t,this.token,this.connectOptions)),this.room}))}disconnect(){return pr(this,void 0,void 0,(function*(){this.room&&this.room.state!==e.ConnectionState.Disconnected&&(yield this.room.disconnect(),yield new Promise((e=>setTimeout(e,500))))}))}skip(){this.setStatus(e.CheckStatus.SKIPPED)}switchProtocol(t){return pr(this,void 0,void 0,(function*(){let n=!1,i=!1;if(this.room.on(e.RoomEvent.Reconnecting,(()=>{n=!0})),this.room.once(e.RoomEvent.Reconnected,(()=>{i=!0})),this.room.simulateScenario("force-".concat(t)),yield new Promise((e=>setTimeout(e,1e3))),!n)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield qs(100)}throw new Error("Could not reconnect using ".concat(t," protocol after 10 seconds"))}))}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return null===(e=this.room)||void 0===e?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class lh extends dh{get description(){return"Cloud regions"}perform(){return pr(this,void 0,void 0,(function*(){const e=new Sl(this.url,this.token);if(!e.isCloud())return void this.skip();const t=[],n=new Set;for(let r=0;r<3;r++){const i=yield e.getNextBestRegionUrl();if(!i)break;if(n.has(i))continue;n.add(i);const r=yield this.checkCloudRegion(i);this.appendMessage("".concat(r.region," RTT: ").concat(r.rtt,"ms, duration: ").concat(r.duration,"ms")),t.push(r)}t.sort(((e,t)=>.5*(e.duration-t.duration)+.5*(e.rtt-t.rtt)));const i=t[0];this.bestStats=i,this.appendMessage("best Cloud region: ".concat(i.region))}))}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return pr(this,void 0,void 0,(function*(){var t,n;yield this.connect(e),"tcp"===this.options.protocol&&(yield this.switchProtocol("tcp"));const i=null===(t=this.room.serverInfo)||void 0===t?void 0:t.region;if(!i)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),a="A".repeat(1e3),s=Date.now();for(let e=0;e<1e3;e++)yield r.write(a);yield r.close();const o=Date.now(),c=yield null===(n=this.room.engine.pcManager)||void 0===n?void 0:n.publisher.getStats(),d={region:i,rtt:1e4,duration:o-s};return null==c||c.forEach((e=>{"candidate-pair"===e.type&&e.nominated&&(d.rtt=1e3*e.currentRoundTripTime)})),yield this.disconnect(),d}))}}const uh=1e4;class hh extends dh{get description(){return"Connection via UDP vs TCP"}perform(){return pr(this,void 0,void 0,(function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const n=this.bestStats;this.appendMessage("upstream bitrate: ".concat((n.bitrateTotal/n.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((n.rttTotal/n.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((n.jitterTotal/n.count*1e3).toFixed(2)," ms")),n.packetsLost>0&&this.appendWarning("packets lost: ".concat((n.packetsLost/n.packetsSent*100).toFixed(2),"%")),n.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((n.qualityLimitationDurations.bandwidth/10*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/10*100).toFixed(2),"%"))}))}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return pr(this,void 0,void 0,(function*(){yield this.connect(),"tcp"===e?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const n=t.getContext("2d");if(!n)throw new Error("Could not get canvas context");let i=0;const r=()=>{i=(i+1)%360,n.fillStyle="hsl(".concat(i,", 100%, 50%)"),n.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const a=t.captureStream(30).getVideoTracks()[0],s=(yield this.room.localParticipant.publishTrack(a,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,o={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},c=setInterval((()=>pr(this,void 0,void 0,(function*(){const e=yield s.getRTCStatsReport();null==e||e.forEach((e=>{"outbound-rtp"===e.type?(o.packetsSent=e.packetsSent,o.qualityLimitationDurations=e.qualityLimitationDurations,o.bitrateTotal+=e.targetBitrate,o.count++):"remote-inbound-rtp"===e.type&&(o.packetsLost=e.packetsLost,o.rttTotal+=e.roundTripTime,o.jitterTotal+=e.jitter)}))}))),1e3);return yield new Promise((e=>setTimeout(e,uh))),clearInterval(c),a.stop(),t.remove(),yield this.disconnect(),o}))}}class ph extends dh{get description(){return"Can publish audio"}perform(){return pr(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),n=yield Yu();if(yield Cs(n,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(n),yield new Promise((e=>setTimeout(e,3e3)));const i=yield null===(e=n.sender)||void 0===e?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let r=0;if(i.forEach((e=>{"outbound-rtp"!==e.type||"audio"!==e.kind&&(e.kind||"audio"!==e.mediaType)||(r=e.packetsSent)})),0===r)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," audio packets"))}))}}class mh extends dh{get description(){return"Can publish video"}perform(){return pr(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),n=yield Qu();yield this.checkForVideo(n.mediaStreamTrack),t.localParticipant.publishTrack(n),yield new Promise((e=>setTimeout(e,5e3)));const i=yield null===(e=n.sender)||void 0===e?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let r=0;if(i.forEach((e=>{"outbound-rtp"!==e.type||"video"!==e.kind&&(e.kind||"video"!==e.mediaType)||(r+=e.packetsSent)})),0===r)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))}))}checkForVideo(e){return pr(this,void 0,void 0,(function*(){const t=new MediaStream;t.addTrack(e.clone());const n=document.createElement("video");n.srcObject=t,n.muted=!0,n.autoplay=!0,n.playsInline=!0,n.setAttribute("playsinline","true"),document.body.appendChild(n),yield new Promise((t=>{n.onplay=()=>{setTimeout((()=>{var i,r,a,s;const o=document.createElement("canvas"),c=e.getSettings(),d=null!==(r=null!==(i=c.width)&&void 0!==i?i:n.videoWidth)&&void 0!==r?r:1280,l=null!==(s=null!==(a=c.height)&&void 0!==a?a:n.videoHeight)&&void 0!==s?s:720;o.width=d,o.height=l;const u=o.getContext("2d");u.drawImage(n,0,0);const h=u.getImageData(0,0,o.width,o.height).data;let p=!0;for(let e=0;e<h.length;e+=4)if(0!==h[e]||0!==h[e+1]||0!==h[e+2]){p=!1;break}p?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),t()}),1e3)},n.play()})),t.getTracks().forEach((e=>e.stop())),n.remove()}))}}class gh extends dh{get description(){return"Resuming connection after interruption"}perform(){return pr(this,void 0,void 0,(function*(){var t;const n=yield this.connect();let i,r=!1,a=!1;const s=new Promise((e=>{setTimeout(e,5e3),i=e})),o=()=>{r=!0};n.on(e.RoomEvent.SignalReconnecting,o).on(e.RoomEvent.Reconnecting,o).on(e.RoomEvent.Reconnected,(()=>{a=!0,i(!0)})),null===(t=n.engine.client.ws)||void 0===t||t.close();const c=n.engine.client.onClose;if(c&&c(""),yield s,!r)throw new Error("Did not attempt to reconnect");if(!a||n.state!==e.ConnectionState.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}))}}class vh extends dh{get description(){return"Can connect via TURN"}perform(){return pr(this,void 0,void 0,(function*(){var e,t,n;ro(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=null!==(e=yield new Sl(this.url,this.token).getNextBestRegionUrl())&&void 0!==e?e:this.url);const i=new id,r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let a=!1,s=!1,o=!1;for(let c of r.iceServers)for(let e of c.urls)e.startsWith("turn:")?(s=!0,o=!0):e.startsWith("turns:")&&(s=!0,o=!0,a=!0),e.startsWith("stun:")&&(o=!0);o?s&&!a&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),(null===(n=null===(t=this.connectOptions)||void 0===t?void 0:t.rtcConfig)||void 0===n?void 0:n.iceServers)||s?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise((e=>setTimeout(e,0))))}))}}class fh extends dh{get description(){return"Establishing WebRTC connection"}perform(){return pr(this,void 0,void 0,(function*(){let t=!1,n=!1;this.room.on(e.RoomEvent.SignalConnected,(()=>{var e;const i=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(e,r)=>{if(e.candidate){const i=new RTCIceCandidate(e);let r="".concat(i.protocol," ").concat(i.address,":").concat(i.port," ").concat(i.type);i.address&&(!function(e){const t=e.split(".");if(4===t.length){if("10"===t[0])return!0;if("192"===t[0]&&"168"===t[1])return!0;if("172"===t[0]){const e=parseInt(t[1],10);if(e>=16&&e<=31)return!0}}return!1}(i.address)?"tcp"===i.protocol&&"passive"===i.tcpType?(t=!0,r+=" (passive)"):"udp"===i.protocol&&(n=!0):r+=" (private)"),this.appendMessage(r)}i&&i(e,r)},(null===(e=this.room.engine.pcManager)||void 0===e?void 0:e.subscriber)&&(this.room.engine.pcManager.subscriber.onIceCandidateError=e=>{e instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(e.errorCode," ").concat(e.errorText," ").concat(e.url))})}));try{yield this.connect(),ar.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}t||this.appendWarning("Server is not configured for ICE/TCP"),n||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")}))}}class kh extends dh{get description(){return"Connecting to signal connection via WebSocket"}perform(){return pr(this,void 0,void 0,(function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r,a=new id;try{r=yield a.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(n){if(ro(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(n.message,". Retrying with region fallback"));const t=new Sl(this.url,this.token),i=yield t.getNextBestRegionUrl();i&&(r=yield a.join(i,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}r?(this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),(null===(e=r.serverInfo)||void 0===e?void 0:e.edition)===Jt.Cloud&&(null===(t=r.serverInfo)||void 0===t?void 0:t.region)&&this.appendMessage("LiveKit Cloud: ".concat(null===(i=r.serverInfo)||void 0===i?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield a.close()}))}}class yh extends br.EventEmitter{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=n}getNextCheckId(){const t=this.checkResults.size;return this.checkResults.set(t,{logs:[],status:e.CheckStatus.IDLE,name:"",description:""}),t}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every((t=>t.status!==e.CheckStatus.FAILED))}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return pr(this,void 0,void 0,(function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token,this.options),i=e=>{this.updateCheck(t,e)};n.on("update",i);const r=yield n.run();return n.off("update",i),r}))}checkWebsocket(){return pr(this,void 0,void 0,(function*(){return this.createAndRunCheck(kh)}))}checkWebRTC(){return pr(this,void 0,void 0,(function*(){return this.createAndRunCheck(fh)}))}checkTURN(){return pr(this,void 0,void 0,(function*(){return this.createAndRunCheck(vh)}))}checkReconnect(){return pr(this,void 0,void 0,(function*(){return this.createAndRunCheck(gh)}))}checkPublishAudio(){return pr(this,void 0,void 0,(function*(){return this.createAndRunCheck(ph)}))}checkPublishVideo(){return pr(this,void 0,void 0,(function*(){return this.createAndRunCheck(mh)}))}checkConnectionProtocol(){return pr(this,void 0,void 0,(function*(){const e=yield this.createAndRunCheck(hh);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e}))}checkCloudRegion(){return pr(this,void 0,void 0,(function*(){return this.createAndRunCheck(lh)}))}}class bh{}class Th{}new TextEncoder;const Sh=new TextDecoder;function Eh(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:Sh.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=Sh.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return function(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);const t=atob(e),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return n}(t)}catch(n){throw new TypeError("The input to be decoded is not correctly encoded.")}}class Ch extends Error{constructor(e,t){var n;super(e,t),N(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor)}}N(Ch,"code","ERR_JOSE_GENERIC");N(class extends Ch{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:i,payload:t}}),N(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),N(this,"claim",void 0),N(this,"reason",void 0),N(this,"payload",void 0),this.claim=n,this.reason=i,this.payload=t}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED");N(class extends Ch{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:i,payload:t}}),N(this,"code","ERR_JWT_EXPIRED"),N(this,"claim",void 0),N(this,"reason",void 0),N(this,"payload",void 0),this.claim=n,this.reason=i,this.payload=t}},"code","ERR_JWT_EXPIRED");N(class extends Ch{constructor(){super(...arguments),N(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED");N(class extends Ch{constructor(){super(...arguments),N(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED");N(class extends Ch{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),N(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED");N(class extends Ch{constructor(){super(...arguments),N(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID");N(class extends Ch{constructor(){super(...arguments),N(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID");class wh extends Ch{constructor(){super(...arguments),N(this,"code","ERR_JWT_INVALID")}}N(wh,"code","ERR_JWT_INVALID");N(class extends Ch{constructor(){super(...arguments),N(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID");N(class extends Ch{constructor(){super(...arguments),N(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID");N(class extends Ch{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),N(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY");N(class extends Ch{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),N(this,Symbol.asyncIterator,void 0),N(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");N(class extends Ch{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),N(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT");N(class extends Ch{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),N(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");function Rh(e){if("string"!=typeof e)throw new wh("JWTs must use Compact JWS serialization, JWT must be a string");const t=e.split("."),n=t[1],i=t.length;if(5===i)throw new wh("Only JWTs using Compact JWS serialization can be decoded");if(3!==i)throw new wh("Invalid JWT");if(!n)throw new wh("JWTs must contain a payload");let r,a;try{r=Eh(n)}catch(s){throw new wh("Failed to base64url decode the payload")}try{a=JSON.parse(Sh.decode(r))}catch(o){throw new wh("Failed to parse the decoded payload as JSON")}if(!function(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let n=e;for(;null!==Object.getPrototypeOf(n);)n=Object.getPrototypeOf(n);return Object.getPrototypeOf(e)===n}(a))throw new wh("Invalid JWT Claims Set");return a}const Ph=1e3;function Ih(e){const t=Rh(e);t.roomConfig;const n=hr(t,["roomConfig"]);return Object.assign(Object.assign({},n),{roomConfig:t.roomConfig?xn.fromJson(t.roomConfig,{ignoreUnknownFields:!0}):void 0})}function _h(e,t){const n=new Set([...Object.keys(e),...Object.keys(t)]);for(const i of n)switch(i){case"roomName":case"participantName":case"participantIdentity":case"participantMetadata":case"participantAttributes":case"agentName":case"agentMetadata":case"deployment":if(e[i]!==t[i])return!1;break;default:throw new Error("Options key ".concat(i," not being checked for equality!"))}return!0}class Mh extends Th{constructor(){super(...arguments),this.cachedFetchOptions=null,this.cachedResponse=null,this.fetchMutex=new r}isSameAsCachedFetchOptions(e){return!!this.cachedFetchOptions&&_h(e,this.cachedFetchOptions)}shouldReturnCachedValueFromFetch(e){return!!this.cachedResponse&&(!!function(e){const t=Ih(e.participantToken);if(!(null==t?void 0:t.exp))return!1;const n=new Date;if(t.nbf){const e=t.nbf*Ph;if(new Date(e)>n)return!1}const i=t.exp*Ph;return new Date(i-6e4)>n}(this.cachedResponse)&&!!this.isSameAsCachedFetchOptions(e))}getCachedResponseJwtPayload(){return this.cachedResponse?Ih(this.cachedResponse.participantToken):null}fetch(e,t){return pr(this,void 0,void 0,(function*(){const n=yield this.fetchMutex.lock();try{if(t&&(this.cachedResponse=null),this.shouldReturnCachedValueFromFetch(e))return this.cachedResponse.toJson();this.cachedFetchOptions=e;const n=yield this.update(e);return this.cachedResponse=n,n.toJson()}finally{n()}}))}}class Dh extends bh{constructor(e){super(),this.literalOrFn=e}fetch(){return pr(this,void 0,void 0,(function*(){return"function"==typeof this.literalOrFn?this.literalOrFn():this.literalOrFn}))}}class Oh extends Mh{constructor(e){super(),this.customFn=e}update(e){return pr(this,void 0,void 0,(function*(){const t=this.customFn(e);let n;return n=t instanceof Promise?yield t:t,Xi.fromJson(n,{ignoreUnknownFields:!0})}))}}class Ah extends Mh{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),this.url=e,this.endpointOptions=t}createRequestFromOptions(e){var t,n,i,r;const a=new Yi;for(const s of Object.keys(e))switch(s){case"roomName":case"participantName":case"participantIdentity":case"participantMetadata":a[s]=e[s];break;case"participantAttributes":a.participantAttributes=null!==(t=e.participantAttributes)&&void 0!==t?t:{};break;case"agentName":a.roomConfig=null!==(n=a.roomConfig)&&void 0!==n?n:new xn,0===a.roomConfig.agents.length&&a.roomConfig.agents.push(new mn),a.roomConfig.agents[0].agentName=e.agentName;break;case"agentMetadata":a.roomConfig=null!==(i=a.roomConfig)&&void 0!==i?i:new xn,0===a.roomConfig.agents.length&&a.roomConfig.agents.push(new mn),a.roomConfig.agents[0].metadata=e.agentMetadata;break;case"deployment":a.roomConfig=null!==(r=a.roomConfig)&&void 0!==r?r:new xn,0===a.roomConfig.agents.length&&a.roomConfig.agents.push(new mn),a.roomConfig.agents[0].deployment=e.deployment;break;default:throw new Error("Options key ".concat(s," not being included in forming request!"))}return a}update(e){return pr(this,void 0,void 0,(function*(){var t;const n=this.createRequestFromOptions(e),i=yield fetch(this.url,Object.assign(Object.assign({},this.endpointOptions),{method:null!==(t=this.endpointOptions.method)&&void 0!==t?t:"POST",headers:Object.assign({"Content-Type":"application/json"},this.endpointOptions.headers),body:n.toJsonString({useProtoFieldName:!0})}));if(!i.ok)throw new Error("Error generating token from endpoint ".concat(this.url,": received ").concat(i.status," / ").concat(yield i.text()));const r=yield i.json();return Xi.fromJson(r,{ignoreUnknownFields:!0})}))}}class Lh extends Ah{constructor(e,t){const n=t.baseUrl,i=void 0===n?"https://cloud-api.livekit.io":n,r=hr(t,["baseUrl"]);super("".concat(i,"/api/v2/sandbox/connection-details"),Object.assign(Object.assign({},r),{headers:{"X-Sandbox-ID":e}}))}}class Nh extends Lh{}const xh={literal:e=>new Dh(e),custom:e=>new Oh(e),endpoint(e){return new Ah(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})},sandboxTokenServer(e){return new Nh(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})},developmentTokenServer(e){return new Lh(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}};const Uh=new Map([["obs virtual camera",{facingMode:"environment",confidence:"medium"}]]),Fh=new Map([["iphone",{facingMode:"environment",confidence:"medium"}],["ipad",{facingMode:"environment",confidence:"medium"}]]);function Bh(e){var t;const n=e.trim().toLowerCase();if(""!==n)return Uh.has(n)?Uh.get(n):null===(t=Array.from(Fh.entries()).find((e=>{let t=F(e,1)[0];return n.includes(t)})))||void 0===t?void 0:t[1]}const jh=Symbol.for("lk.serializer");function qh(e){return Object.assign(Object.assign({},e),{symbol:jh})}const Vh={json:function(){return qh({parse:e=>JSON.parse(e),serialize:e=>JSON.stringify(e)})},raw:function(){return qh({parse:e=>e,serialize:e=>e})},custom:function(e){return qh(e)}};e.BaseKeyProvider=ic,e.CLIENT_PROTOCOL_DATA_STREAM_RPC=1,e.CLIENT_PROTOCOL_DATA_STREAM_V2=2,e.CLIENT_PROTOCOL_DEFAULT=0,e.Checker=dh,e.ConnectionCheck=yh,e.ConnectionError=za,e.CriticalTimers=is,e.CryptorError=class extends Ua{constructor(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.CryptorErrorReason.InternalError,i=arguments.length>2?arguments[2]:void 0;super(40,t),this.reason=n,this.participantIdentity=i}},e.DataPacket_Kind=Ot,e.DataStreamError=ts,e.DataTrackPacket=hu,e.DefaultReconnectPolicy=ur,e.DeviceUnsupportedError=Ga,e.DisconnectReason=at,e.Encryption_Type=ft,e.ExternalE2EEKeyProvider=class extends ic{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(Object.assign(Object.assign({},e),{sharedKey:!0,ratchetWindowSize:0,failureTolerance:-1}))}setKey(e){return pr(this,void 0,void 0,(function*(){const t="string"==typeof e?yield $o(e):yield ec(e);this.onSetEncryptionKey(t)}))}},e.FrameMetadataManager=kc,e.LivekitError=Ua,e.LivekitReasonedError=Fa,e.LocalAudioTrack=$d,e.LocalDataTrack=Ou,e.LocalParticipant=eh,e.LocalTrack=Zd,e.LocalTrackPublication=Gu,e.LocalTrackRecorder=Xd,e.LocalVideoTrack=hl,e.Mutex=r,e.NegotiationError=Xa,e.PacketTrailerManager=yc,e.Participant=$u,e.ParticipantKind=gt,e.PublishDataError=Za,e.PublishTrackError=$a,e.RemoteAudioTrack=Ku,e.RemoteDataTrack=du,e.RemoteParticipant=rh,e.RemoteTrack=uc,e.RemoteTrackPublication=ih,e.RemoteVideoTrack=hc,e.Room=ah,e.RpcError=Uu,e.ScreenSharePresets=bs,e.SignalReconnectError=ns,e.SignalRequestError=es,e.SimulatedError=class extends Ua{constructor(){super(-1,arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Simulated failure"),this.name="simulated"}},e.SubscriptionError=ot,e.TokenSource=xh,e.TokenSourceConfigurable=Th,e.TokenSourceFixed=bh,e.Track=xs,e.TrackInvalidError=Ja,e.TrackPublication=zu,e.TrackType=et,e.UnexpectedConnectionState=Ya,e.UnsupportedServer=Qa,e.VideoPreset=ls,e.VideoPresets=ks,e.VideoPresets43=ys,e.areTokenSourceFetchOptionsEqual=_h,e.asEncryptablePacket=nc,e.attachToElement=Us,e.attributes=ch,e.audioCodecs=us,e.clientProtocol=2,e.compareVersions=lo,e.createAudioAnalyser=function(e,t){const n=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),i=ws();if(!i)throw new Error("Audio Context not supported on this browser");const r=n.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,a=i.createMediaStreamSource(new MediaStream([r])),s=i.createAnalyser();s.minDecibels=n.minDecibels,s.maxDecibels=n.maxDecibels,s.fftSize=n.fftSize,s.smoothingTimeConstant=n.smoothingTimeConstant,a.connect(s);const o=new Uint8Array(s.frequencyBinCount);return{calculateVolume:()=>{s.getByteFrequencyData(o);let e=0;for(const t of o)e+=Math.pow(t/255,2);return Math.sqrt(e/o.length)},analyser:s,cleanup:()=>pr(this,void 0,void 0,(function*(){yield i.close(),n.cloneTrack&&r.stop()}))}},e.createE2EEKey=function(){return window.crypto.getRandomValues(new Uint8Array(32))},e.createKeyMaterialFromBuffer=ec,e.createKeyMaterialFromString=$o,e.createLocalAudioTrack=Yu,e.createLocalScreenTracks=function(e){return pr(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0!==e.resolution||eo()||(e.resolution=bs.h1080fps30.resolution),void 0===navigator.mediaDevices.getDisplayMedia)throw new Ga("getDisplayMedia not supported");const t=Is(e),n=yield navigator.mediaDevices.getDisplayMedia(t),i=n.getVideoTracks();if(0===i.length)throw new Ja("no video track found");const r=new hl(i[0],void 0,!1);r.source=xs.Source.ScreenShare;const a=[r];if(n.getAudioTracks().length>0){const e=new $d(n.getAudioTracks()[0],void 0,!1);e.source=xs.Source.ScreenShareAudio,a.push(e)}return a}))},e.createLocalTracks=Ju,e.createLocalVideoTrack=Qu,e.decodeTokenPayload=Ih,e.deriveKeys=function(e,t){return pr(this,void 0,void 0,(function*(){const n=tc(e.algorithm.name,t.ratchetSalt),i=yield crypto.subtle.deriveKey(n,e,{name:Ho,length:t.keySize},!1,["encrypt","decrypt"]);return{material:e,encryptionKey:i}}))},e.detachTrack=Fs,e.facingModeFromDeviceLabel=Bh,e.facingModeFromLocalTrack=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;const i=Io(e)?e.mediaStreamTrack:e,r=i.getSettings();let a={facingMode:null!==(n=t.defaultFacingMode)&&void 0!==n?n:"user",confidence:"low"};if("facingMode"in r){const e=r.facingMode;ar.trace("rawFacingMode",{rawFacingMode:e}),e&&"string"==typeof e&&function(e){const t=["user","environment","left","right"];return void 0===e||t.includes(e)}(e)&&(a={facingMode:e,confidence:"high"})}if(["low","medium"].includes(a.confidence)){ar.trace("Try to get facing mode from device label: (".concat(i.label,")"));const e=Bh(i.label);void 0!==e&&(a=e)}return a},e.getBrowser=Oa,e.getEmptyAudioStreamTrack=bo,e.getEmptyVideoStreamTrack=function(){return fo||(fo=yo()),fo.clone()},e.getLogger=or,e.importKey=function(e){return pr(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:Ho},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return function*(){return crypto.subtle.importKey("raw",e,t,!1,"derive"===n?["deriveBits","deriveKey"]:["encrypt","decrypt"])}()}))},e.isAudioCodec=function(e){return us.includes(e)},e.isAudioTrack=_o,e.isBackupCodec=gs,e.isBackupVideoCodec=ms,e.isBrowserSupported=Qs,e.isE2EESupported=Yo,e.isInsertableStreamSupported=Zo,e.isLocalParticipant=xo,e.isLocalTrack=Io,e.isRemoteParticipant=function(e){return!e.isLocal},e.isRemoteTrack=Ao,e.isSVCCodec=zs,e.isScriptTransformSupported=Xo,e.isSerializer=function(e){return"object"==typeof e&&null!==e&&"symbol"in e&&e.symbol===jh},e.isVideoCodec=So,e.isVideoFrame=function(e){return"type"in e},e.isVideoTrack=Mo,e.needsRbspUnescaping=function(e){for(var t=0;t<e.length-3;t++)if(0==e[t]&&0==e[t+1]&&3==e[t+2])return!0;return!1},e.parseRbsp=function(e){const t=[];for(var n=e.length,i=0;i<e.length;)n-i>=3&&!e[i]&&!e[i+1]&&3==e[i+2]?(t.push(e[i++]),t.push(e[i++]),i++):t.push(e[i++]);return new Uint8Array(t)},e.protocolVersion=17,e.ratchet=function(e,t){return pr(this,void 0,void 0,(function*(){const n=tc(e.algorithm.name,t);return crypto.subtle.deriveBits(n,e,256)}))},e.serializers=Vh,e.setLogExtension=function(t,n){(n?[n]:sr).forEach((n=>{const i=n.methodFactory;n.methodFactory=(n,r,a)=>{const s=i(n,r,a),o=e.LogLevel[n],c=o>=r&&o<e.LogLevel.silent;return(e,n)=>{n?s(e,n):s(e),c&&t(o,e,n)}},n.setLevel(n.getLevel())}))},e.setLogLevel=function(e,t){if(t)rr.getLogger(t).setLevel(e);else for(const n of sr)n.setLevel(e)},e.supportsAV1=Hs,e.supportsAdaptiveStream=function(){return"undefined"!=typeof ResizeObserver&&"undefined"!=typeof IntersectionObserver},e.supportsAudioOutputSelection=function(){return Js()},e.supportsDynacast=function(){return Vs()},e.supportsH265=function(){if(!("getCapabilities"in RTCRtpSender))return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const n of e.codecs)if("video/h265"===n.mimeType.toLowerCase()){t=!0;break}return t},e.supportsVP9=Ks,e.version=xa,e.videoCodecs=ps,e.writeRbsp=function(e){const t=[];for(var n=0,i=0;i<e.length;++i){var r=e[i];r<=3&&n>=2&&(t.push(3),n=0),t.push(r),0==r?++n:n=0}return new Uint8Array(t)}}));
|
|
2
2
|
//# sourceMappingURL=livekit-client.umd.js.map
|