livekit-client 2.19.0 → 2.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,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 a(e,t){if(!e)throw new Error(t)}const s=34028234663852886e22,o=-34028234663852886e22,c=4294967295,d=2147483647,l=-2147483648;function u(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>d||e<l)throw new Error("invalid int 32: "+e)}function h(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>c||e<0)throw new Error("invalid uint 32: "+e)}function p(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>s||e<o))throw new Error("invalid float 32: "+e)}const m=Symbol("@bufbuild/protobuf/enum-type");function g(e){const t=e[m];return a(t,"missing enum type on enum object"),t}function v(e,t,n,i){e[m]=f(t,n.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function f(e,t,n){const i=Object.create(null),r=Object.create(null),a=[];for(const e of t){const t=y(e);a.push(t),i[e.name]=t,r[e.no]=t}return{typeName:e,values:a,findName:e=>i[e],findNumber:e=>r[e]}}function k(e,t,n){const i={};for(const e of t){const t=y(e);i[t.localName]=t.no,i[t.no]=t.localName}return v(i,e,t),i}function y(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class b{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 n;try{n=JSON.parse(e)}catch(e){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(n,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 T(){let e=0,t=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(e|=(127&i)<<n,0==(128&i))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(15&n)<<28,t=(112&n)>>4,0==(128&n))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(t|=(127&i)<<n,0==(128&i))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function S(e,t,n){for(let i=0;i<28;i+=7){const r=e>>>i,a=!(r>>>7==0&&0==t),s=255&(a?128|r:r);if(n.push(s),!a)return}const i=e>>>28&15|(7&t)<<4,r=!(t>>3==0);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 E=4294967296;function C(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>=E&&(r+=i/E|0,i%=E)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?P(i,r):R(i,r)}function w(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(E*t+e);const n=16777215&(e>>>24|t<<8),i=t>>16&65535;let r=(16777215&e)+6777216*n+6710656*i,a=n+8147497*i,s=2*i;const o=1e7;return r>=o&&(a+=Math.floor(r/o),r%=o),a>=o&&(s+=Math.floor(a/o),a%=o),s.toString()+I(a)+I(r)}function R(e,t){return{lo:0|e,hi:0|t}}function P(e,t){return t=~t,e?e=1+~e:t+=1,R(e,t)}const I=e=>{const t=String(e);return"0000000".slice(t.length)+t};function D(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 M(){let e=this.buf[this.pos++],t=127&e;if(0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,0==(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;0!=(128&e)&&t<10;t++)e=this.buf[this.pos++];if(0!=(128&e))throw new Error("invalid varint");return this.assertBounds(),t>>>0}const _=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),C(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),n(e),C(e)),dec:(e,t)=>function(e,t){let n=R(e,t);const i=2147483648&n.hi;i&&(n=P(n.lo,n.hi));const r=w(n.lo,n.hi);return i?"-"+r:r}(e,t),uDec:(e,t)=>w(e,t)}}();var O,A,N;function x(e,t,n){if(t===n)return!0;if(e==O.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 O.UINT64:case O.FIXED64:case O.INT64:case O.SFIXED64:case O.SINT64:return t==n}return!1}function L(e,t){switch(e){case O.BOOL:return!1;case O.UINT64:case O.FIXED64:case O.INT64:case O.SFIXED64:case O.SINT64:return 0==t?_.zero:"0";case O.DOUBLE:case O.FLOAT:return 0;case O.BYTES:return new Uint8Array(0);case O.STRING:return"";default:return 0}}function U(e,t){switch(e){case O.BOOL:return!1===t;case O.STRING:return""===t;case O.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}!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"}(O||(O={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(A||(A={})),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"}(N||(N={}));class F{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 t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw 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(h(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return u(e),D(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){p(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){h(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){u(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return u(e),D(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=_.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=_.uEnc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}int64(e){let t=_.enc(e);return S(t.lo,t.hi,this.buf),this}sint64(e){let t=_.enc(e),n=t.hi>>31;return S(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=_.uEnc(e);return S(t.lo,t.hi,this.buf),this}}class B{constructor(e,t){this.varint64=T,this.uint32=M,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 N.Varint:for(;128&this.buf[this.pos++];);break;case N.Bit64:this.pos+=4;case N.Bit32:this.pos+=4;break;case N.LengthDelimited:let n=this.uint32();this.pos+=n;break;case N.StartGroup:for(;;){const[e,n]=this.tag();if(n===N.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(n,e)}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 _.dec(...this.varint64())}uint64(){return _.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(1&e);return e=(e>>>1|(1&t)<<31)^n,t=t>>>1^n,_.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return _.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return _.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 j(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 L(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 q="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),V=[];for(let e=0;e<q.length;e++)V[q[e].charCodeAt(0)]=e;V["-".charCodeAt(0)]=q.indexOf("+"),V["_".charCodeAt(0)]=q.indexOf("/");const H={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 t=0;t<e.length;t++){if(n=V[e.charCodeAt(t)],void 0===n)switch(e[t]){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+=q[t>>2],r=(3&t)<<4,i=1;break;case 1:n+=q[r|t>>4],r=(15&t)<<2,i=2;break;case 2:n+=q[r|t>>6],n+=q[63&t],i=0}return i&&(n+=q[r],n+="=",1==i&&(n+="=")),n}};function W(e,t,n){J(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,s]=j(t);for(const e of r)t.runtime.bin.readField(a,i.readerFactory(e.data),t.field,e.wireType,i);return s()}function K(e,t,n,i){J(t,e);const r=t.runtime.bin.makeReadOptions(i),a=t.runtime.bin.makeWriteOptions(i);if(z(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,n]=c.tag(),i=c.skip(n,t);e.getType().runtime.bin.onUnknownField(e,t,n,i)}}function z(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 J(e,t){a(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function G(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:!U(e.T,t[n]);case"message":return void 0!==t[n];case"map":return Object.keys(t[n]).length>0}}function Q(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?L(e.T,e.L):void 0;break;case"message":t[n]=void 0}}function Y(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(b.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 X(e,t){return Y(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}O.DOUBLE,O.FLOAT,O.INT64,O.UINT64,O.INT32,O.UINT32,O.BOOL,O.STRING,O.BYTES;const Z={ignoreUnknownFields:!1},$={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function ee(e){return e?Object.assign(Object.assign({},Z),e):Z}function te(e){return e?Object.assign(Object.assign({},$),e):$}const ne=Symbol(),ie=Symbol();function re(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 ae(e,t,n,i,r){let s=n.localName;if(n.repeated){if(a("map"!=n.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(re(t)));const o=e[s];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(re(e)));switch(n.kind){case"message":o.push(n.T.fromJson(e,i));break;case"enum":const t=ce(n.T,e,i.ignoreUnknownFields,!0);t!==ie&&o.push(t);break;case"scalar":try{o.push(oe(n.T,e,n.L,!0))}catch(t){let i="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(re(e));throw t instanceof Error&&t.message.length>0&&(i+=": ".concat(t.message)),new Error(i)}}}}else if("map"==n.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(re(t)));const a=e[s];for(const[e,s]of Object.entries(t)){if(null===s)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: map value null"));let o;try{o=se(n.K,e)}catch(e){let i="cannot decode map key for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(re(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}switch(n.V.kind){case"message":a[o]=n.V.T.fromJson(s,i);break;case"enum":const e=ce(n.V.T,s,i.ignoreUnknownFields,!0);e!==ie&&(a[o]=e);break;case"scalar":try{a[o]=oe(n.V.T,s,A.BIGINT,!0)}catch(e){let i="cannot decode map value for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(re(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:s},s="value"),n.kind){case"message":const a=n.T;if(null===t&&"google.protobuf.Value"!=a.typeName)return;let o=e[s];Y(o)?o.fromJson(t,i):(e[s]=o=a.fromJson(t,i),a.fieldWrapper&&!n.oneof&&(e[s]=a.fieldWrapper.unwrapField(o)));break;case"enum":const c=ce(n.T,t,i.ignoreUnknownFields,!1);switch(c){case ne:Q(n,e);break;case ie:break;default:e[s]=c}break;case"scalar":try{const i=oe(n.T,t,n.L,!1);if(i===ne)Q(n,e);else e[s]=i}catch(e){let i="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(re(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}function se(e,t){if(e===O.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return oe(e,t,A.BIGINT,!0).toString()}function oe(e,t,n,i){if(null===t)return i?L(e,n):ne;switch(e){case O.DOUBLE:case O.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 i=Number(t);if(Number.isNaN(i))break;if(!Number.isFinite(i))break;return e==O.FLOAT&&p(i),i;case O.INT32:case O.FIXED32:case O.SFIXED32:case O.SINT32:case O.UINT32:let r;if("number"==typeof t?r=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(r=Number(t)),void 0===r)break;return e==O.UINT32||e==O.FIXED32?h(r):u(r),r;case O.INT64:case O.SFIXED64:case O.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const a=_.parse(t);return n?a.toString():a;case O.FIXED64:case O.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const s=_.uParse(t);return n?s.toString():s;case O.BOOL:if("boolean"!=typeof t)break;return t;case O.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case O.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return H.dec(t)}throw new Error}function ce(e,t,n,i){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:i?e.values[0].no:ne;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 ie}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(re(t)))}function de(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function le(e,t,n){if("map"==e.kind){a("object"==typeof t&&null!=t);const i={},r=Object.entries(t);switch(e.V.kind){case"scalar":for(const[t,n]of r)i[t.toString()]=he(e.V.T,n);break;case"message":for(const[e,t]of r)i[e.toString()]=t.toJson(n);break;case"enum":const t=e.V.T;for(const[e,a]of r)i[e.toString()]=ue(t,a,n.enumAsInteger)}return n.emitDefaultValues||r.length>0?i: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(he(e.T,t[n]));break;case"enum":for(let r=0;r<t.length;r++)i.push(ue(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 he(e.T,t);case"enum":return ue(e.T,t,n.enumAsInteger);case"message":return X(e.T,t).toJson(n)}}function ue(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 he(e,t){switch(e){case O.INT32:case O.SFIXED32:case O.SINT32:case O.FIXED32:case O.UINT32:return a("number"==typeof t),t;case O.FLOAT:case O.DOUBLE:return a("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case O.STRING:return a("string"==typeof t),t;case O.BOOL:return a("boolean"==typeof t),t;case O.UINT64:case O.FIXED64:case O.INT64:case O.SFIXED64:case O.SINT64:return a("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case O.BYTES:return a(t instanceof Uint8Array),H.enc(t)}}const pe=Symbol("@bufbuild/protobuf/unknown-fields"),me={readUnknownFields:!0,readerFactory:e=>new B(e)},ge={writeUnknownFields:!0,writerFactory:()=>new F};function ve(e){return e?Object.assign(Object.assign({},me),e):me}function fe(e){return e?Object.assign(Object.assign({},ge),e):ge}function ke(e,t,n,i,r){let{repeated:a,localName:s}=n;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?O.INT32:n.T;let c=Te;if("scalar"==n.kind&&n.L>0&&(c=be),a){let n=e[s];if(i==N.LengthDelimited&&o!=O.STRING&&o!=O.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(ye(t,new d,r,n)):Y(e[s])?ye(t,e[s],r,n):(e[s]=ye(t,new d,r,n),!d.fieldWrapper||n.oneof||n.repeated||(e[s]=d.fieldWrapper.unwrapField(e[s])));break;case"map":let[l,u]=function(e,t,n){const i=t.uint32(),r=t.pos+i;let a,s;for(;t.pos<r;){const[i]=t.tag();switch(i){case 1:a=Te(t,e.K);break;case 2:switch(e.V.kind){case"scalar":s=Te(t,e.V.T);break;case"enum":s=t.int32();break;case"message":s=ye(t,new e.V.T,n,void 0)}}}void 0===a&&(a=L(e.K,A.BIGINT));"string"!=typeof a&&"number"!=typeof a&&(a=a.toString());if(void 0===s)switch(e.V.kind){case"scalar":s=L(e.V.T,A.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);e[s][l]=u}}function ye(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 be(e,t){const n=Te(e,t);return"bigint"==typeof n?n.toString():n}function Te(e,t){switch(t){case O.STRING:return e.string();case O.BOOL:return e.bool();case O.DOUBLE:return e.double();case O.FLOAT:return e.float();case O.INT32:return e.int32();case O.INT64:return e.int64();case O.UINT64:return e.uint64();case O.FIXED64:return e.fixed64();case O.BYTES:return e.bytes();case O.FIXED32:return e.fixed32();case O.SFIXED32:return e.sfixed32();case O.SFIXED64:return e.sfixed64();case O.SINT64:return e.sint64();case O.UINT32:return e.uint32();case O.SINT32:return e.sint32()}}function Se(e,t,n,i){a(void 0!==t);const r=e.repeated;switch(e.kind){case"scalar":case"enum":let s="enum"==e.kind?O.INT32:e.T;if(r)if(a(Array.isArray(t)),e.packed)!function(e,t,n,i){if(!i.length)return;e.tag(n,N.LengthDelimited).fork();let[,r]=Re(t);for(let t=0;t<i.length;t++)e[r](i[t]);e.join()}(n,s,e.no,t);else for(const i of t)we(n,s,e.no,i);else we(n,s,e.no,t);break;case"message":if(r){a(Array.isArray(t));for(const r of t)Ce(n,i,e,r)}else Ce(n,i,e,t);break;case"map":a("object"==typeof t&&null!=t);for(const[r,a]of Object.entries(t))Ee(n,i,e,r,a)}}function Ee(e,t,n,i,r){e.tag(n.no,N.LengthDelimited),e.fork();let s=i;switch(n.K){case O.INT32:case O.FIXED32:case O.UINT32:case O.SFIXED32:case O.SINT32:s=Number.parseInt(i);break;case O.BOOL:a("true"==i||"false"==i),s="true"==i}switch(we(e,n.K,1,s),n.V.kind){case"scalar":we(e,n.V.T,2,r);break;case"enum":we(e,O.INT32,2,r);break;case"message":a(void 0!==r),e.tag(2,N.LengthDelimited).bytes(r.toBinary(t))}e.join()}function Ce(e,t,n,i){const r=X(n.T,i);n.delimited?e.tag(n.no,N.StartGroup).raw(r.toBinary(t)).tag(n.no,N.EndGroup):e.tag(n.no,N.LengthDelimited).bytes(r.toBinary(t))}function we(e,t,n,i){a(void 0!==i);let[r,s]=Re(t);e.tag(n,r)[s](i)}function Re(e){let t=N.Varint;switch(e){case O.BYTES:case O.STRING:t=N.LengthDelimited;break;case O.DOUBLE:case O.FIXED64:case O.SFIXED64:t=N.Bit64;break;case O.FIXED32:case O.SFIXED32:case O.FLOAT:t=N.Bit32}return[t,O[e].toLowerCase()]}function Pe(e){if(void 0===e)return e;if(Y(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Ie(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class De{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 Me(e,t){const n=Oe(e);return t?n:Ue(Le(n))}const _e=Oe;function Oe(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 Ae=new Set(["constructor","toString","toJSON","valueOf"]),Ne=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),xe=e=>"".concat(e,"$"),Le=e=>Ne.has(e)?xe(e):e,Ue=e=>Ae.has(e)?xe(e):e;class Fe{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=Me(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 Be=(je=e=>new De(e,(e=>function(e,t){var n,i,r,a,s,o;const c=[];let d;for(const t of"function"==typeof e?e():e){const e=t;if(e.localName=Me(t.name,void 0!==t.oneof),e.jsonName=null!==(n=t.jsonName)&&void 0!==n?n:_e(t.name),e.repeated=null!==(i=t.repeated)&&void 0!==i&&i,"scalar"==t.kind&&(e.L=null!==(r=t.L)&&void 0!==r?r:A.BIGINT),e.delimited=null!==(a=t.delimited)&&void 0!==a&&a,e.req=null!==(s=t.req)&&void 0!==s&&s,e.opt=null!==(o=t.opt)&&void 0!==o&&o,void 0===t.packed&&(e.packed="enum"==t.kind||"scalar"==t.kind&&t.T!=O.BYTES&&t.T!=O.STRING),void 0!==t.oneof){const n="string"==typeof t.oneof?t.oneof:t.oneof.name;d&&d.name==n||(d=new Fe(n)),e.oneof=d,d.addField(e)}c.push(e)}return c}(e))),qe=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]=L(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:ee,makeWriteOptions:te,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(re(t)));i=null!=i?i:new e;const r=new Map,a=n.typeRegistry;for(const[s,o]of Object.entries(t)){const t=e.fields.findJsonName(s);if(t){if(t.oneof){if(null===o&&"scalar"==t.kind)continue;const n=r.get(t.oneof);if(void 0!==n)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(n,'", "').concat(s,'"'));r.set(t.oneof,s)}ae(i,o,t,n,e)}else{let t=!1;if((null==a?void 0:a.findExtension)&&s.startsWith("[")&&s.endsWith("]")){const r=a.findExtension(s.substring(1,s.length-1));if(r&&r.extendee.typeName==e.typeName){t=!0;const[e,a]=j(r);ae(e,o,r.field,n,r),K(i,r,a(),n)}}if(!t&&!n.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(s,'" is unknown'))}}return i},writeMessage(e,t){const n=e.getType(),i={};let r;try{for(r of n.fields.byNumber()){if(!G(r,e)){if(r.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!de(r))continue}const n=le(r,r.oneof?e[r.oneof.localName].value:e[r.localName],t);void 0!==n&&(i[t.useProtoFieldName?r.name:r.jsonName]=n)}const a=t.typeRegistry;if(null==a?void 0:a.findExtensionFor)for(const r of n.runtime.bin.listUnknownFields(e)){const s=a.findExtensionFor(n.typeName,r.no);if(s&&z(e,s)){const n=W(e,s,t),r=le(s.field,n,t);void 0!==r&&(i[s.field.jsonName]=r)}}}catch(e){const t=r?"cannot encode field ".concat(n.typeName,".").concat(r.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),i=e instanceof Error?e.message:String(e);throw new Error(t+(i.length>0?": ".concat(i):""))}return i},readScalar:(e,t,n)=>oe(e,t,null!=n?n:A.BIGINT,!0),writeScalar(e,t,n){if(void 0!==t)return n||U(e,t)?he(e,t):void 0},debug:re},bin:{makeReadOptions:ve,makeWriteOptions:fe,listUnknownFields(e){var t;return null!==(t=e[pe])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[pe]},writeUnknownFields(e,t){const n=e[pe];if(n)for(const e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,i){const r=e;Array.isArray(r[pe])||(r[pe]=[]),r[pe].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&&([o,c]=t.tag(),!0!==r||c!=N.EndGroup);){const n=a.fields.find(o);if(n)ke(e,t,n,c,i);else{const n=t.skip(c,o);i.readUnknownFields&&this.onUnknownField(e,o,c,n)}}if(r&&(c!=N.EndGroup||o!==n))throw new Error("invalid end group tag")},readField:ke,writeMessage(e,t,n){const i=e.getType();for(const r of i.fields.byNumber())if(G(r,e))Se(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&&Se(e,t,n,i)}},util:Object.assign(Object.assign({},{setEnumType:v,initPartial(e,t){if(void 0===e)return;const n=t.getType();for(const i of n.fields.byMember()){const n=i.localName,r=t,a=e;if(null!=a[n])switch(i.kind){case"oneof":const e=a[n].case;if(void 0===e)continue;const t=i.findField(e);let s=a[n].value;t&&"message"==t.kind&&!Y(s,t.T)?s=new t.T(s):t&&"scalar"===t.kind&&t.T===O.BYTES&&(s=Ie(s)),r[n]={case:e,value:s};break;case"scalar":case"enum":let o=a[n];i.T===O.BYTES&&(o=i.repeated?o.map(Ie):Ie(o)),r[n]=o;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===O.BYTES)for(const[e,t]of Object.entries(a[n]))r[n][e]=Ie(t);else Object.assign(r[n],a[n]);break;case"message":const e=i.V.T;for(const t of Object.keys(a[n])){let i=a[n][t];e.fieldWrapper||(i=new e(i)),r[n][t]=i}}break;case"message":const c=i.T;if(i.repeated)r[n]=a[n].map((e=>Y(e,c)?e:new c(e)));else{const e=a[n];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?r[n]=Ie(e):r[n]=e:r[n]=Y(e,c)?e:new c(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)=>x(e.T,t,r[n])));case"enum":return i.every(((e,t)=>x(O.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||Y(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===n||Y(n)||(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case"enum":return x(O.INT32,i,r);case"scalar":return x(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 x(O.INT32,i.value,r.value);case"scalar":return x(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=>x(O.INT32,i[e],r[e])));case"scalar":const n=e.V.T;return s.every((e=>x(n,i[e],r[e])))}}})),clone(e){const t=e.getType(),n=new t,i=n;for(const n of t.fields.byMember()){const t=e[n.localName];let r;if(n.repeated)r=t.map(Pe);else if("map"==n.kind){r=i[n.localName];for(const[e,n]of Object.entries(t))r[e]=Pe(n)}else r="oneof"==n.kind?n.findField(t.case)?{case:t.case,value:Pe(t.value)}:{case:void 0}:Pe(t);i[n.localName]=r}for(const n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(i,n.no,n.wireType,n.data);return n}}),{newFieldList:je,initFields:qe}),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 b),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:k,makeEnumType:f,getEnumType:g,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 je,qe;class Ve extends b{constructor(e){super(),this.seconds=_.zero,this.nanos=0,Be.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(Be.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=_.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 Ve.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new Ve({seconds:_.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new Ve).fromBinary(e,t)}static fromJson(e,t){return(new Ve).fromJson(e,t)}static fromJsonString(e,t){return(new Ve).fromJsonString(e,t)}static equals(e,t){return Be.util.equals(Ve,e,t)}}Ve.runtime=Be,Ve.typeName="google.protobuf.Timestamp",Ve.fields=Be.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const He=Be.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ve},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:We,repeated:!0},{no:5,name:"events",kind:"message",T:ze,repeated:!0}])),We=Be.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:Ke,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),Ke=Be.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ve},{no:3,name:"value",kind:"scalar",T:2}])),ze=Be.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:Ve},{no:7,name:"normalized_end_timestamp",kind:"message",T:Ve,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),Je=Be.makeEnum("livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"},{no:3,name:"AC_MP3"}]),Ge=Be.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"}]),Qe=Be.makeEnum("livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]),Ye=Be.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Xe=Be.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Ze=Be.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"}]),$e=Be.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),et=Be.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),tt=Be.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),nt=Be.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"}]),it=Be.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"}]),rt=Be.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),at=Be.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"}]),st=Be.makeEnum("livekit.PacketTrailerFeature",[{no:0,name:"PTF_USER_TIMESTAMP"},{no:1,name:"PTF_FRAME_ID"}]),ot=Be.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:ct,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:Kt}])),ct=Be.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),dt=Be.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:Be.getEnumType(Ze),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}])),lt=Be.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:Be.getEnumType(ut)},{no:4,name:"tracks",kind:"message",T:vt,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:dt},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:Be.getEnumType(ht)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:Be.getEnumType(nt)},{no:18,name:"kind_details",kind:"enum",T:Be.getEnumType(pt),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:ft,repeated:!0},{no:20,name:"client_protocol",kind:"scalar",T:5}])),ut=Be.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),ht=Be.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"}]),pt=Be.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"}]),mt=Be.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),gt=Be.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:yt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:Be.getEnumType(bt)},{no:6,name:"sdp_cid",kind:"scalar",T:9}])),vt=Be.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:Be.getEnumType(Xe)},{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:Be.getEnumType(Ze)},{no:10,name:"layers",kind:"message",T:yt,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:gt,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:Be.getEnumType(mt)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Kt},{no:19,name:"audio_features",kind:"enum",T:Be.getEnumType(at),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:Be.getEnumType(Ye)},{no:21,name:"packet_trailer_features",kind:"enum",T:Be.getEnumType(st),repeated:!0}])),ft=Be.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:Be.getEnumType(mt)}])),kt=Be.makeMessageType("livekit.DataTrackSubscriptionOptions",(()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}])),yt=Be.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:Be.getEnumType($e)},{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}])),bt=Be.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"}]),Tt=Be.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:Be.getEnumType(St)},{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:Pt,oneof:"value"},{no:3,name:"speaker",kind:"message",T:wt,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:It,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Dt,oneof:"value"},{no:8,name:"metrics",kind:"message",T:He,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:_t,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Ot,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:At,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Nt,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Qt,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Yt,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Xt,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:Et,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}])),St=Be.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Et=Be.makeMessageType("livekit.EncryptedPacket",(()=>[{no:1,name:"encryption_type",kind:"enum",T:Be.getEnumType(mt)},{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}])),Ct=Be.makeMessageType("livekit.EncryptedPacketPayload",(()=>[{no:1,name:"user",kind:"message",T:Pt,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:_t,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:Ot,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:At,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:Nt,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:Qt,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:Yt,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:Xt,oneof:"value"}])),wt=Be.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:Rt,repeated:!0}])),Rt=Be.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}])),Pt=Be.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}])),It=Be.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),Dt=Be.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:Mt,repeated:!0}])),Mt=Be.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}])),_t=Be.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}])),Ot=Be.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}])),At=Be.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),Nt=Be.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:xt,oneof:"value"},{no:4,name:"compressed_payload",kind:"scalar",T:12,oneof:"value"}])),xt=Be.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}])),Lt=Be.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),Ut=Be.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:Be.getEnumType(Ft)},{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}])),Ft=Be.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Bt=Be.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:Be.getEnumType(jt)},{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:Be.getEnumType(qt),repeated:!0}])),jt=Be.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"}]),qt=Be.makeEnum("livekit.ClientInfo.Capability",[{no:0,name:"CAP_UNUSED"},{no:1,name:"CAP_PACKET_TRAILER"}]),Vt=Be.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:Ht},{no:2,name:"screen",kind:"message",T:Ht},{no:3,name:"resume_connection",kind:"enum",T:Be.getEnumType(tt)},{no:4,name:"disabled_codecs",kind:"message",T:Wt},{no:5,name:"force_relay",kind:"enum",T:Be.getEnumType(tt)}])),Ht=Be.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:Be.getEnumType(tt)}])),Wt=Be.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:ct,repeated:!0},{no:2,name:"publish",kind:"message",T:ct,repeated:!0}])),Kt=Be.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),zt=Be.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Jt=Be.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:Be.getEnumType(zt)},{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"}),Gt=Be.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),Qt=Be.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:Be.getEnumType(mt)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Jt,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Gt,oneof:"content_header"}]),{localName:"DataStream_Header"}),Yt=Be.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"}),Xt=Be.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"}),Zt=Be.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}])),$t=Be.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:Zt}])),en=Be.makeMessageType("livekit.SubscribedAudioCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}])),tn=Be.makeEnum("livekit.JobRestartPolicy",[{no:0,name:"JRP_ON_FAILURE"},{no:1,name:"JRP_NEVER"}]),nn=Be.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:Be.getEnumType(tn)},{no:4,name:"deployment",kind:"scalar",T:9}])),rn=Be.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"}]),an=Be.makeEnum("livekit.EncodedFileType",[{no:0,name:"DEFAULT_FILETYPE"},{no:1,name:"MP4"},{no:2,name:"OGG"},{no:3,name:"MP3"}]),sn=Be.makeEnum("livekit.StreamProtocol",[{no:0,name:"DEFAULT_PROTOCOL"},{no:1,name:"RTMP"},{no:2,name:"SRT"},{no:3,name:"WEBSOCKET"}]),on=Be.makeEnum("livekit.SegmentedFileProtocol",[{no:0,name:"DEFAULT_SEGMENTED_FILE_PROTOCOL"},{no:1,name:"HLS_PROTOCOL"}]),cn=Be.makeEnum("livekit.SegmentedFileSuffix",[{no:0,name:"INDEX"},{no:1,name:"TIMESTAMP"}]),dn=Be.makeEnum("livekit.ImageFileSuffix",[{no:0,name:"IMAGE_SUFFIX_INDEX"},{no:1,name:"IMAGE_SUFFIX_TIMESTAMP"},{no:2,name:"IMAGE_SUFFIX_NONE_OVERWRITE"}]),ln=Be.makeEnum("livekit.AudioMixing",[{no:0,name:"DEFAULT_MIXING"},{no:1,name:"DUAL_CHANNEL_AGENT"},{no:2,name:"DUAL_CHANNEL_ALTERNATE"}]),un=Be.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:Be.getEnumType(Je)},{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:Be.getEnumType(Ge)},{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}])),hn=Be.makeMessageType("livekit.StreamOutput",(()=>[{no:1,name:"protocol",kind:"enum",T:Be.getEnumType(sn)},{no:2,name:"urls",kind:"scalar",T:9,repeated:!0}])),pn=Be.makeMessageType("livekit.SegmentedFileOutput",(()=>[{no:1,name:"protocol",kind:"enum",T:Be.getEnumType(on)},{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:Be.getEnumType(cn)},{no:8,name:"disable_manifest",kind:"scalar",T:8},{no:5,name:"s3",kind:"message",T:gn,oneof:"output"},{no:6,name:"gcp",kind:"message",T:vn,oneof:"output"},{no:7,name:"azure",kind:"message",T:fn,oneof:"output"},{no:9,name:"aliOSS",kind:"message",T:kn,oneof:"output"}])),mn=Be.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:Be.getEnumType(dn)},{no:6,name:"image_codec",kind:"enum",T:Be.getEnumType(Qe)},{no:7,name:"disable_manifest",kind:"scalar",T:8},{no:8,name:"s3",kind:"message",T:gn,oneof:"output"},{no:9,name:"gcp",kind:"message",T:vn,oneof:"output"},{no:10,name:"azure",kind:"message",T:fn,oneof:"output"},{no:11,name:"aliOSS",kind:"message",T:kn,oneof:"output"}])),gn=Be.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:yn}])),vn=Be.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:yn}])),fn=Be.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}])),kn=Be.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}])),yn=Be.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}])),bn=Be.makeMessageType("livekit.AutoParticipantEgress",(()=>[{no:1,name:"preset",kind:"enum",T:Be.getEnumType(rn),oneof:"options"},{no:2,name:"advanced",kind:"message",T:un,oneof:"options"},{no:3,name:"file_outputs",kind:"message",T:En,repeated:!0},{no:4,name:"segment_outputs",kind:"message",T:pn,repeated:!0}])),Tn=Be.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:gn,oneof:"output"},{no:3,name:"gcp",kind:"message",T:vn,oneof:"output"},{no:4,name:"azure",kind:"message",T:fn,oneof:"output"},{no:6,name:"aliOSS",kind:"message",T:kn,oneof:"output"}])),Sn=Be.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:Be.getEnumType(ln)},{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:En,oneof:"output"},{no:7,name:"stream",kind:"message",T:hn,oneof:"output"},{no:10,name:"segments",kind:"message",T:pn,oneof:"output"},{no:8,name:"preset",kind:"enum",T:Be.getEnumType(rn),oneof:"options"},{no:9,name:"advanced",kind:"message",T:un,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:En,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:hn,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:pn,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:mn,repeated:!0},{no:16,name:"webhooks",kind:"message",T:$t,repeated:!0}])),En=Be.makeMessageType("livekit.EncodedFileOutput",(()=>[{no:1,name:"file_type",kind:"enum",T:Be.getEnumType(an)},{no:2,name:"filepath",kind:"scalar",T:9},{no:6,name:"disable_manifest",kind:"scalar",T:8},{no:3,name:"s3",kind:"message",T:gn,oneof:"output"},{no:4,name:"gcp",kind:"message",T:vn,oneof:"output"},{no:5,name:"azure",kind:"message",T:fn,oneof:"output"},{no:7,name:"aliOSS",kind:"message",T:kn,oneof:"output"}])),Cn=Be.makeMessageType("livekit.RoomEgress",(()=>[{no:1,name:"room",kind:"message",T:Sn},{no:3,name:"participant",kind:"message",T:bn},{no:2,name:"tracks",kind:"message",T:Tn}])),wn=Be.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:Cn},{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:nn,repeated:!0},{no:12,name:"tags",kind:"map",K:9,V:{kind:"scalar",T:9}}])),Rn=Be.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Pn=Be.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),In=Be.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Dn=Be.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:Kn,oneof:"message"},{no:2,name:"answer",kind:"message",T:Kn,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Bn,oneof:"message"},{no:4,name:"add_track",kind:"message",T:On,oneof:"message"},{no:5,name:"mute",kind:"message",T:jn,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Jn,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Yn,oneof:"message"},{no:8,name:"leave",kind:"message",T:$n,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:ti,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:gi,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:ki,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Ti,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:ni,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Si,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Xn,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Zn,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:An,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:xn,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:Gn,oneof:"message"}])),Mn=Be.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:qn,oneof:"message"},{no:2,name:"answer",kind:"message",T:Kn,oneof:"message"},{no:3,name:"offer",kind:"message",T:Kn,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Bn,oneof:"message"},{no:5,name:"update",kind:"message",T:zn,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Hn,oneof:"message"},{no:8,name:"leave",kind:"message",T:$n,oneof:"message"},{no:9,name:"mute",kind:"message",T:jn,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:ri,oneof:"message"},{no:11,name:"room_update",kind:"message",T:ai,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:oi,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:di,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:hi,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:vi,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Wn,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Vn,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Ei,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Ri,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Pi,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Di,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:fi,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:Ni,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:pi,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:Nn,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:Ln,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:Un,oneof:"message"}])),_n=Be.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:yt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:Be.getEnumType(bt)}])),On=Be.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:Be.getEnumType(Xe)},{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:Be.getEnumType(Ze)},{no:9,name:"layers",kind:"message",T:yt,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:_n,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:Be.getEnumType(mt)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:Be.getEnumType(Ye)},{no:17,name:"audio_features",kind:"enum",T:Be.getEnumType(at),repeated:!0},{no:18,name:"packet_trailer_features",kind:"enum",T:Be.getEnumType(st),repeated:!0}])),An=Be.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:Be.getEnumType(mt)}])),Nn=Be.makeMessageType("livekit.PublishDataTrackResponse",(()=>[{no:1,name:"info",kind:"message",T:ft}])),xn=Be.makeMessageType("livekit.UnpublishDataTrackRequest",(()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}])),Ln=Be.makeMessageType("livekit.UnpublishDataTrackResponse",(()=>[{no:1,name:"info",kind:"message",T:ft}])),Un=Be.makeMessageType("livekit.DataTrackSubscriberHandles",(()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:Fn}}])),Fn=Be.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"}),Bn=Be.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:Be.getEnumType(Rn)},{no:3,name:"final",kind:"scalar",T:8}])),jn=Be.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),qn=Be.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:ot},{no:2,name:"participant",kind:"message",T:lt},{no:3,name:"other_participants",kind:"message",T:lt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:ii,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:Vt},{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:Ut},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:ct,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),Vn=Be.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:ii,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Vt},{no:3,name:"server_info",kind:"message",T:Ut},{no:4,name:"last_message_seq",kind:"scalar",T:13}])),Hn=Be.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:vt}])),Wn=Be.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),Kn=Be.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}}])),zn=Be.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:lt,repeated:!0}])),Jn=Be.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:Lt,repeated:!0}])),Gn=Be.makeMessageType("livekit.UpdateDataSubscription",(()=>[{no:1,name:"updates",kind:"message",T:Qn,repeated:!0}])),Qn=Be.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:kt}]),{localName:"UpdateDataSubscription_Update"}),Yn=Be.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:Be.getEnumType($e)},{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}])),Xn=Be.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:Be.getEnumType(at),repeated:!0}])),Zn=Be.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}])),$n=Be.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:Be.getEnumType(nt)},{no:3,name:"action",kind:"enum",T:Be.getEnumType(ei)},{no:4,name:"regions",kind:"message",T:Ci}])),ei=Be.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),ti=Be.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:yt,repeated:!0}])),ni=Be.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}])),ii=Be.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}])),ri=Be.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:Rt,repeated:!0}])),ai=Be.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:ot}])),si=Be.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:Be.getEnumType(et)},{no:3,name:"score",kind:"scalar",T:2}])),oi=Be.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:si,repeated:!0}])),ci=Be.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:Be.getEnumType(Pn)}])),di=Be.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:ci,repeated:!0}])),li=Be.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:Be.getEnumType($e)},{no:2,name:"enabled",kind:"scalar",T:8}])),ui=Be.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:li,repeated:!0}])),hi=Be.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:li,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:ui,repeated:!0}])),pi=Be.makeMessageType("livekit.SubscribedAudioCodecUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:en,repeated:!0}])),mi=Be.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}])),gi=Be.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:mi,repeated:!0}])),vi=Be.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}])),fi=Be.makeMessageType("livekit.RoomMovedResponse",(()=>[{no:1,name:"room",kind:"message",T:ot},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:lt},{no:4,name:"other_participants",kind:"message",T:lt,repeated:!0}])),ki=Be.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:Kn},{no:2,name:"subscription",kind:"message",T:Jn},{no:3,name:"publish_tracks",kind:"message",T:Hn,repeated:!0},{no:4,name:"data_channels",kind:"message",T:bi,repeated:!0},{no:5,name:"offer",kind:"message",T:Kn},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:yi,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:Nn,repeated:!0}])),yi=Be.makeMessageType("livekit.DataChannelReceiveState",(()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}])),bi=Be.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:Be.getEnumType(Rn)}])),Ti=Be.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:Be.getEnumType(In),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"}])),Si=Be.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),Ei=Be.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),Ci=Be.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:wi,repeated:!0}])),wi=Be.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}])),Ri=Be.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:Be.getEnumType(rt)}])),Pi=Be.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:Be.getEnumType(Ii)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:Bn,oneof:"request"},{no:5,name:"add_track",kind:"message",T:On,oneof:"request"},{no:6,name:"mute",kind:"message",T:jn,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:ni,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:Xn,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Zn,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:An,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:xn,oneof:"request"}])),Ii=Be.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"}]),Di=Be.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),Mi=Be.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}])),_i=Be.makeMessageType("livekit.JoinRequest",(()=>[{no:1,name:"client_info",kind:"message",T:Bt},{no:2,name:"connection_settings",kind:"message",T:Mi},{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:On,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:Kn},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:Be.getEnumType(it)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:ki}])),Oi=Be.makeMessageType("livekit.WrappedJoinRequest",(()=>[{no:1,name:"compression",kind:"enum",T:Be.getEnumType(Ai)},{no:2,name:"join_request",kind:"scalar",T:12}])),Ai=Be.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),Ni=Be.makeMessageType("livekit.MediaSectionsRequirement",(()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}])),xi=Be.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:wn,opt:!0}])),Li=Be.makeMessageType("livekit.TokenSourceResponse",(()=>[{no:1,name:"server_url",kind:"scalar",T:9},{no:2,name:"participant_token",kind:"scalar",T:9}]));function Ui(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Fi,Bi={exports:{}},ji=Bi.exports;var qi,Vi,Hi=(Fi||(Fi=1,function(e){var t,n;t=ji,n=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],r={},a=null;function s(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var n=this.getLevel(),r=0;r<i.length;r++){var a=i[r];this[a]=r<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 d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function l(i,r,a){return function(i){return"debug"===i&&(i="log"),typeof console!==t&&("trace"===i&&n?o:void 0!==console[i]?s(console,i):void 0!==console.log?s(console,"log"):e)}(i)||d.apply(this,arguments)}function u(e,n){var s,o,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}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(e){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=n||l,u.getLevel=function(){return null!=d?d:null!=o?o:s},u.setLevel=function(e,n){return d=m(e),!1!==n&&function(e){var n=(i[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+n+";"}catch(e){}}}(d),c.call(u)},u.setDefaultLevel=function(e){o=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(a!==u&&(s=m(a.getLevel())),c.call(u),a===u)for(var e in r)r[e].rebuild()},s=m(a?a.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(a=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=r[e];return t||(t=r[e]=new u(e,a.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=h),a},a.getLoggers=function(){return r},a.default=a,a},e.exports?e.exports=n():t.log=n()}(Bi)),Bi.exports);e.LogLevel=void 0,(qi=e.LogLevel||(e.LogLevel={}))[qi.trace=0]="trace",qi[qi.debug=1]="debug",qi[qi.info=2]="info",qi[qi.warn=3]="warn",qi[qi.error=4]="error",qi[qi.silent=5]="silent",e.LoggerNames=void 0,(Vi=e.LoggerNames||(e.LoggerNames={})).Default="livekit",Vi.Room="livekit-room",Vi.TokenSource="livekit-token-source",Vi.Participant="livekit-participant",Vi.Track="livekit-track",Vi.Publication="livekit-track-publication",Vi.Engine="livekit-engine",Vi.Signal="livekit-signal",Vi.PCManager="livekit-pc-manager",Vi.PCTransport="livekit-pc-transport",Vi.E2EE="lk-e2ee",Vi.DataTracks="livekit-data-tracks";let Wi=Hi.getLogger(e.LoggerNames.Default);const Ki=Object.values(e.LoggerNames).map((e=>Hi.getLogger(e)));function zi(e,t){const n=Hi.getLogger(e);return n.setDefaultLevel(Wi.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}Wi.setDefaultLevel(e.LogLevel.info);const Ji=Hi.getLogger(e.LoggerNames.E2EE),Gi=7e3,Qi=[0,300,1200,2700,4800,Gi,Gi,Gi,Gi,Gi];class Yi{constructor(e){this._retryDelays=void 0!==e?[...e]:Qi}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 Xi(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 Zi(e,t,n,i){return new(n||(n=Promise))((function(r,a){function s(e){try{c(i.next(e))}catch(e){a(e)}}function o(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,o)}c((i=i.apply(e,t||[])).next())}))}function $i(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 er(e){return this instanceof er?(this.v=e,this):new er(e)}function tr(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,r=n.apply(e,t||[]),a=[];return i=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",(function(e){return function(t){return Promise.resolve(t).then(e,d)}})),i[Symbol.asyncIterator]=function(){return this},i;function s(e,t){r[e]&&(i[e]=function(t){return new Promise((function(n,i){a.push([e,t,n,i])>1||o(e,t)}))},t&&(i[e]=t(i[e])))}function o(e,t){try{(n=r[e](t)).value instanceof er?Promise.resolve(n.value.v).then(c,d):l(a[0][2],n)}catch(e){l(a[0][3],e)}var n}function c(e){o("next",e)}function d(e){o("throw",e)}function l(e,t){e(t),a.shift(),a.length&&o(a[0][0],a[0][1])}}function nr(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=$i(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 ir,rr={exports:{}};var ar=function(){if(ir)return rr.exports;ir=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)}rr.exports=r,rr.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):[]},rr.exports}(),sr=Ui(ar);let or=!0,cr=!0;function dr(e,t,n){const i=e.match(t);return i&&i.length>=n&&parseFloat(i[n],10)}function lr(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 ur(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(or=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function hr(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(cr=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function pr(){if("object"==typeof window){if(or)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function mr(e,t){cr&&console.warn(e+" is deprecated, please use "+t+" instead.")}function gr(e){return"[object Object]"===Object.prototype.toString.call(e)}function vr(e){return gr(e)?Object.keys(e).reduce((function(t,n){const i=gr(e[n]),r=i?vr(e[n]):e[n],a=i&&!Object.keys(r).length;return void 0===r||a?t:Object.assign(t,{[n]:r})}),{}):e}function fr(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?fr(e,e.get(t[i]),n):i.endsWith("Ids")&&t[i].forEach((t=>{fr(e,e.get(t),n)}))})))}function kr(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&&fr(e,n,r)}))})),r}const yr=pr;function br(e,t){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),yr("chrome: "+JSON.stringify(e)),r(e)}))}e.video=i(e.video)}return yr("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 Tr(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Sr(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 lr(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function Er(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 Cr(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=>kr(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}),lr(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>kr(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 wr(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 Rr(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return wr(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 Pr(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 Ir(e,t){t.version>102||lr(e,"negotiationneeded",(e=>{const n=e.target;if(!(t.version<72||n.getConfiguration&&"plan-b"===n.getConfiguration().sdpSemantics)||"stable"===n.signalingState)return e}))}var Dr=Object.freeze({__proto__:null,fixNegotiationNeeded:Ir,shimAddTrackRemoveTrack:Rr,shimAddTrackRemoveTrackWithNative:wr,shimGetSendersWithDtmf:Er,shimGetUserMedia:br,shimMediaStream:Tr,shimOnTrack:Sr,shimPeerConnection:Pr,shimSenderReceiverGetStats:Cr});function Mr(e,t){const n=e&&e.navigator,i=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,i){mr("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 _r(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 Or(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 Ar(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;if(t.version>=151)return;const n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,a]=arguments;return"closed"===this.signalingState?Promise.resolve(new Map):i.apply(this,[e||null]).then((e=>{if(t.version<53&&!r)try{e.forEach((e=>{e.type=n[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:n[t.type]||t.type}))}))}return e})).then(r,a)}}function Nr(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 xr(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}),lr(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Lr(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){mr("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Ur(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Fr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const n=e.length>0;n&&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=t.apply(this,arguments);if(n){const{sender:t}=i,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 Br(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function jr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function qr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var Vr=Object.freeze({__proto__:null,shimAddTransceiver:Fr,shimCreateAnswer:qr,shimCreateOffer:jr,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||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:Br,shimGetStats:Ar,shimGetUserMedia:Mr,shimOnTrack:_r,shimPeerConnection:Or,shimRTCDataChannel:Ur,shimReceiverGetStats:xr,shimRemoveStream:Lr,shimSenderGetStats:Nr});function Hr(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 Wr(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 Kr(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 zr(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(Jr(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,i){t.mediaDevices.getUserMedia(e).then(n,i)}.bind(t))}function Jr(e){return e&&void 0!==e.video?Object.assign({},e,{video:vr(e.video)}):e}function Gr(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?(mr("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 Qr(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 Yr(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 Xr(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Zr,$r=Object.freeze({__proto__:null,shimAudioContext:Xr,shimCallbacksAPI:Kr,shimConstraints:Jr,shimCreateOfferLegacy:Yr,shimGetUserMedia:zr,shimLocalStreamsAPI:Hr,shimRTCIceServerUrls:Gr,shimRemoteStreamsAPI:Wr,shimTrackEventTransceiver:Qr}),ea={exports:{}};var ta=(Zr||(Zr=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 e=8;e<t.length;e+=2)switch(t[e]){case"raddr":n.relatedAddress=t[e+1];break;case"rport":n.relatedPort=parseInt(t[e+1],10);break;case"tcptype":n.tcpType=t[e+1];break;case"ufrag":n.ufrag=t[e+1],n.usernameFragment=t[e+1];break;default:void 0===n[t[e]]&&(n[t[e]]=t[e+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 e=0;e<i.length;e++)n=i[e].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 r=3;r<i.length;r++){const a=i[r],s=t.matchPrefix(e,"a=rtpmap:"+a+" ")[0];if(s){const i=t.parseRtpMap(s),r=t.matchPrefix(e,"a=fmtp:"+a+" ");switch(i.parameters=r.length?t.parseFmtp(r[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+a+" ").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 e=0;e<i.length;e++)switch(i[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[e].substring(2)}return n?t.getDirection(n):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"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 e=0;e<n.length;e++)if(n[e].length<2||"="!==n[e].charAt(1))return!1;return!0},e.exports=t}(ea)),ea.exports),na=Ui(ta),ia=t({__proto__:null,default:na},[ta]);function ra(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=na.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,lr(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function aa(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||lr(e,"icecandidate",(e=>{if(e.candidate){const t=na.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function sa(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=na.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=na.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=na.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 oa(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},lr(e,"datachannel",(e=>(n(e.channel,e.target),e)))}function ca(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 da(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 la(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 ua(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 ha,pa,ma=Object.freeze({__proto__:null,removeExtmapAllowMixed:da,shimAddIceCandidateNullOrEmpty:la,shimConnectionState:ca,shimMaxMessageSize:sa,shimParameterlessSetLocalDescription:ua,shimRTCIceCandidate:ra,shimRTCIceCandidateRelayProtocol:aa,shimSendThrowTypeError:oa});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const 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{navigator:n}=e;if(n.userAgentData&&n.userAgentData.brands){const e=n.userAgentData.brands.find((e=>"Chromium"===e.brand));if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(n.mozGetUserMedia)t.browser="firefox",t.version=parseInt(dr(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(dr(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(dr(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=dr(n.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),r={browserDetails:i,commonShim:ma,extractVersion:dr,disableLog:ur,disableWarnings:hr,sdp:ia};switch(i.browser){case"chrome":if(!Dr||!Pr||!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=Dr,la(e,i),ua(e),br(e,i),Tr(e),Pr(e,i),Sr(e,i),Rr(e,i),Er(e),Cr(e,i),Ir(e,i),ra(e),aa(e),ca(e),sa(e,i),oa(e,i),da(e,i);break;case"firefox":if(!Vr||!Or||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=Vr,la(e,i),ua(e),Mr(e,i),Or(e,i),Ar(e,i),_r(e),Lr(e),Nr(e),xr(e),Ur(e),Fr(e),Br(e),jr(e),qr(e),ra(e),ca(e),sa(e,i),oa(e,i);break;case"safari":if(!$r||!t.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=$r,la(e,i),ua(e),Gr(e),Yr(e),Kr(e),Hr(e),Wr(e),Qr(e),zr(e),Xr(e),ra(e),aa(e),sa(e,i),oa(e,i),da(e,i);break;default:n("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});class ga 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)}}ha=ga,ga.resolve=e=>Reflect.get(pa,"resolve",ha).call(ha,e);const va=/version\/(\d+(\.?_?\d+)+)/i;let fa;function ka(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===fa||t){const e=ya.find((e=>{let{test:t}=e;return t.test(n)}));fa=null==e?void 0:e.describe(n)}return fa}const ya=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:ba(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Ta(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:ba(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Ta(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:ba(va,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:Ta(e)})}];function ba(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 Ta(e){return e.includes("mac os")?ba(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}const Sa="2.19.0";class Ea 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 Ca extends Ea{}var wa,Ra,Pa,Ia,Da,Ma,_a;e.ConnectionErrorReason=void 0,(wa=e.ConnectionErrorReason||(e.ConnectionErrorReason={}))[wa.NotAllowed=0]="NotAllowed",wa[wa.ServerUnreachable=1]="ServerUnreachable",wa[wa.InternalError=2]="InternalError",wa[wa.Cancelled=3]="Cancelled",wa[wa.LeaveRequest=4]="LeaveRequest",wa[wa.Timeout=5]="Timeout",wa[wa.WebSocket=6]="WebSocket",wa[wa.ServiceNotFound=7]="ServiceNotFound";class Oa extends Ca{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 Oa(t,e.ConnectionErrorReason.NotAllowed,n,i)}static timeout(t){return new Oa(t,e.ConnectionErrorReason.Timeout)}static leaveRequest(t,n){return new Oa(t,e.ConnectionErrorReason.LeaveRequest,void 0,n)}static internal(t,n){return new Oa(t,e.ConnectionErrorReason.InternalError,void 0,n)}static cancelled(t){return new Oa(t,e.ConnectionErrorReason.Cancelled)}static serverUnreachable(t,n){return new Oa(t,e.ConnectionErrorReason.ServerUnreachable,n)}static websocket(t,n,i){return new Oa(t,e.ConnectionErrorReason.WebSocket,n,i)}static serviceNotFound(t,n){return new Oa(t,e.ConnectionErrorReason.ServiceNotFound,void 0,n)}}class Aa extends Ea{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class Na extends Ea{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class xa extends Ea{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class La extends Ea{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Ua extends Ea{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class Fa extends Ea{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Ba extends Ca{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName="string"==typeof t?t:Ii[t]}}e.DataStreamErrorReason=void 0,(Ra=e.DataStreamErrorReason||(e.DataStreamErrorReason={}))[Ra.AlreadyOpened=0]="AlreadyOpened",Ra[Ra.AbnormalEnd=1]="AbnormalEnd",Ra[Ra.DecodeFailed=2]="DecodeFailed",Ra[Ra.LengthExceeded=3]="LengthExceeded",Ra[Ra.Incomplete=4]="Incomplete",Ra[Ra.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",Ra[Ra.EncryptionTypeMismatch=8]="EncryptionTypeMismatch";class ja extends Ca{constructor(t,n){super(16,t),this.name="DataStreamError",this.reason=n,this.reasonName=e.DataStreamErrorReason[n]}}class qa extends Ea{constructor(e){super(18,e),this.name="SignalReconnectError"}}e.MediaDeviceFailure=void 0,(Pa=e.MediaDeviceFailure||(e.MediaDeviceFailure={})).PermissionDenied="PermissionDenied",Pa.NotFound="NotFound",Pa.DeviceInUse="DeviceInUse",Pa.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 Va{}Va.setTimeout=function(){return setTimeout(...arguments)},Va.setInterval=function(){return setInterval(...arguments)},Va.clearTimeout=function(){return clearTimeout(...arguments)},Va.clearInterval=function(){return clearInterval(...arguments)},e.RoomEvent=void 0,(Ia=e.RoomEvent||(e.RoomEvent={})).Connected="connected",Ia.Reconnecting="reconnecting",Ia.SignalReconnecting="signalReconnecting",Ia.Reconnected="reconnected",Ia.Disconnected="disconnected",Ia.ConnectionStateChanged="connectionStateChanged",Ia.Moved="moved",Ia.MediaDevicesChanged="mediaDevicesChanged",Ia.ParticipantConnected="participantConnected",Ia.ParticipantDisconnected="participantDisconnected",Ia.TrackPublished="trackPublished",Ia.TrackSubscribed="trackSubscribed",Ia.TrackSubscriptionFailed="trackSubscriptionFailed",Ia.TrackUnpublished="trackUnpublished",Ia.TrackUnsubscribed="trackUnsubscribed",Ia.TrackMuted="trackMuted",Ia.TrackUnmuted="trackUnmuted",Ia.LocalTrackPublished="localTrackPublished",Ia.LocalTrackUnpublished="localTrackUnpublished",Ia.LocalAudioSilenceDetected="localAudioSilenceDetected",Ia.ActiveSpeakersChanged="activeSpeakersChanged",Ia.ParticipantMetadataChanged="participantMetadataChanged",Ia.ParticipantNameChanged="participantNameChanged",Ia.ParticipantAttributesChanged="participantAttributesChanged",Ia.ParticipantActive="participantActive",Ia.RoomMetadataChanged="roomMetadataChanged",Ia.DataReceived="dataReceived",Ia.SipDTMFReceived="sipDTMFReceived",Ia.TranscriptionReceived="transcriptionReceived",Ia.ConnectionQualityChanged="connectionQualityChanged",Ia.TrackStreamStateChanged="trackStreamStateChanged",Ia.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Ia.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Ia.AudioPlaybackStatusChanged="audioPlaybackChanged",Ia.VideoPlaybackStatusChanged="videoPlaybackChanged",Ia.MediaDevicesError="mediaDevicesError",Ia.ParticipantPermissionsChanged="participantPermissionsChanged",Ia.SignalConnected="signalConnected",Ia.RecordingStatusChanged="recordingStatusChanged",Ia.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Ia.EncryptionError="encryptionError",Ia.DCBufferStatusChanged="dcBufferStatusChanged",Ia.ActiveDeviceChanged="activeDeviceChanged",Ia.ChatMessage="chatMessage",Ia.LocalTrackSubscribed="localTrackSubscribed",Ia.MetricsReceived="metricsReceived",Ia.DataTrackPublished="dataTrackPublished",Ia.DataTrackUnpublished="dataTrackUnpublished",Ia.LocalDataTrackPublished="localDataTrackPublished",Ia.LocalDataTrackUnpublished="localDataTrackUnpublished",e.ParticipantEvent=void 0,(Da=e.ParticipantEvent||(e.ParticipantEvent={})).TrackPublished="trackPublished",Da.TrackSubscribed="trackSubscribed",Da.TrackSubscriptionFailed="trackSubscriptionFailed",Da.TrackUnpublished="trackUnpublished",Da.TrackUnsubscribed="trackUnsubscribed",Da.TrackMuted="trackMuted",Da.TrackUnmuted="trackUnmuted",Da.LocalTrackPublished="localTrackPublished",Da.LocalTrackUnpublished="localTrackUnpublished",Da.LocalTrackCpuConstrained="localTrackCpuConstrained",Da.LocalSenderCreated="localSenderCreated",Da.ParticipantMetadataChanged="participantMetadataChanged",Da.ParticipantNameChanged="participantNameChanged",Da.DataReceived="dataReceived",Da.SipDTMFReceived="sipDTMFReceived",Da.TranscriptionReceived="transcriptionReceived",Da.IsSpeakingChanged="isSpeakingChanged",Da.ConnectionQualityChanged="connectionQualityChanged",Da.TrackStreamStateChanged="trackStreamStateChanged",Da.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Da.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Da.TrackCpuConstrained="trackCpuConstrained",Da.MediaDevicesError="mediaDevicesError",Da.AudioStreamAcquired="audioStreamAcquired",Da.ParticipantPermissionsChanged="participantPermissionsChanged",Da.PCTrackAdded="pcTrackAdded",Da.AttributesChanged="attributesChanged",Da.LocalTrackSubscribed="localTrackSubscribed",Da.ChatMessage="chatMessage",Da.Active="active",e.EngineEvent=void 0,(Ma=e.EngineEvent||(e.EngineEvent={})).TransportsCreated="transportsCreated",Ma.Connected="connected",Ma.Disconnected="disconnected",Ma.Resuming="resuming",Ma.Resumed="resumed",Ma.Restarting="restarting",Ma.Restarted="restarted",Ma.SignalResumed="signalResumed",Ma.SignalRestarted="signalRestarted",Ma.Closing="closing",Ma.MediaTrackAdded="mediaTrackAdded",Ma.ActiveSpeakersUpdate="activeSpeakersUpdate",Ma.DataPacketReceived="dataPacketReceived",Ma.RTPVideoMapUpdate="rtpVideoMapUpdate",Ma.DCBufferStatusChanged="dcBufferStatusChanged",Ma.ParticipantUpdate="participantUpdate",Ma.RoomUpdate="roomUpdate",Ma.SpeakersChanged="speakersChanged",Ma.StreamStateChanged="streamStateChanged",Ma.ConnectionQualityUpdate="connectionQualityUpdate",Ma.SubscriptionError="subscriptionError",Ma.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",Ma.RemoteMute="remoteMute",Ma.SubscribedQualityUpdate="subscribedQualityUpdate",Ma.LocalTrackUnpublished="localTrackUnpublished",Ma.LocalTrackSubscribed="localTrackSubscribed",Ma.Offline="offline",Ma.SignalRequestResponse="signalRequestResponse",Ma.SignalConnected="signalConnected",Ma.RoomMoved="roomMoved",Ma.PublishDataTrackResponse="publishDataTrackResponse",Ma.UnPublishDataTrackResponse="unPublishDataTrackResponse",Ma.DataTrackSubscriberHandles="dataTrackSubscriberHandles",Ma.DataTrackPacketReceived="dataTrackPacketReceived",Ma.Joined="joined",Ma.TokenRefreshed="tokenRefreshed",Ma.ServerRegionsReported="serverRegionsReported",e.TrackEvent=void 0,(_a=e.TrackEvent||(e.TrackEvent={})).Message="message",_a.Muted="muted",_a.Unmuted="unmuted",_a.Restarted="restarted",_a.Ended="ended",_a.Subscribed="subscribed",_a.Unsubscribed="unsubscribed",_a.CpuConstrained="cpuConstrained",_a.UpdateSettings="updateSettings",_a.UpdateSubscription="updateSubscription",_a.AudioPlaybackStarted="audioPlaybackStarted",_a.AudioPlaybackFailed="audioPlaybackFailed",_a.AudioSilenceDetected="audioSilenceDetected",_a.VisibilityChanged="visibilityChanged",_a.VideoDimensionsChanged="videoDimensionsChanged",_a.VideoPlaybackStarted="videoPlaybackStarted",_a.VideoPlaybackFailed="videoPlaybackFailed",_a.ElementAttached="elementAttached",_a.ElementDetached="elementDetached",_a.UpstreamPaused="upstreamPaused",_a.UpstreamResumed="upstreamResumed",_a.SubscriptionPermissionChanged="subscriptionPermissionChanged",_a.SubscriptionStatusChanged="subscriptionStatusChanged",_a.SubscriptionFailed="subscriptionFailed",_a.TrackProcessorUpdate="trackProcessorUpdate",_a.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",_a.TranscriptionReceived="transcriptionReceived",_a.TimeSyncUpdate="timeSyncUpdate",_a.PreConnectBufferFlushed="preConnectBufferFlushed";class Ha{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 Wa=["opus","red"],Ka=["vp8","h264"],za=["vp8","h264","vp9","av1","h265"];function Ja(e){return!!Ka.find((t=>t===e))}const Ga=Ja;var Qa,Ya;e.BackupCodecPolicy=void 0,(Qa=e.BackupCodecPolicy||(e.BackupCodecPolicy={}))[Qa.PREFER_REGRESSION=0]="PREFER_REGRESSION",Qa[Qa.SIMULCAST=1]="SIMULCAST",Qa[Qa.REGRESSION=2]="REGRESSION",e.AudioPresets=void 0,(Ya=e.AudioPresets||(e.AudioPresets={})).telephone={maxBitrate:12e3},Ya.speech={maxBitrate:24e3},Ya.music={maxBitrate:48e3},Ya.musicStereo={maxBitrate:64e3},Ya.musicHighQuality={maxBitrate:96e3},Ya.musicHighQualityStereo={maxBitrate:128e3};const Xa={h90:new Ha(160,90,9e4,20),h180:new Ha(320,180,16e4,20),h216:new Ha(384,216,18e4,20),h360:new Ha(640,360,45e4,20),h540:new Ha(960,540,8e5,25),h720:new Ha(1280,720,17e5,30),h1080:new Ha(1920,1080,3e6,30),h1440:new Ha(2560,1440,5e6,30),h2160:new Ha(3840,2160,8e6,30)},Za={h120:new Ha(160,120,7e4,20),h180:new Ha(240,180,125e3,20),h240:new Ha(320,240,14e4,20),h360:new Ha(480,360,33e4,20),h480:new Ha(640,480,5e5,20),h540:new Ha(720,540,6e5,25),h720:new Ha(960,720,13e5,30),h1080:new Ha(1440,1080,23e5,30),h1440:new Ha(1920,1440,38e5,30)},$a={h360fps3:new Ha(640,360,2e5,3,"medium"),h360fps15:new Ha(640,360,4e5,15,"medium"),h720fps5:new Ha(1280,720,8e5,5,"medium"),h720fps15:new Ha(1280,720,15e5,15,"medium"),h720fps30:new Ha(1280,720,2e6,30,"medium"),h1080fps15:new Ha(1920,1080,25e5,15,"medium"),h1080fps30:new Ha(1920,1080,5e6,30,"medium"),original:new Ha(0,0,7e6,30,"medium")};function es(e,t,n){var i,r,a,s;const{optionsWithoutProcessor:o,audioProcessor:c,videoProcessor:d}=us(null!=e?e:{}),l=null==t?void 0:t.processor,u=null==n?void 0:n.processor,h=null!=o?o:{};return!0===h.audio&&(h.audio={}),!0===h.video&&(h.video={}),h.audio&&(ts(h.audio,t),null!==(i=(a=h.audio).deviceId)&&void 0!==i||(a.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=null!=c?c:l)),h.video&&(ts(h.video,n),null!==(r=(s=h.video).deviceId)&&void 0!==r||(s.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=null!=d?d:u)),h}function ts(e,t){return Object.keys(t).forEach((n=>{void 0===e[n]&&(e[n]=t[n])})),e}function ns(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)ts(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 is(e){return Zi(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const n=rs();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 ys(t),i.getByteTimeDomainData(a);const s=a.some((e=>128!==e&&0!==e));return n.close(),!s}return!1}()}))}function rs(){var e;const t="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){const n=new t({latencyHint:"interactive"});if("suspended"===n.state&&"undefined"!=typeof window&&(null===(e=window.document)||void 0===e?void 0:e.body)){const e=()=>Zi(this,void 0,void 0,(function*(){var t;try{"suspended"===n.state&&(yield n.resume())}catch(e){console.warn("Error trying to auto-resume audio context",e)}finally{null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)}}));n.addEventListener("statechange",(()=>{var t;"closed"===n.state&&(null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e))})),window.document.body.addEventListener("click",e)}return n}}function as(e){return"audioinput"===e?gs.Source.Microphone:"videoinput"===e?gs.Source.Camera:gs.Source.Unknown}function ss(e){return e===gs.Source.Microphone?"audioinput":e===gs.Source.Camera?"videoinput":void 0}function os(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=Ds()?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 cs(e){return e.split("/")[1].toLowerCase()}function ds(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new Hn({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function ls(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?ls(e.track):{})}}function us(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 hs(e,t){return e.width*e.height<t.width*t.height}const ps=[];var ms;e.VideoQuality=void 0,(ms=e.VideoQuality||(e.VideoQuality={}))[ms.LOW=0]="LOW",ms[ms.MEDIUM=1]="MEDIUM",ms[ms.HIGH=2]="HIGH";class gs extends ar.EventEmitter{get streamState(){return this._streamState}setStreamState(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=gs.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Wi,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=zi(null!==(r=i.loggerName)&&void 0!==r?r:e.LoggerNames.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=gs.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),ls(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let n="audio";this.kind===gs.Kind.Video&&(n="video"),0===this.attachedElements.length&&this.kind===gs.Kind.Video&&this.addAppVisibilityListener(),t||("audio"===n&&(ps.forEach((e=>{null!==e.parentElement||t||(t=e)})),t&&ps.splice(ps.indexOf(t),1)),t||(t=document.createElement(n))),this.attachedElements.includes(t)||this.attachedElements.push(t),vs(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?Wi.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):Wi.warn("could not playback ".concat(r?"audio":"video"),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.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=zi(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),ps.forEach((e=>{e.parentElement||(t=!1)})),t&&ps.push(e)}}handleAppVisibilityChanged(){return Zi(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==gs.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){As()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){As()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function vs(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)),Ds()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===n.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(Ds()||Ps())&&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 Xe.AUDIO;case t.Video:return Xe.VIDEO;default:return Xe.DATA}},e.kindFromProto=function(e){switch(e){case Xe.AUDIO:return t.Audio;case Xe.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return Ze.CAMERA;case n.Microphone:return Ze.MICROPHONE;case n.ScreenShare:return Ze.SCREEN_SHARE;case n.ScreenShareAudio:return Ze.SCREEN_SHARE_AUDIO;default:return Ze.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case Ze.CAMERA:return n.Camera;case Ze.MICROPHONE:return n.Microphone;case Ze.SCREEN_SHARE:return n.ScreenShare;case Ze.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case Pn.ACTIVE:return i.Active;case Pn.PAUSED:return i.Paused;default:return i.Unknown}}}(gs||(gs={}));const ks="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function ys(e){return new ga((t=>Va.setTimeout(t,e)))}function bs(){return"addTransceiver"in RTCPeerConnection.prototype}function Ts(){return"addTrack"in RTCPeerConnection.prototype}function Ss(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Ds()||Ps())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 Es(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Ps())return!1;if(Ds()){const e=ka();if((null==e?void 0:e.version)&&js(e.version,"16")<0)return!1;if("iOS"===(null==e?void 0:e.os)&&(null==e?void 0:e.osVersion)&&js(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 Cs(e){return"av1"===e||"vp9"===e}function ws(e){return!(!document||Ms())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function Rs(){return"undefined"!=typeof RTCPeerConnection&&(bs()||Ts())}function Ps(){var e;return"Firefox"===(null===(e=ka())||void 0===e?void 0:e.name)}function Is(){return"undefined"!=typeof window&&void 0!==window.RTCRtpScriptTransform&&!function(){const e=ka();return!!e&&"Chrome"===e.name&&"iOS"!==e.os}()}function Ds(){var e;return"Safari"===(null===(e=ka())||void 0===e?void 0:e.name)}function Ms(){const e=ka();return"Safari"===(null==e?void 0:e.name)||"iOS"===(null==e?void 0:e.os)}function _s(){const e=ka();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)&&js(e.osVersion,"17")>=0}function Os(){var e,t;return!!As()&&(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 As(){return"undefined"!=typeof document}function Ns(){return"ReactNative"==navigator.product}function xs(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function Ls(e){return xs(e)?e.hostname.split(".")[0]:null}function Us(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Fs(){if(!Ns())return;let e=Us();return e?e.platform:void 0}function Bs(){if(As())return window.devicePixelRatio;if(Ns()){let e=Us();if(e)return e.devicePixelRatio}return 1}function js(e,t){const n=e.split("."),i=t.split("."),r=Math.min(n.length,i.length);for(let e=0;e<r;++e){const t=parseInt(n[e],10),a=parseInt(i[e],10);if(t>a)return 1;if(t<a)return-1;if(e===r-1&&t===a)return 0}return""===e&&""!==t?-1:""===t?1:n.length==i.length?0:n.length<i.length?-1:1}function qs(e){for(const t of e)t.target.handleResize(t)}function Vs(e){for(const t of e)t.target.handleVisibilityChanged(t)}let Hs=null;const Ws=()=>(Hs||(Hs=new ResizeObserver(qs)),Hs);let Ks=null;const zs=()=>(Ks||(Ks=new IntersectionObserver(Vs,{root:null,rootMargin:"0px"})),Ks);let Js,Gs;function Qs(){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=r.captureStream(),[o]=s.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=n,o}function Ys(){if(!Gs){const e=new AudioContext,t=e.createOscillator(),n=e.createGain();n.gain.setValueAtTime(0,0);const i=e.createMediaStreamDestination();if(t.connect(n),n.connect(i),t.start(),[Gs]=i.stream.getAudioTracks(),!Gs)throw Error("Could not get empty media stream audio track");Gs.enabled=!1}return Gs.clone()}class Xs{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise(((t,n)=>Zi(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 Zs(e){return za.includes(e)}function $s(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 eo(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function to(t){switch(t.reason){case e.ConnectionErrorReason.LeaveRequest:return t.context;case e.ConnectionErrorReason.Cancelled:return nt.CLIENT_INITIATED;case e.ConnectionErrorReason.NotAllowed:return nt.USER_REJECTED;case e.ConnectionErrorReason.ServerUnreachable:return nt.JOIN_FAILURE;default:return nt.UNKNOWN_REASON}}function no(e){return void 0!==e?Number(e):void 0}function io(e){return void 0!==e?BigInt(e):void 0}function ro(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function ao(e){return!!e&&e.kind==gs.Kind.Audio}function so(e){return!!e&&e.kind==gs.Kind.Video}function oo(e){return ro(e)&&so(e)}function co(e){return ro(e)&&ao(e)}function lo(e){return!!e&&!e.isLocal}function uo(e){return!!e&&!e.isLocal}function ho(e){return lo(e)&&so(e)}function po(e){return e.isLocal}function mo(){return"undefined"!=typeof CompressionStream}function go(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)})),fo(n,"rtc")}(e,t);return n?i:fo(i,"v1")}function vo(e){return e.endsWith("/")?e:"".concat(e,"/")}function fo(e,t){return e.pathname="".concat(vo(e.pathname)).concat(t),e}function ko(e){if("string"==typeof e)return Mn.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return Mn.fromBinary(new Uint8Array(e));throw new Error("could not decode websocket message: ".concat(typeof e))}const yo="AES-GCM",bo="lk_e2ee",To={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16,keySize:128};var So,Eo;function Co(){return Ro()||wo()}function wo(){return"undefined"!=typeof window&&void 0!==window.RTCRtpScriptTransform}function Ro(){return"undefined"!=typeof window&&void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams}function Po(e){return Zi(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 Io(e){return Zi(this,void 0,void 0,(function*(){return yield crypto.subtle.importKey("raw",e,"HKDF",!1,["deriveBits","deriveKey"])}))}function Do(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,(So=e.KeyProviderEvent||(e.KeyProviderEvent={})).SetKey="setKey",So.RatchetRequest="ratchetRequest",So.KeyRatcheted="keyRatcheted",e.KeyHandlerEvent=void 0,(e.KeyHandlerEvent||(e.KeyHandlerEvent={})).KeyRatcheted="keyRatcheted",e.EncryptionEvent=void 0,(Eo=e.EncryptionEvent||(e.EncryptionEvent={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Eo.EncryptionError="encryptionError",e.CryptorEvent=void 0,(e.CryptorEvent||(e.CryptorEvent={})).Error="cryptorError";function Mo(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 Ct({value:e.value})}class _o extends ar.EventEmitter{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.latestManuallySetKeyIndex=0,this.onKeyRatcheted=(e,t,n)=>{Wi.debug("key ratcheted event received",{ratchetResult:e,participantId:t,keyIndex:n})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},To),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 Oo;e.CryptorErrorReason=void 0,(Oo=e.CryptorErrorReason||(e.CryptorErrorReason={}))[Oo.InvalidKey=0]="InvalidKey",Oo[Oo.MissingKey=1]="MissingKey",Oo[Oo.InternalError=2]="InternalError";function Ao(){return Is()}function No(e){return!!(null==e?void 0:e.worker)&&(Ro()||Ao())}function xo(e){return!(!(null==e?void 0:e.timestamp)&&!(null==e?void 0:e.frameId))}function Lo(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&&Va.clearTimeout(a),a=Va.setTimeout((function(){if(a=void 0,d=Date.now(),!s){const t=e.apply(u,i);o&&o(t),l.forEach((e=>{let{resolve:n}=e;return n(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&&Va.clearTimeout(a),l.forEach((t=>{let{reject:n}=t;return n(e)})),l=[]},u}const Uo=2e3;function Fo(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 Bo extends gs{constructor(e,t,n,i,r){super(e,n,r),this.sid=t,this.receiver=i}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 Zi(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()),Uo)),"undefined"!=typeof RTCRtpReceiver&&"function"==typeof RTCRtpReceiver.prototype.getSynchronizationSources&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const t=()=>{var n;this.timeSyncHandle=requestAnimationFrame((()=>t()));const i=null===(n=this.receiver)||void 0===n?void 0:n.getSynchronizationSources()[0];if(i){const{timestamp:t,rtpTimestamp:n}=i;n&&this.rtpTimestamp!==n&&(this.emit(e.TrackEvent.TimeSyncUpdate,{timestamp:t,rtpTimestamp:n}),this.rtpTimestamp=n)}};t()}}class jo extends Bo{constructor(e,t,n,i,r){super(e,t,gs.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>Zi(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=Fo(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=Lo((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}lookupFrameMetadata(e){let{rtpTimestamp:t}=e;var n;return null===(n=this.packetTrailerExtractor)||void 0===n?void 0:n.lookupMetadata(t)}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===gs.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?fs(this._mediaStreamTrack,t):vs(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 qo(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 e of t)e.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 e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return Zi(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 e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Zi(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?Va.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 Bs();if(!t){return Bs()>2?2:1}return t}}class qo{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:n,isIntersecting:i}=e;n===this.element&&(this.isIntersecting=i,this.isPiP=Vo(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=Vo(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)}))}))},this.onLeavePiP=()=>{var e;this.isPiP=Vo(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:Ho(e),this.isPiP=As()&&Vo(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=Ho(this.element),this.isPiP=Vo(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,zs().observe(this.element),Ws().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=zs())||void 0===e||e.unobserve(this.element),null===(t=Ws())||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 Vo(e){var t,n;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&Ho(e,null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)}function Ho(e,t){const n=t||window;let i=e.offsetTop,r=e.offsetLeft;const a=e.offsetWidth,s=e.offsetHeight,{hidden:o}=e,{display:c}=getComputedStyle(e);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 Wo extends ar.EventEmitter{constructor(t,n){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=t=>{var n,i;const{kind:r,data:a}=t.data;switch(r){case"error":if(Wi.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.handlePacketTrailerMetadata(a.trackId,a.rtpTimestamp,a.ssrc,a.metadata)}},this.onWorkerError=t=>{Wi.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(!Co())throw new Aa("tried to setup end-to-end encryption on an unsupported browser");if(Wi.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:Ji.getLevel()}};this.worker&&(Wi.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){Wi.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):Wi.warn("ignoring server sent trailer as it's empty")}handlePacketTrailerMetadata(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 jo&&a.track.packetTrailerExtractor)return void a.track.packetTrailerExtractor.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!==mt.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!==mt.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)=>Zi(this,void 0,void 0,(function*(){this.setupE2EESender(t,e)})))),t.localParticipant.on(e.ParticipantEvent.LocalTrackPublished,(e=>{if(!so(e.track)||!Ms())return;const t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:cs(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 Zi(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 Xs;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 Xs;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{key:n,participantIdentity:i,keyIndex:r}=e;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)}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?cs(n.mimeType):void 0,i)}setupE2EESender(e,t){var n;ro(e)&&t?this.handleSender(t,e.mediaStreamID,void 0,so(e)?null===(n=e.publishOptions)||void 0===n?void 0:n.packetTrailer:void 0):t||Wi.warn("early return because sender is not ready")}handleReceiver(e,t,n,i,r){return Zi(this,void 0,void 0,(function*(){if(this.worker){if(Is()){const a={kind:"decode",participantIdentity:n,trackId:t,codec:i,hasPacketTrailer:r};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{if(bo in e&&i){const e={kind:"updateCodec",data:{trackId:t,codec:i,participantIdentity:n,hasPacketTrailer:r}};return void this.worker.postMessage(e)}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,isReuse:bo in e,hasPacketTrailer:r}};this.worker.postMessage(o,[s,a])}e[bo]=!0}}))}handleSender(e,t,n,i){var r;if(!(bo 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(Is()){Wi.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n,hasPacketTrailer:xo(i),packetTrailer:i};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{Wi.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,isReuse:!1,hasPacketTrailer:xo(i),packetTrailer:i}};this.worker.postMessage(a,[r.readable,r.writable])}e[bo]=!0}}}class Ko{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 zo{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=>{Wi.error("packet trailer 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(!No(this.worker?{worker:this.worker}:void 0)&&!(null===(i=this.room)||void 0===i?void 0:i.hasE2EESetup))return void Wi.warn("packet trailer transform not supported; skipping extraction");const s=new Ko,o=e.mediaStreamID;this.extractors.set(o,s),e.packetTrailerExtractor=s,(null===(r=this.room)||void 0===r?void 0:r.hasE2EESetup)||this.setupWorkerReceiver(a,o,!0)}setupPassthroughReceiver(e,t){Ao()?"transform"in e&&(e.transform=null):(this.worker&&No({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(Ao())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 Wi.warn("createEncodedStreams not supported");let a;try{a=e.createEncodedStreams()}catch(e){return void Wi.warn("failed to create encoded streams",{error:e})}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 jo&&(e.packetTrailerExtractor=void 0)}cleanup(){var e;for(const e of this.extractors.values())e.dispose();this.extractors.clear(),this.workerPipelines.clear(),null===(e=this.worker)||void 0===e||e.terminate()}}class Jo{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new Jo),this._instance}addFailedConnectionAttempt(e){var t;const n=Ls(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,ys(Math.min(500*Math.pow(2,i),15e3)))}getBackOffPromise(e){const t=new URL(e),n=t&&Ls(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),n=t&&Ls(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}Jo._instance=null;const Go="default";class Qo{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new Qo),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return Zi(this,arguments,void 0,(function(e){var t=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var i;if((null===(i=Qo.userMediaPromiseMap)||void 0===i?void 0:i.size)>0){Wi.debug("awaiting getUserMedia promise");try{e?yield Qo.userMediaPromiseMap.get(e):yield Promise.all(Qo.userMediaPromiseMap.values())}catch(e){Wi.warn("error waiting for media permissons")}}let r=yield navigator.mediaDevices.enumerateDevices();if(n&&(!Ds()||!t.hasDeviceInUse(e))){if(0===r.filter((t=>t.kind===e)).length||r.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);r=yield navigator.mediaDevices.enumerateDevices(),n.getTracks().forEach((e=>{e.stop()}))}}return t._previousDevices=r,e&&(r=r.filter((t=>t.kind===e))),r}()}))}normalizeDeviceId(e,t,n){return Zi(this,void 0,void 0,(function*(){if(t!==Go)return t;const i=yield this.getDevices(e),r=i.find((e=>e.deviceId===Go));if(!r)return void Wi.warn("could not reliably determine default device");const a=i.find((e=>e.deviceId!==Go&&e.groupId===(null!=n?n:r.groupId)));if(a)return null==a?void 0:a.deviceId;Wi.warn("could not reliably determine default device")}))}hasDeviceInUse(e){return e?Qo.userMediaPromiseMap.has(e):Qo.userMediaPromiseMap.size>0}}Qo.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Qo.userMediaPromiseMap=new Map;const Yo=65535,Xo=4294967295;class Zo{static u16(e){return new Zo(e,Yo)}static u32(e){return new Zo(e,Xo)}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 Zo(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 Zo(e,this.maxSize)}isBefore(e){const t=this.value>>>0,n=(e.value>>>0)-t>>>0;return 0!==n&&n<this.maxSize+1}}class $o{static fromRtpTicks(e){return new $o(e,9e4)}static rtpRandom(){const e=Math.round(Math.random()*Xo);return $o.fromRtpTicks(e)}constructor(e,t){this.timestamp=Zo.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new $o(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}}class ec{constructor(e,t,n){this.epoch=t,this.base=n,this.previous=n.clone(),this.rateInHz=e}static startingNow(e,t){return new ec(t,new Date,e)}static startingAtTime(e,t,n){return new ec(n,e,t)}static rtpStartingNow(e){return ec.startingNow(e,9e4)}static rtpStartingAtTime(e,t){return ec.startingAtTime(e,t,9e4)}now(){return this.at(new Date)}at(e){let t=e.getTime()-this.epoch.getTime(),n=ec.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 tc(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 nc;!function(e){e[e.Reserved=0]="Reserved",e[e.TooLarge=1]="TooLarge"}(nc||(nc={}));class ic extends Ca{constructor(e,t){super(19,e),this.name="DataTrackHandleError",this.reason=t,this.reasonName=nc[t]}isReason(e){return this.reason===e}static tooLarge(){return new ic("Value too large to be a valid track handle",nc.TooLarge)}static reserved(e){return new ic("0x".concat(e.toString(16)," is a reserved value."),nc.Reserved)}}const rc={fromNumber(e){if(0===e)throw ic.reserved(e);if(e>Yo)throw ic.tooLarge();return e}};class ac{constructor(){this.value=0}get(){return this.value+=1,this.value>Yo?null:this.value}reset(){this.value=0}}const sc={from:e=>({sid:e.sid,pubHandle:e.pubHandle,name:e.name,usesE2ee:e.encryption!==mt.NONE}),toProtobuf:e=>new ft({sid:e.sid,pubHandle:e.pubHandle,name:e.name,encryption:e.usesE2ee?mt.GCM:mt.NONE})};var oc;!function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(oc||(oc={}));class cc{constructor(){this.pendingTasks=new Map,this.taskMutex=new r,this.nextTaskIndex=0}run(e){return Zi(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:oc.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=oc.RUNNING,yield e()}finally{t.status=oc.COMPLETED,this.pendingTasks.delete(t.id),n()}}))}flush(){return Zi(this,void 0,void 0,(function*(){return this.run((()=>Zi(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}class dc{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{closeCode:e,reason:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return r.close(e,t)};this.opened=new ga(((e,t)=>{const n=()=>{t(Oa.websocket("Encountered websocket error during connection establishment"))};r.onopen=()=>{e({readable:new ReadableStream({start(e){r.onmessage=t=>{let{data:n}=t;return e.enqueue(n)},r.onerror=t=>e.error(t)},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 ga(((e,t)=>{const n=()=>Zi(this,void 0,void 0,(function*(){const n=new ga((e=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",(t=>{e(t)}),{once:!0})})),i=yield ga.race([ys(250),n]);i?e(i):t(Oa.websocket("Encountered unspecified websocket error without a timely close event"))}));r.onclose=t=>{let{code:i,reason:a}=t;e({closeCode:i,reason:a}),r.removeEventListener("error",n)},r.addEventListener("error",n)})),t.signal&&(t.signal.onabort=()=>r.close()),this.close=a}}const lc=["syncState","trickle","offer","answer","simulate","leave"];var uc;!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"}(uc||(uc={}));class hc{get currentState(){return this.state}get isDisconnected(){return this.state===uc.DISCONNECTING||this.state===uc.DISCONNECTED}get isEstablishingConnection(){return this.state===uc.CONNECTING||this.state===uc.RECONNECTING}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.state=uc.DISCONNECTED,this.log=Wi,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=zi(null!==(i=n.loggerName)&&void 0!==i?i:e.LoggerNames.Signal,(()=>this.logContext)),this.useJSON=t,this.requestQueue=new cc,this.queuedRequests=[],this.closingLock=new r,this.connectionLock=new r,this.state=uc.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,n,i){return Zi(this,arguments,void 0,(function(e,t,n,i){var r=this;let a=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5?arguments[5]:void 0;return function*(){r.state=uc.CONNECTING,r.options=n;return yield r.connect(e,t,n,i,a,s)}()}))}reconnect(e,t,n,i){return Zi(this,void 0,void 0,(function*(){if(!this.options)return void this.log.warn("attempted to reconnect without signal options being set, ignoring");this.state=uc.RECONNECTING,this.clearPingInterval();return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:i}),void 0,this.useV0SignalPath)}))}connect(e,t,n,i){return Zi(this,arguments,void 0,(function(e,t,n,i){var r=this;let a=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5?arguments[5]:void 0;return function*(){const o=yield r.connectionLock.lock();r.connectOptions=n,r.useV0SignalPath=a;const c=function(e){var t;const n=new Bt({capabilities:e,sdk:jt.JS,protocol:17,clientProtocol:1,version:Sa});return Ns()&&(n.os=null!==(t=Fs())&&void 0!==t?t:""),n}(n.clientInfoCapabilities),d=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",Ns()?"reactnative":"js"),r.set("version",t.version),r.set("protocol",t.protocol.toString()),t.deviceModel&&r.set("device_model",t.deviceModel);t.os&&r.set("os",t.os);t.osVersion&&r.set("os_version",t.osVersion);t.browser&&r.set("browser",t.browser);t.browserVersion&&r.set("browser_version",t.browserVersion);n.adaptiveStream&&r.set("adaptive_stream","1");n.reconnectReason&&r.set("reconnect_reason",n.reconnectReason.toString());(null===(i=navigator.connection)||void 0===i?void 0:i.type)&&r.set("network",navigator.connection.type);return r}(t,c,n):yield function(e,t,n,i){return Zi(this,void 0,void 0,(function*(){const r=new URLSearchParams;r.set("access_token",e);const a=new _i({clientInfo:t,connectionSettings:new Mi({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(mo()){const e=new CompressionStream("gzip"),t=e.writable.getWriter();t.write(new Uint8Array(s)),t.close();const n=[],i=e.readable.getReader();for(;;){const{done:e,value:t}=yield i.read();if(e)break;n.push(t)}const r=n.reduce(((e,t)=>e+t.length),0),a=new Uint8Array(r);let d=0;for(const e of n)a.set(e,d),d+=e.length;o=a,c=Ai.GZIP}else o=s,c=Ai.NONE;const d=new Oi({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,c,n,s),l=go(e,d,a).toString(),u=(h=l,fo(new URL(eo(h)),"validate")).toString();var h;return new Promise(((e,t)=>Zi(r,void 0,void 0,(function*(){var r,a;try{let s=!1;const o=e=>Zi(this,void 0,void 0,(function*(){if(s)return;s=!0;const n=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unknown reason";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(),c(),t(Oa.cancelled(n))}));null==i||i.addEventListener("abort",o);const c=()=>{clearTimeout(d),null==i||i.removeEventListener("abort",o)},d=setTimeout((()=>{o(Oa.timeout("room connection has timed out (signal)"))}),n.websocketTimeout),h=(e,t)=>{this.handleSignalConnected(e,d,t)},p=new URL(l);p.searchParams.has("access_token")&&p.searchParams.set("access_token","<redacted>"),this.log.info("signal connecting to ".concat(p),{reconnect:n.reconnect,reconnectReason:n.reconnectReason}),this.ws&&(yield this.close(!1)),this.ws=new dc(l);try{this.ws.closed.then((e=>{var n;this.isEstablishingConnection&&t(Oa.internal("Websocket got closed during a (re)connection attempt: ".concat(e.reason))),1e3!==e.closeCode&&(this.log.warn("websocket closed",{reason:e.reason,code:e.closeCode,wasClean:1e3===e.closeCode,state:this.state}),this.state===uc.CONNECTED&&this.handleOnClose(null!==(n=e.reason)&&void 0!==n?n:"Unexpected WS error"))})).catch((e=>{this.isEstablishingConnection&&t(Oa.internal("Websocket error during a (re)connection attempt: ".concat(e)))}));const i=yield this.ws.opened.catch((e=>Zi(this,void 0,void 0,(function*(){if(this.state===uc.CONNECTED)this.handleWSError(e),t(e);else{this.state=uc.DISCONNECTED,clearTimeout(d);const n=yield this.handleConnectionError(e,u);t(n)}}))));if(clearTimeout(d),!i)return;const s=i.readable.getReader();this.streamWriter=i.writable.getWriter();const o=yield s.read();if(s.releaseLock(),!o.value)throw Oa.internal("no message received as first message");const c=ko(o.value),l=this.validateFirstMessage(c,null!==(r=n.reconnect)&&void 0!==r&&r);if(!l.isValid)return void t(l.error);"join"===(null===(a=c.message)||void 0===a?void 0:a.case)&&(this.pingTimeoutDuration=c.message.value.pingTimeout,this.pingIntervalDuration=c.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.onJoined&&this.onJoined(c.message.value));h(i,l.shouldProcessFirstMessage?c:void 0),e(l.response)}catch(e){t(e)}finally{c()}}finally{o()}}))))}()}))}startReadingLoop(e,t){return Zi(this,void 0,void 0,(function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield ys(this.signalLatency));const{done:t,value:n}=yield e.read();if(t)break;const i=ko(n);this.handleSignalResponse(i)}}))}close(){return Zi(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*(){if([uc.DISCONNECTING||uc.DISCONNECTED].includes(e.state))return void e.log.debug("ignoring signal close as it's already in disconnecting state");const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=uc.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:n});const t=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([t,ys(250)])}}catch(t){e.log.debug("websocket error while closing",{error:t})}finally{t&&(e.state=uc.DISCONNECTED),i()}}()}))}sendOffer(e,t){this.log.debug("sending offer",{offerSdp:e.sdp}),this.sendRequest({case:"offer",value:mc(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",{answerSdp:e.sdp}),this.sendRequest({case:"answer",value:mc(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",{candidate:e}),this.sendRequest({case:"trickle",value:new Bn({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new jn({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return Zi(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 ni({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 ti({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new gi({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:_.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Si({timestamp:_.parse(Date.now()),rtt:_.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Xn({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new $n({reason:nt.CLIENT_INITIATED,action:ei.DISCONNECT})})}sendPublishDataTrackRequest(e,t,n){return this.sendRequest({case:"publishDataTrackRequest",value:new An({pubHandle:e,name:t,encryption:n?mt.GCM:mt.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:"unpublishDataTrackRequest",value:new xn({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:"updateDataSubscription",value:new Gn({updates:[new Qn({trackSid:e,subscribe:t})]})})}sendRequest(e){return Zi(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&&!function(e){const t=lc.indexOf(e.case)>=0;return Wi.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(i&&t.state===uc.RECONNECTING)return void t.queuedRequests.push((()=>Zi(t,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(n||(yield t.requestQueue.flush()),t.signalLatency&&(yield ys(t.signalLatency)),t.isDisconnected)return void t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));if(!t.streamWriter)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case));const r=new Dn({message:e});try{t.useJSON?yield t.streamWriter.write(r.toJsonString()):yield t.streamWriter.write(r.toBinary().buffer)}catch(e){t.log.error("error sending signal message",{error:e})}}()}))}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=pc(i.value);this.onAnswer&&this.onAnswer(e,i.value.id,i.value.midToTrackId)}else if("offer"===i.case){const e=pc(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 Zi(this,void 0,void 0,(function*(){if(this.state===uc.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.info("websocket connection closed: ".concat(e),{reason:e}),t&&t(e)}))}handleWSError(e){this.log.error("websocket error",{error:e})}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=Va.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&&Va.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval"),this.pingInterval=Va.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&&Va.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n){this.state=uc.CONNECTED,this.log.info("signal connected"),clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),n)}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}:this.state===uc.RECONNECTING&&"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:Oa.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:Oa.internal("Unexpected first message")}:{isValid:!1,error:Oa.internal("did not receive join response, got ".concat(null===(s=e.message)||void 0===s?void 0:s.case," instead"))}}handleConnectionError(e,t){return Zi(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")?Oa.notAllowed(e,n.status):Oa.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const t=yield n.text();return Oa.notAllowed(t,n.status)}return e instanceof Oa?e:Oa.internal("Encountered unknown websocket error during connection: ".concat(e),{status:n.status,statusText:n.statusText})}catch(e){return e instanceof Oa?e:Oa.serverUnreachable(e instanceof Error?e.message:"server was not reachable")}}))}}function pc(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 mc(e,t){return new Kn({sdp:e.sdp,type:e.type,id:t})}class gc{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0;){if(!(this.buffer[0].sequence<=e))break;this.pop()}}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class vc{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[t,n]of this._map.entries())n.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e(n.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],n=this.asValueMap();for(const[i,r]of n.entries())t.push(e(r,i,n));return t}asValueMap(){const e=new Map;for(const[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e.set(t,n.value);return e}}var fc,kc,yc,bc,Tc,Sc={},Ec={},Cc={exports:{}};function wc(){if(fc)return Cc.exports;fc=1;var e=Cc.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")}))})),Cc.exports}function Rc(){return kc||(kc=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=wc(),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}}))}))}}(Ec)),Ec}function Pc(){if(bc)return yc;bc=1;var e=wc(),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 yc=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"},yc}var Ic=function(){if(Tc)return Sc;Tc=1;var e=Rc(),t=Pc(),n=wc();return Sc.grammar=n,Sc.write=t,Sc.parse=e.parse,Sc.parseParams=e.parseParams,Sc.parseFmtpConfig=e.parseFmtpConfig,Sc.parsePayloads=e.parsePayloads,Sc.parseRemoteCandidates=e.parseRemoteCandidates,Sc.parseImageAttributes=e.parseImageAttributes,Sc.parseSimulcastStreamList=e.parseSimulcastStreamList,Sc}();const Dc="negotiationStarted",Mc="negotiationComplete",_c="offerAnswered",Oc="rtpVideoPayloadTypes";class Ac extends ar.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.log=Wi,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=Lo((e=>Zi(this,void 0,void 0,(function*(){this.emit(Dc);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}))),20),this.close=()=>{this._pc&&(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.log=zi(null!==(i=n.loggerName)&&void 0!==i?i:e.LoggerNames.PCTransport),this.loggerOptions=n,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&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return Zi(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e,t){return Zi(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",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let r;if("offer"===e.type){let{stereoMids:t,nackMids:n}=function(e){var t;const n=[],i=[],r=Ic.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let a=0;return r.media.forEach((e=>{var t;const r=Lc(e.mid);"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(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&&(e.config.includes("sprop-stereo=1")&&n.push(r),!0))))})),{stereoMids:n,nackMids:i}}(e);this.remoteStereoMids=t,this.remoteNackMids=n}else if("answer"===e.type){if(this.pendingInitialOffer&&this._pc){const e=this.pendingInitialOffer;this.pendingInitialOffer=void 0;const t=Ic.parse(null!==(n=e.sdp)&&void 0!==n?n:"");t.media.forEach((e=>{xc(e)})),this.log.debug("setting pending initial offer before processing answer",this.logContext),yield this.setMungedSDP(e,Ic.write(t))}const t=Ic.parse(null!==(i=e.sdp)&&void 0!==i?i:"");t.media.forEach((e=>{const t=Lc(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}))})),r=Ic.write(t)}if(yield this.setMungedSDP(e,r,!0),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,"answer"===e.type&&(this.latestAcknowledgedOfferId=t,this.emit(_c,t)),this.renegotiate)this.renegotiate=!1,yield this.createAndSendOffer();else if("answer"===e.type&&(this.emit(Mc),e.sdp)){Ic.parse(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(Oc,e.rtp)}))}return!0}))}createInitialOffer(){return Zi(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",this.logContext);const t=this.latestOfferId+1;this.latestOfferId=t;const n=yield this.pc.createOffer();this.pendingInitialOffer={sdp:n.sdp,type:n.type};const i=Ic.parse(null!==(e=n.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{xc(e)})),n.sdp=Ic.write(i),{offer:n,offerId:t}}finally{t()}}))}createAndSendOffer(e){return Zi(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.log.debug("restarting ICE",this.logContext),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)return this.renegotiate=!0,void this.log.debug("requesting renegotiation",Object.assign({},this.logContext));yield this._pc.setRemoteDescription(t)}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);const n=this.latestOfferId+1;this.latestOfferId=n;const i=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:i.sdp},this.logContext));const r=Ic.parse(null!==(t=i.sdp)&&void 0!==t?t:"");if(r.media.forEach((e=>{xc(e),"audio"===e.type?Nc(e,["all"],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let n=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(n=e.payload,!0))),0===n)return!0;if(Cs(t.codec)&&!Ds()&&this.ensureVideoDDExtensionForSVC(e,r),!Cs(t.codec))return!0;const i=Math.round(.7*t.maxbr);for(const t of e.fmtp)if(t.payload===n){t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(i));break}return!0}))})),this.latestOfferId>n)return void this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:n}));yield this.setMungedSDP(i,Ic.write(r)),this.onOffer(i,this.latestOfferId)}finally{n()}}))}createAndSetAnswer(){return Zi(this,void 0,void 0,(function*(){var e;const t=yield this.pc.createAnswer(),n=Ic.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return n.media.forEach((e=>{xc(e),"audio"===e.type&&Nc(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,Ic.write(n)),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 La("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 La("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return Zi(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,n){return Zi(this,void 0,void 0,(function*(){var i,r;const a=e.sdp;if(t){e.sdp=t;try{return this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),void(n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(n){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:n,mungedSdp:t,originalSdp:a})),e.sdp=a}}try{n?yield null===(i=this._pc)||void 0===i?void 0:i.setRemoteDescription(e):yield null===(r=this._pc)||void 0===r?void 0:r.setLocalDescription(e)}catch(i){let r="unknown error";i instanceof Error?r=i.message:"string"==typeof i&&(r=i);const s={error:r,sdp:e.sdp};throw t&&t!==a&&(s.mungedSdp=t),!n&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new Ua(r)}}))}ensureVideoDDExtensionForSVC(e,t){var n,i;if(!(null===(n=e.ext)||void 0===n?void 0:n.some((e=>e.uri===ks)))){if(0===this.ddExtID){let e=0;t.media.forEach((t=>{var n;null===(n=t.ext)||void 0===n||n.forEach((t=>{t.value>e&&(e=t.value)}))})),this.ddExtID=e+1}null===(i=e.ext)||void 0===i||i.push({value:this.ddExtID,uri:ks})}}}function Nc(e,t,n){const i=Lc(e.mid);let r=0;e.rtp.some((e=>"opus"===e.codec&&(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&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}function xc(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 Lc(e){return"number"==typeof e?e.toFixed(0):e}const Uc="vp8",Fc={audioPreset:e.AudioPresets.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:$a.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Uc,backupCodec:!0,preConnectBuffer:!1},Bc={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},jc={deviceId:{ideal:"default"},resolution:Xa.h720.resolution},qc={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Yi,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Vc={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Hc;!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"}(Hc||(Hc={}));class Wc{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=Vc.peerConnectionTimeout,this.log=Wi,this.updateState=()=>{var e,t;const n=this.state,i=this.requiredTransports.map((e=>e.getConnectionState()));i.every((e=>"connected"===e))?this.state=Hc.CONNECTED:i.some((e=>"failed"===e))?this.state=Hc.FAILED:i.some((e=>"connecting"===e))?this.state=Hc.CONNECTING:i.every((e=>"closed"===e))?this.state=Hc.CLOSED:i.some((e=>"closed"===e))?this.state=Hc.CLOSING:i.every((e=>"new"===e))&&(this.state=Hc.NEW),n!==this.state&&(this.log.debug("pc state change: from ".concat(Hc[n]," to ").concat(Hc[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),null===(t=this.subscriber)||void 0===t?void 0:t.getConnectionState()))},this.log=zi(null!==(a=n.loggerName)&&void 0!==a?a:e.LoggerNames.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired="subscriber-primary"!==t,this.isSubscriberConnectionRequired="subscriber-primary"===t,this.publisher=new Ac(i,n),this._mode=t,"publisher-only"!==t&&(this.subscriber=new Ac(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,Rn.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,Rn.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=Hc.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 Zi(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(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),null===(e=this.subscriber)||void 0===e?void 0:e.close()]),this.updateState()}))}triggerIceRestart(){return Zi(this,void 0,void 0,(function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return Zi(this,void 0,void 0,(function*(){var n;t===Rn.PUBLISHER?yield this.publisher.addIceCandidate(e):yield null===(n=this.subscriber)||void 0===n?void 0:n.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e,t){return Zi(this,void 0,void 0,(function*(){var n,i,r;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{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.publisher.setConfiguration(e),null===(n=this.subscriber)||void 0===n||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return Zi(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.logContext),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 Zi(this,void 0,void 0,(function*(){return new ga(((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(_c,s),e.signal.removeEventListener("abort",o))},s=e=>{e>i&&(a(),t())},o=()=>{a(),n(new Ua("negotiation aborted"))},c=setTimeout((()=>{a(),n(new Ua("negotiation timed out"))}),this.peerConnectionTimeout);e.signal.addEventListener("abort",o),this.publisher.on(_c,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}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Rn.PUBLISHER||e===Rn.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 Zi(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)=>Zi(n,void 0,void 0,(function*(){const n=()=>{this.log.warn("abort transport connection",this.logContext),Va.clearTimeout(a),r(Oa.cancelled("room connection has been cancelled"))};(null==t?void 0:t.signal.aborted)&&n(),null==t||t.signal.addEventListener("abort",n);const a=Va.setTimeout((()=>{null==t||t.signal.removeEventListener("abort",n),r(Oa.internal("could not establish pc connection"))}),i);for(;this.state!==Hc.CONNECTED;)if(yield ys(50),null==t?void 0:t.signal.aborted)return void r(Oa.cancelled("room connection has been cancelled"));Va.clearTimeout(a),null==t||t.signal.removeEventListener("abort",n),e()}))))}()}))}}const Kc="undefined"!=typeof MediaRecorder;const zc=Kc?MediaRecorder:class{constructor(){throw new Error("MediaRecorder is not available in this environment")}};class Jc extends zc{constructor(e,t){if(!Kc)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=>Zi(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 Gc extends gs{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=Lo((()=>Zi(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>Zi(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=>Zi(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!==gs.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t,n){return Zi(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&&(vs(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=>{vs(null!=r?r:e,t)})))}))}waitForDimensions(){return Zi(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===gs.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(n=ka())||void 0===n?void 0:n.os)&&(yield ys(10));const i=Date.now();for(;Date.now()-i<t;){const t=e.dimensions;if(t)return t;yield ys(50)}throw new Na("unable to get track dimensions after timeout")}()}))}setDeviceId(e){return Zi(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===$s(e)||(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),$s(e)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return Zi(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===gs.Source.ScreenShare)return;const{deviceId:n,groupId:i}=e._mediaStreamTrack.getSettings(),r=e.kind===gs.Kind.Audio?"audioinput":"videoinput";return t?Qo.getInstance().normalizeDeviceId(r,n,i):n}()}))}mute(){return Zi(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return Zi(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return Zi(this,void 0,void 0,(function*(){const n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Na("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 Zi(this,void 0,void 0,(function*(){}))}restart(t,n){return Zi(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const i=yield this.trackChangeLock.lock();try{t||(t=this._constraints);const{deviceId:i,facingMode:r}=t,a=Xi(t,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:t}));const s={audio:!1,video:!1};this.kind===gs.Kind.Video?s.video=!i&&!r||{deviceId:i,facingMode:r}:s.audio=!i||Object.assign({deviceId:i},a),this.attachedElements.forEach((e=>{fs(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const o=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return this.kind===gs.Kind.Video&&(yield o.applyConstraints(a)),o.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(o,!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 Zi(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Os()&&(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 Zi(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=ka();if("Safari"===(null==n?void 0:n.name)&&js(n.version,"12.0")<0)throw new Aa("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 Zi(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 Zi(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 Zi(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(vs(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),vs(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 Zi(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 Zi(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(Kc)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 Jc(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 Qc extends Gc{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(t,n){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=arguments.length>3?arguments[3]:void 0,a=arguments.length>4?arguments[4]:void 0;super(t,gs.Kind.Audio,n,i,a),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>Zi(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}e&&this.prevStats&&(this._currentBitrate=Fo(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,at.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,at.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Zi(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===gs.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 Zi(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==gs.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 Zi(this,void 0,void 0,(function*(){let t;if(e){const n=ns({audio:e});"boolean"!=typeof n.audio&&(t=n.audio)}yield this.restart(t)}))}restart(e,t){const n=Object.create(null,{restart:{get:()=>super.restart}});return Zi(this,void 0,void 0,(function*(){const i=yield n.restart.call(this,e,t);return this.checkForSilence(),i}))}startMonitor(){As()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),Uo)))}setProcessor(t){return Zi(this,void 0,void 0,(function*(){var n;const i=yield this.trackChangeLock.lock();try{if(!Ns()&&!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 Zi(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield this.sender.getStats()).forEach((e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})})),t}))}checkForSilence(){return Zi(this,void 0,void 0,(function*(){const t=yield is(this);return t&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(e.TrackEvent.AudioSilenceDetected)),t}))}}const Yc=Object.values(Xa),Xc=Object.values(Za),Zc=Object.values($a),$c=[Xa.h180,Xa.h360],ed=[Za.h180,Za.h360],td=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map((t=>{var n,i;return new Ha(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*((null!==(n=e.encoding.maxFramerate)&&void 0!==n?n:30)/(null!==(i=t.fps)&&void 0!==i?i:30))))),t.fps,e.encoding.priority)})),nd=["q","h","f"];function id(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 Zc;const i=t>n?t/n:n/t;if(Math.abs(i-16/9)<Math.abs(i-4/3))return Yc;return Xc}(e,t,n);let{encoding:a}=r[0];const s=Math.max(t,n);for(let e=0;e<r.length;e+=1){const t=r[e];if(a=t.encoding,t.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),Wi.debug("using video encoding",s));const l=s.maxFramerate,u=new Ha(t,n,s.maxBitrate,s.maxFramerate,s.priority);if(c&&Cs(d)){const e=new cd(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const n=ka();if(Ms()||Ns()||"Chrome"===(null==n?void 0:n.name)&&js(null==n?void 0:n.version,"113")<0){const i="h"==e.suffix?2:3,r=function(e){return e||(e=ka()),"Safari"===(null==e?void 0:e.name)&&js(e.version,"18.3")>0||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&js(e.osVersion,"18.3")>0}(n);for(let n=0;n<e.spatial;n+=1)t.push({rid:nd[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),Wi.debug("using svc encoding",{encodings:t}),t}if(!o)return[s];let h,p;if(h=e?null!==(r=od(null==i?void 0:i.screenShareSimulcastLayers))&&void 0!==r?r:ad(e,u):null!==(a=od(null==i?void 0:i.videoSimulcastLayers))&&void 0!==a?a:ad(e,u),h.length>0){const e=h[0];h.length>1&&([,p]=h);const i=Math.max(t,n);if(i>=960&&p)return sd(t,n,[e,p,u],l);if(i>=480)return sd(t,n,[e,u],l)}return sd(t,n,[u])}function rd(e,t,n){var i,r,a,s;if(!n.backupCodec||!0===n.backupCodec||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&Wi.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===gs.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1);return id(e.source===gs.Source.ScreenShare,c,d,n)}function ad(e,t){if(e)return td(t);const{width:n,height:i}=t,r=n>i?n/i:i/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?$c:ed}function sd(e,t,n,i){const r=[];if(n.forEach(((n,a)=>{if(a>=nd.length)return;const s=Math.min(e,t),o={rid:nd[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=ka(),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)})),Ns()&&"ios"===Fs()){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,Wi.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Wi.info('Setting framerate of encoding "'.concat(null!==(i=n.rid)&&void 0!==i?i:"",'" to ').concat(e)),n.maxFramerate=e)}))}return r}function od(e){if(e)return e.sort(((e,t)=>{const{encoding:n}=e,{encoding:i}=t;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 cd{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 dd extends Gc{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(t,n){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],a=arguments.length>3?arguments[3]:void 0;super(t,gs.Kind.Video,n,i,a),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>Zi(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let t;try{t=yield this.getSenderStats()}catch(e){return void this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}const n=new Map(t.map((e=>[e.rid,e]))),i=t.some((e=>"cpu"===e.qualityLimitationReason));if(i!==this.isCpuConstrained&&(this.isCpuConstrained=i,this.isCpuConstrained&&this.emit(e.TrackEvent.CpuConstrained)),this.prevStats){let e=0;n.forEach(((t,n)=>{var i;const r=null===(i=this.prevStats)||void 0===i?void 0:i.get(n);e+=Fo(t,r)})),this._currentBitrate=e}this.prevStats=n})),this.senderLock=new r}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!As())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()}),Uo))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return Zi(this,void 0,void 0,(function*(){var t,n,i,r,a;yield e.pauseUpstream.call(this);try{for(var s,o=!0,c=nr(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(e){n={error:e}}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 Zi(this,void 0,void 0,(function*(){var t,n,i,r,a;yield e.resumeUpstream.call(this);try{for(var s,o=!0,c=nr(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(e){n={error:e}}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 Zi(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!==gs.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 Zi(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==gs.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 Zi(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 li({quality:i,enabled:i<=t}));this.log.debug("setting publishing quality. max quality ".concat(t),this.logContext),this.setPublishingLayers(Cs(this.codec),n)}restartTrack(e){return Zi(this,void 0,void 0,(function*(){var t,n,i,r,a;let s;if(e){const t=ns({video:e});"boolean"!=typeof t.video&&(s=t.video)}yield this.restart(s),this.isCpuConstrained=!1;try{for(var o,c=!0,d=nr(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(e){n={error:e}}finally{try{c||t||!(i=d.return)||(yield i.call(d))}finally{if(n)throw n.error}}yield this.onSenderTrackSwapped()}))}onSenderTrackSwapped(){return Zi(this,void 0,void 0,(function*(){yield this.refreshSenderEncodings()}))}refreshSenderEncodings(){return Zi(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(e){return void this.log.warn("could not determine new track dimensions, skipping encoding recompute",Object.assign(Object.assign({},this.logContext),{error:e}))}if(this.lastEncodedDimensions&&this.lastEncodedDimensions.width===t.width&&this.lastEncodedDimensions.height===t.height)return;const n=id(this.source===gs.Source.ScreenShare,t.width,t.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,n),this.encodings=n,this.lastEncodedDimensions=t;for(const[t,n]of this.simulcastCodecs){if(!n.sender||"closed"===(null===(e=n.sender.transport)||void 0===e?void 0:e.state))continue;if(!Ja(t))continue;const i=rd(this,t,Object.assign({},this.publishOptions));i&&(yield this.applyEncodingsToSender(n.sender,i),n.encodings=i)}}catch(e){this.log.warn("failed to apply recomputed encodings",Object.assign(Object.assign({},this.logContext),{error:e}))}finally{t()}}))}applyEncodingsToSender(e,t){return Zi(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 Zi(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=nr(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(e){a={error:e}}finally{try{u||r||!(s=h.return)||(yield s.call(h))}finally{if(a)throw a.error}}}()}))}setDegradationPreference(e){return Zi(this,void 0,void 0,(function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},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){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}setPublishingCodecs(e){return Zi(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(Cs(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,n=nr(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 ld(t.sender,t.encodings,e.qualities,this.senderLock,Cs(e.codec),this.log,this.logContext));else for(const t of e.qualities)if(t.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(Cs(e.codec),e.qualities)}}catch(e){a={error:e}}finally{try{t||r||!(s=n.return)||(yield s.call(n))}finally{if(a)throw a.error}}return c}))}setPublishingLayers(e,t){return Zi(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 ld(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))}))}prioritizePerformance(){return Zi(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&&Cs(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(e){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Zi(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Os()&&this.isInBackground&&this.source===gs.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function ld(e,t,n,i,r,a,s){return Zi(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(),{encodings:o}=i;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=ud(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),Ps()&&(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 ud(t){switch(t){case"f":default:return e.VideoQuality.HIGH;case"h":return e.VideoQuality.MEDIUM;case"q":return e.VideoQuality.LOW}}function hd(t,n,i,r){if(!i)return[new yt({quality:e.VideoQuality.HIGH,width:t,height:n,bitrate:0,ssrc:0})];if(r){const r=i[0].scalabilityMode,a=new cd(r),s=[],o="h"==a.suffix?1.5:2,c="h"==a.suffix?2:3;for(let r=0;r<a.spatial;r+=1)s.push(new yt({quality:Math.min(e.VideoQuality.HIGH,a.spatial-1)-r,width:Math.ceil(t/Math.pow(o,r)),height:Math.ceil(n/Math.pow(o,r)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(c,r)):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=ud(null!==(r=e.rid)&&void 0!==r?r:"");return new yt({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 pd="_lossy",md="_reliable",gd="_data_track",vd="leave-reconnect";var fd,kd;!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"}(fd||(fd={})),function(e){e[e.RELIABLE=0]="RELIABLE",e[e.LOSSY=1]="LOSSY",e[e.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY"}(kd||(kd={}));class yd extends ar.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}constructor(t){var n;super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=Vc.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=fd.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=Wi,this.reliableDataSequence=1,this.reliableMessageBuffer=new gc,this.reliableReceivedState=new vc(3e4),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.bufferStatusLowClosingFuture=new Xs,this.handleDataChannel=e=>Zi(this,[e],void 0,(function(e){var t=this;let{channel:n}=e;return function*(){if(!n)return;let e;if(n.label===md)t.reliableDCSub=n,e=t.handleDataMessage;else if(n.label===pd)t.lossyDCSub=n,e=t.handleDataMessage;else{if(n.label!==gd)return;t.dataTrackDCSub=n,e=t.handleDataTrackMessage}t.log.debug("on data channel ".concat(n.id,", ").concat(n.label)),n.onmessage=e}()})),this.handleDataMessage=t=>Zi(this,void 0,void 0,(function*(){var n,i,r,a,s;const o=yield this.dataProcessLock.lock();try{let o;if(t.data instanceof ArrayBuffer)o=t.data;else{if(!(t.data instanceof Blob))return void this.log.error("unsupported data type",{data:t.data});o=yield t.data.arrayBuffer()}const c=Tt.fromBinary(new Uint8Array(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=Ct.fromBinary(t.payload),i=new Tt({value:n.value,participantIdentity:c.participantIdentity,participantSid:c.participantSid});"user"===(null===(a=i.value)||void 0===a?void 0:a.case)&&bd(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)&&bd(c,c.value.value),this.emit(e.EngineEvent.DataPacketReceived,c,mt.NONE)}finally{o()}})),this.handleDataTrackMessage=e=>Zi(this,void 0,void 0,(function*(){let t;if(e.data instanceof ArrayBuffer)t=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",{data:e.data});t=yield e.data.arrayBuffer()}this.emit("dataTrackPacketReceived",new Uint8Array(t))})),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:n}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),{error:n})}else this.log.error("Unknown DataChannel error on ".concat(t),{event:e})},this.handleBufferedAmountLow=e=>{this.updateAndEmitDCBufferStatus(e)},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()},r=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:r,retryCount:this.reconnectAttempts});null!==a?(t===vd&&(a=0),this.log.debug("reconnecting in ".concat(a,"ms")),this.clearReconnectTimeout(),this.token&&this.emit(e.EngineEvent.TokenRefreshed,this.token),this.reconnectTimeout=Va.setTimeout((()=>this.attemptReconnect(n).finally((()=>this.reconnectTimeout=void 0))),a)):i(r)},this.waitForRestarted=()=>new Promise(((t,n)=>{this.pcState===fd.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.updateAndEmitDCBufferStatus=t=>{if(t===kd.RELIABLE){const e=this.dataChannelForKind(t);e&&this.reliableMessageBuffer.alignBufferedAmount(e.bufferedAmount)}const n=this.isBufferStatusLow(t);void 0!==n&&n!==this.dcBufferStatus.get(t)&&(this.dcBufferStatus.set(t,n),this.emit(e.EngineEvent.DCBufferStatusChanged,n,t))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>Zi(this,void 0,void 0,(function*(){if(!this.url)return;(yield fetch(eo(this.url),{method:"HEAD"}).then((e=>e.ok)).catch((()=>!1)))&&(this.log.info("detected network reconnected"),(this.client.currentState===uc.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===uc.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(it.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))})),this.handleBrowserOffline=()=>Zi(this,void 0,void 0,(function*(){if(this.url)try{yield Promise.race([fetch(eo(this.url),{method:"HEAD"}),ys(4e3).then((()=>Promise.reject()))])}catch(e){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}})),this.log=zi(null!==(n=t.loggerName)&&void 0!==n?n:e.LoggerNames.Engine,(()=>this.logContext)),this.loggerOptions={loggerName:t.loggerName,loggerContextCb:()=>this.logContext},this.client=new hc(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new r,this.dataProcessLock=new r,this.dcBufferStatus=new Map([[kd.RELIABLE,!0],[kd.LOSSY,!0],[kd.DATA_TRACK_LOSSY,!0]]),this.client.onParticipantUpdate=t=>this.emit(e.EngineEvent.ParticipantUpdate,t),this.client.onConnectionQuality=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),this.on(e.EngineEvent.Closing,(()=>{var e,t;null===(t=(e=this.bufferStatusLowClosingFuture).reject)||void 0===t||t.call(e,new La("engine closed"))})),this.bufferStatusLowClosingFuture.promise.catch((()=>{}))}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,n,i,r){return Zi(this,arguments,void 0,(function(t,n,i,r){var a=this;let s=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){var o,c,d;a._isNewlyCreated=!1,a.url=t,a.token=n,a.signalOpts=i,a.maxJoinAttempts=i.maxRetries;try{let l;if(a.joinAttempts+=1,a.setupSignalClientCallbacks(),!s&&mo()){a.pcManager||(yield a.configure(),a.createDataChannels(),a.addMediaSections(3,3));const e=yield null===(o=a.pcManager)||void 0===o?void 0:o.publisher.createInitialOffer();e&&(l=mc(e.offer,e.offerId))}if(null==r?void 0:r.aborted)throw Oa.cancelled("Connection aborted");if(!s&&a.shouldFailOnV1Path)throw a.shouldFailOnV1Path=!1,Oa.serviceNotFound("Simulated v1 path failure","v0-rtc");const u=yield a.client.join(t,n,i,r,s,l);a._isClosed=!1,a.latestJoinResponse=u,a.participantSid=null===(c=u.participant)||void 0===c?void 0:c.sid,a.subscriberPrimary=u.subscriberPrimary,!s&&mo()?null===(d=a.pcManager)||void 0===d||d.updateConfiguration(a.makeRTCConfiguration(u)):(a.pcManager||(yield a.configure(u,!s)),a.subscriberPrimary&&!u.fastPublish||a.negotiate().catch((e=>{a.log.error(e)}))),a.registerOnLineListener(),a.clientConfiguration=u.clientConfiguration,a.emit(e.EngineEvent.SignalConnected,u);let h=u.serverInfo;return h||(h={version:u.serverVersion,region:u.serverRegion}),a.log.info("connected to Livekit Server ".concat(Object.entries(h).map((e=>{let[t,n]=e;return"".concat(t,": ").concat(n)})).join(", "))),{joinResponse:u,serverInfo:h}}catch(o){if(o instanceof Oa)if(o.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,n,i,r,s)}else if(o.reason===e.ConnectionErrorReason.ServiceNotFound)return a.log.warn("Initial connection failed: ".concat(o.message," – Retrying")),a.pcManager&&(a.pcManager.onStateChange=void 0,yield a.cleanupPeerConnections()),a.join(t,n,i,r,!0);throw o}}()}))}close(){return Zi(this,void 0,void 0,(function*(){const t=yield this.closingLock.lock();if(this.isClosed)t();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(e.EngineEvent.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{t()}}))}cleanupPeerConnections(){return Zi(this,void 0,void 0,(function*(){var e;yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;const t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),t(this.dataTrackDC),t(this.dataTrackDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.dataTrackDC=void 0,this.dataTrackDCSub=void 0,this.reliableMessageBuffer=new gc,this.reliableDataSequence=1,this.reliableReceivedState.clear()}))}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return Zi(this,void 0,void 0,(function*(){yield this.client.close(),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 Na("a track with the same ID has already been published");return new Promise(((t,n)=>{const i=setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],n(Oa.timeout("publication of local track timed out, no response from server"))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(i),t(e)},reject:()=>{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{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",{error:e})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return Zi(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 Zi(this,void 0,void 0,(function*(){var i;if(!this.pcManager||this.pcManager.currentState===Hc.NEW){if(t){this.participantSid=null===(i=t.participant)||void 0===i?void 0:i.sid;const e=this.makeRTCConfiguration(t);this.pcManager=new Wc(n?"publisher-only":t.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,e)}else{const e=this.makeRTCConfiguration();this.pcManager=new Wc("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)=>Zi(this,void 0,void 0,(function*(){if(this.log.debug("primary PC state changed ".concat(t)),["closed","disconnected","failed"].includes(n)&&(this.publisherConnectionPromise=void 0),t===Hc.CONNECTED){const t=this.pcState===fd.New;this.pcState=fd.Connected,t&&this.emit(e.EngineEvent.Connected,this.latestJoinResponse)}else t===Hc.FAILED&&(this.pcState!==fd.Connected&&this.pcState!==fd.Reconnecting||(this.pcState=fd.Disconnected,this.handleDisconnect("peerconnection failed","failed"===i?it.RR_SUBSCRIBER_FAILED:it.RR_PUBLISHER_FAILED)));const r=this.client.isDisconnected||this.client.currentState===uc.RECONNECTING,a=[Hc.FAILED,Hc.CLOSING,Hc.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)=>Zi(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)=>Zi(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{resolve:n}=this.pendingTrackResolvers[e.cid];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",it.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=t=>{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 ei.DISCONNECT:this.emit(e.EngineEvent.Disconnected,null==t?void 0:t.reason),this.close();break;case ei.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(vd);break;case ei.RESUME:this.handleDisconnect(vd)}}}makeRTCConfiguration(e){var t,n;const i=Object.assign({},this.rtcConfig);if(((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)||(null===(n=this.options.packetTrailer)||void 0===n?void 0:n.worker)&&!Ao())&&Ro()&&(this.log.debug("E2EE - setting up transports with insertable streams"),i.encodedInsertableStreams=!0),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",!e)return i;if(e.iceServers&&!i.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)})),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===tt.ENABLED&&(i.iceTransportPolicy="relay"),i}addMediaSections(e,t){var n,i;const r={direction:"recvonly"};for(let t=0;t<e;t++)null===(n=this.pcManager)||void 0===n||n.addPublisherTransceiverOfKind("audio",r);for(let e=0;e<t;e++)null===(i=this.pcManager)||void 0===i||i.addPublisherTransceiverOfKind("video",r)}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.dataTrackDC&&(this.dataTrackDC.onmessage=null,this.dataTrackDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(pd,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(md,{ordered:!0}),this.dataTrackDC=this.pcManager.createPublisherDataChannel(gd,{ordered:!1,maxRetransmits:0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.dataTrackDC.onmessage=this.handleDataTrackMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.dataTrackDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.dataTrackDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(kd.LOSSY),this.reliableDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(kd.RELIABLE),this.dataTrackDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(kd.DATA_TRACK_LOSSY),this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval((()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(kd.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,8192),262144)}}),1e3))}createSender(e,t,n){return Zi(this,void 0,void 0,(function*(){let i;if(bs())i=yield this.createTransceiverRTCRtpSender(e,t,n);else{if(!Ts())throw new La("Required webRTC APIs not supported on this device");this.log.warn("using add-track fallback"),i=yield this.createRTCRtpSender(e.mediaStreamTrack)}return this.setupPacketTrailerSender(i,t),i}))}createSimulcastSender(e,t,n,i){return Zi(this,void 0,void 0,(function*(){let r;if(bs())r=yield this.createSimulcastTransceiverSender(e,t,n,i);else{if(!Ts())throw new La("Cannot stream on this device");this.log.debug("using add-track fallback"),r=yield this.createRTCRtpSender(e.mediaStreamTrack)}return r&&this.setupPacketTrailerSender(r,n),r}))}setupPacketTrailerSender(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n,i;if(!(null===(n=this.options.packetTrailer)||void 0===n?void 0:n.worker)||(null===(i=this.signalOpts)||void 0===i?void 0:i.e2eeEnabled))return;const r=t.packetTrailer,a=xo(r);if(Ao())return void(a&&(e.transform=new RTCRtpScriptTransform(this.options.packetTrailer.worker,{kind:"encode",packetTrailer:r})));if(!No(this.options.packetTrailer)||!("createEncodedStreams"in e))return void(a&&this.log.warn("packet trailer transform not supported; skipping write",this.logContext));const{readable:s,writable:o}=e.createEncodedStreams();a?this.options.packetTrailer.worker.postMessage({kind:"encode",data:{readableStream:s,writableStream:o,packetTrailer:r}},[s,o]):s.pipeTo(o)}createTransceiverRTCRtpSender(e,t,n){return Zi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new La("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),so(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 Zi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new La("publisher is closed");const r={direction:"sendonly"};i&&(r.sendEncodings=i);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,a.sender),a.sender}))}createRTCRtpSender(e){return Zi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new La("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}attemptReconnect(t){return Zi(this,void 0,void 0,(function*(){var n,i,r;if(!this._isClosed)if(this.attemptingReconnect)this.log.warn("already attempting reconnect, returning early");else{(null===(n=this.clientConfiguration)||void 0===n?void 0:n.resumeConnection)!==tt.DISABLED&&(null!==(r=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==r?r:Hc.NEW)!==Hc.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(t),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(t){this.reconnectAttempts+=1;let n=!0;t instanceof La?(this.log.debug("received unrecoverable error",{error:t}),n=!1):t instanceof qa||(this.fullReconnectOnNext=!0),n?this.handleDisconnect("reconnect",it.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())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn("encountered error in reconnect policy",{error:e})}return null}restartConnection(t){return Zi(this,void 0,void 0,(function*(){var n,i,r;try{if(!this.url||!this.token)throw new La("could not reconnect, url or token not saved");let i;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 qa;i=(yield this.join(null!=t?t:this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(t){if(t instanceof Oa&&t.reason===e.ConnectionErrorReason.NotAllowed)throw new La("could not reconnect, token might be expired");throw new qa}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(e.EngineEvent.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==uc.CONNECTED)throw new qa("Signal connection got severed during reconnect");null===(n=this.regionStrategy)||void 0===n||n.resetAttempts(),this.emit(e.EngineEvent.Restarted)}catch(e){const t=yield null===(i=this.regionStrategy)||void 0===i?void 0:i.getNextUrl();if(t)return void(yield this.restartConnection(t));throw null===(r=this.regionStrategy)||void 0===r||r.resetAttempts(),e}}))}resumeConnection(t){return Zi(this,void 0,void 0,(function*(){var n;if(!this.url||!this.token)throw new La("could not reconnect, url or token not saved");if(!this.pcManager)throw new La("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(e.EngineEvent.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,t)}catch(t){let n="";if(t instanceof Error&&(n=t.message,this.log.error(t.message,{error:t})),t instanceof Oa&&t.reason===e.ConnectionErrorReason.NotAllowed)throw new La("could not reconnect, token might be expired");if(t instanceof Oa&&t.reason===e.ConnectionErrorReason.LeaveRequest)throw t;throw new qa(n)}if(this.emit(e.EngineEvent.SignalResumed),i){const e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response");if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==uc.CONNECTED)throw new qa("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(n=this.reliableDC)||void 0===n?void 0:n.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),(null==i?void 0:i.lastMessageSeq)&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(e.EngineEvent.Resumed)}))}waitForPCInitialConnection(e,t){return Zi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new La("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)}))}waitForPCReconnected(){return Zi(this,void 0,void 0,(function*(){this.pcState=fd.Reconnecting,this.log.debug("waiting for peer connection to reconnect");try{if(yield ys(2e3),!this.pcManager)throw new La("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=fd.Connected}catch(e){throw this.pcState=fd.Disconnected,Oa.internal("could not establish PC connection, ".concat(e.message))}}))}publishRpcAck(e,t){return Zi(this,void 0,void 0,(function*(){const n=new Tt({destinationIdentities:[e],kind:St.RELIABLE,value:{case:"rpcAck",value:new At({requestId:t})}});yield this.sendDataPacket(n,kd.RELIABLE)}))}sendDataPacket(e,t){return Zi(this,void 0,void 0,(function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const t=Mo(e);if(t){const n=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:"encryptedPacket",value:new Et({encryptedValue:n.payload,iv:n.iv,keyIndex:n.keyIndex})}}}t===kd.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const n=e.toBinary();switch(t){case kd.LOSSY:case kd.DATA_TRACK_LOSSY:return this.sendLossyBytes(n,t);case kd.RELIABLE:const i=this.dataChannelForKind(t);if(i){if(yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:n,sequence:e.sequence}),this.attemptingReconnect)return;i.send(n)}this.updateAndEmitDCBufferStatus(t)}}))}sendLossyBytes(e,t){return Zi(this,arguments,void 0,(function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"drop";return function*(){yield n.ensurePublisherConnected(t);const r=n.dataChannelForKind(t);if(r){if(!n.isBufferStatusLow(t))switch(i){case"wait":yield n.waitForBufferStatusLow(t);break;case"drop":return n.lossyDataDropCount+=1,void(n.lossyDataDropCount%100==0&&n.log.warn("dropping lossy data channel messages, total dropped: ".concat(n.lossyDataDropCount)))}if(n.lossyDataStatCurrentBytes+=e.byteLength,n.attemptingReconnect)return;r.send(e)}n.updateAndEmitDCBufferStatus(t)}()}))}resendReliableMessagesForResume(e){return Zi(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(kd.RELIABLE);const t=this.dataChannelForKind(kd.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach((e=>{t.send(e.data)}))),this.updateAndEmitDCBufferStatus(kd.RELIABLE)}))}waitForBufferStatusLow(e){return Zi(this,void 0,void 0,(function*(){return new ga(((t,n)=>Zi(this,void 0,void 0,(function*(){if(this.isClosed&&n(new La("engine closed")),this.isBufferStatusLow(e))t();else{const i=this.dataChannelForKind(e);if(!i)return void n(new La("DataChannel not found, kind: ".concat(e)));this.bufferStatusLowClosingFuture.promise.catch((e=>n(e))),i.addEventListener("bufferedamountlow",(()=>t()),{once:!0})}}))))}))}ensureDataTransportConnected(e){return Zi(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 La("PC manager is closed");const r=n?t.pcManager.subscriber:t.pcManager.publisher,a=n?"Subscriber":"Publisher";if(!r)throw Oa.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 ys(50)}throw Oa.internal("could not establish ".concat(a," connection, state: ").concat(r.getICEConnectionState()))}()}))}ensurePublisherConnected(e){return Zi(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){if(!this.pcManager)return!1;return!![Hc.CONNECTING,Hc.CONNECTED].includes(this.pcManager.currentState)&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return Zi(this,void 0,void 0,(function*(){return new ga(((t,n)=>Zi(this,void 0,void 0,(function*(){if(!this.pcManager)return void n(new Ua("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.dataTrackDC||this.createDataChannels();const i=new AbortController,r=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing"),t()};this.isClosed&&n(new Ua("cannot negotiate on closed engine")),this.on(e.EngineEvent.Closing,r),this.on(e.EngineEvent.Restarting,r),this.pcManager.publisher.once(Oc,(t=>{const n=new Map;t.forEach((e=>{const t=e.codec.toLowerCase();Zs(t)&&n.set(e.payload,t)})),this.emit(e.EngineEvent.RTPVideoMapUpdate,n)}));try{yield this.pcManager.negotiate(i),t()}catch(e){if(i.signal.aborted)return void t();e instanceof Ua&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",it.RR_UNKNOWN),e instanceof Error?n(e):n(new Error(String(e)))}finally{this.off(e.EngineEvent.Closing,r),this.off(e.EngineEvent.Restarting,r)}}))))}))}dataChannelForKind(e,t){switch(e){case kd.RELIABLE:return t?this.reliableDCSub:this.reliableDC;case kd.LOSSY:return t?this.lossyDCSub:this.lossyDC;case kd.DATA_TRACK_LOSSY:return t?this.dataTrackDCSub:this.dataTrackDC}}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 ki({answer:"publisher-only"===this.pcManager.mode?c?mc({sdp:c.sdp,type:c.type}):void 0:l?mc({sdp:l.sdp,type:l.type}):void 0,offer:"publisher-only"===this.pcManager.mode?o?mc({sdp:o.sdp,type:o.type}):void 0:d?mc({sdp:d.sdp,type:d.type}):void 0,subscription:new Jn({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:ds(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:p,datachannelReceiveStates:this.reliableReceivedState.map(((e,t)=>new yi({publisherSid:t,lastSeq:e}))),publishDataTracks:n.map((e=>new Nn({info:sc.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 bi({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(kd.LOSSY),Rn.PUBLISHER),t(this.dataChannelForKind(kd.RELIABLE),Rn.PUBLISHER),t(this.dataChannelForKind(kd.LOSSY,!0),Rn.SUBSCRIBER),t(this.dataChannelForKind(kd.RELIABLE,!0),Rn.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Va.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){As()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){As()&&(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=>{let[t]=e;return t===n}));if(e)return e[1]}}}function bd(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 Td=5e3;class Sd{static fetchRegionSettings(e,t,n){return Zi(this,void 0,void 0,(function*(){const i=yield Sd.fetchLock.lock();try{const i=yield fetch("".concat(function(e){return"".concat(e.protocol.replace("ws","http"),"//").concat(e.host,"/settings")}(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:n});if(i.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)}}(i.headers),t=e?1e3*e:Td;return{regionSettings:yield i.json(),updatedAtInMs:Date.now(),maxAgeInMs:t}}throw 401===i.status?Oa.notAllowed("Could not fetch region settings: ".concat(i.statusText),i.status):Oa.internal("Could not fetch region settings: ".concat(i.statusText))}catch(e){throw e instanceof Oa?e:(null==n?void 0:n.aborted)?Oa.cancelled("Region fetching was aborted"):Oa.serverUnreachable("Could not fetch region settings, ".concat(e instanceof Error?"".concat(e.name,": ").concat(e.message):e))}finally{i()}}))}static scheduleRefetch(t,n,i){return Zi(this,void 0,void 0,(function*(){const r=Sd.settingsTimeouts.get(t.hostname);clearTimeout(r),Sd.settingsTimeouts.set(t.hostname,setTimeout((()=>Zi(this,void 0,void 0,(function*(){try{const e=yield Sd.fetchRegionSettings(t,n);Sd.updateCachedRegionSettings(t,n,e)}catch(r){if(r instanceof Oa&&r.reason===e.ConnectionErrorReason.NotAllowed)return void Wi.debug("token is not valid, cancelling auto region refresh");Wi.debug("auto refetching of region settings failed",{error:r}),Sd.scheduleRefetch(t,n,i)}}))),i))}))}static updateCachedRegionSettings(e,t,n){Sd.cache.set(e.hostname,n),Sd.scheduleRefetch(e,t,n.maxAgeInMs)}static stopRefetch(e){const t=Sd.settingsTimeouts.get(e);t&&(clearTimeout(t),Sd.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=Sd.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout((()=>{const t=Sd.connectionTrackers.get(e);t&&0===t.connectionCount&&(Wi.debug("stopping region refetch after disconnect delay",{hostname:e}),Sd.stopRefetch(e)),t&&(t.cleanupTimeout=void 0)}),3e4))}static cancelCleanup(e){const t=Sd.connectionTrackers.get(e);(null==t?void 0:t.cleanupTimeout)&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=Sd.connectionTrackers.get(e);t||(t={connectionCount:0},Sd.connectionTrackers.set(e,t)),t.connectionCount++,Sd.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=Sd.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),0===t.connectionCount&&Sd.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=Sd.cache.get(n.hostname);Sd.scheduleRefetch(this.serverUrl,this.token,null!==(t=null==i?void 0:i.maxAgeInMs)&&void 0!==t?t:Td)}isCloud(){return xs(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return Zi(this,void 0,void 0,(function*(){return Sd.fetchRegionSettings(this.serverUrl,this.token,e)}))}getNextBestRegionUrl(e){return Zi(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=Sd.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),Sd.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),Wi.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){Sd.updateCachedRegionSettings(this.serverUrl,this.token,e)}}Sd.cache=new Map,Sd.settingsTimeouts=new Map,Sd.connectionTrackers=new Map,Sd.fetchLock=new r;class Ed{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 ja("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 ja("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 Cd extends Ed{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:()=>Zi(this,void 0,void 0,(function*(){try{const t=this.signal;if(null==t?void 0:t.aborted)throw t.reason;const n=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 n.done?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(n.value),{done:!1,value:n.value.content})}catch(e){throw t(),e}})),return(){return Zi(this,void 0,void 0,(function*(){return t(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Zi(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=nr(o);!(n=(c=yield l.next()).done);d=!0){a=c.value,d=!1;const e=a;s.add(e)}}catch(e){i={error:e}}finally{try{d||n||!(r=l.return)||(yield r.call(l))}finally{if(i)throw i.error}}return Array.from(s)}()}))}}class wd extends Ed{constructor(e,t,n){super(e,t,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=no(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",{fatal:!0}),i=this.signal,r=()=>{t.releaseLock(),this.signal=void 0};return{next:()=>Zi(this,void 0,void 0,(function*(){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),{done:!0,value:void 0};{let t;this.handleChunkReceived(r.value);try{t=n.decode(r.value.content)}catch(t){throw new ja("Cannot decode datastream chunk ".concat(r.value.chunkIndex," as text: ").concat(t),e.DataStreamErrorReason.DecodeFailed)}return{done:!1,value:t}}}catch(e){throw r(),e}})),return(){return Zi(this,void 0,void 0,(function*(){return r(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Zi(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=nr(o);!(n=(c=yield l.next()).done);d=!0){a=c.value,d=!1;s+=a}}catch(e){i={error:e}}finally{try{d||n||!(r=l.return)||(yield r.call(l))}finally{if(i)throw i.error}}return s}()}))}}class Rd{constructor(){this.log=Wi,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[]}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){const e=this.bufferedPackets;this.bufferedPackets=[];for(const{packet:t,encryptionType:n}of e)this.handleDataStreamPacket(t,n)}registerTextStreamHandler(t,n){if(this.textStreamHandlers.has(t))throw new ja('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 ja('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 r=new ja("Participant ".concat(t," unexpectedly disconnected in the middle of sending data"),e.DataStreamErrorReason.AbnormalEnd);for(const[e,t]of i)t.controller.error(r),this.byteStreamControllers.delete(e);for(const[e,t]of n)t.controller.error(r),this.textStreamControllers.delete(e)}}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;if("byteHeader"===t.contentHeader.case){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:no(t.timestamp),attributes:t.attributes,encryptionType:i},c=new ReadableStream({start:i=>{if(s=i,this.textStreamControllers.has(t.streamId))throw new ja("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})}});a(new Cd(o,c,no(t.totalLength)),{identity:n})}else if("textHeader"===t.contentHeader.case){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},o=new ReadableStream({start:i=>{if(a=i,this.textStreamControllers.has(t.streamId))throw new ja("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})}});r(new wd(s,o,no(t.totalLength)),{identity:n})}}handleStreamChunk(t,n){const i=this.byteStreamControllers.get(t.streamId);i&&(i.info.encryptionType!==n?(i.controller.error(new ja("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 ja("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 ja("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),i.controller.close(),this.textStreamControllers.delete(t.streamId)));const r=this.byteStreamControllers.get(t.streamId);r&&(r.info.encryptionType!==n?r.controller.error(new ja("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),r.controller.close()),this.byteStreamControllers.delete(t.streamId))}}class Pd{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 Zi(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 Id extends Pd{}class Dd extends Pd{}class Md{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return Zi(this,void 0,void 0,(function*(){var n;const i=crypto.randomUUID(),r=(new TextEncoder).encode(e).byteLength,a=null===(n=null==t?void 0:t.attachments)||void 0===n?void 0:n.map((()=>crypto.randomUUID())),s=new Array(a?a.length+1:1).fill(0),o=(e,n)=>{var i;s[n]=e;const r=s.reduce(((e,t)=>e+t),0);null===(i=null==t?void 0:t.onProgress)||void 0===i||i.call(t,r)},c=yield this.streamText({streamId:i,totalSize:r,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:a,attributes:null==t?void 0:t.attributes});return yield c.write(e),o(1,0),yield c.close(),(null==t?void 0:t.attachments)&&a&&(yield Promise.all(t.attachments.map(((e,n)=>Zi(this,void 0,void 0,(function*(){return this._sendFile(a[n],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{o(e,n+1)}})})))))),c.info}))}streamText(t){return Zi(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={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)?mt.GCM:mt.NONE,attachedStreamIds:null==t?void 0:t.attachedStreamIds},o=new Qt({streamId:a,mimeType:s.mimeType,topic:s.topic,timestamp:io(s.timestamp),totalLength:io(s.size),attributes:s.attributes,contentHeader:{case:"textHeader",value:new Jt({version:null==t?void 0:t.version,attachedStreamIds:s.attachedStreamIds,replyToStreamId:null==t?void 0:t.replyToStreamId,operationType:"update"===(null==t?void 0:t.type)?zt.UPDATE:zt.CREATE})}}),c=null==t?void 0:t.destinationIdentities,d=new Tt({destinationIdentities:c,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(d,kd.RELIABLE);let l=0;const u=this.engine,h=new WritableStream({write(e){return Zi(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,15e3)){const e=new Yt({content:t,streamId:a,chunkIndex:io(l)}),n=new Tt({destinationIdentities:c,value:{case:"streamChunk",value:e}});yield u.sendDataPacket(n,kd.RELIABLE),l+=1}}))},close(){return Zi(this,void 0,void 0,(function*(){const e=new Xt({streamId:a}),t=new Tt({destinationIdentities:c,value:{case:"streamTrailer",value:e}});yield u.sendDataPacket(t,kd.RELIABLE)}))},abort(e){console.log("Sink error:",e)}});let p=()=>Zi(this,void 0,void 0,(function*(){yield m.close()}));u.once(e.EngineEvent.Closing,p);const m=new Id(h,s,(()=>this.engine.off(e.EngineEvent.Closing,p)));return m}))}sendFile(e,t){return Zi(this,void 0,void 0,(function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}}))}_sendFile(e,t,n){return Zi(this,void 0,void 0,(function*(){var i;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(i=null==n?void 0:n.mimeType)&&void 0!==i?i:t.type,topic:null==n?void 0:n.topic,destinationIdentities:null==n?void 0:n.destinationIdentities}),a=t.stream().getReader();for(;;){const{done:e,value:t}=yield a.read();if(e)break;yield r.write(t)}return yield r.close(),r.info}))}streamBytes(e){return Zi(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)?mt.GCM:mt.NONE},l=new Qt({totalLength:io(d.size),mimeType:d.mimeType,streamId:o,topic:d.topic,timestamp:io(Date.now()),attributes:d.attributes,contentHeader:{case:"byteHeader",value:new Gt({name:d.name})}}),u=new Tt({destinationIdentities:c,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(u,kd.RELIABLE);let h=0;const p=new r,m=this.engine,g=this.log,v=new WritableStream({write(e){return Zi(this,void 0,void 0,(function*(){const t=yield p.lock();let n=0;try{for(;n<e.byteLength;){const t=e.slice(n,n+15e3),i=new Tt({destinationIdentities:c,value:{case:"streamChunk",value:new Yt({content:t,streamId:o,chunkIndex:io(h)})}});yield m.sendDataPacket(i,kd.RELIABLE),h+=1,n+=t.byteLength}}finally{t()}}))},close(){return Zi(this,void 0,void 0,(function*(){const e=new Xt({streamId:o}),t=new Tt({destinationIdentities:c,value:{case:"streamTrailer",value:e}});yield m.sendDataPacket(t,kd.RELIABLE)}))},abort(e){g.error("Sink error:",e)}});return new Dd(v,d)}))}}function _d(e){if(0===e.length){return(new AbortController).signal}if(1===e.length)return e[0];for(const t of e)if(t.aborted)return t;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 Od(e){const t=new AbortController;return setTimeout((()=>{t.abort(new DOMException("signal timed out after ".concat(e," ms"),"TimeoutError"))}),e),t.signal}var Ad,Nd,xd;!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"}(Ad||(Ad={}));class Ld extends Ca{constructor(e,t,n){super(19,e,n),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=Ad[t]}static tooShort(){return new Ld("Too short to contain a valid header",Ad.TooShort)}static headerOverrun(){return new Ld("Header exceeds total packet length",Ad.HeaderOverrun)}static missingExtWords(){return new Ld("Extension word indicator is missing",Ad.MissingExtWords)}static unsupportedVersion(e){return new Ld("Unsupported version ".concat(e),Ad.UnsupportedVersion)}static invalidHandle(e){return new Ld("invalid track handle: ".concat(e.message),Ad.InvalidHandle,{cause:e})}static malformedExt(e){return new Ld("Extension with tag ".concat(e," is malformed"),Ad.MalformedExt)}}!function(e){e[e.TooSmallForHeader=0]="TooSmallForHeader",e[e.TooSmallForPayload=1]="TooSmallForPayload"}(Nd||(Nd={}));class Ud extends Ca{constructor(e,t,n){super(19,e,n),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=Nd[t]}static tooSmallForHeader(){return new Ud("Buffer cannot fit header",Nd.TooSmallForHeader)}static tooSmallForPayload(){return new Ud("Buffer cannot fit payload",Nd.TooSmallForPayload)}}class Fd{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"}(xd||(xd={}));class Bd extends Fd{}class jd extends Bd{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return 2+jd.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,jd.tag),t+=1,e.setUint8(t,jd.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:jd.tag,lengthBytes:jd.lengthBytes,timestamp:this.timestamp}}}jd.tag=xd.UserTimestamp,jd.lengthBytes=8;class qd extends Bd{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return 2+qd.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,qd.tag),t+=1,e.setUint8(t,qd.lengthBytes),t+=1,e.setUint8(t,this.keyIndex),t+=1;for(let n=0;n<this.iv.length;n+=1)e.setUint8(t,this.iv[n]),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:qd.tag,lengthBytes:qd.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}}qd.tag=xd.E2ee,qd.lengthBytes=13;class Vd extends Fd{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=tc(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 xd.UserTimestamp:if(t.byteLength-r<jd.lengthBytes)throw Ld.malformedExt(e);n=new jd(t.getBigUint64(r)),r+=a;break;case xd.E2ee:if(t.byteLength-r<qd.lengthBytes)throw Ld.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 qd(s,o),r+=a;break;default:if(t.byteLength-r<a)throw Ld.malformedExt(e);r+=a}}return[new Vd({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 Hd={from:e=>({payload:e.payload,extensions:new Vd({userTimestamp:e.userTimestamp?new jd(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}}},Wd=Symbol.for("lk.track"),Kd=Symbol.for("lk.data-track");class zd{constructor(e,t,n){this.trackSymbol=Wd,this.isLocal=!1,this.typeSymbol=Kd,this.info=e,this.manager=t,this.publisherIdentity=n.publisherIdentity}subscribe(e){try{const[t,n]=this.manager.openSubscriptionStream(this.info.sid,null==e?void 0:e.signal,null==e?void 0:e.bufferSize);return n.catch((()=>{})),t}catch(e){throw e}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}}class Jd extends Fd{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 Vd}extensionsMetrics(){const e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((2+e)/4);return{lengthBytes:e,lengthWords:t,paddingLengthBytes:4*t-2-e}}toBinaryLengthBytes(){const{lengthBytes:e,paddingLengthBytes:t}=this.extensionsMetrics();let n=12;return e>0&&(n+=2+e+t),n}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw Ud.tooSmallForHeader();let t,n=0;switch(this.marker){case Gd.Inter:t=0;break;case Gd.Final:t=1;break;case Gd.Start:t=2;break;case Gd.Single:t=3}n|=t<<3;const{lengthBytes:i,lengthWords:r,paddingLengthBytes:a}=this.extensionsMetrics();i>0&&(n|=4);let s=0;if(e.setUint8(s,n),s+=1,e.setUint8(s,0),s+=1,e.setUint16(s,this.trackHandle),s+=2,e.setUint16(s,this.sequence.value),s+=2,e.setUint16(s,this.frameNumber.value),s+=2,e.setUint32(s,this.timestamp.asTicks()),s+=4,i>0){const t=r-1;e.setUint16(s,t),s+=2;s+=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+s));for(let t=0;t<a;t+=1)e.setUint8(s,0),s+=1}const o=this.toBinaryLengthBytes();if(s!==o)throw new Error("DataTrackPacketHeader.toBinaryInto: Wrote ".concat(s," bytes but expected length was ").concat(o," bytes"));return o}static fromBinary(e){const t=tc(e);if(t.byteLength<12)throw Ld.tooShort();let n=0;const i=t.getUint8(n);n+=1;const r=i>>5&7;if(r>0)throw Ld.unsupportedVersion(r);let a;switch(i>>3&3){case 2:a=Gd.Start;break;case 1:a=Gd.Final;break;case 3:a=Gd.Single;break;default:a=Gd.Inter}const s=(i>>2&1)>0;let o;n+=1;try{o=rc.fromNumber(t.getUint16(n))}catch(e){throw e instanceof ic&&(e.isReason(nc.Reserved)||e.isReason(nc.TooLarge))?Ld.invalidHandle(e):e}n+=2;const c=Zo.u16(t.getUint16(n));n+=2;const d=Zo.u16(t.getUint16(n));n+=2;const l=$o.fromRtpTicks(t.getUint32(n));n+=4;let u=new Vd;if(s){if(t.byteLength-n<2)throw Ld.missingExtWords();let e=t.getUint16(n);n+=2;let i=4*(e+1)-2;if(n+i>t.byteLength)throw Ld.headerOverrun();let r=new DataView(t.buffer,t.byteOffset+n,i);const[a,s]=Vd.fromBinary(r);u=a,n+=s}return[new Jd({marker:a,trackHandle:o,sequence:c,frameNumber:d,timestamp:l,extensions:u}),n]}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 Gd;!function(e){e[e.Start=0]="Start",e[e.Inter=1]="Inter",e[e.Final=2]="Final",e[e.Single=3]="Single"}(Gd||(Gd={}));class Qd extends Fd{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 Ud.tooSmallForPayload();for(let n=0;n<this.payload.length;n+=1)e.setUint8(t,this.payload[n]),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=tc(e),[n,i]=Jd.fromBinary(t),r=t.buffer.slice(t.byteOffset+i,t.byteOffset+t.byteLength);return[new Qd(n,new Uint8Array(r)),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}}const Yd=zi(e.LoggerNames.DataTracks);class Xd extends Ca{constructor(e,t,n,i){super(19,"Frame ".concat(n," dropped: ").concat(e),i),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=Zd[t],this.frameNumber=n}static interrupted(e,t){return new Xd("Interrupted by the start of a new frame ".concat(t),Zd.Interrupted,e)}static unknownFrame(e){return new Xd("Initial packet was never received.",Zd.UnknownFrame,e)}static bufferFull(e){return new Xd("Reorder buffer is full.",Zd.BufferFull,e)}static incomplete(e,t,n){return new Xd("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(n," packets."),Zd.Incomplete,e)}}var Zd,$d;!function(e){e[e.Interrupted=0]="Interrupted",e[e.UnknownFrame=1]="UnknownFrame",e[e.BufferFull=2]="BufferFull",e[e.Incomplete=3]="Incomplete"}(Zd||(Zd={}));class el{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case Gd.Single:return this.frameFromSingle(e,t);case Gd.Start:return this.beginPartial(e,t);case Gd.Inter:case Gd.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!==Gd.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 Xd.interrupted(n,e.header.frameNumber.value);Yd.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!==Gd.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 Xd.interrupted(e,r);Yd.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!==Gd.Inter&&e.header.marker!==Gd.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),Xd.unknownFrame(t);if(n.payloads.size>=el.MAX_BUFFER_PACKETS)throw this.partials.delete(t),Xd.bufferFull(t);return n.payloads.has(e.header.sequence.value)&&Yd.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===Gd.Final?this.finalize(t,n,e.header.sequence.value):null}finalize(e,t,n){const i=t.payloads.size;let r=0;for(const e of t.payloads.values())r+=e.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),Xd.incomplete(e,i,n-t.startSequence.value+1)}}el.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"}($d||($d={}));class tl extends Ca{constructor(e,t,n){super(22,e,n),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=$d[t]}static unpublished(){return new tl("The track has been unpublished and is no longer available",$d.Unpublished)}static timeout(){return new tl("Request to subscribe to data track timed-out",$d.Timeout)}static disconnected(){return new tl("Cannot subscribe to data track when disconnected",$d.Disconnected)}static cancelled(){return new tl("Subscription to data track cancelled by caller",$d.Cancelled)}}const nl=zi(e.LoggerNames.DataTracks);class il{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 el;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 Zi(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(e){return nl.warn("Data frame depacketize error: ".concat(e)),null}return t}decryptIfNeeded(e){return Zi(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 nl.error("Missing E2EE meta"),null;let a;try{a=yield i.handleEncryptedData(e.payload,r.iv,this.publisherIdentity,r.keyIndex)}catch(e){return nl.error("Error decrypting packet: ".concat(e)),null}return e.payload=a.payload,e}))}}const rl=zi(e.LoggerNames.DataTracks);class al extends ar.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)):rl.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 Xs,a=()=>{null==t||t.removeEventListener("abort",o)},s=()=>{if(a(),!i)return void rl.warn("ReadableStream subscribed to ".concat(e," was not started."));const t=this.descriptors.get(e);t?"active"===t.subscription.type?(t.subscription.streamControllers.delete(i),0===t.subscription.streamControllers.size&&this.unSubscribeRequest(t.info.sid)):rl.warn("Subscription for track ".concat(e," is not active, skipping cancel...")):rl.warn("Unknown track ".concat(e,", skipping cancel..."))},o=()=>{var t;if(!i)return;const n=this.descriptors.get(e);"active"===(null==n?void 0:n.subscription.type)&&n.subscription.streamControllers.delete(i),i.error(tl.cancelled()),null===(t=r.reject)||void 0===t||t.call(r,tl.cancelled()),s()},c=new ReadableStream({start:n=>{i=n,this.subscribeRequest(e,t).then((()=>Zi(this,void 0,void 0,(function*(){var i,s,c;const d=this.descriptors.get(e);if(!d){rl.error("Unknown track ".concat(e));const t=tl.disconnected();return n.error(t),void(null===(i=r.reject)||void 0===i||i.call(r,t))}if("active"!==d.subscription.type){rl.error("Subscription for track ".concat(e," is not active"));const t=tl.disconnected();return n.error(t),void(null===(s=r.reject)||void 0===s||s.call(r,t))}(null==t?void 0:t.aborted)?o():(null==t||t.addEventListener("abort",o),d.subscription.streamControllers.set(n,a),null===(c=r.resolve)||void 0===c||c.call(r))})))).catch((e=>{var t;n.error(e),null===(t=r.reject)||void 0===t||t.call(r,e)}))},cancel:()=>{s()}},new CountQueuingStrategy({highWaterMark:n}));return[c,r.promise]}subscribeRequest(e,t){return Zi(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)=>Zi(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=_d([n,i].filter((e=>void 0!==e))),a=new Xs;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,tl.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 Xs,pendingRequestCount:1,cancel:()=>{var t,i;const a=n.subscription;n.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1}),"pending"===a.type&&(null===(i=(t=a.completionFuture).reject)||void 0===i||i.call(t,r.aborted?tl.timeout():tl.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});const r=Od(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 Zi(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 rl.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[n,i]of e){i();try{n.close()}catch(e){rl.warn("Failed to close readable stream for track ".concat(t,": ").concat(e))}}}receiveSfuPublicationUpdates(e){return Zi(this,void 0,void 0,(function*(){if(0===e.size)return;const t=new Map;for(const[n,i]of e.entries()){const e=new Set;for(const t of i)e.add(t.sid),this.descriptors.has(t.sid)||(yield this.handleTrackPublished(n,t));t.set(n,e)}for(const[e,n]of t.entries()){let t=Array.from(this.descriptors.entries()).filter((t=>{let[n,i]=t;return i.publisherIdentity===e})).map((e=>{let[t]=e;return t})).filter((e=>!n.has(e)));for(const e of t)this.handleTrackUnpublished(e)}}))}queryPublications(){return Zi(this,void 0,void 0,(function*(){return Array.from(this.descriptors.values()).map((e=>e.info))}))}handleTrackPublished(e,t){return Zi(this,void 0,void 0,(function*(){if(this.descriptors.has(t.sid))return void rl.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 zd(n.info,this,{publisherIdentity:e});this.emit("trackPublished",{track:i})}))}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})):rl.error("Unknown track ".concat(e))}receivedSfuSubscriberHandles(e){for(const[t,n]of e.entries())this.registerSubscriberHandle(t,n)}registerSubscriberHandle(e,t){var n,i;const r=this.descriptors.get(t);if(r)switch(r.subscription.type){case"none":return void rl.warn("No subscription for ".concat(t));case"active":return r.subscription.subcriptionHandle=e,void this.subscriptionHandles.set(e,t);case"pending":{const a=new il({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 rl.error("Unknown track ".concat(t))}packetReceived(e){return Zi(this,void 0,void 0,(function*(){let t;try{[t]=Qd.fromBinary(e)}catch(e){return void rl.error("Failed to deserialize packet: ".concat(e))}const n=this.subscriptionHandles.get(t.header.trackHandle);if(!n)return void rl.warn("Unknown subscriber handle ".concat(t.header.trackHandle));const i=this.descriptors.get(n);if(!i)return void rl.error("Missing descriptor for track ".concat(n));if("active"!==i.subscription.type)return void rl.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){rl.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=Hd.lossyIntoFrame(r);e.enqueue(t)}}))}resendSubscriptionUpdates(){for(const[e,t]of this.descriptors)"none"!==t.subscription.type&&this.emit("sfuUpdateSubscription",{sid:e,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,tl.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,tl.disconnected())),"active"===n.subscription.type&&this.closeStreamControllers(n.subscription.streamControllers,n.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}}class sl extends Ca{constructor(e,t,n){super(19,e,n),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=ol[t]}static mtuTooShort(){return new sl("MTU is too short to send frame",ol.MtuTooShort)}}var ol,cl,dl,ll;!function(e){e[e.MtuTooShort=0]="MtuTooShort"}(ol||(ol={}));class ul{constructor(e,t){this.sequence=Zo.u16(0),this.frameNumber=Zo.u16(0),this.clock=ec.rtpStartingNow($o.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?Gd.Single:0===e?Gd.Start:e===t-1?Gd.Final:Gd.Inter}*packetize(e,t){var n;const i=this.frameNumber.getThenIncrement(),r={marker:Gd.Inter,trackHandle:this.handle,sequence:Zo.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 Jd(r).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw sl.mtuTooShort();const s=this.mtuSizeBytes-a,o=Math.ceil(e.payload.byteLength/s);for(let t=0,n=0;n<e.payload.byteLength;[t,n]=[t+1,n+s]){const i=this.sequence.getThenIncrement(),a=new Jd(Object.assign(Object.assign({},r),{marker:ul.computeFrameMarker(t,o),sequence:i})),c=Math.min(s,e.payload.byteLength-n),d=new Uint8Array(e.payload.buffer,e.payload.byteOffset+n,c);yield new Qd(a,d)}}}!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"}(cl||(cl={}));class hl extends Ca{constructor(e,t,n){super(21,e,n),this.name="DataTrackPublishError",this.reason=t,this.reasonName=cl[t],this.rawMessage=null==n?void 0:n.rawMessage}static notAllowed(e){return new hl("Data track publishing unauthorized",cl.NotAllowed,{rawMessage:e})}static duplicateName(e){return new hl("Track name already taken",cl.DuplicateName,{rawMessage:e})}static invalidName(e){return new hl("Track name is invalid",cl.InvalidName,{rawMessage:e})}static timeout(){return new hl("Publish data track timed-out. Does the LiveKit server support data tracks?",cl.Timeout)}static limitReached(e){return new hl("Data track publication limit reached",cl.LimitReached,{rawMessage:e})}static unknown(e,t){return new hl("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),cl.Unknown)}static disconnected(){return new hl("Room disconnected",cl.Disconnected)}static cancelled(){return new hl("Publish data track cancelled by caller",cl.Cancelled)}}!function(e){e[e.TrackUnpublished=0]="TrackUnpublished",e[e.Dropped=1]="Dropped"}(dl||(dl={}));class pl extends Ca{constructor(e,t,n){super(22,e,n),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=dl[t]}static trackUnpublished(){return new pl("Track is no longer published",dl.TrackUnpublished)}static dropped(e){return new pl("Frame was dropped",dl.Dropped,{cause:e})}}!function(e){e[e.Packetizer=0]="Packetizer",e[e.Encryption=1]="Encryption"}(ll||(ll={}));class ml extends Ca{constructor(e,t,n){super(21,e,n),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=ll[t]}static packetizer(e){return new ml("Error packetizing frame",ll.Packetizer,{cause:e})}static encryption(e){return new ml("Error encrypting frame",ll.Encryption,{cause:e})}}class gl{constructor(t,n){this.trackSymbol=Wd,this.isLocal=!0,this.typeSymbol=Kd,this.handle=null,this.log=Wi,this.flushedFuture=new Xs,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 Xs)},this.options=t,this.manager=n,this.log=zi(e.LoggerNames.DataTracks),this.manager.on("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.on("reset",this.handleManagerReset)}static withExplicitHandle(e,t,n){const i=new gl(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 Zi(this,void 0,void 0,(function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(e){throw e}}))}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 pl.trackUnpublished();const t=Hd.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(e){throw e}}flush(){return Zi(this,void 0,void 0,(function*(){if(!this.isFlushed)return this.flushedFuture.promise}))}unpublish(){return Zi(this,void 0,void 0,(function*(){if(this.handle)try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}else Wi.warn('Data track "'.concat(this.options.name,'" is not published, so unpublishing has no effect.'))}))}}class vl{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new ul(e.info.pubHandle,vl.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return tr(this,arguments,(function*(){const t=yield er(this.encryptIfNeeded(e));try{yield er(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:er(e[i](t)),done:!1}:r?r(t):t}:r}}(nr(this.packetizer.packetize(t))))}catch(e){if(e instanceof sl)throw ml.packetizer(e);throw e}}))}encryptIfNeeded(e){return Zi(this,void 0,void 0,(function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(e){throw ml.encryption(e)}return e.payload=t.payload,e.extensions.e2ee=new qd(t.keyIndex,t.iv),e}))}}vl.TRANSPORT_MTU_BYTES=16e3;const fl=zi(e.LoggerNames.DataTracks),kl={pending:()=>({type:"pending",completionFuture:new Xs}),active:(e,t)=>({type:"active",info:e,publishState:"published",pipeline:new vl({info:e,e2eeManager:t}),unpublishingFuture:new Xs})};class yl extends ar.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new ac,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 yl;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 Zi(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 pl.trackUnpublished();if("unpublished"===o.publishState)throw pl.trackUnpublished();if("republishing"===o.publishState)throw pl.dropped("Data track republishing");try{try{for(var c,d=!0,l=nr(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(e){i={error:e}}finally{try{d||n||!(r=l.return)||(yield r.call(l))}finally{if(i)throw i.error}}}catch(e){throw pl.dropped(e)}}))}handlePacketSendComplete(e){var t;let n=(null!==(t=this.inFlightPacketCounter.get(e))&&void 0!==t?t:0)-1;n<0&&(fl.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 Zi(this,void 0,void 0,(function*(){const n=this.handleAllocator.get();if(!n)throw hl.limitReached();const i=Od(1e4),r=t?_d([t,i]):i;if(this.descriptors.has(n))throw new Error("Descriptor for handle already exists");const a=kl.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?hl.timeout():hl.cancelled()))):fl.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:gl.withExplicitHandle(e,this,n)}),n)}))}queryPublished(){return Array.from(this.descriptors.values()).filter((e=>"active"===e.type)).map((e=>e.info))}unpublishRequest(e){return Zi(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})):fl.warn("Track ".concat(e," not active")):fl.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 e=t.data,r=e.usesE2ee?this.e2eeManager:null;this.descriptors.set(e.pubHandle,kl.active(e,r)),null===(i=(n=s.completionFuture).resolve)||void 0===i||i.call(n)}else null===(a=(r=s.completionFuture).reject)||void 0===a||a.call(r,t.error);return;case"active":if("republishing"!==s.publishState)return void fl.warn("Track ".concat(e," already active"));if("error"===t.type)return void fl.warn("Republish failed for track ".concat(e));fl.debug("Track ".concat(e," republished")),s.info.sid=t.data.sid,s.publishState="published",this.descriptors.set(s.info.pubHandle,s)}else fl.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)):fl.warn("Track ".concat(e," not active"))):fl.warn("No descriptor for ".concat(e))}sfuWillRepublishTracks(){var e,t;for(const[n,i]of this.descriptors.entries())switch(i.type){case"pending":this.descriptors.delete(n),null===(t=(e=i.completionFuture).reject)||void 0===t||t.call(e,hl.disconnected());break;case"active":i.publishState="republishing",this.emit("sfuPublishRequest",{handle:i.info.pubHandle,name:i.info.name,usesE2ee:i.info.usesE2ee})}}reset(){return Zi(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,hl.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 bl extends Error{constructor(e,t,n,i){super(t),this.code=e,this.message=wl(t,bl.MAX_MESSAGE_BYTES),this.data=n?wl(n,bl.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 bl(e.code,e.message,e.data)}toProto(){return new xt({code:this.code,message:this.message,data:this.data})}static builtIn(e,t,n){return new bl(bl.ErrorCode[e],bl.ErrorMessage[e],t,n)}}bl.MAX_MESSAGE_BYTES=256,bl.MAX_DATA_BYTES=15360,bl.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},bl.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 Tl="lk.rpc_request",Sl="lk.rpc_response";var El;!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"}(El||(El={}));function Cl(e){return(new TextEncoder).encode(e).length}function wl(e,t){if(Cl(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 Rl extends sr{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 Zi(this,arguments,void 0,(function(e){var t=this;let{destinationIdentity:n,method:i,payload:r,responseTimeout:a=15e3}=e;return function*(){const e=t.getRemoteParticipantClientProtocol(n);if(Cl(r)>15360&&e<1)throw bl.builtIn("REQUEST_PAYLOAD_TOO_LARGE");const s=t.getServerVersion();if(s&&js(s,"1.8.0")<0)throw bl.builtIn("UNSUPPORTED_SERVER");const o=Math.max(a,8e3),c=crypto.randomUUID(),d=new Xs,l=setTimeout((()=>{var e;t.pendingAcks.delete(c),null===(e=d.reject)||void 0===e||e.call(d,bl.builtIn("CONNECTION_TIMEOUT")),t.pendingResponses.delete(c),clearTimeout(u)}),7e3);t.pendingAcks.set(c,{resolve:()=>{clearTimeout(l)},participantIdentity:n}),t.pendingResponses.set(c,{completionFuture:d,participantIdentity:n}),yield t.publishRpcRequest(n,c,i,r,o,e);const u=setTimeout((()=>{var e;t.pendingResponses.delete(c),null===(e=d.reject)||void 0===e||e.call(d,bl.builtIn("RESPONSE_TIMEOUT"))}),a),h=d.promise.finally((()=>{clearTimeout(u),t.pendingAcks.has(c)&&(t.log.warn("RPC response received before ack",c),t.pendingAcks.delete(c),clearTimeout(l))}));return[c,h]}()}))}publishRpcRequest(e,t,n,i,r,a){return Zi(this,void 0,void 0,(function*(){if(a>=1){const a=yield this.outgoingDataStreamManager.streamText({topic:Tl,destinationIdentities:[e],attributes:{[El.RPC_REQUEST_ID]:t,[El.RPC_REQUEST_METHOD]:n,[El.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:"".concat(r),[El.RPC_REQUEST_VERSION]:"".concat(2)}});return yield a.write(i),void(yield a.close())}this.emit("sendDataPacket",{packet:new Tt({destinationIdentities:[e],kind:St.RELIABLE,value:{case:"rpcRequest",value:new Ot({id:t,method:n,payload:i,responseTimeoutMs:r,version:1})}})})}))}handleIncomingDataStream(e,t,n){return Zi(this,void 0,void 0,(function*(){const i=n[El.RPC_REQUEST_ID];if(!i)return void this.log.warn("RPC data stream malformed: ".concat(El.RPC_REQUEST_ID," not set."));const r=this.pendingResponses.get(i);if(r&&r.participantIdentity!==t)return void this.log.warn("RPC response stream for ".concat(i," arrived from unexpected sender ").concat(t,", expected ").concat(r.participantIdentity,". Ignoring."));let a;try{a=yield e.readAll()}catch(e){return this.log.warn("Error reading RPC response payload: ".concat(e)),void this.handleIncomingRpcResponseFailure(i,bl.builtIn("APPLICATION_ERROR","Error reading RPC response payload",{cause:e}))}this.handleIncomingRpcResponseSuccess(i,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[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(const[n,{participantIdentity:i,completionFuture:r}]of this.pendingResponses)i===e&&(null===(t=r.reject)||void 0===t||t.call(r,bl.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(n))}}class Pl extends sr{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 Zi(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,bl.builtIn("UNSUPPORTED_VERSION"));const i=this.rpcHandlers.get(t.method);if(!i)return void this.publishRpcResponsePacket(e,t.id,null,bl.builtIn("UNSUPPORTED_METHOD"));let r;try{r=yield i({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(i){let r;return i instanceof bl?r=i:(this.log.warn("Uncaught error returned by RPC handler for ".concat(t.method,". Returning APPLICATION_ERROR instead."),i),r=bl.builtIn("APPLICATION_ERROR","Uncaught error: ".concat(null!==(n=null==i?void 0:i.message)&&void 0!==n?n:i),{cause:i})),void this.publishRpcResponsePacket(e,t.id,null,r)}yield this.publishRpcResponse(e,t.id,null!=r?r:"")}))}handleIncomingDataStream(e,t,n){return Zi(this,void 0,void 0,(function*(){const i=n[El.RPC_REQUEST_ID],r=n[El.RPC_REQUEST_METHOD],a=parseInt(n[El.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),s=parseInt(n[El.RPC_REQUEST_VERSION],10);if(!i||!r||Number.isNaN(a)||Number.isNaN(s))return this.log.warn("RPC data stream malformed: ".concat(El.RPC_REQUEST_ID," / ").concat(El.RPC_REQUEST_METHOD," / ").concat(El.RPC_REQUEST_RESPONSE_TIMEOUT_MS," / ").concat(El.RPC_REQUEST_VERSION," not set.")),void this.publishRpcResponsePacket(t,i,null,bl.builtIn("APPLICATION_ERROR","RPC data stream malformed"));if(this.publishRpcAck(t,i),2!==s)return void this.publishRpcResponsePacket(t,i,null,bl.builtIn("UNSUPPORTED_VERSION"));let o;try{o=yield e.readAll()}catch(e){return this.log.warn("Error reading RPC request payload: ".concat(e)),void this.publishRpcResponsePacket(t,i,null,bl.builtIn("APPLICATION_ERROR","Error reading RPC request payload",{cause:e}))}const c=this.rpcHandlers.get(r);if(!c)return void this.publishRpcResponsePacket(t,i,null,bl.builtIn("UNSUPPORTED_METHOD"));let d;try{d=yield c({requestId:i,callerIdentity:t,payload:o,responseTimeout:a})}catch(e){let n;return e instanceof bl?n=e:(this.log.warn("Uncaught error returned by RPC handler for ".concat(r,". Returning APPLICATION_ERROR instead."),e),n=bl.builtIn("APPLICATION_ERROR")),void this.publishRpcResponsePacket(t,i,null,n)}yield this.publishRpcResponse(t,i,null!=d?d:"")}))}publishRpcAck(e,t){this.emit("sendDataPacket",{packet:new Tt({destinationIdentities:[e],kind:St.RELIABLE,value:{case:"rpcAck",value:new At({requestId:t})}})})}publishRpcResponsePacket(e,t,n,i){this.emit("sendDataPacket",{packet:new Tt({destinationIdentities:[e],kind:St.RELIABLE,value:{case:"rpcResponse",value:new Nt({requestId:t,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:null!=n?n:""}})}})})}publishRpcResponse(e,t,n){return Zi(this,void 0,void 0,(function*(){if(this.getRemoteParticipantClientProtocol(e)>=1){const i=yield this.outgoingDataStreamManager.streamText({topic:Sl,destinationIdentities:[e],attributes:{[El.RPC_REQUEST_ID]:t}});return yield i.write(n),void(yield i.close())}if(Cl(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,bl.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"));this.publishRpcResponsePacket(e,t,n,null)}))}}class Il extends Bo{constructor(e,t,n,i,r,a){super(e,t,gs.Kind.Audio,n,a),this.monitorReceiver=()=>Zi(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=Fo(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;Ns()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Ns())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return Zi(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(ws(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&ws(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 Zi(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 Dl extends ar.EventEmitter{constructor(t,n,i,r){var a;super(),this.metadataMuted=!1,this.encryption=mt.NONE,this.log=Wi,this.handleMuted=()=>{this.emit(e.TrackEvent.Muted)},this.handleUnmuted=()=>{this.emit(e.TrackEvent.Unmuted)},this.log=zi(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=gs.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)),ls(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==mt.NONE}get audioTrack(){if(ao(this.track))return this.track}get videoTrack(){if(so(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=gs.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===gs.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"}(Dl||(Dl={}));class Ml extends Dl{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&&so(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 Zi(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){return Zi(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){return Zi(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){return Zi(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}getTrackFeatures(){var e;if(ao(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(at.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(at.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(at.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(at.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||n.add(at.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(at.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}return[]}}function _l(e,t){return Zi(this,void 0,void 0,(function*(){null!=e||(e={});let n=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:a}=us(e);let s=a.audio,o=a.video;if(i&&"object"==typeof a.audio&&(a.audio.processor=i),r&&"object"==typeof a.video&&(a.video.processor=r),e.audio&&"object"==typeof a.audio&&"string"==typeof a.audio.deviceId){const e=a.audio.deviceId;a.audio.deviceId={exact:e},n=!0,s=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:e}})}if(a.video&&"object"==typeof a.video&&"string"==typeof a.video.deviceId){const e=a.video.deviceId;a.video.deviceId={exact:e},n=!0,o=Object.assign(Object.assign({},a.video),{deviceId:{ideal:e}})}!0===a.audio?a.audio={deviceId:"default"}:"object"==typeof a.audio&&null!==a.audio&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||"default"})),!0===a.video?a.video={deviceId:"default"}:"object"!=typeof a.video||a.video.deviceId||(a.video.deviceId="default");const c=ns(es(a,Bc,jc)),d=navigator.mediaDevices.getUserMedia(c);a.audio&&(Qo.userMediaPromiseMap.set("audioinput",d),d.catch((()=>Qo.userMediaPromiseMap.delete("audioinput")))),a.video&&(Qo.userMediaPromiseMap.set("videoinput",d),d.catch((()=>Qo.userMediaPromiseMap.delete("videoinput"))));try{const e=yield d;return yield Promise.all(e.getTracks().map((n=>Zi(this,void 0,void 0,(function*(){let a;const s="audio"===n.kind?c.audio:c.video;"boolean"!=typeof s&&(a=s);const o=n.getSettings().deviceId;(null==a?void 0:a.deviceId)&&$s(a.deviceId)!==o?a.deviceId=o:a||(a={deviceId:o});const d=function(e,t,n){switch(e.kind){case"audio":return new Qc(e,t,!1,void 0,n);case"video":return new dd(e,t,!1,n);default:throw new Na("unsupported track type: ".concat(e.kind))}}(n,a,t);return d.kind===gs.Kind.Video?d.source=gs.Source.Camera:d.kind===gs.Kind.Audio&&(d.source=gs.Source.Microphone),d.mediaStream=e,ao(d)&&i?yield d.setProcessor(i):so(d)&&r&&(yield d.setProcessor(r)),d})))))}catch(i){if(!n)throw i;return _l(Object.assign(Object.assign({},e),{audio:s,video:o}),t)}}))}function Ol(e){return Zi(this,void 0,void 0,(function*(){return(yield _l({audio:!1,video:null==e||e}))[0]}))}function Al(e){return Zi(this,void 0,void 0,(function*(){return(yield _l({audio:null==e||e,video:!1}))[0]}))}var Nl,xl;e.ConnectionQuality=void 0,(Nl=e.ConnectionQuality||(e.ConnectionQuality={})).Excellent="excellent",Nl.Good="good",Nl.Poor="poor",Nl.Lost="lost",Nl.Unknown="unknown";class Ll extends ar.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===ht.AGENT}get isActive(){var e;return(null===(e=this.participantInfo)||void 0===e?void 0:e.state)===ut.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]:ht.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=e.ConnectionQuality.Unknown,this.log=Wi,this.loggerOptions=s,this.log=zi(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)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new Xs,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(gs.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(gs.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(gs.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===ut.ACTIVE&&(null===(n=this.participantInfo)||void 0===n?void 0:n.state)!==ut.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 et.EXCELLENT:return e.ConnectionQuality.Excellent;case et.GOOD:return e.ConnectionQuality.Good;case et.POOR:return e.ConnectionQuality.Poor;case et.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=>ao(t.track)&&t.track.setAudioContext(e)))}addTrackPublication(t){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 gs.Kind.Audio:this.audioTrackPublications.set(t.trackSid,t);break;case gs.Kind.Video:this.videoTrackPublications.set(t.trackSid,t)}}}class Ul extends Ll{constructor(t,n,i,a,s,o,c,d){super(t,n,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=mt.NONE,this.e2eeStateMutex=new r,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Xs)},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 Xs),null===(n=(t=this.signalConnectedFuture).resolve)||void 0===n||n.call(t)},this.handleSignalRequestResponse=e=>{const{requestId:t,reason:n,message:i}=e,r=this.pendingSignalRequests.get(t);switch(r&&(n!==Ii.OK&&r.reject(new Ba(i,n)),this.pendingSignalRequests.delete(t)),e.request.case){case"publishDataTrack":{let t;switch(e.reason){case Ii.NOT_ALLOWED:t=hl.notAllowed(e.message);break;case Ii.DUPLICATE_NAME:t=hl.duplicateName(e.message);break;case Ii.INVALID_NAME:t=hl.invalidName(e.message);break;case Ii.LIMIT_EXCEEDED:t=hl.limitReached(e.message);break;default:t=hl.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 mi({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",ls(e))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",ls(e)),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",ls(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",ls(n)),this.emit(e.ParticipantEvent.LocalTrackCpuConstrained,t,n)},this.handleSubscribedQualityUpdate=e=>Zi(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=nr(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(s.videoTrack.sid),ls(s)),yield this.publishAdditionalCodecForTrack(s.videoTrack,e,s.options))}}catch(e){n={error:e}}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=>Zi(this,void 0,void 0,(function*(){if(e.source===gs.Source.ScreenShare||e.source===gs.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",ls(e)),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(co(e)||oo(e))try{if(As())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===gs.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),ls(e)),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",ls(e)),co(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",ls(e)),yield e.mute()}})),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=a,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.roomOutgoingDataStreamManager=s,this.roomOutgoingDataTrackManager=o,this.rpcClientManager=c,this.rpcServerManager=d}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==mt.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 Zi(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:e})}))}setName(e){return Zi(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:e})}))}setAttributes(e){return Zi(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:e})}))}requestMetadataUpdate(e){return Zi(this,arguments,void 0,(function(e){var t=this;let{metadata:n,name:i,attributes:r}=e;return function*(){return new ga(((e,a)=>Zi(t,void 0,void 0,(function*(){var t,s;try{let o=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=n?n:this.metadata)&&void 0!==t?t:"",null!==(s=null!=i?i:this.name)&&void 0!==s?s:"",r),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{a(e),o=!0},values:{name:i,metadata:n,attributes:r}});performance.now()-d<5e3&&!o;){if((!i||this.name===i)&&(!n||this.metadata===n)&&(!r||Object.entries(r).every((e=>{let[t,n]=e;return this.attributes[t]===n||""===n&&!this.attributes[t]}))))return this.pendingSignalRequests.delete(c),void e();yield ys(50)}a(new Ba("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error?a(e):a(new Error(String(e)))}}))))}()}))}setCameraEnabled(e,t,n){return this.setTrackEnabled(gs.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(gs.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(gs.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return Zi(this,void 0,void 0,(function*(){const t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?mt.GCM:mt.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,n,i,r){return Zi(this,void 0,void 0,(function*(){var a,s;this.log.debug("setTrackEnabled",{source:t,enabled:n}),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(t);if(n)if(o)yield o.unmute();else{let n;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 gs.Source.Camera:n=yield this.createTracks({video:null===(a=i)||void 0===a||a});break;case gs.Source.Microphone:n=yield this.createTracks({audio:null===(s=i)||void 0===s||s});break;case gs.Source.ScreenShare:n=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Na(t)}}catch(i){throw null==n||n.forEach((e=>{e.stop()})),i instanceof Error&&this.emit(e.ParticipantEvent.MediaDevicesError,i,ss(t)),this.pendingPublishing.delete(t),i}for(const e of n){const n=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);t===gs.Source.Microphone&&ao(e)&&n.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone"),e.startPreConnectBuffer())}try{const e=[];for(const t of n)this.log.info("publishing track",ls(t)),e.push(this.publishTrack(t,r));const t=yield Promise.all(e);[o]=t}catch(e){throw null==n||n.forEach((e=>{e.stop()})),e}finally{this.pendingPublishing.delete(t)}}else if(!(null==o?void 0:o.track)&&this.pendingPublishing.has(t)&&(o=yield this.waitForPendingPublicationOfSource(t),o||this.log.info("waiting for pending publication promise timed out",{source:t})),o&&o.track)if(t===gs.Source.ScreenShare){const e=[this.unpublishTrack(o.track)],t=this.getTrackPublication(gs.Source.ScreenShareAudio);t&&t.track&&e.push(this.unpublishTrack(t.track)),[o]=yield Promise.all(e)}else yield o.mute();return o}))}enableCameraAndMicrophone(){return Zi(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(gs.Source.Camera)&&!this.pendingPublishing.has(gs.Source.Microphone)){this.pendingPublishing.add(gs.Source.Camera),this.pendingPublishing.add(gs.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(gs.Source.Camera),this.pendingPublishing.delete(gs.Source.Microphone)}}}))}createTracks(t){return Zi(this,void 0,void 0,(function*(){var n,i;null!=t||(t={});const r=es(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 _l(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return t.map((t=>(ao(t)&&(this.microphoneError=void 0,t.setAudioContext(this.audioContext),t.source=gs.Source.Microphone,this.emit(e.ParticipantEvent.AudioStreamAcquired)),so(t)&&(this.cameraError=void 0,t.source=gs.Source.Camera),t)))}catch(e){throw e instanceof Error&&(t.audio&&(this.microphoneError=e),t.video&&(this.cameraError=e)),e}}))}createScreenTracks(t){return Zi(this,void 0,void 0,(function*(){if(void 0===t&&(t={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new Aa("getDisplayMedia not supported");void 0!==t.resolution||_s()||(t.resolution=$a.h1080fps30.resolution);const n=os(t),i=yield navigator.mediaDevices.getDisplayMedia(n),r=i.getVideoTracks();if(0===r.length)throw new Na("no video track found");const a=new dd(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=gs.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 Qc(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});t.source=gs.Source.ScreenShareAudio,s.push(t)}return s}))}publishTrack(e,t){return Zi(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 Zi(this,arguments,void 0,(function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return function*(){var a,s,o,c;let d,l;if(co(e)&&e.setAudioContext(n.audioContext),yield null===(a=n.reconnectFuture)||void 0===a?void 0:a.promise,n.republishPromise&&!i&&(yield n.republishPromise),ro(e)&&n.pendingPublishPromises.has(e)&&(yield n.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)d=e.getConstraints();else{let t;switch(d=e.constraints,e.source){case gs.Source.Microphone:t="audioinput";break;case gs.Source.Camera:t="videoinput"}t&&n.activeDeviceMap.has(t)&&(d=Object.assign(Object.assign({},d),{deviceId:n.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new Qc(e,d,!0,n.audioContext,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;case"video":e=new dd(e,d,!0,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;default:throw new Na("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});if(n.trackPublications.forEach((t=>{t.track&&t.track===e&&(l=t)})),l)return n.log.warn("track has already been published, skipping",ls(l)),l;const u=Object.assign(Object.assign({},n.roomOptions.publishDefaults),t),h="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,p=null!==(s=u.forceStereo)&&void 0!==s?s:h;p&&(void 0===u.dtx&&n.log.debug("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",ls(e)),void 0===u.red&&n.log.debug("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(o=u.dtx)&&void 0!==o||(u.dtx=!1),null!==(c=u.red)&&void 0!==c||(u.red=!1)),!function(){const e=ka(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&js(e.osVersion,t)>=0)||"Safari"===e.name&&js(e.version,t)>=0}()&&n.roomOptions.e2ee&&(n.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2"),u.simulcast=!1),u.source&&(e.source=u.source);const m=new Promise(((t,i)=>Zi(n,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==uc.CONNECTED){this.log.debug("deferring track publication until signal is connected",{track:ls(e)});let n=!1;const r=setTimeout((()=>{n=!0,e.stop(),i(new Fa("publishing rejected as engine not connected within timeout",408))}),15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(r),n)return;const a=yield this.publish(e,u,p);t(a)}else try{const n=yield this.publish(e,u,p);t(n)}catch(e){i(e)}}catch(e){i(e)}}))));n.pendingPublishPromises.set(e,m);try{return yield m}catch(a){if(!r&&a instanceof Ua)return n.log.warn("negotiation due to track publish failed, retrying after reconnect",{error:a}),n.pendingPublishPromises.delete(e),yield n.waitForNextEngineRestart(),yield n.publishOrRepublishTrack(e,t,i,!0);throw a}finally{n.pendingPublishPromises.delete(e)}}()}))}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Xs),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",ls(e)),!1;const{canPublish:t,canPublishSources:n}=this.permissions;return!(!t||0!==n.length&&!n.map((e=>function(e){switch(e){case Ze.CAMERA:return gs.Source.Camera;case Ze.MICROPHONE:return gs.Source.Microphone;case Ze.SCREEN_SHARE:return gs.Source.ScreenShare;case Ze.SCREEN_SHARE_AUDIO:return gs.Source.ScreenShareAudio;default:return gs.Source.Unknown}}(e))).includes(e.source))||(this.log.warn("insufficient permissions to publish",ls(e)),!1)}publish(t,n,i){return Zi(this,void 0,void 0,(function*(){var r,a,s,o,c,d,l,u,h,p;if(!this.hasPermissionsToPublish(t))throw new Fa("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((e=>ro(t)&&e.source===t.source))&&t.source!==gs.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(t.source),ls(t)),n.stopMicTrackOnMute&&ao(t)&&(t.stopOnMute=!0),t.source===gs.Source.ScreenShare&&Ps()&&(n.simulcast=!1),"av1"!==n.videoCodec||Ss()||(n.videoCodec=void 0),"vp9"!==n.videoCodec||Es()||(n.videoCodec=void 0),void 0===n.videoCodec&&(n.videoCodec=Uc),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((e=>n.videoCodec===cs(e.mime)))||(n.videoCodec=cs(this.enabledPublishVideoCodecs[0].mime)));const m=n.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 g=[],v=!(null===(r=n.dtx)||void 0===r||r),f=t.getSourceTrackSettings();f.autoGainControl&&g.push(at.TF_AUTO_GAIN_CONTROL),f.echoCancellation&&g.push(at.TF_ECHO_CANCELLATION),f.noiseSuppression&&g.push(at.TF_NOISE_SUPPRESSION),f.channelCount&&f.channelCount>1&&g.push(at.TF_STEREO),v&&g.push(at.TF_NO_DTX),co(t)&&t.hasPreConnectBuffer&&g.push(at.TF_PRECONNECT_BUFFER);const k=this.normalizeRequestedPacketTrailerOptions(t,n),y=new On({cid:t.mediaStreamTrack.id,name:n.name,type:gs.kindToProto(t.kind),muted:t.isMuted,source:gs.sourceToProto(t.source),disableDtx:v,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(a=n.red)||void 0===a||a),stream:null==n?void 0:n.stream,backupCodecPolicy:null==n?void 0:n.backupCodecPolicy,audioFeatures:g,packetTrailerFeatures:k});let b;if(t.kind===gs.Kind.Video){let e;try{e=yield t.waitForDimensions()}catch(n){const i=null!==(o=null===(s=this.roomOptions.videoCaptureDefaults)||void 0===s?void 0:s.resolution)&&void 0!==o?o:Xa.h720.resolution;e={width:i.width,height:i.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},ls(t)),{dims:e}))}y.width=e.width,y.height=e.height,oo(t)&&(Cs(m)&&(t.source===gs.Source.ScreenShare&&(n.scalabilityMode="L1T3","contentHint"in t.mediaStreamTrack&&(t.mediaStreamTrack.contentHint="motion",this.log.debug("forcing contentHint to motion for screenshare with SVC codecs",ls(t)))),n.scalabilityMode=null!==(c=n.scalabilityMode)&&void 0!==c?c:"L3T3_KEY"),y.simulcastCodecs=[new _n({codec:m,cid:t.mediaStreamTrack.id})],!0===n.backupCodec&&(n.backupCodec={codec:Uc}),n.backupCodec&&m!==n.backupCodec.codec&&y.encryption===mt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),y.simulcastCodecs.push(new _n({codec:n.backupCodec.codec,cid:""})))),b=id(t.source===gs.Source.ScreenShare,y.width,y.height,n),y.layers=hd(y.width,y.height,b,Cs(n.videoCodec))}else t.kind===gs.Kind.Audio&&(b=[{maxBitrate:null===(d=n.audioPreset)||void 0===d?void 0:d.maxBitrate,priority:null!==(u=null===(l=n.audioPreset)||void 0===l?void 0:l.priority)&&void 0!==u?u:"high",networkPriority:null!==(p=null===(h=n.audioPreset)||void 0===h?void 0:h.priority)&&void 0!==p?p:"high"}]);if(!this.engine||this.engine.isClosed)throw new La("cannot publish track when not connected");const T=()=>Zi(this,void 0,void 0,(function*(){var i,r,a;if(!this.engine.pcManager)throw new La("pcManager is not ready");if(t.sender=yield this.engine.createSender(t,n,b),oo(t)&&(t.publishOptions=n),this.emit(e.ParticipantEvent.LocalSenderCreated,t.sender,t),oo(t)&&(null!==(i=n.degradationPreference)&&void 0!==i||(n.degradationPreference=function(e){return e.source===gs.Source.ScreenShare||e.constraints.height&&$s(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(t)),t.setDegradationPreference(n.degradationPreference)),b)if(Ps()&&t.kind===gs.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=b[0])||void 0===r?void 0:r.maxBitrate)?b[0].maxBitrate/1e3:0})}else t.codec&&Cs(t.codec)&&(null===(a=b[0])||void 0===a?void 0:a.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:y.cid,codec:t.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()}));let S;const E=new Promise(((e,n)=>Zi(this,void 0,void 0,(function*(){var i;try{S=yield this.engine.addTrack(y),e(S)}catch(e){if(t.sender&&(null===(i=this.engine.pcManager)||void 0===i?void 0:i.publisher)){try{this.engine.pcManager.publisher.removeTrack(t.sender)}catch(e){this.log.error(e)}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({},ls(t)),{error:e}))}))}n(e)}}))));if(this.enabledPublishVideoCodecs.length>0&&0===k.length){const e=yield Promise.all([E,T()]);S=e[0]}else{let e;if(S=yield E,S.codecs.forEach((t=>{void 0===e&&(e=t.mimeType)})),e&&t.kind===gs.Kind.Video){const i=cs(e);i!==m&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign({},ls(t)),{codec:i})),n.videoCodec=i,b=id(t.source===gs.Source.ScreenShare,y.width,y.height,n))}yield T()}const C=new Ml(t.kind,S,t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(C.on(e.TrackEvent.CpuConstrained,(e=>this.onTrackCpuConstrained(e,C))),C.options=n,t.sid=S.sid,oo(t)&&(t.publishOptions=n,y.width&&y.height&&(t.lastEncodedDimensions={width:y.width,height:y.height})),this.log.debug("publishing ".concat(t.kind," with encodings"),{encodings:b,trackInfo:S}),oo(t)?t.startMonitor(this.engine.client):co(t)&&t.startMonitor(),this.addTrackPublication(C),this.emit(e.ParticipantEvent.LocalTrackPublished,C),co(t)&&S.audioFeatures.includes(at.TF_PRECONNECT_BUFFER)){const n=t.getPreConnectBuffer(),i=t.getPreConnectBufferMimeType();if(this.on(e.ParticipantEvent.LocalTrackSubscribed,(e=>{if(e.trackSid===S.sid){if(!t.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed");this.log.debug("finished recording preconnect buffer",ls(t)),t.stopPreConnectBuffer()}})),n){const e=new Promise(((e,r)=>Zi(this,void 0,void 0,(function*(){var a,s,o,c,d,l;try{this.log.debug("waiting for agent",ls(t));const m=setTimeout((()=>{r(new Error("agent not active within 10 seconds"))}),1e4),g=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug("sending preconnect buffer",ls(t));const v=yield this.streamBytes({name:"preconnect-buffer",mimeType:i,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[g.identity],attributes:{trackId:C.trackSid,sampleRate:String(null!==(d=f.sampleRate)&&void 0!==d?d:"48000"),channels:String(null!==(l=f.channelCount)&&void 0!==l?l:"1")}});try{for(var u,h=!0,p=nr(n);!(a=(u=yield p.next()).done);h=!0){c=u.value,h=!1;const e=c;yield v.write(e)}}catch(e){s={error:e}}finally{try{h||a||!(o=p.return)||(yield o.call(p))}finally{if(s)throw s.error}}yield v.close(),e()}catch(e){r(e)}}))));e.then((()=>{this.log.debug("preconnect buffer sent successfully",ls(t))})).catch((e=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign({},ls(t)),{error:e}))}))}}return C}))}canPublishPacketTrailer(){return!!(this.roomOptions.e2ee||this.roomOptions.encryption||No(this.roomOptions.packetTrailer))}normalizeRequestedPacketTrailerOptions(e,t){if(e.kind!==gs.Kind.Video||!xo(t.packetTrailer))return t.packetTrailer=void 0,[];if(!this.canPublishPacketTrailer())return this.log.warn("packet trailer transform not supported; not advertising features",Object.assign(Object.assign({},this.logContext),ls(e))),t.packetTrailer=void 0,[];const n=function(e){const t=[];return(null==e?void 0:e.timestamp)&&t.push(st.PTF_USER_TIMESTAMP),(null==e?void 0:e.frameId)&&t.push(st.PTF_FRAME_ID),t}(t.packetTrailer);return t.packetTrailer=function(e){if(!e||0===e.length)return;const t={};return e.includes(st.PTF_USER_TIMESTAMP)&&(t.timestamp=!0),e.includes(st.PTF_FRAME_ID)&&(t.frameId=!0),t.timestamp||t.frameId?t:void 0}(n),n}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return Zi(this,void 0,void 0,(function*(){var i;if(this.encryptionType!==mt.NONE)return;let r;if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(r=t)})),!r)throw new Na("track is not published");if(!oo(e))throw new Na("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=rd(e,t,a);if(!s)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",ls(e));const o=e.addSimulcastTrack(t,s);if(!o)return;const c=this.normalizeRequestedPacketTrailerOptions(e,a),d=new On({cid:o.mediaStreamTrack.id,type:gs.kindToProto(e.kind),muted:e.isMuted,source:gs.sourceToProto(e.source),sid:e.sid,packetTrailerFeatures:c,simulcastCodecs:[{codec:a.videoCodec,cid:o.mediaStreamTrack.id}]});if(d.layers=hd(d.width,d.height,s),!this.engine||this.engine.isClosed)throw new La("cannot publish track when not connected");const l=(yield Promise.all([this.engine.addTrack(d),(()=>Zi(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,n){return Zi(this,void 0,void 0,(function*(){var i,r;if(ro(t)){const e=this.pendingPublishPromises.get(t);e&&(this.log.debug("awaiting publish promise before attempting to unpublish",ls(t)),yield e)}const a=this.getPublicationForTrack(t),s=a?ls(a):void 0;if(this.log.info("unpublishing track",s),!a||!a.track)return void this.log.warn("track was not unpublished because no publication was found",s);(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===n&&(n=null===(r=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===r||r),n?t.stop():t.stopMonitor();let o=!1;const c=t.sender;if(t.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Hc.FAILED&&c)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===c&&(e.direction="inactive",o=!0);try{o=this.engine.removeTrack(c)}catch(e){this.log.warn(e),o=!0}if(oo(t)){for(const[,e]of t.simulcastCodecs)if(e.sender){try{o=this.engine.removeTrack(e.sender)}catch(e){this.log.warn(e),o=!0}e.sender=void 0}t.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign({},s),{error:e}))}switch(this.trackPublications.delete(a.trackSid),a.kind){case gs.Kind.Audio:this.audioTrackPublications.delete(a.trackSid);break;case gs.Kind.Video:this.videoTrackPublications.delete(a.trackSid)}return this.emit(e.ParticipantEvent.LocalTrackUnpublished,a),a.setTrack(void 0),o&&(yield this.engine.negotiate()),a}))}unpublishTracks(e){return Zi(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>!!e))}))}republishAllTracks(e){return Zi(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 ga(((i,r)=>Zi(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=>Zi(this,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),!n||t.isMuted||t.source===gs.Source.ScreenShare||t.source===gs.Source.ScreenShareAudio||!co(t)&&!oo(t)||t.isUserProvided||(this.log.debug("restarting existing track",{track:e.trackSid}),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))))),i()}catch(e){e instanceof Error?r(e):r(new Error(String(e)))}finally{this.republishPromise=void 0}})))),yield t.republishPromise}()}))}publishData(e){return Zi(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?kd.RELIABLE:kd.LOSSY,r=n.reliable?St.RELIABLE:St.LOSSY,a=n.destinationIdentities,s=n.topic;let o=new Pt({participantIdentity:t.identity,payload:e,destinationIdentities:a,topic:s});const c=new Tt({kind:r,value:{case:"user",value:o}});yield t.engine.sendDataPacket(c,i)}()}))}publishDtmf(e,t){return Zi(this,void 0,void 0,(function*(){const n=new Tt({kind:St.RELIABLE,value:{case:"sipDtmf",value:new It({code:e,digit:t})}});yield this.engine.sendDataPacket(n,kd.RELIABLE)}))}sendChatMessage(t,n){return Zi(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 Tt({value:{case:"chatMessage",value:new _t(Object.assign(Object.assign({},i),{timestamp:_.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,kd.RELIABLE),this.emit(e.ParticipantEvent.ChatMessage,i),i}))}editChatMessage(t,n){return Zi(this,void 0,void 0,(function*(){const i=Object.assign(Object.assign({},n),{message:t,editTimestamp:Date.now()}),r=new Tt({value:{case:"chatMessage",value:new _t(Object.assign(Object.assign({},i),{timestamp:_.parse(i.timestamp),editTimestamp:_.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,kd.RELIABLE),this.emit(e.ParticipantEvent.ChatMessage,i),i}))}sendText(e,t){return Zi(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)}))}streamText(e){return Zi(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamText(e)}))}sendFile(e,t){return Zi(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)}))}streamBytes(e){return Zi(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)}))}performRpc(e){return this.rpcClientManager.performRpc(e).then((e=>{let[t,n]=e;return n}))}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({},ls(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 Xs),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach((n=>{const i=n.track;i&&(e instanceof MediaStreamTrack?(co(i)||oo(i))&&i.mediaStreamTrack===e&&(t=n):e===i&&(t=n))})),t}waitForPendingPublicationOfSource(e){return Zi(this,void 0,void 0,(function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find((t=>{let[n]=t;return n.source===e}));if(t)return t[1];yield ys(20)}}))}publishDataTrack(e){return Zi(this,void 0,void 0,(function*(){const t=new gl(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t}))}}class Fl extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}}class Bl 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 Zi(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 Fl("The operation was aborted.",t.reason);const i=new Xs(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 Fl("The operation was aborted.",t.reason))};t.addEventListener("abort",e,{once:!0}),i.promise.finally((()=>{t.removeEventListener("abort",e)}))}return i.promise}))}}class jl extends Dl{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 Jn({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Lt({participantSid:"",trackSids:[this.trackSid]})]});this.emit(e.TrackEvent.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?Dl.SubscriptionStatus.Unsubscribed:super.isSubscribed?Dl.SubscriptionStatus.Subscribed:Dl.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Dl.PermissionStatus.Allowed:Dl.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||(ho(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&ho(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 ho(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=new Yn({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===gs.Kind.Video){let n=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(n){hs(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&&hs(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 ql extends Ll{static fromParticipantInfo(e,t,n,i){return new ql(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind,t.dataTracks.map((e=>{const n=sc.from(e);return new zd(n,i,{publisherIdentity:t.identity})})),t.clientProtocol)}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]:ht.STANDARD,c=arguments.length>8&&void 0!==arguments[8]?arguments[8]:[],d=arguments.length>9&&void 0!==arguments[9]?arguments[9]:0;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 Bl(c.map((e=>[e.info.name,e]))),this.volumeMap=new Map,this.clientProtocol=d}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),ls(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]:gs.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]:gs.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),ls(o))),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,n);let c;return c="video"===t.kind?new jo(t,n,r,a):new Il(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)&&lo(c)&&ao(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=gs.kindFromProto(e.type);if(!n)return;a=new jl(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!==gs.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:ls(s),newTrack:ls(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),ls(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{track:r}=i;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(t),i.kind){case gs.Kind.Audio:this.audioTrackPublications.delete(t);break;case gs.Kind.Video:this.videoTrackPublications.delete(t)}n&&this.emit(e.ParticipantEvent.TrackUnpublished,i)}setAudioOutput(e){return Zi(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((n=>{var i;ao(n.track)&&lo(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[t,n]of this.dataTracks.entries())e===n.info.sid&&this.dataTracks.delete(t)}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,(xl=e.ConnectionState||(e.ConnectionState={})).Disconnected="disconnected",xl.Connecting="connecting",xl.Connected="connected",xl.Reconnecting="reconnecting",xl.SignalReconnecting="signalReconnecting";class Vl extends ar.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(t){var n,i,a,s,o,c,d;if(super(),n=this,this.state=e.ConnectionState.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new r,this.isVideoPlaybackBlocked=!1,this.log=Wi,this.bufferedEvents=[],this.isResuming=!1,this.connect=(t,n,i)=>Zi(this,void 0,void 0,(function*(){var r;if(!Rs())throw Ns()?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())!==vo(t)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),xs(new URL(t))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new Sd(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)=>Zi(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 Jo.getInstance().getBackOffPromise(t),u.signal.aborted)throw Oa.cancelled("Connection attempt aborted");yield this.attemptConnection(null!=c?c:t,n,i,u),this.abortController=void 0,r()}catch(n){if(this.regionUrlProvider&&n instanceof Oa&&n.reason!==e.ConnectionErrorReason.Cancelled&&n.reason!==e.ConnectionErrorReason.NotAllowed){let i=null;try{this.log.debug("Fetching next region"),i=yield this.regionUrlProvider.getNextBestRegionUrl(null===(d=this.abortController)||void 0===d?void 0:d.signal)}catch(t){if(t instanceof Oa&&(401===t.status||t.reason===e.ConnectionErrorReason.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void o(t)}[e.ConnectionErrorReason.InternalError,e.ConnectionErrorReason.ServerUnreachable,e.ConnectionErrorReason.Timeout].includes(n.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Jo.getInstance().addFailedConnectionAttempt(t)),i&&!(null===(l=this.abortController)||void 0===l?void 0:l.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(n.message,". Retrying with another region: ").concat(i)),this.recreateEngine(!0),yield s(r,o,i)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,to(n)),o(n))}else{let e=nt.UNKNOWN_REASON;n instanceof Oa&&(e=to(n)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),o(n)}}})),o=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Xs(((e,t)=>{s(e,t,o)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,n,i,r,a)=>Zi(this,void 0,void 0,(function*(){const{joinResponse:s,serverInfo:o}=yield n.join(e,t,{autoSubscribe:i.autoSubscribe,adaptiveStream:"object"==typeof r.adaptiveStream||r.adaptiveStream,clientInfoCapabilities:No(r.packetTrailer)||this.e2eeManager?[qt.CAP_PACKET_TRAILER]:void 0,maxRetries:i.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:i.websocketTimeout},a.signal,!r.singlePeerConnection);if(this.serverInfo=o,!o.version)throw new xa("unknown server version");return"0.15.1"===o.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version"),r.dynacast=!1),s})),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(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",{error:e})}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(t,n,i,r)=>Zi(this,void 0,void 0,(function*(){var a,s;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===(s=this.regionUrlProvider)||void 0===s?void 0:s.isCloud())&&this.engine.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Vc),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=yield this.connectSignal(t,n,this.engine,this.connOptions,this.options,r);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();const t=r.signal.aborted?Oa.cancelled("Signal connection aborted"):Oa.serverUnreachable("could not establish signal connection");throw e instanceof Error&&(t.message="".concat(t.message,": ").concat(e.message)),e instanceof Oa&&(t.reason=e.reason,t.status=e.status),this.log.debug("error trying to establish signal connection",{error:e}),t}if(r.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),Oa.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,r)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}As()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),As()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Connected),Jo.getInstance().resetFailedConnectionAttempts(t),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()})),this.disconnect=function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return Zi(n,[...i],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,Oa.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,nt.CLIENT_INITIATED),t.engine=void 0}finally{s()}}()}))},this.onPageLeave=()=>Zi(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting"),yield this.disconnect()})),this.startAudio=()=>Zi(this,void 0,void 0,(function*(){const t=[],n=ka();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=Ys();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=>(e.muted=!1,e.play())))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}})),this.startVideo=()=>Zi(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=>Zi(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(e){this.log.error("error trying to re-publish tracks after reconnection",{error:e})}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",{region:t.serverRegion})}catch(e){return}this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()})),this.handleParticipantUpdates=e=>{var t;for(const n of e){if(n.identity===this.localParticipant.identity){this.localParticipant.updateInfo(n);continue}""===n.identity&&(n.identity=null!==(t=this.sidToIdentity.get(n.sid))&&void 0!==t?t:"");let e=this.remoteParticipants.get(n.identity);n.state===ut.DISCONNECTED?this.handleParticipantDisconnected(n.identity,e):this.getOrCreateParticipant(n.identity,n)}const n=new Map(e.filter((e=>e.identity!==this.localParticipant.identity)).map((e=>[e.identity,e.dataTracks.map((e=>sc.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=gs.streamStateFromProto(t.state);i.track.setStreamState(r),r!==i.track.streamState&&(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=>{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,bl.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{id:n,text:i,language:r,startTime:a,endTime:s,final:o}=e;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{id:t,timestamp:n,message:i,editTimestamp:r}=e;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=()=>Zi(this,void 0,void 0,(function*(){var t;"iOS"!==(null===(t=ka())||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.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=>Zi(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),co(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=ss(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=>Zi(this,void 0,void 0,(function*(){const n=yield t.getDeviceId(!1),i=ss(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({},qc),t),this.log=zi(null!==(i=this.options.loggerName)&&void 0!==i?i:e.LoggerNames.Room,(()=>this.logContext)),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Bc),null==t?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},jc),null==t?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Fc),null==t?void 0:t.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Rd,this.outgoingDataStreamManager=new Md(this.engine,this.log),this.incomingDataTrackManager=new al({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 yl({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{handle:t,bytes:n}=e;this.engine.sendLossyBytes(n,kd.DATA_TRACK_LOSSY,"wait").finally((()=>this.outgoingDataTrackManager.handlePacketSendComplete(t)))})),this.registerRpcDataStreamHandler(),this.rpcClientManager=new Rl(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{packet:t}=e;var n;null===(n=this.engine)||void 0===n||n.sendDataPacket(t,kd.RELIABLE)})),this.rpcServerManager=new Pl(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol),this.rpcServerManager.on("sendDataPacket",(e=>{let{packet:t}=e;var n;null===(n=this.engine)||void 0===n||n.sendDataPacket(t,kd.RELIABLE)})),this.disconnectLock=new r,this.localParticipant=new Ul("","",this.engine,this.options,this.outgoingDataStreamManager,this.outgoingDataTrackManager,this.rpcClientManager,this.rpcServerManager),this.setupPacketTrailer(),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager(null!==(a=this.e2eeManager)&&void 0!==a?a:null),this.outgoingDataTrackManager.updateE2eeManager(null!==(s=this.e2eeManager)&&void 0!==s?s:null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",$s(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",$s(this.options.audioCaptureDefaults.deviceId)),(null===(o=this.options.audioOutput)||void 0===o?void 0:o.deviceId)&&this.switchActiveDevice("audiooutput",$s(this.options.audioOutput.deviceId)).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message)))),As()){const e=new AbortController;null===(d=null===(c=navigator.mediaDevices)||void 0===c?void 0:c.addEventListener)||void 0===d||d.call(c,"devicechange",this.handleDeviceChange,{signal:e.signal}),Vl.cleanupRegistry&&Vl.cleanupRegistry.register(this,(()=>{e.abort()}))}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setE2EEEnabled(e){return Zi(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 Wo(r,i),this.e2eeManager.on(e.EncryptionEvent.ParticipantEncryptionStatusChanged,((t,n)=>{po(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))}setupPacketTrailer(){this.packetTrailerManager=new zo(this.options.packetTrailer),this.packetTrailerManager.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?ga.resolve(""):this.roomInfo&&""!==this.roomInfo.sid?ga.resolve(this.roomInfo.sid):new ga(((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 La("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 yd(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.emitBufferedEvents(),this.setAndEmitConnectionState(e.ConnectionState.Connected)&&this.emit(e.RoomEvent.Reconnected)})).on(e.EngineEvent.SignalResumed,(()=>{this.bufferedEvents=[],(this.state===e.ConnectionState.Reconnecting||this.isResuming)&&this.sendSyncState()})).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!==mt.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,n]=e;return[parseInt(t,10),n.trackSid]})));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)})).on(e.EngineEvent.DataTrackPacketReceived,(e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(e){throw e}})).on(e.EngineEvent.Joined,(e=>{const t=new Map(e.otherParticipants.map((e=>[e.identity,e.dataTracks.map((e=>sc.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:Td})})),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=>Zi(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 Qo.getInstance().getDevices(e,t)}prepareConnection(t,n){return Zi(this,void 0,void 0,(function*(){if(this.state===e.ConnectionState.Disconnected){this.log.debug("prepareConnection to ".concat(t));try{if(xs(new URL(t))&&n){this.regionUrlProvider=new Sd(t,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===e.ConnectionState.Disconnected&&(this.regionUrl=i,yield fetch(eo(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i)))}else yield fetch(eo(t),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",{error:e})}}}))}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return Zi(this,void 0,void 0,(function*(){let n,i=()=>Zi(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 Ti({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":n=new Ti({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":n=new Ti({scenario:{case:"serverLeave",value:!0}});break;case"migration":n=new Ti({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=()=>Zi(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),n=new Ti({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>Zi(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),n=new Ti({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 Ti({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),i=()=>Zi(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new $n({reason:nt.CLIENT_INITIATED,action:ei.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");n=new Ti({scenario:{case:"subscriberBandwidth",value:io(t)}});break;case"leave-full-reconnect":n=new Ti({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,n){return Zi(this,arguments,void 0,(function(t,n){var i=this;let r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var a,s,o,c,d,l,u;let h=!0,p=!1;const m=r?{exact:n}:n;if("audioinput"===t){p=0===i.localParticipant.audioTrackPublications.size;const e=null!==(a=i.getActiveDevice(t))&&void 0!==a?a:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.audioTrackPublications.values()).filter((e=>e.source===gs.Source.Microphone));try{h=(yield Promise.all(n.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(t){throw i.options.audioCaptureDefaults.deviceId=e,t}const r=n.some((e=>{var t,n;return null!==(n=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==n&&n}));h&&r&&(p=!0)}else if("videoinput"===t){p=0===i.localParticipant.videoTrackPublications.size;const e=null!==(s=i.getActiveDevice(t))&&void 0!==s?s:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter((e=>e.source===gs.Source.Camera));try{h=(yield Promise.all(n.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(t){throw i.options.videoCaptureDefaults.deviceId=e,t}const r=n.some((e=>{var t,n;return null!==(n=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==n&&n}));h&&r&&(p=!0)}else if("audiooutput"===t){if(p=!0,!ws()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");i.options.webAudioMix&&(n=null!==(o=yield Qo.getInstance().normalizeDeviceId("audiooutput",n))&&void 0!==o?o:""),null!==(c=(u=i.options).audioOutput)&&void 0!==c||(u.audioOutput={});const e=null!==(d=i.getActiveDevice(t))&&void 0!==d?d:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=n;try{i.options.webAudioMix&&(null===(l=i.audioContext)||void 0===l||l.setSinkId(n)),yield Promise.all(Array.from(i.remoteParticipants.values()).map((e=>e.setAudioOutput({deviceId:n}))))}catch(t){throw i.options.audioOutput.deviceId=e,t}}return p&&(i.localParticipant.activeDeviceMap.set(t,n),i.emit(e.RoomEvent.ActiveDeviceChanged,t,n)),h}()}))}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){if(this.state===e.ConnectionState.Connecting||this.state===e.ConnectionState.Reconnecting){const r=()=>{this.log.debug("deferring on track for later",{mediaTrackId:t.id,mediaStreamId:n.id,tracksInStream:n.getTracks().map((e=>e.id))}),this.onTrackAdded(t,n,i),a()},a=()=>{this.off(e.RoomEvent.Reconnected,r),this.off(e.RoomEvent.Connected,r),this.off(e.RoomEvent.Disconnected,a)};return this.once(e.RoomEvent.Reconnected,r),this.once(e.RoomEvent.Connected,r),void this.once(e.RoomEvent.Disconnected,a)}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 r=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(n.id),a=r[0];let s=r[1],o=t.id;if(s&&s.startsWith("TR")&&(o=s),a===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant");const c=Array.from(this.remoteParticipants.values()).find((e=>e.sid===a));if(!c)return void(a.startsWith("PA")&&this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(a)));if(!o.startsWith("TR")){const e=this.engine.getTrackIdForReceiver(i);if(!e)return void this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(a));o=e}let d;o.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(a,", streamId: ").concat(s,", trackId: ").concat(o),{remoteParticipantID:a,streamId:s,trackId:o}),this.options.adaptiveStream&&(d="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});const l=c.addSubscribedMediaTrack(t,o,n,i,d);(null==l?void 0:l.isEncrypted)&&!this.e2eeManager&&this.emit(e.RoomEvent.EncryptionError,new Error("Encrypted ".concat(l.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleLocalTrackSubscribed(t){const n=()=>this.localParticipant.getTrackPublications().find((e=>{let{trackSid:n}=e;return n===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),As()&&(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){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),n.setDisconnected(),this.rpcClientManager.handleParticipantDisconnected(n.identity))}selectDefaultDevices(){return Zi(this,void 0,void 0,(function*(){var t,n,i;const r=Qo.getInstance().previousDevices,a=yield Qo.getInstance().getDevices(void 0,!1),s=ka();if("Chrome"===(null==s?void 0:s.name)&&"iOS"!==s.os)for(let t of a){const n=r.find((e=>e.deviceId===t.deviceId));n&&""!==n.label&&n.kind===t.kind&&n.label!==t.label&&"default"===this.getActiveDevice(t.kind)&&this.emit(e.RoomEvent.ActiveDeviceChanged,t.kind,t.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let e of o){const s=as(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&&!Ms()||"videoinput"===e||!(c.length>0)||c.find((t=>t.deviceId===this.getActiveDevice(e)))||"audiooutput"===e&&Ms()||(yield this.switchActiveDevice(e,c[0].deviceId))}}))}acquireAudioContext(){return Zi(this,void 0,void 0,(function*(){var t,n;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=rs())&&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(),ys(200)])}catch(e){this.log.warn("Could not resume audio context",{error:e})}const i="running"===(null===(n=this.audioContext)||void 0===n?void 0:n.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,i))}))}createParticipant(e,t){var n;let i;return i=t?ql.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):new ql(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===gs.Kind.Audio?(t.on(e.TrackEvent.AudioPlaybackStarted,this.handleAudioPlaybackStarted),t.on(e.TrackEvent.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):t.kind===gs.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.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===ht.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&&uo(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(Tl,((e,t)=>Zi(this,[e,t],void 0,(function(e,t){var n=this;let{identity:i}=t;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(Sl,((e,t)=>Zi(this,[e,t],void 0,(function(e,t){var n=this;let{identity:i}=t;return function*(){var t;const r=null!==(t=e.info.attributes)&&void 0!==t?t:{};yield n.rpcClientManager.handleIncomingDataStream(e,i,r)}()}))))}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Va.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.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,nt.STATE_MISMATCH)))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&Va.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.emit(e.RoomEvent.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach((e=>{let[t,n]=e;this.emit(t,...n)})),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 Zi(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 ot({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:_.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new lt({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 Ml(gs.Kind.Video,new vt({source:Ze.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Xe.AUDIO,name:"video-dummy"}),new dd(s.useRealTracks&&(null===(n=window.navigator.mediaDevices)||void 0===n?void 0:n.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Qs(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 Ml(gs.Kind.Audio,new vt({source:Ze.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Xe.AUDIO}),new Qc(s.useRealTracks&&(null===(r=navigator.mediaDevices)||void 0===r?void 0:r.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ys(),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 lt({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:ut.ACTIVE,tracks:[],joinedAt:_.parse(Date.now())});const n=this.getOrCreateParticipant(t.identity,t);if(o.video){const i=Qs(160*(null!==(a=o.aspectRatios[e%o.aspectRatios.length])&&void 0!==a?a:1),160,!1,!0),r=new vt({source:Ze.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Xe.AUDIO});n.addSubscribedMediaTrack(i,r.sid,new MediaStream([i]),new RTCRtpReceiver),t.tracks=[...t.tracks,r]}if(o.audio){const e=Ys(),i=new vt({source:Ze.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Xe.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=Hl(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 Hl(e){return e.map((e=>{if(e)return Array.isArray(e)?Hl(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e}))}Vl.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry((e=>{e()}));var Wl,Kl=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,(Wl=e.CheckStatus||(e.CheckStatus={}))[Wl.IDLE=0]="IDLE",Wl[Wl.RUNNING=1]="RUNNING",Wl[Wl.SKIPPED=2]="SKIPPED",Wl[Wl.SUCCESS=3]="SUCCESS",Wl[Wl.FAILED=4]="FAILED";class zl extends ar.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 Vl(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(t){return Zi(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(e){e instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(e.message):this.appendError(e.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 Zi(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 Zi(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 Zi(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 ys(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 Jl extends zl{get description(){return"Cloud regions"}perform(){return Zi(this,void 0,void 0,(function*(){const e=new Sd(this.url,this.token);if(!e.isCloud())return void this.skip();const t=[],n=new Set;for(let i=0;i<3;i++){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 Zi(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 Gl=1e4;class Ql extends zl{get description(){return"Connection via UDP vs TCP"}perform(){return Zi(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 Zi(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((()=>Zi(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,Gl))),clearInterval(c),a.stop(),t.remove(),yield this.disconnect(),o}))}}class Yl extends zl{get description(){return"Can publish audio"}perform(){return Zi(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),n=yield Al();if(yield is(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 Xl extends zl{get description(){return"Can publish video"}perform(){return Zi(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),n=yield Ol();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 Zi(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 Zl extends zl{get description(){return"Resuming connection after interruption"}perform(){return Zi(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 $l extends zl{get description(){return"Can connect via TURN"}perform(){return Zi(this,void 0,void 0,(function*(){var e,t,n;xs(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=null!==(e=yield new Sd(this.url,this.token).getNextBestRegionUrl())&&void 0!==e?e:this.url);const i=new hc,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 e of r.iceServers)for(let t of e.urls)t.startsWith("turn:")?(s=!0,o=!0):t.startsWith("turns:")&&(s=!0,o=!0,a=!0),t.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 eu extends zl{get description(){return"Establishing WebRTC connection"}perform(){return Zi(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(),Wi.info("now the room is connected")}catch(e){throw this.appendWarning("ports need to be open on firewall in order to connect."),e}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 tu extends zl{get description(){return"Connecting to signal connection via WebSocket"}perform(){return Zi(this,void 0,void 0,(function*(){var e,t,n;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let i,r=new hc;try{i=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(e){if(xs(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(e.message,". Retrying with region fallback"));const t=new Sd(this.url,this.token),n=yield t.getNextBestRegionUrl();n&&(i=yield r.join(n,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"))}}i?(this.appendMessage("Connected to server, version ".concat(i.serverVersion,".")),(null===(e=i.serverInfo)||void 0===e?void 0:e.edition)===Ft.Cloud&&(null===(t=i.serverInfo)||void 0===t?void 0:t.region)&&this.appendMessage("LiveKit Cloud: ".concat(null===(n=i.serverInfo)||void 0===n?void 0:n.region))):this.appendError("Websocket connection could not be established"),yield r.close()}))}}class nu extends ar.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 Zi(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 Zi(this,void 0,void 0,(function*(){return this.createAndRunCheck(tu)}))}checkWebRTC(){return Zi(this,void 0,void 0,(function*(){return this.createAndRunCheck(eu)}))}checkTURN(){return Zi(this,void 0,void 0,(function*(){return this.createAndRunCheck($l)}))}checkReconnect(){return Zi(this,void 0,void 0,(function*(){return this.createAndRunCheck(Zl)}))}checkPublishAudio(){return Zi(this,void 0,void 0,(function*(){return this.createAndRunCheck(Yl)}))}checkPublishVideo(){return Zi(this,void 0,void 0,(function*(){return this.createAndRunCheck(Xl)}))}checkConnectionProtocol(){return Zi(this,void 0,void 0,(function*(){const e=yield this.createAndRunCheck(Ql);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e}))}checkCloudRegion(){return Zi(this,void 0,void 0,(function*(){return this.createAndRunCheck(Jl)}))}}class iu{}class ru{}function au(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}new TextEncoder;const su=new TextDecoder;function ou(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:su.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=su.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 e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}(t)}catch(e){throw new TypeError("The input to be decoded is not correctly encoded.")}}class cu extends Error{constructor(e,t){var n;super(e,t),au(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor)}}au(cu,"code","ERR_JOSE_GENERIC");au(class extends cu{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}}),au(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),au(this,"claim",void 0),au(this,"reason",void 0),au(this,"payload",void 0),this.claim=n,this.reason=i,this.payload=t}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED");au(class extends cu{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}}),au(this,"code","ERR_JWT_EXPIRED"),au(this,"claim",void 0),au(this,"reason",void 0),au(this,"payload",void 0),this.claim=n,this.reason=i,this.payload=t}},"code","ERR_JWT_EXPIRED");au(class extends cu{constructor(){super(...arguments),au(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED");au(class extends cu{constructor(){super(...arguments),au(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED");au(class extends cu{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),au(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED");au(class extends cu{constructor(){super(...arguments),au(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID");au(class extends cu{constructor(){super(...arguments),au(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID");class du extends cu{constructor(){super(...arguments),au(this,"code","ERR_JWT_INVALID")}}au(du,"code","ERR_JWT_INVALID");au(class extends cu{constructor(){super(...arguments),au(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID");au(class extends cu{constructor(){super(...arguments),au(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID");au(class extends cu{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),au(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY");au(class extends cu{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),au(this,Symbol.asyncIterator,void 0),au(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");au(class extends cu{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),au(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT");au(class extends cu{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),au(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const lu=e=>"object"==typeof e&&null!==e;function uu(e){if("string"!=typeof e)throw new du("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:n}=e.split(".");if(5===n)throw new du("Only JWTs using Compact JWS serialization can be decoded");if(3!==n)throw new du("Invalid JWT");if(!t)throw new du("JWTs must contain a payload");let i,r;try{i=ou(t)}catch(e){throw new du("Failed to base64url decode the payload")}try{r=JSON.parse(su.decode(i))}catch(e){throw new du("Failed to parse the decoded payload as JSON")}if(!function(e){if(!lu(e)||"[object Object]"!==Object.prototype.toString.call(e))return!1;if(null===Object.getPrototypeOf(e))return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}(r))throw new du("Invalid JWT Claims Set");return r}const hu=1e3;function pu(e){const t=uu(e),{roomConfig:n}=t,i=Xi(t,["roomConfig"]);return Object.assign(Object.assign({},i),{roomConfig:t.roomConfig?wn.fromJson(t.roomConfig,{ignoreUnknownFields:!0}):void 0})}class mu extends ru{constructor(){super(...arguments),this.cachedFetchOptions=null,this.cachedResponse=null,this.fetchMutex=new r}isSameAsCachedFetchOptions(e){if(!this.cachedFetchOptions)return!1;for(const t of Object.keys(this.cachedFetchOptions))switch(t){case"roomName":case"participantName":case"participantIdentity":case"participantMetadata":case"participantAttributes":case"agentName":case"agentMetadata":if(this.cachedFetchOptions[t]!==e[t])return!1;break;default:throw new Error("Options key ".concat(t," not being checked for equality!"))}return!0}shouldReturnCachedValueFromFetch(e){return!!this.cachedResponse&&(!!function(e){const t=pu(e.participantToken);if(!(null==t?void 0:t.nbf)||!(null==t?void 0:t.exp))return!0;const n=new Date,i=t.nbf*hu,r=new Date(i),a=t.exp*hu,s=new Date(a-6e4);return r<=n&&s>n}(this.cachedResponse)&&!!this.isSameAsCachedFetchOptions(e))}getCachedResponseJwtPayload(){return this.cachedResponse?pu(this.cachedResponse.participantToken):null}fetch(e,t){return Zi(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 gu extends iu{constructor(e){super(),this.literalOrFn=e}fetch(){return Zi(this,void 0,void 0,(function*(){return"function"==typeof this.literalOrFn?this.literalOrFn():this.literalOrFn}))}}class vu extends mu{constructor(e){super(),this.customFn=e}update(e){return Zi(this,void 0,void 0,(function*(){const t=this.customFn(e);let n;return n=t instanceof Promise?yield t:t,Li.fromJson(n,{ignoreUnknownFields:!0})}))}}class fu extends mu{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;const r=new xi;for(const a of Object.keys(e))switch(a){case"roomName":case"participantName":case"participantIdentity":case"participantMetadata":r[a]=e[a];break;case"participantAttributes":r.participantAttributes=null!==(t=e.participantAttributes)&&void 0!==t?t:{};break;case"agentName":r.roomConfig=null!==(n=r.roomConfig)&&void 0!==n?n:new wn,0===r.roomConfig.agents.length&&r.roomConfig.agents.push(new nn),r.roomConfig.agents[0].agentName=e.agentName;break;case"agentMetadata":r.roomConfig=null!==(i=r.roomConfig)&&void 0!==i?i:new wn,0===r.roomConfig.agents.length&&r.roomConfig.agents.push(new nn),r.roomConfig.agents[0].metadata=e.agentMetadata;break;default:throw new Error("Options key ".concat(a," not being included in forming request!"))}return r}update(e){return Zi(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 Li.fromJson(r,{ignoreUnknownFields:!0})}))}}class ku extends fu{constructor(e,t){const{baseUrl:n="https://cloud-api.livekit.io"}=t,i=Xi(t,["baseUrl"]);super("".concat(n,"/api/v2/sandbox/connection-details"),Object.assign(Object.assign({},i),{headers:{"X-Sandbox-ID":e}}))}}const yu={literal:e=>new gu(e),custom:e=>new vu(e),endpoint(e){return new fu(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})},sandboxTokenServer(e){return new ku(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}};const bu=new Map([["obs virtual camera",{facingMode:"environment",confidence:"medium"}]]),Tu=new Map([["iphone",{facingMode:"environment",confidence:"medium"}],["ipad",{facingMode:"environment",confidence:"medium"}]]);function Su(e){var t;const n=e.trim().toLowerCase();if(""!==n)return bu.has(n)?bu.get(n):null===(t=Array.from(Tu.entries()).find((e=>{let[t]=e;return n.includes(t)})))||void 0===t?void 0:t[1]}const Eu=Symbol.for("lk.serializer");function Cu(e){return Object.assign(Object.assign({},e),{symbol:Eu})}const wu={json:function(){return Cu({parse:e=>JSON.parse(e),serialize:e=>JSON.stringify(e)})},raw:function(){return Cu({parse:e=>e,serialize:e=>e})},custom:function(e){return Cu(e)}};e.BaseKeyProvider=_o,e.CLIENT_PROTOCOL_DATA_STREAM_RPC=1,e.CLIENT_PROTOCOL_DEFAULT=0,e.Checker=zl,e.ConnectionCheck=nu,e.ConnectionError=Oa,e.CriticalTimers=Va,e.CryptorError=class extends Ea{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=St,e.DataStreamError=ja,e.DataTrackPacket=Qd,e.DefaultReconnectPolicy=Yi,e.DeviceUnsupportedError=Aa,e.DisconnectReason=nt,e.Encryption_Type=mt,e.ExternalE2EEKeyProvider=class extends _o{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 Zi(this,void 0,void 0,(function*(){const t="string"==typeof e?yield Po(e):yield Io(e);this.onSetEncryptionKey(t)}))}},e.LivekitError=Ea,e.LivekitReasonedError=Ca,e.LocalAudioTrack=Qc,e.LocalDataTrack=gl,e.LocalParticipant=Ul,e.LocalTrack=Gc,e.LocalTrackPublication=Ml,e.LocalTrackRecorder=Jc,e.LocalVideoTrack=dd,e.Mutex=r,e.NegotiationError=Ua,e.PacketTrailerManager=zo,e.Participant=Ll,e.ParticipantKind=ht,e.PublishDataError=class extends Ea{constructor(e){super(14,null!=e?e:"unable to publish data"),this.name="PublishDataError"}},e.PublishTrackError=Fa,e.RemoteAudioTrack=Il,e.RemoteDataTrack=zd,e.RemoteParticipant=ql,e.RemoteTrack=Bo,e.RemoteTrackPublication=jl,e.RemoteVideoTrack=jo,e.Room=Vl,e.RpcError=bl,e.ScreenSharePresets=$a,e.SignalReconnectError=qa,e.SignalRequestError=Ba,e.SimulatedError=class extends Ea{constructor(){super(-1,arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Simulated failure"),this.name="simulated"}},e.SubscriptionError=rt,e.TokenSource=yu,e.TokenSourceConfigurable=ru,e.TokenSourceFixed=iu,e.Track=gs,e.TrackInvalidError=Na,e.TrackPublication=Dl,e.TrackType=Xe,e.UnexpectedConnectionState=La,e.UnsupportedServer=xa,e.VideoPreset=Ha,e.VideoPresets=Xa,e.VideoPresets43=Za,e.areTokenSourceFetchOptionsEqual=function(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":if(e[i]!==t[i])return!1;break;default:throw new Error("Options key ".concat(i," not being checked for equality!"))}return!0},e.asEncryptablePacket=Mo,e.attachToElement=vs,e.attributes=Kl,e.audioCodecs=Wa,e.clientProtocol=1,e.compareVersions=js,e.createAudioAnalyser=function(e,t){const n=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),i=rs();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:()=>Zi(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=Io,e.createKeyMaterialFromString=Po,e.createLocalAudioTrack=Al,e.createLocalScreenTracks=function(e){return Zi(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0!==e.resolution||_s()||(e.resolution=$a.h1080fps30.resolution),void 0===navigator.mediaDevices.getDisplayMedia)throw new Aa("getDisplayMedia not supported");const t=os(e),n=yield navigator.mediaDevices.getDisplayMedia(t),i=n.getVideoTracks();if(0===i.length)throw new Na("no video track found");const r=new dd(i[0],void 0,!1);r.source=gs.Source.ScreenShare;const a=[r];if(n.getAudioTracks().length>0){const e=new Qc(n.getAudioTracks()[0],void 0,!1);e.source=gs.Source.ScreenShareAudio,a.push(e)}return a}))},e.createLocalTracks=_l,e.createLocalVideoTrack=Ol,e.decodeTokenPayload=pu,e.deriveKeys=function(e,t){return Zi(this,void 0,void 0,(function*(){const n=Do(e.algorithm.name,t.ratchetSalt),i=yield crypto.subtle.deriveKey(n,e,{name:yo,length:t.keySize},!1,["encrypt","decrypt"]);return{material:e,encryptionKey:i}}))},e.detachTrack=fs,e.facingModeFromDeviceLabel=Su,e.facingModeFromLocalTrack=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;const i=ro(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;Wi.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)){Wi.trace("Try to get facing mode from device label: (".concat(i.label,")"));const e=Su(i.label);void 0!==e&&(a=e)}return a},e.getBrowser=ka,e.getEmptyAudioStreamTrack=Ys,e.getEmptyVideoStreamTrack=function(){return Js||(Js=Qs()),Js.clone()},e.getLogger=zi,e.importKey=function(e){return Zi(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:yo},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 Wa.includes(e)},e.isAudioTrack=ao,e.isBackupCodec=Ga,e.isBackupVideoCodec=Ja,e.isBrowserSupported=Rs,e.isE2EESupported=Co,e.isInsertableStreamSupported=Ro,e.isLocalParticipant=po,e.isLocalTrack=ro,e.isRemoteParticipant=function(e){return!e.isLocal},e.isRemoteTrack=lo,e.isScriptTransformSupported=wo,e.isSerializer=function(e){return"object"==typeof e&&null!==e&&"symbol"in e&&e.symbol===Eu},e.isVideoCodec=Zs,e.isVideoFrame=function(e){return"type"in e},e.isVideoTrack=so,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 Zi(this,void 0,void 0,(function*(){const n=Do(e.algorithm.name,t);return crypto.subtle.deriveBits(n,e,256)}))},e.serializers=wu,e.setLogExtension=function(t,n){(n?[n]:Ki).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)Hi.getLogger(t).setLevel(e);else for(const t of Ki)t.setLevel(e)},e.supportsAV1=Ss,e.supportsAdaptiveStream=function(){return void 0!==typeof ResizeObserver&&void 0!==typeof IntersectionObserver},e.supportsAudioOutputSelection=function(){return ws()},e.supportsDynacast=function(){return bs()},e.supportsVP9=Es,e.version=Sa,e.videoCodecs=za,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)}const s=34028234663852886e22,o=-34028234663852886e22,c=4294967295,d=2147483647,l=-2147483648;function u(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>d||e<l)throw new Error("invalid int 32: "+e)}function h(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>c||e<0)throw new Error("invalid uint 32: "+e)}function p(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>s||e<o))throw new Error("invalid float 32: "+e)}const m=Symbol("@bufbuild/protobuf/enum-type");function g(e){const t=e[m];return a(t,"missing enum type on enum object"),t}function v(e,t,n,i){e[m]=f(t,n.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function f(e,t,n){const i=Object.create(null),r=Object.create(null),a=[];for(const e of t){const t=y(e);a.push(t),i[e.name]=t,r[e.no]=t}return{typeName:e,values:a,findName:e=>i[e],findNumber:e=>r[e]}}function k(e,t,n){const i={};for(const e of t){const t=y(e);i[t.localName]=t.no,i[t.no]=t.localName}return v(i,e,t),i}function y(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class b{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 n;try{n=JSON.parse(e)}catch(e){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(n,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 T(){let e=0,t=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(e|=(127&i)<<n,0==(128&i))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(15&n)<<28,t=(112&n)>>4,0==(128&n))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(t|=(127&i)<<n,0==(128&i))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function S(e,t,n){for(let i=0;i<28;i+=7){const r=e>>>i,a=!(r>>>7==0&&0==t),s=255&(a?128|r:r);if(n.push(s),!a)return}const i=e>>>28&15|(7&t)<<4,r=!(t>>3==0);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 E=4294967296;function C(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>=E&&(r+=i/E|0,i%=E)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?P(i,r):R(i,r)}function w(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(E*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()+I(s)+I(a)}function R(e,t){return{lo:0|e,hi:0|t}}function P(e,t){return t=~t,e?e=1+~e:t+=1,R(e,t)}const I=e=>{const t=String(e);return"0000000".slice(t.length)+t};function D(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 M(){let e=this.buf[this.pos++],t=127&e;if(0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,0==(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;0!=(128&e)&&t<10;t++)e=this.buf[this.pos++];if(0!=(128&e))throw new Error("invalid varint");return this.assertBounds(),t>>>0}const _=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),C(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),n(e),C(e)),dec:(e,t)=>function(e,t){let n=R(e,t);const i=2147483648&n.hi;i&&(n=P(n.lo,n.hi));const r=w(n.lo,n.hi);return i?"-"+r:r}(e,t),uDec:(e,t)=>w(e,t)}}();var O,A,N;function x(e,t,n){if(t===n)return!0;if(e==O.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 O.UINT64:case O.FIXED64:case O.INT64:case O.SFIXED64:case O.SINT64:return t==n}return!1}function L(e,t){switch(e){case O.BOOL:return!1;case O.UINT64:case O.FIXED64:case O.INT64:case O.SFIXED64:case O.SINT64:return 0==t?_.zero:"0";case O.DOUBLE:case O.FLOAT:return 0;case O.BYTES:return new Uint8Array(0);case O.STRING:return"";default:return 0}}function U(e,t){switch(e){case O.BOOL:return!1===t;case O.STRING:return""===t;case O.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}function F(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 B(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 j(e,t){return function(e){if(Array.isArray(e))return e}(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)||function(e,t){if(e){if("string"==typeof e)return F(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)?F(e,t):void 0}}(e,t)||function(){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(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"}(O||(O={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(A||(A={})),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"}(N||(N={}));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 t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw 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(h(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return u(e),D(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){p(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){h(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){u(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return u(e),D(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=_.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=_.uEnc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}int64(e){let t=_.enc(e);return S(t.lo,t.hi,this.buf),this}sint64(e){let t=_.enc(e),n=t.hi>>31;return S(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=_.uEnc(e);return S(t.lo,t.hi,this.buf),this}}class V{constructor(e,t){this.varint64=T,this.uint32=M,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 N.Varint:for(;128&this.buf[this.pos++];);break;case N.Bit64:this.pos+=4;case N.Bit32:this.pos+=4;break;case N.LengthDelimited:let n=this.uint32();this.pos+=n;break;case N.StartGroup:for(;;){const e=j(this.tag(),2),n=e[0],i=e[1];if(i===N.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 _.dec(...this.varint64())}uint64(){return _.uDec(...this.varint64())}sint64(){let e=j(this.varint64(),2),t=e[0],n=e[1],i=-(1&t);return t=(t>>>1|(1&n)<<31)^i,n=n>>>1^i,_.dec(t,n)}bool(){let e=j(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 _.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return _.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 H(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 L(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 W="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),K=[];for(let e=0;e<W.length;e++)K[W[e].charCodeAt(0)]=e;K["-".charCodeAt(0)]=W.indexOf("+"),K["_".charCodeAt(0)]=W.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 t=0;t<e.length;t++){if(n=K[e.charCodeAt(t)],void 0===n)switch(e[t]){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+=W[t>>2],r=(3&t)<<4,i=1;break;case 1:n+=W[r|t>>4],r=(15&t)<<2,i=2;break;case 2:n+=W[r|t>>6],n+=W[63&t],i=0}return i&&(n+=W[r],n+="=",1==i&&(n+="=")),n}};function J(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=j(H(t),2),s=a[0],o=a[1];for(const e of r)t.runtime.bin.readField(s,i.readerFactory(e.data),t.field,e.wireType,i);return o()}function G(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=j(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:!U(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?L(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(b.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)}O.DOUBLE,O.FLOAT,O.INT64,O.UINT64,O.INT32,O.UINT32,O.BOOL,O.STRING,O.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,n,i,r){let s=n.localName;if(n.repeated){if(a("map"!=n.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(oe(t)));const o=e[s];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(oe(e)));switch(n.kind){case"message":o.push(n.T.fromJson(e,i));break;case"enum":const t=ue(n.T,e,i.ignoreUnknownFields,!0);t!==se&&o.push(t);break;case"scalar":try{o.push(le(n.T,e,n.L,!0))}catch(t){let i="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(oe(e));throw t instanceof Error&&t.message.length>0&&(i+=": ".concat(t.message)),new Error(i)}}}}else if("map"==n.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(oe(t)));const a=e[s];for(const e of Object.entries(t)){var o=j(e,2);const s=o[0],c=o[1];if(null===c)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: map value null"));let d;try{d=de(n.K,s)}catch(e){let i="cannot decode map key for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(oe(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}switch(n.V.kind){case"message":a[d]=n.V.T.fromJson(c,i);break;case"enum":const e=ue(n.V.T,c,i.ignoreUnknownFields,!0);e!==se&&(a[d]=e);break;case"scalar":try{a[d]=le(n.V.T,c,A.BIGINT,!0)}catch(e){let i="cannot decode map value for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(oe(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:s},s="value"),n.kind){case"message":const a=n.T;if(null===t&&"google.protobuf.Value"!=a.typeName)return;let o=e[s];$(o)?o.fromJson(t,i):(e[s]=o=a.fromJson(t,i),a.fieldWrapper&&!n.oneof&&(e[s]=a.fieldWrapper.unwrapField(o)));break;case"enum":const c=ue(n.T,t,i.ignoreUnknownFields,!1);switch(c){case ae:Z(n,e);break;case se:break;default:e[s]=c}break;case"scalar":try{const i=le(n.T,t,n.L,!1);if(i===ae)Z(n,e);else e[s]=i}catch(e){let i="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(oe(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}function de(e,t){if(e===O.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return le(e,t,A.BIGINT,!0).toString()}function le(e,t,n,i){if(null===t)return i?L(e,n):ae;switch(e){case O.DOUBLE:case O.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 i=Number(t);if(Number.isNaN(i))break;if(!Number.isFinite(i))break;return e==O.FLOAT&&p(i),i;case O.INT32:case O.FIXED32:case O.SFIXED32:case O.SINT32:case O.UINT32:let r;if("number"==typeof t?r=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(r=Number(t)),void 0===r)break;return e==O.UINT32||e==O.FIXED32?h(r):u(r),r;case O.INT64:case O.SFIXED64:case O.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const a=_.parse(t);return n?a.toString():a;case O.FIXED64:case O.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const s=_.uParse(t);return n?s.toString():s;case O.BOOL:if("boolean"!=typeof t)break;return t;case O.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case O.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 t of c){var i=j(t,2);const n=i[0],r=i[1];o[n.toString()]=ge(e.V.T,r)}break;case"message":for(const e of c){var r=j(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=j(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 O.INT32:case O.SFIXED32:case O.SINT32:case O.FIXED32:case O.UINT32:return a("number"==typeof t),t;case O.FLOAT:case O.DOUBLE:return a("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case O.STRING:return a("string"==typeof t),t;case O.BOOL:return a("boolean"==typeof t),t;case O.UINT64:case O.FIXED64:case O.INT64:case O.SFIXED64:case O.SINT64:return a("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case O.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?O.INT32:n.T;let c=Ce;if("scalar"==n.kind&&n.L>0&&(c=Ee),a){let n=e[s];if(i==N.LengthDelimited&&o!=O.STRING&&o!=O.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(j(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=L(e.K,A.BIGINT));"string"!=typeof a&&"number"!=typeof a&&(a=a.toString());if(void 0===s)switch(e.V.kind){case"scalar":s=L(e.V.T,A.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=j(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 O.STRING:return e.string();case O.BOOL:return e.bool();case O.DOUBLE:return e.double();case O.FLOAT:return e.float();case O.INT32:return e.int32();case O.INT64:return e.int64();case O.UINT64:return e.uint64();case O.FIXED64:return e.fixed64();case O.BYTES:return e.bytes();case O.FIXED32:return e.fixed32();case O.SFIXED32:return e.sfixed32();case O.SFIXED64:return e.sfixed64();case O.SINT64:return e.sint64();case O.UINT32:return e.uint32();case O.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?O.INT32:e.T;if(r)if(a(Array.isArray(t)),e.packed)!function(e,t,n,i){if(!i.length)return;e.tag(n,N.LengthDelimited).fork();let r=j(De(t),2)[1];for(let t=0;t<i.length;t++)e[r](i[t]);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=j(r,2);Re(n,i,e,s[0],s[1])}}}function Re(e,t,n,i,r){e.tag(n.no,N.LengthDelimited),e.fork();let s=i;switch(n.K){case O.INT32:case O.FIXED32:case O.UINT32:case O.SFIXED32:case O.SINT32:s=Number.parseInt(i);break;case O.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,O.INT32,2,r);break;case"message":a(void 0!==r),e.tag(2,N.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,N.StartGroup).raw(r.toBinary(t)).tag(n.no,N.EndGroup):e.tag(n.no,N.LengthDelimited).bytes(r.toBinary(t))}function Ie(e,t,n,i){a(void 0!==i);let r=j(De(t),2),s=r[0],o=r[1];e.tag(n,s)[o](i)}function De(e){let t=N.Varint;switch(e){case O.BYTES:case O.STRING:t=N.LengthDelimited;break;case O.DOUBLE:case O.FIXED64:case O.SFIXED64:t=N.Bit64;break;case O.FIXED32:case O.SFIXED32:case O.FLOAT:t=N.Bit32}return[t,O[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 _e(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=xe(e);return t?n:je(Be(n))}const Ne=xe;function xe(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 Le=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=>Le.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=(He=e=>new Oe(e,(e=>function(e,t){var n,i,r,a,s,o;const c=[];let d;for(const t of"function"==typeof e?e():e){const e=t;if(e.localName=Ae(t.name,void 0!==t.oneof),e.jsonName=null!==(n=t.jsonName)&&void 0!==n?n:Ne(t.name),e.repeated=null!==(i=t.repeated)&&void 0!==i&&i,"scalar"==t.kind&&(e.L=null!==(r=t.L)&&void 0!==r?r:A.BIGINT),e.delimited=null!==(a=t.delimited)&&void 0!==a&&a,e.req=null!==(s=t.req)&&void 0!==s&&s,e.opt=null!==(o=t.opt)&&void 0!==o&&o,void 0===t.packed&&(e.packed="enum"==t.kind||"scalar"==t.kind&&t.T!=O.BYTES&&t.T!=O.STRING),void 0!==t.oneof){const n="string"==typeof t.oneof?t.oneof:t.oneof.name;d&&d.name==n||(d=new qe(n)),e.oneof=d,d.addField(e)}c.push(e)}return c}(e))),We=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]=L(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=j(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=j(H(s),2),t=e[0],a=e[1];ce(t,c,s.field,n,s),G(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 n=e.getType(),i={};let r;try{for(r of n.fields.byNumber()){if(!X(r,e)){if(r.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!he(r))continue}const n=pe(r,r.oneof?e[r.oneof.localName].value:e[r.localName],t);void 0!==n&&(i[t.useProtoFieldName?r.name:r.jsonName]=n)}const a=t.typeRegistry;if(null==a?void 0:a.findExtensionFor)for(const r of n.runtime.bin.listUnknownFields(e)){const s=a.findExtensionFor(n.typeName,r.no);if(s&&Q(e,s)){const n=J(e,s,t),r=pe(s.field,n,t);void 0!==r&&(i[s.field.jsonName]=r)}}}catch(e){const t=r?"cannot encode field ".concat(n.typeName,".").concat(r.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),i=e instanceof Error?e.message:String(e);throw new Error(t+(i.length>0?": ".concat(i):""))}return i},readScalar:(e,t,n)=>le(e,t,null!=n?n:A.BIGINT,!0),writeScalar(e,t,n){if(void 0!==t)return n||U(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 e of n)t.tag(e.no,e.wireType).raw(e.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=j(t.tag(),2);if(o=d[0],c=d[1],!0===r&&c==N.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!=N.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:v,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===O.BYTES&&(o=_e(o)),a[n]={case:e,value:o};break;case"scalar":case"enum":let c=s[n];r.T===O.BYTES&&(c=r.repeated?c.map(_e):_e(c)),a[n]=c;break;case"map":switch(r.V.kind){case"scalar":case"enum":if(r.V.T===O.BYTES)for(const e of Object.entries(s[n])){var i=j(e,2);const t=i[0],r=i[1];a[n][t]=_e(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]=_e(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)=>x(e.T,t,r[n])));case"enum":return i.every(((e,t)=>x(O.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 x(O.INT32,i,r);case"scalar":return x(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 x(O.INT32,i.value,r.value);case"scalar":return x(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=>x(O.INT32,i[e],r[e])));case"scalar":const n=e.V.T;return s.every((e=>x(n,i[e],r[e])))}}})),clone(e){const t=e.getType(),n=new t,i=n;for(const n of t.fields.byMember()){const t=e[n.localName];let a;if(n.repeated)a=t.map(Me);else if("map"==n.kind){a=i[n.localName];for(const e of Object.entries(t)){var r=j(e,2);const t=r[0],n=r[1];a[t]=Me(n)}}else a="oneof"==n.kind?n.findField(t.case)?{case:t.case,value:Me(t.value)}:{case:void 0}:Me(t);i[n.localName]=a}for(const n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(i,n.no,n.wireType,n.data);return n}}),{newFieldList:He,initFields:We}),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 b),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:k,makeEnumType:f,getEnumType:g,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 He,We;class Ke extends b{constructor(e){super(),this.seconds=_.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=_.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:_.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:Je,repeated:!0},{no:5,name:"events",kind:"message",T:Qe,repeated:!0}])),Je=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:Ge,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),Ge=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"}]),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:Gt}])),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}])),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"}]),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:St,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:Ve.getEnumType(Et)},{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:St,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:Gt},{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)}])),Tt=Ve.makeMessageType("livekit.DataTrackSubscriptionOptions",(()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}])),St=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}])),Et=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"}]),Ct=Ve.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:Ve.getEnumType(wt)},{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:Mt,oneof:"value"},{no:3,name:"speaker",kind:"message",T:It,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:_t,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Ot,oneof:"value"},{no:8,name:"metrics",kind:"message",T:ze,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:Nt,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:xt,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Lt,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Ut,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Zt,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:$t,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:en,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:Rt,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}])),wt=Ve.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Rt=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}])),Pt=Ve.makeMessageType("livekit.EncryptedPacketPayload",(()=>[{no:1,name:"user",kind:"message",T:Mt,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:Nt,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:xt,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:Lt,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:Ut,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:Zt,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:$t,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:en,oneof:"value"}])),It=Ve.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:Dt,repeated:!0}])),Dt=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}])),Mt=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}])),_t=Ve.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),Ot=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:At,repeated:!0}])),At=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}])),Nt=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}])),xt=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}])),Lt=Ve.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),Ut=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:Ft,oneof:"value"},{no:4,name:"compressed_payload",kind:"scalar",T:12,oneof:"value"}])),Ft=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}])),Bt=Ve.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),jt=Ve.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:Ve.getEnumType(qt)},{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}])),qt=Ve.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Vt=Ve.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:Ve.getEnumType(Ht)},{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(Wt),repeated:!0}])),Ht=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"}]),Wt=Ve.makeEnum("livekit.ClientInfo.Capability",[{no:0,name:"CAP_UNUSED"},{no:1,name:"CAP_PACKET_TRAILER"}]),Kt=Ve.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:zt},{no:2,name:"screen",kind:"message",T:zt},{no:3,name:"resume_connection",kind:"enum",T:Ve.getEnumType(rt)},{no:4,name:"disabled_codecs",kind:"message",T:Jt},{no:5,name:"force_relay",kind:"enum",T:Ve.getEnumType(rt)}])),zt=Ve.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:Ve.getEnumType(rt)}])),Jt=Ve.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:ut,repeated:!0},{no:2,name:"publish",kind:"message",T:ut,repeated:!0}])),Gt=Ve.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),Qt=Ve.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Yt=Ve.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:Ve.getEnumType(Qt)},{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"}),Xt=Ve.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),Zt=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:Yt,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Xt,oneof:"content_header"}]),{localName:"DataStream_Header"}),$t=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"}),en=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"}),tn=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}])),nn=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:tn}])),rn=Ve.makeMessageType("livekit.SubscribedAudioCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}])),an=Ve.makeEnum("livekit.JobRestartPolicy",[{no:0,name:"JRP_ON_FAILURE"},{no:1,name:"JRP_NEVER"}]),sn=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(an)},{no:4,name:"deployment",kind:"scalar",T:9}])),on=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"}]),cn=Ve.makeEnum("livekit.EncodedFileType",[{no:0,name:"DEFAULT_FILETYPE"},{no:1,name:"MP4"},{no:2,name:"OGG"},{no:3,name:"MP3"}]),dn=Ve.makeEnum("livekit.StreamProtocol",[{no:0,name:"DEFAULT_PROTOCOL"},{no:1,name:"RTMP"},{no:2,name:"SRT"},{no:3,name:"WEBSOCKET"}]),ln=Ve.makeEnum("livekit.SegmentedFileProtocol",[{no:0,name:"DEFAULT_SEGMENTED_FILE_PROTOCOL"},{no:1,name:"HLS_PROTOCOL"}]),un=Ve.makeEnum("livekit.SegmentedFileSuffix",[{no:0,name:"INDEX"},{no:1,name:"TIMESTAMP"}]),hn=Ve.makeEnum("livekit.ImageFileSuffix",[{no:0,name:"IMAGE_SUFFIX_INDEX"},{no:1,name:"IMAGE_SUFFIX_TIMESTAMP"},{no:2,name:"IMAGE_SUFFIX_NONE_OVERWRITE"}]),pn=Ve.makeEnum("livekit.AudioMixing",[{no:0,name:"DEFAULT_MIXING"},{no:1,name:"DUAL_CHANNEL_AGENT"},{no:2,name:"DUAL_CHANNEL_ALTERNATE"}]),mn=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}])),gn=Ve.makeMessageType("livekit.StreamOutput",(()=>[{no:1,name:"protocol",kind:"enum",T:Ve.getEnumType(dn)},{no:2,name:"urls",kind:"scalar",T:9,repeated:!0}])),vn=Ve.makeMessageType("livekit.SegmentedFileOutput",(()=>[{no:1,name:"protocol",kind:"enum",T:Ve.getEnumType(ln)},{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(un)},{no:8,name:"disable_manifest",kind:"scalar",T:8},{no:5,name:"s3",kind:"message",T:kn,oneof:"output"},{no:6,name:"gcp",kind:"message",T:yn,oneof:"output"},{no:7,name:"azure",kind:"message",T:bn,oneof:"output"},{no:9,name:"aliOSS",kind:"message",T:Tn,oneof:"output"}])),fn=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(hn)},{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:kn,oneof:"output"},{no:9,name:"gcp",kind:"message",T:yn,oneof:"output"},{no:10,name:"azure",kind:"message",T:bn,oneof:"output"},{no:11,name:"aliOSS",kind:"message",T:Tn,oneof:"output"}])),kn=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:Sn}])),yn=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:Sn}])),bn=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}])),Tn=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}])),Sn=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}])),En=Ve.makeMessageType("livekit.AutoParticipantEgress",(()=>[{no:1,name:"preset",kind:"enum",T:Ve.getEnumType(on),oneof:"options"},{no:2,name:"advanced",kind:"message",T:mn,oneof:"options"},{no:3,name:"file_outputs",kind:"message",T:Rn,repeated:!0},{no:4,name:"segment_outputs",kind:"message",T:vn,repeated:!0}])),Cn=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:kn,oneof:"output"},{no:3,name:"gcp",kind:"message",T:yn,oneof:"output"},{no:4,name:"azure",kind:"message",T:bn,oneof:"output"},{no:6,name:"aliOSS",kind:"message",T:Tn,oneof:"output"}])),wn=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(pn)},{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:Rn,oneof:"output"},{no:7,name:"stream",kind:"message",T:gn,oneof:"output"},{no:10,name:"segments",kind:"message",T:vn,oneof:"output"},{no:8,name:"preset",kind:"enum",T:Ve.getEnumType(on),oneof:"options"},{no:9,name:"advanced",kind:"message",T:mn,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:Rn,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:gn,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:vn,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:fn,repeated:!0},{no:16,name:"webhooks",kind:"message",T:nn,repeated:!0}])),Rn=Ve.makeMessageType("livekit.EncodedFileOutput",(()=>[{no:1,name:"file_type",kind:"enum",T:Ve.getEnumType(cn)},{no:2,name:"filepath",kind:"scalar",T:9},{no:6,name:"disable_manifest",kind:"scalar",T:8},{no:3,name:"s3",kind:"message",T:kn,oneof:"output"},{no:4,name:"gcp",kind:"message",T:yn,oneof:"output"},{no:5,name:"azure",kind:"message",T:bn,oneof:"output"},{no:7,name:"aliOSS",kind:"message",T:Tn,oneof:"output"}])),Pn=Ve.makeMessageType("livekit.RoomEgress",(()=>[{no:1,name:"room",kind:"message",T:wn},{no:3,name:"participant",kind:"message",T:En},{no:2,name:"tracks",kind:"message",T:Cn}])),In=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:Pn},{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:sn,repeated:!0},{no:12,name:"tags",kind:"map",K:9,V:{kind:"scalar",T:9}}])),Dn=Ve.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Mn=Ve.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),_n=Ve.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),On=Ve.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:Gn,oneof:"message"},{no:2,name:"answer",kind:"message",T:Gn,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Vn,oneof:"message"},{no:4,name:"add_track",kind:"message",T:xn,oneof:"message"},{no:5,name:"mute",kind:"message",T:Hn,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Yn,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:$n,oneof:"message"},{no:8,name:"leave",kind:"message",T:ni,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:ri,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:ki,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Ti,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Ci,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:ai,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:wi,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:ei,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:ti,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:Ln,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:Fn,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:Xn,oneof:"message"}])),An=Ve.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:Wn,oneof:"message"},{no:2,name:"answer",kind:"message",T:Gn,oneof:"message"},{no:3,name:"offer",kind:"message",T:Gn,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Vn,oneof:"message"},{no:5,name:"update",kind:"message",T:Qn,oneof:"message"},{no:6,name:"track_published",kind:"message",T:zn,oneof:"message"},{no:8,name:"leave",kind:"message",T:ni,oneof:"message"},{no:9,name:"mute",kind:"message",T:Hn,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:oi,oneof:"message"},{no:11,name:"room_update",kind:"message",T:ci,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:li,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:hi,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:gi,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:yi,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Jn,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Kn,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Ri,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Di,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Mi,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Oi,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:bi,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:Ui,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:vi,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:Un,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:Bn,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:jn,oneof:"message"}])),Nn=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:St,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:Ve.getEnumType(Et)}])),xn=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:St,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Nn,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}])),Ln=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)}])),Un=Ve.makeMessageType("livekit.PublishDataTrackResponse",(()=>[{no:1,name:"info",kind:"message",T:bt}])),Fn=Ve.makeMessageType("livekit.UnpublishDataTrackRequest",(()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}])),Bn=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"}),Vn=Ve.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:Ve.getEnumType(Dn)},{no:3,name:"final",kind:"scalar",T:8}])),Hn=Ve.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),Wn=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:si,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:Kt},{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:jt},{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}])),Kn=Ve.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:si,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Kt},{no:3,name:"server_info",kind:"message",T:jt},{no:4,name:"last_message_seq",kind:"scalar",T:13}])),zn=Ve.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:yt}])),Jn=Ve.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),Gn=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}}])),Qn=Ve.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:pt,repeated:!0}])),Yn=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:Bt,repeated:!0}])),Xn=Ve.makeMessageType("livekit.UpdateDataSubscription",(()=>[{no:1,name:"updates",kind:"message",T:Zn,repeated:!0}])),Zn=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:Tt}]),{localName:"UpdateDataSubscription_Update"}),$n=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}])),ei=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}])),ti=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}])),ni=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(ii)},{no:4,name:"regions",kind:"message",T:Pi}])),ii=Ve.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),ri=Ve.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:St,repeated:!0}])),ai=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}])),si=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}])),oi=Ve.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:Dt,repeated:!0}])),ci=Ve.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:lt}])),di=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}])),li=Ve.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:di,repeated:!0}])),ui=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(Mn)}])),hi=Ve.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:ui,repeated:!0}])),pi=Ve.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:Ve.getEnumType(nt)},{no:2,name:"enabled",kind:"scalar",T:8}])),mi=Ve.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:pi,repeated:!0}])),gi=Ve.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:pi,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:mi,repeated:!0}])),vi=Ve.makeMessageType("livekit.SubscribedAudioCodecUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:rn,repeated:!0}])),fi=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}])),ki=Ve.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:fi,repeated:!0}])),yi=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}])),bi=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}])),Ti=Ve.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:Gn},{no:2,name:"subscription",kind:"message",T:Yn},{no:3,name:"publish_tracks",kind:"message",T:zn,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Ei,repeated:!0},{no:5,name:"offer",kind:"message",T:Gn},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:Si,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:Un,repeated:!0}])),Si=Ve.makeMessageType("livekit.DataChannelReceiveState",(()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}])),Ei=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(Dn)}])),Ci=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(_n),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}])),wi=Ve.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),Ri=Ve.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),Pi=Ve.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:Ii,repeated:!0}])),Ii=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}])),Di=Ve.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:Ve.getEnumType(ot)}])),Mi=Ve.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:Ve.getEnumType(_i)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:Vn,oneof:"request"},{no:5,name:"add_track",kind:"message",T:xn,oneof:"request"},{no:6,name:"mute",kind:"message",T:Hn,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:ai,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:ei,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:ti,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:Ln,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:Fn,oneof:"request"}])),_i=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"}]),Oi=Ve.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),Ai=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}])),Ni=Ve.makeMessageType("livekit.JoinRequest",(()=>[{no:1,name:"client_info",kind:"message",T:Vt},{no:2,name:"connection_settings",kind:"message",T:Ai},{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:xn,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:Gn},{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:Ti}])),xi=Ve.makeMessageType("livekit.WrappedJoinRequest",(()=>[{no:1,name:"compression",kind:"enum",T:Ve.getEnumType(Li)},{no:2,name:"join_request",kind:"scalar",T:12}])),Li=Ve.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),Ui=Ve.makeMessageType("livekit.MediaSectionsRequirement",(()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}])),Fi=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:In,opt:!0}])),Bi=Ve.makeMessageType("livekit.TokenSourceResponse",(()=>[{no:1,name:"server_url",kind:"scalar",T:9},{no:2,name:"participant_token",kind:"scalar",T:9}]));function ji(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var qi,Vi={exports:{}},Hi=Vi.exports;var Wi,Ki,zi=(qi||(qi=1,function(e){var t,n;t=Hi,n=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],r={},a=null;function s(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var n=this.getLevel(),r=0;r<i.length;r++){var a=i[r];this[a]=r<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 d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function l(i,r,a){return function(i){return"debug"===i&&(i="log"),typeof console!==t&&("trace"===i&&n?o:void 0!==console[i]?s(console,i):void 0!==console.log?s(console,"log"):e)}(i)||d.apply(this,arguments)}function u(e,n){var s,o,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}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(e){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=n||l,u.getLevel=function(){return null!=d?d:null!=o?o:s},u.setLevel=function(e,n){return d=m(e),!1!==n&&function(e){var n=(i[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+n+";"}catch(e){}}}(d),c.call(u)},u.setDefaultLevel=function(e){o=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(a!==u&&(s=m(a.getLevel())),c.call(u),a===u)for(var e in r)r[e].rebuild()},s=m(a?a.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(a=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=r[e];return t||(t=r[e]=new u(e,a.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=h),a},a.getLoggers=function(){return r},a.default=a,a},e.exports?e.exports=n():t.log=n()}(Vi)),Vi.exports);e.LogLevel=void 0,(Wi=e.LogLevel||(e.LogLevel={}))[Wi.trace=0]="trace",Wi[Wi.debug=1]="debug",Wi[Wi.info=2]="info",Wi[Wi.warn=3]="warn",Wi[Wi.error=4]="error",Wi[Wi.silent=5]="silent",e.LoggerNames=void 0,(Ki=e.LoggerNames||(e.LoggerNames={})).Default="livekit",Ki.Room="livekit-room",Ki.TokenSource="livekit-token-source",Ki.Participant="livekit-participant",Ki.Track="livekit-track",Ki.Publication="livekit-track-publication",Ki.Engine="livekit-engine",Ki.Signal="livekit-signal",Ki.PCManager="livekit-pc-manager",Ki.PCTransport="livekit-pc-transport",Ki.E2EE="lk-e2ee",Ki.DataTracks="livekit-data-tracks";let Ji=zi.getLogger(e.LoggerNames.Default);const Gi=Object.values(e.LoggerNames).map((e=>zi.getLogger(e)));function Qi(e,t){const n=zi.getLogger(e);return n.setDefaultLevel(Ji.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}Ji.setDefaultLevel(e.LogLevel.info);const Yi=zi.getLogger(e.LoggerNames.E2EE),Xi=7e3,Zi=[0,300,1200,2700,4800,Xi,Xi,Xi,Xi,Xi];class $i{constructor(e){this._retryDelays=void 0!==e?[...e]:Zi}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 er(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 tr(e,t,n,i){return new(n||(n=Promise))((function(r,a){function s(e){try{c(i.next(e))}catch(e){a(e)}}function o(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,o)}c((i=i.apply(e,t||[])).next())}))}function nr(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 ir(e){return this instanceof ir?(this.v=e,this):new ir(e)}function rr(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,r=n.apply(e,t||[]),a=[];return i=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",(function(e){return function(t){return Promise.resolve(t).then(e,d)}})),i[Symbol.asyncIterator]=function(){return this},i;function s(e,t){r[e]&&(i[e]=function(t){return new Promise((function(n,i){a.push([e,t,n,i])>1||o(e,t)}))},t&&(i[e]=t(i[e])))}function o(e,t){try{(n=r[e](t)).value instanceof ir?Promise.resolve(n.value.v).then(c,d):l(a[0][2],n)}catch(e){l(a[0][3],e)}var n}function c(e){o("next",e)}function d(e){o("throw",e)}function l(e,t){e(t),a.shift(),a.length&&o(a[0][0],a[0][1])}}function ar(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=nr(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 sr,or={exports:{}};var cr=function(){if(sr)return or.exports;sr=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)}or.exports=r,or.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):[]},or.exports}(),dr=ji(cr);let lr=!0,ur=!0;function hr(e,t,n){const i=e.match(t);return i&&i.length>=n&&parseFloat(i[n],10)}function pr(e,t,n){if(!e.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,"addEventListener").writable)return void vr("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 mr(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(lr=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function gr(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(ur=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function vr(){if("object"==typeof window){if(lr)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function fr(e,t){ur&&console.warn(e+" is deprecated, please use "+t+" instead.")}function kr(e){return"[object Object]"===Object.prototype.toString.call(e)}function yr(e){return kr(e)?Object.keys(e).reduce((function(t,n){const i=kr(e[n]),r=i?yr(e[n]):e[n],a=i&&!Object.keys(r).length;return void 0===r||a?t:Object.assign(t,{[n]:r})}),{}):e}function br(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?br(e,e.get(t[i]),n):i.endsWith("Ids")&&t[i].forEach((t=>{br(e,e.get(t),n)}))})))}function Tr(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&&br(e,n,r)}))})),r}const Sr=vr;function Er(e,t){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),Sr("chrome: "+JSON.stringify(e)),r(e)}))}e.video=i(e.video)}return Sr("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 Cr(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function wr(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 pr(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function Rr(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 Pr(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=>Tr(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}),pr(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Tr(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 Ir(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 Dr(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Ir(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 Mr(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 _r(e,t){t.version>102||pr(e,"negotiationneeded",(e=>{const n=e.target;if(!(t.version<72||n.getConfiguration&&"plan-b"===n.getConfiguration().sdpSemantics)||"stable"===n.signalingState)return e}))}var Or=Object.freeze({__proto__:null,fixNegotiationNeeded:_r,shimAddTrackRemoveTrack:Dr,shimAddTrackRemoveTrackWithNative:Ir,shimGetSendersWithDtmf:Rr,shimGetUserMedia:Er,shimMediaStream:Cr,shimOnTrack:wr,shimPeerConnection:Mr,shimSenderReceiverGetStats:Pr});function Ar(e,t){const n=e&&e.navigator,i=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,i){fr("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 Nr(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 xr(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 Lr(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;if(t.version>=151)return;const n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const e=Array.prototype.slice.call(arguments),r=e[0],a=e[1],s=e[2];return"closed"===this.signalingState?Promise.resolve(new Map):i.apply(this,[r||null]).then((e=>{if(t.version<53&&!a)try{e.forEach((e=>{e.type=n[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:n[t.type]||t.type}))}))}return e})).then(a,s)}}function Ur(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 Fr(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}),pr(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Br(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){fr("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function jr(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function qr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const n=e.length>0;n&&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=t.apply(this,arguments);if(n){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 Vr(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Hr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function Wr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var Kr=Object.freeze({__proto__:null,shimAddTransceiver:qr,shimCreateAnswer:Wr,shimCreateOffer:Hr,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||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:Vr,shimGetStats:Lr,shimGetUserMedia:Ar,shimOnTrack:Nr,shimPeerConnection:xr,shimRTCDataChannel:jr,shimReceiverGetStats:Fr,shimRemoveStream:Br,shimSenderGetStats:Ur});function zr(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 Jr(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 Gr(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 Qr(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(Yr(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,i){t.mediaDevices.getUserMedia(e).then(n,i)}.bind(t))}function Yr(e){return e&&void 0!==e.video?Object.assign({},e,{video:yr(e.video)}):e}function Xr(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?(fr("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 Zr(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 $r(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 ea(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var ta,na=Object.freeze({__proto__:null,shimAudioContext:ea,shimCallbacksAPI:Gr,shimConstraints:Yr,shimCreateOfferLegacy:$r,shimGetUserMedia:Qr,shimLocalStreamsAPI:zr,shimRTCIceServerUrls:Xr,shimRemoteStreamsAPI:Jr,shimTrackEventTransceiver:Zr}),ia={exports:{}};var ra=(ta||(ta=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 e=8;e<t.length;e+=2)switch(t[e]){case"raddr":n.relatedAddress=t[e+1];break;case"rport":n.relatedPort=parseInt(t[e+1],10);break;case"tcptype":n.tcpType=t[e+1];break;case"ufrag":n.ufrag=t[e+1],n.usernameFragment=t[e+1];break;default:void 0===n[t[e]]&&(n[t[e]]=t[e+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 e=0;e<i.length;e++)n=i[e].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 r=3;r<i.length;r++){const a=i[r],s=t.matchPrefix(e,"a=rtpmap:"+a+" ")[0];if(s){const i=t.parseRtpMap(s),r=t.matchPrefix(e,"a=fmtp:"+a+" ");switch(i.parameters=r.length?t.parseFmtp(r[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+a+" ").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 e=0;e<i.length;e++)switch(i[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[e].substring(2)}return n?t.getDirection(n):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"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 e=0;e<n.length;e++)if(n[e].length<2||"="!==n[e].charAt(1))return!1;return!0},e.exports=t}(ia)),ia.exports),aa=ji(ra),sa=t({__proto__:null,default:aa},[ra]);function oa(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=aa.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,pr(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function ca(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||pr(e,"icecandidate",(e=>{if(e.candidate){const t=aa.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function da(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const 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=aa.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=aa.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=aa.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 la(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},pr(e,"datachannel",(e=>(n(e.channel,e.target),e)))}function ua(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 ha(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 pa(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 ma(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 ga,va,fa=Object.freeze({__proto__:null,removeExtmapAllowMixed:ha,shimAddIceCandidateNullOrEmpty:pa,shimConnectionState:ua,shimMaxMessageSize:da,shimParameterlessSetLocalDescription:ma,shimRTCIceCandidate:oa,shimRTCIceCandidateRelayProtocol:ca,shimSendThrowTypeError:la});!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=vr,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)return{browser:"chrome",version:parseInt(e.version,10)}}if(n.mozGetUserMedia)t.browser="firefox",t.version=parseInt(hr(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(hr(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(hr(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=hr(n.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),r={browserDetails:i,commonShim:fa,extractVersion:hr,disableLog:mr,disableWarnings:gr,sdp:sa};switch(i.browser){case"chrome":if(!Or||!Mr||!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=Or,pa(e,i),ma(e),Er(e,i),Cr(e),Mr(e,i),wr(e,i),Dr(e,i),Rr(e),Pr(e,i),_r(e,i),oa(e),ca(e),ua(e),da(e,i),la(e,i),ha(e,i);break;case"firefox":if(!Kr||!xr||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=Kr,pa(e,i),ma(e),Ar(e,i),xr(e,i),Lr(e,i),Nr(e),Br(e),Ur(e),Fr(e),jr(e),qr(e),Vr(e),Hr(e),Wr(e),oa(e),ua(e),da(e,i),la(e,i);break;case"safari":if(!na||!t.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=na,pa(e,i),ma(e),Xr(e),$r(e),Gr(e),zr(e),Jr(e),Zr(e),Qr(e),ea(e),oa(e),ca(e),da(e,i),la(e,i),ha(e,i);break;default:n("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});class ka extends(va=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)}}ga=ka,ka.resolve=e=>Reflect.get(va,"resolve",ga).call(ga,e);const ya=/version\/(\d+(\.?_?\d+)+)/i;let ba;function Ta(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===ba||t){const e=Sa.find((e=>e.test.test(n)));ba=null==e?void 0:e.describe(n)}return ba}const Sa=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:Ea(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Ca(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:Ea(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Ca(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:Ea(ya,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:Ca(e)})}];function Ea(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 Ca(e){return e.includes("mac os")?Ea(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}const wa="2.19.2";class Ra 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 Pa extends Ra{}var Ia,Da,Ma,_a,Oa,Aa,Na;e.ConnectionErrorReason=void 0,(Ia=e.ConnectionErrorReason||(e.ConnectionErrorReason={}))[Ia.NotAllowed=0]="NotAllowed",Ia[Ia.ServerUnreachable=1]="ServerUnreachable",Ia[Ia.InternalError=2]="InternalError",Ia[Ia.Cancelled=3]="Cancelled",Ia[Ia.LeaveRequest=4]="LeaveRequest",Ia[Ia.Timeout=5]="Timeout",Ia[Ia.WebSocket=6]="WebSocket",Ia[Ia.ServiceNotFound=7]="ServiceNotFound";class xa extends Pa{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 xa(t,e.ConnectionErrorReason.NotAllowed,n,i)}static timeout(t){return new xa(t,e.ConnectionErrorReason.Timeout)}static leaveRequest(t,n){return new xa(t,e.ConnectionErrorReason.LeaveRequest,void 0,n)}static internal(t,n){return new xa(t,e.ConnectionErrorReason.InternalError,void 0,n)}static cancelled(t){return new xa(t,e.ConnectionErrorReason.Cancelled)}static serverUnreachable(t,n){return new xa(t,e.ConnectionErrorReason.ServerUnreachable,n)}static websocket(t,n,i){return new xa(t,e.ConnectionErrorReason.WebSocket,n,i)}static serviceNotFound(t,n){return new xa(t,e.ConnectionErrorReason.ServiceNotFound,void 0,n)}}class La extends Ra{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class Ua extends Ra{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class Fa extends Ra{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class Ba extends Ra{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class ja extends Ra{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class qa extends Ra{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Va extends Pa{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName="string"==typeof t?t:_i[t]}}e.DataStreamErrorReason=void 0,(Da=e.DataStreamErrorReason||(e.DataStreamErrorReason={}))[Da.AlreadyOpened=0]="AlreadyOpened",Da[Da.AbnormalEnd=1]="AbnormalEnd",Da[Da.DecodeFailed=2]="DecodeFailed",Da[Da.LengthExceeded=3]="LengthExceeded",Da[Da.Incomplete=4]="Incomplete",Da[Da.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",Da[Da.EncryptionTypeMismatch=8]="EncryptionTypeMismatch";class Ha extends Pa{constructor(t,n){super(16,t),this.name="DataStreamError",this.reason=n,this.reasonName=e.DataStreamErrorReason[n]}}class Wa extends Ra{constructor(e){super(18,e),this.name="SignalReconnectError"}}e.MediaDeviceFailure=void 0,(Ma=e.MediaDeviceFailure||(e.MediaDeviceFailure={})).PermissionDenied="PermissionDenied",Ma.NotFound="NotFound",Ma.DeviceInUse="DeviceInUse",Ma.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 Ka{}Ka.setTimeout=function(){return setTimeout(...arguments)},Ka.setInterval=function(){return setInterval(...arguments)},Ka.clearTimeout=function(){return clearTimeout(...arguments)},Ka.clearInterval=function(){return clearInterval(...arguments)},e.RoomEvent=void 0,(_a=e.RoomEvent||(e.RoomEvent={})).Connected="connected",_a.Reconnecting="reconnecting",_a.SignalReconnecting="signalReconnecting",_a.Reconnected="reconnected",_a.Disconnected="disconnected",_a.ConnectionStateChanged="connectionStateChanged",_a.Moved="moved",_a.MediaDevicesChanged="mediaDevicesChanged",_a.ParticipantConnected="participantConnected",_a.ParticipantDisconnected="participantDisconnected",_a.TrackPublished="trackPublished",_a.TrackSubscribed="trackSubscribed",_a.TrackSubscriptionFailed="trackSubscriptionFailed",_a.TrackUnpublished="trackUnpublished",_a.TrackUnsubscribed="trackUnsubscribed",_a.TrackMuted="trackMuted",_a.TrackUnmuted="trackUnmuted",_a.LocalTrackPublished="localTrackPublished",_a.LocalTrackUnpublished="localTrackUnpublished",_a.LocalAudioSilenceDetected="localAudioSilenceDetected",_a.ActiveSpeakersChanged="activeSpeakersChanged",_a.ParticipantMetadataChanged="participantMetadataChanged",_a.ParticipantNameChanged="participantNameChanged",_a.ParticipantAttributesChanged="participantAttributesChanged",_a.ParticipantActive="participantActive",_a.RoomMetadataChanged="roomMetadataChanged",_a.DataReceived="dataReceived",_a.SipDTMFReceived="sipDTMFReceived",_a.TranscriptionReceived="transcriptionReceived",_a.ConnectionQualityChanged="connectionQualityChanged",_a.TrackStreamStateChanged="trackStreamStateChanged",_a.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",_a.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",_a.AudioPlaybackStatusChanged="audioPlaybackChanged",_a.VideoPlaybackStatusChanged="videoPlaybackChanged",_a.MediaDevicesError="mediaDevicesError",_a.ParticipantPermissionsChanged="participantPermissionsChanged",_a.SignalConnected="signalConnected",_a.RecordingStatusChanged="recordingStatusChanged",_a.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",_a.EncryptionError="encryptionError",_a.DCBufferStatusChanged="dcBufferStatusChanged",_a.ActiveDeviceChanged="activeDeviceChanged",_a.ChatMessage="chatMessage",_a.LocalTrackSubscribed="localTrackSubscribed",_a.MetricsReceived="metricsReceived",_a.DataTrackPublished="dataTrackPublished",_a.DataTrackUnpublished="dataTrackUnpublished",_a.LocalDataTrackPublished="localDataTrackPublished",_a.LocalDataTrackUnpublished="localDataTrackUnpublished",e.ParticipantEvent=void 0,(Oa=e.ParticipantEvent||(e.ParticipantEvent={})).TrackPublished="trackPublished",Oa.TrackSubscribed="trackSubscribed",Oa.TrackSubscriptionFailed="trackSubscriptionFailed",Oa.TrackUnpublished="trackUnpublished",Oa.TrackUnsubscribed="trackUnsubscribed",Oa.TrackMuted="trackMuted",Oa.TrackUnmuted="trackUnmuted",Oa.LocalTrackPublished="localTrackPublished",Oa.LocalTrackUnpublished="localTrackUnpublished",Oa.LocalTrackCpuConstrained="localTrackCpuConstrained",Oa.LocalSenderCreated="localSenderCreated",Oa.ParticipantMetadataChanged="participantMetadataChanged",Oa.ParticipantNameChanged="participantNameChanged",Oa.DataReceived="dataReceived",Oa.SipDTMFReceived="sipDTMFReceived",Oa.TranscriptionReceived="transcriptionReceived",Oa.IsSpeakingChanged="isSpeakingChanged",Oa.ConnectionQualityChanged="connectionQualityChanged",Oa.TrackStreamStateChanged="trackStreamStateChanged",Oa.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Oa.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Oa.TrackCpuConstrained="trackCpuConstrained",Oa.MediaDevicesError="mediaDevicesError",Oa.AudioStreamAcquired="audioStreamAcquired",Oa.ParticipantPermissionsChanged="participantPermissionsChanged",Oa.PCTrackAdded="pcTrackAdded",Oa.AttributesChanged="attributesChanged",Oa.LocalTrackSubscribed="localTrackSubscribed",Oa.ChatMessage="chatMessage",Oa.Active="active",e.EngineEvent=void 0,(Aa=e.EngineEvent||(e.EngineEvent={})).TransportsCreated="transportsCreated",Aa.Connected="connected",Aa.Disconnected="disconnected",Aa.Resuming="resuming",Aa.Resumed="resumed",Aa.Restarting="restarting",Aa.Restarted="restarted",Aa.SignalResumed="signalResumed",Aa.SignalRestarted="signalRestarted",Aa.Closing="closing",Aa.MediaTrackAdded="mediaTrackAdded",Aa.ActiveSpeakersUpdate="activeSpeakersUpdate",Aa.DataPacketReceived="dataPacketReceived",Aa.RTPVideoMapUpdate="rtpVideoMapUpdate",Aa.DCBufferStatusChanged="dcBufferStatusChanged",Aa.ParticipantUpdate="participantUpdate",Aa.RoomUpdate="roomUpdate",Aa.SpeakersChanged="speakersChanged",Aa.StreamStateChanged="streamStateChanged",Aa.ConnectionQualityUpdate="connectionQualityUpdate",Aa.SubscriptionError="subscriptionError",Aa.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",Aa.RemoteMute="remoteMute",Aa.SubscribedQualityUpdate="subscribedQualityUpdate",Aa.LocalTrackUnpublished="localTrackUnpublished",Aa.LocalTrackSubscribed="localTrackSubscribed",Aa.Offline="offline",Aa.SignalRequestResponse="signalRequestResponse",Aa.SignalConnected="signalConnected",Aa.RoomMoved="roomMoved",Aa.PublishDataTrackResponse="publishDataTrackResponse",Aa.UnPublishDataTrackResponse="unPublishDataTrackResponse",Aa.DataTrackSubscriberHandles="dataTrackSubscriberHandles",Aa.DataTrackPacketReceived="dataTrackPacketReceived",Aa.Joined="joined",Aa.TokenRefreshed="tokenRefreshed",Aa.ServerRegionsReported="serverRegionsReported",e.TrackEvent=void 0,(Na=e.TrackEvent||(e.TrackEvent={})).Message="message",Na.Muted="muted",Na.Unmuted="unmuted",Na.Restarted="restarted",Na.Ended="ended",Na.Subscribed="subscribed",Na.Unsubscribed="unsubscribed",Na.CpuConstrained="cpuConstrained",Na.UpdateSettings="updateSettings",Na.UpdateSubscription="updateSubscription",Na.AudioPlaybackStarted="audioPlaybackStarted",Na.AudioPlaybackFailed="audioPlaybackFailed",Na.AudioSilenceDetected="audioSilenceDetected",Na.VisibilityChanged="visibilityChanged",Na.VideoDimensionsChanged="videoDimensionsChanged",Na.VideoPlaybackStarted="videoPlaybackStarted",Na.VideoPlaybackFailed="videoPlaybackFailed",Na.ElementAttached="elementAttached",Na.ElementDetached="elementDetached",Na.UpstreamPaused="upstreamPaused",Na.UpstreamResumed="upstreamResumed",Na.SubscriptionPermissionChanged="subscriptionPermissionChanged",Na.SubscriptionStatusChanged="subscriptionStatusChanged",Na.SubscriptionFailed="subscriptionFailed",Na.TrackProcessorUpdate="trackProcessorUpdate",Na.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",Na.TranscriptionReceived="transcriptionReceived",Na.TimeSyncUpdate="timeSyncUpdate",Na.PreConnectBufferFlushed="preConnectBufferFlushed";class za{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 Ja=["opus","red"],Ga=["vp8","h264"],Qa=["vp8","h264","vp9","av1","h265"];function Ya(e){return!!Ga.find((t=>t===e))}const Xa=Ya;var Za,$a;e.BackupCodecPolicy=void 0,(Za=e.BackupCodecPolicy||(e.BackupCodecPolicy={}))[Za.PREFER_REGRESSION=0]="PREFER_REGRESSION",Za[Za.SIMULCAST=1]="SIMULCAST",Za[Za.REGRESSION=2]="REGRESSION",e.AudioPresets=void 0,($a=e.AudioPresets||(e.AudioPresets={})).telephone={maxBitrate:12e3},$a.speech={maxBitrate:24e3},$a.music={maxBitrate:48e3},$a.musicStereo={maxBitrate:64e3},$a.musicHighQuality={maxBitrate:96e3},$a.musicHighQualityStereo={maxBitrate:128e3};const es={h90:new za(160,90,9e4,20),h180:new za(320,180,16e4,20),h216:new za(384,216,18e4,20),h360:new za(640,360,45e4,20),h540:new za(960,540,8e5,25),h720:new za(1280,720,17e5,30),h1080:new za(1920,1080,3e6,30),h1440:new za(2560,1440,5e6,30),h2160:new za(3840,2160,8e6,30)},ts={h120:new za(160,120,7e4,20),h180:new za(240,180,125e3,20),h240:new za(320,240,14e4,20),h360:new za(480,360,33e4,20),h480:new za(640,480,5e5,20),h540:new za(720,540,6e5,25),h720:new za(960,720,13e5,30),h1080:new za(1440,1080,23e5,30),h1440:new za(1920,1440,38e5,30)},ns={h360fps3:new za(640,360,2e5,3,"medium"),h360fps15:new za(640,360,4e5,15,"medium"),h720fps5:new za(1280,720,8e5,5,"medium"),h720fps15:new za(1280,720,15e5,15,"medium"),h720fps30:new za(1280,720,2e6,30,"medium"),h1080fps15:new za(1920,1080,25e5,15,"medium"),h1080fps30:new za(1920,1080,5e6,30,"medium"),original:new za(0,0,7e6,30,"medium")};function is(e,t,n){var i,r,a,s;const o=ms(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&&(rs(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&&(rs(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 rs(e,t){return Object.keys(t).forEach((n=>{void 0===e[n]&&(e[n]=t[n])})),e}function as(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)rs(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 ss(e){return tr(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const n=os();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 Ss(t),i.getByteTimeDomainData(a);const s=a.some((e=>128!==e&&0!==e));return n.close(),!s}return!1}()}))}function os(){var e;const t="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){const n=new t({latencyHint:"interactive"});if("suspended"===n.state&&"undefined"!=typeof window&&(null===(e=window.document)||void 0===e?void 0:e.body)){const e=()=>tr(this,void 0,void 0,(function*(){var t;try{"suspended"===n.state&&(yield n.resume())}catch(e){console.warn("Error trying to auto-resume audio context",e)}finally{null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)}}));n.addEventListener("statechange",(()=>{var t;"closed"===n.state&&(null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e))})),window.document.body.addEventListener("click",e)}return n}}function cs(e){return"audioinput"===e?ks.Source.Microphone:"videoinput"===e?ks.Source.Camera:ks.Source.Unknown}function ds(e){return e===ks.Source.Microphone?"audioinput":e===ks.Source.Camera?"videoinput":void 0}function ls(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=Os()?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 us(e){return e.split("/")[1].toLowerCase()}function hs(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new zn({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function ps(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?ps(e.track):{})}}function ms(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 gs(e,t){return e.width*e.height<t.width*t.height}const vs=[];var fs;e.VideoQuality=void 0,(fs=e.VideoQuality||(e.VideoQuality={}))[fs.LOW=0]="LOW",fs[fs.MEDIUM=1]="MEDIUM",fs[fs.HIGH=2]="HIGH";class ks extends cr.EventEmitter{get streamState(){return this._streamState}setStreamState(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=ks.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Ji,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=Qi(null!==(r=i.loggerName)&&void 0!==r?r:e.LoggerNames.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=ks.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),ps(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let n="audio";this.kind===ks.Kind.Video&&(n="video"),0===this.attachedElements.length&&this.kind===ks.Kind.Video&&this.addAppVisibilityListener(),t||("audio"===n&&(vs.forEach((e=>{null!==e.parentElement||t||(t=e)})),t&&vs.splice(vs.indexOf(t),1)),t||(t=document.createElement(n))),this.attachedElements.includes(t)||this.attachedElements.push(t),ys(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?Ji.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):Ji.warn("could not playback ".concat(r?"audio":"video"),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){bs(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=>{bs(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.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=Qi(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),vs.forEach((e=>{e.parentElement||(t=!1)})),t&&vs.push(e)}}handleAppVisibilityChanged(){return tr(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==ks.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){Ls()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Ls()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function ys(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)),Os()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===n.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(Os()||Ms())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=n,t.play().catch((()=>{}))}),0))}function bs(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 Mn.ACTIVE:return i.Active;case Mn.PAUSED:return i.Paused;default:return i.Unknown}}}(ks||(ks={}));const Ts="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Ss(e){return new ka((t=>Ka.setTimeout(t,e)))}function Es(){return"addTransceiver"in RTCPeerConnection.prototype}function Cs(){return"addTrack"in RTCPeerConnection.prototype}function ws(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Os()||Ms())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 Rs(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Ms())return!1;if(Os()){const e=Ta();if((null==e?void 0:e.version)&&Hs(e.version,"16")<0)return!1;if("iOS"===(null==e?void 0:e.os)&&(null==e?void 0:e.osVersion)&&Hs(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 Ps(e){return"av1"===e||"vp9"===e}function Is(e){return!(!document||As())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function Ds(){return"undefined"!=typeof RTCPeerConnection&&(Es()||Cs())}function Ms(){var e;return"Firefox"===(null===(e=Ta())||void 0===e?void 0:e.name)}function _s(){return"undefined"!=typeof window&&void 0!==window.RTCRtpScriptTransform&&!function(){const e=Ta();return!!e&&"Chrome"===e.name&&"iOS"!==e.os}()}function Os(){var e;return"Safari"===(null===(e=Ta())||void 0===e?void 0:e.name)}function As(){const e=Ta();return"Safari"===(null==e?void 0:e.name)||"iOS"===(null==e?void 0:e.os)}function Ns(){const e=Ta();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)&&Hs(e.osVersion,"17")>=0}function xs(){var e,t;return!!Ls()&&(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 Ls(){return"undefined"!=typeof document}function Us(){return"ReactNative"==navigator.product}function Fs(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function Bs(e){return Fs(e)?e.hostname.split(".")[0]:null}function js(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function qs(){if(!Us())return;let e=js();return e?e.platform:void 0}function Vs(){if(Ls())return window.devicePixelRatio;if(Us()){let e=js();if(e)return e.devicePixelRatio}return 1}function Hs(e,t){const n=e.split("."),i=t.split("."),r=Math.min(n.length,i.length);for(let e=0;e<r;++e){const t=parseInt(n[e],10),a=parseInt(i[e],10);if(t>a)return 1;if(t<a)return-1;if(e===r-1&&t===a)return 0}return""===e&&""!==t?-1:""===t?1:n.length==i.length?0:n.length<i.length?-1:1}function Ws(e){for(const t of e)t.target.handleResize(t)}function Ks(e){for(const t of e)t.target.handleVisibilityChanged(t)}let zs=null;const Js=()=>(zs||(zs=new ResizeObserver(Ws)),zs);let Gs=null;const Qs=()=>(Gs||(Gs=new IntersectionObserver(Ks,{root:null,rootMargin:"0px"})),Gs);let Ys,Xs;function Zs(){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=j(r.captureStream().getTracks(),1)[0];if(!s)throw Error("Could not get empty media stream video track");return s.enabled=n,s}function $s(){if(!Xs){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=j(r.stream.getAudioTracks(),1);if(Xs=e[0],!Xs)throw Error("Could not get empty media stream audio track");Xs.enabled=!1}return Xs.clone()}class eo{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise(((t,n)=>tr(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 to(e){return Qa.includes(e)}function no(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 io(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function ro(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 ao(e){return void 0!==e?Number(e):void 0}function so(e){return void 0!==e?BigInt(e):void 0}function oo(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function co(e){return!!e&&e.kind==ks.Kind.Audio}function lo(e){return!!e&&e.kind==ks.Kind.Video}function uo(e){return oo(e)&&lo(e)}function ho(e){return oo(e)&&co(e)}function po(e){return!!e&&!e.isLocal}function mo(e){return!!e&&!e.isLocal}function go(e){return po(e)&&lo(e)}function vo(e){return e.isLocal}function fo(){return"undefined"!=typeof CompressionStream}function ko(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)})),bo(n,"rtc")}(e,t);return n?i:bo(i,"v1")}function yo(e){return e.endsWith("/")?e:"".concat(e,"/")}function bo(e,t){return e.pathname="".concat(yo(e.pathname)).concat(t),e}function To(e){if("string"==typeof e)return An.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return An.fromBinary(new Uint8Array(e));throw new Error("could not decode websocket message: ".concat(typeof e))}const So="AES-GCM",Eo="lk_e2ee",Co={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16,keySize:128};var wo,Ro;function Po(){return Do()||Io()}function Io(){return"undefined"!=typeof window&&void 0!==window.RTCRtpScriptTransform}function Do(){return"undefined"!=typeof window&&void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams}function Mo(e){return tr(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 tr(this,void 0,void 0,(function*(){return yield crypto.subtle.importKey("raw",e,"HKDF",!1,["deriveBits","deriveKey"])}))}function Oo(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,(wo=e.KeyProviderEvent||(e.KeyProviderEvent={})).SetKey="setKey",wo.RatchetRequest="ratchetRequest",wo.KeyRatcheted="keyRatcheted",e.KeyHandlerEvent=void 0,(e.KeyHandlerEvent||(e.KeyHandlerEvent={})).KeyRatcheted="keyRatcheted",e.EncryptionEvent=void 0,(Ro=e.EncryptionEvent||(e.EncryptionEvent={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Ro.EncryptionError="encryptionError",e.CryptorEvent=void 0,(e.CryptorEvent||(e.CryptorEvent={})).Error="cryptorError";function Ao(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 Pt({value:e.value})}class No extends cr.EventEmitter{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.latestManuallySetKeyIndex=0,this.onKeyRatcheted=(e,t,n)=>{Ji.debug("key ratcheted event received",{ratchetResult:e,participantId:t,keyIndex:n})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Co),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 xo;e.CryptorErrorReason=void 0,(xo=e.CryptorErrorReason||(e.CryptorErrorReason={}))[xo.InvalidKey=0]="InvalidKey",xo[xo.MissingKey=1]="MissingKey",xo[xo.InternalError=2]="InternalError";function Lo(){return _s()}function Uo(e){return!!(null==e?void 0:e.worker)&&(Do()||Lo())}function Fo(e){return!(!(null==e?void 0:e.timestamp)&&!(null==e?void 0:e.frameId))}function Bo(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&&Ka.clearTimeout(a),a=Ka.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&&Ka.clearTimeout(a),l.forEach((t=>(0,t.reject)(e))),l=[]},u}const jo=2e3;function qo(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 Vo extends ks{constructor(e,t,n,i,r){super(e,n,r),this.sid=t,this.receiver=i}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 tr(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()),jo)),"undefined"!=typeof RTCRtpReceiver&&"function"==typeof RTCRtpReceiver.prototype.getSynchronizationSources&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const t=()=>{var n;this.timeSyncHandle=requestAnimationFrame((()=>t()));const i=null===(n=this.receiver)||void 0===n?void 0:n.getSynchronizationSources()[0];if(i){const t=i.timestamp,n=i.rtpTimestamp;n&&this.rtpTimestamp!==n&&(this.emit(e.TrackEvent.TimeSyncUpdate,{timestamp:t,rtpTimestamp:n}),this.rtpTimestamp=n)}};t()}}class Ho extends Vo{constructor(e,t,n,i,r){super(e,t,ks.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>tr(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=qo(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=Bo((()=>{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.packetTrailerExtractor)||void 0===n?void 0:n.lookupMetadata(t)}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===ks.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?bs(this._mediaStreamTrack,t):ys(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 Wo(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 e of t)e.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 e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return tr(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 e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return tr(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?Ka.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 Vs();if(!t){return Vs()>2?2:1}return t}}class Wo{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=Ko(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=Ko(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)}))}))},this.onLeavePiP=()=>{var e;this.isPiP=Ko(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:zo(e),this.isPiP=Ls()&&Ko(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=zo(this.element),this.isPiP=Ko(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Qs().observe(this.element),Js().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=Qs())||void 0===e||e.unobserve(this.element),null===(t=Js())||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 Ko(e){var t,n;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&zo(e,null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)}function zo(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 Jo extends cr.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(Ji.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.handlePacketTrailerMetadata(s.trackId,s.rtpTimestamp,s.ssrc,s.metadata)}},this.onWorkerError=t=>{Ji.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(!Po())throw new La("tried to setup end-to-end encryption on an unsupported browser");if(Ji.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:Yi.getLevel()}};this.worker&&(Ji.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){Ji.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):Ji.warn("ignoring server sent trailer as it's empty")}handlePacketTrailerMetadata(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 Ho&&a.track.packetTrailerExtractor)return void a.track.packetTrailerExtractor.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)=>tr(this,void 0,void 0,(function*(){this.setupE2EESender(t,e)})))),t.localParticipant.on(e.ParticipantEvent.LocalTrackPublished,(e=>{if(!lo(e.track)||!As())return;const t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:us(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 tr(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 eo;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 eo;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)}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?us(n.mimeType):void 0,i)}setupE2EESender(e,t){var n;oo(e)&&t?this.handleSender(t,e.mediaStreamID,void 0,lo(e)?null===(n=e.publishOptions)||void 0===n?void 0:n.packetTrailer:void 0):t||Ji.warn("early return because sender is not ready")}handleReceiver(e,t,n,i,r){return tr(this,void 0,void 0,(function*(){if(this.worker){if(_s()){const a={kind:"decode",participantIdentity:n,trackId:t,codec:i,hasPacketTrailer:r};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{if(Eo in e&&i){const e={kind:"updateCodec",data:{trackId:t,codec:i,participantIdentity:n,hasPacketTrailer:r}};return void this.worker.postMessage(e)}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,isReuse:Eo in e,hasPacketTrailer:r}};this.worker.postMessage(o,[s,a])}e[Eo]=!0}}))}handleSender(e,t,n,i){var r;if(!(Eo 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(_s()){Ji.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n,hasPacketTrailer:Fo(i),packetTrailer:i};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{Ji.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,isReuse:!1,hasPacketTrailer:Fo(i),packetTrailer:i}};this.worker.postMessage(a,[r.readable,r.writable])}e[Eo]=!0}}}class Go{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 Qo{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=>{Ji.error("packet trailer 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(!Uo(this.worker?{worker:this.worker}:void 0)&&!(null===(i=this.room)||void 0===i?void 0:i.hasE2EESetup))return void Ji.warn("packet trailer transform not supported; skipping extraction");const s=new Go,o=e.mediaStreamID;this.extractors.set(o,s),e.packetTrailerExtractor=s,(null===(r=this.room)||void 0===r?void 0:r.hasE2EESetup)||this.setupWorkerReceiver(a,o,!0)}setupPassthroughReceiver(e,t){Lo()?"transform"in e&&(e.transform=null):(this.worker&&Uo({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(Lo())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 Ji.warn("createEncodedStreams not supported");let a;try{a=e.createEncodedStreams()}catch(e){return void Ji.warn("failed to create encoded streams",{error:e})}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 Ho&&(e.packetTrailerExtractor=void 0)}cleanup(){var e;for(const e of this.extractors.values())e.dispose();this.extractors.clear(),this.workerPipelines.clear(),null===(e=this.worker)||void 0===e||e.terminate()}}class Yo{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new Yo),this._instance}addFailedConnectionAttempt(e){var t;const n=Bs(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,Ss(Math.min(500*Math.pow(2,i),15e3)))}getBackOffPromise(e){const t=new URL(e),n=t&&Bs(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),n=t&&Bs(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}Yo._instance=null;const Xo="default";class Zo{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new Zo),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return tr(this,arguments,void 0,(function(e){var t=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var i;if((null===(i=Zo.userMediaPromiseMap)||void 0===i?void 0:i.size)>0){Ji.debug("awaiting getUserMedia promise");try{e?yield Zo.userMediaPromiseMap.get(e):yield Promise.all(Zo.userMediaPromiseMap.values())}catch(e){Ji.warn("error waiting for media permissons")}}let r=yield navigator.mediaDevices.enumerateDevices();if(n&&(!Os()||!t.hasDeviceInUse(e))){if(0===r.filter((t=>t.kind===e)).length||r.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);r=yield navigator.mediaDevices.enumerateDevices(),n.getTracks().forEach((e=>{e.stop()}))}}return t._previousDevices=r,e&&(r=r.filter((t=>t.kind===e))),r}()}))}normalizeDeviceId(e,t,n){return tr(this,void 0,void 0,(function*(){if(t!==Xo)return t;const i=yield this.getDevices(e),r=i.find((e=>e.deviceId===Xo));if(!r)return void Ji.warn("could not reliably determine default device");const a=i.find((e=>e.deviceId!==Xo&&e.groupId===(null!=n?n:r.groupId)));if(a)return null==a?void 0:a.deviceId;Ji.warn("could not reliably determine default device")}))}hasDeviceInUse(e){return e?Zo.userMediaPromiseMap.has(e):Zo.userMediaPromiseMap.size>0}}Zo.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Zo.userMediaPromiseMap=new Map;const $o=65535,ec=4294967295;class tc{static u16(e){return new tc(e,$o)}static u32(e){return new tc(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 tc(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 tc(e,this.maxSize)}isBefore(e){const t=this.value>>>0,n=(e.value>>>0)-t>>>0;return 0!==n&&n<this.maxSize+1}}class nc{static fromRtpTicks(e){return new nc(e,9e4)}static rtpRandom(){const e=Math.round(Math.random()*ec);return nc.fromRtpTicks(e)}constructor(e,t){this.timestamp=tc.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new nc(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}}class ic{constructor(e,t,n){this.epoch=t,this.base=n,this.previous=n.clone(),this.rateInHz=e}static startingNow(e,t){return new ic(t,new Date,e)}static startingAtTime(e,t,n){return new ic(n,e,t)}static rtpStartingNow(e){return ic.startingNow(e,9e4)}static rtpStartingAtTime(e,t){return ic.startingAtTime(e,t,9e4)}now(){return this.at(new Date)}at(e){let t=e.getTime()-this.epoch.getTime(),n=ic.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 rc(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 ac;!function(e){e[e.Reserved=0]="Reserved",e[e.TooLarge=1]="TooLarge"}(ac||(ac={}));class sc extends Pa{constructor(e,t){super(19,e),this.name="DataTrackHandleError",this.reason=t,this.reasonName=ac[t]}isReason(e){return this.reason===e}static tooLarge(){return new sc("Value too large to be a valid track handle",ac.TooLarge)}static reserved(e){return new sc("0x".concat(e.toString(16)," is a reserved value."),ac.Reserved)}}const oc={fromNumber(e){if(0===e)throw sc.reserved(e);if(e>$o)throw sc.tooLarge();return e}};class cc{constructor(){this.value=0}get(){return this.value+=1,this.value>$o?null:this.value}reset(){this.value=0}}const dc={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 uc{constructor(){this.pendingTasks=new Map,this.taskMutex=new r,this.nextTaskIndex=0}run(e){return tr(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 tr(this,void 0,void 0,(function*(){return this.run((()=>tr(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}class hc{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 ka(((e,t)=>{const n=()=>{t(xa.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(t)},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 ka(((e,t)=>{const n=()=>tr(this,void 0,void 0,(function*(){const n=new ka((e=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",(t=>{e(t)}),{once:!0})})),i=yield ka.race([Ss(250),n]);i?e(i):t(xa.websocket("Encountered unspecified websocket error without a timely close event"))}));r.onclose=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 pc=["syncState","trickle","offer","answer","simulate","leave"];var mc;!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"}(mc||(mc={}));class gc{get currentState(){return this.state}get isDisconnected(){return this.state===mc.DISCONNECTING||this.state===mc.DISCONNECTED}get isEstablishingConnection(){return this.state===mc.CONNECTING||this.state===mc.RECONNECTING}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.state=mc.DISCONNECTED,this.log=Ji,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=Qi(null!==(i=n.loggerName)&&void 0!==i?i:e.LoggerNames.Signal,(()=>this.logContext)),this.useJSON=t,this.requestQueue=new uc,this.queuedRequests=[],this.closingLock=new r,this.connectionLock=new r,this.state=mc.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,n,i){return tr(this,arguments,void 0,(function(e,t,n,i){var r=this;let a=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5?arguments[5]:void 0;return function*(){r.state=mc.CONNECTING,r.options=n;return yield r.connect(e,t,n,i,a,s)}()}))}reconnect(e,t,n,i){return tr(this,void 0,void 0,(function*(){if(!this.options)return void this.log.warn("attempted to reconnect without signal options being set, ignoring");this.state=mc.RECONNECTING,this.clearPingInterval();return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:i}),void 0,this.useV0SignalPath)}))}connect(e,t,n,i){return tr(this,arguments,void 0,(function(e,t,n,i){var r=this;let a=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5?arguments[5]:void 0;return function*(){const o=yield r.connectionLock.lock();r.connectOptions=n,r.useV0SignalPath=a;const c=function(e){var t;const n=new Vt({capabilities:e,sdk:Ht.JS,protocol:17,clientProtocol:1,version:wa});return Us()&&(n.os=null!==(t=qs())&&void 0!==t?t:""),n}(n.clientInfoCapabilities),d=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",Us()?"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,c,n):yield function(e,t,n,i){return tr(this,void 0,void 0,(function*(){const r=new URLSearchParams;r.set("access_token",e);const a=new Ni({clientInfo:t,connectionSettings:new Ai({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 e of n)a.set(e,d),d+=e.length;o=a,c=Li.GZIP}else o=s,c=Li.NONE;const d=new xi({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,c,n,s),l=ko(e,d,a).toString(),u=(h=l,bo(new URL(io(h)),"validate")).toString();var h;return new Promise(((e,t)=>tr(r,void 0,void 0,(function*(){var r,a;try{let s=!1;const o=e=>tr(this,void 0,void 0,(function*(){if(s)return;s=!0;const n=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unknown reason";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(),c(),t(xa.cancelled(n))}));null==i||i.addEventListener("abort",o);const c=()=>{clearTimeout(d),null==i||i.removeEventListener("abort",o)},d=setTimeout((()=>{o(xa.timeout("room connection has timed out (signal)"))}),n.websocketTimeout),h=(e,t)=>{this.handleSignalConnected(e,d,t)},p=new URL(l);p.searchParams.has("access_token")&&p.searchParams.set("access_token","<redacted>"),this.log.info("signal connecting to ".concat(p),{reconnect:n.reconnect,reconnectReason:n.reconnectReason}),this.ws&&(yield this.close(!1)),this.ws=new hc(l);try{this.ws.closed.then((e=>{var n;this.isEstablishingConnection&&t(xa.internal("Websocket got closed during a (re)connection attempt: ".concat(e.reason))),1e3!==e.closeCode&&(this.log.warn("websocket closed",{reason:e.reason,code:e.closeCode,wasClean:1e3===e.closeCode,state:this.state}),this.state===mc.CONNECTED&&this.handleOnClose(null!==(n=e.reason)&&void 0!==n?n:"Unexpected WS error"))})).catch((e=>{this.isEstablishingConnection&&t(xa.internal("Websocket error during a (re)connection attempt: ".concat(e)))}));const i=yield this.ws.opened.catch((e=>tr(this,void 0,void 0,(function*(){if(this.state===mc.CONNECTED)this.handleWSError(e),t(e);else{this.state=mc.DISCONNECTED,clearTimeout(d);const n=yield this.handleConnectionError(e,u);t(n)}}))));if(clearTimeout(d),!i)return;const s=i.readable.getReader();this.streamWriter=i.writable.getWriter();const o=yield s.read();if(s.releaseLock(),!o.value)throw xa.internal("no message received as first message");const c=To(o.value),l=this.validateFirstMessage(c,null!==(r=n.reconnect)&&void 0!==r&&r);if(!l.isValid)return void t(l.error);"join"===(null===(a=c.message)||void 0===a?void 0:a.case)&&(this.pingTimeoutDuration=c.message.value.pingTimeout,this.pingIntervalDuration=c.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.onJoined&&this.onJoined(c.message.value));h(i,l.shouldProcessFirstMessage?c:void 0),e(l.response)}catch(e){t(e)}finally{c()}}finally{o()}}))))}()}))}startReadingLoop(e,t){return tr(this,void 0,void 0,(function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield Ss(this.signalLatency));const t=yield e.read(),n=t.done,i=t.value;if(n)break;const r=To(i);this.handleSignalResponse(r)}}))}close(){return tr(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*(){if([mc.DISCONNECTING||mc.DISCONNECTED].includes(e.state))return void e.log.debug("ignoring signal close as it's already in disconnecting state");const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=mc.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:n});const t=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([t,Ss(250)])}}catch(t){e.log.debug("websocket error while closing",{error:t})}finally{t&&(e.state=mc.DISCONNECTED),i()}}()}))}sendOffer(e,t){this.log.debug("sending offer",{offerSdp:e.sdp}),this.sendRequest({case:"offer",value:fc(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",{answerSdp:e.sdp}),this.sendRequest({case:"answer",value:fc(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",{candidate:e}),this.sendRequest({case:"trickle",value:new Vn({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Hn({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return tr(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 ai({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 ri({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new ki({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:_.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new wi({timestamp:_.parse(Date.now()),rtt:_.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new ei({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new ni({reason:at.CLIENT_INITIATED,action:ii.DISCONNECT})})}sendPublishDataTrackRequest(e,t,n){return this.sendRequest({case:"publishDataTrackRequest",value:new Ln({pubHandle:e,name:t,encryption:n?ft.GCM:ft.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:"unpublishDataTrackRequest",value:new Fn({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:"updateDataSubscription",value:new Xn({updates:[new Zn({trackSid:e,subscribe:t})]})})}sendRequest(e){return tr(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&&!function(e){const t=pc.indexOf(e.case)>=0;return Ji.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(i&&t.state===mc.RECONNECTING)return void t.queuedRequests.push((()=>tr(t,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(n||(yield t.requestQueue.flush()),t.signalLatency&&(yield Ss(t.signalLatency)),t.isDisconnected)return void t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));if(!t.streamWriter)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case));const r=new On({message:e});try{t.useJSON?yield t.streamWriter.write(r.toJsonString()):yield t.streamWriter.write(r.toBinary().buffer)}catch(e){t.log.error("error sending signal message",{error:e})}}()}))}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=vc(i.value);this.onAnswer&&this.onAnswer(e,i.value.id,i.value.midToTrackId)}else if("offer"===i.case){const e=vc(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 tr(this,void 0,void 0,(function*(){if(this.state===mc.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.info("websocket connection closed: ".concat(e),{reason:e}),t&&t(e)}))}handleWSError(e){this.log.error("websocket error",{error:e})}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=Ka.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&&Ka.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval"),this.pingInterval=Ka.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&&Ka.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n){this.state=mc.CONNECTED,this.log.info("signal connected"),clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),n)}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}:this.state===mc.RECONNECTING&&"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:xa.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:xa.internal("Unexpected first message")}:{isValid:!1,error:xa.internal("did not receive join response, got ".concat(null===(s=e.message)||void 0===s?void 0:s.case," instead"))}}handleConnectionError(e,t){return tr(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")?xa.notAllowed(e,n.status):xa.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const t=yield n.text();return xa.notAllowed(t,n.status)}return e instanceof xa?e:xa.internal("Encountered unknown websocket error during connection: ".concat(e),{status:n.status,statusText:n.statusText})}catch(e){return e instanceof xa?e:xa.serverUnreachable(e instanceof Error?e.message:"server was not reachable")}}))}}function vc(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 fc(e,t){return new Gn({sdp:e.sdp,type:e.type,id:t})}class kc{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0;){if(!(this.buffer[0].sequence<=e))break;this.pop()}}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class yc{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=j(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=j(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=j(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=j(n,2);const i=t[0],r=t[1];r.expiresAt>=Date.now()&&e.set(i,r.value)}return e}}var bc,Tc,Sc,Ec,Cc,wc={},Rc={},Pc={exports:{}};function Ic(){if(bc)return Pc.exports;bc=1;var e=Pc.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")}))})),Pc.exports}function Dc(){return Tc||(Tc=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=Ic(),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}}))}))}}(Rc)),Rc}function Mc(){if(Ec)return Sc;Ec=1;var e=Ic(),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 Sc=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"},Sc}var _c=function(){if(Cc)return wc;Cc=1;var e=Dc(),t=Mc(),n=Ic();return wc.grammar=n,wc.write=t,wc.parse=e.parse,wc.parseParams=e.parseParams,wc.parseFmtpConfig=e.parseFmtpConfig,wc.parsePayloads=e.parsePayloads,wc.parseRemoteCandidates=e.parseRemoteCandidates,wc.parseImageAttributes=e.parseImageAttributes,wc.parseSimulcastStreamList=e.parseSimulcastStreamList,wc}();const Oc="negotiationStarted",Ac="negotiationComplete",Nc="offerAnswered",xc="rtpVideoPayloadTypes";class Lc extends cr.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.log=Ji,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=Bo((e=>tr(this,void 0,void 0,(function*(){this.emit(Oc);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}))),20),this.close=()=>{this._pc&&(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.log=Qi(null!==(i=n.loggerName)&&void 0!==i?i:e.LoggerNames.PCTransport),this.loggerOptions=n,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&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return tr(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e,t){return tr(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",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let r;if("offer"===e.type){let t=function(e){var t;const n=[],i=[],r=_c.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let a=0;return r.media.forEach((e=>{var t;const r=Bc(e.mid);"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(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&&(e.config.includes("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=_c.parse(null!==(n=e.sdp)&&void 0!==n?n:"");t.media.forEach((e=>{Fc(e)})),this.log.debug("setting pending initial offer before processing answer",this.logContext),yield this.setMungedSDP(e,_c.write(t))}const t=_c.parse(null!==(i=e.sdp)&&void 0!==i?i:"");t.media.forEach((e=>{const t=Bc(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}))})),r=_c.write(t)}if(yield this.setMungedSDP(e,r,!0),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,"answer"===e.type&&(this.latestAcknowledgedOfferId=t,this.emit(Nc,t)),this.renegotiate)this.renegotiate=!1,yield this.createAndSendOffer();else if("answer"===e.type&&(this.emit(Ac),e.sdp)){_c.parse(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(xc,e.rtp)}))}return!0}))}createInitialOffer(){return tr(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",this.logContext);const t=this.latestOfferId+1;this.latestOfferId=t;const n=yield this.pc.createOffer();this.pendingInitialOffer={sdp:n.sdp,type:n.type};const i=_c.parse(null!==(e=n.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{Fc(e)})),n.sdp=_c.write(i),{offer:n,offerId:t}}finally{t()}}))}createAndSendOffer(e){return tr(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.log.debug("restarting ICE",this.logContext),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)return this.renegotiate=!0,void this.log.debug("requesting renegotiation",Object.assign({},this.logContext));yield this._pc.setRemoteDescription(t)}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);const n=this.latestOfferId+1;this.latestOfferId=n;const i=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:i.sdp},this.logContext));const r=_c.parse(null!==(t=i.sdp)&&void 0!==t?t:"");if(r.media.forEach((e=>{Fc(e),"audio"===e.type?Uc(e,["all"],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let n=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(n=e.payload,!0))),0===n)return!0;if(Ps(t.codec)&&!Os()&&this.ensureVideoDDExtensionForSVC(e,r),!Ps(t.codec))return!0;const i=Math.round(.7*t.maxbr);for(const t of e.fmtp)if(t.payload===n){t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(i));break}return!0}))})),this.latestOfferId>n)return void this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:n}));yield this.setMungedSDP(i,_c.write(r)),this.onOffer(i,this.latestOfferId)}finally{n()}}))}createAndSetAnswer(){return tr(this,void 0,void 0,(function*(){var e;const t=yield this.pc.createAnswer(),n=_c.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return n.media.forEach((e=>{Fc(e),"audio"===e.type&&Uc(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,_c.write(n)),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 Ba("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 Ba("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return tr(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,n){return tr(this,void 0,void 0,(function*(){var i,r;const a=e.sdp;if(t){e.sdp=t;try{return this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),void(n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(n){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:n,mungedSdp:t,originalSdp:a})),e.sdp=a}}try{n?yield null===(i=this._pc)||void 0===i?void 0:i.setRemoteDescription(e):yield null===(r=this._pc)||void 0===r?void 0:r.setLocalDescription(e)}catch(i){let r="unknown error";i instanceof Error?r=i.message:"string"==typeof i&&(r=i);const s={error:r,sdp:e.sdp};throw t&&t!==a&&(s.mungedSdp=t),!n&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new ja(r)}}))}ensureVideoDDExtensionForSVC(e,t){var n,i;if(!(null===(n=e.ext)||void 0===n?void 0:n.some((e=>e.uri===Ts)))){if(0===this.ddExtID){let e=0;t.media.forEach((t=>{var n;null===(n=t.ext)||void 0===n||n.forEach((t=>{t.value>e&&(e=t.value)}))})),this.ddExtID=e+1}null===(i=e.ext)||void 0===i||i.push({value:this.ddExtID,uri:Ts})}}}function Uc(e,t,n){const i=Bc(e.mid);let r=0;e.rtp.some((e=>"opus"===e.codec&&(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&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}function Fc(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 Bc(e){return"number"==typeof e?e.toFixed(0):e}const jc="vp8",qc={audioPreset:e.AudioPresets.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:ns.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:jc,backupCodec:!0,preConnectBuffer:!1},Vc={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Hc={deviceId:{ideal:"default"},resolution:es.h720.resolution},Wc={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new $i,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Kc={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var zc;!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"}(zc||(zc={}));class Jc{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=Kc.peerConnectionTimeout,this.log=Ji,this.updateState=()=>{var e,t;const n=this.state,i=this.requiredTransports.map((e=>e.getConnectionState()));i.every((e=>"connected"===e))?this.state=zc.CONNECTED:i.some((e=>"failed"===e))?this.state=zc.FAILED:i.some((e=>"connecting"===e))?this.state=zc.CONNECTING:i.every((e=>"closed"===e))?this.state=zc.CLOSED:i.some((e=>"closed"===e))?this.state=zc.CLOSING:i.every((e=>"new"===e))&&(this.state=zc.NEW),n!==this.state&&(this.log.debug("pc state change: from ".concat(zc[n]," to ").concat(zc[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),null===(t=this.subscriber)||void 0===t?void 0:t.getConnectionState()))},this.log=Qi(null!==(a=n.loggerName)&&void 0!==a?a:e.LoggerNames.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired="subscriber-primary"!==t,this.isSubscriberConnectionRequired="subscriber-primary"===t,this.publisher=new Lc(i,n),this._mode=t,"publisher-only"!==t&&(this.subscriber=new Lc(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,Dn.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,Dn.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=zc.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 tr(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(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),null===(e=this.subscriber)||void 0===e?void 0:e.close()]),this.updateState()}))}triggerIceRestart(){return tr(this,void 0,void 0,(function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return tr(this,void 0,void 0,(function*(){var n;t===Dn.PUBLISHER?yield this.publisher.addIceCandidate(e):yield null===(n=this.subscriber)||void 0===n?void 0:n.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e,t){return tr(this,void 0,void 0,(function*(){var n,i,r;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{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.publisher.setConfiguration(e),null===(n=this.subscriber)||void 0===n||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return tr(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.logContext),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 tr(this,void 0,void 0,(function*(){return new ka(((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(Nc,s),e.signal.removeEventListener("abort",o))},s=e=>{e>i&&(a(),t())},o=()=>{a(),n(new ja("negotiation aborted"))},c=setTimeout((()=>{a(),n(new ja("negotiation timed out"))}),this.peerConnectionTimeout);e.signal.addEventListener("abort",o),this.publisher.on(Nc,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}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Dn.PUBLISHER||e===Dn.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 tr(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)=>tr(n,void 0,void 0,(function*(){const n=()=>{this.log.warn("abort transport connection",this.logContext),Ka.clearTimeout(a),r(xa.cancelled("room connection has been cancelled"))};(null==t?void 0:t.signal.aborted)&&n(),null==t||t.signal.addEventListener("abort",n);const a=Ka.setTimeout((()=>{null==t||t.signal.removeEventListener("abort",n),r(xa.internal("could not establish pc connection"))}),i);for(;this.state!==zc.CONNECTED;)if(yield Ss(50),null==t?void 0:t.signal.aborted)return void r(xa.cancelled("room connection has been cancelled"));Ka.clearTimeout(a),null==t||t.signal.removeEventListener("abort",n),e()}))))}()}))}}const Gc="undefined"!=typeof MediaRecorder;const Qc=Gc?MediaRecorder:class{constructor(){throw new Error("MediaRecorder is not available in this environment")}};class Yc extends Qc{constructor(e,t){if(!Gc)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=>tr(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 Xc extends ks{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=Bo((()=>tr(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>tr(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=>tr(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!==ks.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 tr(this,void 0,void 0,(function*(){var i;if(e===this._mediaStreamTrack&&!t)return;let r;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{bs(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&&(ys(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=>{ys(null!=r?r:e,t)})))}))}waitForDimensions(){return tr(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===ks.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(n=Ta())||void 0===n?void 0:n.os)&&(yield Ss(10));const i=Date.now();for(;Date.now()-i<t;){const t=e.dimensions;if(t)return t;yield Ss(50)}throw new Ua("unable to get track dimensions after timeout")}()}))}setDeviceId(e){return tr(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===no(e)||(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),no(e)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return tr(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===ks.Source.ScreenShare)return;const n=e._mediaStreamTrack.getSettings(),i=n.deviceId,r=n.groupId,a=e.kind===ks.Kind.Audio?"audioinput":"videoinput";return t?Zo.getInstance().normalizeDeviceId(a,i,r):i}()}))}mute(){return tr(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return tr(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return tr(this,void 0,void 0,(function*(){const n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Ua("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 tr(this,void 0,void 0,(function*(){}))}restart(t,n){return tr(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=er(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===ks.Kind.Video?o.video=!r&&!a||{deviceId:r,facingMode:a}:o.audio=!r||Object.assign({deviceId:r},s),this.attachedElements.forEach((e=>{bs(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return this.kind===ks.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 tr(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),xs()&&(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 tr(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=Ta();if("Safari"===(null==n?void 0:n.name)&&Hs(n.version,"12.0")<0)throw new La("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 tr(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 tr(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 tr(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(ys(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&&(bs(n._mediaStreamTrack,e),ys(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 tr(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 tr(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(Gc)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 Yc(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 Zc extends Xc{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(t,n){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=arguments.length>3?arguments[3]:void 0,a=arguments.length>4?arguments[4]:void 0;super(t,ks.Kind.Audio,n,i,a),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>tr(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}e&&this.prevStats&&(this._currentBitrate=qo(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=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return tr(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===ks.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 tr(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==ks.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 tr(this,void 0,void 0,(function*(){let t;if(e){const n=as({audio:e});"boolean"!=typeof n.audio&&(t=n.audio)}yield this.restart(t)}))}restart(e,t){const n=Object.create(null,{restart:{get:()=>super.restart}});return tr(this,void 0,void 0,(function*(){const i=yield n.restart.call(this,e,t);return this.checkForSilence(),i}))}startMonitor(){Ls()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),jo)))}setProcessor(t){return tr(this,void 0,void 0,(function*(){var n;const i=yield this.trackChangeLock.lock();try{if(!Us()&&!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 tr(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield this.sender.getStats()).forEach((e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})})),t}))}checkForSilence(){return tr(this,void 0,void 0,(function*(){const t=yield ss(this);return t&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(e.TrackEvent.AudioSilenceDetected)),t}))}}const $c=Object.values(es),ed=Object.values(ts),td=Object.values(ns),nd=[es.h180,es.h360],id=[ts.h180,ts.h360],rd=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map((t=>{var n,i;return new za(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*((null!==(n=e.encoding.maxFramerate)&&void 0!==n?n:30)/(null!==(i=t.fps)&&void 0!==i?i:30))))),t.fps,e.encoding.priority)})),ad=["q","h","f"];function sd(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 td;const i=t>n?t/n:n/t;if(Math.abs(i-16/9)<Math.abs(i-4/3))return $c;return ed}(e,t,n);let a=r[0].encoding;const s=Math.max(t,n);for(let e=0;e<r.length;e+=1){const t=r[e];if(a=t.encoding,t.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),Ji.debug("using video encoding",s));const l=s.maxFramerate,u=new za(t,n,s.maxBitrate,s.maxFramerate,s.priority);if(c&&Ps(d)){const e=new ud(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const n=Ta();if(As()||Us()||"Chrome"===(null==n?void 0:n.name)&&Hs(null==n?void 0:n.version,"113")<0){const i="h"==e.suffix?2:3,r=function(e){return e||(e=Ta()),"Safari"===(null==e?void 0:e.name)&&Hs(e.version,"18.3")>0||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&Hs(e.osVersion,"18.3")>0}(n);for(let n=0;n<e.spatial;n+=1)t.push({rid:ad[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),Ji.debug("using svc encoding",{encodings:t}),t}if(!o)return[s];let h,p;if(h=e?null!==(r=ld(null==i?void 0:i.screenShareSimulcastLayers))&&void 0!==r?r:cd(e,u):null!==(a=ld(null==i?void 0:i.videoSimulcastLayers))&&void 0!==a?a:cd(e,u),h.length>0){const e=h[0];if(h.length>1)p=j(h,2)[1];const i=Math.max(t,n);if(i>=960&&p)return dd(t,n,[e,p,u],l);if(i>=480)return dd(t,n,[e,u],l)}return dd(t,n,[u])}function od(e,t,n){var i,r,a,s;if(!n.backupCodec||!0===n.backupCodec||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&Ji.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===ks.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1);return sd(e.source===ks.Source.ScreenShare,c,d,n)}function cd(e,t){if(e)return rd(t);const n=t.width,i=t.height,r=n>i?n/i:i/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?nd:id}function dd(e,t,n,i){const r=[];if(n.forEach(((n,a)=>{if(a>=ad.length)return;const s=Math.min(e,t),o={rid:ad[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=Ta(),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)})),Us()&&"ios"===qs()){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,Ji.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Ji.info('Setting framerate of encoding "'.concat(null!==(i=n.rid)&&void 0!==i?i:"",'" to ').concat(e)),n.maxFramerate=e)}))}return r}function ld(e){if(e)return e.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 ud{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 hd extends Xc{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(t,n){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],a=arguments.length>3?arguments[3]:void 0;super(t,ks.Kind.Video,n,i,a),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>tr(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let t;try{t=yield this.getSenderStats()}catch(e){return void this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}const n=new Map(t.map((e=>[e.rid,e]))),i=t.some((e=>"cpu"===e.qualityLimitationReason));if(i!==this.isCpuConstrained&&(this.isCpuConstrained=i,this.isCpuConstrained&&this.emit(e.TrackEvent.CpuConstrained)),this.prevStats){let e=0;n.forEach(((t,n)=>{var i;const r=null===(i=this.prevStats)||void 0===i?void 0:i.get(n);e+=qo(t,r)})),this._currentBitrate=e}this.prevStats=n})),this.senderLock=new r}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Ls())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()}),jo))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return tr(this,void 0,void 0,(function*(){var t,n,i,r,a;yield e.pauseUpstream.call(this);try{for(var s,o=!0,c=ar(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(e){n={error:e}}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 tr(this,void 0,void 0,(function*(){var t,n,i,r,a;yield e.resumeUpstream.call(this);try{for(var s,o=!0,c=ar(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(e){n={error:e}}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 tr(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!==ks.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 tr(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==ks.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 tr(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 pi({quality:i,enabled:i<=t}));this.log.debug("setting publishing quality. max quality ".concat(t),this.logContext),this.setPublishingLayers(Ps(this.codec),n)}restartTrack(e){return tr(this,void 0,void 0,(function*(){var t,n,i,r,a;let s;if(e){const t=as({video:e});"boolean"!=typeof t.video&&(s=t.video)}yield this.restart(s),this.isCpuConstrained=!1;try{for(var o,c=!0,d=ar(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(e){n={error:e}}finally{try{c||t||!(i=d.return)||(yield i.call(d))}finally{if(n)throw n.error}}yield this.onSenderTrackSwapped()}))}onSenderTrackSwapped(){return tr(this,void 0,void 0,(function*(){yield this.refreshSenderEncodings()}))}refreshSenderEncodings(){return tr(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(e){return void this.log.warn("could not determine new track dimensions, skipping encoding recompute",Object.assign(Object.assign({},this.logContext),{error:e}))}if(this.lastEncodedDimensions&&this.lastEncodedDimensions.width===t.width&&this.lastEncodedDimensions.height===t.height)return;const i=sd(this.source===ks.Source.ScreenShare,t.width,t.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,i),this.encodings=i,this.lastEncodedDimensions=t;for(const t of this.simulcastCodecs){var n=j(t,2);const i=n[0],r=n[1];if(!r.sender||"closed"===(null===(e=r.sender.transport)||void 0===e?void 0:e.state))continue;if(!Ya(i))continue;const a=od(this,i,Object.assign({},this.publishOptions));a&&(yield this.applyEncodingsToSender(r.sender,a),r.encodings=a)}}catch(e){this.log.warn("failed to apply recomputed encodings",Object.assign(Object.assign({},this.logContext),{error:e}))}finally{t()}}))}applyEncodingsToSender(e,t){return tr(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 tr(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=ar(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(e){a={error:e}}finally{try{u||r||!(s=h.return)||(yield s.call(h))}finally{if(a)throw a.error}}}()}))}setDegradationPreference(e){return tr(this,void 0,void 0,(function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},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){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}setPublishingCodecs(e){return tr(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(Ps(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,n=ar(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 pd(t.sender,t.encodings,e.qualities,this.senderLock,Ps(e.codec),this.log,this.logContext));else for(const t of e.qualities)if(t.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(Ps(e.codec),e.qualities)}}catch(e){a={error:e}}finally{try{t||r||!(s=n.return)||(yield s.call(n))}finally{if(a)throw a.error}}return c}))}setPublishingLayers(e,t){return tr(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 pd(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))}))}prioritizePerformance(){return tr(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&&Ps(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(e){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return tr(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),xs()&&this.isInBackground&&this.source===ks.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function pd(e,t,n,i,r,a,s){return tr(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=md(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),Ms()&&(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 md(t){switch(t){case"f":default:return e.VideoQuality.HIGH;case"h":return e.VideoQuality.MEDIUM;case"q":return e.VideoQuality.LOW}}function gd(t,n,i,r){if(!i)return[new St({quality:e.VideoQuality.HIGH,width:t,height:n,bitrate:0,ssrc:0})];if(r){const r=i[0].scalabilityMode,a=new ud(r),s=[],o="h"==a.suffix?1.5:2,c="h"==a.suffix?2:3;for(let r=0;r<a.spatial;r+=1)s.push(new St({quality:Math.min(e.VideoQuality.HIGH,a.spatial-1)-r,width:Math.ceil(t/Math.pow(o,r)),height:Math.ceil(n/Math.pow(o,r)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(c,r)):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=md(null!==(r=e.rid)&&void 0!==r?r:"");return new St({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 vd="_lossy",fd="_reliable",kd="_data_track",yd="leave-reconnect";var bd,Td;!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"}(bd||(bd={})),function(e){e[e.RELIABLE=0]="RELIABLE",e[e.LOSSY=1]="LOSSY",e[e.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY"}(Td||(Td={}));class Sd extends cr.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}constructor(t){var n;super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=Kc.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=bd.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=Ji,this.reliableDataSequence=1,this.reliableMessageBuffer=new kc,this.reliableReceivedState=new yc(3e4),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.bufferStatusLowClosingFuture=new eo,this.handleDataChannel=e=>tr(this,[e],void 0,(function(e){var t=this;let n=e.channel;return function*(){if(!n)return;let e;if(n.label===fd)t.reliableDCSub=n,e=t.handleDataMessage;else if(n.label===vd)t.lossyDCSub=n,e=t.handleDataMessage;else{if(n.label!==kd)return;t.dataTrackDCSub=n,e=t.handleDataTrackMessage}t.log.debug("on data channel ".concat(n.id,", ").concat(n.label)),n.onmessage=e}()})),this.handleDataMessage=t=>tr(this,void 0,void 0,(function*(){var n,i,r,a,s;const o=yield this.dataProcessLock.lock();try{let o;if(t.data instanceof ArrayBuffer)o=t.data;else{if(!(t.data instanceof Blob))return void this.log.error("unsupported data type",{data:t.data});o=yield t.data.arrayBuffer()}const c=Ct.fromBinary(new Uint8Array(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=Pt.fromBinary(t.payload),i=new Ct({value:n.value,participantIdentity:c.participantIdentity,participantSid:c.participantSid});"user"===(null===(a=i.value)||void 0===a?void 0:a.case)&&Ed(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)&&Ed(c,c.value.value),this.emit(e.EngineEvent.DataPacketReceived,c,ft.NONE)}finally{o()}})),this.handleDataTrackMessage=e=>tr(this,void 0,void 0,(function*(){let t;if(e.data instanceof ArrayBuffer)t=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",{data:e.data});t=yield e.data.arrayBuffer()}this.emit("dataTrackPacketReceived",new Uint8Array(t))})),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const n=e.error.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),{error:n})}else this.log.error("Unknown DataChannel error on ".concat(t),{event:e})},this.handleBufferedAmountLow=e=>{this.updateAndEmitDCBufferStatus(e)},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()},r=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:r,retryCount:this.reconnectAttempts});null!==a?(t===yd&&(a=0),this.log.debug("reconnecting in ".concat(a,"ms")),this.clearReconnectTimeout(),this.token&&this.emit(e.EngineEvent.TokenRefreshed,this.token),this.reconnectTimeout=Ka.setTimeout((()=>this.attemptReconnect(n).finally((()=>this.reconnectTimeout=void 0))),a)):i(r)},this.waitForRestarted=()=>new Promise(((t,n)=>{this.pcState===bd.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.updateAndEmitDCBufferStatus=t=>{if(t===Td.RELIABLE){const e=this.dataChannelForKind(t);e&&this.reliableMessageBuffer.alignBufferedAmount(e.bufferedAmount)}const n=this.isBufferStatusLow(t);void 0!==n&&n!==this.dcBufferStatus.get(t)&&(this.dcBufferStatus.set(t,n),this.emit(e.EngineEvent.DCBufferStatusChanged,n,t))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.onRtpMapAvailable=t=>{const n=new Map;t.forEach((e=>{const t=e.codec.toLowerCase();to(t)&&n.set(e.payload,t)})),this.emit(e.EngineEvent.RTPVideoMapUpdate,n)},this.handleBrowserOnLine=()=>tr(this,void 0,void 0,(function*(){if(!this.url)return;(yield fetch(io(this.url),{method:"HEAD"}).then((e=>e.ok)).catch((()=>!1)))&&(this.log.info("detected network reconnected"),(this.client.currentState===mc.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===mc.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(st.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))})),this.handleBrowserOffline=()=>tr(this,void 0,void 0,(function*(){if(this.url)try{yield Promise.race([fetch(io(this.url),{method:"HEAD"}),Ss(4e3).then((()=>Promise.reject()))])}catch(e){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}})),this.log=Qi(null!==(n=t.loggerName)&&void 0!==n?n:e.LoggerNames.Engine,(()=>this.logContext)),this.loggerOptions={loggerName:t.loggerName,loggerContextCb:()=>this.logContext},this.client=new gc(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new r,this.dataProcessLock=new r,this.dcBufferStatus=new Map([[Td.RELIABLE,!0],[Td.LOSSY,!0],[Td.DATA_TRACK_LOSSY,!0]]),this.client.onParticipantUpdate=t=>this.emit(e.EngineEvent.ParticipantUpdate,t),this.client.onConnectionQuality=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),this.on(e.EngineEvent.Closing,(()=>{var e,t;null===(t=(e=this.bufferStatusLowClosingFuture).reject)||void 0===t||t.call(e,new Ba("engine closed"))})),this.bufferStatusLowClosingFuture.promise.catch((()=>{}))}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,n,i,r){return tr(this,arguments,void 0,(function(t,n,i,r){var a=this;let s=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){var o,c,d;a._isNewlyCreated=!1,a.url=t,a.token=n,a.signalOpts=i,a.maxJoinAttempts=i.maxRetries;try{a.joinAttempts+=1,a.setupSignalClientCallbacks();const l=!s&&fo()&&!Ms();let u;if(l){a.pcManager||(yield a.configure(),a.applyInitialPublisherLayout());const e=yield null===(o=a.pcManager)||void 0===o?void 0:o.publisher.createInitialOffer();e&&(u=fc(e.offer,e.offerId))}if(null==r?void 0:r.aborted)throw xa.cancelled("Connection aborted");if(!s&&a.shouldFailOnV1Path)throw a.shouldFailOnV1Path=!1,xa.serviceNotFound("Simulated v1 path failure","v0-rtc");const h=yield a.client.join(t,n,i,r,s,u);a._isClosed=!1,a.latestJoinResponse=h,a.participantSid=null===(c=h.participant)||void 0===c?void 0:c.sid,a.subscriberPrimary=h.subscriberPrimary,l?null===(d=a.pcManager)||void 0===d||d.updateConfiguration(a.makeRTCConfiguration(h)):(a.pcManager||(yield a.configure(h,!s),s||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=j(e,2),n=t[0],i=t[1];return"".concat(n,": ").concat(i)})).join(", "))),{joinResponse:h,serverInfo:p}}catch(o){if(o instanceof xa)if(o.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,n,i,r,s)}else if(o.reason===e.ConnectionErrorReason.ServiceNotFound)return a.log.warn("Initial connection failed: ".concat(o.message," – Retrying")),a.pcManager&&(a.pcManager.onStateChange=void 0,yield a.cleanupPeerConnections()),a.join(t,n,i,r,!0);throw o}}()}))}close(){return tr(this,void 0,void 0,(function*(){const t=yield this.closingLock.lock();if(this.isClosed)t();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(e.EngineEvent.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{t()}}))}cleanupPeerConnections(){return tr(this,void 0,void 0,(function*(){var e;yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;const t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),t(this.dataTrackDC),t(this.dataTrackDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.dataTrackDC=void 0,this.dataTrackDCSub=void 0,this.reliableMessageBuffer=new kc,this.reliableDataSequence=1,this.reliableReceivedState.clear()}))}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return tr(this,void 0,void 0,(function*(){yield this.client.close(),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 Ua("a track with the same ID has already been published");return new Promise(((t,n)=>{const i=setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],n(xa.timeout("publication of local track timed out, no response from server"))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(i),t(e)},reject:()=>{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(e){this.log.warn("failed to remove track",{error:e})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return tr(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 tr(this,void 0,void 0,(function*(){var i;if(!this.pcManager||this.pcManager.currentState===zc.NEW){if(t){this.participantSid=null===(i=t.participant)||void 0===i?void 0:i.sid;const e=this.makeRTCConfiguration(t);this.pcManager=new Jc(n?"publisher-only":t.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,e)}else{const e=this.makeRTCConfiguration();this.pcManager=new Jc("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)=>tr(this,void 0,void 0,(function*(){if(this.log.debug("primary PC state changed ".concat(t)),["closed","disconnected","failed"].includes(n)&&(this.publisherConnectionPromise=void 0),t===zc.CONNECTED){const t=this.pcState===bd.New;this.pcState=bd.Connected,t&&this.emit(e.EngineEvent.Connected,this.latestJoinResponse)}else t===zc.FAILED&&(this.pcState!==bd.Connected&&this.pcState!==bd.Reconnecting||(this.pcState=bd.Disconnected,this.handleDisconnect("peerconnection failed","failed"===i?st.RR_SUBSCRIBER_FAILED:st.RR_PUBLISHER_FAILED)));const r=this.client.isDisconnected||this.client.currentState===mc.RECONNECTING,a=[zc.FAILED,zc.CLOSING,zc.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)=>tr(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)=>tr(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=>{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 ii.DISCONNECT:this.emit(e.EngineEvent.Disconnected,null==t?void 0:t.reason),this.close();break;case ii.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(yd);break;case ii.RESUME:this.handleDisconnect(yd)}}}makeRTCConfiguration(e){var t,n;const i=Object.assign({},this.rtcConfig);if(((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)||(null===(n=this.options.packetTrailer)||void 0===n?void 0:n.worker)&&!Lo())&&Do()&&(this.log.debug("E2EE - setting up transports with insertable streams"),i.encodedInsertableStreams=!0),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",!e)return i;if(e.iceServers&&!i.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)})),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===rt.ENABLED&&(i.iceTransportPolicy="relay"),i}applyInitialPublisherLayout(){this.createDataChannels(),this.addMediaSections(3,3)}addMediaSections(e,t){var n,i;const r={direction:"recvonly"};for(let t=0;t<e;t++)null===(n=this.pcManager)||void 0===n||n.addPublisherTransceiverOfKind("audio",r);for(let e=0;e<t;e++)null===(i=this.pcManager)||void 0===i||i.addPublisherTransceiverOfKind("video",r)}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.dataTrackDC&&(this.dataTrackDC.onmessage=null,this.dataTrackDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(vd,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(fd,{ordered:!0}),this.dataTrackDC=this.pcManager.createPublisherDataChannel(kd,{ordered:!1,maxRetransmits:0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.dataTrackDC.onmessage=this.handleDataTrackMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.dataTrackDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.dataTrackDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(Td.LOSSY),this.reliableDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(Td.RELIABLE),this.dataTrackDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(Td.DATA_TRACK_LOSSY),this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval((()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(Td.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,8192),262144)}}),1e3))}createSender(e,t,n){return tr(this,void 0,void 0,(function*(){let i;if(Es())i=yield this.createTransceiverRTCRtpSender(e,t,n);else{if(!Cs())throw new Ba("Required webRTC APIs not supported on this device");this.log.warn("using add-track fallback"),i=yield this.createRTCRtpSender(e.mediaStreamTrack)}return this.setupPacketTrailerSender(i,t),i}))}createSimulcastSender(e,t,n,i){return tr(this,void 0,void 0,(function*(){let r;if(Es())r=yield this.createSimulcastTransceiverSender(e,t,n,i);else{if(!Cs())throw new Ba("Cannot stream on this device");this.log.debug("using add-track fallback"),r=yield this.createRTCRtpSender(e.mediaStreamTrack)}return r&&this.setupPacketTrailerSender(r,n),r}))}setupPacketTrailerSender(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n,i;if(!(null===(n=this.options.packetTrailer)||void 0===n?void 0:n.worker)||(null===(i=this.signalOpts)||void 0===i?void 0:i.e2eeEnabled))return;const r=t.packetTrailer,a=Fo(r);if(Lo())return void(a&&(e.transform=new RTCRtpScriptTransform(this.options.packetTrailer.worker,{kind:"encode",packetTrailer:r})));if(!Uo(this.options.packetTrailer)||!("createEncodedStreams"in e))return void(a&&this.log.warn("packet trailer transform not supported; skipping write",this.logContext));const s=e.createEncodedStreams(),o=s.readable,c=s.writable;a?this.options.packetTrailer.worker.postMessage({kind:"encode",data:{readableStream:o,writableStream:c,packetTrailer:r}},[o,c]):o.pipeTo(c)}createTransceiverRTCRtpSender(e,t,n){return tr(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Ba("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),lo(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 tr(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Ba("publisher is closed");const r={direction:"sendonly"};i&&(r.sendEncodings=i);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,a.sender),a.sender}))}createRTCRtpSender(e){return tr(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Ba("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}attemptReconnect(t){return tr(this,void 0,void 0,(function*(){var n,i,r;if(!this._isClosed)if(this.attemptingReconnect)this.log.warn("already attempting reconnect, returning early");else{(null===(n=this.clientConfiguration)||void 0===n?void 0:n.resumeConnection)!==rt.DISABLED&&(null!==(r=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==r?r:zc.NEW)!==zc.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(t),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(t){this.reconnectAttempts+=1;let n=!0;t instanceof Ba?(this.log.debug("received unrecoverable error",{error:t}),n=!1):t instanceof Wa||(this.fullReconnectOnNext=!0),n?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())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn("encountered error in reconnect policy",{error:e})}return null}restartConnection(t){return tr(this,void 0,void 0,(function*(){var n,i,r;try{if(!this.url||!this.token)throw new Ba("could not reconnect, url or token not saved");let i;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 Wa;i=(yield this.join(null!=t?t:this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(t){if(t instanceof xa&&t.reason===e.ConnectionErrorReason.NotAllowed)throw new Ba("could not reconnect, token might be expired");throw new Wa}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(e.EngineEvent.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==mc.CONNECTED)throw new Wa("Signal connection got severed during reconnect");null===(n=this.regionStrategy)||void 0===n||n.resetAttempts(),this.emit(e.EngineEvent.Restarted)}catch(e){const t=yield null===(i=this.regionStrategy)||void 0===i?void 0:i.getNextUrl();if(t)return void(yield this.restartConnection(t));throw null===(r=this.regionStrategy)||void 0===r||r.resetAttempts(),e}}))}resumeConnection(t){return tr(this,void 0,void 0,(function*(){var n;if(!this.url||!this.token)throw new Ba("could not reconnect, url or token not saved");if(!this.pcManager)throw new Ba("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(e.EngineEvent.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,t)}catch(t){let n="";if(t instanceof Error&&(n=t.message,this.log.error(t.message,{error:t})),t instanceof xa&&t.reason===e.ConnectionErrorReason.NotAllowed)throw new Ba("could not reconnect, token might be expired");if(t instanceof xa&&t.reason===e.ConnectionErrorReason.LeaveRequest)throw t;throw new Wa(n)}if(this.emit(e.EngineEvent.SignalResumed),i){const e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response");if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==mc.CONNECTED)throw new Wa("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(n=this.reliableDC)||void 0===n?void 0:n.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),(null==i?void 0:i.lastMessageSeq)&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(e.EngineEvent.Resumed)}))}waitForPCInitialConnection(e,t){return tr(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Ba("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)}))}waitForPCReconnected(){return tr(this,void 0,void 0,(function*(){this.pcState=bd.Reconnecting,this.log.debug("waiting for peer connection to reconnect");try{if(yield Ss(2e3),!this.pcManager)throw new Ba("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=bd.Connected}catch(e){throw this.pcState=bd.Disconnected,xa.internal("could not establish PC connection, ".concat(e.message))}}))}publishRpcAck(e,t){return tr(this,void 0,void 0,(function*(){const n=new Ct({destinationIdentities:[e],kind:wt.RELIABLE,value:{case:"rpcAck",value:new Lt({requestId:t})}});yield this.sendDataPacket(n,Td.RELIABLE)}))}sendDataPacket(e,t){return tr(this,void 0,void 0,(function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const t=Ao(e);if(t){const n=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:"encryptedPacket",value:new Rt({encryptedValue:n.payload,iv:n.iv,keyIndex:n.keyIndex})}}}t===Td.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const n=e.toBinary();switch(t){case Td.LOSSY:case Td.DATA_TRACK_LOSSY:return this.sendLossyBytes(n,t);case Td.RELIABLE:const i=this.dataChannelForKind(t);if(i){if(yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:n,sequence:e.sequence}),this.attemptingReconnect)return;i.send(n)}this.updateAndEmitDCBufferStatus(t)}}))}sendLossyBytes(e,t){return tr(this,arguments,void 0,(function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"drop";return function*(){yield n.ensurePublisherConnected(t);const r=n.dataChannelForKind(t);if(r){if(!n.isBufferStatusLow(t))switch(i){case"wait":yield n.waitForBufferStatusLow(t);break;case"drop":return n.lossyDataDropCount+=1,void(n.lossyDataDropCount%100==0&&n.log.warn("dropping lossy data channel messages, total dropped: ".concat(n.lossyDataDropCount)))}if(n.lossyDataStatCurrentBytes+=e.byteLength,n.attemptingReconnect)return;r.send(e)}n.updateAndEmitDCBufferStatus(t)}()}))}resendReliableMessagesForResume(e){return tr(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(Td.RELIABLE);const t=this.dataChannelForKind(Td.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach((e=>{t.send(e.data)}))),this.updateAndEmitDCBufferStatus(Td.RELIABLE)}))}waitForBufferStatusLow(e){return tr(this,void 0,void 0,(function*(){return new ka(((t,n)=>tr(this,void 0,void 0,(function*(){if(this.isClosed&&n(new Ba("engine closed")),this.isBufferStatusLow(e))t();else{const i=this.dataChannelForKind(e);if(!i)return void n(new Ba("DataChannel not found, kind: ".concat(e)));this.bufferStatusLowClosingFuture.promise.catch((e=>n(e))),i.addEventListener("bufferedamountlow",(()=>t()),{once:!0})}}))))}))}ensureDataTransportConnected(e){return tr(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 Ba("PC manager is closed");const r=n?t.pcManager.subscriber:t.pcManager.publisher,a=n?"Subscriber":"Publisher";if(!r)throw xa.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 Ss(50)}throw xa.internal("could not establish ".concat(a," connection, state: ").concat(r.getICEConnectionState()))}()}))}ensurePublisherConnected(e){return tr(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){if(!this.pcManager)return!1;return!![zc.CONNECTING,zc.CONNECTED].includes(this.pcManager.currentState)&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return tr(this,void 0,void 0,(function*(){return new ka(((t,n)=>tr(this,void 0,void 0,(function*(){if(!this.pcManager)return void n(new ja("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.dataTrackDC||this.createDataChannels();const i=new AbortController,r=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing"),t()};this.isClosed&&n(new ja("cannot negotiate on closed engine")),this.on(e.EngineEvent.Closing,r),this.on(e.EngineEvent.Restarting,r),this.pcManager.publisher.off(xc,this.onRtpMapAvailable),this.pcManager.publisher.once(xc,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(i),t()}catch(e){if(i.signal.aborted)return void t();e instanceof ja&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",st.RR_UNKNOWN),e instanceof Error?n(e):n(new Error(String(e)))}finally{this.off(e.EngineEvent.Closing,r),this.off(e.EngineEvent.Restarting,r)}}))))}))}dataChannelForKind(e,t){switch(e){case Td.RELIABLE:return t?this.reliableDCSub:this.reliableDC;case Td.LOSSY:return t?this.lossyDCSub:this.lossyDC;case Td.DATA_TRACK_LOSSY:return t?this.dataTrackDCSub:this.dataTrackDC}}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 Ti({answer:"publisher-only"===this.pcManager.mode?c?fc({sdp:c.sdp,type:c.type}):void 0:l?fc({sdp:l.sdp,type:l.type}):void 0,offer:"publisher-only"===this.pcManager.mode?o?fc({sdp:o.sdp,type:o.type}):void 0:d?fc({sdp:d.sdp,type:d.type}):void 0,subscription:new Yn({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:hs(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:p,datachannelReceiveStates:this.reliableReceivedState.map(((e,t)=>new Si({publisherSid:t,lastSeq:e}))),publishDataTracks:n.map((e=>new Un({info:dc.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 Ei({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(Td.LOSSY),Dn.PUBLISHER),t(this.dataChannelForKind(Td.RELIABLE),Dn.PUBLISHER),t(this.dataChannelForKind(Td.LOSSY,!0),Dn.SUBSCRIBER),t(this.dataChannelForKind(Td.RELIABLE,!0),Dn.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Ka.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Ls()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){Ls()&&(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=>j(e,1)[0]===n));if(e)return e[1]}}}function Ed(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 Cd=5e3;class wd{static fetchRegionSettings(e,t,n){return tr(this,void 0,void 0,(function*(){const i=yield wd.fetchLock.lock();try{const i=yield fetch("".concat(function(e){return"".concat(e.protocol.replace("ws","http"),"//").concat(e.host,"/settings")}(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:n});if(i.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)}}(i.headers),t=e?1e3*e:Cd;return{regionSettings:yield i.json(),updatedAtInMs:Date.now(),maxAgeInMs:t}}throw 401===i.status?xa.notAllowed("Could not fetch region settings: ".concat(i.statusText),i.status):xa.internal("Could not fetch region settings: ".concat(i.statusText))}catch(e){throw e instanceof xa?e:(null==n?void 0:n.aborted)?xa.cancelled("Region fetching was aborted"):xa.serverUnreachable("Could not fetch region settings, ".concat(e instanceof Error?"".concat(e.name,": ").concat(e.message):e))}finally{i()}}))}static scheduleRefetch(t,n,i){return tr(this,void 0,void 0,(function*(){const r=wd.settingsTimeouts.get(t.hostname);clearTimeout(r),wd.settingsTimeouts.set(t.hostname,setTimeout((()=>tr(this,void 0,void 0,(function*(){try{const e=yield wd.fetchRegionSettings(t,n);wd.updateCachedRegionSettings(t,n,e)}catch(r){if(r instanceof xa&&r.reason===e.ConnectionErrorReason.NotAllowed)return void Ji.debug("token is not valid, cancelling auto region refresh");Ji.debug("auto refetching of region settings failed",{error:r}),wd.scheduleRefetch(t,n,i)}}))),i))}))}static updateCachedRegionSettings(e,t,n){wd.cache.set(e.hostname,n),wd.scheduleRefetch(e,t,n.maxAgeInMs)}static stopRefetch(e){const t=wd.settingsTimeouts.get(e);t&&(clearTimeout(t),wd.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=wd.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout((()=>{const t=wd.connectionTrackers.get(e);t&&0===t.connectionCount&&(Ji.debug("stopping region refetch after disconnect delay",{hostname:e}),wd.stopRefetch(e)),t&&(t.cleanupTimeout=void 0)}),3e4))}static cancelCleanup(e){const t=wd.connectionTrackers.get(e);(null==t?void 0:t.cleanupTimeout)&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=wd.connectionTrackers.get(e);t||(t={connectionCount:0},wd.connectionTrackers.set(e,t)),t.connectionCount++,wd.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=wd.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),0===t.connectionCount&&wd.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=wd.cache.get(n.hostname);wd.scheduleRefetch(this.serverUrl,this.token,null!==(t=null==i?void 0:i.maxAgeInMs)&&void 0!==t?t:Cd)}isCloud(){return Fs(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return tr(this,void 0,void 0,(function*(){return wd.fetchRegionSettings(this.serverUrl,this.token,e)}))}getNextBestRegionUrl(e){return tr(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=wd.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),wd.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),Ji.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){wd.updateCachedRegionSettings(this.serverUrl,this.token,e)}}wd.cache=new Map,wd.settingsTimeouts=new Map,wd.connectionTrackers=new Map,wd.fetchLock=new r;class Rd{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 Ha("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 Ha("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 Pd extends Rd{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:()=>tr(this,void 0,void 0,(function*(){try{const t=this.signal;if(null==t?void 0:t.aborted)throw t.reason;const n=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 n.done?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(n.value),{done:!1,value:n.value.content})}catch(e){throw t(),e}})),return(){return tr(this,void 0,void 0,(function*(){return t(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return tr(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=ar(o);!(n=(c=yield l.next()).done);d=!0){a=c.value,d=!1;const e=a;s.add(e)}}catch(e){i={error:e}}finally{try{d||n||!(r=l.return)||(yield r.call(l))}finally{if(i)throw i.error}}return Array.from(s)}()}))}}class Id extends Rd{constructor(e,t,n){super(e,t,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=ao(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",{fatal:!0}),i=this.signal,r=()=>{t.releaseLock(),this.signal=void 0};return{next:()=>tr(this,void 0,void 0,(function*(){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),{done:!0,value:void 0};{let t;this.handleChunkReceived(r.value);try{t=n.decode(r.value.content)}catch(t){throw new Ha("Cannot decode datastream chunk ".concat(r.value.chunkIndex," as text: ").concat(t),e.DataStreamErrorReason.DecodeFailed)}return{done:!1,value:t}}}catch(e){throw r(),e}})),return(){return tr(this,void 0,void 0,(function*(){return r(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return tr(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=ar(o);!(n=(c=yield l.next()).done);d=!0){a=c.value,d=!1;s+=a}}catch(e){i={error:e}}finally{try{d||n||!(r=l.return)||(yield r.call(l))}finally{if(i)throw i.error}}return s}()}))}}class Dd{constructor(){this.log=Ji,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[]}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 Ha('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 Ha('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 Ha("Participant ".concat(t," unexpectedly disconnected in the middle of sending data"),e.DataStreamErrorReason.AbnormalEnd);for(const e of i){var r=j(e,2);const t=r[0];r[1].controller.error(s),this.byteStreamControllers.delete(t)}for(const e of n){var a=j(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;if("byteHeader"===t.contentHeader.case){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:ao(t.timestamp),attributes:t.attributes,encryptionType:i},c=new ReadableStream({start:i=>{if(s=i,this.textStreamControllers.has(t.streamId))throw new Ha("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})}});a(new Pd(o,c,ao(t.totalLength)),{identity:n})}else if("textHeader"===t.contentHeader.case){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},o=new ReadableStream({start:i=>{if(a=i,this.textStreamControllers.has(t.streamId))throw new Ha("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})}});r(new Id(s,o,ao(t.totalLength)),{identity:n})}}handleStreamChunk(t,n){const i=this.byteStreamControllers.get(t.streamId);i&&(i.info.encryptionType!==n?(i.controller.error(new Ha("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 Ha("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 Ha("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),i.controller.close(),this.textStreamControllers.delete(t.streamId)));const r=this.byteStreamControllers.get(t.streamId);r&&(r.info.encryptionType!==n?r.controller.error(new Ha("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),r.controller.close()),this.byteStreamControllers.delete(t.streamId))}}class Md{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 tr(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 _d extends Md{}class Od extends Md{}class Ad{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return tr(this,void 0,void 0,(function*(){var n;const i=crypto.randomUUID(),r=(new TextEncoder).encode(e).byteLength,a=null===(n=null==t?void 0:t.attachments)||void 0===n?void 0:n.map((()=>crypto.randomUUID())),s=new Array(a?a.length+1:1).fill(0),o=(e,n)=>{var i;s[n]=e;const r=s.reduce(((e,t)=>e+t),0);null===(i=null==t?void 0:t.onProgress)||void 0===i||i.call(t,r)},c=yield this.streamText({streamId:i,totalSize:r,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:a,attributes:null==t?void 0:t.attributes});return yield c.write(e),o(1,0),yield c.close(),(null==t?void 0:t.attachments)&&a&&(yield Promise.all(t.attachments.map(((e,n)=>tr(this,void 0,void 0,(function*(){return this._sendFile(a[n],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{o(e,n+1)}})})))))),c.info}))}streamText(t){return tr(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={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},o=new Zt({streamId:a,mimeType:s.mimeType,topic:s.topic,timestamp:so(s.timestamp),totalLength:so(s.size),attributes:s.attributes,contentHeader:{case:"textHeader",value:new Yt({version:null==t?void 0:t.version,attachedStreamIds:s.attachedStreamIds,replyToStreamId:null==t?void 0:t.replyToStreamId,operationType:"update"===(null==t?void 0:t.type)?Qt.UPDATE:Qt.CREATE})}}),c=null==t?void 0:t.destinationIdentities,d=new Ct({destinationIdentities:c,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(d,Td.RELIABLE);let l=0;const u=this.engine,h=new WritableStream({write(e){return tr(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,15e3)){const e=new $t({content:t,streamId:a,chunkIndex:so(l)}),n=new Ct({destinationIdentities:c,value:{case:"streamChunk",value:e}});yield u.sendDataPacket(n,Td.RELIABLE),l+=1}}))},close(){return tr(this,void 0,void 0,(function*(){const e=new en({streamId:a}),t=new Ct({destinationIdentities:c,value:{case:"streamTrailer",value:e}});yield u.sendDataPacket(t,Td.RELIABLE)}))},abort(e){console.log("Sink error:",e)}});let p=()=>tr(this,void 0,void 0,(function*(){yield m.close()}));u.once(e.EngineEvent.Closing,p);const m=new _d(h,s,(()=>this.engine.off(e.EngineEvent.Closing,p)));return m}))}sendFile(e,t){return tr(this,void 0,void 0,(function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}}))}_sendFile(e,t,n){return tr(this,void 0,void 0,(function*(){var i;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(i=null==n?void 0:n.mimeType)&&void 0!==i?i:t.type,topic:null==n?void 0:n.topic,destinationIdentities:null==n?void 0:n.destinationIdentities}),a=t.stream().getReader();for(;;){const e=yield a.read(),t=e.done,n=e.value;if(t)break;yield r.write(n)}return yield r.close(),r.info}))}streamBytes(e){return tr(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=new Zt({totalLength:so(d.size),mimeType:d.mimeType,streamId:o,topic:d.topic,timestamp:so(Date.now()),attributes:d.attributes,contentHeader:{case:"byteHeader",value:new Xt({name:d.name})}}),u=new Ct({destinationIdentities:c,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(u,Td.RELIABLE);let h=0;const p=new r,m=this.engine,g=this.log,v=new WritableStream({write(e){return tr(this,void 0,void 0,(function*(){const t=yield p.lock();let n=0;try{for(;n<e.byteLength;){const t=e.slice(n,n+15e3),i=new Ct({destinationIdentities:c,value:{case:"streamChunk",value:new $t({content:t,streamId:o,chunkIndex:so(h)})}});yield m.sendDataPacket(i,Td.RELIABLE),h+=1,n+=t.byteLength}}finally{t()}}))},close(){return tr(this,void 0,void 0,(function*(){const e=new en({streamId:o}),t=new Ct({destinationIdentities:c,value:{case:"streamTrailer",value:e}});yield m.sendDataPacket(t,Td.RELIABLE)}))},abort(e){g.error("Sink error:",e)}});return new Od(v,d)}))}}function Nd(e){if(0===e.length){return(new AbortController).signal}if(1===e.length)return e[0];for(const t of e)if(t.aborted)return t;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 xd(e){const t=new AbortController;return setTimeout((()=>{t.abort(new DOMException("signal timed out after ".concat(e," ms"),"TimeoutError"))}),e),t.signal}var Ld,Ud,Fd;!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"}(Ld||(Ld={}));class Bd extends Pa{constructor(e,t,n){super(19,e,n),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=Ld[t]}static tooShort(){return new Bd("Too short to contain a valid header",Ld.TooShort)}static headerOverrun(){return new Bd("Header exceeds total packet length",Ld.HeaderOverrun)}static missingExtWords(){return new Bd("Extension word indicator is missing",Ld.MissingExtWords)}static unsupportedVersion(e){return new Bd("Unsupported version ".concat(e),Ld.UnsupportedVersion)}static invalidHandle(e){return new Bd("invalid track handle: ".concat(e.message),Ld.InvalidHandle,{cause:e})}static malformedExt(e){return new Bd("Extension with tag ".concat(e," is malformed"),Ld.MalformedExt)}}!function(e){e[e.TooSmallForHeader=0]="TooSmallForHeader",e[e.TooSmallForPayload=1]="TooSmallForPayload"}(Ud||(Ud={}));class jd extends Pa{constructor(e,t,n){super(19,e,n),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=Ud[t]}static tooSmallForHeader(){return new jd("Buffer cannot fit header",Ud.TooSmallForHeader)}static tooSmallForPayload(){return new jd("Buffer cannot fit payload",Ud.TooSmallForPayload)}}class qd{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"}(Fd||(Fd={}));class Vd extends qd{}class Hd extends Vd{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return 2+Hd.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,Hd.tag),t+=1,e.setUint8(t,Hd.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:Hd.tag,lengthBytes:Hd.lengthBytes,timestamp:this.timestamp}}}Hd.tag=Fd.UserTimestamp,Hd.lengthBytes=8;class Wd extends Vd{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return 2+Wd.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,Wd.tag),t+=1,e.setUint8(t,Wd.lengthBytes),t+=1,e.setUint8(t,this.keyIndex),t+=1;for(let n=0;n<this.iv.length;n+=1)e.setUint8(t,this.iv[n]),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:Wd.tag,lengthBytes:Wd.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}}Wd.tag=Fd.E2ee,Wd.lengthBytes=13;class Kd extends qd{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=rc(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 Fd.UserTimestamp:if(t.byteLength-r<Hd.lengthBytes)throw Bd.malformedExt(e);n=new Hd(t.getBigUint64(r)),r+=a;break;case Fd.E2ee:if(t.byteLength-r<Wd.lengthBytes)throw Bd.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 Wd(s,o),r+=a;break;default:if(t.byteLength-r<a)throw Bd.malformedExt(e);r+=a}}return[new Kd({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 zd={from:e=>({payload:e.payload,extensions:new Kd({userTimestamp:e.userTimestamp?new Hd(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}}},Jd=Symbol.for("lk.track"),Gd=Symbol.for("lk.data-track");class Qd{constructor(e,t,n){this.trackSymbol=Jd,this.isLocal=!1,this.typeSymbol=Gd,this.info=e,this.manager=t,this.publisherIdentity=n.publisherIdentity}subscribe(e){try{const t=j(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(e){throw e}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}}class Yd extends qd{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 Kd}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 jd.tooSmallForHeader();let t,n=0;switch(this.marker){case Xd.Inter:t=0;break;case Xd.Final:t=1;break;case Xd.Start:t=2;break;case Xd.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 t=0;t<s;t+=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=rc(e);if(t.byteLength<12)throw Bd.tooShort();let n=0;const i=t.getUint8(n);n+=1;const r=i>>5&7;if(r>0)throw Bd.unsupportedVersion(r);let a;switch(i>>3&3){case 2:a=Xd.Start;break;case 1:a=Xd.Final;break;case 3:a=Xd.Single;break;default:a=Xd.Inter}const s=(i>>2&1)>0;let o;n+=1;try{o=oc.fromNumber(t.getUint16(n))}catch(e){throw e instanceof sc&&(e.isReason(ac.Reserved)||e.isReason(ac.TooLarge))?Bd.invalidHandle(e):e}n+=2;const c=tc.u16(t.getUint16(n));n+=2;const d=tc.u16(t.getUint16(n));n+=2;const l=nc.fromRtpTicks(t.getUint32(n));n+=4;let u=new Kd;if(s){if(t.byteLength-n<2)throw Bd.missingExtWords();let e=t.getUint16(n);n+=2;let i=4*(e+1)-2;if(n+i>t.byteLength)throw Bd.headerOverrun();let r=new DataView(t.buffer,t.byteOffset+n,i);const a=j(Kd.fromBinary(r),2);u=a[0],n+=a[1]}return[new Yd({marker:a,trackHandle:o,sequence:c,frameNumber:d,timestamp:l,extensions:u}),n]}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 Xd;!function(e){e[e.Start=0]="Start",e[e.Inter=1]="Inter",e[e.Final=2]="Final",e[e.Single=3]="Single"}(Xd||(Xd={}));class Zd extends qd{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 jd.tooSmallForPayload();for(let n=0;n<this.payload.length;n+=1)e.setUint8(t,this.payload[n]),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=rc(e),n=j(Yd.fromBinary(t),2),i=n[0],r=n[1],a=t.buffer.slice(t.byteOffset+r,t.byteOffset+t.byteLength);return[new Zd(i,new Uint8Array(a)),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}}const $d=Qi(e.LoggerNames.DataTracks);class el extends Pa{constructor(e,t,n,i){super(19,"Frame ".concat(n," dropped: ").concat(e),i),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=tl[t],this.frameNumber=n}static interrupted(e,t){return new el("Interrupted by the start of a new frame ".concat(t),tl.Interrupted,e)}static unknownFrame(e){return new el("Initial packet was never received.",tl.UnknownFrame,e)}static bufferFull(e){return new el("Reorder buffer is full.",tl.BufferFull,e)}static incomplete(e,t,n){return new el("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(n," packets."),tl.Incomplete,e)}}var tl,nl;!function(e){e[e.Interrupted=0]="Interrupted",e[e.UnknownFrame=1]="UnknownFrame",e[e.BufferFull=2]="BufferFull",e[e.Incomplete=3]="Incomplete"}(tl||(tl={}));class il{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case Xd.Single:return this.frameFromSingle(e,t);case Xd.Start:return this.beginPartial(e,t);case Xd.Inter:case Xd.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!==Xd.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 el.interrupted(n,e.header.frameNumber.value);$d.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!==Xd.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 el.interrupted(e,r);$d.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!==Xd.Inter&&e.header.marker!==Xd.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),el.unknownFrame(t);if(n.payloads.size>=il.MAX_BUFFER_PACKETS)throw this.partials.delete(t),el.bufferFull(t);return n.payloads.has(e.header.sequence.value)&&$d.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===Xd.Final?this.finalize(t,n,e.header.sequence.value):null}finalize(e,t,n){const i=t.payloads.size;let r=0;for(const e of t.payloads.values())r+=e.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),el.incomplete(e,i,n-t.startSequence.value+1)}}il.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"}(nl||(nl={}));class rl extends Pa{constructor(e,t,n){super(22,e,n),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=nl[t]}static unpublished(){return new rl("The track has been unpublished and is no longer available",nl.Unpublished)}static timeout(){return new rl("Request to subscribe to data track timed-out",nl.Timeout)}static disconnected(){return new rl("Cannot subscribe to data track when disconnected",nl.Disconnected)}static cancelled(){return new rl("Subscription to data track cancelled by caller",nl.Cancelled)}}const al=Qi(e.LoggerNames.DataTracks);class sl{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 il;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 tr(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(e){return al.warn("Data frame depacketize error: ".concat(e)),null}return t}decryptIfNeeded(e){return tr(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 al.error("Missing E2EE meta"),null;let a;try{a=yield i.handleEncryptedData(e.payload,r.iv,this.publisherIdentity,r.keyIndex)}catch(e){return al.error("Error decrypting packet: ".concat(e)),null}return e.payload=a.payload,e}))}}const ol=Qi(e.LoggerNames.DataTracks);class cl extends cr.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)):ol.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 eo,a=()=>{null==t||t.removeEventListener("abort",o)},s=()=>{if(a(),!i)return void ol.warn("ReadableStream subscribed to ".concat(e," was not started."));const t=this.descriptors.get(e);t?"active"===t.subscription.type?(t.subscription.streamControllers.delete(i),0===t.subscription.streamControllers.size&&this.unSubscribeRequest(t.info.sid)):ol.warn("Subscription for track ".concat(e," is not active, skipping cancel...")):ol.warn("Unknown track ".concat(e,", skipping cancel..."))},o=()=>{var t;if(!i)return;const n=this.descriptors.get(e);"active"===(null==n?void 0:n.subscription.type)&&n.subscription.streamControllers.delete(i),i.error(rl.cancelled()),null===(t=r.reject)||void 0===t||t.call(r,rl.cancelled()),s()},c=new ReadableStream({start:n=>{i=n,this.subscribeRequest(e,t).then((()=>tr(this,void 0,void 0,(function*(){var i,s,c;const d=this.descriptors.get(e);if(!d){ol.error("Unknown track ".concat(e));const t=rl.disconnected();return n.error(t),void(null===(i=r.reject)||void 0===i||i.call(r,t))}if("active"!==d.subscription.type){ol.error("Subscription for track ".concat(e," is not active"));const t=rl.disconnected();return n.error(t),void(null===(s=r.reject)||void 0===s||s.call(r,t))}(null==t?void 0:t.aborted)?o():(null==t||t.addEventListener("abort",o),d.subscription.streamControllers.set(n,a),null===(c=r.resolve)||void 0===c||c.call(r))})))).catch((e=>{var t;n.error(e),null===(t=r.reject)||void 0===t||t.call(r,e)}))},cancel:()=>{s()}},new CountQueuingStrategy({highWaterMark:n}));return[c,r.promise]}subscribeRequest(e,t){return tr(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)=>tr(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=Nd([n,i].filter((e=>void 0!==e))),a=new eo;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,rl.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 eo,pendingRequestCount:1,cancel:()=>{var t,i;const a=n.subscription;n.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1}),"pending"===a.type&&(null===(i=(t=a.completionFuture).reject)||void 0===i||i.call(t,r.aborted?rl.timeout():rl.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});const r=xd(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 tr(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 ol.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 i of e){var n=j(i,2);const e=n[0];(0,n[1])();try{e.close()}catch(e){ol.warn("Failed to close readable stream for track ".concat(t,": ").concat(e))}}}receiveSfuPublicationUpdates(e){return tr(this,void 0,void 0,(function*(){if(0===e.size)return;const t=new Map;for(const i of e.entries()){var n=j(i,2);const e=n[0],r=n[1],a=new Set;for(const t of r)a.add(t.sid),this.descriptors.has(t.sid)||(yield this.handleTrackPublished(e,t));t.set(e,a)}for(const e of t.entries()){var i=j(e,2);const t=i[0],n=i[1];let r=Array.from(this.descriptors.entries()).filter((e=>{let n=j(e,2);return n[0],n[1].publisherIdentity===t})).map((e=>j(e,1)[0])).filter((e=>!n.has(e)));for(const e of r)this.handleTrackUnpublished(e)}}))}queryPublications(){return tr(this,void 0,void 0,(function*(){return Array.from(this.descriptors.values()).map((e=>e.info))}))}handleTrackPublished(e,t){return tr(this,void 0,void 0,(function*(){if(this.descriptors.has(t.sid))return void ol.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 Qd(n.info,this,{publisherIdentity:e});this.emit("trackPublished",{track:i})}))}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})):ol.error("Unknown track ".concat(e))}receivedSfuSubscriberHandles(e){for(const n of e.entries()){var t=j(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 ol.warn("No subscription for ".concat(t));case"active":return r.subscription.subcriptionHandle=e,void this.subscriptionHandles.set(e,t);case"pending":{const a=new sl({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 ol.error("Unknown track ".concat(t))}packetReceived(e){return tr(this,void 0,void 0,(function*(){let t;try{t=j(Zd.fromBinary(e),1)[0]}catch(e){return void ol.error("Failed to deserialize packet: ".concat(e))}const n=this.subscriptionHandles.get(t.header.trackHandle);if(!n)return void ol.warn("Unknown subscriber handle ".concat(t.header.trackHandle));const i=this.descriptors.get(n);if(!i)return void ol.error("Missing descriptor for track ".concat(n));if("active"!==i.subscription.type)return void ol.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){ol.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=zd.lossyIntoFrame(r);e.enqueue(t)}}))}resendSubscriptionUpdates(){for(const t of this.descriptors){var e=j(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,rl.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,rl.disconnected())),"active"===n.subscription.type&&this.closeStreamControllers(n.subscription.streamControllers,n.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}}class dl extends Pa{constructor(e,t,n){super(19,e,n),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=ll[t]}static mtuTooShort(){return new dl("MTU is too short to send frame",ll.MtuTooShort)}}var ll,ul,hl,pl;!function(e){e[e.MtuTooShort=0]="MtuTooShort"}(ll||(ll={}));class ml{constructor(e,t){this.sequence=tc.u16(0),this.frameNumber=tc.u16(0),this.clock=ic.rtpStartingNow(nc.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?Xd.Single:0===e?Xd.Start:e===t-1?Xd.Final:Xd.Inter}*packetize(e,t){var n;const i=this.frameNumber.getThenIncrement(),r={marker:Xd.Inter,trackHandle:this.handle,sequence:tc.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 Yd(r).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw dl.mtuTooShort();const s=this.mtuSizeBytes-a,o=Math.ceil(e.payload.byteLength/s);for(let t=0,n=0;n<e.payload.byteLength;t=(c=[t+1,n+s])[0],n=c[1],c){var c;const i=this.sequence.getThenIncrement(),a=new Yd(Object.assign(Object.assign({},r),{marker:ml.computeFrameMarker(t,o),sequence:i})),d=Math.min(s,e.payload.byteLength-n),l=new Uint8Array(e.payload.buffer,e.payload.byteOffset+n,d);yield new Zd(a,l)}}}!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"}(ul||(ul={}));class gl extends Pa{constructor(e,t,n){super(21,e,n),this.name="DataTrackPublishError",this.reason=t,this.reasonName=ul[t],this.rawMessage=null==n?void 0:n.rawMessage}static notAllowed(e){return new gl("Data track publishing unauthorized",ul.NotAllowed,{rawMessage:e})}static duplicateName(e){return new gl("Track name already taken",ul.DuplicateName,{rawMessage:e})}static invalidName(e){return new gl("Track name is invalid",ul.InvalidName,{rawMessage:e})}static timeout(){return new gl("Publish data track timed-out. Does the LiveKit server support data tracks?",ul.Timeout)}static limitReached(e){return new gl("Data track publication limit reached",ul.LimitReached,{rawMessage:e})}static unknown(e,t){return new gl("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),ul.Unknown)}static disconnected(){return new gl("Room disconnected",ul.Disconnected)}static cancelled(){return new gl("Publish data track cancelled by caller",ul.Cancelled)}}!function(e){e[e.TrackUnpublished=0]="TrackUnpublished",e[e.Dropped=1]="Dropped"}(hl||(hl={}));class vl extends Pa{constructor(e,t,n){super(22,e,n),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=hl[t]}static trackUnpublished(){return new vl("Track is no longer published",hl.TrackUnpublished)}static dropped(e){return new vl("Frame was dropped",hl.Dropped,{cause:e})}}!function(e){e[e.Packetizer=0]="Packetizer",e[e.Encryption=1]="Encryption"}(pl||(pl={}));class fl extends Pa{constructor(e,t,n){super(21,e,n),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=pl[t]}static packetizer(e){return new fl("Error packetizing frame",pl.Packetizer,{cause:e})}static encryption(e){return new fl("Error encrypting frame",pl.Encryption,{cause:e})}}class kl{constructor(t,n){this.trackSymbol=Jd,this.isLocal=!0,this.typeSymbol=Gd,this.handle=null,this.log=Ji,this.flushedFuture=new eo,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 eo)},this.options=t,this.manager=n,this.log=Qi(e.LoggerNames.DataTracks),this.manager.on("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.on("reset",this.handleManagerReset)}static withExplicitHandle(e,t,n){const i=new kl(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 tr(this,void 0,void 0,(function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(e){throw e}}))}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 vl.trackUnpublished();const t=zd.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(e){throw e}}flush(){return tr(this,void 0,void 0,(function*(){if(!this.isFlushed)return this.flushedFuture.promise}))}unpublish(){return tr(this,void 0,void 0,(function*(){if(this.handle)try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}else Ji.warn('Data track "'.concat(this.options.name,'" is not published, so unpublishing has no effect.'))}))}}class yl{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new ml(e.info.pubHandle,yl.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return rr(this,arguments,(function*(){const t=yield ir(this.encryptIfNeeded(e));try{yield ir(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:ir(e[i](t)),done:!1}:r?r(t):t}:r}}(ar(this.packetizer.packetize(t))))}catch(e){if(e instanceof dl)throw fl.packetizer(e);throw e}}))}encryptIfNeeded(e){return tr(this,void 0,void 0,(function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(e){throw fl.encryption(e)}return e.payload=t.payload,e.extensions.e2ee=new Wd(t.keyIndex,t.iv),e}))}}yl.TRANSPORT_MTU_BYTES=16e3;const bl=Qi(e.LoggerNames.DataTracks),Tl={pending:()=>({type:"pending",completionFuture:new eo}),active:(e,t)=>({type:"active",info:e,publishState:"published",pipeline:new yl({info:e,e2eeManager:t}),unpublishingFuture:new eo})};class Sl extends cr.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new cc,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 Sl;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 tr(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 vl.trackUnpublished();if("unpublished"===o.publishState)throw vl.trackUnpublished();if("republishing"===o.publishState)throw vl.dropped("Data track republishing");try{try{for(var c,d=!0,l=ar(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(e){i={error:e}}finally{try{d||n||!(r=l.return)||(yield r.call(l))}finally{if(i)throw i.error}}}catch(e){throw vl.dropped(e)}}))}handlePacketSendComplete(e){var t;let n=(null!==(t=this.inFlightPacketCounter.get(e))&&void 0!==t?t:0)-1;n<0&&(bl.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 tr(this,void 0,void 0,(function*(){const n=this.handleAllocator.get();if(!n)throw gl.limitReached();const i=xd(1e4),r=t?Nd([t,i]):i;if(this.descriptors.has(n))throw new Error("Descriptor for handle already exists");const a=Tl.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?gl.timeout():gl.cancelled()))):bl.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:kl.withExplicitHandle(e,this,n)}),n)}))}queryPublished(){return Array.from(this.descriptors.values()).filter((e=>"active"===e.type)).map((e=>e.info))}unpublishRequest(e){return tr(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})):bl.warn("Track ".concat(e," not active")):bl.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 e=t.data,r=e.usesE2ee?this.e2eeManager:null;this.descriptors.set(e.pubHandle,Tl.active(e,r)),null===(i=(n=s.completionFuture).resolve)||void 0===i||i.call(n)}else null===(a=(r=s.completionFuture).reject)||void 0===a||a.call(r,t.error);return;case"active":if("republishing"!==s.publishState)return void bl.warn("Track ".concat(e," already active"));if("error"===t.type)return void bl.warn("Republish failed for track ".concat(e));bl.debug("Track ".concat(e," republished")),s.info.sid=t.data.sid,s.publishState="published",this.descriptors.set(s.info.pubHandle,s)}else bl.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)):bl.warn("Track ".concat(e," not active"))):bl.warn("No descriptor for ".concat(e))}sfuWillRepublishTracks(){var e,t;for(const i of this.descriptors.entries()){var n=j(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,gl.disconnected());break;case"active":a.publishState="republishing",this.emit("sfuPublishRequest",{handle:a.info.pubHandle,name:a.info.name,usesE2ee:a.info.usesE2ee})}}}reset(){return tr(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,gl.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 El extends Error{constructor(e,t,n,i){super(t),this.code=e,this.message=Il(t,El.MAX_MESSAGE_BYTES),this.data=n?Il(n,El.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 El(e.code,e.message,e.data)}toProto(){return new Ft({code:this.code,message:this.message,data:this.data})}static builtIn(e,t,n){return new El(El.ErrorCode[e],El.ErrorMessage[e],t,n)}}El.MAX_MESSAGE_BYTES=256,El.MAX_DATA_BYTES=15360,El.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},El.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 Cl="lk.rpc_request",wl="lk.rpc_response";var Rl;!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"}(Rl||(Rl={}));function Pl(e){return(new TextEncoder).encode(e).length}function Il(e,t){if(Pl(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 Dl extends dr{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 tr(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(Pl(r)>15360&&e<1)throw El.builtIn("REQUEST_PAYLOAD_TOO_LARGE");const a=t.getServerVersion();if(a&&Hs(a,"1.8.0")<0)throw El.builtIn("UNSUPPORTED_SERVER");const o=Math.max(s,8e3),c=crypto.randomUUID(),d=new eo;let l=null;const u=setTimeout((()=>{var e;t.pendingAcks.delete(c),null===(e=d.reject)||void 0===e||e.call(d,El.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,El.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 tr(this,void 0,void 0,(function*(){if(a>=1){const a=yield this.outgoingDataStreamManager.streamText({topic:Cl,destinationIdentities:[e],attributes:{[Rl.RPC_REQUEST_ID]:t,[Rl.RPC_REQUEST_METHOD]:n,[Rl.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:"".concat(r),[Rl.RPC_REQUEST_VERSION]:"".concat(2)}});return yield a.write(i),void(yield a.close())}this.emit("sendDataPacket",{packet:new Ct({destinationIdentities:[e],kind:wt.RELIABLE,value:{case:"rpcRequest",value:new xt({id:t,method:n,payload:i,responseTimeoutMs:r,version:1})}})})}))}handleIncomingDataStream(e,t,n){return tr(this,void 0,void 0,(function*(){const i=n[Rl.RPC_REQUEST_ID];if(!i)return void this.log.warn("RPC data stream malformed: ".concat(Rl.RPC_REQUEST_ID," not set."));const r=this.pendingResponses.get(i);if(r&&r.participantIdentity!==t)return void this.log.warn("RPC response stream for ".concat(i," arrived from unexpected sender ").concat(t,", expected ").concat(r.participantIdentity,". Ignoring."));let a;try{a=yield e.readAll()}catch(e){return this.log.warn("Error reading RPC response payload: ".concat(e)),void this.handleIncomingRpcResponseFailure(i,El.builtIn("APPLICATION_ERROR","Error reading RPC response payload",{cause:e}))}this.handleIncomingRpcResponseSuccess(i,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 t of this.pendingAcks){var n=j(t,2);const i=n[0];n[1].participantIdentity===e&&this.pendingAcks.delete(i)}for(const n of this.pendingResponses){var i=j(n,2);const a=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,El.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(a))}}}class Ml extends dr{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 tr(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,El.builtIn("UNSUPPORTED_VERSION"));const i=this.rpcHandlers.get(t.method);if(!i)return void this.publishRpcResponsePacket(e,t.id,null,El.builtIn("UNSUPPORTED_METHOD"));let r;try{r=yield i({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(i){let r;return i instanceof El?r=i:(this.log.warn("Uncaught error returned by RPC handler for ".concat(t.method,". Returning APPLICATION_ERROR instead."),i),r=El.builtIn("APPLICATION_ERROR","Uncaught error: ".concat(null!==(n=null==i?void 0:i.message)&&void 0!==n?n:i),{cause:i})),void this.publishRpcResponsePacket(e,t.id,null,r)}yield this.publishRpcResponse(e,t.id,null!=r?r:"")}))}handleIncomingDataStream(e,t,n){return tr(this,void 0,void 0,(function*(){const i=n[Rl.RPC_REQUEST_ID],r=n[Rl.RPC_REQUEST_METHOD],a=parseInt(n[Rl.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),s=parseInt(n[Rl.RPC_REQUEST_VERSION],10);if(!i||!r||Number.isNaN(a)||Number.isNaN(s))return this.log.warn("RPC data stream malformed: ".concat(Rl.RPC_REQUEST_ID," / ").concat(Rl.RPC_REQUEST_METHOD," / ").concat(Rl.RPC_REQUEST_RESPONSE_TIMEOUT_MS," / ").concat(Rl.RPC_REQUEST_VERSION," not set.")),void this.publishRpcResponsePacket(t,i,null,El.builtIn("APPLICATION_ERROR","RPC data stream malformed"));if(this.publishRpcAck(t,i),2!==s)return void this.publishRpcResponsePacket(t,i,null,El.builtIn("UNSUPPORTED_VERSION"));let o;try{o=yield e.readAll()}catch(e){return this.log.warn("Error reading RPC request payload: ".concat(e)),void this.publishRpcResponsePacket(t,i,null,El.builtIn("APPLICATION_ERROR","Error reading RPC request payload",{cause:e}))}const c=this.rpcHandlers.get(r);if(!c)return void this.publishRpcResponsePacket(t,i,null,El.builtIn("UNSUPPORTED_METHOD"));let d;try{d=yield c({requestId:i,callerIdentity:t,payload:o,responseTimeout:a})}catch(e){let n;return e instanceof El?n=e:(this.log.warn("Uncaught error returned by RPC handler for ".concat(r,". Returning APPLICATION_ERROR instead."),e),n=El.builtIn("APPLICATION_ERROR")),void this.publishRpcResponsePacket(t,i,null,n)}yield this.publishRpcResponse(t,i,null!=d?d:"")}))}publishRpcAck(e,t){this.emit("sendDataPacket",{packet:new Ct({destinationIdentities:[e],kind:wt.RELIABLE,value:{case:"rpcAck",value:new Lt({requestId:t})}})})}publishRpcResponsePacket(e,t,n,i){this.emit("sendDataPacket",{packet:new Ct({destinationIdentities:[e],kind:wt.RELIABLE,value:{case:"rpcResponse",value:new Ut({requestId:t,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:null!=n?n:""}})}})})}publishRpcResponse(e,t,n){return tr(this,void 0,void 0,(function*(){if(this.getRemoteParticipantClientProtocol(e)>=1){const i=yield this.outgoingDataStreamManager.streamText({topic:wl,destinationIdentities:[e],attributes:{[Rl.RPC_REQUEST_ID]:t}});return yield i.write(n),void(yield i.close())}if(Pl(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,El.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"));this.publishRpcResponsePacket(e,t,n,null)}))}}class _l extends Vo{constructor(e,t,n,i,r,a){super(e,t,ks.Kind.Audio,n,a),this.monitorReceiver=()=>tr(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=qo(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;Us()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Us())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return tr(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(Is(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&Is(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 tr(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 Ol extends cr.EventEmitter{constructor(t,n,i,r){var a;super(),this.metadataMuted=!1,this.encryption=ft.NONE,this.log=Ji,this.handleMuted=()=>{this.emit(e.TrackEvent.Muted)},this.handleUnmuted=()=>{this.emit(e.TrackEvent.Unmuted)},this.log=Qi(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=ks.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)),ps(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(co(this.track))return this.track}get videoTrack(){if(lo(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=ks.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===ks.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"}(Ol||(Ol={}));class Al extends Ol{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&&lo(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 tr(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){return tr(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){return tr(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){return tr(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}getTrackFeatures(){var e;if(co(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 Nl(e,t){return tr(this,void 0,void 0,(function*(){null!=e||(e={});let n=!1;const i=ms(e),r=i.audioProcessor,a=i.videoProcessor,s=i.optionsWithoutProcessor;let o=s.audio,c=s.video;if(r&&"object"==typeof s.audio&&(s.audio.processor=r),a&&"object"==typeof s.video&&(s.video.processor=a),e.audio&&"object"==typeof s.audio&&"string"==typeof s.audio.deviceId){const e=s.audio.deviceId;s.audio.deviceId={exact:e},n=!0,o=Object.assign(Object.assign({},s.audio),{deviceId:{ideal:e}})}if(s.video&&"object"==typeof s.video&&"string"==typeof s.video.deviceId){const e=s.video.deviceId;s.video.deviceId={exact:e},n=!0,c=Object.assign(Object.assign({},s.video),{deviceId:{ideal:e}})}!0===s.audio?s.audio={deviceId:"default"}:"object"==typeof s.audio&&null!==s.audio&&(s.audio=Object.assign(Object.assign({},s.audio),{deviceId:s.audio.deviceId||"default"})),!0===s.video?s.video={deviceId:"default"}:"object"!=typeof s.video||s.video.deviceId||(s.video.deviceId="default");const d=as(is(s,Vc,Hc)),l=navigator.mediaDevices.getUserMedia(d);s.audio&&(Zo.userMediaPromiseMap.set("audioinput",l),l.catch((()=>Zo.userMediaPromiseMap.delete("audioinput")))),s.video&&(Zo.userMediaPromiseMap.set("videoinput",l),l.catch((()=>Zo.userMediaPromiseMap.delete("videoinput"))));try{const e=yield l;return yield Promise.all(e.getTracks().map((n=>tr(this,void 0,void 0,(function*(){let i;const s="audio"===n.kind?d.audio:d.video;"boolean"!=typeof s&&(i=s);const o=n.getSettings().deviceId;(null==i?void 0:i.deviceId)&&no(i.deviceId)!==o?i.deviceId=o:i||(i={deviceId:o});const c=function(e,t,n){switch(e.kind){case"audio":return new Zc(e,t,!1,void 0,n);case"video":return new hd(e,t,!1,n);default:throw new Ua("unsupported track type: ".concat(e.kind))}}(n,i,t);return c.kind===ks.Kind.Video?c.source=ks.Source.Camera:c.kind===ks.Kind.Audio&&(c.source=ks.Source.Microphone),c.mediaStream=e,co(c)&&r?yield c.setProcessor(r):lo(c)&&a&&(yield c.setProcessor(a)),c})))))}catch(i){if(!n)throw i;return Nl(Object.assign(Object.assign({},e),{audio:o,video:c}),t)}}))}function xl(e){return tr(this,void 0,void 0,(function*(){return(yield Nl({audio:!1,video:null==e||e}))[0]}))}function Ll(e){return tr(this,void 0,void 0,(function*(){return(yield Nl({audio:null==e||e,video:!1}))[0]}))}var Ul,Fl;e.ConnectionQuality=void 0,(Ul=e.ConnectionQuality||(e.ConnectionQuality={})).Excellent="excellent",Ul.Good="good",Ul.Poor="poor",Ul.Lost="lost",Ul.Unknown="unknown";class Bl extends cr.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=Ji,this.loggerOptions=s,this.log=Qi(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=j(t,2)[1];if(n.source===e)return n}}getTrackPublicationByName(e){for(const t of this.trackPublications){const n=j(t,2)[1];if(n.trackName===e)return n}}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new eo,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(ks.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(ks.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(ks.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=>co(t.track)&&t.track.setAudioContext(e)))}addTrackPublication(t){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 ks.Kind.Audio:this.audioTrackPublications.set(t.trackSid,t);break;case ks.Kind.Video:this.videoTrackPublications.set(t.trackSid,t)}}}class jl extends Bl{constructor(t,n,i,a,s,o,c,d){super(t,n,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 eo)},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 eo),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!==_i.OK&&r.reject(new Va(i,n)),this.pendingSignalRequests.delete(t)),e.request.case){case"publishDataTrack":{let t;switch(e.reason){case _i.NOT_ALLOWED:t=gl.notAllowed(e.message);break;case _i.DUPLICATE_NAME:t=gl.duplicateName(e.message);break;case _i.INVALID_NAME:t=gl.invalidName(e.message);break;case _i.LIMIT_EXCEEDED:t=gl.limitReached(e.message);break;default:t=gl.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 fi({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",ps(e))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",ps(e)),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",ps(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",ps(n)),this.emit(e.ParticipantEvent.LocalTrackCpuConstrained,t,n)},this.handleSubscribedQualityUpdate=e=>tr(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=ar(o);!(t=(c=yield l.next()).done);d=!0){r=c.value,d=!1;const e=r;Xa(e)&&(this.log.debug("publish ".concat(e," for ").concat(s.videoTrack.sid),ps(s)),yield this.publishAdditionalCodecForTrack(s.videoTrack,e,s.options))}}catch(e){n={error:e}}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=>tr(this,void 0,void 0,(function*(){if(e.source===ks.Source.ScreenShare||e.source===ks.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",ps(e)),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(ho(e)||uo(e))try{if(Ls())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===ks.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),ps(e)),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",ps(e)),ho(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",ps(e)),yield e.mute()}})),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=a,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.roomOutgoingDataStreamManager=s,this.roomOutgoingDataTrackManager=o,this.rpcClientManager=c,this.rpcServerManager=d}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 tr(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:e})}))}setName(e){return tr(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:e})}))}setAttributes(e){return tr(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:e})}))}requestMetadataUpdate(e){return tr(this,arguments,void 0,(function(e){var t=this;let n=e.metadata,i=e.name,r=e.attributes;return function*(){return new ka(((e,a)=>tr(t,void 0,void 0,(function*(){var t,s;try{let o=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=n?n:this.metadata)&&void 0!==t?t:"",null!==(s=null!=i?i:this.name)&&void 0!==s?s:"",r),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{a(e),o=!0},values:{name:i,metadata:n,attributes:r}});performance.now()-d<5e3&&!o;){if((!i||this.name===i)&&(!n||this.metadata===n)&&(!r||Object.entries(r).every((e=>{let t=j(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 Ss(50)}a(new Va("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error?a(e):a(new Error(String(e)))}}))))}()}))}setCameraEnabled(e,t,n){return this.setTrackEnabled(ks.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(ks.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(ks.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return tr(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,n,i,r){return tr(this,void 0,void 0,(function*(){var a,s;this.log.debug("setTrackEnabled",{source:t,enabled:n}),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(t);if(n)if(o)yield o.unmute();else{let n;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 ks.Source.Camera:n=yield this.createTracks({video:null===(a=i)||void 0===a||a});break;case ks.Source.Microphone:n=yield this.createTracks({audio:null===(s=i)||void 0===s||s});break;case ks.Source.ScreenShare:n=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Ua(t)}}catch(i){throw null==n||n.forEach((e=>{e.stop()})),i instanceof Error&&this.emit(e.ParticipantEvent.MediaDevicesError,i,ds(t)),this.pendingPublishing.delete(t),i}for(const e of n){const n=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);t===ks.Source.Microphone&&co(e)&&n.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone"),e.startPreConnectBuffer())}try{const e=[];for(const t of n)this.log.info("publishing track",ps(t)),e.push(this.publishTrack(t,r));o=j(yield Promise.all(e),1)[0]}catch(e){throw null==n||n.forEach((e=>{e.stop()})),e}finally{this.pendingPublishing.delete(t)}}else if(!(null==o?void 0:o.track)&&this.pendingPublishing.has(t)&&(o=yield this.waitForPendingPublicationOfSource(t),o||this.log.info("waiting for pending publication promise timed out",{source:t})),o&&o.track)if(t===ks.Source.ScreenShare){const e=[this.unpublishTrack(o.track)],t=this.getTrackPublication(ks.Source.ScreenShareAudio);t&&t.track&&e.push(this.unpublishTrack(t.track)),o=j(yield Promise.all(e),1)[0]}else yield o.mute();return o}))}enableCameraAndMicrophone(){return tr(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(ks.Source.Camera)&&!this.pendingPublishing.has(ks.Source.Microphone)){this.pendingPublishing.add(ks.Source.Camera),this.pendingPublishing.add(ks.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(ks.Source.Camera),this.pendingPublishing.delete(ks.Source.Microphone)}}}))}createTracks(t){return tr(this,void 0,void 0,(function*(){var n,i;null!=t||(t={});const r=is(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 Nl(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return t.map((t=>(co(t)&&(this.microphoneError=void 0,t.setAudioContext(this.audioContext),t.source=ks.Source.Microphone,this.emit(e.ParticipantEvent.AudioStreamAcquired)),lo(t)&&(this.cameraError=void 0,t.source=ks.Source.Camera),t)))}catch(e){throw e instanceof Error&&(t.audio&&(this.microphoneError=e),t.video&&(this.cameraError=e)),e}}))}createScreenTracks(t){return tr(this,void 0,void 0,(function*(){if(void 0===t&&(t={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new La("getDisplayMedia not supported");void 0!==t.resolution||Ns()||(t.resolution=ns.h1080fps30.resolution);const n=ls(t),i=yield navigator.mediaDevices.getDisplayMedia(n),r=i.getVideoTracks();if(0===r.length)throw new Ua("no video track found");const a=new hd(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=ks.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 Zc(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});t.source=ks.Source.ScreenShareAudio,s.push(t)}return s}))}publishTrack(e,t){return tr(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 tr(this,arguments,void 0,(function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return function*(){var a,s,o,c;let d,l;if(ho(e)&&e.setAudioContext(n.audioContext),yield null===(a=n.reconnectFuture)||void 0===a?void 0:a.promise,n.republishPromise&&!i&&(yield n.republishPromise),oo(e)&&n.pendingPublishPromises.has(e)&&(yield n.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)d=e.getConstraints();else{let t;switch(d=e.constraints,e.source){case ks.Source.Microphone:t="audioinput";break;case ks.Source.Camera:t="videoinput"}t&&n.activeDeviceMap.has(t)&&(d=Object.assign(Object.assign({},d),{deviceId:n.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new Zc(e,d,!0,n.audioContext,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;case"video":e=new hd(e,d,!0,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;default:throw new Ua("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});if(n.trackPublications.forEach((t=>{t.track&&t.track===e&&(l=t)})),l)return n.log.warn("track has already been published, skipping",ps(l)),l;const u=Object.assign(Object.assign({},n.roomOptions.publishDefaults),t),h="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,p=null!==(s=u.forceStereo)&&void 0!==s?s:h;p&&(void 0===u.dtx&&n.log.debug("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",ps(e)),void 0===u.red&&n.log.debug("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(o=u.dtx)&&void 0!==o||(u.dtx=!1),null!==(c=u.red)&&void 0!==c||(u.red=!1)),!function(){const e=Ta(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&Hs(e.osVersion,t)>=0)||"Safari"===e.name&&Hs(e.version,t)>=0}()&&n.roomOptions.e2ee&&(n.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2"),u.simulcast=!1),u.source&&(e.source=u.source);const m=new Promise(((t,i)=>tr(n,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==mc.CONNECTED){this.log.debug("deferring track publication until signal is connected",{track:ps(e)});let n=!1;const r=setTimeout((()=>{n=!0,e.stop(),i(new qa("publishing rejected as engine not connected within timeout",408))}),15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(r),n)return;const a=yield this.publish(e,u,p);t(a)}else try{const n=yield this.publish(e,u,p);t(n)}catch(e){i(e)}}catch(e){i(e)}}))));n.pendingPublishPromises.set(e,m);try{return yield m}catch(a){if(!r&&a instanceof ja)return n.log.warn("negotiation due to track publish failed, retrying after reconnect",{error:a}),n.pendingPublishPromises.delete(e),yield n.waitForNextEngineRestart(),yield n.publishOrRepublishTrack(e,t,i,!0);throw a}finally{n.pendingPublishPromises.delete(e)}}()}))}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new eo),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",ps(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 ks.Source.Camera;case tt.MICROPHONE:return ks.Source.Microphone;case tt.SCREEN_SHARE:return ks.Source.ScreenShare;case tt.SCREEN_SHARE_AUDIO:return ks.Source.ScreenShareAudio;default:return ks.Source.Unknown}}(e))).includes(e.source))||(this.log.warn("insufficient permissions to publish",ps(e)),!1)}publish(t,n,i){return tr(this,void 0,void 0,(function*(){var r,a,s,o,c,d,l,u,h,p;if(!this.hasPermissionsToPublish(t))throw new qa("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((e=>oo(t)&&e.source===t.source))&&t.source!==ks.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(t.source),ps(t)),n.stopMicTrackOnMute&&co(t)&&(t.stopOnMute=!0),t.source===ks.Source.ScreenShare&&Ms()&&(n.simulcast=!1),"av1"!==n.videoCodec||ws()||(n.videoCodec=void 0),"vp9"!==n.videoCodec||Rs()||(n.videoCodec=void 0),void 0===n.videoCodec&&(n.videoCodec=jc),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((e=>n.videoCodec===us(e.mime)))||(n.videoCodec=us(this.enabledPublishVideoCodecs[0].mime)));const m=n.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 g=[],v=!(null===(r=n.dtx)||void 0===r||r),f=t.getSourceTrackSettings();f.autoGainControl&&g.push(ct.TF_AUTO_GAIN_CONTROL),f.echoCancellation&&g.push(ct.TF_ECHO_CANCELLATION),f.noiseSuppression&&g.push(ct.TF_NOISE_SUPPRESSION),f.channelCount&&f.channelCount>1&&g.push(ct.TF_STEREO),v&&g.push(ct.TF_NO_DTX),ho(t)&&t.hasPreConnectBuffer&&g.push(ct.TF_PRECONNECT_BUFFER);const k=this.normalizeRequestedPacketTrailerOptions(t,n),y=new xn({cid:t.mediaStreamTrack.id,name:n.name,type:ks.kindToProto(t.kind),muted:t.isMuted,source:ks.sourceToProto(t.source),disableDtx:v,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(a=n.red)||void 0===a||a),stream:null==n?void 0:n.stream,backupCodecPolicy:null==n?void 0:n.backupCodecPolicy,audioFeatures:g,packetTrailerFeatures:k});let b;if(t.kind===ks.Kind.Video){let e;try{e=yield t.waitForDimensions()}catch(n){const i=null!==(o=null===(s=this.roomOptions.videoCaptureDefaults)||void 0===s?void 0:s.resolution)&&void 0!==o?o:es.h720.resolution;e={width:i.width,height:i.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},ps(t)),{dims:e}))}y.width=e.width,y.height=e.height,uo(t)&&(Ps(m)&&(t.source===ks.Source.ScreenShare&&(n.scalabilityMode="L1T3","contentHint"in t.mediaStreamTrack&&(t.mediaStreamTrack.contentHint="motion",this.log.debug("forcing contentHint to motion for screenshare with SVC codecs",ps(t)))),n.scalabilityMode=null!==(c=n.scalabilityMode)&&void 0!==c?c:"L3T3_KEY"),y.simulcastCodecs=[new Nn({codec:m,cid:t.mediaStreamTrack.id})],!0===n.backupCodec&&(n.backupCodec={codec:jc}),n.backupCodec&&m!==n.backupCodec.codec&&y.encryption===ft.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),y.simulcastCodecs.push(new Nn({codec:n.backupCodec.codec,cid:""})))),b=sd(t.source===ks.Source.ScreenShare,y.width,y.height,n),y.layers=gd(y.width,y.height,b,Ps(n.videoCodec))}else t.kind===ks.Kind.Audio&&(b=[{maxBitrate:null===(d=n.audioPreset)||void 0===d?void 0:d.maxBitrate,priority:null!==(u=null===(l=n.audioPreset)||void 0===l?void 0:l.priority)&&void 0!==u?u:"high",networkPriority:null!==(p=null===(h=n.audioPreset)||void 0===h?void 0:h.priority)&&void 0!==p?p:"high"}]);if(!this.engine||this.engine.isClosed)throw new Ba("cannot publish track when not connected");const T=()=>tr(this,void 0,void 0,(function*(){var i,r,a;if(!this.engine.pcManager)throw new Ba("pcManager is not ready");if(t.sender=yield this.engine.createSender(t,n,b),uo(t)&&(t.publishOptions=n),this.emit(e.ParticipantEvent.LocalSenderCreated,t.sender,t),uo(t)&&(null!==(i=n.degradationPreference)&&void 0!==i||(n.degradationPreference=function(e){return e.source===ks.Source.ScreenShare||e.constraints.height&&no(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(t)),t.setDegradationPreference(n.degradationPreference)),b)if(Ms()&&t.kind===ks.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=b[0])||void 0===r?void 0:r.maxBitrate)?b[0].maxBitrate/1e3:0})}else t.codec&&Ps(t.codec)&&(null===(a=b[0])||void 0===a?void 0:a.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:y.cid,codec:t.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()}));let S;const E=new Promise(((e,n)=>tr(this,void 0,void 0,(function*(){var i;try{S=yield this.engine.addTrack(y),e(S)}catch(e){if(t.sender&&(null===(i=this.engine.pcManager)||void 0===i?void 0:i.publisher)){try{this.engine.pcManager.publisher.removeTrack(t.sender)}catch(e){this.log.error(e)}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({},ps(t)),{error:e}))}))}n(e)}}))));if(this.enabledPublishVideoCodecs.length>0&&0===k.length){const e=yield Promise.all([E,T()]);S=e[0]}else{let e;if(S=yield E,S.codecs.forEach((t=>{void 0===e&&(e=t.mimeType)})),e&&t.kind===ks.Kind.Video){const i=us(e);i!==m&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign({},ps(t)),{codec:i})),n.videoCodec=i,b=sd(t.source===ks.Source.ScreenShare,y.width,y.height,n))}yield T()}const C=new Al(t.kind,S,t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(C.on(e.TrackEvent.CpuConstrained,(e=>this.onTrackCpuConstrained(e,C))),C.options=n,t.sid=S.sid,uo(t)&&(t.publishOptions=n,y.width&&y.height&&(t.lastEncodedDimensions={width:y.width,height:y.height})),this.log.debug("publishing ".concat(t.kind," with encodings"),{encodings:b,trackInfo:S}),uo(t)?t.startMonitor(this.engine.client):ho(t)&&t.startMonitor(),this.addTrackPublication(C),this.emit(e.ParticipantEvent.LocalTrackPublished,C),ho(t)&&S.audioFeatures.includes(ct.TF_PRECONNECT_BUFFER)){const n=t.getPreConnectBuffer(),i=t.getPreConnectBufferMimeType();if(this.on(e.ParticipantEvent.LocalTrackSubscribed,(e=>{if(e.trackSid===S.sid){if(!t.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed");this.log.debug("finished recording preconnect buffer",ps(t)),t.stopPreConnectBuffer()}})),n){const e=new Promise(((e,r)=>tr(this,void 0,void 0,(function*(){var a,s,o,c,d,l;try{this.log.debug("waiting for agent",ps(t));const m=setTimeout((()=>{r(new Error("agent not active within 10 seconds"))}),1e4),g=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug("sending preconnect buffer",ps(t));const v=yield this.streamBytes({name:"preconnect-buffer",mimeType:i,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[g.identity],attributes:{trackId:C.trackSid,sampleRate:String(null!==(d=f.sampleRate)&&void 0!==d?d:"48000"),channels:String(null!==(l=f.channelCount)&&void 0!==l?l:"1")}});try{for(var u,h=!0,p=ar(n);!(a=(u=yield p.next()).done);h=!0){c=u.value,h=!1;const e=c;yield v.write(e)}}catch(e){s={error:e}}finally{try{h||a||!(o=p.return)||(yield o.call(p))}finally{if(s)throw s.error}}yield v.close(),e()}catch(e){r(e)}}))));e.then((()=>{this.log.debug("preconnect buffer sent successfully",ps(t))})).catch((e=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign({},ps(t)),{error:e}))}))}}return C}))}canPublishPacketTrailer(){return!!(this.roomOptions.e2ee||this.roomOptions.encryption||Uo(this.roomOptions.packetTrailer))}normalizeRequestedPacketTrailerOptions(e,t){if(e.kind!==ks.Kind.Video||!Fo(t.packetTrailer))return t.packetTrailer=void 0,[];if(!this.canPublishPacketTrailer())return this.log.warn("packet trailer transform not supported; not advertising features",Object.assign(Object.assign({},this.logContext),ps(e))),t.packetTrailer=void 0,[];const n=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}(t.packetTrailer);return t.packetTrailer=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}(n),n}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return tr(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 Ua("track is not published");if(!uo(e))throw new Ua("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=od(e,t,a);if(!s)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",ps(e));const o=e.addSimulcastTrack(t,s);if(!o)return;const c=this.normalizeRequestedPacketTrailerOptions(e,a),d=new xn({cid:o.mediaStreamTrack.id,type:ks.kindToProto(e.kind),muted:e.isMuted,source:ks.sourceToProto(e.source),sid:e.sid,packetTrailerFeatures:c,simulcastCodecs:[{codec:a.videoCodec,cid:o.mediaStreamTrack.id}]});if(d.layers=gd(d.width,d.height,s),!this.engine||this.engine.isClosed)throw new Ba("cannot publish track when not connected");const l=(yield Promise.all([this.engine.addTrack(d),(()=>tr(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,n){return tr(this,void 0,void 0,(function*(){var i,r;if(oo(t)){const e=this.pendingPublishPromises.get(t);e&&(this.log.debug("awaiting publish promise before attempting to unpublish",ps(t)),yield e)}const a=this.getPublicationForTrack(t),s=a?ps(a):void 0;if(this.log.info("unpublishing track",s),!a||!a.track)return void this.log.warn("track was not unpublished because no publication was found",s);(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===n&&(n=null===(r=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===r||r),n?t.stop():t.stopMonitor();let o=!1;const c=t.sender;if(t.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<zc.FAILED&&c)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===c&&(e.direction="inactive",o=!0);try{o=this.engine.removeTrack(c)}catch(e){this.log.warn(e),o=!0}if(uo(t)){for(const e of t.simulcastCodecs){const t=j(e,2)[1];if(t.sender){try{o=this.engine.removeTrack(t.sender)}catch(e){this.log.warn(e),o=!0}t.sender=void 0}}t.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign({},s),{error:e}))}switch(this.trackPublications.delete(a.trackSid),a.kind){case ks.Kind.Audio:this.audioTrackPublications.delete(a.trackSid);break;case ks.Kind.Video:this.videoTrackPublications.delete(a.trackSid)}return this.emit(e.ParticipantEvent.LocalTrackUnpublished,a),a.setTrack(void 0),o&&(yield this.engine.negotiate()),a}))}unpublishTracks(e){return tr(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>!!e))}))}republishAllTracks(e){return tr(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 ka(((i,r)=>tr(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=>tr(this,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),!n||t.isMuted||t.source===ks.Source.ScreenShare||t.source===ks.Source.ScreenShareAudio||!ho(t)&&!uo(t)||t.isUserProvided||(this.log.debug("restarting existing track",{track:e.trackSid}),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))))),i()}catch(e){e instanceof Error?r(e):r(new Error(String(e)))}finally{this.republishPromise=void 0}})))),yield t.republishPromise}()}))}publishData(e){return tr(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?Td.RELIABLE:Td.LOSSY,r=n.reliable?wt.RELIABLE:wt.LOSSY,a=n.destinationIdentities,s=n.topic;let o=new Mt({participantIdentity:t.identity,payload:e,destinationIdentities:a,topic:s});const c=new Ct({kind:r,value:{case:"user",value:o}});yield t.engine.sendDataPacket(c,i)}()}))}publishDtmf(e,t){return tr(this,void 0,void 0,(function*(){const n=new Ct({kind:wt.RELIABLE,value:{case:"sipDtmf",value:new _t({code:e,digit:t})}});yield this.engine.sendDataPacket(n,Td.RELIABLE)}))}sendChatMessage(t,n){return tr(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 Ct({value:{case:"chatMessage",value:new Nt(Object.assign(Object.assign({},i),{timestamp:_.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,Td.RELIABLE),this.emit(e.ParticipantEvent.ChatMessage,i),i}))}editChatMessage(t,n){return tr(this,void 0,void 0,(function*(){const i=Object.assign(Object.assign({},n),{message:t,editTimestamp:Date.now()}),r=new Ct({value:{case:"chatMessage",value:new Nt(Object.assign(Object.assign({},i),{timestamp:_.parse(i.timestamp),editTimestamp:_.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,Td.RELIABLE),this.emit(e.ParticipantEvent.ChatMessage,i),i}))}sendText(e,t){return tr(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)}))}streamText(e){return tr(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamText(e)}))}sendFile(e,t){return tr(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)}))}streamBytes(e){return tr(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)}))}performRpc(e){return this.rpcClientManager.performRpc(e).then((e=>{let t=j(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({},ps(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 eo),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach((n=>{const i=n.track;i&&(e instanceof MediaStreamTrack?(ho(i)||uo(i))&&i.mediaStreamTrack===e&&(t=n):e===i&&(t=n))})),t}waitForPendingPublicationOfSource(e){return tr(this,void 0,void 0,(function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find((t=>j(t,1)[0].source===e));if(t)return t[1];yield Ss(20)}}))}publishDataTrack(e){return tr(this,void 0,void 0,(function*(){const t=new kl(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t}))}}class ql extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}}class Vl 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 tr(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 ql("The operation was aborted.",t.reason);const i=new eo(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 ql("The operation was aborted.",t.reason))};t.addEventListener("abort",e,{once:!0}),i.promise.finally((()=>{t.removeEventListener("abort",e)}))}return i.promise}))}}class Hl extends Ol{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 Yn({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Bt({participantSid:"",trackSids:[this.trackSid]})]});this.emit(e.TrackEvent.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?Ol.SubscriptionStatus.Unsubscribed:super.isSubscribed?Ol.SubscriptionStatus.Subscribed:Ol.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Ol.PermissionStatus.Allowed:Ol.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||(go(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&go(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 go(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=new $n({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===ks.Kind.Video){let n=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(n){gs(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&&gs(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 Wl extends Bl{static fromParticipantInfo(e,t,n,i){return new Wl(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind,t.dataTracks.map((e=>{const n=dc.from(e);return new Qd(n,i,{publisherIdentity:t.identity})})),t.clientProtocol)}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;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 Vl(c.map((e=>[e.info.name,e]))),this.volumeMap=new Map,this.clientProtocol=d}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),ps(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]:ks.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]:ks.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),ps(o))),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,n);let c;return c="video"===t.kind?new Ho(t,n,r,a):new _l(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)&&po(c)&&co(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=ks.kindFromProto(e.type);if(!n)return;a=new Hl(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!==ks.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:ps(s),newTrack:ps(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),ps(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 ks.Kind.Audio:this.audioTrackPublications.delete(t);break;case ks.Kind.Video:this.videoTrackPublications.delete(t)}n&&this.emit(e.ParticipantEvent.TrackUnpublished,i)}setAudioOutput(e){return tr(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((n=>{var i;co(n.track)&&po(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=j(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,(Fl=e.ConnectionState||(e.ConnectionState={})).Disconnected="disconnected",Fl.Connecting="connecting",Fl.Connected="connected",Fl.Reconnecting="reconnecting",Fl.SignalReconnecting="signalReconnecting";class Kl extends cr.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(t){var n,i,a,s,o,c,d;if(super(),n=this,this.state=e.ConnectionState.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new r,this.isVideoPlaybackBlocked=!1,this.log=Ji,this.bufferedEvents=[],this.isResuming=!1,this.connect=(t,n,i)=>tr(this,void 0,void 0,(function*(){var r;if(!Ds())throw Us()?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())!==yo(t)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Fs(new URL(t))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new wd(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)=>tr(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 Yo.getInstance().getBackOffPromise(t),u.signal.aborted)throw xa.cancelled("Connection attempt aborted");yield this.attemptConnection(null!=c?c:t,n,i,u),this.abortController=void 0,r()}catch(n){if(this.regionUrlProvider&&n instanceof xa&&n.reason!==e.ConnectionErrorReason.Cancelled&&n.reason!==e.ConnectionErrorReason.NotAllowed){let i=null;try{this.log.debug("Fetching next region"),i=yield this.regionUrlProvider.getNextBestRegionUrl(null===(d=this.abortController)||void 0===d?void 0:d.signal)}catch(t){if(t instanceof xa&&(401===t.status||t.reason===e.ConnectionErrorReason.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void o(t)}[e.ConnectionErrorReason.InternalError,e.ConnectionErrorReason.ServerUnreachable,e.ConnectionErrorReason.Timeout].includes(n.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Yo.getInstance().addFailedConnectionAttempt(t)),i&&!(null===(l=this.abortController)||void 0===l?void 0:l.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(n.message,". Retrying with another region: ").concat(i)),this.recreateEngine(!0),yield s(r,o,i)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,ro(n)),o(n))}else{let e=at.UNKNOWN_REASON;n instanceof xa&&(e=ro(n)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),o(n)}}})),o=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new eo(((e,t)=>{s(e,t,o)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,n,i,r,a)=>tr(this,void 0,void 0,(function*(){const s=yield n.join(e,t,{autoSubscribe:i.autoSubscribe,adaptiveStream:"object"==typeof r.adaptiveStream||r.adaptiveStream,clientInfoCapabilities:Uo(r.packetTrailer)||this.e2eeManager?[Wt.CAP_PACKET_TRAILER]:void 0,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 Fa("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(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",{error:e})}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(t,n,i,r)=>tr(this,void 0,void 0,(function*(){var a,s;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===(s=this.regionUrlProvider)||void 0===s?void 0:s.isCloud())&&this.engine.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Kc),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=yield this.connectSignal(t,n,this.engine,this.connOptions,this.options,r);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();const t=r.signal.aborted?xa.cancelled("Signal connection aborted"):xa.serverUnreachable("could not establish signal connection");throw e instanceof Error&&(t.message="".concat(t.message,": ").concat(e.message)),e instanceof xa&&(t.reason=e.reason,t.status=e.status),this.log.debug("error trying to establish signal connection",{error:e}),t}if(r.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),xa.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,r)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}Ls()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Ls()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Connected),Yo.getInstance().resetFailedConnectionAttempts(t),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()})),this.disconnect=function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return tr(n,[...i],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,xa.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=()=>tr(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting"),yield this.disconnect()})),this.startAudio=()=>tr(this,void 0,void 0,(function*(){const t=[],n=Ta();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=$s();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=>(e.muted=!1,e.play())))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}})),this.startVideo=()=>tr(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=>tr(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(e){this.log.error("error trying to re-publish tracks after reconnection",{error:e})}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",{region:t.serverRegion})}catch(e){return}this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()})),this.handleParticipantUpdates=e=>{var t;for(const n of e){if(n.identity===this.localParticipant.identity){this.localParticipant.updateInfo(n);continue}""===n.identity&&(n.identity=null!==(t=this.sidToIdentity.get(n.sid))&&void 0!==t?t:"");let e=this.remoteParticipants.get(n.identity);n.state===mt.DISCONNECTED?this.handleParticipantDisconnected(n.identity,e):this.getOrCreateParticipant(n.identity,n)}const n=new Map(e.filter((e=>e.identity!==this.localParticipant.identity)).map((e=>[e.identity,e.dataTracks.map((e=>dc.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=ks.streamStateFromProto(t.state);i.track.setStreamState(r),r!==i.track.streamState&&(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=>{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,El.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=()=>tr(this,void 0,void 0,(function*(){var t;"iOS"!==(null===(t=Ta())||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.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=>tr(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),ho(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=ds(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=>tr(this,void 0,void 0,(function*(){const n=yield t.getDeviceId(!1),i=ds(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({},Wc),t),this.log=Qi(null!==(i=this.options.loggerName)&&void 0!==i?i:e.LoggerNames.Room,(()=>this.logContext)),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Vc),null==t?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Hc),null==t?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},qc),null==t?void 0:t.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Dd,this.outgoingDataStreamManager=new Ad(this.engine,this.log),this.incomingDataTrackManager=new cl({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 Sl({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.sendLossyBytes(n,Td.DATA_TRACK_LOSSY,"wait").finally((()=>this.outgoingDataTrackManager.handlePacketSendComplete(t)))})),this.registerRpcDataStreamHandler(),this.rpcClientManager=new Dl(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,Td.RELIABLE)})),this.rpcServerManager=new Ml(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,Td.RELIABLE)})),this.disconnectLock=new r,this.localParticipant=new jl("","",this.engine,this.options,this.outgoingDataStreamManager,this.outgoingDataTrackManager,this.rpcClientManager,this.rpcServerManager),this.setupPacketTrailer(),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager(null!==(a=this.e2eeManager)&&void 0!==a?a:null),this.outgoingDataTrackManager.updateE2eeManager(null!==(s=this.e2eeManager)&&void 0!==s?s:null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",no(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",no(this.options.audioCaptureDefaults.deviceId)),(null===(o=this.options.audioOutput)||void 0===o?void 0:o.deviceId)&&this.switchActiveDevice("audiooutput",no(this.options.audioOutput.deviceId)).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message)))),Ls()){const e=new AbortController;let t;if(Kl.cleanupRegistry){const n=new WeakRef(this);t=()=>{const e=n.deref();e&&e.handleDeviceChange()},Kl.cleanupRegistry.register(this,(()=>{e.abort()}))}else t=this.handleDeviceChange;null===(d=null===(c=navigator.mediaDevices)||void 0===c?void 0:c.addEventListener)||void 0===d||d.call(c,"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 tr(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 Jo(r,i),this.e2eeManager.on(e.EncryptionEvent.ParticipantEncryptionStatusChanged,((t,n)=>{vo(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))}setupPacketTrailer(){this.packetTrailerManager=new Qo(this.options.packetTrailer),this.packetTrailerManager.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?ka.resolve(""):this.roomInfo&&""!==this.roomInfo.sid?ka.resolve(this.roomInfo.sid):new ka(((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 Ba("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 Sd(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.emitBufferedEvents(),this.setAndEmitConnectionState(e.ConnectionState.Connected)&&this.emit(e.RoomEvent.Reconnected)})).on(e.EngineEvent.SignalResumed,(()=>{this.bufferedEvents=[],(this.state===e.ConnectionState.Reconnecting||this.isResuming)&&this.sendSyncState()})).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=j(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(e){throw e}})).on(e.EngineEvent.Joined,(e=>{const t=new Map(e.otherParticipants.map((e=>[e.identity,e.dataTracks.map((e=>dc.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:Cd})})),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=>tr(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 Zo.getInstance().getDevices(e,t)}prepareConnection(t,n){return tr(this,void 0,void 0,(function*(){if(this.state===e.ConnectionState.Disconnected){this.log.debug("prepareConnection to ".concat(t));try{if(Fs(new URL(t))&&n){this.regionUrlProvider=new wd(t,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===e.ConnectionState.Disconnected&&(this.regionUrl=i,yield fetch(io(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i)))}else yield fetch(io(t),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",{error:e})}}}))}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return tr(this,void 0,void 0,(function*(){let n,i=()=>tr(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 Ci({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":n=new Ci({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":n=new Ci({scenario:{case:"serverLeave",value:!0}});break;case"migration":n=new Ci({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=()=>tr(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),n=new Ci({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>tr(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),n=new Ci({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 Ci({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),i=()=>tr(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new ni({reason:at.CLIENT_INITIATED,action:ii.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");n=new Ci({scenario:{case:"subscriberBandwidth",value:so(t)}});break;case"leave-full-reconnect":n=new Ci({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,n){return tr(this,arguments,void 0,(function(t,n){var i=this;let r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var a,s,o,c,d,l,u;let h=!0,p=!1;const m=r?{exact:n}:n;if("audioinput"===t){p=0===i.localParticipant.audioTrackPublications.size;const e=null!==(a=i.getActiveDevice(t))&&void 0!==a?a:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.audioTrackPublications.values()).filter((e=>e.source===ks.Source.Microphone));try{h=(yield Promise.all(n.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(t){throw i.options.audioCaptureDefaults.deviceId=e,t}const r=n.some((e=>{var t,n;return null!==(n=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==n&&n}));h&&r&&(p=!0)}else if("videoinput"===t){p=0===i.localParticipant.videoTrackPublications.size;const e=null!==(s=i.getActiveDevice(t))&&void 0!==s?s:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter((e=>e.source===ks.Source.Camera));try{h=(yield Promise.all(n.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(t){throw i.options.videoCaptureDefaults.deviceId=e,t}const r=n.some((e=>{var t,n;return null!==(n=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==n&&n}));h&&r&&(p=!0)}else if("audiooutput"===t){if(p=!0,!Is()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");i.options.webAudioMix&&(n=null!==(o=yield Zo.getInstance().normalizeDeviceId("audiooutput",n))&&void 0!==o?o:""),null!==(c=(u=i.options).audioOutput)&&void 0!==c||(u.audioOutput={});const e=null!==(d=i.getActiveDevice(t))&&void 0!==d?d:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=n;try{i.options.webAudioMix&&(null===(l=i.audioContext)||void 0===l||l.setSinkId(n)),yield Promise.all(Array.from(i.remoteParticipants.values()).map((e=>e.setAudioOutput({deviceId:n}))))}catch(t){throw i.options.audioOutput.deviceId=e,t}}return p&&(i.localParticipant.activeDeviceMap.set(t,n),i.emit(e.RoomEvent.ActiveDeviceChanged,t,n)),h}()}))}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){if(this.state===e.ConnectionState.Connecting||this.state===e.ConnectionState.Reconnecting){const r=()=>{this.log.debug("deferring on track for later",{mediaTrackId:t.id,mediaStreamId:n.id,tracksInStream:n.getTracks().map((e=>e.id))}),this.onTrackAdded(t,n,i),a()},a=()=>{this.off(e.RoomEvent.Reconnected,r),this.off(e.RoomEvent.Connected,r),this.off(e.RoomEvent.Disconnected,a)};return this.once(e.RoomEvent.Reconnected,r),this.once(e.RoomEvent.Connected,r),void this.once(e.RoomEvent.Disconnected,a)}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 r=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(n.id),a=r[0];let s=r[1],o=t.id;if(s&&s.startsWith("TR")&&(o=s),a===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant");const c=Array.from(this.remoteParticipants.values()).find((e=>e.sid===a));if(!c)return void(a.startsWith("PA")&&this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(a)));if(!o.startsWith("TR")){const e=this.engine.getTrackIdForReceiver(i);if(!e)return void this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(a));o=e}let d;o.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(a,", streamId: ").concat(s,", trackId: ").concat(o),{remoteParticipantID:a,streamId:s,trackId:o}),this.options.adaptiveStream&&(d="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});const l=c.addSubscribedMediaTrack(t,o,n,i,d);(null==l?void 0:l.isEncrypted)&&!this.e2eeManager&&this.emit(e.RoomEvent.EncryptionError,new Error("Encrypted ".concat(l.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}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),Ls()&&(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){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),n.setDisconnected(),this.rpcClientManager.handleParticipantDisconnected(n.identity))}selectDefaultDevices(){return tr(this,void 0,void 0,(function*(){var t,n,i;const r=Zo.getInstance().previousDevices,a=yield Zo.getInstance().getDevices(void 0,!1),s=Ta();if("Chrome"===(null==s?void 0:s.name)&&"iOS"!==s.os)for(let t of a){const n=r.find((e=>e.deviceId===t.deviceId));n&&""!==n.label&&n.kind===t.kind&&n.label!==t.label&&"default"===this.getActiveDevice(t.kind)&&this.emit(e.RoomEvent.ActiveDeviceChanged,t.kind,t.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let e of o){const s=cs(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&&!As()||"videoinput"===e||!(c.length>0)||c.find((t=>t.deviceId===this.getActiveDevice(e)))||"audiooutput"===e&&As()||(yield this.switchActiveDevice(e,c[0].deviceId))}}))}acquireAudioContext(){return tr(this,void 0,void 0,(function*(){var t,n;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=os())&&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(),Ss(200)])}catch(e){this.log.warn("Could not resume audio context",{error:e})}const i="running"===(null===(n=this.audioContext)||void 0===n?void 0:n.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,i))}))}createParticipant(e,t){var n;let i;return i=t?Wl.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):new Wl(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===ks.Kind.Audio?(t.on(e.TrackEvent.AudioPlaybackStarted,this.handleAudioPlaybackStarted),t.on(e.TrackEvent.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):t.kind===ks.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.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&&mo(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(Cl,((e,t)=>tr(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(wl,((e,t)=>tr(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)}()}))))}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Ka.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.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,at.STATE_MISMATCH)))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&Ka.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.emit(e.RoomEvent.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach((e=>{let t=j(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 tr(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:_.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 Al(ks.Kind.Video,new yt({source:tt.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:et.AUDIO,name:"video-dummy"}),new hd(s.useRealTracks&&(null===(n=window.navigator.mediaDevices)||void 0===n?void 0:n.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Zs(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 Al(ks.Kind.Audio,new yt({source:tt.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:et.AUDIO}),new Zc(s.useRealTracks&&(null===(r=navigator.mediaDevices)||void 0===r?void 0:r.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:$s(),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:_.parse(Date.now())});const n=this.getOrCreateParticipant(t.identity,t);if(o.video){const i=Zs(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=$s(),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=zl(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 zl(e){return e.map((e=>{if(e)return Array.isArray(e)?zl(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e}))}Kl.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&"undefined"!=typeof WeakRef&&new FinalizationRegistry((e=>{e()}));var Jl,Gl=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,(Jl=e.CheckStatus||(e.CheckStatus={}))[Jl.IDLE=0]="IDLE",Jl[Jl.RUNNING=1]="RUNNING",Jl[Jl.SKIPPED=2]="SKIPPED",Jl[Jl.SUCCESS=3]="SUCCESS",Jl[Jl.FAILED=4]="FAILED";class Ql extends cr.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 Kl(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(t){return tr(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(e){e instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(e.message):this.appendError(e.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 tr(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 tr(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 tr(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 Ss(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 Yl extends Ql{get description(){return"Cloud regions"}perform(){return tr(this,void 0,void 0,(function*(){const e=new wd(this.url,this.token);if(!e.isCloud())return void this.skip();const t=[],n=new Set;for(let i=0;i<3;i++){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 tr(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 Xl=1e4;class Zl extends Ql{get description(){return"Connection via UDP vs TCP"}perform(){return tr(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 tr(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((()=>tr(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,Xl))),clearInterval(c),a.stop(),t.remove(),yield this.disconnect(),o}))}}class $l extends Ql{get description(){return"Can publish audio"}perform(){return tr(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),n=yield Ll();if(yield ss(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 eu extends Ql{get description(){return"Can publish video"}perform(){return tr(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),n=yield xl();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 tr(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 tu extends Ql{get description(){return"Resuming connection after interruption"}perform(){return tr(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 nu extends Ql{get description(){return"Can connect via TURN"}perform(){return tr(this,void 0,void 0,(function*(){var e,t,n;Fs(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=null!==(e=yield new wd(this.url,this.token).getNextBestRegionUrl())&&void 0!==e?e:this.url);const i=new gc,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 e of r.iceServers)for(let t of e.urls)t.startsWith("turn:")?(s=!0,o=!0):t.startsWith("turns:")&&(s=!0,o=!0,a=!0),t.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 iu extends Ql{get description(){return"Establishing WebRTC connection"}perform(){return tr(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(),Ji.info("now the room is connected")}catch(e){throw this.appendWarning("ports need to be open on firewall in order to connect."),e}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 ru extends Ql{get description(){return"Connecting to signal connection via WebSocket"}perform(){return tr(this,void 0,void 0,(function*(){var e,t,n;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let i,r=new gc;try{i=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(e){if(Fs(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(e.message,". Retrying with region fallback"));const t=new wd(this.url,this.token),n=yield t.getNextBestRegionUrl();n&&(i=yield r.join(n,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"))}}i?(this.appendMessage("Connected to server, version ".concat(i.serverVersion,".")),(null===(e=i.serverInfo)||void 0===e?void 0:e.edition)===qt.Cloud&&(null===(t=i.serverInfo)||void 0===t?void 0:t.region)&&this.appendMessage("LiveKit Cloud: ".concat(null===(n=i.serverInfo)||void 0===n?void 0:n.region))):this.appendError("Websocket connection could not be established"),yield r.close()}))}}class au extends cr.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 tr(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 tr(this,void 0,void 0,(function*(){return this.createAndRunCheck(ru)}))}checkWebRTC(){return tr(this,void 0,void 0,(function*(){return this.createAndRunCheck(iu)}))}checkTURN(){return tr(this,void 0,void 0,(function*(){return this.createAndRunCheck(nu)}))}checkReconnect(){return tr(this,void 0,void 0,(function*(){return this.createAndRunCheck(tu)}))}checkPublishAudio(){return tr(this,void 0,void 0,(function*(){return this.createAndRunCheck($l)}))}checkPublishVideo(){return tr(this,void 0,void 0,(function*(){return this.createAndRunCheck(eu)}))}checkConnectionProtocol(){return tr(this,void 0,void 0,(function*(){const e=yield this.createAndRunCheck(Zl);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e}))}checkCloudRegion(){return tr(this,void 0,void 0,(function*(){return this.createAndRunCheck(Yl)}))}}class su{}class ou{}new TextEncoder;const cu=new TextDecoder;function du(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:cu.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=cu.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 e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}(t)}catch(e){throw new TypeError("The input to be decoded is not correctly encoded.")}}class lu extends Error{constructor(e,t){var n;super(e,t),B(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor)}}B(lu,"code","ERR_JOSE_GENERIC");B(class extends lu{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}}),B(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),B(this,"claim",void 0),B(this,"reason",void 0),B(this,"payload",void 0),this.claim=n,this.reason=i,this.payload=t}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED");B(class extends lu{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}}),B(this,"code","ERR_JWT_EXPIRED"),B(this,"claim",void 0),B(this,"reason",void 0),B(this,"payload",void 0),this.claim=n,this.reason=i,this.payload=t}},"code","ERR_JWT_EXPIRED");B(class extends lu{constructor(){super(...arguments),B(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED");B(class extends lu{constructor(){super(...arguments),B(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED");B(class extends lu{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),B(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED");B(class extends lu{constructor(){super(...arguments),B(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID");B(class extends lu{constructor(){super(...arguments),B(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID");class uu extends lu{constructor(){super(...arguments),B(this,"code","ERR_JWT_INVALID")}}B(uu,"code","ERR_JWT_INVALID");B(class extends lu{constructor(){super(...arguments),B(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID");B(class extends lu{constructor(){super(...arguments),B(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID");B(class extends lu{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),B(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY");B(class extends lu{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),B(this,Symbol.asyncIterator,void 0),B(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");B(class extends lu{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),B(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT");B(class extends lu{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),B(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const hu=e=>"object"==typeof e&&null!==e;function pu(e){if("string"!=typeof e)throw new uu("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 uu("Only JWTs using Compact JWS serialization can be decoded");if(3!==i)throw new uu("Invalid JWT");if(!n)throw new uu("JWTs must contain a payload");let r,a;try{r=du(n)}catch(e){throw new uu("Failed to base64url decode the payload")}try{a=JSON.parse(cu.decode(r))}catch(e){throw new uu("Failed to parse the decoded payload as JSON")}if(!function(e){if(!hu(e)||"[object Object]"!==Object.prototype.toString.call(e))return!1;if(null===Object.getPrototypeOf(e))return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}(a))throw new uu("Invalid JWT Claims Set");return a}const mu=1e3;function gu(e){const t=pu(e);t.roomConfig;const n=er(t,["roomConfig"]);return Object.assign(Object.assign({},n),{roomConfig:t.roomConfig?In.fromJson(t.roomConfig,{ignoreUnknownFields:!0}):void 0})}class vu extends ou{constructor(){super(...arguments),this.cachedFetchOptions=null,this.cachedResponse=null,this.fetchMutex=new r}isSameAsCachedFetchOptions(e){if(!this.cachedFetchOptions)return!1;for(const t of Object.keys(this.cachedFetchOptions))switch(t){case"roomName":case"participantName":case"participantIdentity":case"participantMetadata":case"participantAttributes":case"agentName":case"agentMetadata":if(this.cachedFetchOptions[t]!==e[t])return!1;break;default:throw new Error("Options key ".concat(t," not being checked for equality!"))}return!0}shouldReturnCachedValueFromFetch(e){return!!this.cachedResponse&&(!!function(e){const t=gu(e.participantToken);if(!(null==t?void 0:t.nbf)||!(null==t?void 0:t.exp))return!0;const n=new Date,i=t.nbf*mu,r=new Date(i),a=t.exp*mu,s=new Date(a-6e4);return r<=n&&s>n}(this.cachedResponse)&&!!this.isSameAsCachedFetchOptions(e))}getCachedResponseJwtPayload(){return this.cachedResponse?gu(this.cachedResponse.participantToken):null}fetch(e,t){return tr(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 fu extends su{constructor(e){super(),this.literalOrFn=e}fetch(){return tr(this,void 0,void 0,(function*(){return"function"==typeof this.literalOrFn?this.literalOrFn():this.literalOrFn}))}}class ku extends vu{constructor(e){super(),this.customFn=e}update(e){return tr(this,void 0,void 0,(function*(){const t=this.customFn(e);let n;return n=t instanceof Promise?yield t:t,Bi.fromJson(n,{ignoreUnknownFields:!0})}))}}class yu extends vu{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;const r=new Fi;for(const a of Object.keys(e))switch(a){case"roomName":case"participantName":case"participantIdentity":case"participantMetadata":r[a]=e[a];break;case"participantAttributes":r.participantAttributes=null!==(t=e.participantAttributes)&&void 0!==t?t:{};break;case"agentName":r.roomConfig=null!==(n=r.roomConfig)&&void 0!==n?n:new In,0===r.roomConfig.agents.length&&r.roomConfig.agents.push(new sn),r.roomConfig.agents[0].agentName=e.agentName;break;case"agentMetadata":r.roomConfig=null!==(i=r.roomConfig)&&void 0!==i?i:new In,0===r.roomConfig.agents.length&&r.roomConfig.agents.push(new sn),r.roomConfig.agents[0].metadata=e.agentMetadata;break;default:throw new Error("Options key ".concat(a," not being included in forming request!"))}return r}update(e){return tr(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 Bi.fromJson(r,{ignoreUnknownFields:!0})}))}}class bu extends yu{constructor(e,t){const n=t.baseUrl,i=void 0===n?"https://cloud-api.livekit.io":n,r=er(t,["baseUrl"]);super("".concat(i,"/api/v2/sandbox/connection-details"),Object.assign(Object.assign({},r),{headers:{"X-Sandbox-ID":e}}))}}const Tu={literal:e=>new fu(e),custom:e=>new ku(e),endpoint(e){return new yu(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})},sandboxTokenServer(e){return new bu(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}};const Su=new Map([["obs virtual camera",{facingMode:"environment",confidence:"medium"}]]),Eu=new Map([["iphone",{facingMode:"environment",confidence:"medium"}],["ipad",{facingMode:"environment",confidence:"medium"}]]);function Cu(e){var t;const n=e.trim().toLowerCase();if(""!==n)return Su.has(n)?Su.get(n):null===(t=Array.from(Eu.entries()).find((e=>{let t=j(e,1)[0];return n.includes(t)})))||void 0===t?void 0:t[1]}const wu=Symbol.for("lk.serializer");function Ru(e){return Object.assign(Object.assign({},e),{symbol:wu})}const Pu={json:function(){return Ru({parse:e=>JSON.parse(e),serialize:e=>JSON.stringify(e)})},raw:function(){return Ru({parse:e=>e,serialize:e=>e})},custom:function(e){return Ru(e)}};e.BaseKeyProvider=No,e.CLIENT_PROTOCOL_DATA_STREAM_RPC=1,e.CLIENT_PROTOCOL_DEFAULT=0,e.Checker=Ql,e.ConnectionCheck=au,e.ConnectionError=xa,e.CriticalTimers=Ka,e.CryptorError=class extends Ra{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=wt,e.DataStreamError=Ha,e.DataTrackPacket=Zd,e.DefaultReconnectPolicy=$i,e.DeviceUnsupportedError=La,e.DisconnectReason=at,e.Encryption_Type=ft,e.ExternalE2EEKeyProvider=class extends No{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 tr(this,void 0,void 0,(function*(){const t="string"==typeof e?yield Mo(e):yield _o(e);this.onSetEncryptionKey(t)}))}},e.LivekitError=Ra,e.LivekitReasonedError=Pa,e.LocalAudioTrack=Zc,e.LocalDataTrack=kl,e.LocalParticipant=jl,e.LocalTrack=Xc,e.LocalTrackPublication=Al,e.LocalTrackRecorder=Yc,e.LocalVideoTrack=hd,e.Mutex=r,e.NegotiationError=ja,e.PacketTrailerManager=Qo,e.Participant=Bl,e.ParticipantKind=gt,e.PublishDataError=class extends Ra{constructor(e){super(14,null!=e?e:"unable to publish data"),this.name="PublishDataError"}},e.PublishTrackError=qa,e.RemoteAudioTrack=_l,e.RemoteDataTrack=Qd,e.RemoteParticipant=Wl,e.RemoteTrack=Vo,e.RemoteTrackPublication=Hl,e.RemoteVideoTrack=Ho,e.Room=Kl,e.RpcError=El,e.ScreenSharePresets=ns,e.SignalReconnectError=Wa,e.SignalRequestError=Va,e.SimulatedError=class extends Ra{constructor(){super(-1,arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Simulated failure"),this.name="simulated"}},e.SubscriptionError=ot,e.TokenSource=Tu,e.TokenSourceConfigurable=ou,e.TokenSourceFixed=su,e.Track=ks,e.TrackInvalidError=Ua,e.TrackPublication=Ol,e.TrackType=et,e.UnexpectedConnectionState=Ba,e.UnsupportedServer=Fa,e.VideoPreset=za,e.VideoPresets=es,e.VideoPresets43=ts,e.areTokenSourceFetchOptionsEqual=function(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":if(e[i]!==t[i])return!1;break;default:throw new Error("Options key ".concat(i," not being checked for equality!"))}return!0},e.asEncryptablePacket=Ao,e.attachToElement=ys,e.attributes=Gl,e.audioCodecs=Ja,e.clientProtocol=1,e.compareVersions=Hs,e.createAudioAnalyser=function(e,t){const n=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),i=os();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:()=>tr(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=Mo,e.createLocalAudioTrack=Ll,e.createLocalScreenTracks=function(e){return tr(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0!==e.resolution||Ns()||(e.resolution=ns.h1080fps30.resolution),void 0===navigator.mediaDevices.getDisplayMedia)throw new La("getDisplayMedia not supported");const t=ls(e),n=yield navigator.mediaDevices.getDisplayMedia(t),i=n.getVideoTracks();if(0===i.length)throw new Ua("no video track found");const r=new hd(i[0],void 0,!1);r.source=ks.Source.ScreenShare;const a=[r];if(n.getAudioTracks().length>0){const e=new Zc(n.getAudioTracks()[0],void 0,!1);e.source=ks.Source.ScreenShareAudio,a.push(e)}return a}))},e.createLocalTracks=Nl,e.createLocalVideoTrack=xl,e.decodeTokenPayload=gu,e.deriveKeys=function(e,t){return tr(this,void 0,void 0,(function*(){const n=Oo(e.algorithm.name,t.ratchetSalt),i=yield crypto.subtle.deriveKey(n,e,{name:So,length:t.keySize},!1,["encrypt","decrypt"]);return{material:e,encryptionKey:i}}))},e.detachTrack=bs,e.facingModeFromDeviceLabel=Cu,e.facingModeFromLocalTrack=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;const i=oo(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;Ji.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)){Ji.trace("Try to get facing mode from device label: (".concat(i.label,")"));const e=Cu(i.label);void 0!==e&&(a=e)}return a},e.getBrowser=Ta,e.getEmptyAudioStreamTrack=$s,e.getEmptyVideoStreamTrack=function(){return Ys||(Ys=Zs()),Ys.clone()},e.getLogger=Qi,e.importKey=function(e){return tr(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:So},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 Ja.includes(e)},e.isAudioTrack=co,e.isBackupCodec=Xa,e.isBackupVideoCodec=Ya,e.isBrowserSupported=Ds,e.isE2EESupported=Po,e.isInsertableStreamSupported=Do,e.isLocalParticipant=vo,e.isLocalTrack=oo,e.isRemoteParticipant=function(e){return!e.isLocal},e.isRemoteTrack=po,e.isScriptTransformSupported=Io,e.isSerializer=function(e){return"object"==typeof e&&null!==e&&"symbol"in e&&e.symbol===wu},e.isVideoCodec=to,e.isVideoFrame=function(e){return"type"in e},e.isVideoTrack=lo,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 tr(this,void 0,void 0,(function*(){const n=Oo(e.algorithm.name,t);return crypto.subtle.deriveBits(n,e,256)}))},e.serializers=Pu,e.setLogExtension=function(t,n){(n?[n]:Gi).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)zi.getLogger(t).setLevel(e);else for(const t of Gi)t.setLevel(e)},e.supportsAV1=ws,e.supportsAdaptiveStream=function(){return void 0!==typeof ResizeObserver&&void 0!==typeof IntersectionObserver},e.supportsAudioOutputSelection=function(){return Is()},e.supportsDynacast=function(){return Es()},e.supportsVP9=Rs,e.version=wa,e.videoCodecs=Qa,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