1!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},t=(new e.Error).stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0bfe4512-9b95-4483-85ef-88be2cb61fa3",e._sentryDebugIdIdentifier="sentry-dbid-0bfe4512-9b95-4483-85ef-88be2cb61fa3")}catch(e){}}();"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[6481],{53819:function(e,t,i){let n,r,a,s,o;i.d(t,{CB:function(){return eg},E8:function(){return c8},OE:function(){return sU},TQ:function(){return ef},dd:function(){return ev},du:function(){return c7},em:function(){return eX},fQ:function(){return ss},nC:function(){return iw},qs:function(){return aL},rl:function(){return c0},vN:function(){return eb}});var c,l,d,u,h,p,m,g,f,v,k,b,y,T,S,C,E,w,P,R,I,D,_,M,O,A,N,x,L,U,F,B,j,q,V,H,W,z,G,K,J,Q,Y,X,Z,$,ee,et,ei,en,er,ea,es,eo,ec,el,ed,eu,eh,ep,em,eg,ef,ev,ek,eb,ey,eT,eS,eC,eE,ew,eP,eR,eI,eD,e_,eM,eO,eA,eN,ex,eL,eU,eF,eB,ej,eq,eV,eH,eW,ez,eG,eK,eJ,eQ,eY,eX,eZ,e$=i(40257),e0=Object.defineProperty,e1=(e,t,i)=>t in e?e0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,e2=(e,t,i)=>e1(e,"symbol"!=typeof t?t+"":t,i);class e3{constructor(){e2(this,"_locking"),e2(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;let t=new Promise(t=>e=()=>{this._locks-=1,t()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function e4(e,t){if(!e)throw Error(t)}function e9(e){if("number"!=typeof e)throw Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw Error("invalid int 32: "+e)}function e6(e){if("number"!=typeof e)throw Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw Error("invalid uint 32: "+e)}function e8(e){if("number"!=typeof e)throw Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw Error("invalid float 32: "+e)}let e5=Symbol("@bufbuild/protobuf/enum-type");function e7(e,t,i,n){e[e5]=te(t,i.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function te(e,t,i){let n=Object.create(null),r=Object.create(null),a=[];for(let e of t){let t=tt(e);a.push(t),n[e.name]=t,r[e.no]=t}return{typeName:e,values:a,findName:e=>n[e],findNumber:e=>r[e]}}function tt(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class ti{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){let i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){let i=this.getType(),n=i.runtime.json,r=n.makeReadOptions(t);return n.readMessage(i,e,r,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(e){throw Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(i,t)}toBinary(e){let t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){let t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;return JSON.stringify(this.toJson(e),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 tn(){let e=0,t=0;for(let i=0;i<28;i+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<i,(128&n)==0)return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,(128&i)==0)return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,(128&n)==0)return this.assertBounds(),[e,t]}throw Error("invalid varint")}function tr(e,t,i){for(let n=0;n<28;n+=7){let r=e>>>n,a=!(r>>>7==0&&0==t),s=(a?128|r:r)&255;if(i.push(s),!a)return}let n=e>>>28&15|(7&t)<<4,r=t>>3!=0;if(i.push((r?128|n:n)&255),r){for(let e=3;e<31;e+=7){let n=t>>>e,r=n>>>7!=0,a=(r?128|n:n)&255;if(i.push(a),!r)return}i.push(t>>>31&1)}}function ta(e){let t="-"===e[0];t&&(e=e.slice(1));let i=0,n=0;function r(t,r){let a=Number(e.slice(t,r));n*=1e6,(i=1e6*i+a)>=4294967296&&(n+=i/4294967296|0,i%=4294967296)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),t?tc(i,n):to(i,n)}function ts(e,t){if({lo:e,hi:t}={lo:e>>>0,hi:t>>>0},t<=2097151)return String(4294967296*t+e);let i=16777215&e,n=(e>>>24|t<<8)&16777215,r=t>>16&65535,a=i+6777216*n+6710656*r,s=n+8147497*r,o=2*r;return a>=1e7&&(s+=Math.floor(a/1e7),a%=1e7),s>=1e7&&(o+=Math.floor(s/1e7),s%=1e7),o.toString()+tl(s)+tl(a)}function to(e,t){return{lo:0|e,hi:0|t}}function tc(e,t){return t=~t,e?e=~e+1:t+=1,to(e,t)}let tl=e=>{let t=String(e);return"0000000".slice(t.length)+t};function td(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let i=0;i<9;i++)t.push(127&e|128),e>>=7;t.push(1)}}function tu(){let e=this.buf[this.pos++],t=127&e;if((128&e)==0||(t|=(127&(e=this.buf[this.pos++]))<<7,(128&e)==0)||(t|=(127&(e=this.buf[this.pos++]))<<14,(128&e)==0)||(t|=(127&(e=this.buf[this.pos++]))<<21,(128&e)==0))return this.assertBounds(),t;
1t|=(15&(e=this.buf[this.pos++]))<<28;for(let t=5;(128&e)!=0&&t<10;t++)e=this.buf[this.pos++];if((128&e)!=0)throw Error("invalid varint");return this.assertBounds(),t>>>0}let th=function(){let 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 e$||"object"!=typeof e$.env||"1"!==e$.env.BUF_BIGINT_DISABLE)){let t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),r=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){let n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw Error("int64 invalid: ".concat(e));return n},uParse(e){let t="bigint"==typeof e?e:BigInt(e);if(t>r||t<n)throw Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}let t=e=>e4(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>e4(/^[0-9]+$/.test(e),"uint64 invalid: ".concat(e));return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),t(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),i(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),ta(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),ta(e)),dec:(e,t)=>(function(e,t){let i=to(e,t),n=2147483648&i.hi;n&&(i=tc(i.lo,i.hi));let r=ts(i.lo,i.hi);return n?"-"+r:r})(e,t),uDec:(e,t)=>ts(e,t)}}();function tp(e,t,i){if(t===i)return!0;if(e==er.BYTES){if(!(t instanceof Uint8Array)||!(i instanceof Uint8Array)||t.length!==i.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==i[e])return!1;return!0}switch(e){case er.UINT64:case er.FIXED64:case er.INT64:case er.SFIXED64:case er.SINT64:return t==i}return!1}function tm(e,t){switch(e){case er.BOOL:return!1;case er.UINT64:case er.FIXED64:case er.INT64:case er.SFIXED64:case er.SINT64:return 0==t?th.zero:"0";case er.DOUBLE:case er.FLOAT:return 0;case er.BYTES:return new Uint8Array(0);case er.STRING:return"";default:return 0}}function tg(e,t){switch(e){case er.BOOL:return!1===t;case er.STRING:return""===t;case er.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}(l=er||(er={}))[l.DOUBLE=1]="DOUBLE",l[l.FLOAT=2]="FLOAT",l[l.INT64=3]="INT64",l[l.UINT64=4]="UINT64",l[l.INT32=5]="INT32",l[l.FIXED64=6]="FIXED64",l[l.FIXED32=7]="FIXED32",l[l.BOOL=8]="BOOL",l[l.STRING=9]="STRING",l[l.BYTES=12]="BYTES",l[l.UINT32=13]="UINT32",l[l.SFIXED32=15]="SFIXED32",l[l.SFIXED64=16]="SFIXED64",l[l.SINT32=17]="SINT32",l[l.SINT64=18]="SINT64",(d=ea||(ea={}))[d.BIGINT=0]="BIGINT",d[d.STRING=1]="STRING",(u=es||(es={}))[u.Varint=0]="Varint",u[u.Bit64=1]="Bit64",u[u.LengthDelimited=2]="LengthDelimited",u[u.StartGroup=3]="StartGroup",u[u.EndGroup=4]="EndGroup",u[u.Bit32=5]="Bit32";class tf{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),i=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],i),i+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(e6(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return e9(e),td(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){e8(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){e6(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){e9(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return e9(e),td(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=th.enc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=th.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=th.enc(e);return tr(t.lo,t.hi,this.buf),this}sint64(e){let t=th.enc(e),i=t.hi>>31;return tr(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=th.uEnc(e);return tr(t.lo,t.hi,this.buf),this}}class tv{constructor(e,t){this.varint64=tn,this.uint32=tu,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=7&e;
1if(t<=0||i<0||i>5)throw Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case es.Varint:for(;128&this.buf[this.pos++];);break;case es.Bit64:this.pos+=4;case es.Bit32:this.pos+=4;break;case es.LengthDelimited:let n=this.uint32();this.pos+=n;break;case es.StartGroup:for(;;){let[e,i]=this.tag();if(i===es.EndGroup){if(void 0!==t&&e!==t)throw Error("invalid end group tag");break}this.skip(i,e)}break;default:throw Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return th.dec(...this.varint64())}uint64(){return th.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,th.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 th.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return th.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 tk(e){let t=e.field.localName,i=Object.create(null);return i[t]=function(e){let 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 tm(t.T,t.L);case"message":let i=t.T,n=new i;return i.fieldWrapper?i.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let tb="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),ty=[];for(let e=0;e<tb.length;e++)ty[tb[e].charCodeAt(0)]=e;ty["-".charCodeAt(0)]=tb.indexOf("+"),ty["_".charCodeAt(0)]=tb.indexOf("/");let tT={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i=new Uint8Array(t),n=0,r=0,a,s=0;for(let t=0;t<e.length;t++){if(void 0===(a=ty[e.charCodeAt(t)]))switch(e[t]){case"=":r=0;case"\n":case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:s=a,r=1;break;case 1:i[n++]=s<<2|(48&a)>>4,s=a,r=2;break;case 2:i[n++]=(15&s)<<4|(60&a)>>2,s=a,r=3;break;case 3:i[n++]=(3&s)<<6|a,r=0}}if(1==r)throw Error("invalid base64 string.");return i.subarray(0,n)},enc(e){let t="",i=0,n,r=0;for(let a=0;a<e.length;a++)switch(n=e[a],i){case 0:t+=tb[n>>2],r=(3&n)<<4,i=1;break;case 1:t+=tb[r|n>>4],r=(15&n)<<2,i=2;break;case 2:t+=tb[r|n>>6]+tb[63&n],i=0}return i&&(t+=tb[r]+"=",1==i&&(t+="=")),t}};function tS(e,t){let i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find(e=>e.no==t.field.no)}function tC(e,t){e4(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function tE(e,t){let i=e.localName;if(e.repeated)return t[i].length>0;if(e.oneof)return t[e.oneof.localName].case===i;switch(e.kind){case"enum":case"scalar":if(e.opt||e.req)return void 0!==t[i];if("enum"==e.kind)return t[i]!==e.T.values[0].no;return!tg(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function tw(e,t){let i=e.localName,n=!e.opt&&!e.req;if(e.repeated)t[i]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[i]={};break;case"enum":t[i]=n?e.T.values[0].no:void 0;break;case"scalar":t[i]=n?tm(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function tP(e,t){if(null===e||"object"!=typeof e||!Object.getOwnPropertyNames(ti.prototype).every(t=>t in e&&"function"==typeof e[t]))return!1;let i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function tR(e,t){return tP(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}er.DOUBLE,er.FLOAT,er.INT64,er.UINT64,er.INT32,er.UINT32,er.BOOL,er.STRING,er.BYTES;let tI={ignoreUnknownFields:!1},tD={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},t_=Symbol(),tM=Symbol();function tO(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 tA(e,t,i,n,r){let a=i.localName;if(i.repeated){if(e4("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(tO(t)));let s=e[a];for(let e of t){if(null===e)throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(tO(e)));switch(i.kind){case"message":s.push(i.T.fromJson(e,n));break;case"enum":let t=tx(i.T,e,n.ignoreUnknownFields,!0);t!==tM&&s.push(t);break;case"scalar":try{s.push(tN(i.T,e,i.L,!0))}catch(n){let t="cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(tO(e));throw n instanceof Error&&n.message.length>0&&(t+=": ".concat(n.message)),Error(t)}}}}else if("map"==i.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(tO(t)));let s=e[a];for(let[e,a]of Object.entries(t)){let o;if(null===a)throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: map value null"));try{o=function(e,t){if(e===er.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return tN(e,t,ea.BIGINT,!0).toString()}(i.K,e)}catch(n){let e="cannot decode map key for field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(tO(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}switch(i.V.kind){case"message":s[o]=i.V.T.fromJson(a,n);break;case"enum":let c=tx(i.V.T,a,n.ignoreUnknownFields,!0);c!==tM&&(s[o]=c);break;case"scalar":try{s[o]=tN(i.V.T,a,ea.BIGINT,!0)}catch(n){let e="cannot decode map value for field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(tO(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}}}}else switch(i.oneof&&(e=e[i.oneof.localName]={case:a},a="value"),i.kind){case"message":let s=i.T;if(null===t&&"google.protobuf.Value"!=s.typeName)return;let o=e[a];tP(o)?o.fromJson(t,n):(e[a]=o=s.fromJson(t,n),s.fieldWrapper&&!i.oneof&&(e[a]=s.fieldWrapper.unwrapField(o)));break;case"enum":let c=tx(i.T,t,n.ignoreUnknownFields,!1);switch(c){case t_:tw(i,e);break;case tM:break;default:e[a]=c}break;case"scalar":try{let n=tN(i.T,t,i.L,!1);n===t_?tw(i,e):e[a]=n}catch(n){let e="cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(tO(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}}}function tN(e,t,i,n){if(null===t)return n?tm(e,i):t_;switch(e){case er.DOUBLE:case er.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t||"string"==typeof t&&t.trim().length!==t.length||"string"!=typeof t&&"number"!=typeof t)break;let r=Number(t);if(Number.isNaN(r)||!Number.isFinite(r))break;return e==er.FLOAT&&e8(r),r;case er.INT32:case er.FIXED32:case er.SFIXED32:case er.SINT32:case er.UINT32:let a;if("number"==typeof t?a=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(a=Number(t)),void 0===a)break;return e==er.UINT32||e==er.FIXED32?e6(a):e9(a),a;case er.INT64:case er.SFIXED64:case er.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;let s=th.parse(t);return i?s.toString():s;case er.FIXED64:case er.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;let o=th.uParse(t);return i?o.toString():o;case er.BOOL:if("boolean"!=typeof t)break;return t;case er.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw Error("invalid UTF8")}return t;case er.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return tT.dec(t)}throw Error()}function tx(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:t_;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":let r=e.findName(t);if(void 0!==r)return r.no;if(i)return tM}throw Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(tO(t)))}function tL(e,t,i){if("map"==e.kind){e4("object"==typeof t&&null!=t);let n={},r=Object.entries(t);switch(e.V.kind){case"scalar":for(let[t,i]of r)n[t.toString()]=tF(e.V.T,i);break;case"message":for(let[e,t]of r)n[e.toString()]=t.toJson(i);break;case"enum":let a=e.V.T;for(let[e,t]of r)n[e.toString()]=tU(a,t,i.enumAsInteger)}return i.emitDefaultValues||r.length>0?n:void 0}if(e.repeated){e4(Array.isArray(t));let n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(tF(e.T,t[i]));break;case"enum":for(let r=0;r<t.length;r++)n.push(tU(e.T,t[r],i.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)n.push(t[e].toJson(i))}return i.emitDefaultValues||n.length>0?n:void 0}switch(e.kind){case"scalar":return tF(e.T,t);case"enum":return tU(e.T,t,i.enumAsInteger);case"message":return tR(e.T,t).toJson(i)}}function tU(e,t,i){var n;if(e4("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;let r=e.findNumber(t);return null!==(n=null==r?void 0:r.name)&&void 0!==n?n:t}function tF(e,t){switch(e){case er.INT32:case er.SFIXED32:case er.SINT32:case er.FIXED32:case er.UINT32:return e4("number"==typeof t),t;case er.FLOAT:case er.DOUBLE:if(e4("number"==typeof t),Number.isNaN(t))return"NaN";if(t===Number.POSITIVE_INFINITY)return"Infinity";if(t===Number.NEGATIVE_INFINITY)return"-Infinity";return t;case er.STRING:return e4("string"==typeof t),t;case er.BOOL:return e4("boolean"==typeof t),t;case er.UINT64:case er.FIXED64:case er.INT64:case er.SFIXED64:case er.SINT64:return e4("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case er.BYTES:return e4(t instanceof Uint8Array),tT.enc(t)}}let tB=Symbol("@bufbuild/protobuf/unknown-fields"),tj={readUnknownFields:!0,readerFactory:e=>
1new tv(e)},tq={writeUnknownFields:!0,writerFactory:()=>new tf};function tV(e,t,i,n,r){let{repeated:a,localName:s}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=s&&delete e.value,e.case=s,s="value"),i.kind){case"scalar":case"enum":let o="enum"==i.kind?er.INT32:i.T,c=tz;if("scalar"==i.kind&&i.L>0&&(c=tW),a){let i=e[s];if(n==es.LengthDelimited&&o!=er.STRING&&o!=er.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(c(t,o))}else i.push(c(t,o))}else e[s]=c(t,o);break;case"message":let l=i.T;a?e[s].push(tH(t,new l,r,i)):tP(e[s])?tH(t,e[s],r,i):(e[s]=tH(t,new l,r,i),!l.fieldWrapper||i.oneof||i.repeated||(e[s]=l.fieldWrapper.unwrapField(e[s])));break;case"map":let[d,u]=function(e,t,i){let n,r;let a=t.uint32(),s=t.pos+a;for(;t.pos<s;){let[a]=t.tag();switch(a){case 1:n=tz(t,e.K);break;case 2:switch(e.V.kind){case"scalar":r=tz(t,e.V.T);break;case"enum":r=t.int32();break;case"message":r=tH(t,new e.V.T,i,void 0)}}}if(void 0===n&&(n=tm(e.K,ea.BIGINT)),"string"!=typeof n&&"number"!=typeof n&&(n=n.toString()),void 0===r)switch(e.V.kind){case"scalar":r=tm(e.V.T,ea.BIGINT);break;case"enum":r=e.V.T.values[0].no;break;case"message":r=new e.V.T}return[n,r]}(i,t,r);e[s][d]=u}}function tH(e,t,i,n){let r=t.getType().runtime.bin,a=null==n?void 0:n.delimited;return r.readMessage(t,e,a?n.no:e.uint32(),i,a),t}function tW(e,t){let i=tz(e,t);return"bigint"==typeof i?i.toString():i}function tz(e,t){switch(t){case er.STRING:return e.string();case er.BOOL:return e.bool();case er.DOUBLE:return e.double();case er.FLOAT:return e.float();case er.INT32:return e.int32();case er.INT64:return e.int64();case er.UINT64:return e.uint64();case er.FIXED64:return e.fixed64();case er.BYTES:return e.bytes();case er.FIXED32:return e.fixed32();case er.SFIXED32:return e.sfixed32();case er.SFIXED64:return e.sfixed64();case er.SINT64:return e.sint64();case er.UINT32:return e.uint32();case er.SINT32:return e.sint32()}}function tG(e,t,i,n){e4(void 0!==t);let r=e.repeated;switch(e.kind){case"scalar":case"enum":let a="enum"==e.kind?er.INT32:e.T;if(r){if(e4(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,es.LengthDelimited).fork();let[,r]=tQ(t);for(let t=0;t<n.length;t++)e[r](n[t]);e.join()}(i,a,e.no,t);else for(let n of t)tJ(i,a,e.no,n)}else tJ(i,a,e.no,t);break;case"message":if(r)for(let r of(e4(Array.isArray(t)),t))tK(i,n,e,r);else tK(i,n,e,t);break;case"map":for(let[r,a]of(e4("object"==typeof t&&null!=t),Object.entries(t)))!function(e,t,i,n,r){e.tag(i.no,es.LengthDelimited),e.fork();let a=n;switch(i.K){case er.INT32:case er.FIXED32:case er.UINT32:case er.SFIXED32:case er.SINT32:a=Number.parseInt(n);break;case er.BOOL:e4("true"==n||"false"==n),a="true"==n}switch(tJ(e,i.K,1,a),i.V.kind){case"scalar":tJ(e,i.V.T,2,r);break;case"enum":tJ(e,er.INT32,2,r);break;case"message":e4(void 0!==r),e.tag(2,es.LengthDelimited).bytes(r.toBinary(t))}e.join()}(i,n,e,r,a)}}function tK(e,t,i,n){let r=tR(i.T,n);i.delimited?e.tag(i.no,es.StartGroup).raw(r.toBinary(t)).tag(i.no,es.EndGroup):e.tag(i.no,es.LengthDelimited).bytes(r.toBinary(t))}function tJ(e,t,i,n){e4(void 0!==n);let[r,a]=tQ(t);e.tag(i,r)[a](n)}function tQ(e){let t=es.Varint;switch(e){case er.BYTES:case er.STRING:t=es.LengthDelimited;break;case er.DOUBLE:case er.FIXED64:case er.SFIXED64:t=es.Bit64;break;case er.FIXED32:case er.SFIXED32:case er.FLOAT:t=es.Bit32}return[t,er[e].toLowerCase()]}function tY(e){if(void 0===e)return e;if(tP(e))return e.clone();if(e instanceof Uint8Array){let t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function tX(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class tZ{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){let e={};for(let t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){let e={};for(let t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||(this.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){let e;this.members=[];let t=this.members;for(let i of this.list())i.oneof?i.oneof!==e&&(e=i.oneof,t.push(e)):t.push(i)}return this.members}}function t$(e,t){let i=t1(e);return t?i:t6(t9(i))}let t0=t1;function t1(e){let t=!1,i=[];for(let n=0;n<e.length;n++){let r=e.charAt(n);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":i.push(r),t=!1;break;default:t&&(t=!1,r=r.toUpperCase()),i.push(r)}}return i.join("")}let t2=new Set(["constructor","toString","toJSON","valueOf"]),t3=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),t4=e=>"".concat(e,"$"),t9=e=>t3.has(e)?t4(e):e,t6=e=>t2.has(e)?t4(e):e;class t8{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=t$(e,!1)}addField(e){e4(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]}}let t5=(h=e=>
1new tZ(e,e=>(function(e,t){var i,n,r,a,s,o;let c;let l=[];for(let t of"function"==typeof e?e():e){if(t.localName=t$(t.name,void 0!==t.oneof),t.jsonName=null!==(i=t.jsonName)&&void 0!==i?i:t0(t.name),t.repeated=null!==(n=t.repeated)&&void 0!==n&&n,"scalar"==t.kind&&(t.L=null!==(r=t.L)&&void 0!==r?r:ea.BIGINT),t.delimited=null!==(a=t.delimited)&&void 0!==a&&a,t.req=null!==(s=t.req)&&void 0!==s&&s,t.opt=null!==(o=t.opt)&&void 0!==o&&o,void 0===t.packed&&(t.packed="enum"==t.kind||"scalar"==t.kind&&t.T!=er.BYTES&&t.T!=er.STRING),void 0!==t.oneof){let e="string"==typeof t.oneof?t.oneof:t.oneof.name;c&&c.name==e||(c=new t8(e)),t.oneof=c,c.addField(t)}l.push(t)}return l})(e)),p=e=>{for(let t of e.getType().fields.byMember()){if(t.opt)continue;let i=t.localName;if(t.repeated){e[i]=[];continue}switch(t.kind){case"oneof":e[i]={case:void 0};break;case"enum":e[i]=0;break;case"map":e[i]={};break;case"scalar":e[i]=tm(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},tI),e):tI},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},tD),e):tD},readMessage(e,t,i,n){if(null==t||Array.isArray(t)||"object"!=typeof t)throw Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(tO(t)));n=null!=n?n:new e;let r=new Map,a=i.typeRegistry;for(let[s,o]of Object.entries(t)){let t=e.fields.findJsonName(s);if(t){if(t.oneof){if(null===o&&"scalar"==t.kind)continue;let i=r.get(t.oneof);if(void 0!==i)throw Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(s,'"'));r.set(t.oneof,s)}tA(n,o,t,i,e)}else{let t=!1;if((null==a?void 0:a.findExtension)&&s.startsWith("[")&&s.endsWith("]")){let r=a.findExtension(s.substring(1,s.length-1));if(r&&r.extendee.typeName==e.typeName){t=!0;let[e,a]=tk(r);tA(e,o,r.field,i,r),function(e,t,i,n){tC(t,e);let r=t.runtime.bin.makeReadOptions(n),a=t.runtime.bin.makeWriteOptions(n);if(tS(e,t)){let i=e.getType().runtime.bin.listUnknownFields(e).filter(e=>e.no!=t.field.no);for(let t of(e.getType().runtime.bin.discardUnknownFields(e),i))e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}let s=a.writerFactory(),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,i,s,a);let c=r.readerFactory(s.finish());for(;c.pos<c.len;){let[t,i]=c.tag(),n=c.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}(n,r,a(),i)}}if(!t&&!i.ignoreUnknownFields)throw Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(s,'" is unknown'))}}return n},writeMessage(e,t){let i;let n=e.getType(),r={};try{for(i of n.fields.byNumber()){if(!tE(i,e)){var a;if(i.req)throw"required field not set";if(!t.emitDefaultValues||!((a=i).repeated||"map"==a.kind||!a.oneof&&"message"!=a.kind&&!a.opt&&!a.req))continue}let n=i.oneof?e[i.oneof.localName].value:e[i.localName],s=tL(i,n,t);void 0!==s&&(r[t.useProtoFieldName?i.name:i.jsonName]=s)}let s=t.typeRegistry;if(null==s?void 0:s.findExtensionFor)for(let i of n.runtime.bin.listUnknownFields(e)){let a=s.findExtensionFor(n.typeName,i.no);if(a&&tS(e,a)){let i=function(e,t,i){tC(t,e);let n=t.runtime.bin.makeReadOptions(i),r=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let i=e.length-1;i>=0;--i)if(e[i].no==t.no)return[e[i]];return[]}return e.filter(e=>e.no===t.no)}(e.getType().runtime.bin.listUnknownFields(e),t.field),[a,s]=tk(t);for(let e of r)t.runtime.bin.readField(a,n.readerFactory(e.data),t.field,e.wireType,n);return s()}(e,a,t),n=tL(a.field,i,t);void 0!==n&&(r[a.field.jsonName]=n)}}}catch(r){let e=i?"cannot encode field ".concat(n.typeName,".").concat(i.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),t=r instanceof Error?r.message:String(r);throw Error(e+(t.length>0?": ".concat(t):""))}return r},readScalar:(e,t,i)=>tN(e,t,null!=i?i:ea.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t&&(i||tg(e,t)))return tF(e,t)},debug:tO},bin:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},tj),e):tj},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},tq),e):tq},listUnknownFields(e){var t;return null!==(t=e[tB])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[tB]},writeUnknownFields(e,t){let i=e[tB];if(i)for(let e of i)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,i,n){Array.isArray(e[tB])||(e[tB]=[]),e[tB].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,r){let a,s;let o=e.getType(),c=r?t.len:t.pos+i;for(;t.pos<c&&([a,s]=t.tag(),!0!==r||s!=es.EndGroup);){let i=o.fields.find(a);if(!i){let i=t.skip(s,a);n.readUnknownFields&&this.onUnknownField(e,a,s,i);continue}tV(e,t,i,s,n)}if(r&&(s!=es.EndGroup||a!==i))throw Error("invalid end group tag")},readField:tV,writeMessage(e,t,i){let n=e.getType();for(let r of n.fields.byNumber()){if(!tE(r,e)){if(r.req)throw Error("cannot encode field ".concat(n.typeName,".").concat(r.name," to binary: required field not set"));continue}let a=r.oneof?e[r.oneof.localName].value:e[r.localName];tG(r,a,t,i)}return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&tG(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:e7,initPartial(e,t){if(void 0!==e)for(let i of t.getType().fields.byMember()){let n=i.localName;if(null!=e[n])switch(i.kind){case"oneof":let r=e[n].case;if(void 0===r)continue;let a=i.findField(r),s=e[n].value;a&&"message"==a.kind&&!tP(s,a.T)?s=new a.T(s):a&&"scalar"===a.kind&&a.T===er.BYTES&&(s=tX(s)),t[n]={case:r,value:s};break;case"scalar":case"enum":let o=e[n];i.T===er.BYTES&&(o=i.repeated?o.map(tX):tX(o)),t[n]=o;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===er.BYTES)for(let[i,r]of Object.entries(e[n]))t[n][i]=tX(r);else Object.assign(t[n],e[n]);break;case"message":let c=i.V.T;for(let i of Object.keys(e[n])){let r=e[n][i];c.fieldWrapper||(r=new c(r)),t[n][i]=r}}break;case"message":let l=i.T;if(i.repeated)t[n]=e[n].map(e=>tP(e,l)?e:new l(e));else{let i=e[n];l.fieldWrapper?"google.protobuf.BytesValue"===l.typeName?t[n]=tX(i):t[n]=i:t[n]=tP(i,l)?i:new l(i)}}}},equals:(e,t,i)=>t===i||!!t&&!!i&&e.fields.byMember().every(e=>{let n=t[e.localName],r=i[e.localName];if(e.repeated){if(n.length!==r.length)return!1;switch(e.kind){case"message":return n.every((t,i)=>e.T.equals(t,r[i]));case"scalar":return n.every((t,i)=>tp(e.T,t,r[i]));case"enum":return n.every((e,t)=>tp(er.INT32,e,r[t]))}throw Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let a=n,s=r;return e.T.fieldWrapper&&(void 0===a||tP(a)||(a=e.T.fieldWrapper.wrapField(a)),void 0===s||tP(s)||(s=e.T.fieldWrapper.wrapField(s))),e.T.equals(a,s);case"enum":return tp(er.INT32,n,r);case"scalar":return tp(e.T,n,r);case"oneof":if(n.case!==r.case)return!1;let o=e.findField(n.case);if(void 0===o)return!0;switch(o.kind){case"message":return o.T.equals(n.value,r.value);case"enum":return tp(er.INT32,n.value,r.value);case"scalar":return tp(o.T,n.value,r.value)}throw Error("oneof cannot contain ".concat(o.kind));case"map":let c=Object.keys(n).concat(Object.keys(r));switch(e.V.kind){case"message":let l=e.V.T;return c.every(e=>l.equals(n[e],r[e]));case"enum":return c.every(e=>tp(er.INT32,n[e],r[e]));case"scalar":let d=e.V.T;return c.every(e=>tp(d,n[e],r[e]))}}}),clone(e){let t=e.getType(),i=new t;for(let n of t.fields.byMember()){let t;let r=e[n.localName];if(n.repeated)t=r.map(tY);else if("map"==n.kind)for(let[e,a]of(t=i[n.localName],Object.entries(r)))t[e]=tY(a);else t="oneof"==n.kind?n.findField(r.case)?{case:r.case,value:tY(r.value)}:{case:void 0}:tY(r);i[n.localName]=t}for(let n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(i,n.no,n.wireType,n.data);return i}}),{newFieldList:h,initFields:p}),makeMessageType(e,t,i){return function(e,t,i,n){var r;let a=null!==(r=null==n?void 0:n.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 ti),Object.assign(s,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>new s().fromBinary(e,t),fromJson:(e,t)=>new s().fromJson(e,t),fromJsonString:(e,t)=>
1new s().fromJsonString(e,t),equals:(t,i)=>e.util.equals(s,t,i)}),s}(this,e,t,i)},makeEnum:function(e,t,i){let n={};for(let e of t){let t=tt(e);n[t.localName]=t.no,n[t.no]=t.localName}return e7(n,e,t),n},makeEnumType:te,getEnumType:function(e){let t=e[e5];return e4(t,"missing enum type on enum object"),t},makeExtension(e,t,i){var n;let r;return n=this,{typeName:e,extendee:t,get field(){if(!r){let t="function"==typeof i?i():i;t.name=e.split(".").pop(),t.jsonName="[".concat(e,"]"),r=n.util.newFieldList([t]).list()[0]}return r},runtime:n}}});class t7 extends ti{constructor(e){super(),this.seconds=th.zero,this.nanos=0,t5.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(t5.json.debug(e)));let i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");let n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw 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=th.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){let t=1e3*Number(this.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){let e=(this.nanos+1e9).toString().substring(1);i="000000"===e.substring(3)?"."+e.substring(0,3)+"Z":"000"===e.substring(6)?"."+e.substring(0,6)+"Z":"."+e+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return t7.fromDate(new Date)}static fromDate(e){let t=e.getTime();return new t7({seconds:th.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new t7().fromBinary(e,t)}static fromJson(e,t){return new t7().fromJson(e,t)}static fromJsonString(e,t){return new t7().fromJsonString(e,t)}static equals(e,t){return t5.util.equals(t7,e,t)}}t7.runtime=t5,t7.typeName="google.protobuf.Timestamp",t7.fields=t5.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);let ie=t5.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:t7},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:it,repeated:!0},{no:5,name:"events",kind:"message",T:ir,repeated:!0}]),it=t5.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:ii,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),ii=t5.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:t7},{no:3,name:"value",kind:"scalar",T:2}]),ir=t5.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:t7},{no:7,name:"normalized_end_timestamp",kind:"message",T:t7,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),ia=t5.makeEnum("livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"},{no:3,name:"AC_MP3"}]),is=t5.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"}]),io=t5.makeEnum("livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]),ic=t5.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),il=t5.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),id=t5.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"}]),iu=t5.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),ih=t5.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),ip=t5.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),im=t5.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"}]),ig=t5.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"}]),iv=t5.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),ik=t5.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"}]),ib=t5.makeEnum("livekit.PacketTrailerFeature",[{no:0,name:"PTF_USER_TIMESTAMP"},{no:1,name:"PTF_FRAME_ID"}]),iy=t5.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:iT,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:i4}]),iT=t5.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),iS=t5.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:t5.getEnumType(id),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}]),iC=t5.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:t5.getEnumType(iE)},{no:4,name:"tracks",kind:"message",T:iD,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:iS},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:t5.getEnumType(iw)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:t5.getEnumType(im)},{no:18,name:"kind_details",kind:"enum",T:t5.getEnumType(iP),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:i_,repeated:!0},{no:20,name:"client_protocol",kind:"scalar",T:5}]),iE=t5.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),iw=t5.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"}]),iP=t5.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"}]),iR=t5.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),iI=t5.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:iO,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:t5.getEnumType(iA)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),iD=t5.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:t5.getEnumType(il)},{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:t5.getEnumType(id)},{no:10,name:"layers",kind:"message",T:iO,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:iI,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:t5.getEnumType(iR)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:i4},{no:19,name:"audio_features",kind:"enum",T:t5.getEnumType(ik),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:t5.getEnumType(ic)},{no:21,name:"packet_trailer_features",kind:"enum",T:t5.getEnumType(ib),repeated:!0}]),i_=t5.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:t5.getEnumType(iR)}]),iM=t5.makeMessageType("livekit.DataTrackSubscriptionOptions",()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}]),iO=t5.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:t5.getEnumType(iu)},{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}]),iA=t5.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"}]),iN=t5.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:t5.getEnumType(ix)},{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:ij,oneof:"value"},{no:3,name:"speaker",kind:"message",T:iF,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:iq,oneof:"value"},{no:7,name:"transcription",kind:"message",T:iV,oneof:"value"},{no:8,name:"metrics",kind:"message",T:ie,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:iW,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:iz,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:iG,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:iK,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:i5,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:i7,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:ne,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:iL,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}
vendor: 20,790 bytes, line 1
1]),ix=t5.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),iL=t5.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:t5.getEnumType(iR)},{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}]),iU=t5.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:ij,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:iW,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:iz,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:iG,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:iK,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:i5,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:i7,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:ne,oneof:"value"}]),iF=t5.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:iB,repeated:!0}]),iB=t5.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}]),ij=t5.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}]),iq=t5.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),iV=t5.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:iH,repeated:!0}]),iH=t5.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}]),iW=t5.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}]),iz=t5.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}]),iG=t5.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),iK=t5.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:iJ,oneof:"value"},{no:4,name:"compressed_payload",kind:"scalar",T:12,oneof:"value"}]),iJ=t5.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}]),iQ=t5.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),iY=t5.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:t5.getEnumType(iX)},{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}]),iX=t5.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),iZ=t5.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:t5.getEnumType(i$)},{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:t5.getEnumType(i0),repeated:!0}]),i$=t5.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"}]),i0=t5.makeEnum("livekit.ClientInfo.Capability",[{no:0,name:"CAP_UNUSED"},{no:1,name:"CAP_PACKET_TRAILER"}]),i1=t5.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:i2},{no:2,name:"screen",kind:"message",T:i2},{no:3,name:"resume_connection",kind:"enum",T:t5.getEnumType(ip)},{no:4,name:"disabled_codecs",kind:"message",T:i3},{no:5,name:"force_relay",kind:"enum",T:t5.getEnumType(ip)}]),i2=t5.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:t5.getEnumType(ip)}]),i3=t5.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:iT,repeated:!0},{no:2,name:"publish",kind:"message",T:iT,repeated:!0}]),i4=t5.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),i9=t5.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),i6=t5.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:t5.getEnumType(i9)},{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"}),i8=t5.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),i5=t5.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:t5.getEnumType(iR)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:i6,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:i8,oneof:"content_header"}],{localName:"DataStream_Header"}),i7=t5.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"}),ne=t5.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"}),nt=t5.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}]),ni=t5.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:nt}]),nn=t5.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),nr=t5.makeEnum("livekit.JobRestartPolicy",[{no:0,name:"JRP_ON_FAILURE"},{no:1,name:"JRP_NEVER"}]),na=t5.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:t5.getEnumType(nr)},{no:4,name:"deployment",kind:"scalar",T:9}]),ns=t5.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"}]),no=t5.makeEnum("livekit.EncodedFileType",[{no:0,name:"DEFAULT_FILETYPE"},{no:1,name:"MP4"},{no:2,name:"OGG"},{no:3,name:"MP3"}]),nc=t5.makeEnum("livekit.StreamProtocol",[{no:0,name:"DEFAULT_PROTOCOL"},{no:1,name:"RTMP"},{no:2,name:"SRT"},{no:3,name:"WEBSOCKET"}]),nl=t5.makeEnum("livekit.SegmentedFileProtocol",[{no:0,name:"DEFAULT_SEGMENTED_FILE_PROTOCOL"},{no:1,name:"HLS_PROTOCOL"}]),nd=t5.makeEnum("livekit.SegmentedFileSuffix",[{no:0,name:"INDEX"},{no:1,name:"TIMESTAMP"}]),nu=t5.makeEnum("livekit.ImageFileSuffix",[{no:0,name:"IMAGE_SUFFIX_INDEX"},{no:1,name:"IMAGE_SUFFIX_TIMESTAMP"},{no:2,name:"IMAGE_SUFFIX_NONE_OVERWRITE"}]),nh=t5.makeEnum("livekit.AudioMixing",[{no:0,name:"DEFAULT_MIXING"},{no:1,name:"DUAL_CHANNEL_AGENT"},{no:2,name:"DUAL_CHANNEL_ALTERNATE"}]),np=t5.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:t5.getEnumType(ia)},{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:t5.getEnumType(is)},{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}]),nm=t5.makeMessageType("livekit.StreamOutput",()=>[{no:1,name:"protocol",kind:"enum",T:t5.getEnumType(nc)},{no:2,name:"urls",kind:"scalar",T:9,repeated:!0}]),ng=t5.makeMessageType("livekit.SegmentedFileOutput",()=>[{no:1,name:"protocol",kind:"enum",T:t5.getEnumType(nl)},{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:t5.getEnumType(nd)},{no:8,name:"disable_manifest",kind:"scalar",T:8},{no:5,name:"s3",kind:"message",T:nv,oneof:"output"},{no:6,name:"gcp",kind:"message",T:nk,oneof:"output"},{no:7,name:"azure",kind:"message",T:nb,oneof:"output"},{no:9,name:"aliOSS",kind:"message",T:ny,oneof:"output"}]),nf=t5.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:t5.getEnumType(nu)},{no:6,name:"image_codec",kind:"enum",T:t5.getEnumType(io)},{no:7,name:"disable_manifest",kind:"scalar",T:8},{no:8,name:"s3",kind:"message",T:nv,oneof:"output"},{no:9,name:"gcp",kind:"message",T:nk,oneof:"output"},{no:10,name:"azure",kind:"message",T:nb,oneof:"output"},{no:11,name:"aliOSS",kind:"message",T:ny,oneof:"output"}]),nv=t5.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:nT}]),nk=t5.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:nT}]),nb=t5.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}]),ny=t5.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}]),nT=t5.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}]),nS=t5.makeMessageType("livekit.AutoParticipantEgress",()=>[{no:1,name:"preset",kind:"enum",T:t5.getEnumType(ns),oneof:"options"},{no:2,name:"advanced",kind:"message",T:np,oneof:"options"},{no:3,name:"file_outputs",kind:"message",T:nw,repeated:!0},{no:4,name:"segment_outputs",kind:"message",T:ng,repeated:!0}]),nC=t5.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:nv,oneof:"output"},{no:3,name:"gcp",kind:"message",T:nk,oneof:"output"},{no:4,name:"azure",kind:"message",T:nb,oneof:"output"},{no:6,name:"aliOSS",kind:"message",T:ny,oneof:"output"}]),nE=t5.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:t5.getEnumType(nh)},{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:nw,oneof:"output"},{no:7,name:"stream",kind:"message",T:nm,oneof:"output"},{no:10,name:"segments",kind:"message",T:ng,oneof:"output"},{no:8,name:"preset",kind:"enum",T:t5.getEnumType(ns),oneof:"options"},{no:9,name:"advanced",kind:"message",T:np,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:nw,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:nm,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:ng,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:nf,repeated:!0},{no:16,name:"webhooks",kind:"message",T:ni,repeated:!0}]),nw=t5.makeMessageType("livekit.EncodedFileOutput",()=>[{no:1,name:"file_type",kind:"enum",T:t5.getEnumType(no)},{no:2,name:"filepath",kind:"scalar",T:9},{no:6,name:"disable_manifest",kind:"scalar",T:8},{no:3,name:"s3",kind:"message",T:nv,oneof:"output"},{no:4,name:"gcp",kind:"message",T:nk,oneof:"output"},{no:5,name:"azure",kind:"message",T:nb,oneof:"output"},{no:7,name:"aliOSS",kind:"message",T:ny,oneof:"output"}]),nP=t5.makeMessageType("livekit.RoomEgress",()=>[{no:1,name:"room",kind:"message",T:nE},{no:3,name:"participant",kind:"message",T:nS},{no:2,name:"tracks",kind:"message",T:nC}]),nR=(()=>[{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:nP},{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:na,repeated:!0},{no:12,name:"tags",kind:"map",K:9,V:{kind:"scalar",T:9}}],t5.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}])),nI=t5.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),nD=t5.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),n_=t5.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:nG,oneof:"message"},{no:2,name:"answer",kind:"message",T:nG,oneof:"message"},{no:3,name:"trickle",kind:"message",T:nj,oneof:"message"},{no:4,name:"add_track",kind:"message",T:nA,oneof:"message"},{no:5,name:"mute",kind:"message",T:nq,oneof:"message"},{no:6,name:"subscription",kind:"message",T:nJ,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:nX,oneof:"message"},{no:8,name:"leave",kind:"message",T:n0,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:n2,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:rs,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:rl,oneof:"message"},{no:13,name:"simulate",kind:"message",T:rh,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:n3,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:rp,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:nZ,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:n$,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:nN,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:nL,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:nQ,oneof:"message"}]),nM=t5.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:nV,oneof:"message"},{no:2,name:"answer",kind:"message",T:nG,oneof:"message"},{no:3,name:"offer",kind:"message",T:nG,oneof:"message"},{no:4,name:"trickle",kind:"message",T:nj,oneof:"message"},{no:5,name:"update",kind:"message",T:nK,oneof:"message"},{no:6,name:"track_published",kind:"message",T:nW,oneof:"message"},{no:8,name:"leave",kind:"message",T:n0,oneof:"message"},{no:9,name:"mute",kind:"message",T:nq,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:n9,oneof:"message"},{no:11,name:"room_update",kind:"message",T:n6,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:n5,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:re,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:rn,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:ro,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:nz,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:nH,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:rm,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:rv,oneof:"message"},{no:22,name:"request_response",kind:"message",T:rk,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:ry,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:rc,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:rw,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:rr,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:nx,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:nU,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:nF,oneof:"message"}]),nO=t5.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:iO,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:t5.getEnumType(iA)}]),nA=t5.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:t5.getEnumType(il)},{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:t5.getEnumType(id)},{no:9,name:"layers",kind:"message",T:iO,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:nO,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:t5.getEnumType(iR)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:t5.getEnumType(ic)},{no:17,name:"audio_features",kind:"enum",T:t5.getEnumType(ik),repeated:!0},{no:18,name:"packet_trailer_features",kind:"enum",T:t5.getEnumType(ib),repeated:!0}]),nN=t5.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:t5.getEnumType(iR)}]),nx=t5.makeMessageType("livekit.PublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:i_}
vendor: 9,088 bytes, line 1
1]),nL=t5.makeMessageType("livekit.UnpublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}]),nU=t5.makeMessageType("livekit.UnpublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:i_}]),nF=t5.makeMessageType("livekit.DataTrackSubscriberHandles",()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:nB}}]),nB=t5.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"}),nj=t5.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:t5.getEnumType(nR)},{no:3,name:"final",kind:"scalar",T:8}]),nq=t5.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),nV=t5.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:iy},{no:2,name:"participant",kind:"message",T:iC},{no:3,name:"other_participants",kind:"message",T:iC,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:n4,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:i1},{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:iY},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:iT,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),nH=t5.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:n4,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:i1},{no:3,name:"server_info",kind:"message",T:iY},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),nW=t5.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:iD}]),nz=t5.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),nG=t5.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}}]),nK=t5.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:iC,repeated:!0}]),nJ=t5.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:iQ,repeated:!0}]),nQ=t5.makeMessageType("livekit.UpdateDataSubscription",()=>[{no:1,name:"updates",kind:"message",T:nY,repeated:!0}]),nY=t5.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:iM}],{localName:"UpdateDataSubscription_Update"}),nX=t5.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:t5.getEnumType(iu)},{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}]),nZ=t5.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:t5.getEnumType(ik),repeated:!0}]),n$=t5.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}]),n0=t5.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:t5.getEnumType(im)},{no:3,name:"action",kind:"enum",T:t5.getEnumType(n1)},{no:4,name:"regions",kind:"message",T:rg}]),n1=t5.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),n2=t5.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:iO,repeated:!0}]),n3=t5.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}]),n4=t5.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}]),n9=t5.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:iB,repeated:!0}]),n6=t5.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:iy}]),n8=t5.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:t5.getEnumType(ih)},{no:3,name:"score",kind:"scalar",T:2}]),n5=t5.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:n8,repeated:!0}]),n7=t5.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:t5.getEnumType(nI)}]),re=t5.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:n7,repeated:!0}]),rt=t5.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:t5.getEnumType(iu)},{no:2,name:"enabled",kind:"scalar",T:8}]),ri=t5.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:rt,repeated:!0}]),rn=t5.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:rt,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:ri,repeated:!0}]),rr=t5.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:nn,repeated:!0}]),ra=t5.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}]),rs=t5.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:ra,repeated:!0}]),ro=t5.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}]),rc=t5.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:iy},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:iC},{no:4,name:"other_participants",kind:"message",T:iC,repeated:!0}]),rl=t5.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:nG},{no:2,name:"subscription",kind:"message",T:nJ},{no:3,name:"publish_tracks",kind:"message",T:nW,repeated:!0},{no:4,name:"data_channels",kind:"message",T:ru,repeated:!0},{no:5,name:"offer",kind:"message",T:nG},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:rd,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:nx,repeated:!0}]),rd=t5.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),ru=t5.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:t5.getEnumType(nR)}]),rh=t5.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:t5.getEnumType(nD),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"}]),rp=t5.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),rm=t5.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}
vendor: 4,648 bytes, line 1
1]),rg=t5.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:rf,repeated:!0}]),rf=t5.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}]),rv=t5.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:t5.getEnumType(iv)}]),rk=t5.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:t5.getEnumType(rb)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:nj,oneof:"request"},{no:5,name:"add_track",kind:"message",T:nA,oneof:"request"},{no:6,name:"mute",kind:"message",T:nq,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:n3,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:nZ,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:n$,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:nN,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:nL,oneof:"request"}]),rb=t5.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"}]),ry=t5.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),rT=t5.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}]),rS=t5.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:iZ},{no:2,name:"connection_settings",kind:"message",T:rT},{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:nA,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:nG},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:t5.getEnumType(ig)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:rl}]),rC=t5.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:t5.getEnumType(rE)},{no:2,name:"join_request",kind:"scalar",T:12}]),rE=t5.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),rw=t5.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function rP(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var rR={exports:{}},rI=rR.exports,rD=(eo||(eo=1,c=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],r={},a=null;function s(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[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 i=this.getLevel(),r=0;r<n.length;r++){var a=n[r];this[a]=r<i?e:this.methodFactory(a,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function l(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function d(n,r,a){var c;return"debug"===(c=n)&&(c="log"),typeof console!==t&&("trace"===c&&i?o:void 0!==console[c]?s(console,c):void 0!==console.log?s(console,"log"):e)||l.apply(this,arguments)}function u(e,i){var s,o,l,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 i=window.document.cookie,n=encodeURIComponent(h),r=i.indexOf(n+"=");-1!==r&&(e=/^([^;]+)/.exec(i.slice(r+n.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;
1throw TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||d,u.getLevel=function(){return null!=l?l:null!=o?o:s},u.setLevel=function(e,i){return l=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{window.localStorage[h]=i;return}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(e){}}}(l),c.call(u)},u.setDefaultLevel=function(e){o=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){l=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&&(l=m(g)),c.call(u)}(a=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw 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},rR.exports?rR.exports=c():rI.log=c()),rR.exports);(m=ec||(ec={}))[m.trace=0]="trace",m[m.debug=1]="debug",m[m.info=2]="info",m[m.warn=3]="warn",m[m.error=4]="error",m[m.silent=5]="silent",(g=el||(el={})).Default="livekit",g.Room="livekit-room",g.TokenSource="livekit-token-source",g.Participant="livekit-participant",g.Track="livekit-track",g.Publication="livekit-track-publication",g.Engine="livekit-engine",g.Signal="livekit-signal",g.PCManager="livekit-pc-manager",g.PCTransport="livekit-pc-transport",g.E2EE="lk-e2ee",g.DataTracks="livekit-data-tracks";let r_=rD.getLogger(el.Default);function rM(e,t){let i=rD.getLogger(e);return(i.setDefaultLevel(r_.getLevel()),t)?function(e,t){let i=i=>(n,r)=>{let a=t(),s=a||r?Object.assign(Object.assign({},a),r):void 0;e[i](n,s)},n=Object.create(e);return n.trace=i("trace"),n.debug=i("debug"),n.info=i("info"),n.warn=i("warn"),n.error=i("error"),n}(i,t):i}Object.values(el).map(e=>rD.getLogger(e)),r_.setDefaultLevel(ec.info);let rO=rD.getLogger(el.E2EE),rA=[0,300,1200,2700,4800,7e3,7e3,7e3,7e3,7e3];class rN{constructor(e){this._retryDelays=void 0!==e?[...e]:rA}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;let t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}}function rx(e,t,i,n){return new(i||(i=Promise))(function(r,a){function s(e){try{c(n.next(e))}catch(e){a(e)}}function o(e){try{c(n.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):((t=e.value)instanceof i?t:new i(function(e){e(t)})).then(s,o)}c((n=n.apply(e,t||[])).next())})}function rL(e){return this instanceof rL?(this.v=e,this):new rL(e)}function rU(e){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=function(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise(function(n,r){!function(e,t,i,n){Promise.resolve(n).then(function(t){e({value:t,done:i})},t)}(n,r,(t=e[i](t)).done,t.value)})}}}"function"==typeof SuppressedError&&SuppressedError;var rF={exports:{}},rB=function(){if(ed)return rF.exports;ed=1;var e,t="object"==typeof Reflect?Reflect:null,i=t&&"function"==typeof t.apply?t.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function r(){r.init.call(this)}rF.exports=r,rF.exports.once=function(e,t){return new Promise(function(i,n){var r;function a(i){e.removeListener(t,s),n(i)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",a),i([].slice.call(arguments))}m(e,t,s,{once:!0}),"error"!==t&&(r={once:!0},"function"==typeof e.on&&m(e,"error",a,r))})},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 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,i,n){if(s(i),void 0===(a=e._events)?(a=e._events=Object.create(null),e._eventsCount=0):(void 0!==a.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),a=e._events),c=a[t]),void 0===c)c=a[t]=i,++e._eventsCount;else if("function"==typeof c?c=a[t]=n?[i,c]:[c,i]:n?c.unshift(i):c.push(i),(r=o(e))>0&&c.length>r&&!c.warned){c.warned=!0;var r,a,c,l=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,console&&console.warn&&console.warn(l)}return e}function l(){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 d(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},r=l.bind(n);return r.listener=i,n.wrapFn=r,r}function u(e,t,i){var n=e._events;if(void 0===n)return[];var r=n[t];return void 0===r?[]:"function"==typeof r?i?[r.listener||r]:[r]:i?function(e){for(var t=Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(r):p(r,r.length)}function h(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function p(e,t){for(var i=Array(t),n=0;n<t;++n)i[n]=e[n];return i}function m(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else if("function"==typeof e.addEventListener)e.addEventListener(t,function r(a){n.once&&e.removeEventListener(t,r),i(a)});else throw TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e)}return Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return a}
1,set:function(e){if("number"!=typeof e||e<0||n(e))throw 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||n(e))throw RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},r.prototype.getMaxListeners=function(){return o(this)},r.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r="error"===e,a=this._events;if(void 0!==a)r=r&&void 0===a.error;else if(!r)return!1;if(r){if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var s,o=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)i(c,this,t);else for(var l=c.length,d=p(c,l),n=0;n<l;++n)i(d[n],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,d(this,e,t)),this},r.prototype.prependOnceListener=function(e,t){return s(t),this.prependListener(e,d(this,e,t)),this},r.prototype.removeListener=function(e,t){var i,n,r,a,o;if(s(t),void 0===(n=this._events)||void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(r=-1,a=i.length-1;a>=0;a--)if(i[a]===t||i[a].listener===t){o=i[a].listener,r=a;break}if(r<0)return this;0===r?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,r),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0==arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0==arguments.length){var r,a=Object.keys(i);for(n=0;n<a.length;++n)"removeListener"!==(r=a[n])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},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):[]},rF.exports}(),rj=rP(rB);let rq=!0,rV=!0;function rH(e,t,i){let n=e.match(t);return n&&n.length>=i&&parseFloat(n[i],10)}function rW(e,t,i){if(!e.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,"addEventListener").writable){rK("Unable to polyfill events");return}let n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);let a=e=>{let t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,a),r.apply(this,[e,a])};let a=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t]||!this._eventMap[t].has(i))return a.apply(this,arguments);let n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,a.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function rz(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(rq=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function rG(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(rV=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function rK(){"object"!=typeof window||rq||"undefined"==typeof console||"function"!=typeof console.log||console.log.apply(console,arguments)}function rJ(e,t){rV&&console.warn(e+" is deprecated, please use "+t+" instead.")}function rQ(e){return"[object Object]"===Object.prototype.toString.call(e)}function rY(e,t,i){let n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;let a=[];
vendor: 13,516 bytes, line 1
1return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&a.push(e)}),a.forEach(t=>{e.forEach(i=>{i.type===n&&i.trackId===t.id&&function e(t,i,n){!i||n.has(i.id)||(n.set(i.id,i),Object.keys(i).forEach(r=>{r.endsWith("Id")?e(t,t.get(i[r]),n):r.endsWith("Ids")&&i[r].forEach(i=>{e(t,t.get(i),n)})}))}(e,i,r)})}),r}let rX=rK;function rZ(e,t){let i=e&&e.navigator;if(!i.mediaDevices)return;let n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;let t={};return Object.keys(e).forEach(i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;let n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);let r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),(e={})[r("max",i)]=n.ideal):e[r("",i)]=n.ideal,t.optional.push(e)}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach(e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[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){let t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let a=e.video.facingMode;a=a&&("object"==typeof a?a:{ideal:a});let s=t.version<66;if(a&&("user"===a.exact||"environment"===a.exact||"user"===a.ideal||"environment"===a.ideal)&&!(i.mediaDevices.getSupportedConstraints&&i.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 i.mediaDevices.enumerateDevices().then(i=>{let s=(i=i.filter(e=>"videoinput"===e.kind)).find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!s&&i.length&&t.includes("back")&&(s=i[i.length-1]),s&&(e.video.deviceId=a.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=n(e.video),rX("chrome: "+JSON.stringify(e)),r(e)})}e.video=n(e.video)}return rX("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(i.getUserMedia=(function(e,t,n){r(e,e=>{i.webkitGetUserMedia(e,t,e=>{n&&n(a(e))})})}).bind(i),i.mediaDevices.getUserMedia){let e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.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 r$(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function r0(e,t){if(!(t.version>102)){if("object"!=typeof e||!e.RTCPeerConnection||"ontrack"in e.RTCPeerConnection.prototype)rW(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e));else{Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.track.id):{track:i.track};let r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}),t.stream.getTracks().forEach(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.id):{track:i};let r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}}}function r1(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){let 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()};let i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};let n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);let t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}let i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};let n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{let t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function r2(e,t){if(t.version>=67||!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>rY(t,e.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),rW(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>rY(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype&&"getStats"in e.RTCRtpReceiver.prototype))return;let i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){let e,t,i;let n=arguments[0];return(this.getSenders().forEach(t=>{t.track===n&&(e?i=!0:e=t)}),this.getReceivers().forEach(e=>(e.track===n&&(t?i=!0:t=e),e.track===n)),i||e&&t)?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):e?e.getStats():t?t.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return i.apply(this,arguments)}}function r3(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};let i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")});let t=this.getSenders();i.apply(this,arguments);let n=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(n)};let n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};let r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{let i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]}),r.apply(this,arguments)}}function r4(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return r3(e);let i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[t.id]){let i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};let r=e.RTCPeerConnection.prototype.removeStream;function a(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(RegExp(r.id,"g"),n.id)}),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},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,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");let n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find(e=>e===t))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(e=>e.track===t))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let r=this._streams[i.id];if(r)r.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{let n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find(e=>e.track===t)},["createOffer","createAnswer"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){let e=arguments,t=arguments.length&&"function"==typeof arguments[0];return t?i.apply(this,[t=>{let i=a(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then(e=>a(this,e))}})[t]});let s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){var e,t;let i;return arguments.length&&arguments[0].type&&(arguments[0]=(e=this,t=arguments[0],i=t.sdp,Object.keys(e._reverseStreams||[]).forEach(t=>{let n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(RegExp(n.id,"g"),r.id)}),new RTCSessionDescription({type:t.type,sdp:i}))),s.apply(this,arguments)};let o=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){let e=o.get.apply(this);return""===e.type?e:a(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){let t;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");
1if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(e._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{},Object.keys(this._streams).forEach(i=>{this._streams[i].getTracks().find(t=>e.track===t)&&(t=this._streams[i])}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function r9(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}})[t]})}function r6(e,t){t.version>102||rW(e,"negotiationneeded",e=>{let i=e.target;if(!(t.version<72)&&(!i.getConfiguration||"plan-b"!==i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e})}var r8=Object.freeze({__proto__:null,fixNegotiationNeeded:r6,shimAddTrackRemoveTrack:r4,shimAddTrackRemoveTrackWithNative:r3,shimGetSendersWithDtmf:r1,shimGetUserMedia:rZ,shimMediaStream:r$,shimOnTrack:r0,shimPeerConnection:r9,shimSenderReceiverGetStats:r2});function r5(e,t){let i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){rJ("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){let e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(e((i=JSON.parse(JSON.stringify(i))).audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){let t=n.prototype.getSettings;n.prototype.getSettings=function(){let i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){let t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(e(i=JSON.parse(JSON.stringify(i)),"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function r7(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 ae(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){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}})[t]}))}function at(e,t){if("object"!=typeof e||!(e.RTCPeerConnection||e.mozRTCPeerConnection)||t.version>=151)return;let i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let[e,r,a]=arguments;return"closed"===this.signalingState?Promise.resolve(new Map):n.apply(this,[e||null]).then(e=>{if(t.version<53&&!r)try{e.forEach(e=>{e.type=i[e.type]||e.type})}catch(t){if("TypeError"!==t.name)throw t;e.forEach((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))})}return e}).then(r,a)}}function ai(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);
vendor: 20,549 bytes, line 1
1return e.forEach(e=>e._pc=this),e});let i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function an(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),rW(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ar(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){rJ("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function aa(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function as(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]);let i=(e=[...e]).length>0;i&&e.forEach(e=>{if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw RangeError("max_framerate must be >= 0.0")});let n=t.apply(this,arguments);if(i){let{sender:t}=n,i=t.getParameters();"encodings"in i&&(1!==i.encodings.length||0!==Object.keys(i.encodings[0]).length)||(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return n})}function ao(e){if(!("object"==typeof e&&e.RTCRtpSender))return;let t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){let e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function ac(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function al(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var ad=Object.freeze({__proto__:null,shimAddTransceiver:as,shimCreateAnswer:al,shimCreateOffer:ac,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||!e.navigator.mediaDevices||(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){let e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:ao,shimGetStats:at,shimGetUserMedia:r5,shimOnTrack:r7,shimPeerConnection:ae,shimRTCDataChannel:aa,shimReceiverGetStats:an,shimRemoveStream:ar,shimSenderGetStats:ai});function au(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)){let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(i=>t.call(this,i,e)),e.getVideoTracks().forEach(i=>t.call(this,i,e))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return n&&n.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);let t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);let i=e.getTracks();this.getSenders().forEach(e=>{i.includes(e.track)&&this.removeTrack(e)})})}}function ah(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);let t=new Event("addstream");t.stream=e,this.dispatchEvent(t)})})}});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){let e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);let i=new Event("addstream");i.stream=t,e.dispatchEvent(i)})}),t.apply(e,arguments)}}}function ap(e){if("object"!=typeof e||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,a=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){let n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){let i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};let o=function(e,t,i){let n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=o,o=function(e,t,i){let n=a.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=o,o=function(e,t,i){let n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=o}function am(e){let t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){let e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(ag(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=(function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}).bind(t))}function ag(e){return e&&void 0!==e.video?Object.assign({},e,{video:function e(t){return rQ(t)?Object.keys(t).reduce(function(i,n){let r=rQ(t[n]),a=r?e(t[n]):t[n],s=r&&!Object.keys(a).length;return void 0===a||s?i:Object.assign(i,{[n]:a})},{}):t}(e.video)}):e}function af(e){if(!e.RTCPeerConnection)return;let t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){let t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(rJ("RTCIceServer.url","RTCIceServer.urls"),(n=JSON.parse(JSON.stringify(n))).urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function av(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 ak(e){let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);let 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);let i=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function ab(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var ay=Object.freeze({__proto__:null,shimAudioContext:ab,shimCallbacksAPI:ap,shimConstraints:ag,shimCreateOfferLegacy:ak,shimGetUserMedia:am,shimLocalStreamsAPI:au,shimRTCIceServerUrls:af,shimRemoteStreamsAPI:ah,shimTrackEventTransceiver:av}),aT={exports:{}},aS=(eu||(eu=1,function(e){let t={};t.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\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){let i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){let i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter(e=>0===e.indexOf(i))},t.parseCandidate=function(e){let t;let i={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[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":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},t.writeCandidate=function(e){let t=[];t.push(e.foundation);let i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);let n=e.type;return t.push("typ"),t.push(n),"host"!==n&&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(" "),i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);let i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){let 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){let t;let i={},n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i[(t=n[e].trim().split("="))[0].trim()]=t[1];return i},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){let n=[];Object.keys(e.parameters).forEach(t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)}),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){let t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},t.parseSsrcMedia=function(e){let t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){let t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},t.getMid=function(e){let i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){let t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),i},t.parseCryptoLine=function(e){let 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;let t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){let n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.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){let i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){let a=n[r],s=t.matchPrefix(e,"a=rtpmap:"+a+" ")[0];if(s){let n=t.parseRtpMap(s),r=t.matchPrefix(e,"a=fmtp:"+a+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+a+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach(e=>{i.headerExtensions.push(t.parseExtmap(e))});let r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach(e=>{r.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" "+(i.codecs.length>0?"9":"0")+" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" "+i.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\nc=IN IP4 0.0.0.0\r\na=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach(e=>{n+=t.writeRtpMap(e)+t.writeFmtp(e)+t.writeRtcpFb(e)});let r=0;return i.codecs.forEach(e=>{e.maxptime>r&&(r=e.maxptime)}),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach(e=>{n+=t.writeExtmap(e)}),n},t.parseRtpEncodingParameters=function(e){let i;let n=[],r=t.parseRtpParameters(e),a=-1!==r.fecMechanisms.indexOf("RED"),s=-1!==r.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),c=o.length>0&&o[0].ssrc,l=t.matchPrefix(e,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));l.length>0&&l[0].length>1&&l[0][0]===c&&(i=l[0][1]),r.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&i&&(t.rtx={ssrc:i}),n.push(t),a&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:c,mechanism:s?"red+ulpfec":"red"},n.push(t))}}),0===n.length&&c&&n.push({ssrc:c});let d=t.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?950*parseInt(d[0].substring(5),10)-16e3:void 0,n.forEach(e=>{e.maxBitrate=d})),n},t.parseRtcpParameters=function(e){let i={},n=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute)[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);let r=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=0===r.length;let a=t.matchPrefix(e,"a=rtcp-mux");return i.mux=a.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;let n=t.matchPrefix(e,"a=msid:");if(1===n.length)return{stream:(i=n[0].substring(7).split(" "))[0],track:i[1]};let r=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"msid"===e.attribute);if(r.length>0)return{stream:(i=r[0].value.split(" "))[0],track:i[1]}},t.parseSctpDescription=function(e){let i;let n=t.parseMLine(e),r=t.matchPrefix(e,"a=max-message-size:");r.length>0&&(i=parseInt(r[0].substring(19),10)),isNaN(i)&&(i=65536);let a=t.matchPrefix(e,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:n.fmt,maxMessageSize:i};let s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){let e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:i}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){return"v=0\r\no="+(n||"thisisadapterortc")+" "+(e||t.generateSessionId())+" "+(void 0!==i?i:2)+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){let n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){let i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){let i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;let i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(aT)),aT.exports),aC=rP(aS),aE=(f={__proto__:null,default:aC}
1,[aS].forEach(function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach(function(t){if("default"!==t&&!(t in f)){var i=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(f,t,i.get?i:{enumerable:!0,get:function(){return e[t]}})}})}),Object.freeze(f));function aw(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;let 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){let i=new t(e),n=aC.parseCandidate(e.candidate);for(let e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,rW(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function aP(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||rW(e,"icecandidate",e=>{if(e.candidate){let t=aC.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol=({0:"tls",1:"tcp",2:"udp"})[t.priority>>24])}return e})}function aR(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}});let i=function(e){if(!e||!e.sdp)return!1;let t=aC.splitSections(e.sdp);return t.shift(),t.some(e=>{let t=aC.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")})},n=function(e){let t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return -1;let i=parseInt(t[1],10);return i!=i?-1:i},r=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i},a=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);let r=aC.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n},s=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){let{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(i(arguments[0])){let e;let t=n(arguments[0]),i=r(t),s=a(arguments[0],t);e=0===i&&0===s?Number.POSITIVE_INFINITY:0===i||0===s?Math.max(i,s):Math.min(i,s);let o={};Object.defineProperty(o,"maxMessageSize",{get:()=>e}),this._sctp=o}return s.apply(this,arguments)}}function aI(e,t){if(!(e.RTCPeerConnection&&"createDataChannel"in e.RTCPeerConnection.prototype)||"chrome"===t.browser&&t.version>149||"firefox"===t.browser&&t.version>60)return;function i(e,t){let i=e.send;e.send=function(){let n=arguments[0],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}let n=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){let e=n.apply(this,arguments);return i(e,this),e},rW(e,"datachannel",e=>(i(e.channel,e.target),e))}function aD(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;let t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return({completed:"connected",checking:"connecting"})[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}
1),["setLocalDescription","setRemoteDescription"].forEach(e=>{let i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{let t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;let i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function a_(e,t){if(!e.RTCPeerConnection||"chrome"===t.browser&&t.version>=71||"safari"===t.browser&&t._safariVersion>=13.1)return;let i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){let i=t.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==e.trim()).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function aM(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function aO(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(!(e={type:e.type,sdp:e.sdp}).type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}return e.sdp||"offer"!==e.type&&"answer"!==e.type?i.apply(this,[e]):("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>i.apply(this,[e]))})}var aA=Object.freeze({__proto__:null,removeExtmapAllowMixed:a_,shimAddIceCandidateNullOrEmpty:aM,shimConnectionState:aD,shimMaxMessageSize:aR,shimParameterlessSetLocalDescription:aO,shimRTCIceCandidate:aw,shimRTCIceCandidateRelayProtocol:aP,shimSendThrowTypeError:aI});!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},i=rK,n=function(e){let t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;let{navigator:i}=e;if(i.userAgentData&&i.userAgentData.brands){let e=i.userAgentData.brands.find(e=>"Chromium"===e.brand);if(e)return{browser:"chrome",version:parseInt(e.version,10)}}return i.mozGetUserMedia?(t.browser="firefox",t.version=parseInt(rH(i.userAgent,/Firefox\/(\d+)\./,1))):i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection?(t.browser="chrome",t.version=parseInt(rH(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null):e.RTCPeerConnection&&i.userAgent.match(/AppleWebKit\/(\d+)\./)?(t.browser="safari",t.version=parseInt(rH(i.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=rH(i.userAgent,/Version\/(\d+(\.?\d+))/,1)):t.browser="Not a supported browser.",t}(e),r={browserDetails:n,commonShim:aA,extractVersion:rH,disableLog:rz,disableWarnings:rG,sdp:aE};switch(n.browser){case"chrome":if(!r8||!r9||!t.shimChrome){i("Chrome shim is not included in this adapter release.");break}if(null===n.version){i("Chrome shim can not determine version, not shimming.");break}i("adapter.js shimming chrome."),r.browserShim=r8,aM(e,n),aO(e),rZ(e,n),r$(e),r9(e,n),r0(e,n),r4(e,n),r1(e),r2(e,n),r6(e,n),aw(e),aP(e),aD(e),aR(e,n),aI(e,n),a_(e,n);break;case"firefox":if(!ad||!ae||!t.shimFirefox){i("Firefox shim is not included in this adapter release.");break}i("adapter.js shimming firefox."),r.browserShim=ad,aM(e,n),aO(e),r5(e,n),ae(e,n),at(e,n),r7(e),ar(e),ai(e),an(e),aa(e),as(e),ao(e),ac(e),al(e),aw(e),aD(e),aR(e,n),aI(e,n);break;case"safari":if(!ay||!t.shimSafari){i("Safari shim is not included in this adapter release.");break}
1i("adapter.js shimming safari."),r.browserShim=ay,aM(e,n),aO(e),af(e),ak(e),ap(e),au(e),ah(e),av(e),am(e),ab(e),aw(e),aP(e),aR(e,n),aI(e,n),a_(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});class aN extends(eh=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)}}aN.resolve=e=>Reflect.get(eh,"resolve",aN).call(aN,e);let ax=/version\/(\d+(\.?_?\d+)+)/i;function aL(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;let i=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===n||t){let e=aU.find(e=>{let{test:t}=e;return t.test(i)});n=null==e?void 0:e.describe(i)}return n}let aU=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:aF(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:aB(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:aF(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:aB(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:aF(ax,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:aB(e)})}];function aF(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=t.match(e);return n&&n.length>=i&&n[i]||""}function aB(e){return e.includes("mac os")?aF(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class aj extends Error{constructor(e,t,i){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,void 0!==(null==i?void 0:i.cause)&&(this.cause=null==i?void 0:i.cause)}}class aq extends aj{}(v=ep||(ep={}))[v.NotAllowed=0]="NotAllowed",v[v.ServerUnreachable=1]="ServerUnreachable",v[v.InternalError=2]="InternalError",v[v.Cancelled=3]="Cancelled",v[v.LeaveRequest=4]="LeaveRequest",v[v.Timeout=5]="Timeout",v[v.WebSocket=6]="WebSocket",v[v.ServiceNotFound=7]="ServiceNotFound";class aV extends aq{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=ep[t]}static notAllowed(e,t,i){return new aV(e,ep.NotAllowed,t,i)}static timeout(e){return new aV(e,ep.Timeout)}static leaveRequest(e,t){return new aV(e,ep.LeaveRequest,void 0,t)}static internal(e,t){return new aV(e,ep.InternalError,void 0,t)}static cancelled(e){return new aV(e,ep.Cancelled)}static serverUnreachable(e,t){return new aV(e,ep.ServerUnreachable,t)}static websocket(e,t,i){return new aV(e,ep.WebSocket,t,i)}static serviceNotFound(e,t){return new aV(e,ep.ServiceNotFound,void 0,t)}}class aH extends aj{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class aW extends aj{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class az extends aj{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class aG extends aj{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class aK extends aj{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class aJ extends aj{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class aQ extends aq{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName="string"==typeof t?t:rb[t]}}(k=em||(em={}))[k.AlreadyOpened=0]="AlreadyOpened",k[k.AbnormalEnd=1]="AbnormalEnd",k[k.DecodeFailed=2]="DecodeFailed",k[k.LengthExceeded=3]="LengthExceeded",k[k.Incomplete=4]="Incomplete",k[k.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",k[k.EncryptionTypeMismatch=8]="EncryptionTypeMismatch";class aY extends aq{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=em[t]}}class aX extends aj{constructor(e){super(18,e),this.name="SignalReconnectError"}}(b=eg||(eg={})).PermissionDenied="PermissionDenied",b.NotFound="NotFound",b.DeviceInUse="DeviceInUse",b.Other="Other",(y=eg||(eg={})).getFailure=function(e){if(e&&"name"in e)return"NotFoundError"===e.name||"DevicesNotFoundError"===e.name?y.NotFound:"NotAllowedError"===e.name||"PermissionDeniedError"===e.name?y.PermissionDenied:"NotReadableError"===e.name||"TrackStartError"===e.name?y.DeviceInUse:y.Other};class aZ{}aZ.setTimeout=function(){return setTimeout(...arguments)},aZ.setInterval=function(){return setInterval(...arguments)},aZ.clearTimeout=function(){return clearTimeout(...arguments)},aZ.clearInterval=function(){return clearInterval(...arguments)},(T=ef||(ef={})).Connected="connected",T.Reconnecting="reconnecting",T.SignalReconnecting="signalReconnecting",T.Reconnected="reconnected",T.Disconnected="disconnected",T.ConnectionStateChanged="connectionStateChanged",T.Moved="moved",T.MediaDevicesChanged="mediaDevicesChanged",T.ParticipantConnected="participantConnected",T.ParticipantDisconnected="participantDisconnected",T.TrackPublished="trackPublished",T.TrackSubscribed="trackSubscribed",T.TrackSubscriptionFailed="trackSubscriptionFailed",T.TrackUnpublished="trackUnpublished",T.TrackUnsubscribed="trackUnsubscribed",T.TrackMuted="trackMuted",T.TrackUnmuted="trackUnmuted",T.LocalTrackPublished="localTrackPublished",T.LocalTrackUnpublished="localTrackUnpublished",T.LocalAudioSilenceDetected="localAudioSilenceDetected",T.ActiveSpeakersChanged="activeSpeakersChanged",T.ParticipantMetadataChanged="participantMetadataChanged",T.ParticipantNameChanged="participantNameChanged",T.ParticipantAttributesChanged="participantAttributesChanged",T.ParticipantActive="participantActive",T.RoomMetadataChanged="roomMetadataChanged",T.DataReceived="dataReceived",T.SipDTMFReceived="sipDTMFReceived",T.TranscriptionReceived="transcriptionReceived",T.ConnectionQualityChanged="connectionQualityChanged",T.TrackStreamStateChanged="trackStreamStateChanged",T.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",T.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",T.AudioPlaybackStatusChanged="audioPlaybackChanged",T.VideoPlaybackStatusChanged="videoPlaybackChanged",T.MediaDevicesError="mediaDevicesError",T.ParticipantPermissionsChanged="participantPermissionsChanged",T.SignalConnected="signalConnected",T.RecordingStatusChanged="recordingStatusChanged",T.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",T.EncryptionError="encryptionError",T.DCBufferStatusChanged="dcBufferStatusChanged",T.ActiveDeviceChanged="activeDeviceChanged",T.ChatMessage="chatMessage",T.LocalTrackSubscribed="localTrackSubscribed",T.MetricsReceived="metricsReceived",T.DataTrackPublished="dataTrackPublished",T.DataTrackUnpublished="dataTrackUnpublished",T.LocalDataTrackPublished="localDataTrackPublished",T.LocalDataTrackUnpublished="localDataTrackUnpublished",(S=ev||(ev={})).TrackPublished="trackPublished",S.TrackSubscribed="trackSubscribed",S.TrackSubscriptionFailed="trackSubscriptionFailed",S.TrackUnpublished="trackUnpublished",S.TrackUnsubscribed="trackUnsubscribed",S.TrackMuted="trackMuted",S.TrackUnmuted="trackUnmuted",S.LocalTrackPublished="localTrackPublished",S.LocalTrackUnpublished="localTrackUnpublished",S.LocalTrackCpuConstrained="localTrackCpuConstrained",S.LocalSenderCreated="localSenderCreated",S.ParticipantMetadataChanged="participantMetadataChanged",S.ParticipantNameChanged="participantNameChanged",S.DataReceived="dataReceived",S.SipDTMFReceived="sipDTMFReceived",S.TranscriptionReceived="transcriptionReceived",S.IsSpeakingChanged="isSpeakingChanged",S.ConnectionQualityChanged="connectionQualityChanged",S.TrackStreamStateChanged="trackStreamStateChanged",S.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",S.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",S.TrackCpuConstrained="trackCpuConstrained",S.MediaDevicesError="mediaDevicesError",S.AudioStreamAcquired="audioStreamAcquired",S.ParticipantPermissionsChanged="participantPermissionsChanged",S.PCTrackAdded="pcTrackAdded",S.AttributesChanged="attributesChanged",S.LocalTrackSubscribed="localTrackSubscribed",S.ChatMessage="chatMessage",S.Active="active",(C=ek||(ek={})).TransportsCreated="transportsCreated",C.Connected="connected",C.Disconnected="disconnected",C.Resuming="resuming",C.Resumed="resumed",C.Restarting="restarting",C.Restarted="restarted",C.SignalResumed="signalResumed",C.SignalRestarted="signalRestarted",C.Closing="closing",C.MediaTrackAdded="mediaTrackAdded",C.ActiveSpeakersUpdate="activeSpeakersUpdate",C.DataPacketReceived="dataPacketReceived",C.RTPVideoMapUpdate="rtpVideoMapUpdate",C.DCBufferStatusChanged="dcBufferStatusChanged",C.ParticipantUpdate="participantUpdate",C.RoomUpdate="roomUpdate",C.SpeakersChanged="speakersChanged",C.StreamStateChanged="streamStateChanged",C.ConnectionQualityUpdate="connectionQualityUpdate",C.SubscriptionError="subscriptionError",C.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",C.RemoteMute="remoteMute",C.SubscribedQualityUpdate="subscribedQualityUpdate",C.LocalTrackUnpublished="localTrackUnpublished",C.LocalTrackSubscribed="localTrackSubscribed",C.Offline="offline",C.SignalRequestResponse="signalRequestResponse",C.SignalConnected="signalConnected",C.RoomMoved="roomMoved",C.PublishDataTrackResponse="publishDataTrackResponse",C.UnPublishDataTrackResponse="unPublishDataTrackResponse",C.DataTrackSubscriberHandles="dataTrackSubscriberHandles",C.DataTrackPacketReceived="dataTrackPacketReceived",C.Joined="joined",C.TokenRefreshed="tokenRefreshed",C.ServerRegionsReported="serverRegionsReported",(E=eb||(eb={})).Message="message",E.Muted="muted",E.Unmuted="unmuted",E.Restarted="restarted",E.Ended="ended",E.Subscribed="subscribed",E.Unsubscribed="unsubscribed",E.CpuConstrained="cpuConstrained",E.UpdateSettings="updateSettings",E.UpdateSubscription="updateSubscription",E.AudioPlaybackStarted="audioPlaybackStarted",E.AudioPlaybackFailed="audioPlaybackFailed",E.AudioSilenceDetected="audioSilenceDetected",E.VisibilityChanged="visibilityChanged",E.VideoDimensionsChanged="videoDimensionsChanged",E.VideoPlaybackStarted="videoPlaybackStarted",E.VideoPlaybackFailed="videoPlaybackFailed",E.ElementAttached="elementAttached",E.ElementDetached="elementDetached",E.UpstreamPaused="upstreamPaused",E.UpstreamResumed="upstreamResumed",E.SubscriptionPermissionChanged="subscriptionPermissionChanged",E.SubscriptionStatusChanged="subscriptionStatusChanged",E.SubscriptionFailed="subscriptionFailed",E.TrackProcessorUpdate="trackProcessorUpdate",E.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",E.TranscriptionReceived="transcriptionReceived",E.TimeSyncUpdate="timeSyncUpdate",E.PreConnectBufferFlushed="preConnectBufferFlushed";class a${constructor(e,t,i,n,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!==i)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:n,priority:r};else throw TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}let a0=["vp8","h264"],a1=["vp8","h264","vp9","av1","h265"];function a2(e){return!!a0.find(t=>t===e)}(w=ey||(ey={}))[w.PREFER_REGRESSION=0]="PREFER_REGRESSION",w[w.SIMULCAST=1]="SIMULCAST",w[w.REGRESSION=2]="REGRESSION",(P=eT||(eT={})).telephone={maxBitrate:12e3}
1,P.speech={maxBitrate:24e3},P.music={maxBitrate:48e3},P.musicStereo={maxBitrate:64e3},P.musicHighQuality={maxBitrate:96e3},P.musicHighQualityStereo={maxBitrate:128e3};let a3={h90:new a$(160,90,9e4,20),h180:new a$(320,180,16e4,20),h216:new a$(384,216,18e4,20),h360:new a$(640,360,45e4,20),h540:new a$(960,540,8e5,25),h720:new a$(1280,720,17e5,30),h1080:new a$(1920,1080,3e6,30),h1440:new a$(2560,1440,5e6,30),h2160:new a$(3840,2160,8e6,30)},a4={h120:new a$(160,120,7e4,20),h180:new a$(240,180,125e3,20),h240:new a$(320,240,14e4,20),h360:new a$(480,360,33e4,20),h480:new a$(640,480,5e5,20),h540:new a$(720,540,6e5,25),h720:new a$(960,720,13e5,30),h1080:new a$(1440,1080,23e5,30),h1440:new a$(1920,1440,38e5,30)},a9={h360fps3:new a$(640,360,2e5,3,"medium"),h360fps15:new a$(640,360,4e5,15,"medium"),h720fps5:new a$(1280,720,8e5,5,"medium"),h720fps15:new a$(1280,720,15e5,15,"medium"),h720fps30:new a$(1280,720,2e6,30,"medium"),h1080fps15:new a$(1920,1080,25e5,15,"medium"),h1080fps30:new a$(1920,1080,5e6,30,"medium"),original:new a$(0,0,7e6,30,"medium")};function a6(e,t,i){var n,r,a,s;let{optionsWithoutProcessor:o,audioProcessor:c,videoProcessor:l}=sn(null!=e?e:{}),d=null==t?void 0:t.processor,u=null==i?void 0:i.processor,h=null!=o?o:{};return!0===h.audio&&(h.audio={}),!0===h.video&&(h.video={}),h.audio&&(a8(h.audio,t),null!==(n=(a=h.audio).deviceId)&&void 0!==n||(a.deviceId={ideal:"default"}),(c||d)&&(h.audio.processor=null!=c?c:d)),h.video&&(a8(h.video,i),null!==(r=(s=h.video).deviceId)&&void 0!==r||(s.deviceId={ideal:"default"}),(l||u)&&(h.video.processor=null!=l?l:u)),h}function a8(e,t){return Object.keys(t).forEach(i=>{void 0===e[i]&&(e[i]=t[i])}),e}function a5(e){var t,i,n,r;let a={};if(e.video){if("object"==typeof e.video){let i={},r=e.video;Object.keys(r).forEach(e=>{"resolution"===e?a8(i,r.resolution):i[e]=r[e]}),a.video=i,null!==(t=(n=a.video).deviceId)&&void 0!==t||(n.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!==(i=(r=a.audio).deviceId)&&void 0!==i||(r.deviceId={ideal:"default"})):a.audio={deviceId:{ideal:"default"}}:a.audio=!1,a}function a7(){var e;let t="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){let i=new t({latencyHint:"interactive"});if("suspended"===i.state&&"undefined"!=typeof window&&(null===(e=window.document)||void 0===e?void 0:e.body)){let e=()=>rx(this,void 0,void 0,function*(){var t;try{"suspended"===i.state&&(yield i.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)}});i.addEventListener("statechange",()=>{var t;"closed"===i.state&&(null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e))}),window.document.body.addEventListener("click",e)}return i}}function se(e){return e===ss.Source.Microphone?"audioinput":e===ss.Source.Camera?"videoinput":void 0}function st(e){return e.split("/")[1].toLowerCase()}function si(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?si(e.track):{})}}function sn(e){let t,i;let n=Object.assign({},e);return"object"==typeof n.audio&&n.audio.processor&&(t=n.audio.processor,n.audio=Object.assign(Object.assign({},n.audio),{processor:void 0})),"object"==typeof n.video&&n.video.processor&&(i=n.video.processor,n.video=Object.assign(Object.assign({},n.video),{processor:void 0})),{audioProcessor:t,videoProcessor:i,optionsWithoutProcessor:void 0===n?n:"function"!=typeof structuredClone?JSON.parse(JSON.stringify(n)):"object"==typeof n&&null!==n?structuredClone(Object.assign({},n)):structuredClone(n)}}function sr(e,t){return e.width*e.height<t.width*t.height}let sa=[];(R=eS||(eS={}))[R.LOW=0]="LOW",R[R.MEDIUM=1]="MEDIUM",R[R.HIGH=2]="HIGH";class ss extends rB.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){var i;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.attachedElements=[],this.isMuted=!1,this._streamState=ss.StreamState.Active,this.isInBackgroun
1d=!1,this._currentBitrate=0,this.log=r_,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),5e3):this.handleAppVisibilityChanged()},this.log=rM(null!==(i=n.loggerName)&&void 0!==i?i:el.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=ss.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),si(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===ss.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===ss.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(sa.forEach(t=>{null!==t.parentElement||e||(e=t)}),e&&sa.splice(sa.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),so(this.mediaStreamTrack,e);let i=e.srcObject.getTracks(),n=i.some(e=>"audio"===e.kind);return e.play().then(()=>{this.emit(n?eb.AudioPlaybackStarted:eb.VideoPlaybackStarted)}).catch(t=>{"NotAllowedError"===t.name?this.emit(n?eb.AudioPlaybackFailed:eb.VideoPlaybackFailed,t):"AbortError"===t.name?r_.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):r_.warn("could not playback ".concat(n?"audio":"video"),t),n&&e&&i.some(e=>"video"===e.kind)&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(eb.ElementAttached,e),e}detach(e){try{if(e){sc(this.mediaStreamTrack,e);let t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(eb.ElementDetached,e)),e}let t=[];return this.attachedElements.forEach(e=>{sc(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(eb.ElementDetached,e)}),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=rM(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),sa.forEach(e=>{e.parentElement||(t=!1)}),t&&sa.push(e)}}handleAppVisibilityChanged(){return rx(this,void 0,void 0,function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==ss.Kind.Video||setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){sy()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){sy()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function so(e,t){let i,n;t.srcObject instanceof MediaStream?i=t.srcObject:i=new MediaStream,(n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks()).includes(e)||(n.forEach(e=>{i.removeTrack(e)}),i.addTrack(e)),sv()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(sv()||sg())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=i,t.play().catch(()=>{})},0))}function sc(e,t){if(t.srcObject instanceof MediaStream){let i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}(D=a=(I=ss||(ss={})).Kind||(I.Kind={})).Audio="audio",D.Video="video",D.Unknown="unknown",(_=s=I.Source||(I.Source={})).Camera="camera",_.Microphone="microphone",_.ScreenShare="screen_share",_.ScreenShareAudio="screen_share_audio",_.Unknown="unknown",(M=o=I.StreamState||(I.StreamState={})).Active="active",M.Paused="paused",M.Unknown="unknown",I.kindToProto=function(e){switch(e){case a.Audio:return il.AUDIO;case a.Video:return il.VIDEO;default:return il.DATA}},I.kindFromProto=function(e){switch(e){case il.AUDIO:return a.Audio;case il.VIDEO:return a.Video;default:return a.Unknown}},I.sourceToProto=function(e){switch(e){case s.Camera:return id.CAMERA;case s.Microphone:return id.MICROPHONE;case s.ScreenShare:return id.SCREEN_SHARE;case s.ScreenShareAudio:return id.SCREEN_SHARE_AUDIO;default:return id.UNKNOWN}},I.sourceFromProto=function(e){switch(e){case id.CAMERA:return s.Camera;case id.MICROPHONE:return s.Microphone;case id.SCREEN_SHARE:return s.ScreenShare;case id.SCREEN_SHARE_AUDIO:return s.ScreenShareAudio;default:return s.Unknown}},I.streamStateFromProto=function(e){switch(e){case nI.ACTIVE:return o.Active;case nI.PAUSED:return o.Paused;default:return o.Unknown}};let sl="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function sd(e){return new aN(t=>aZ.setTimeout(t,e))}function su(){return"addTransceiver"in RTCPeerConnection.prototype}function sh(){return"addTrack"in RTCPeerConnection.prototype}function sp(e){return"av1"===e||"vp9"===e}function sm(e){return!(!document||sk())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function sg(){var e;return(null===(e=aL())||void 0===e?void 0:e.name)==="Firefox"}function sf(){return"undefined"!=typeof window&&void 0!==window.RTCRtpScriptTransform&&!function(){let e=aL();return!!e&&"Chrome"===e.name&&"iOS"!==e.os}()}function sv(){var e;return(null===(e=aL())||void 0===e?void 0:e.name)==="Safari"}function sk(){let e=aL();return(null==e?void 0:e.name)==="Safari"||(null==e?void 0:e.os)==="iOS"}
1function sb(){var e,t;return!!sy()&&(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 sy(){return"undefined"!=typeof document}function sT(){return"ReactNative"==navigator.product}function sS(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function sC(e){return sS(e)?e.hostname.split(".")[0]:null}function sE(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function sw(){if(!sT())return;let e=sE();if(e)return e.platform}function sP(){if(sy())return window.devicePixelRatio;if(sT()){let e=sE();if(e)return e.devicePixelRatio}return 1}function sR(e,t){let i=e.split("."),n=t.split("."),r=Math.min(i.length,n.length);for(let e=0;e<r;++e){let t=parseInt(i[e],10),a=parseInt(n[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:i.length==n.length?0:i.length<n.length?-1:1}function sI(e){for(let t of e)t.target.handleResize(t)}function sD(e){for(let t of e)t.target.handleVisibilityChanged(t)}let s_=null,sM=()=>(s_||(s_=new ResizeObserver(sI)),s_),sO=null,sA=()=>(sO||(sO=new IntersectionObserver(sD,{root:null,rootMargin:"0px"})),sO);function sN(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=document.createElement("canvas");r.width=e,r.height=t;let a=r.getContext("2d");null==a||a.fillRect(0,0,r.width,r.height),n&&a&&(a.beginPath(),a.arc(e/2,t/2,50,0,2*Math.PI,!0),a.closePath(),a.fillStyle="grey",a.fill());let[s]=r.captureStream().getTracks();if(!s)throw Error("Could not get empty media stream video track");return s.enabled=i,s}function sx(){if(!r){let e=new AudioContext,t=e.createOscillator(),i=e.createGain();i.gain.setValueAtTime(0,0);let n=e.createMediaStreamDestination();if(t.connect(i),i.connect(n),t.start(),[r]=n.stream.getAudioTracks(),!r)throw Error("Could not get empty media stream audio track");r.enabled=!1}return r.clone()}class sL{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,i)=>rx(this,void 0,void 0,function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})).finally(()=>{var e;this._isResolved=!0,null===(e=this.onFinally)||void 0===e||e.call(this)})}}function sU(e,t){let i=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),n=a7();if(!n)throw Error("Audio Context not supported on this browser");let r=i.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,a=n.createMediaStreamSource(new MediaStream([r])),s=n.createAnalyser();s.minDecibels=i.minDecibels,s.maxDecibels=i.maxDecibels,s.fftSize=i.fftSize,s.smoothingTimeConstant=i.smoothingTimeConstant,a.connect(s);let o=new Uint8Array(s.frequencyBinCount);return{calculateVolume:()=>{s.getByteFrequencyData(o);let e=0;for(let t of o)e+=Math.pow(t/255,2);return Math.sqrt(e/o.length)},analyser:s,cleanup:()=>rx(this,void 0,void 0,function*(){yield n.close(),i.cloneTrack&&r.stop()})}}function sF(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 sB(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function sj(e){switch(e.reason){case ep.LeaveRequest:return e.context;case ep.Cancelled:return im.CLIENT_INITIATED;case ep.NotAllowed:return im.USER_REJECTED;case ep.ServerUnreachable:return im.JOIN_FAILURE;default:return im.UNKNOWN_REASON}}function sq(e){return void 0!==e?Number(e):void 0}function sV(e){return void 0!==e?BigInt(e):void 0}function sH(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function sW(e){return!!e&&e.kind==ss.Kind.Audio}function sz(e){return!!e&&e.kind==ss.Kind.Video}function sG(e){return sH(e)&&sz(e)}function sK(e){return sH(e)&&sW(e)}function sJ(e){return!!e&&!e.isLocal}function sQ(e){return sJ(e)&&sz(e)}function sY(){return"undefined"!=typeof CompressionStream}function sX(e){return e.endsWith("/")?e:"".concat(e,"/")}function sZ(e,t){return e.pathname="".concat(sX(e.pathname)).concat(t),e}function s$(e){if("string"==typeof e)return nM.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return nM.fromBinary(new Uint8Array(e));throw Error("could not decode websocket message: ".concat(typeof e))}let s0="lk_e2ee";function s1(){return"undefined"!=typeof window&&void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams}function s2(e){return!!(null==e?void 0:e.worker)&&(s1()||sf())}function s3(e){return!!((null==e?void 0:e.timestamp)||(null==e?void 0:e.frameId))}function s4(e){var t,i;let n,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=null!==(t=a.isImmediate)&&void 0!==t&&t,o=null!==(i=a.callback)&&void 0!==i&&i,c=a.maxWait,l=Date.now(),d=[],u=function(){for(var t=arguments.length,i=Array(t),a=0;a<t;a++)i[a]=arguments[a];let u=this;return new Promise((t,a)=>{let h=s&&void 0===n;if(void 0!==n&&aZ.clearTimeout(n),n=aZ.setTimeout(function(){if(n=void 0,l=Date.now(),!s){let t=e.apply(u,i);
1o&&o(t),d.forEach(e=>{let{resolve:i}=e;return i(t)}),d=[]}},function(){if(void 0!==c){let e=Date.now()-l;if(e+r>=c)return c-e}return r}()),h){let n=e.apply(u,i);return o&&o(n),t(n)}d.push({resolve:t,reject:a})})};return u.cancel=function(e){void 0!==n&&aZ.clearTimeout(n),d.forEach(t=>{let{reject:i}=t;return i(e)}),d=[]},u}function s9(e,t){let i,n;return t?("bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp)?0:(i-n)*8e3/(e.timestamp-t.timestamp):0}(O=eC||(eC={})).SetKey="setKey",O.RatchetRequest="ratchetRequest",O.KeyRatcheted="keyRatcheted",(eE||(eE={})).KeyRatcheted="keyRatcheted",(A=ew||(ew={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",A.EncryptionError="encryptionError",(eP||(eP={})).Error="cryptorError",(N=eR||(eR={}))[N.InvalidKey=0]="InvalidKey",N[N.MissingKey=1]="MissingKey",N[N.InternalError=2]="InternalError";class s6 extends ss{constructor(e,t,i,n,r){super(e,i,r),this.sid=t,this.receiver=n}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?eb.Muted:eb.Unmuted,this))}setMediaStream(e){this.mediaStream=e;let t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(eb.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return rx(this,void 0,void 0,function*(){var e;if(null===(e=this.receiver)||void 0===e?void 0:e.getStats)return yield this.receiver.getStats()})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),2e3)),"undefined"!=typeof RTCRtpReceiver&&"function"==typeof RTCRtpReceiver.prototype.getSynchronizationSources&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){let e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());let i=null===(t=this.receiver)||void 0===t?void 0:t.getSynchronizationSources()[0];if(i){let{timestamp:e,rtpTimestamp:t}=i;
1t&&this.rtpTimestamp!==t&&(this.emit(eb.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class s8 extends s6{constructor(e,t,i,n,r){super(e,t,ss.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>rx(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=s9(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=s4(()=>{this.updateDimensions()},100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}lookupFrameMetadata(e){var t;let{rtpTimestamp:i}=e;return null===(t=this.packetTrailerExtractor)||void 0===t?void 0:t.lookupMetadata(i)}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===ss.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?sc(this._mediaStreamTrack,t):so(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t.element===e)){let t=new s5(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){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}for(let t of this.elementInfos.filter(t=>t===e))t.stopObserving();this.elementInfos=this.elementInfos.filter(t=>t!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){if(e)return this.stopObservingElement(e),super.detach(e);let t=super.detach();for(let 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 rx(this,void 0,void 0,function*(){let e;if(!this.receiver||!this.receiver.getStats)return;let t=yield this.receiver.getStats(),i="",n=new Map;return t.forEach(t=>{"inbound-rtp"===t.type?(i=t.codecId,e={type:"video",streamId:t.id,framesDecoded:t.framesDecoded,framesDropped:t.framesDropped,framesReceived:t.framesReceived,packetsReceived:t.packetsReceived,packetsLost:t.packetsLost,frameWidth:t.frameWidth,frameHeight:t.frameHeight,pliCount:t.pliCount,firCount:t.firCount,nackCount:t.nackCount,jitter:t.jitter,timestamp:t.timestamp,bytesReceived:t.bytesReceived,decoderImplementation:t.decoderImplementation}):"codec"===t.type&&n.set(t.id,t)}),e&&""!==i&&n.get(i)&&(e.mimeType=n.get(i).mimeType),e})}stopObservingElement(e){for(let t of this.elementInfos.filter(t=>t.element===e))this.stopObservingElementInfo(t)}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return rx(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;let n=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),r=(null===(i=null===(t=this.adaptiveStreamSettings)||void 0===t?void 0:t.pauseVideoInBackground)||void 0===i||!!i)&&this.isInBackground,a=this.elementInfos.some(e=>e.pictureInPicture),s=this.elementInfos.some(e=>e.visible)&&!r||a;if(this.lastVisible!==s||e){if(!s&&Date.now()-n<100){aZ.setTimeout(()=>{this.updateVisibility()},100);return}this.lastVisible=s,this.emit(eb.VisibilityChanged,s,this)}}updateDimensions(){var e,t;let i=0,n=0,r=this.getPixelDensity();for(let e of this.elementInfos){let t=e.width()*r,a=e.height()*r;t+a>i+n&&(i=t,n=a)}((null===(e=this.lastDimensions)||void 0===e?void 0:e.width)!==i||(null===(t=this.lastDimensions)||void 0===t?void 0:t.height)!==n)&&(this.lastDimensions={width:i,height:n}
1,this.emit(eb.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;let t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;return"screen"===t?sP():t||(sP()>2?2:1)}}class s5{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;let{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.isPiP=s7(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=s7(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)})})},this.onLeavePiP=()=>{var e;this.isPiP=s7(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:oe(e),this.isPiP=sy()&&s7(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=oe(this.element),this.isPiP=s7(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,sA().observe(this.element),sM().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null===(e=window.documentPictureInPicture)||void 0===e||e.addEventListener("enter",this.onEnterPiP),null===(i=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===i||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,n,r;null===(e=sA())||void 0===e||e.unobserve(this.element),null===(t=sM())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(i=window.documentPictureInPicture)||void 0===i||i.removeEventListener("enter",this.onEnterPiP),null===(r=null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)||void 0===r||r.removeEventListener("pagehide",this.onLeavePiP)}}function s7(e){var t,i;return document.pictureInPictureElement===e||null!==(t=window.documentPictureInPicture)&&void 0!==t&&!!t.window&&oe(e,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function oe(e,t){let i=t||window,n=e.offsetTop,r=e.offsetLeft,a=e.offsetWidth,s=e.offsetHeight,{hidden:o}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,r+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&r<i.pageXOffset+i.innerWidth&&n+s>i.pageYOffset&&r+a>i.pageXOffset&&!o&&"none"!==c}class ot extends rB.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=e=>{var t,i;let{kind:n,data:r}=e.data;switch(n){case"error":if(r_.error(r.error.message),r.uuid){let e=this.decryptDataRequests.get(r.uuid);if(null==e?void 0:e.reject){e.reject(r.error);break}let t=this.encryptDataRequests.get(r.uuid);if(null==t?void 0:t.reject){t.reject(r.error);break}}this.emit(ew.EncryptionError,r.error,r.participantIdentity);break;case"initAck":r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)});break;case"enable":if(r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)}),this.encryptionEnabled!==r.enabled&&r.participantIdentity===(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))this.emit(ew.ParticipantEncryptionStatusChanged,r.enabled,this.room.localParticipant),this.encryptionEnabled=r.enabled;else if(r.participantIdentity){let e=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(r.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(r.participantIdentity));
1this.emit(ew.ParticipantEncryptionStatusChanged,r.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(eC.KeyRatcheted,r.ratchetResult,r.participantIdentity,r.keyIndex);break;case"decryptDataResponse":let a=this.decryptDataRequests.get(r.uuid);(null==a?void 0:a.resolve)&&a.resolve(r);break;case"encryptDataResponse":let s=this.encryptDataRequests.get(r.uuid);(null==s?void 0:s.resolve)&&s.resolve(r);break;case"packetTrailerMetadata":this.handlePacketTrailerMetadata(r.trackId,r.rtpTimestamp,r.ssrc,r.metadata)}},this.onWorkerError=e=>{r_.error("e2ee worker encountered an error:",{error:e.error}),this.emit(ew.EncryptionError,e.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!(s1()||"undefined"!=typeof window&&void 0!==window.RTCRtpScriptTransform))throw new aH("tried to setup end-to-end encryption on an unsupported browser");if(r_.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);let t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:rO.getLevel()}};this.worker&&(r_.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){r_.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):r_.warn("ignoring server sent trailer as it's empty")}handlePacketTrailerMetadata(e,t,i,n){if(this.room){for(let r of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(let a of r.trackPublications.values())if(a.track&&a.track.mediaStreamID===e&&a.track instanceof s8&&a.track.packetTrailerExtractor){a.track.packetTrailerExtractor.storeMetadata(t,i,n);return}}}setupEngine(e){e.on(ek.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(ef.TrackPublished,(e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==iR.NONE,t.identity)),e.on(ef.ConnectionStateChanged,t=>
1{t===eX.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==iR.NONE,e.identity)})})}).on(ef.TrackUnsubscribed,(e,t,i)=>{var n;let r={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(r)}).on(ef.TrackSubscribed,(e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)}).on(ef.SignalConnected,()=>{if(!this.room)throw TypeError("expected room to be present on signal connect");let e=t.getLatestManuallySetKeyIndex();t.getKeys().forEach(t=>{var i;this.postKey(t,e===(null!==(i=t.keyIndex)&&void 0!==i?i:0))}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(ev.LocalSenderCreated,(e,t)=>rx(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),e.localParticipant.on(ev.LocalTrackPublished,e=>{if(!sz(e.track)||!sk())return;let t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:st(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1}};this.worker.postMessage(t)}),t.on(eC.SetKey,(e,t)=>this.postKey(e,null==t||t)).on(eC.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}encryptData(e){return rx(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");let t=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},n=new sL;return n.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,n),this.worker.postMessage(i),n.promise})}handleEncryptedData(e,t,i,n){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");let r=crypto.randomUUID(),a=new sL;return a.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,a),this.worker.postMessage({kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:i,keyIndex:n}}),a.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");this.worker.postMessage({kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}})}postKey(e,t){var i;let{key:n,participantIdentity:r,keyIndex:a}=e;if(!this.worker)throw Error("could not set key, worker is missing");let s={kind:"setKey",data:{participantIdentity:r,isPublisher:r===(null===(i=this.room)||void 0===i?void 0:i.localParticipant.identity),key:n,keyIndex:a,updateCurrentKeyIndex:t}};this.worker.postMessage(s)}postEnable(e,t){if(this.worker)this.worker.postMessage({kind:"enable",data:{enabled:e,participantIdentity:t}});else throw ReferenceError("failed to enable e2ee, worker is not ready")}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");let i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");this.worker.postMessage({kind:"setSifTrailer",data:{trailer:e}})}setupE2EEReceiver(e,t,i){if(!e.receiver)return;if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");let n="video"===e.kind&&!!i.packetTrailerFeatures&&i.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?st(i.mimeType):void 0,n)}setupE2EESender(e,t){var i;if(!sH(e)||!t){t||r_.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0,sz(e)?null===(i=e.publishOptions)||void 0===i?void 0:i.packetTrailer:void 0)}handleReceiver(e,t,i,n,r){return rx(this,void 0,void 0,function*(){if(this.worker){if(sf())e.transform=new RTCRtpScriptTransform(this.worker,{kind:"decode",participantIdentity:i,trackId:t,codec:n,hasPacketTrailer:r});else{if(s0 in e&&n){this.worker.postMessage({kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i,hasPacketTrailer:r}});return}let a=e.writableStream,s=e.readableStream;if(!a||!s){let t=e.createEncodedStreams();e.writableStream=t.writable,a=t.writable,e.readableStream=t.readable,s=t.readable}let o={kind:"decode",data:{readableStream:s,writableStream:a,trackId:t,codec:n,participantIdentity:i,isReuse:s0 in e,hasPacketTrailer:r}};this.worker.postMessage(o,[s,a])}e[s0]=!0}})}handleSender(e,t,i,n){var r;if(!(s0 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(sf()){r_.info("initialize script transform");let r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i,hasPacketTrailer:s3(n),packetTrailer:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{r_.info("initialize encoded streams");let r=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1,hasPacketTrailer:s3(n),packetTrailer:n}};
1this.worker.postMessage(a,[r.readable,r.writable])}e[s0]=!0}}}class oi{constructor(){this.metadataMap=new Map,this.activeSsrc=0}storeMetadata(e,t,i){for(0!==this.activeSsrc&&this.activeSsrc!==t&&this.metadataMap.clear(),this.activeSsrc=t;this.metadataMap.size>=300;){let e=this.metadataMap.keys().next().value;this.metadataMap.delete(e)}this.metadataMap.set(e,i)}lookupMetadata(e){return this.metadataMap.get(e)}dispose(){this.metadataMap.clear(),this.activeSsrc=0}}class on{constructor(e){this.extractors=new Map,this.workerPipelines=new Map,this.onWorkerMessage=e=>{let t=e.data;if("metadata"===t.kind){let e=this.extractors.get(t.data.trackId);e&&e.storeMetadata(t.data.rtpTimestamp,t.data.ssrc,t.data.metadata)}},this.onWorkerError=e=>{r_.error("packet trailer worker encountered an error:",{error:e.error})},this.worker=null==e?void 0:e.worker}setup(e){e!==this.room&&(this.room=e,this.worker&&(this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage({kind:"init"})),e.on(ef.TrackSubscribed,(e,t,i)=>{"video"===e.kind&&this.setupReceiver(e,t.trackInfo)}).on(ef.TrackUnsubscribed,e=>{this.teardownTrack(e)}).on(ef.Disconnected,()=>{this.cleanup()}))}setupReceiver(e,t){var i,n,r;let a=e.receiver;if(!a)return;if(!((null==t?void 0:t.packetTrailerFeatures)&&t.packetTrailerFeatures.length>0)){(null===(i=this.room)||void 0===i?void 0:i.hasE2EESetup)||this.setupPassthroughReceiver(a,e.mediaStreamID);return}if(!s2(this.worker?{worker:this.worker}:void 0)&&!(null===(n=this.room)||void 0===n?void 0:n.hasE2EESetup)){r_.warn("packet trailer transform not supported; skipping extraction");return}let s=new oi,o=e.mediaStreamID;this.extractors.set(o,s),e.packetTrailerExtractor=s,null!==(r=this.room)&&void 0!==r&&r.hasE2EESetup||this.setupWorkerReceiver(a,o,!0)}setupPassthroughReceiver(e,t){if(sf()){"transform"in e&&(e.transform=null);return}if(this.worker&&s2({worker:this.worker})&&!this.workerPipelines.has(e)){this.setupWorkerReceiver(e,t,!1);return}this.worker&&this.workerPipelines.has(e)&&this.setupWorkerReceiver(e,t,!1)}setupWorkerReceiver(e,t){let i,n=!(arguments.length>2)||void 0===arguments[2]||arguments[2],r=this.worker;if(!r)return;if(sf()){e.transform=new RTCRtpScriptTransform(r,{kind:"decode",trackId:t});return}let a=this.workerPipelines.get(e);if(a){r.postMessage({kind:"updateTrackId",data:{oldTrackId:a,newTrackId:t,hasPacketTrailer:n}}),this.workerPipelines.set(e,t);return}if(!("createEncodedStreams"in e)){r_.warn("createEncodedStreams not supported");return}try{i=e.createEncodedStreams()}catch(e){r_.warn("failed to create encoded streams",{error:e});return}let s={kind:"decode",data:{readableStream:i.readable,writableStream:i.writable,trackId:t,hasPacketTrailer:n}};r.postMessage(s,[i.readable,i.writable]),this.workerPipelines.set(e,t)}teardownTrack(e){let t=e.mediaStreamID,i=this.extractors.get(t);i&&(i.dispose(),this.extractors.delete(t)),e instanceof s8&&(e.packetTrailerExtractor=void 0)}cleanup(){var e;for(let e of this.extractors.values())e.dispose();this.extractors.clear(),this.workerPipelines.clear(),null===(e=this.worker)||void 0===e||e.terminate()}}class or{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new or),this._instance}addFailedConnectionAttempt(e){var t;let i=sC(new URL(e));if(!i)return;let n=null!==(t=this.failedConnectionAttempts.get(i))&&void 0!==t?t:0;this.failedConnectionAttempts.set(i,n+1),this.backOffPromises.set(i,sd(Math.min(500*Math.pow(2,n),15e3)))}getBackOffPromise(e){let t=new URL(e),i=t&&sC(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){let t=new URL(e),i=t&&sC(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}or._instance=null;let oa="default";class os{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new os),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return rx(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){var n;if((null===(n=os.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){r_.debug("awaiting getUserMedia promise");try{e?yield os.userMediaPromiseMap.get(e):yield Promise.all(os.userMediaPromiseMap.values())}catch(e){r_.warn("error waiting for media permissons")}}let r=yield navigator.mediaDevices.enumerateDevices();if(i&&!(sv()&&t.hasDeviceInUse(e))&&(0===r.filter(t=>t.kind===e).length||r.some(t=>{let i=""===t.label,n=!e||t.kind===e;return i&&n}))){let t=yield navigator.mediaDevices.getUserMedia({video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}});r=yield navigator.mediaDevices.enumerateDevices(),t.getTracks().forEac
1h(e=>{e.stop()})}return t._previousDevices=r,e&&(r=r.filter(t=>t.kind===e)),r}()})}normalizeDeviceId(e,t,i){return rx(this,void 0,void 0,function*(){if(t!==oa)return t;let n=yield this.getDevices(e),r=n.find(e=>e.deviceId===oa);if(!r){r_.warn("could not reliably determine default device");return}let a=n.find(e=>e.deviceId!==oa&&e.groupId===(null!=i?i:r.groupId));if(!a){r_.warn("could not reliably determine default device");return}return null==a?void 0:a.deviceId})}hasDeviceInUse(e){return e?os.userMediaPromiseMap.has(e):os.userMediaPromiseMap.size>0}}os.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],os.userMediaPromiseMap=new Map;class oo{static u16(e){return new oo(e,65535)}static u32(e){return new oo(e,4294967295)}constructor(e,t){if(this.value=e,e<0)throw Error("WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0");if(t>Number.MAX_SAFE_INTEGER)throw Error("WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.");this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new oo(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(){let e=this.value;return this.increment(),new oo(e,this.maxSize)}isBefore(e){let t=this.value>>>0,i=(e.value>>>0)-t>>>0;return 0!==i&&i<this.maxSize+1}}class oc{static fromRtpTicks(e){return new oc(e,9e4)}static rtpRandom(){return oc.fromRtpTicks(Math.round(4294967295*Math.random()))}constructor(e,t){this.timestamp=oo.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new oc(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}}class ol{constructor(e,t,i){this.epoch=t,this.base=i,this.previous=i.clone(),this.rateInHz=e}static startingNow(e,t){return new ol(t,new Date,e)}static startingAtTime(e,t,i){return new ol(i,e,t)}static rtpStartingNow(e){return ol.startingNow(e,9e4)}static rtpStartingAtTime(e,t){return ol.startingAtTime(e,t,9e4)}now(){return this.at(new Date)}at(e){let t=e.getTime()-this.epoch.getTime(),i=ol.durationInMsToTicks(t,this.rateInHz),n=this.base.clone();return n.wrappingAdd(i),n.isBefore(this.previous)&&(n=this.previous),this.previous=n.clone(),n.clone()}static durationInMsToTicks(e,t){return Math.round((1e6*e*t+5e8)/1e9)}}function od(e){if(e instanceof DataView)return e;if(e instanceof ArrayBuffer)return new DataView(e);if(e instanceof Uint8Array)return new DataView(e.buffer,e.byteOffset,e.byteLength);throw Error("Error coercing ".concat(e," to DataView - input was not DataView, ArrayBuffer, or Uint8Array."))}(x=eI||(eI={}))[x.Reserved=0]="Reserved",x[x.TooLarge=1]="TooLarge";class ou extends aq{constructor(e,t){super(19,e),this.name="DataTrackHandleError",this.reason=t,this.reasonName=eI[t]}isReason(e){return this.reason===e}static tooLarge(){return new ou("Value too large to be a valid track handle",eI.TooLarge)}static reserved(e){return new ou("0x".concat(e.toString(16)," is a reserved value."),eI.Reserved)}}let oh={fromNumber(e){if(0===e)throw ou.reserved(e);if(e>65535)throw ou.tooLarge();return e}};class op{constructor(){this.value=0}get(){return(this.value+=1,this.value>65535)?null:this.value}reset(){this.value=0}}let om=e=>({sid:e.sid,pubHandle:e.pubHandle,name:e.name,usesE2ee:e.encryption!==iR.NONE}),og=e=>new i_({sid:e.sid,pubHandle:e.pubHandle,name:e.name,encryption:e.usesE2ee?iR.GCM:iR.NONE});(L=eD||(eD={}))[L.WAITING=0]="WAITING",L[L.RUNNING=1]="RUNNING",L[L.COMPLETED=2]="COMPLETED";class of{constructor(){this.pendingTasks=new Map,this.taskMutex=new e3,this.nextTaskIndex=0}run(e){return rx(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:eD.WAITING};this.pendingTasks.set(t.id,t);let i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=eD.RUNNING,yield e()}finally{t.status=eD.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return rx(this,void 0,void 0,function*(){return this.run(()=>rx(this,void 0,void 0,function*(){}))})}
1snapshot(){return Array.from(this.pendingTasks.values())}}class ov{get readyState(){return this.ws.readyState}constructor(e){var t,i;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null===(t=n.signal)||void 0===t?void 0:t.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;let r=new WebSocket(e,null!==(i=n.protocols)&&void 0!==i?i:[]);r.binaryType="arraybuffer",this.ws=r;let a=function(){let{closeCode:e,reason:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return r.close(e,t)};this.opened=new aN((e,t)=>{let i=()=>{t(aV.websocket("Encountered websocket error during connection establishment"))};r.onopen=()=>{e({readable:new ReadableStream({start(e){r.onmessage=t=>{let{data:i}=t;return e.enqueue(i)},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",i)},r.addEventListener("error",i)}),this.closed=new aN((e,t)=>{let i=()=>rx(this,void 0,void 0,function*(){let i=new aN(e=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",t=>{e(t)},{once:!0})}),n=yield aN.race([sd(250),i]);n?e(n):t(aV.websocket("Encountered unspecified websocket error without a timely close event"))});r.onclose=t=>{let{code:n,reason:a}=t;e({closeCode:n,reason:a}),r.removeEventListener("error",i)},r.addEventListener("error",i)}),n.signal&&(n.signal.onabort=()=>r.close()),this.close=a}}let ok=["syncState","trickle","offer","answer","simulate","leave"];(U=e_||(e_={}))[U.CONNECTING=0]="CONNECTING",U[U.CONNECTED=1]="CONNECTED",U[U.RECONNECTING=2]="RECONNECTING",U[U.DISCONNECTING=3]="DISCONNECTING",U[U.DISCONNECTED=4]="DISCONNECTED";class ob{get currentState(){return this.state}get isDisconnected(){return this.state===e_.DISCONNECTING||this.state===e_.DISCONNECTED}get isEstablishingConnection(){return this.state===e_.CONNECTING||this.state===e_.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){var e;let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.rtt=0,this.state=e_.DISCONNECTED,this.log=r_,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.loggerContextCb=i.loggerContextCb,this.log=rM(null!==(e=i.loggerName)&&void 0!==e?e:el.Signal,()=>this.logContext),this.useJSON=t,this.requestQueue=new of,this.queuedRequests=[],this.closingLock=new e3,this.connectionLock=new e3,this.state=e_.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,i,n){return rx(this,arguments,void 0,function(e,t,i,n){var r=this;let a=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5?arguments[5]:void 0;return function*(){return r.state=e_.CONNECTING,r.options=i,yield r.connect(e,t,i,n,a,s)}()})}reconnect(e,t,i,n){return rx(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring");return}return this.state=e_.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}),void 0,this.useV0SignalPath)})}connect(e,t,i,n){return rx(this,arguments,void 0,function(e,t,i,n){var r=this;let a=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5?arguments[5]:void 0;return function*(){let o=yield r.connectionLock.lock();r.connectOptions=i,r.useV0SignalPath=a;let c=function(e){var t;let i=new iZ({capabilities:e,sdk:i$.JS,protocol:17,clientProtocol:1,version:"2.19.0"});return sT()&&(i.os=null!==(t=sw())&&void 0!==t?t:""),i}(i.clientInfoCapabilities),l=(function(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=function(e,t){let i=new URL(e.startsWith("http")?e.replace(/^(http)/,"ws"):e);return t.forEach((e,t)=>{i.searchParams.set(t,e)}),sZ(i,"rtc")}(e,t);return i?n:sZ(n,"v1")})(e,a?function(e,t,i){var n;let r=new URLSearchParams;return r.set("access_token",e),i.reconnect&&(r.set("reconnect","1"),i.sid&&r.set("sid",i.sid)),r.set("auto_subscribe",i.autoSubscribe?"1":"0"),r.set("sdk",sT()?"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),i.adaptiveStream&&r.set("adaptive_stream","1"),i.reconnectReason&&r.set("reconnect_reason",i.reconnectReason.toString()),(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&r.set("network",navigator.connection.type),r}(t,c,i):yield function(e,t,i,n){return rx(this,void 0,void 0,function*(){let r,a;let s=new URLSearchParams;s.set("access_token",e);let o=new rS({clientInfo:t,connectionSettings:new rT({autoSubscribe:!!i.autoSubscribe,adaptiveStream:!!i.adaptiveStream}),reconnect:!!i.reconnect,participantSid:i.sid?i.sid:void 0,publisherOffer:n});i.reconnectReason&&(o.reconnectReason=i.reconnectReason);let c=o.toBinary();if(sY()){let e=new CompressionStream("gzip"),t=e.writable.getWriter();t.write(new Uint8Array(c)),t.close();let i=[],n=e.readable.getReader();for(;;){let{done:e,value:t}=yield n.read();if(e)break;i.push(t)}let s=new Uint8Array(i.reduce((e,t)=>
1e+t.length,0)),o=0;for(let e of i)s.set(e,o),o+=e.length;r=s,a=rE.GZIP}else r=c,a=rE.NONE;let l=new rC({joinRequest:r,compression:a}).toBinary();return s.set("join_request",btoa(Array.from(l,e=>String.fromCodePoint(e)).join("")).replace(/\+/g,"-").replace(/\//g,"_")),s})}(t,c,i,s),a).toString(),d=sZ(new URL(sB(l)),"validate").toString();return new Promise((e,t)=>rx(r,void 0,void 0,function*(){var r,a;try{let s=!1,o=e=>rx(this,void 0,void 0,function*(){if(s)return;s=!0;let i=e instanceof Event?e.currentTarget:e,n=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unknown reason";if(!(e instanceof AbortSignal))return t;let i=e.reason;switch(typeof i){case"string":return i;case"object":return i instanceof Error?i.message:t;default:return"toString"in i?i.toString():t}}(i,"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(aV.cancelled(n))});null==n||n.addEventListener("abort",o);let c=()=>{clearTimeout(u),null==n||n.removeEventListener("abort",o)},u=setTimeout(()=>{o(aV.timeout("room connection has timed out (signal)"))},i.websocketTimeout),h=new URL(l);h.searchParams.has("access_token")&&h.searchParams.set("access_token","<redacted>"),this.log.info("signal connecting to ".concat(h),{reconnect:i.reconnect,reconnectReason:i.reconnectReason}),this.ws&&(yield this.close(!1)),this.ws=new ov(l);try{this.ws.closed.then(e=>{var i;this.isEstablishingConnection&&t(aV.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===e_.CONNECTED&&this.handleOnClose(null!==(i=e.reason)&&void 0!==i?i:"Unexpected WS error"))}).catch(e=>{this.isEstablishingConnection&&t(aV.internal("Websocket error during a (re)connection attempt: ".concat(e)))});let n=yield this.ws.opened.catch(e=>rx(this,void 0,void 0,function*(){if(this.state!==e_.CONNECTED){this.state=e_.DISCONNECTED,clearTimeout(u);let i=yield this.handleConnectionError(e,d);t(i);return}this.handleWSError(e),t(e)}));if(clearTimeout(u),!n)return;let s=n.readable.getReader();this.streamWriter=n.writable.getWriter();let o=yield s.read();if(s.releaseLock(),!o.value)throw aV.internal("no message received as first message");let c=s$(o.value),l=this.validateFirstMessage(c,null!==(r=i.reconnect)&&void 0!==r&&r);if(!l.isValid){t(l.error);return}(null===(a=c.message)||void 0===a?void 0:a.case)==="join"&&(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));let h=l.shouldProcessFirstMessage?c:void 0;((e,t)=>{this.handleSignalConnected(e,u,t)})(n,h),e(l.response)}catch(e){t(e)}finally{c()}}finally{o()}}))}()})}startReadingLoop(e,t){return rx(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield sd(this.signalLatency));let{done:t,value:i}=yield e.read();if(t)break;let n=s$(i);this.handleSignalResponse(n)}})}close(){return rx(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Close method called on signal client";return function*(){if([e_.DISCONNECTING||e_.DISCONNECTED].includes(e.state)){e.log.debug("ignoring signal close as it's already in disconnecting state");return}let n=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=e_.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});let t=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([t,sd(250)])}}catch(t){e.log.debug("websocket error while closing",{error:t})}finally{t&&(e.state=e_.DISCONNECTED),n()}}()})}sendOffer(e,t){this.log.debug("sending offer",{offerSdp:e.sdp}),this.sendRequest({case:"offer",value:oT(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",{answerSdp:e.sdp}),this.sendRequest({case:"answer",value:oT(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",{candidate:e}),this.sendRequest({case:"trickle",value:new nj({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new nq({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return rx(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){let r=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new n3({requestId:r,metadata:e,name:t,attributes:n}
1)}),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 n2({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new rs({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:th.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new rp({timestamp:th.parse(Date.now()),rtt:th.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new nZ({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new n0({reason:im.CLIENT_INITIATED,action:n1.DISCONNECT})})}sendPublishDataTrackRequest(e,t,i){return this.sendRequest({case:"publishDataTrackRequest",value:new nN({pubHandle:e,name:t,encryption:i?iR.GCM:iR.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:"unpublishDataTrackRequest",value:new nL({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:"updateDataSubscription",value:new nQ({updates:[new nY({trackSid:e,subscribe:t})]})})}sendRequest(e){return rx(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){if(!i&&!function(e){let t=ok.indexOf(e.case)>=0;return r_.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e)&&t.state===e_.RECONNECTING){t.queuedRequests.push(()=>rx(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));return}if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield sd(t.signalLatency)),t.isDisconnected){t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));return}if(!t.streamWriter){t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case));return}let n=new n_({message:e});try{t.useJSON?yield t.streamWriter.write(n.toJsonString()):yield t.streamWriter.write(n.toBinary().buffer)}catch(e){t.log.error("error sending signal message",{error:e})}}()})}handleSignalResponse(e){var t,i;let n=e.message;if(void 0==n){this.log.debug("received unsupported message");return}let r=!1;if("answer"===n.case){let e=oy(n.value);this.onAnswer&&this.onAnswer(e,n.value.id,n.value.midToTrackId)}else if("offer"===n.case){let e=oy(n.value);this.onOffer&&this.onOffer(e,n.value.id,n.value.midToTrackId)}else if("trickle"===n.case){let e=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(e,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=n.value.participants)&&void 0!==t?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.value.speakers)&&void 0!==i?i:[]):"leave"===n.case?this.onLeave&&this.onLeave(n.value):"mute"===n.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.value.sid,n.value.muted):"roomUpdate"===n.case?this.onRoomUpdate&&n.value.room&&this.onRoomUpdate(n.value.room):"connectionQuality"===n.case?this.onConnectionQuality&&this.onConnectionQuality(n.value):"streamStateUpdate"===n.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.value):"subscribedQualityUpdate"===n.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.value):"subscriptionPermissionUpdate"===n.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.value):"refreshToken"===n.case?this.onTokenRefresh&&this.onTokenRefresh(n.value):"trackUnpublished"===n.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.value):"subscriptionResponse"===n.case?this.onSubscriptionError&&this.onSubscriptionError(n.value):"pong"===n.case||("pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):"roomMoved"===n.case?(this.onTokenRefresh&&this.onTokenRefresh(n.value.token),this.onRoomMoved&&this.onRoomMoved(n.value)):"mediaSectionsRequirement"===n.case?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement
1(n.value):"publishDataTrackResponse"===n.case?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(n.value):"unpublishDataTrackResponse"===n.case?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(n.value):"dataTrackSubscriberHandles"===n.case?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(n.value):this.log.debug("unsupported message",{msgCase:n.case}));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){let e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return rx(this,void 0,void 0,function*(){if(this.state===e_.DISCONNECTED)return;let 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(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set");return}this.pingTimeout=aZ.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)}clearPingTimeout(){this.pingTimeout&&aZ.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set");return}this.log.debug("start ping interval"),this.pingInterval=aZ.setInterval(()=>{this.sendPing()},1e3*this.pingIntervalDuration)}clearPingInterval(){this.log.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&aZ.clearInterval(this.pingInterval)}handleSignalConnected(e,t,i){this.state=e_.CONNECTED,this.log.info("signal connected"),clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,t){var i,n,r,a,s;return(null===(i=e.message)||void 0===i?void 0:i.case)==="join"?{isValid:!0,response:e.message.value}:this.state===e_.RECONNECTING&&(null===(n=e.message)||void 0===n?void 0:n.case)!=="leave"?(null===(r=e.message)||void 0===r?void 0:r.case)==="reconnect"?{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&&(null===(a=e.message)||void 0===a?void 0:a.case)==="leave"?{isValid:!1,error:aV.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:aV.internal("Unexpected first message")}:{isValid:!1,error:aV.internal("did not receive join response, got ".concat(null===(s=e.message)||void 0===s?void 0:s.case," instead"))}}handleConnectionError(e,t){return rx(this,void 0,void 0,function*(){try{let i=yield fetch(t);switch(i.status){case 404:let n=yield i.text();if(n.includes("requested room does not exist"))return aV.notAllowed(n,i.status);return aV.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:let r=yield i.text();return aV.notAllowed(r,i.status)}if(e instanceof aV)return e;return aV.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(e){return e instanceof aV?e:aV.serverUnreachable(e instanceof Error?e.message:"server was not reachable")}})}}function oy(e){let t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function oT(e,t){return new nG({sdp:e.sdp,type:e.type,id:t})}class oS{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){let e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0;)if(this.buffer[0].sequence<=e)this.pop();else break}alignBufferedAmount(e){for(;this.buffer.length>0;){let t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class oC{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){let i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();let n=i+this.ttl;return this._map.set(e,{value:t,expiresAt:n}),this}get(e){let t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){let t=this._map.get(e);
1return!!t&&(!(t.expiresAt<Date.now())||(this._map.delete(e),!1))}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){let e=Date.now();for(let[t,i]of this._map.entries())i.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){for(let[t,i]of(this.cleanup(),this._map.entries()))i.expiresAt>=Date.now()&&e(i.value,t,this.asValueMap())}map(e){this.cleanup();let t=[],i=this.asValueMap();for(let[n,r]of i.entries())t.push(e(r,n,i));return t}asValueMap(){let e=new Map;for(let[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(t,i.value);return e}}var oE={},ow={},oP={exports:{}};function oR(){if(eM)return oP.exports;eM=1;var e=oP.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")+(null!=e.tcptype?" tcptype %s":"%v"),null!=e.generation&&(t+=" generation %d"),t+=(null!=e["network-id"]?" network-id %d":"%v")+(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","max
1MessageSize"],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:RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){return"mediaclk:"+((null!=e.id?"id=%s %s":"%v%s")+(null!=e.mediaClockValue?"=%s":"")+(null!=e.rateNumerator?" rate=%s":""))+(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")})}),oP.exports}var oI=function(){if(ex)return oE;ex=1;var e,t,i,n,r,a,s=(eO||(eO=1,e=function(e){return String(Number(e))===e?Number(e):e},t=function(t,i,n,r){if(r&&!n)i[r]=e(t[1]);else for(var a=0;a<n.length;a+=1)null!=t[a+1]&&(i[n[a]]=e(t[a+1]))},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var a=e.push?{}:r?i[e.name]:i;t(n.match(e.reg),a,e.names,e.name),e.push&&i[e.push].push(a)},n=oR(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/),ow.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<(n[t]||[]).length;o+=1){var c=n[t][o];if(c.reg.test(r))return i(c,s,r)}}),t.media=a,t},a=function(t,i){var n=i.split(/=(.+)/,2);return 2===n.length?t[n[0]]=e(n[1]):1===n.length&&i.length>1&&(t[n[0]]=void 0),t},ow.parseParams=function(e){return e.split(/;\s?/).reduce(a,{})},ow.parseFmtpConfig=ow.parseParams,ow.parsePayloads=function(e){return e.toString().split(" ").map(Number)},ow.parseRemoteCandidates=function(t){for(var i=[],n=t.split(" ").map(e),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},ow.parseImageAttributes=function(e){return e.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(a,{})})},ow.parseSimulcastStreamList=function(t){return t.split(";").map(function(t){return t.split(",").map(function(t){var i,n=!1;return"~"!==t[0]?i=e(t):(i=e(t.substring(1,t.length)),n=!0),{scid:i,paused:n}})})}),ow),o=function(){if(eN)return eA;eN=1;var e=oR(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,r=n.length;return e.replace(t,function(e){if(i>=r)return e;var t=n[i];switch(i+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}})},n=function(e,t,n){var r=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[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(n[t.name][s]):r.push(n[t.names[a]])}else r.push(n[t.name]);return i.apply(null,r)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];return eA=function(t,i){i=i||{}
1,null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach(function(e){null==e.payloads&&(e.payloads="")});var s=i.outerOrder||r,o=i.innerOrder||a,c=[];return s.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){c.push(n(i,e,t))})})}),t.media.forEach(function(t){c.push(n("m",e.m[0],t)),o.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){c.push(n(i,e,t))})})})}),c.join("\r\n")+"\r\n"}}(),c=oR();return oE.grammar=c,oE.write=o,oE.parse=s.parse,oE.parseParams=s.parseParams,oE.parseFmtpConfig=s.parseFmtpConfig,oE.parsePayloads=s.parsePayloads,oE.parseRemoteCandidates=s.parseRemoteCandidates,oE.parseImageAttributes=s.parseImageAttributes,oE.parseSimulcastStreamList=s.parseSimulcastStreamList,oE}();let oD={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",OfferAnswered:"offerAnswered",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class o_ extends rB.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),this.log=r_,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=s4(e=>rx(this,void 0,void 0,function*(){this.emit(oD.NegotiationStarted);try{yield this.createAndSendOffer()}catch(t){if(e)e(t);else throw 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=rM(null!==(t=i.loggerName)&&void 0!==t?t:el.PCTransport),this.loggerOptions=i,this.config=e,this._pc=this.createPC(),this.offerLock=new e3}createPC(){let 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 rx(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 rx(this,void 0,void 0,function*(){var i,n;let r;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;if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;let i=[],n=[],r=oI.parse(null!==(t=e.sdp)&&void 0!==t?t:""),a=0;return r.media.forEach(e=>{var t;let r=oA(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))&&n.push(r),e.fmtp.some(e=>e.payload===a&&(e.config.includes("sprop-stereo=1")&&i.push(r),!0)))}),{stereoMids:i,nackMids:n}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}else if("answer"===e.type){if(this.pendingInitialOffer&&this._pc){let e=this.pendingInitialOffer;this.pendingInitialOffer=void 0;let t=oI.parse(null!==(i=e.sdp)&&void 0!==i?i:"");
1t.media.forEach(e=>{oO(e)}),this.log.debug("setting pending initial offer before processing answer",this.logContext),yield this.setMungedSDP(e,oI.write(t))}let t=oI.parse(null!==(n=e.sdp)&&void 0!==n?n:"");t.media.forEach(e=>{let t=oA(e.mid);"audio"===e.type&&this.trackBitrates.some(i=>{if(!i.transceiver||t!=i.transceiver.mid)return!1;let n=0;if(e.rtp.some(e=>e.codec.toUpperCase()===i.codec.toUpperCase()&&(n=e.payload,!0)),0===n)return!0;let r=!1;for(let t of e.fmtp)if(t.payload===n){t.config=t.config.split(";").filter(e=>!e.includes("maxaveragebitrate")).join(";"),i.maxbr>0&&(t.config+=";maxaveragebitrate=".concat(1e3*i.maxbr)),r=!0;break}return!r&&i.maxbr>0&&e.fmtp.push({payload:n,config:"maxaveragebitrate=".concat(1e3*i.maxbr)}),!0})}),r=oI.write(t)}return 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(oD.OfferAnswered,t)),this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):"answer"===e.type&&(this.emit
1(oD.NegotiationComplete),e.sdp&&oI.parse(e.sdp).media.forEach(e=>{"video"===e.type&&this.emit(oD.RTPVideoPayloadTypes,e.rtp)})),!0})}createInitialOffer(){return rx(this,void 0,void 0,function*(){var e;let t=yield this.offerLock.lock();try{if("stable"!==this.pc.signalingState){this.log.warn("signaling state is not stable, cannot create initial offer",this.logContext);return}let t=this.latestOfferId+1;this.latestOfferId=t;let i=yield this.pc.createOffer();this.pendingInitialOffer={sdp:i.sdp,type:i.type};let n=oI.parse(null!==(e=i.sdp)&&void 0!==e?e:"");return n.media.forEach(e=>{oO(e)}),i.sdp=oI.write(n),{offer:i,offerId:t}}finally{t()}})}createAndSendOffer(e){return rx(this,void 0,void 0,function*(){var t;let i=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&("have-local-offer"===this._pc.signalingState||this.pendingInitialOffer)){let t=this._pc.remoteDescription;if((null==e?void 0:e.iceRestart)&&t)yield this._pc.setRemoteDescription(t);else{this.renegotiate=!0,this.log.debug("requesting renegotiation",Object.assign({},this.logContext));return}}else if(!this._pc||"closed"===this._pc.signalingState){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);let i=this.latestOfferId+1;this.latestOfferId=i;let n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));let r=oI.parse(null!==(t=n.sdp)&&void 0!==t?t:"");if(r.media.forEach(e=>{oO(e),"audio"===e.type?oM(e,["all"],[]):"video"===e.type&&this.trackBitrates.some(t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0)),0===i||(sp(t.codec)&&!sv()&&this.ensureVideoDDExtensionForSVC(e,r),!sp(t.codec)))return!0;let n=Math.round(.7*t.maxbr);for(let t of e.fmtp)if(t.payload===i){t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(n));break}return!0})}),this.latestOfferId>i){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:i}));return}yield this.setMungedSDP(n,oI.write(r)),this.onOffer(n,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return rx(this,void 0,void 0,function*(){var e;let t=yield this.pc.createAnswer(),i=oI.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach(e=>{oO(e),"audio"===e.type&&oM(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,oI.write(i)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new aG("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 aG("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 rx(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="",i=new Map,n=new Map;
1if((yield this._pc.getStats()).forEach(e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),i.set(e.id,e);break;case"remote-candidate":n.set(e.id,"".concat(e.address,":").concat(e.port))}}),""===t)return;let r=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;if(void 0!==r)return n.get(r)})}setMungedSDP(e,t,i){return rx(this,void 0,void 0,function*(){var n,r;let a=e.sdp;if(t){e.sdp=t;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(i){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:i,mungedSdp:t,originalSdp:a})),e.sdp=a}}try{i?yield null===(n=this._pc)||void 0===n?void 0:n.setRemoteDescription(e):yield null===(r=this._pc)||void 0===r?void 0:r.setLocalDescription(e)}catch(s){let n="unknown error";s instanceof Error?n=s.message:"string"==typeof s&&(n=s);let r={error:n,sdp:e.sdp};throw t&&t!==a&&(r.mungedSdp=t),!i&&this.pc.remoteDescription&&(r.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:r})),new aK(n)}})}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null===(i=e.ext)||void 0===i?void 0:i.some(e=>e.uri===sl))){if(0===this.ddExtID){let e=0;t.media.forEach(t=>{var i;null===(i=t.ext)||void 0===i||i.forEach(t=>{t.value>e&&(e=t.value)})}),this.ddExtID=e+1}null===(n=e.ext)||void 0===n||n.push({value:this.ddExtID,uri:sl})}}}function oM(e,t,i){let n=oA(e.mid),r=0;e.rtp.some(e=>"opus"===e.codec&&(r=e.payload,!0)),r>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(n)&&!e.rtcpFb.some(e=>e.payload===r&&"nack"===e.type)&&e.rtcpFb.push({payload:r,type:"nack"}),(t.includes(n)||1===t.length&&"all"===t[0])&&e.fmtp.some(e=>e.payload===r&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0)))}function oO(e){if(e.connection){let 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 oA(e){return"number"==typeof e?e.toFixed(0):e}let oN={audioPreset:eT.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:a9.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:"vp8",backupCodec:!0,preConnectBuffer:!1},ox={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},oL={deviceId:{ideal:"default"},resolution:a3.h720.resolution},oU={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new rN,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},oF={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};(F=eL||(eL={}))[F.NEW=0]="NEW",F[F.CONNECTING=1]="CONNECTING",F[F.CONNECTED=2]="CONNECTED",F[F.FAILED=3]="FAILED",F[F.CLOSING=4]="CLOSING",F[F.CLOSED=5]="CLOSED";class oB{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,i){var n;this.peerConnectionTimeout=oF.peerConnectionTimeout,this.log=r_,this.updateState=()=>{var e,t;let i=this.state,n=this.requiredTransports.map(e=>e.getConnectionState());n.every(e=>"connected"===e)?this.state=eL.CONNECTED:n.some(e=>"failed"===e)?this.state=eL.FAILED:n.some(e=>"connecting"===e)?this.state=eL.CONNECTING:n.every(e=>"closed"===e)?this.state=eL.CLOSED:n.some(e=>"closed"===e)?this.state=eL.CLOSING:n.every(e=>"new"===e)&&(this.state=eL.NEW),i!==this.state&&(this.log.debug("pc state change: from ".concat(eL[i]," to ").concat(eL[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=rM(null!==(n=t.loggerName)&&void 0!==n?n:el.PCManager),this.loggerOptions=t,this.isPublisherConnectionRequired="subscriber-primary"!==e,this.isSubscriberConnectionRequired="subscriber-primary"===e,this.publisher=new o_(i,t),this._mode=e,"publisher-only"!==e&&(this.subscriber=new o_(i,t),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,nR.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,nR.PUBLISHER)},this.publisher.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var i;null===(i=this.onPublisherOffer)||void 0===i||i.call(this,e,t)},this.state=eL.NEW,this.connectionLock=new e3,this.remoteOfferLock=new e3}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 rx(this,void 0,void 0,function*(){var e;if(this.publisher&&"closed"!==this.publisher.getSignallingState()){let e=this.publisher;for(let t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),null===(e=this.subscriber)||void 0===e?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return rx(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return rx(this,void 0,void 0,function*(){var i;t===nR.PUBLISHER?yield this.publisher.addIceCandidate(e):yield null===(i=this.subscriber)||void 0===i?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return rx(this,void 0,void 0,function*(){var i,n,r;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:null===(i=this.subscriber)||void 0===i?void 0:i.getSignallingState().toString()}));let a=yield this.remoteOfferLock.lock();try{if(!(yield null===(n=this.subscriber)||void 0===n?void 0:n.setRemoteDescription(e,t)))return;return yield null===(r=this.subscriber)||void 0===r?void 0:r.createAndSetAnswer()}finally{a()}})}updateConfiguration(e,t){var i;this.publisher.setConfiguration(e),null===(i=this.subscriber)||void 0===i||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return rx(this,void 0,void 0,function*(){var i;let n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null===(i=this.requiredTransports)||void 0===i?void 0:i.map(i=>
1this.ensureTransportConnected(i,e,t)))}finally{n()}})}negotiate(e){return rx(this,void 0,void 0,function*(){return new aN((t,i)=>{let n=this.publisher.latestOfferId;if(this.publisher.latestAcknowledgedOfferId>n){this.log.debug("negotiation already handled in more recent acknowledged offer",this.logContext),t();return}let r=!1,a=()=>{r||(r=!0,clearTimeout(c),this.publisher.off(oD.OfferAnswered,s),e.signal.removeEventListener("abort",o))},s=e=>{e>n&&(a(),t())},o=()=>{a(),i(new aK("negotiation aborted"))},c=setTimeout(()=>{a(),i(new aK("negotiation timed out"))},this.peerConnectionTimeout);e.signal.addEventListener("abort",o),this.publisher.on(oD.OfferAnswered,s),this.publisher.negotiate(e=>{a(),e instanceof Error?i(e):i(Error(String(e)))})})})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){let 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===nR.PUBLISHER?this.publisher.getConnectedAddress():e===nR.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){let e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return rx(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise((e,r)=>rx(i,void 0,void 0,function*(){let i=()=>{this.log.warn("abort transport connection",this.logContext),aZ.clearTimeout(a),r(aV.cancelled("room connection has been cancelled"))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);let a=aZ.setTimeout(()=>{null==t||t.signal.removeEventListener("abort",i),r(aV.internal("could not establish pc connection"))},n);for(;this.state!==eL.CONNECTED;)if(yield sd(50),null==t?void 0:t.signal.aborted){r(aV.cancelled("room connection has been cancelled"));return}aZ.clearTimeout(a),null==t||t.signal.removeEventListener("abort",i),e()}))}()})}}let oj="undefined"!=typeof MediaRecorder;class oq{constructor(){throw Error("MediaRecorder is not available in this environment")}}let oV=oj?MediaRecorder:oq;class oH extends oV{constructor(e,t){let i,n;if(!oj)throw Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let r=()=>void 0===n,a=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",s),null==n||n.close(),n=void 0},s=e=>{null==n||n.error(e),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",s),n=void 0};this.byteStream=new ReadableStream({start:e=>{n=e,i=t=>rx(this,void 0,void 0,function*(){let i;if(t.data.arrayBuffer)i=new Uint8Array((yield t.data.arrayBuffer()));else if(t.data.byteArray)i=t.data.byteArray;else throw Error("no data available!");r()||e.enqueue(i)}),this.addEventListener("dataavailable",i)},cancel:()=>{a()}}),this.addEventListener("stop",a),this.addEventListener("error",s)}}class oW extends ss{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4?arguments[4]:void 0;super(e,t,r),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=s4(()=>rx(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>rx(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>
1{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(eb.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new e3,this.pauseUpstreamLock=new e3,this.trackChangeLock=new e3,this.trackChangeLock.lock().then(t=>rx(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==ss.Kind.Video)return;let{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){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,i){return rx(this,void 0,void 0,function*(){var n;let r;if(e!==this._mediaStreamTrack||t){if(this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{sc(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&&(so(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&&(null===(n=this.sender.transport)||void 0===n?void 0:n.state)!=="closed"&&(yield this.sender.replaceTrack(null!=r?r:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!!i||!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{so(null!=r?r:e,t)}))}})}waitForDimensions(){return rx(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(e.kind===ss.Kind.Audio)throw Error("cannot get dimensions for audio tracks");
1(null===(i=aL())||void 0===i?void 0:i.os)==="iOS"&&(yield sd(10));let n=Date.now();for(;Date.now()-n<t;){let t=e.dimensions;if(t)return t;yield sd(50)}throw new aW("unable to get track dimensions after timeout")}()})}setDeviceId(e){return rx(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===sF(e)||((this._constraints.deviceId=e,this.isMuted)?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),sF(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return rx(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){if(e.source===ss.Source.ScreenShare)return;let{deviceId:i,groupId:n}=e._mediaStreamTrack.getSettings(),r=e.kind===ss.Kind.Audio?"audioinput":"videoinput";return t?os.getInstance().normalizeDeviceId(r,i,n):i}()})}mute(){return rx(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return rx(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return rx(this,void 0,void 0,function*(){let i=yield this.trackChangeLock.lock();try{let i,n;if(!this.sender)throw new aW("unable to replace an unpublished track");"boolean"==typeof t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.internalStopProcessor())}finally{i()}return yield this.onSenderTrackSwapped(),this})}onSenderTrackSwapped(){return rx(this,void 0,void 0,function*(){})}restart(e,t){return rx(this,void 0,void 0,function*(){this.manuallyStopped=!1;let i=yield this.trackChangeLock.lock();try{e||(e=this._constraints);let{deviceId:i,facingMode:n}=e,r=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&0>t.indexOf(n)&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,n=Object.getOwnPropertySymbols(e);r<n.length;r++)0>t.indexOf(n[r])&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]]);return i}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));let a={audio:!1,video:!1};this.kind===ss.Kind.Video?a.video=!i&&!n||{deviceId:i,facingMode:n}:a.audio=!i||Object.assign({deviceId:i},r),this.attachedElements.forEach(e=>{sc(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();let s=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===ss.Kind.Video&&(yield s.applyConstraints(r)),s.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(s,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit(eb.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{i()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),(this.isMuted!==e||this._mediaStreamTrack.enabled===e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?eb.Muted:eb.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return rx(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),!sb()||(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 rx(this,void 0,void 0,function*(){var e;let t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}
1this._isUpstreamPaused=!0,this.emit(eb.UpstreamPaused,this);let t=aL();if((null==t?void 0:t.name)==="Safari"&&0>sR(t.version,"12.0"))throw new aH("pauseUpstream is not supported on Safari < 12.");(null===(e=this.sender.transport)||void 0===e?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return rx(this,void 0,void 0,function*(){var e;let t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(eb.UpstreamResumed,this),(null===(e=this.sender.transport)||void 0===e?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return rx(this,void 0,void 0,function*(){var e;if(null===(e=this.sender)||void 0===e?void 0:e.getStats)return yield this.sender.getStats()})}setProcessor(e){return rx(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){var n;let r=yield t.trackChangeLock.lock();try{t.log.debug("setting up processor",t.logContext);let r=document.createElement(t.kind),a={kind:t.kind,track:t._mediaStreamTrack,element:r,audioContext:t.audioContext,localTrack:t};if(yield e.init(a),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.internalStopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(so(t._mediaStreamTrack,r),r.muted=!0,r.play().catch(e=>{e instanceof DOMException&&"AbortError"===e.name?(t.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout(()=>{r.play().catch(e=>{t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{err:e}))})},100)):t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{error:e}))}),t.processor=e,t.processorElement=r,t.processor.processedTrack){for(let e of t.attachedElements)e!==t.processorElement&&i&&(sc(t._mediaStreamTrack,e),so(t.processor.processedTrack,e));yield null===(n=t.sender)||void 0===n?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit(eb.TrackProcessorUpdate,t.processor)}finally{r()}yield t.onSenderTrackSwapped()}()})}getProcessor(){return this.processor}stopProcessor(){return rx(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){let i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}yield e.onSenderTrackSwapped()}()})}internalStopProcessor(){return rx(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){var i,n;e.processor&&(e.log.debug("stopping processor",e.logContext),null===(i=e.processor.processedTrack)||void 0===i||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||(null===(n=e.processorElement)||void 0===n||n.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(eb.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(!oj){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}{let e="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(e)||(e="video/mp4"),this.localTrackRecorder=new oH(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)}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 oz extends oW{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=!(arguments.length>2)||void 0===arguments[2]||arguments[2],n=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,ss.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>rx(this,void 0,void 0,function*(){let e;if(!this.sender){this._currentBitrate=0;return}
1try{e=yield this.getSenderStats()}catch(e){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}));return}e&&this.prevStats&&(this._currentBitrate=s9(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(eb.AudioTrackFeatureUpdate,this,ik.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(eb.AudioTrackFeatureUpdate,this,ik.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return rx(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(this.isMuted)return this.log.debug("Track already muted",this.logContext),this;return this.source===ss.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return rx(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;return this.source===ss.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}finally{t()}})}restartTrack(e){return rx(this,void 0,void 0,function*(){let t;if(e){let i=a5({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)})}restart(e,t){let i=Object.create(null,{restart:{get:()=>super.restart}});return rx(this,void 0,void 0,function*(){let n=yield i.restart.call(this,e,t);return this.checkForSilence(),n})}startMonitor(){sy()&&!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},2e3))}setProcessor(e){return rx(this,void 0,void 0,function*(){var t;let i=yield this.trackChangeLock.lock();try{if(!sT()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());let i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext,localTrack:this};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),this.processor=e,this.processor.processedTrack&&(yield null===(t=this.sender)||void 0===t?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(eb.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return rx(this,void 0,void 0,function*(){var e;let t;if(null===(e=this.sender)||void 0===e?void 0:e.getStats)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 rx(this,void 0,void 0,function*(){let e=yield function(e){return rx(this,arguments,void 0,function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){let i=a7();if(i){let n=i.createAnalyser();n.fftSize=2048;let r=new Uint8Array(n.frequencyBinCount);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield sd(t),n.getByteTimeDomainData(r);let a=r.some(e=>128!==e&&0!==e);return i.close(),!a}return!1}()})}(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(eb.AudioSilenceDetected)),e})}}let oG=Object.values(a3),oK=Object.values(a4),oJ=Object.values(a9),oQ=[a3.h180,a3.h360],oY=[a4.h180,a4.h360],oX=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map(t=>{var i,n;return new a$(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!==(i=e.encoding.maxFramerate)&&void 0!==i?i:30)/(null!==(n=t.fps)&&void 0!==n?n:30))))),t.fps,e.encoding.priority)}),oZ=["q","h","f"];function o$(e,t,i,n){var r,a,s;let o,c;let l=null==n?void 0:n.videoEncoding;e&&(l=null==n?void 0:n.screenShareEncoding);let d=null==n?void 0:n.simulcast,u=null==n?void 0:n.scalabilityMode,h=null==n?void 0:n.videoCodec;if(!l&&!d&&!u||!t||!i)return[{}];l||(l=function(e,t,i,n){let r=function(e,t,i){if(e)return oJ;let n=t>i?t/i:i/t;return Math.abs(n-16/9)<Math.abs(n-4/3)?oG:oK}(e,t,i),{encoding:a}=r[0],s=Math.max(t,i);for(let e=0;e<r.length;e+=1){let t=r[e];if(a=t.encoding,t.width>=s)break}if(n)switch(n){case"av1":case"h265":(a=Object.assign({},a)).maxBitrate=.7*a.maxBitrate;break;case"vp9":(a=Object.assign({},a)).maxBitrate=.85*a.maxBitrate}return a}(e,t,i,h),r_.debug("using video encoding",l));let p=l.maxFramerate,m=new a$(t,i,l.maxBitrate,l.maxFramerate,l.priority);if(u&&sp(h)){let e=new o4(u),t=[];if(e.spatial>3)throw Error("unsupported scalabilityMode: ".concat(u));let i=aL();if(sk()||sT()||(null==i?void 0:i.name)==="Chrome"&&0>sR(null==i?void 0:i.version,"113")){let n="h"==e.suffix?2:3,r=((s=i)||(s=aL()),(null==s?void 0:s.name)==="Safari"&&sR(s.version,"18.3")>0||(null==s?void 0:s.os)==="iOS"&&!!(null==s?void 0:s.osVersion)&&sR(s.osVersion,"18.3")>0);for(let i=0;i<e.spatial;i+=1)t.push({rid:oZ[2-i],maxBitrate:l.maxBitrate/Math.pow(n,i),maxFramerate:m.encoding.maxFramerate,scaleResolutionDownBy:r?Math.pow(2,i):void 0});t[0].scalabilityMode=u}else t.push({maxBitrate:l.maxBitrate,maxFramerate:m.encoding.maxFramerate,scalabilityMode:u});return m.encoding.priority&&(t[0].priority=m.encoding.priority,t[0].networkPriority=m.encoding.priority),r_.debug("using svc encoding",{encodings:t}),t}if(!d)return[l];if((o=e?null!==(r=o3(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==r?r:o1(e,m):null!==(a=o3(null==n?void 0:n.videoSimulcastLayers))&&void 0!==a?a:o1(e,m)).length>0){let e=o[0];o.length>1&&([,c]=o);let n=Math.max(t,i);if(n>=960&&c)return o2(t,i,[e,c,m],p);if(n>=480)return o2(t,i,[e,m],p)}return o2(t,i,[m])}function o0(e,t,i){var n,r,a,s;
1if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&r_.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;let o=e.mediaStreamTrack.getSettings(),c=null!==(n=o.width)&&void 0!==n?n:null===(r=e.dimensions)||void 0===r?void 0:r.width,l=null!==(a=o.height)&&void 0!==a?a:null===(s=e.dimensions)||void 0===s?void 0:s.height;return e.source===ss.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),o$(e.source===ss.Source.ScreenShare,c,l,i)}function o1(e,t){if(e)return oX(t);let{width:i,height:n}=t,r=i>n?i/n:n/i;return Math.abs(r-16/9)<Math.abs(r-4/3)?oQ:oY}function o2(e,t,i,n){let r=[];if(i.forEach((i,a)=>{if(a>=oZ.length)return;let s={rid:oZ[a],scaleResolutionDownBy:Math.max(1,Math.min(e,t)/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},o=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;o&&(s.maxFramerate=o);let c=aL(),l=(null==c?void 0:c.name)==="Firefox"&&"iOS"!==c.os||0===a;i.encoding.priority&&l&&(s.priority=i.encoding.priority,s.networkPriority=i.encoding.priority),r.push(s)}),sT()&&"ios"===sw()){let e;r.forEach(t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate});let t=!0;r.forEach(i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,r_.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),r_.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)})}return r}function o3(e){if(e)return e.sort((e,t)=>{let{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitrate<n.maxBitrate?-1:i.maxBitrate===n.maxBitrate&&i.maxFramerate&&n.maxFramerate?i.maxFramerate>n.maxFramerate?1:-1:0})}class o4{constructor(e){let t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!==(e=this.suffix)&&void 0!==e?e:"")}}class o9 extends oW{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=!(arguments.length>2)||void 0===arguments[2]||arguments[2],n=arguments.length>3?arguments[3]:void 0;super(e,ss.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>rx(this,void 0,void 0,function*(){let e;if(!this.sender){this._currentBitrate=0;return}try{e=yield this.getSenderStats()}catch(e){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:e}));return}let t=new Map(e.map(e=>[e.rid,e])),i=e.some(e=>"cpu"===e.qualityLimitationReason);if(i!==this.isCpuConstrained&&(this.isCpuConstrained=i,this.isCpuConstrained&&this.emit(eb.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,i)=>{var n;let r=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=s9(t,r)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new e3}get isSimulcast(){return!!this.sender&&this.sender.getParameters().encodings.length>1}startMonitor(e){var t;if(this.signalClient=e,!sy())return;let i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},2e3))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){let e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return rx(this,void 0,void 0,function*(){yield e.pauseUpstream.call(this);try{for(var t,i,n,r,a,s,o=!0,c=rU(this.simulcastCodecs.values());!(t=(s=yield c.next()).done);o=!0)r=s.value,o=!1,yield null===(a=r.sender)||void 0===a?void 0:a.replaceTrack(null)}catch(e){i={error:e}}
1finally{try{!o&&!t&&(n=c.return)&&(yield n.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){let e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return rx(this,void 0,void 0,function*(){yield e.resumeUpstream.call(this);try{for(var t,i,n,r,a,s,o=!0,c=rU(this.simulcastCodecs.values());!(t=(s=yield c.next()).done);o=!0)r=s.value,o=!1,yield null===(a=r.sender)||void 0===a?void 0:a.replaceTrack(r.mediaStreamTrack)}catch(e){i={error:e}}finally{try{!o&&!t&&(n=c.return)&&(yield n.call(c))}finally{if(i)throw i.error}}})}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return rx(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(this.isMuted)return this.log.debug("Track already muted",this.logContext),this;return this.source!==ss.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return rx(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;return this.source!==ss.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this}finally{t()}})}setTrackMuted(e){for(let t of(super.setTrackMuted(e),this.simulcastCodecs.values()))t.mediaStreamTrack.enabled=!e}getSenderStats(){return rx(this,void 0,void 0,function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];let t=[],i=yield this.sender.getStats();return i.forEach(e=>{var n;if("outbound-rtp"===e.type){let 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!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},a=i.get(e.remoteId);a&&(r.jitter=a.jitter,r.packetsLost=a.packetsLost,r.roundTripTime=a.roundTripTime),t.push(r)}}),t.sort((e,t)=>{var i,n;return(null!==(i=t.frameWidth)&&void 0!==i?i:0)-(null!==(n=e.frameWidth)&&void 0!==n?n:0)}),t})}setPublishingQuality(e){let t=[];for(let i=eS.LOW;i<=eS.HIGH;i+=1)t.push(new rt({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(sp(this.codec),t)}restartTrack(e){return rx(this,void 0,void 0,function*(){let t;if(e){let i=a5({video:e});"boolean"!=typeof i.video&&(t=i.video)}yield this.restart(t),this.isCpuConstrained=!1;try{for(var i,n,r,a,s,o,c=!0,l=rU(this.simulcastCodecs.values());!(i=(o=yield l.next()).done);c=!0)a=o.value,c=!1,a.sender&&(null===(s=a.sender.transport)||void 0===s?void 0:s.state)!=="closed"&&(a.mediaStreamTrack=this.mediaStreamTrack.clone(),yield a.sender.replaceTrack(a.mediaStreamTrack))}catch(e){n={error:e}}finally{try{!c&&!i&&(r=l.return)&&(yield r.call(l))}finally{if(n)throw n.error}}yield this.onSenderTrackSwapped()})}onSenderTrackSwapped(){return rx(this,void 0,void 0,function*(){yield this.refreshSen
1derEncodings()})}refreshSenderEncodings(){return rx(this,void 0,void 0,function*(){var e;if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;let t=yield this.senderLock.lock();try{let t;try{t=yield this.waitForDimensions()}catch(e){this.log.warn("could not determine new track dimensions, skipping encoding recompute",Object.assign(Object.assign({},this.logContext),{error:e}));return}if(this.lastEncodedDimensions&&this.lastEncodedDimensions.width===t.width&&this.lastEncodedDimensions.height===t.height)return;let i=this.source===ss.Source.ScreenShare,n=o$(i,t.width,t.height,Object.assign({},this.publishOptions));for(let[i,r]of(yield this.applyEncodingsToSender(this.sender,n),this.encodings=n,this.lastEncodedDimensions=t,this.simulcastCodecs)){if(!r.sender||(null===(e=r.sender.transport)||void 0===e?void 0:e.state)==="closed"||!a2(i))continue;let t=Object.assign({},this.publishOptions),n=o0(this,i,t);n&&(yield this.applyEncodingsToSender(r.sender,n),r.encodings=n)}}catch(e){this.log.warn("failed to apply recomputed encodings",Object.assign(Object.assign({},this.logContext),{error:e}))}finally{t()}})}applyEncodingsToSender(e,t){return rx(this,void 0,void 0,function*(){let i=e.getParameters();
1i.encodings&&i.encodings.length===t.length&&(i.encodings.forEach((e,i)=>{if(!1===e.active)return;let n=t[i];void 0!==n.scaleResolutionDownBy&&(e.scaleResolutionDownBy=n.scaleResolutionDownBy),void 0!==n.maxBitrate&&(e.maxBitrate=n.maxBitrate),void 0!==n.maxFramerate&&(e.maxFramerate=n.maxFramerate),void 0!==n.priority&&(e.priority=n.priority,e.networkPriority=n.priority)}),this.log.debug("updating sender encodings after track restart",Object.assign(Object.assign({},this.logContext),{encodings:i.encodings})),yield e.setParameters(i))})}setProcessor(e){let t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return rx(this,arguments,void 0,function(e){var i=this;let n=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){if(yield t.setProcessor.call(i,e,n),null===(c=i.processor)||void 0===c?void 0:c.processedTrack)try{for(var r,a,s,o,c,l,d,u=!0,h=rU(i.simulcastCodecs.values());!(r=(d=yield h.next()).done);u=!0)o=d.value,u=!1,yield null===(l=o.sender)||void 0===l?void 0:l.replaceTrack(i.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 rx(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);let t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}let i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){let i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},5e3))}setPublishingCodecs(e){return rx(this,void 0,void 0,function*(){var t,i,n,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(sp(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;let c=[];try{for(t=!0,i=rU(e);!(r=(n=yield i.next()).done);t=!0)if(o=n.value,t=!1,this.codec&&this.codec!==o.codec){let e=this.simulcastCodecs.get(o.codec);if(this.log.debug("try setPublishingCodec for ".concat(o.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:e})),e&&e.sender)e.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(o.codec),this.logContext),yield o6(e.sender,e.encodings,o.qualities,this.senderLock,sp(o.codec),this.log,this.logContext));else for(let e of o.qualities)if(e.enabled){c.push(o.codec);break}}else yield this.setPublishingLayers(sp(o.codec),o.qualities)}catch(e){a={error:e}}finally{try{!t&&!r&&(s=i.return)&&(yield s.call(i))}finally{if(a)throw a.error}}return c})}setPublishingLayers(e,t){return rx(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),this.sender&&this.encodings&&(yield o6(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return rx(this,void 0,void 0,function*(){if(!this.sender)throw Error("sender not found");let e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;let e=this.sender.getParameters();e.encodings=e.encodings.map((e,t)=>{var i;return Object.assign(Object.assign({},e),{active:0===t,scaleResolutionDownBy:Math.max(1,Math.ceil((null!==(i=this.mediaStreamTrack.getSettings().height)&&void 0!==i?i:360)/360)),scalabilityMode:0===t&&sp(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(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return rx(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),sb()&&this.isInBackgroun
1d&&this.source===ss.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function o6(e,t,i,n,r,a,s){return rx(this,void 0,void 0,function*(){let o=yield n.lock();a.debug("setPublishingLayersForSender",Object.assign(Object.assign({},s),{sender:e,qualities:i,senderEncodings:t}));try{let n=e.getParameters(),{encodings:o}=n;if(!o)return;if(o.length!==t.length){a.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},s),{encodings:o,senderEncodings:t}));return}let c=!1;r&&i.some(e=>e.enabled)&&i.forEach(e=>e.enabled=!0),o.forEach((e,n)=>{var r;let o=null!==(r=e.rid)&&void 0!==r?r:"";""===o&&(o="q");let l=o8(o),d=i.find(e=>e.quality===l);d&&e.active!==d.enabled&&(c=!0,e.active=d.enabled,a.debug("setting layer ".concat(d.quality," to ").concat(e.active?"enabled":"disabled"),s),sg()&&(d.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}),c&&(n.encodings=o,a.debug("setting encodings",Object.assign(Object.assign({},s),{encodings:n.encodings})),yield e.setParameters(n))}finally{o()}})}function o8(e){switch(e){case"f":default:return eS.HIGH;case"h":return eS.MEDIUM;case"q":return eS.LOW}}function o5(e,t,i,n){if(!i)return[new iO({quality:eS.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){let n=new o4(i[0].scalabilityMode),r=[],a="h"==n.suffix?1.5:2,s="h"==n.suffix?2:3;for(let o=0;o<n.spatial;o+=1)r.push(new iO({quality:Math.min(eS.HIGH,n.spatial-1)-o,width:Math.ceil(e/Math.pow(a,o)),height:Math.ceil(t/Math.pow(a,o)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(s,o)):0,ssrc:0}));return r}return i.map(i=>{var n,r,a;let s=null!==(n=i.scaleResolutionDownBy)&&void 0!==n?n:1;return new iO({quality:o8(null!==(r=i.rid)&&void 0!==r?r:""),width:Math.ceil(e/s),height:Math.ceil(t/s),bitrate:null!==(a=i.maxBitrate)&&void 0!==a?a:0,ssrc:0})})}let o7="_lossy",ce="_reliable",ct="_data_track",ci="leave-reconnect";(B=eU||(eU={}))[B.New=0]="New",B[B.Connected=1]="Connected",B[B.Disconnected=2]="Disconnected",B[B.Reconnecting=3]="Reconnecting",B[B.Closed=4]="Closed",(j=eF||(eF={}))[j.RELIABLE=0]="RELIABLE",j[j.LOSSY=1]="LOSSY",j[j.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY";class cn extends rB.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=oF.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=eU.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=r_,this.reliableDataSequence=1,this.reliableMessageBuffer=new oS,this.reliableReceivedState=new oC(3e4),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.bufferStatusLowClosingFuture=new sL,this.handleDataChannel=e=>rx(this,[e],void 0,function(e){var t=this;let{channel:i}=e;return function*(){let e;if(i){if(i.label===ce)t.reliableDCSub=i,e=t.handleDataMessage;else if(i.label===o7)t.lossyDCSub=i,e=t.handleDataMessage;else{if(i.label!==ct)return;t.dataTrackDCSub=i,e=t.handleDataTrackMessage}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label)),i.onmessage=e}}()}),this.handleDataMessage=e=>rx(this,void 0,void 0,function*(){var t,i,n,r,a;let s=yield this.dataProcessLock.lock();try{let s;if(e.data instanceof ArrayBuffer)s=e.data;else if(e.data instanceof Blob)s=yield e.data.arrayBuffer();else{this.log.error("unsupported data type",{data:e.data});return}let o=iN.fromBinary(new Uint8Array(s));if(o.sequence>0&&""!==o.participantSid){let e=this.reliableReceivedState.get(o.participantSid);if(e&&o.sequence<=e)return;this.reliableReceivedState.set(o.participantSid,o.sequence)}if((null===(t=o.value)||void 0===t?void 0:t.case)==="speaker")this.emit
1(ek.ActiveSpeakersUpdate,o.value.value.speakers);else if((null===(i=o.value)||void 0===i?void 0:i.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up");return}let e=yield null===(n=this.e2eeManager)||void 0===n?void 0:n.handleEncryptedData(o.value.value.encryptedValue,o.value.value.iv,o.participantIdentity,o.value.value.keyIndex),t=iU.fromBinary(e.payload),i=new iN({value:t.value,participantIdentity:o.participantIdentity,participantSid:o.participantSid});(null===(r=i.value)||void 0===r?void 0:r.case)==="user"&&cr(i,i.value.value),this.emit(ek.DataPacketReceived,i,o.value.value.encryptionType)}else(null===(a=o.value)||void 0===a?void 0:a.case)==="user"&&cr(o,o.value.value),this.emit(ek.DataPacketReceived,o,iR.NONE)}finally{s()}}),this.handleDataTrackMessage=e=>rx(this,void 0,void 0,function*(){let t;if(e.data instanceof ArrayBuffer)t=e.data;else if(e.data instanceof Blob)t=yield e.data.arrayBuffer();else{this.log.error("unsupported data type",{data:e.data});return}this.emit("dataTrackPacketReceived",new Uint8Array(t))}),this.handleDataError=e=>{let t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){let{error:i}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),{error:i})}else this.log.error("Unknown DataChannel error on ".concat(t),{event:e})},this.handleBufferedAmountLow=e=>{this.updateAndEmitDCBufferStatus(e)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected")),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());let i=Date.now()-this.reconnectStart,n=this.getNextRetryDelay({elapsedMs:i,retryCount:this.reconnectAttempts});if(null===n){(e=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up")),this.emit(ek.Disconnected),this.close()})(i);return}e===ci&&(n=0),this.log.debug("reconnecting in ".concat(n,"ms")),this.clearReconnectTimeout(),this.token&&this.emit(ek.TokenRefreshed,this.token),this.reconnectTimeout=aZ.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),n)},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===eU.Connected&&e();let i=()=>{this.off(ek.Disconnected,n),e()},n=()=>{this.off(ek.Restarted,i),t()};this.once(ek.Restarted,i),this.once(ek.Disconnected,n)}),this.updateAndEmitDCBufferStatus=e=>{if(e===eF.RELIABLE){let t=this.dataChannelForKind(e);t&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount)}let t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(ek.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{let t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>rx(this,void 0,void 0,function*(){this.url&&(yield fetch(sB(this.url),{method:"HEAD"}).then(e=>e.ok).catch(()=>!1))&&(this.log.info("detected network reconnected"),(this.client.currentState===e_.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===e_.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(ig.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>rx(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(sB(this.url),{method:"HEAD"}),sd(4e3).then(()=>Promise.reject())])}catch(e){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=rM(null!==(t=e.loggerName)&&void 0!==t?t:el.Engine,()=>this.logContext),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new ob(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new e3,this.dataProcessLock=new e3,this.dcBufferStatus=new Map([[eF.RELIABLE,!0],[eF.LOSSY,!0],[eF.DATA_TRACK_LOSSY,!0]]),this.client.onParticipantUpdate=e=>this.emit(ek.ParticipantUpdate,e),this.client.onConnectionQuality=e=>
1this.emit(ek.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(ek.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(ek.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(ek.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(ek.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(ek.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(ek.SignalRequestResponse,e),this.client.onParticipantUpdate=e=>this.emit(ek.ParticipantUpdate,e),this.client.onJoined=e=>this.emit(ek.Joined,e),this.on(ek.Closing,()=>{var e,t;null===(t=(e=this.bufferStatusLowClosingFuture).reject)||void 0===t||t.call(e,new aG("engine closed"))}),this.bufferStatusLowClosingFuture.promise.catch(()=>{})}get logContext(){var e,t,i,n,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===(n=null===(i=this.latestJoinResponse)||void 0===i?void 0:i.room)||void 0===n?void 0:n.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(e,t,i,n){return rx(this,arguments,void 0,function(e,t,i,n){var r=this;let a=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){var s,o,c;r._isNewlyCreated=!1,r.url=e,r.token=t,r.signalOpts=i,r.maxJoinAttempts=i.maxRetries;try{let l;if(r.joinAttempts+=1,r.setupSignalClientCallbacks(),!a&&sY()){r.pcManager||(yield r.configure(),r.createDataChannels(),r.addMediaSections(3,3));let e=yield null===(s=r.pcManager)||void 0===s?void 0:s.publisher.createInitialOffer();e&&(l=oT(e.offer,e.offerId))}if(null==n?void 0:n.aborted)throw aV.cancelled("Connection aborted");if(!a&&r.shouldFailOnV1Path)throw r.shouldFailOnV1Path=!1,aV.serviceNotFound("Simulated v1 path failure","v0-rtc");let d=yield r.client.join(e,t,i,n,a,l);r._isClosed=!1,r.latestJoinResponse=d,r.participantSid=null===(o=d.participant)||void 0===o?void 0:o.sid,r.subscriberPrimary=d.subscriberPrimary,!a&&sY()?null===(c=r.pcManager)||void 0===c||c.updateConfiguration(r.makeRTCConfiguration(d)):(r.pcManager||(yield r.configure(d,!a)),(!r.subscriberPrimary||d.fastPublish)&&r.negotiate().catch(e=>{r.log.error(e)})),r.registerOnLineListener(),r.clientConfiguration=d.clientConfiguration,r.emit(ek.SignalConnected,d);let u=d.serverInfo;return u||(u={version:d.serverVersion,region:d.serverRegion}),r.log.info("connected to Livekit Server ".concat(Object.entries(u).map(e=>{let[t,i]=e;return"".concat(t,": ").concat(i)}).join(", "))),{joinResponse:d,serverInfo:u}}catch(s){if(s instanceof aV){if(s.reason===ep.ServerUnreachable){if(r.log.warn("Couldn't connect to server, attempt ".concat(r.joinAttempts," of ").concat(r.maxJoinAttempts)),r.joinAttempts<r.maxJoinAttempts)return r.join(e,t,i,n,a)}else if(s.reason===ep.ServiceNotFound)return r.log.warn("Initial connection failed: ".concat(s.message," – Retrying")),r.pcManager&&(r.pcManager.onStateChange=void 0,yield r.cleanupPeerConnections()),r.join(e,t,i,n,!0)}throw s}}()})}close(){return rx(this,void 0,void 0,function*(){let e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(ek.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return rx(this,void 0,void 0,function*(){var e;yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;let 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 oS,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 rx(this,void 0,void 0,function*(){for(let e of(yield this.client.close(),this.client.resetCallbacks(),Object.keys(this.pendingTrackResolvers)))this.pendingTrackResolvers[e].reject();this.pendingTrackResolvers={}})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new aW("a track with the same ID has already been published");return new Promise((t,i)=>{let n=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(aV.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){let{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",{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 rx(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(e,t){return rx(this,void 0,void 0,function*(){var i;if(!this.pcManager||this.pcManager.currentState===eL.NEW){if(e){this.participantSid=null===(i=e.participant)||void 0===i?void 0:i.sid;let n=this.makeRTCConfiguration(e);this.pcManager=new oB(t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,n)}else{let e=this.makeRTCConfiguration();this.pcManager=new oB("publisher-only",this.loggerOptions,e)}
1this.emit(ek.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=(e,t)=>{this.client.sendOffer(e,t)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(e,t,i)=>rx(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(e)),["closed","disconnected","failed"].includes(t)&&(this.publisherConnectionPromise=void 0),e===eL.CONNECTED){let e=this.pcState===eU.New;this.pcState=eU.Connected,e&&this.emit(ek.Connected,this.latestJoinResponse)}else e===eL.FAILED&&(this.pcState===eU.Connected||this.pcState===eU.Reconnecting)&&(this.pcState=eU.Disconnected,this.handleDisconnect("peerconnection failed","failed"===i?ig.RR_SUBSCRIBER_FAILED:ig.RR_PUBLISHER_FAILED));let n=this.client.isDisconnected||this.client.currentState===e_.RECONNECTING,r=[eL.FAILED,eL.CLOSING,eL.CLOSED].includes(e);n&&r&&!this._isClosed&&this.emit(ek.Offline)}),this.pcManager.onTrack=e=>{0!==e.streams.length&&this.emit(ek.MediaTrackAdded,e.track,e.streams[0],e.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>rx(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:i}),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",{candidate:e,target:t}),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,i)=>rx(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;let n=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);n&&this.client.sendAnswer(n,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",{cid:e.cid,track:null===(t=e.track)||void 0===t?void 0:t.sid}),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),{cid:e.cid});return}let{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(ek.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(ek.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e,this.emit(ek.TokenRefreshed,e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(ek.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(ek.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(ek.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(ek.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(ek.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(ek.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect("signal",ig.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.info("client leave request received (action=".concat(null==e?void 0:e.action,")"),{reason:null==e?void 0:e.reason}),e.regions&&(this.log.debug("updating regions"),this.emit(ek.ServerRegionsReported,e.regions)),e.action){case n1.DISCONNECT:this.emit(ek.Disconnected,null==e?void 0:e.reason),this.close();break;case n1.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(ci);break;case n1.RESUME:this.handleDisconnect(ci)}}}makeRTCConfiguration(e){var t,i;let n=Object.assign({},this.rtcConfig);if(((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)||(null===(i=this.options.packetTrailer)||void 0===i?void 0:i.worker)&&!sf())&&s1()&&(this.log.debug("E2EE - setting up transports with insertable streams"),n.encodedInsertableStreams=!0),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",!e)return n;if(e.iceServers&&!n.iceServers){let t=[];
1e.iceServers.forEach(e=>{let i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)}),n.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===ip.ENABLED&&(n.iceTransportPolicy="relay"),n}addMediaSections(e,t){var i,n;let r={direction:"recvonly"};for(let t=0;t<e;t++)null===(i=this.pcManager)||void 0===i||i.addPublisherTransceiverOfKind("audio",r);for(let e=0;e<t;e++)null===(n=this.pcManager)||void 0===n||n.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(o7,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(ce,{ordered:!0}),this.dataTrackDC=this.pcManager.createPublisherDataChannel(ct,{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(eF.LOSSY),this.reliableDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(eF.RELIABLE),this.dataTrackDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(eF.DATA_TRACK_LOSSY),this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;let e=this.dataChannelForKind(eF.LOSSY);if(e){let t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,8192),262144)}},1e3))}createSender(e,t,i){return rx(this,void 0,void 0,function*(){let n;if(su())n=yield this.createTransceiverRTCRtpSender(e,t,i);else if(sh())this.log.warn("using add-track fallback"),n=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new aG("Required webRTC APIs not supported on this device");return this.setupPacketTrailerSender(n,t),n})}createSimulcastSender(e,t,i,n){return rx(this,void 0,void 0,function*(){let r;if(su())r=yield this.createSimulcastTransceiverSender(e,t,i,n);else if(sh())this.log.debug("using add-track fallback"),r=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new aG("Cannot stream on this device");return r&&this.setupPacketTrailerSender(r,i),r})}setupPacketTrailerSender(e){var t,i;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!(null===(t=this.options.packetTrailer)||void 0===t?void 0:t.worker)||(null===(i=this.signalOpts)||void 0===i?void 0:i.e2eeEnabled))return;let r=n.packetTrailer,a=s3(r);if(sf()){a&&(e.transform=new RTCRtpScriptTransform(this.options.packetTrailer.worker,{kind:"encode",packetTrailer:r}));return}if(!s2(this.options.packetTrailer)||!("createEncodedStreams"in e)){a&&this.log.warn("packet trailer transform not supported; skipping write",this.logContext);return}let{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,i){return rx(this,void 0,void 0,function*(){if(!this.pcManager)throw new aG("publisher is closed");let n=[];e.mediaStream&&n.push(e.mediaStream),sz(e)&&(e.codec=t.videoCodec);let r={direction:"sendonly",streams:n};return i&&(r.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,i,n){return rx(this,void 0,void 0,function*(){if(!this.pcManager)throw new aG("publisher is closed");let r={direction:"sendonly"};n&&(r.sendEncodings=n);let a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return rx(this,void 0,void 0,function*(){if(!this.pcManager)throw new aG("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return rx(this,void 0,void 0,function*(){var t,i,n;if(!this._isClosed){if(this.attemptingReconnect){this.log.warn("already attempting reconnect, returning early");return}((null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)===ip.DISABLED||(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==n?n:eL.NEW)===eL.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(t){this.reconnectAttempts+=1;let e=!0;t instanceof aG?(this.log.debug("received unrecoverable error",{error:t}),e=!1):t instanceof aX||(this.fullReconnectOnNext=!0),e?this.handleDisconnect("reconnect",ig.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit
1(ek.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(e){return rx(this,void 0,void 0,function*(){var t,i,n;try{let i;if(!this.url||!this.token)throw new aG("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(ek.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 aX;i=(yield this.join(null!=e?e:this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(e){if(e instanceof aV&&e.reason===ep.NotAllowed)throw new aG("could not reconnect, token might be expired");throw new aX}if(this.shouldFailNext)throw this.shouldFailNext=!1,Error("simulated failure");if(this.client.setReconnected(),this.emit(ek.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==e_.CONNECTED)throw new aX("Signal connection got severed during reconnect");null===(t=this.regionStrategy)||void 0===t||t.resetAttempts(),this.emit(ek.Restarted)}catch(t){let e=yield null===(i=this.regionStrategy)||void 0===i?void 0:i.getNextUrl();if(e){yield this.restartConnection(e);return}throw null===(n=this.regionStrategy)||void 0===n||n.resetAttempts(),t}})}resumeConnection(e){return rx(this,void 0,void 0,function*(){var t;let i;if(!this.url||!this.token)throw new aG("could not reconnect, url or token not saved");if(!this.pcManager)throw new aG("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(ek.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(t){let e="";if(t instanceof Error&&(e=t.message,this.log.error(t.message,{error:t})),t instanceof aV&&t.reason===ep.NotAllowed)throw new aG("could not reconnect, token might be expired");if(t instanceof aV&&t.reason===ep.LeaveRequest)throw t;throw new aX(e)}
1if(this.emit(ek.SignalResumed),i){let 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,Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==e_.CONNECTED)throw new aX("Signal connection got severed during reconnect");this.client.setReconnected(),(null===(t=this.reliableDC)||void 0===t?void 0:t.readyState)==="open"&&null===this.reliableDC.id&&this.createDataChannels(),(null==i?void 0:i.lastMessageSeq)&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(ek.Resumed)})}waitForPCInitialConnection(e,t){return rx(this,void 0,void 0,function*(){if(!this.pcManager)throw new aG("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return rx(this,void 0,void 0,function*(){this.pcState=eU.Reconnecting,this.log.debug("waiting for peer connection to reconnect");try{if(yield sd(2e3),!this.pcManager)throw new aG("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=eU.Connected}catch(e){throw this.pcState=eU.Disconnected,aV.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcAck(e,t){return rx(this,void 0,void 0,function*(){let i=new iN({destinationIdentities:[e],kind:ix.RELIABLE,value:{case:"rpcAck",value:new iG({requestId:t})}});yield this.sendDataPacket(i,eF.RELIABLE)})}sendDataPacket(e,t){return rx(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){let t=function(e){var t,i,n,r,a;if((null===(t=e.value)||void 0===t?void 0:t.case)!=="sipDtmf"&&(null===(i=e.value)||void 0===i?void 0:i.case)!=="metrics"&&(null===(n=e.value)||void 0===n?void 0:n.case)!=="speaker"&&(null===(r=e.value)||void 0===r?void 0:r.case)!=="transcription"&&(null===(a=e.value)||void 0===a?void 0:a.case)!=="encryptedPacket")return new iU({value:e.value})}(e);if(t){let i=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:"encryptedPacket",value:new iL({encryptedValue:i.payload,iv:i.iv,keyIndex:i.keyIndex})}}}t===eF.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);let i=e.toBinary();switch(t){case eF.LOSSY:case eF.DATA_TRACK_LOSSY:return this.sendLossyBytes(i,t);case eF.RELIABLE:let n=this.dataChannelForKind(t);if(n){if(yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:i,sequence:e.sequence}),this.attemptingReconnect)return;n.send(i)}this.updateAndEmitDCBufferStatus(t)}})}sendLossyBytes(e,t){return rx(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"drop";return function*(){yield i.ensurePublisherConnected(t);let r=i.dataChannelForKind(t);if(r){if(!i.isBufferStatusLow(t))switch(n){case"wait":yield i.waitForBufferStatusLow(t);break;case"drop":i.lossyDataDropCount+=1,i.lossyDataDropCount%100==0&&i.log.warn("dropping lossy data channel messages, total dropped: ".concat(i.lossyDataDropCount));return}if(i.lossyDataStatCurrentBytes+=e.byteLength,i.attemptingReconnect)return;r.send(e)}i.updateAndEmitDCBufferStatus(t)}()})}resendReliableMessagesForResume(e){return rx(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(eF.RELIABLE);let t=this.dataChannelForKind(eF.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(e=>{t.send(e.data)})),this.updateAndEmitDCBufferStatus(eF.RELIABLE)})}waitForBufferStatusLow(e){return rx(this,void 0,void 0,function*(){return new aN((t,i)=>rx(this,void 0,void 0,function*(){if(this.isClosed&&i(new aG("engine closed")),this.isBufferStatusLow(e))t();else{let n=this.dataChannelForKind(e);if(!n){i(new aG("DataChannel not found, kind: ".concat(e)));return}this.bufferStatusLowClosingFuture.promise.catch(e=>i(e)),n.addEventListener("bufferedamountlow",()=>t(),{once:!0})}}))})}ensureDataTransportConnected(e){return rx(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var n;if(!t.pcManager)throw new aG("PC manager is closed");let r=i?t.pcManager.subscriber:t.pcManager.publisher,a=i?"Subscriber":"Publisher";if(!r)throw aV.internal("".concat(a," connection not set"));let s=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),s=!0),s||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(s=!0),s&&t.negotiate().catch(e=>{t.log.error(e)});let o=t.dataChannelForKind(e,i);if((null==o?void 0:o.readyState)==="open")return;let c=new Date().getTime()+t.peerConnectionTimeout;for(;new Date().getTime()<c;){if(r.isICEConnected&&(null===(n=t.dataChannelForKind(e,i))||void 0===n?void 0:n.readyState)==="open")return;yield sd(50)}throw aV.internal("could not establish ".concat(a," connection, state: ").concat(r.getICEConnectionState()))}()})}ensurePublisherConnected(e){return rx(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!!(this.pcManager&&[eL.CONNECTING,eL.CONNECTED].includes(this.pcManager.currentState))&&!!this.client.ws&&this.client.ws.readyState!==WebSocket.CLOSED}negotiate(){return rx(this,void 0,void 0,function*(){return new aN((e,t)=>rx(this,void 0,void 0,function*(){if(!this.pcManager){t(new aK("PC manager is closed"));return}this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.dataTrackDC||this.createDataChannels();let i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing"),e()};this.isClosed&&t(new aK("cannot negotiate on closed engine")),this.on(ek.Closing,n),this.on(ek.Restarting,n),this.pcManager.publisher.once(oD.RTPVideoPayloadTypes,e=>{let t=new Map;
1e.forEach(e=>{let i=e.codec.toLowerCase();a1.includes(i)&&t.set(e.payload,i)}),this.emit(ek.RTPVideoMapUpdate,t)});try{yield this.pcManager.negotiate(i),e()}catch(n){if(i.signal.aborted){e();return}n instanceof aK&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ig.RR_UNKNOWN),n instanceof Error?t(n):t(Error(String(n)))}finally{this.off(ek.Closing,n),this.off(ek.Restarting,n)}}))})}dataChannelForKind(e,t){switch(e){case eF.RELIABLE:if(!t)return this.reliableDC;return this.reliableDCSub;case eF.LOSSY:if(!t)return this.lossyDC;return this.lossyDCSub;case eF.DATA_TRACK_LOSSY:if(!t)return this.dataTrackDC;return this.dataTrackDCSub}}sendSyncState(e,t,i){var n,r,a,s;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup");return}let o=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),l=null===(n=this.pcManager.subscriber)||void 0===n?void 0:n.getRemoteDescription(),d=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=[],p=[];e.forEach(e=>{e.isDesired!==u&&h.push(e.trackSid),e.isEnabled||p.push(e.trackSid)}),this.client.sendSyncState(new rl({answer:"publisher-only"===this.pcManager.mode?c?oT({sdp:c.sdp,type:c.type}):void 0:d?oT({sdp:d.sdp,type:d.type}):void 0,offer:"publisher-only"===this.pcManager.mode?o?oT({sdp:o.sdp,type:o.type}):void 0:l?oT({sdp:l.sdp,type:l.type}):void 0,subscription:new nJ({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:function(e){let t=[];return e.forEach(e=>{void 0!==e.track&&t.push(new nW({cid:e.track.mediaStreamID,track:e.trackInfo}))}),t}(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:p,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new rd({publisherSid:t,lastSeq:e})),publishDataTracks:i.map(e=>new nx({info:og(e)}))}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){let e=[],t=(t,i)=>{(null==t?void 0:t.id)!==void 0&&null!==t.id&&e.push(new ru({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(eF.LOSSY),nR.PUBLISHER),t(this.dataChannelForKind(eF.RELIABLE),nR.PUBLISHER),t(this.dataChannelForKind(eF.LOSSY,!0),nR.SUBSCRIBER),t(this.dataChannelForKind(eF.RELIABLE,!0),nR.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&aZ.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){sy()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){sy()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;let i=null===(t=this.pcManager)||void 0===t?void 0:t.getMidForReceiver(e);if(i){let e=Object.entries(this.midToTrackId).find(e=>{let[t]=e;return t===i});if(e)return e[1]}}}function cr(e,t){let i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;let n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}class ca{static fetchRegionSettings(e,t,i){return rx(this,void 0,void 0,function*(){let n=yield ca.fetchLock.lock();try{let n=yield fetch("".concat("".concat(e.protocol.replace("ws","http"),"//").concat(e.host,"/settings"),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(n.ok){let e=function(e){var t;let i=e.get("Cache-Control");if(i){let e=null===(t=i.match(/(?:^|[,\s])max-age=(\d+)/))||void 0===t?void 0:t[1];if(e)return parseInt(e,10)}}(n.headers);return{regionSettings:yield n.json(),updatedAtInMs:Date.now(),maxAgeInMs:e?1e3*e:5e3}}if(401===n.status)throw aV.notAllowed("Could not fetch region settings: ".concat(n.statusText),n.status);throw aV.internal("Could not fetch region settings: ".concat(n.statusText))}catch(e){if(e instanceof aV)throw e;if(null==i?void 0:i.aborted)throw aV.cancelled("Region fetching was aborted");
1throw aV.serverUnreachable("Could not fetch region settings, ".concat(e instanceof Error?"".concat(e.name,": ").concat(e.message):e))}finally{n()}})}static scheduleRefetch(e,t,i){return rx(this,void 0,void 0,function*(){clearTimeout(ca.settingsTimeouts.get(e.hostname)),ca.settingsTimeouts.set(e.hostname,setTimeout(()=>rx(this,void 0,void 0,function*(){try{let i=yield ca.fetchRegionSettings(e,t);ca.updateCachedRegionSettings(e,t,i)}catch(n){if(n instanceof aV&&n.reason===ep.NotAllowed){r_.debug("token is not valid, cancelling auto region refresh");return}r_.debug("auto refetching of region settings failed",{error:n}),ca.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){ca.cache.set(e.hostname,i),ca.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){let t=ca.settingsTimeouts.get(e);t&&(clearTimeout(t),ca.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=ca.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{let t=ca.connectionTrackers.get(e);t&&0===t.connectionCount&&(r_.debug("stopping region refetch after disconnect delay",{hostname:e}),ca.stopRefetch(e)),t&&(t.cleanupTimeout=void 0)},3e4))}static cancelCleanup(e){let t=ca.connectionTrackers.get(e);(null==t?void 0:t.cleanupTimeout)&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){let e=this.serverUrl.hostname,t=ca.connectionTrackers.get(e);t||(t={connectionCount:0},ca.connectionTrackers.set(e,t)),t.connectionCount++,ca.cancelCleanup(e)}notifyDisconnected(){let e=this.serverUrl.hostname,t=ca.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),0===t.connectionCount&&ca.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){var t;this.token=e;let i=this.getServerUrl(),n=ca.cache.get(i.hostname);ca.scheduleRefetch(this.serverUrl,this.token,null!==(t=null==n?void 0:n.maxAgeInMs)&&void 0!==t?t:5e3)}isCloud(){return sS(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return rx(this,void 0,void 0,function*(){return ca.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return rx(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=ca.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),ca.updateCachedRegionSettings(this.serverUrl,this.token,t));let i=t.regionSettings.regions.filter(e=>!this.attemptedRegions.find(t=>t.url===e.url));if(!(i.length>0))return null;{let e=i[0];return this.attemptedRegions.push(e),r_.debug("next region: ".concat(e.region)),e.url}})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){ca.updateCachedRegionSettings(this.serverUrl,this.token,e)}}ca.cache=new Map,ca.settingsTimeouts=new Map,ca.connectionTrackers=new Map,ca.fetchLock=new e3;class cs{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if("number"==typeof this.totalByteSize&&0!==this.totalByteSize){if(e&&this.bytesReceived<this.totalByteSize)throw new aY("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),em.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new aY("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),em.LengthExceeded)}}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class co extends cs{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,i)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>rx(this,void 0,void 0,function*(){try{let t=this.signal;if(null==t?void 0:t.aborted)throw t.reason;let i=yield new Promise((i,n)=>{if(t){let r=()=>n(t.reason);t.addEventListener("abort",r,{once:!0}),e.read().then(i,n).finally(()=>{t.removeEventListener("abort",r)})}else e.read().then(i,n)});if(i.done)return this.validateBytesReceived(!0),{done:!0,value:void 0};return this.handleChunkReceived(i.value),{done:!1,value:i.value.content}}catch(e){throw t(),e}}),return(){return rx(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return rx(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,r,a;let s=new Set,o=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,l=!0,d=rU(o);!(i=(c=yield d.next()).done);l=!0)a=c.value,l=!1,s.add(a)}catch(e){n={error:e}}finally{try{!l&&!i&&(r=d.return)&&(yield r.call(d))}finally{if(n)throw n.error}}return Array.from(s)}()})}}class cc extends cs{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;let i=sq(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,r)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=new TextDecoder("utf-8",{fatal:!0}),i=this.signal,n=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>rx(this,void 0,void 0,function*(){try{if(null==i?void 0:i.aborted)throw i.reason;let n=yield new Promise((t,n)=>{if(i){let r=()=>n(i.reason);i.addEventListener("abort",r,{once:!0}),e.read().then(t,n).finally(()=>{i.removeEventListener("abort",r)})}else e.read().then(t,n)});if(n.done)return this.validateBytesReceived(!0),{done:!0,value:void 0};{let e;this.handleChunkReceived(n.value);try{e=t.decode(n.value.content)}catch(e){throw new aY("Cannot decode datastream chunk ".concat(n.value.chunkIndex," as text: ").concat(e),em.DecodeFailed)}return{done:!1,value:e}}}catch(e){throw n(),e}}),return(){return rx(this,void 0,void 0,function*(){return n(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return rx(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,r,a;let s="",o=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,l=!0,d=rU(o);!(i=(c=yield d.next()).done);l=!0)a=c.value,l=!1,s+=a}catch(e){n={error:e}}finally{try{!l&&!i&&(r=d.return)&&(yield r.call(d))}finally{if(n)throw n.error}}return s}()})}}class cl{constructor(){this.log=r_,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(){let e=this.bufferedPackets;for(let{packet:t,encryptionType:i}of(this.bufferedPackets=[],e))this.handleDataStreamPacket(t,i)}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new aY('A text stream handler for topic "'.concat(e,'" has already been set.'),em.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new aY('A byte stream handler for topic "'.concat(e,'" has already been set.'),em.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}
1validateParticipantHasNoActiveDataStreams(e){let t=Array.from(this.textStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e),i=Array.from(this.byteStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e);if(t.length>0||i.length>0){let n=new aY("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),em.AbnormalEnd);for(let[e,t]of i)t.controller.error(n),this.byteStreamControllers.delete(e);for(let[e,i]of t)i.controller.error(n),this.textStreamControllers.delete(e)}}handleDataStreamPacket(e,t){if(!this.isConnected){this.bufferedPackets.push({packet:e,encryptionType:t});return}switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}}handleStreamHeader(e,t,i){var n;if("byteHeader"===e.contentHeader.case){let r;let a=this.byteStreamHandlers.get(e.topic);if(!a){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let s={id:e.streamId,name:null!==(n=e.contentHeader.value.name)&&void 0!==n?n:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:sq(e.timestamp),attributes:e.attributes,encryptionType:i},o=new ReadableStream({start:i=>{if(r=i,this.textStreamControllers.has(e.streamId))throw new aY("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),em.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:s,controller:r,startTime:Date.now(),sendingParticipantIdentity:t})}});a(new co(s,o,sq(e.totalLength)),{identity:t})}else if("textHeader"===e.contentHeader.case){let n;let r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let a={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:i,attachedStreamIds:e.contentHeader.value.attachedStreamIds},s=new ReadableStream({start:i=>{if(n=i,this.textStreamControllers.has(e.streamId))throw new aY("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),em.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:a,controller:n,startTime:Date.now(),sendingParticipantIdentity:t})}});r(new cc(a,s,sq(e.totalLength)),{identity:t})}}handleStreamChunk(e,t){let i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new aY("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),em.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));let n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new aY("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),em.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&n.controller.enqueue(e))}handleStreamTrailer(e,t){let i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new aY("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),em.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));let n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new aY("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),em.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class cd{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return rx(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 cu extends cd{}class ch extends cd{}class cp{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return rx(this,void 0,void 0,function*(){var i;let n=crypto.randomUUID(),r=new TextEncoder().encode(e).byteLength,a=null===(i=null==t?void 0:t.attachments)||void 0===i?void 0:i.map(()=>crypto.randomUUID()),s=Array(a?a.length+1:1).fill(0),o=(e,i)=>{var n;s[i]=e;let r=s.reduce((e,t)=>
1e+t,0);null===(n=null==t?void 0:t.onProgress)||void 0===n||n.call(t,r)},c=yield this.streamText({streamId:n,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,i)=>rx(this,void 0,void 0,function*(){return this._sendFile(a[i],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{o(e,i+1)}})})))),c.info})}streamText(e){return rx(this,void 0,void 0,function*(){var t,i,n;let r=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),a={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==e?void 0:e.topic)&&void 0!==i?i:"",size:null==e?void 0:e.totalSize,attributes:null==e?void 0:e.attributes,encryptionType:(null===(n=this.engine.e2eeManager)||void 0===n?void 0:n.isDataChannelEncryptionEnabled)?iR.GCM:iR.NONE,attachedStreamIds:null==e?void 0:e.attachedStreamIds},s=new i5({streamId:r,mimeType:a.mimeType,topic:a.topic,timestamp:sV(a.timestamp),totalLength:sV(a.size),attributes:a.attributes,contentHeader:{case:"textHeader",value:new i6({version:null==e?void 0:e.version,attachedStreamIds:a.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:(null==e?void 0:e.type)==="update"?i9.UPDATE:i9.CREATE})}}),o=null==e?void 0:e.destinationIdentities,c=new iN({destinationIdentities:o,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(c,eF.RELIABLE);let l=0,d=this.engine,u=new WritableStream({write(e){return rx(this,void 0,void 0,function*(){for(let t of function(e,t){let i=[],n=new TextEncoder().encode(e);for(;n.length>15e3;){let e=15e3;for(;e>0;){let t=n[e];if(void 0!==t&&(192&t)!=128)break;e--}i.push(n.slice(0,e)),n=n.slice(e)}return n.length>0&&i.push(n),i}(e,0)){let e=new iN({destinationIdentities:o,value:{case:"streamChunk",value:new i7({content:t,streamId:r,chunkIndex:sV(l)})}});yield d.sendDataPacket(e,eF.RELIABLE),l+=1}})},close(){return rx(this,void 0,void 0,function*(){let e=new iN({destinationIdentities:o,value:{case:"streamTrailer",value:new ne({streamId:r})}});yield d.sendDataPacket(e,eF.RELIABLE)})},abort(e){console.log("Sink error:",e)}}),h=()=>rx(this,void 0,void 0,function*(){yield p.close()});d.once(ek.Closing,h);let p=new cu(u,a,()=>this.engine.off(ek.Closing,h));return p})}sendFile(e,t){return rx(this,void 0,void 0,function*(){let i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return rx(this,void 0,void 0,function*(){var n;let r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(n=null==i?void 0:i.mimeType)&&void 0!==n?n:t.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),a=t.stream().getReader();for(;;){let{done:e,value:t}=yield a.read();if(e)break;yield r.write(t)}return yield r.close(),r.info})}streamBytes(e){return rx(this,void 0,void 0,function*(){var t,i,n,r,a;let s=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),o=null==e?void 0:e.destinationIdentities,c={id:s,mimeType:null!==(i=null==e?void 0:e.mimeType)&&void 0!==i?i:"application/octet-stream",topic:null!==(n=null==e?void 0:e.topic)&&void 0!==n?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!==(r=null==e?void 0:e.name)&&void 0!==r?r:"unknown",encryptionType:(null===(a=this.engine.e2eeManager)||void 0===a?void 0:a.isDataChannelEncryptionEnabled)?iR.GCM:iR.NONE},l=new iN({destinationIdentities:o,value:{case:"streamHeader",value:new i5({totalLength:sV(c.size),mimeType:c.mimeType,streamId:s,topic:c.topic,timestamp:sV(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new i8({name:c.name})}})}});yield this.engine.sendDataPacket(l,eF.RELIABLE);let d=0,u=new e3,h=this.engine,p=this.log;return new ch(new WritableStream({write(e){return rx(this,void 0,void 0,function*(){let t=yield u.lock(),i=0;try{for(;i<e.byteLength;){let t=e.slice(i,i+15e3),n=new iN({destinationIdentities:o,value:{case:"streamChunk",value:new i7({content:t,streamId:s,chunkIndex:sV(d)})}});yield h.sendDataPacket(n,eF.RELIABLE),d+=1,i+=t.byteLength}}finally{t()}})},close(){return rx(this,void 0,void 0,function*(){let e=new iN({destinationIdentities:o,value:{case:"streamTrailer",value:new ne({streamId:s})}});yield h.sendDataPacket(e,eF.RELIABLE)})},abort(e){p.error("Sink error:",e)}}),c)})}}function cm(e){if(0===e.length)return new AbortController().signal;if(1===e.length)return e[0];for(let t of e)if(t.aborted)return t;let t=new AbortController,i=Array(e.length),n=()=>{for(let e of i)e()};return e.forEach((e,r)=>{let a=()=>{t.abort(e.reason),n()};e.addEventListener("abort",a),i[r]=()=>e.removeEventListener("abort",a)}),t.signal}function cg(e){let t=new AbortController;return setTimeout(()=>{t.abort(new DOMException("signal timed out after ".concat(e," ms"),"TimeoutError"))},e),t.signal}(q=eB||(eB={}))[q.TooShort=0]="TooShort",q[q.HeaderOverrun=1]="HeaderOverrun",q[q.MissingExtWords=2]="MissingExtWords",q[q.UnsupportedVersion=3]="UnsupportedVersion",q[q.InvalidHandle=4]="InvalidHandle",q[q.MalformedExt=5]="MalformedExt";class cf extends aq{constructor(e,t,i){super(19,e,i),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=eB[t]}static tooShort(){return new cf("Too short to contain a valid header",eB.TooShort)}static headerOverrun(){return new cf("Header exceeds total packet length",eB.HeaderOverrun)}static missingExtWords(){return new cf("Extension word indicator is missing",eB.MissingExtWords)}static unsupportedVersion(e){return new cf("Unsupported version ".concat(e),eB.UnsupportedVersion)}
1static invalidHandle(e){return new cf("invalid track handle: ".concat(e.message),eB.InvalidHandle,{cause:e})}static malformedExt(e){return new cf("Extension with tag ".concat(e," is malformed"),eB.MalformedExt)}}(V=ej||(ej={}))[V.TooSmallForHeader=0]="TooSmallForHeader",V[V.TooSmallForPayload=1]="TooSmallForPayload";class cv extends aq{constructor(e,t,i){super(19,e,i),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=ej[t]}static tooSmallForHeader(){return new cv("Buffer cannot fit header",ej.TooSmallForHeader)}static tooSmallForPayload(){return new cv("Buffer cannot fit payload",ej.TooSmallForPayload)}}class ck{toBinary(){let e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),i=new DataView(t),n=this.toBinaryInto(i);if(e!==n)throw Error("".concat(this.constructor.name,".toBinary: written bytes (").concat(n," bytes) not equal to allocated array buffer length (").concat(e," bytes)."));return new Uint8Array(t)}}(H=eq||(eq={}))[H.UserTimestamp=2]="UserTimestamp",H[H.E2ee=1]="E2ee";class cb extends ck{}class cy extends cb{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return 2+cy.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,cy.tag),t+=1,e.setUint8(t,cy.lengthBytes),t+=1,e.setBigUint64(t,this.timestamp),t+=8;let i=this.toBinaryLengthBytes();if(t!==i)throw Error("DataTrackUserTimestampExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}toJSON(){return{tag:cy.tag,lengthBytes:cy.lengthBytes,timestamp:this.timestamp}}}cy.tag=eq.UserTimestamp,cy.lengthBytes=8;class cT extends cb{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return 2+cT.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,cT.tag),t+=1,e.setUint8(t,cT.lengthBytes),t+=1,e.setUint8(t,this.keyIndex),t+=1;for(let i=0;i<this.iv.length;i+=1)e.setUint8(t,this.iv[i]),t+=1;let i=this.toBinaryLengthBytes();if(t!==i)throw Error("DataTrackE2eeExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}toJSON(){return{tag:cT.tag,lengthBytes:cT.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}}cT.tag=eq.E2ee,cT.lengthBytes=13;class cS extends ck{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)),this.userTimestamp){let i=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=i}let i=this.toBinaryLengthBytes();if(t!==i)throw Error("DataTrackExtensions.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}static fromBinary(e){let t,i;let n=od(e),r=0;for(;n.byteLength-r>=2;){let e=n.getUint8(r);r+=1;let a=n.getUint8(r);if(r+=1,0!==e)switch(e){case eq.UserTimestamp:if(n.byteLength-r<cy.lengthBytes)throw cf.malformedExt(e);t=new cy(n.getBigUint64(r)),r+=a;break;case eq.E2ee:if(n.byteLength-r<cT.lengthBytes)throw cf.malformedExt(e);let s=n.getUint8(r),o=new Uint8Array(12);for(let e=0;e<o.length;e+=1){let t=r;t+=1+1*e,o[e]=n.getUint8(t)}i=new cT(s,o),r+=a;break;default:if(n.byteLength-r<a)throw cf.malformedExt(e);r+=a}}return[new cS({userTimestamp:t,e2ee:i}),n.byteLength]}toJSON(){var e,t,i,n;return{userTimestamp:null!==(t=null===(e=this.userTimestamp)||void 0===e?void 0:e.toJSON())&&void 0!==t?t:null,e2ee:null!==(n=null===(i=this.e2ee)||void 0===i?void 0:i.toJSON())&&void 0!==n?n:null}}}let cC={from:e=>({payload:e.payload,extensions:new cS({userTimestamp:e.userTimestamp?new cy(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}}},cE=Symbol.for("lk.track"),cw=Symbol.for("lk.data-track");class cP{constructor(e,t,i){this.trackSymbol=cE,this.isLocal=!1,this.typeSymbol=cw,this.info=e,this.manager=t,this.publisherIdentity=i.publisherIdentity}subscribe(e){try{let[t,i]=this.manager.openSubscriptionStream(this.info.sid,null==e?void 0:e.signal,null==e?void 0:e.bufferSize);return i.catch(()=>{}),t}catch(e){throw e}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}}class cR extends ck{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 cS}extensionsMetrics(){let e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((2+e)/4);return{lengthBytes:e,lengthWords:t,paddingLengthBytes:4*t-2-e}}toBinaryLengthBytes(){let{lengthBytes:e,paddingLengthBytes:t}=this.extensionsMetrics(),i=12;return e>0&&(i+=2+e+t),i}toBinaryInto(e){let t;if(e.byteLength<this.toBinaryLengthBytes())throw cv.tooSmallForHeader();let i=0;switch(this.marker){case eV.Inter:t=0;break;case eV.Final:t=1;break;case eV.Start:t=2;break;case eV.Single:t=3}i|=t<<3;let{lengthBytes:n,lengthWords:r,paddingLengthBytes:a}=this.extensionsMetrics();n>0&&(i|=4);let s=0;if(e.setUint8(s,i),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,n>0){e.setUint16(s,r-1),s+=2;let t=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+s));s+=t;for(let t=0;t<a;t+=1)e.setUint8(s,0),s+=1}let o=this.toBinaryLengthBytes();if(s!==o)throw Error("DataTrackPacketHeader.toBinaryInto: Wrote ".concat(s," bytes but expected length
1was ").concat(o," bytes"));return o}static fromBinary(e){let t,i;let n=od(e);if(n.byteLength<12)throw cf.tooShort();let r=0,a=n.getUint8(r);r+=1;let s=a>>5&7;if(s>0)throw cf.unsupportedVersion(s);switch(a>>3&3){case 2:t=eV.Start;break;case 1:t=eV.Final;break;case 3:t=eV.Single;break;default:t=eV.Inter}r+=1;try{i=oh.fromNumber(n.getUint16(r))}catch(e){if(e instanceof ou&&(e.isReason(eI.Reserved)||e.isReason(eI.TooLarge)))throw cf.invalidHandle(e);throw e}r+=2;let o=oo.u16(n.getUint16(r));r+=2;let c=oo.u16(n.getUint16(r));r+=2;let l=oc.fromRtpTicks(n.getUint32(r));r+=4;let d=new cS;if((a>>2&1)>0){if(n.byteLength-r<2)throw cf.missingExtWords();let e=4*(n.getUint16(r)+1)-2;if((r+=2)+e>n.byteLength)throw cf.headerOverrun();let t=new DataView(n.buffer,n.byteOffset+r,e),[i,a]=cS.fromBinary(t);d=i,r+=a}return[new cR({marker:t,trackHandle:i,sequence:o,frameNumber:c,timestamp:l,extensions:d}),r]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}}(W=eV||(eV={}))[W.Start=0]="Start",W[W.Inter=1]="Inter",W[W.Final=2]="Final",W[W.Single=3]="Single";class cI extends ck{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t;if(t=0+this.header.toBinaryInto(e),e.byteLength-t<this.payload.byteLength)throw cv.tooSmallForPayload();for(let i=0;i<this.payload.length;i+=1)e.setUint8(t,this.payload[i]),t+=1;let i=this.toBinaryLengthBytes();if(t!==i)throw Error("DataTrackPacket.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return i}static fromBinary(e){let t=od(e),[i,n]=cR.fromBinary(t);return[new cI(i,new Uint8Array(t.buffer.slice(t.byteOffset+n,t.byteOffset+t.byteLength))),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}}let cD=rM(el.DataTracks);class c_ extends aq{constructor(e,t,i,n){super(19,"Frame ".concat(i," dropped: ").concat(e),n),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=eH[t],this.frameNumber=i}static interrupted(e,t){return new c_("Interrupted by the start of a new frame ".concat(t),eH.Interrupted,e)}static unknownFrame(e){return new c_("Initial packet was never received.",eH.UnknownFrame,e)}static bufferFull(e){return new c_("Reorder buffer is full.",eH.BufferFull,e)}static incomplete(e,t,i){return new c_("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(i," packets."),eH.Incomplete,e)}}(z=eH||(eH={}))[z.Interrupted=0]="Interrupted",z[z.UnknownFrame=1]="UnknownFrame",z[z.BufferFull=2]="BufferFull",z[z.Incomplete=3]="Incomplete";class cM{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case eV.Single:return this.frameFromSingle(e,t);case eV.Start:return this.beginPartial(e,t);case eV.Inter:case eV.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){let e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){var i;if(e.header.marker!==eV.Single)throw Error("Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ".concat(e.header.marker,"."));let n=null!==(i=null==t?void 0:t.maxPartialFrames)&&void 0!==i?i:1;if(this.partials.size>=n){let i=this.peekOldestPartialFrameNumber();if("number"!=typeof i)throw Error("Depacketizer.frameFromSingle: no olde
1st frame number found, but partials.size is ".concat(this.partials.size,"."));if(this.partials.delete(i),null==t?void 0:t.throwOnInterruption)throw c_.interrupted(i,e.header.frameNumber.value);cD.warn("Data track frame ".concat(i," was interrupted by single-packet frame ").concat(e.header.frameNumber.value,", dropping."))}return{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){var i;if(e.header.marker!==eV.Start)throw Error("Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ".concat(e.header.marker,"."));let n=e.header.sequence,r=e.header.frameNumber.value,a={startSequence:n,extensions:e.header.extensions,payloads:new Map([[n.value,e.payload]])},s=null!==(i=null==t?void 0:t.maxPartialFrames)&&void 0!==i?i:1;for(;this.partials.size>=s;){let e=this.peekOldestPartialFrameNumber();if("number"!=typeof e)break;if(this.partials.delete(e),null==t?void 0:t.throwOnInterruption)throw c_.interrupted(e,r);cD.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!==eV.Inter&&e.header.marker!==eV.Final)throw Error("Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ".concat(e.header.marker,"."));let t=e.header.frameNumber.value,i=this.partials.get(t);if(!i)throw this.partials.delete(t),c_.unknownFrame(t);if(i.payloads.size>=cM.MAX_BUFFER_PACKETS)throw this.partials.delete(t),c_.bufferFull(t);return(i.payloads.has(e.header.sequence.value)&&cD.warn("Data track frame ".concat(t," received duplicate packet for sequence ").concat(e.header.sequence.value,", so replacing with newly received packet.")),i.payloads.set(e.header.sequence.value,e.payload),e.header.marker===eV.Final)?this.finalize(t,i,e.header.sequence.value):null}finalize(e,t,i){let n=t.payloads.size,r=0;for(let e of t.payloads.values())r+=e.length;let a=new Uint8Array(r),s=t.startSequence.clone(),o=0;for(;;){let n=t.payloads.get(s.value);if(!n)break;t.payloads.delete(s.value);let r=a.length-o;if(n.length>r)throw Error("Depacketizer.finalize: Expected at least ".concat(n.length," more bytes left in the payload buffer, only got ").concat(r," bytes."));if(a.set(n,o),o+=n.length,s.value!=i){s.increment();continue}return this.partials.delete(e),{payload:a,extensions:t.extensions}}throw this.partials.delete(e),c_.incomplete(e,n,i-t.startSequence.value+1)}}cM.MAX_BUFFER_PACKETS=128,(G=eW||(eW={}))[G.Unpublished=0]="Unpublished",G[G.Timeout=1]="Timeout",G[G.Disconnected=2]="Disconnected",G[G.Cancelled=4]="Cancelled";class cO extends aq{constructor(e,t,i){super(22,e,i),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=eW[t]}static unpublished(){return new cO("The track has been unpublished and is no longer available",eW.Unpublished)}static timeout(){return new cO("Request to subscribe to data track timed-out",eW.Timeout)}static disconnected(){return new cO("Cannot subscribe to data track when disconnected",eW.Disconnected)}static cancelled(){return new cO("Subscription to data track cancelled by caller",eW.Cancelled)}}let cA=rM(el.DataTracks);class cN{constructor(e){var t,i;let n=null!==e.e2eeManager;if(e.info.usesE2ee!==n)throw Error("IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider");let r=new cM;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=null!==(t=e.e2eeManager)&&void 0!==t?t:null,this.depacketizer=r,this.options=null!==(i=e.pipelineOptions)&&void 0!==i?i:{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return rx(this,void 0,void 0,function*(){let t=this.depacketize(e);return t&&(yield this.decryptIfNeeded(t))||null})}depacketize(e){let t;try{t=this.depacketizer.push(e,{throwOnInterruption:!1,maxPartialFrames:this.options.maxPartialFrames})}catch(e){return cA.warn("Data frame depacketize error: ".concat(e)),null}return t}decryptIfNeeded(e){return rx(this,void 0,void 0,function*(){var t,i;let n;let r=this.e2eeManager;if(!r)return e;let a=null!==(i=null===(t=e.extensions)||void 0===t?void 0:t.e2ee)&&void 0!==i?i:null;if(!a)return cA.error("Missing E2EE meta"),null;try{n=yield r.handleEncryptedData(e.payload,a.iv,this.publisherIdentity,a.keyIndex)}catch(e){return cA.error("Error decrypting packet: ".concat(e)),null}return e.payload=n.payload,e})}}let cx=rM(el.DataTracks);class cL extends rB.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){for(let t of(this.e2eeManager=e,this.descriptors.values())
1)"active"===t.subscription.type&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){let i=this.descriptors.get(e);if(!i){cx.warn("Unknown track ".concat(e,", cannot set pipeline options."));return}i.pipelineOptions=t,"active"===i.subscription.type&&i.subscription.pipeline.setOptions(t)}openSubscriptionStream(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16,n=null,r=new sL,a=()=>{null==t||t.removeEventListener("abort",o)},s=()=>{if(a(),!n){cx.warn("ReadableStream subscribed to ".concat(e," was not started."));return}let t=this.descriptors.get(e);if(!t){cx.warn("Unknown track ".concat(e,", skipping cancel..."));return}if("active"!==t.subscription.type){cx.warn("Subscription for track ".concat(e," is not active, skipping cancel..."));return}t.subscription.streamControllers.delete(n),0===t.subscription.streamControllers.size&&this.unSubscribeRequest(t.info.sid)},o=()=>{var t;if(!n)return;let i=this.descriptors.get(e);(null==i?void 0:i.subscription.type)==="active"&&i.subscription.streamControllers.delete(n),n.error(cO.cancelled()),null===(t=r.reject)||void 0===t||t.call(r,cO.cancelled()),s()};return[new ReadableStream({start:i=>{n=i,this.subscribeRequest(e,t).then(()=>rx(this,void 0,void 0,function*(){var n,s,c;let l=this.descriptors.get(e);if(!l){cx.error("Unknown track ".concat(e));let t=cO.disconnected();i.error(t),null===(n=r.reject)||void 0===n||n.call(r,t);return}if("active"!==l.subscription.type){cx.error("Subscription for track ".concat(e," is not active"));let t=cO.disconnected();i.error(t),null===(s=r.reject)||void 0===s||s.call(r,t);return}if(null==t?void 0:t.aborted){o();return}null==t||t.addEventListener("abort",o),l.subscription.streamControllers.set(i,a),null===(c=r.resolve)||void 0===c||c.call(r)})).catch(e=>{var t;i.error(e),null===(t=r.reject)||void 0===t||t.call(r,e)})},cancel:()=>{s()}},new CountQueuingStrategy({highWaterMark:i})),r.promise]}subscribeRequest(e,t){return rx(this,void 0,void 0,function*(){let i=this.descriptors.get(e);if(!i)throw Error("Cannot subscribe to unknown track");let n=(t,i,n)=>rx(this,void 0,void 0,function*(){if("active"===t.subscription.type)return;if("pending"!==t.subscription.type)throw Error("Descriptor for track ".concat(e," is not pending, found ").concat(t.subscription.type));let r=cm([i,n].filter(e=>void 0!==e)),a=new sL;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)});let s=()=>{var e;if("pending"===t.subscription.type){if(t.subscription.pendingRequestCount-=1,(null==n?void 0:n.aborted)||t.subscription.pendingRequestCount<=0){t.subscription.cancel();return}null===(e=a.reject)||void 0===e||e.call(a,cO.cancelled())}};r.aborted&&s(),r.addEventListener("abort",s),yield a.promise,r.removeEventListener("abort",s)});switch(i.subscription.type){case"none":{i.subscription={type:"pending",completionFuture:new sL,pendingRequestCount:1,cancel:()=>{var t,n;let a=i.subscription;i.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1}),"pending"===a.type&&(null===(n=(t=a.completionFuture).reject)||void 0===n||n.call(t,r.aborted?cO.timeout():cO.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});let r=cg(1e4);yield n(i,t,r);return}case"pending":i.subscription.pendingRequestCount+=1,yield n(i,t);return;case"active":return}})}querySubscribed(){return rx(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;let i=this.descriptors.get(e);if(!i)throw Error("Cannot subscribe to unknown track");if("active"!==i.subscription.type){cx.warn("Unexpected descriptor state in unSubscribeRequest, expected active, found ".concat(null===(t=i.subscription)||void 0===t?void 0:t.type));return}this.closeStreamControllers(i.subscription.streamControllers,e);let n=i.subscription;i.subscription={type:"none"}
1,this.subscriptionHandles.delete(n.subcriptionHandle),this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(let[i,n]of e){n();try{i.close()}catch(e){cx.warn("Failed to close readable stream for track ".concat(t,": ").concat(e))}}}receiveSfuPublicationUpdates(e){return rx(this,void 0,void 0,function*(){if(0===e.size)return;let t=new Map;for(let[i,n]of e.entries()){let e=new Set;for(let t of n)e.add(t.sid),this.descriptors.has(t.sid)||(yield this.handleTrackPublished(i,t));t.set(i,e)}for(let[e,i]of t.entries())for(let t of Array.from(this.descriptors.entries()).filter(t=>{let[i,n]=t;return n.publisherIdentity===e}).map(e=>{let[t]=e;return t}).filter(e=>!i.has(e)))this.handleTrackUnpublished(t)})}queryPublications(){return rx(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return rx(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){cx.error("Existing descriptor for track ".concat(t.sid));return}let i={info:t,publisherIdentity:e,subscription:{type:"none"},pipelineOptions:{}};this.descriptors.set(i.info.sid,i);let n=new cP(i.info,this,{publisherIdentity:e});this.emit("trackPublished",{track:n})})}handleTrackUnpublished(e){let t=this.descriptors.get(e);if(!t){cx.error("Unknown track ".concat(e));return}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})}receivedSfuSubscriberHandles(e){for(let[t,i]of e.entries())this.registerSubscriberHandle(t,i)}registerSubscriberHandle(e,t){var i,n;let r=this.descriptors.get(t);if(!r){cx.error("Unknown track ".concat(t));return}switch(r.subscription.type){case"none":cx.warn("No subscription for ".concat(t));return;case"active":r.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return;case"pending":{let a=new cN({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===(n=(i=s.completionFuture).resolve)||void 0===n||n.call(i)}}}packetReceived(e){return rx(this,void 0,void 0,function*(){let t;try{[t]=cI.fromBinary(e)}catch(e){cx.error("Failed to deserialize packet: ".concat(e));return}let i=this.subscriptionHandles.get(t.header.trackHandle);if(!i){cx.warn("Unknown subscriber handle ".concat(t.header.trackHandle));return}let n=this.descriptors.get(i);if(!n){cx.error("Missing descriptor for track ".concat(i));return}if("active"!==n.subscription.type){cx.warn("Received packet for track ".concat(i," without active subscription"));return}let r=yield n.subscription.pipeline.processPacket(t);if(r)for(let e of n.subscription.streamControllers.keys()){if(null!==e.desiredSize&&e.desiredSize<=0){cx.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}let t=cC.lossyIntoFrame(r);e.enqueue(t)}})}resendSubscriptionUpdates(){for(let[e,t]of this.descriptors)"none"!==t.subscription.type&&this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0})}handleRemoteParticipantDisconnected(e){var t,i;for(let n of this.descriptors.values())if(n.publisherIdentity===e)switch(n.subscription.type){case"none":break;case"pending":null===(i=(t=n.subscription.completionFuture).reject)||void 0===i||i.call(t,cO.disconnected());break;case"active":this.unSubscribeRequest(n.info.sid)}}reset(){var e,t;
1for(let i of this.descriptors.values())this.emit("trackUnpublished",{sid:i.info.sid,publisherIdentity:i.publisherIdentity}),"pending"===i.subscription.type&&(null===(t=(e=i.subscription.completionFuture).reject)||void 0===t||t.call(e,cO.disconnected())),"active"===i.subscription.type&&this.closeStreamControllers(i.subscription.streamControllers,i.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}}class cU extends aq{constructor(e,t,i){super(19,e,i),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=ez[t]}static mtuTooShort(){return new cU("MTU is too short to send frame",ez.MtuTooShort)}}(K=ez||(ez={}))[K.MtuTooShort=0]="MtuTooShort";class cF{constructor(e,t){this.sequence=oo.u16(0),this.frameNumber=oo.u16(0),this.clock=ol.rtpStartingNow(oc.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?eV.Single:0===e?eV.Start:e===t-1?eV.Final:eV.Inter}*packetize(e,t){var i;let n=this.frameNumber.getThenIncrement(),r={marker:eV.Inter,trackHandle:this.handle,sequence:oo.u16(0),frameNumber:n,timestamp:null!==(i=null==t?void 0:t.now)&&void 0!==i?i:this.clock.now(),extensions:e.extensions},a=new cR(r).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw cU.mtuTooShort();let s=this.mtuSizeBytes-a,o=Math.ceil(e.payload.byteLength/s);for(let t=0,i=0;i<e.payload.byteLength;[t,i]=[t+1,i+s]){let n=this.sequence.getThenIncrement(),a=new cR(Object.assign(Object.assign({},r),{marker:cF.computeFrameMarker(t,o),sequence:n})),c=Math.min(s,e.payload.byteLength-i),l=new Uint8Array(e.payload.buffer,e.payload.byteOffset+i,c);yield new cI(a,l)}}}(J=eG||(eG={}))[J.NotAllowed=0]="NotAllowed",J[J.DuplicateName=1]="DuplicateName",J[J.Timeout=2]="Timeout",J[J.LimitReached=3]="LimitReached",J[J.Disconnected=4]="Disconnected",J[J.Cancelled=5]="Cancelled",J[J.InvalidName=6]="InvalidName",J[J.Unknown=7]="Unknown";class cB extends aq{constructor(e,t,i){super(21,e,i),this.name="DataTrackPublishError",this.reason=t,this.reasonName=eG[t],this.rawMessage=null==i?void 0:i.rawMessage}static notAllowed(e){return new cB("Data track publishing unauthorized",eG.NotAllowed,{rawMessage:e})}static duplicateName(e){return new cB("Track name already taken",eG.DuplicateName,{rawMessage:e})}static invalidName(e){return new cB("Track name is invalid",eG.InvalidName,{rawMessage:e})}static timeout(){return new cB("Publish data track timed-out. Does the LiveKit server support data tracks?",eG.Timeout)}static limitReached(e){return new cB("Data track publication limit reached",eG.LimitReached,{rawMessage:e})}static unknown(e,t){return new cB("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),eG.Unknown)}static disconnected(){return new cB("Room disconnected",eG.Disconnected)}static cancelled(){return new cB("Publish data track cancelled by caller",eG.Cancelled)}}(Q=eK||(eK={}))[Q.TrackUnpublished=0]="TrackUnpublished",Q[Q.Dropped=1]="Dropped";class cj extends aq{constructor(e,t,i){super(22,e,i),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=eK[t]}static trackUnpublished(){return new cj("Track is no longer published",eK.TrackUnpublished)}static dropped(e){return new cj("Frame was dropped",eK.Dropped,{cause:e})}}(Y=eJ||(eJ={}))[Y.Packetizer=0]="Packetizer",Y[Y.Encryption=1]="Encryption";class cq extends aq{constructor(e,t,i){super(21,e,i),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=eJ[t]}static packetizer(e){return new cq("Error packetizing frame",eJ.Packetizer,{cause:e})}static encryption(e){return new cq("Error encrypting frame",eJ.Encryption,{cause:e})}}class cV{constructor(e,t){this.trackSymbol=cE,this.isLocal=!0,this.typeSymbol=cw,this.handle=null,this.log=r_,this.flushedFuture=new sL,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,i;this.isFlushed=e.isFlushed,e.isFlushed&&(null===(i=(t=this.flushedFuture).resolve)||void 0===i||i.call(t),this.flushedFuture=new sL)},this.options=e,this.manager=t,this.log=rM(el.DataTracks),this.manager.on("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.on("reset",this.handleManagerReset)}static withExplicitHandle(e,t,i){let n=new cV(e,t);return n.handle=i,n}get info(){let e=this.descriptor;return(null==e?void 0:e.type)==="active"?e.info:void 0}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return rx(this,void 0,void 0,function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(e){throw e}})}isPublished(){var e;return(null===(e=this.descriptor)||void 0===e?void 0:e.type)==="active"&&"unpublished"!==this.descriptor.publishState}tryPush(e){if(!this.handle)throw cj.trackUnpublished();let t=cC.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(e){throw e}}flush(){return rx(this,void 0,void 0,function*(){if(!this.isFlushed)return this.flushedFuture.promise})}unpublish(){return rx(this,void 0,void 0,function*(){if(!this.handle){r_.warn('Data track "'.concat(this.options.name,'" is not published, so unpublishing has no effect.'));return}try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}})}}class cH{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new cF(e.info.pubHandle,cH.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return function(e,t,i){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var n,r=i.apply(e,t||[]),a=[];return n=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,l)}}),n[Symbol.asyncIterator]=function(){return this},n;function s(e,t){r[e]&&(n[e]=function(t){return new Promise(function(i,n){a.push([e,t,i,n])>1||o(e,t)})},t&&(n[e]=t(n[e])))}function o(e,t){try{var i;(i=r[e](t)).value instanceof rL?Promise.resolve(i.value.v).then(c,l):d(a[0][2],i)}catch(e){d(a[0][3],e)}}function c(e){o("next",e)}function l(e){o("throw",e)}function d(e,t){e(t),a.shift(),a.length&&o(a[0][0],a[0][1])}}(this,arguments,function*(){let t=yield rL(this.encryptIfNeeded(e));try{yield rL((yield*function(e){var t,i;return t={},n("next"),n("throw",function(e){throw e}),n("return"),t[Symbol.iterator]=function(){return this},t;function n(n,r){t[n]=e[n]?function(t){return(i=!i)?{value:rL(e[n](t)),done:!1}:r?r(t):t}:r}}(rU(this.packetizer.packetize(t)))))}catch(e){if(e instanceof cU)throw cq.packetizer(e);throw e}})}encryptIfNeeded(e){return rx(this,void 0,void 0,function*(){let t;if(!this.e2eeManager)return e;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(e){throw cq.encryption(e)}return e.payload=t.payload,e.extensions.e2ee=new cT(t.keyIndex,t.iv),e})}}cH.TRANSPORT_MTU_BYTES=16e3;let cW=rM(el.DataTracks),cz={pending:()=>({type:"pending",completionFuture:new sL}),active:(e,t)=>
1({type:"active",info:e,publishState:"published",pipeline:new cH({info:e,e2eeManager:t}),unpublishingFuture:new sL})};class cG extends rB.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new op,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){let t=new cG;return t.descriptors=e,t}updateE2eeManager(e){for(let t of(this.e2eeManager=e,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 rx(this,void 0,void 0,function*(){let i=this.getDescriptor(e);if((null==i?void 0:i.type)!=="active"||"unpublished"===i.publishState)throw cj.trackUnpublished();if("republishing"===i.publishState)throw cj.dropped("Data track republishing");try{try{for(var n,r,a,s,o,c,l=!0,d=rU(i.pipeline.processFrame(t));!(n=(c=yield d.next()).done);l=!0){s=c.value,l=!1;let t=null!==(o=this.inFlightPacketCounter.get(e))&&void 0!==o?o:0;this.inFlightPacketCounter.set(e,t+1),0===t&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!1}),this.emit("packetAvailable",{handle:e,bytes:s.toBinary()})}}catch(e){r={error:e}}finally{try{!l&&!n&&(a=d.return)&&(yield a.call(d))}finally{if(r)throw r.error}}}catch(e){throw cj.dropped(e)}})}handlePacketSendComplete(e){var t;let i=(null!==(t=this.inFlightPacketCounter.get(e))&&void 0!==t?t:0)-1;i<0&&(cW.warn("OutgoingDataTrackManager.handlePacketSendComplete: inFlightPacketCounter was decremented below 0 (got ".concat(this.inFlightPacketCounter," - resetting to 0. Were more packets send than were emitted?")),i=0),this.inFlightPacketCounter.set(e,i),0===i&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!0})}publishRequest(e,t){return rx(this,void 0,void 0,function*(){let i=this.handleAllocator.get();if(!i)throw cB.limitReached();let n=cg(1e4),r=t?cm([t,n]):n;if(this.descriptors.has(i))throw Error("Descriptor for handle already exists");let a=cz.pending();this.descriptors.set(i,a);let s=()=>{var e,t;let r=this.descriptors.get(i);if(!r){cW.warn("No descriptor for ".concat(i));return}this.descriptors.delete(i),this.emit("sfuUnpublishRequest",{handle:i}),"pending"===r.type&&(null===(t=(e=r.completionFuture).reject)||void 0===t||t.call(e,n.aborted?cB.timeout():cB.cancelled()))};return r.aborted?(s(),a.completionFuture.promise.then(()=>i)):(r.addEventListener("abort",s),this.emit("sfuPublishRequest",{handle:i,name:e.name,usesE2ee:null!==this.e2eeManager}),yield a.completionFuture.promise,r.removeEventListener("abort",s),this.emit("trackPublished",{track:cV.withExplicitHandle(e,this,i)}),i)})}queryPublished(){return Array.from(this.descriptors.values()).filter(e=>"active"===e.type).map(e=>e.info)}unpublishRequest(e){return rx(this,void 0,void 0,function*(){let t=this.descriptors.get(e);if(!t){cW.warn("No descriptor for ".concat(e));return}if("active"!==t.type){cW.warn("Track ".concat(e," not active"));return}this.emit("sfuUnpublishRequest",{handle:e}),yield t.unpublishingFuture.promise,this.inFlightPacketCounter.delete(e),this.emit("trackUnpublished",{sid:t.info.sid})})}receivedSfuPublishResponse(e,t){var i,n,r,a;let s=this.descriptors.get(e);if(!s){cW.warn("No descriptor for ".concat(e));return}switch(this.descriptors.delete(e),s.type){case"pending":if("ok"===t.type){let e=t.data,r=e.usesE2ee?this.e2eeManager:null;this.descriptors.set(e.pubHandle,cz.active(e,r)),null===(n=(i=s.completionFuture).resolve)||void 0===n||n.call(i)}else null===(a=(r=s.completionFuture).reject)||void 0===a||a.call(r,t.error);return;case"active":if("republishing"!==s.publishState){cW.warn("Track ".concat(e," already active"));return}if("error"===t.type){cW.warn("Republish failed for track ".concat(e));return}cW.debug("Track ".concat(e," republished")),s.info.sid=t.data.sid,s.publishState="published",this.descriptors.set(s.info.pubHandle,s)}}receivedSfuUnpublishResponse(e){var t,i;let n=this.descriptors.get(e);if(!n){cW.warn("No descriptor for ".concat(e));return}if(this.descriptors.delete(e),"active"!==n.type){cW.warn("Track ".concat(e," not active"));return}n.publishState="unpublished",null===(i=(t=n.unpublishingFuture).resolve)||void 0===i||i.call(t)}sfuWillRepublishTracks(){var e,t;for(let[i,n]of this.descriptors.entries())switch(n.type){case"pen
1ding":this.descriptors.delete(i),null===(t=(e=n.completionFuture).reject)||void 0===t||t.call(e,cB.disconnected());break;case"active":n.publishState="republishing",this.emit("sfuPublishRequest",{handle:n.info.pubHandle,name:n.info.name,usesE2ee:n.info.usesE2ee})}}reset(){return rx(this,void 0,void 0,function*(){var e,t,i,n;for(let r of(this.handleAllocator.reset(),this.descriptors.values()))switch(r.type){case"pending":null===(t=(e=r.completionFuture).reject)||void 0===t||t.call(e,cB.disconnected());break;case"active":null===(n=(i=r.unpublishingFuture).resolve)||void 0===n||n.call(i),yield this.unpublishRequest(r.info.pubHandle)}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit("reset")})}}class cK extends Error{constructor(e,t,i,n){super(t),this.code=e,this.message=cX(t,cK.MAX_MESSAGE_BYTES),this.data=i?cX(i,cK.MAX_DATA_BYTES):void 0,void 0!==(null==n?void 0:n.cause)&&(this.cause=null==n?void 0:n.cause)}static fromProto(e){return new cK(e.code,e.message,e.data)}toProto(){return new iJ({code:this.code,message:this.message,data:this.data})}static builtIn(e,t,i){return new cK(cK.ErrorCode[e],cK.ErrorMessage[e],t,i)}}cK.MAX_MESSAGE_BYTES=256,cK.MAX_DATA_BYTES=15360,cK.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},cK.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"};let cJ="lk.rpc_request",cQ="lk.rpc_response";function cY(e){return new TextEncoder().encode(e).length}function cX(e,t){if(cY(e)<=t)return e;let i=0,n=e.length,r=new TextEncoder;for(;i<n;){let a=Math.floor((i+n+1)/2);r.encode(e.slice(0,a)).length<=t?i=a:n=a-1}return e.slice(0,i)}(X=eQ||(eQ={})).RPC_REQUEST_ID="lk.rpc_request_id",X.RPC_REQUEST_METHOD="lk.rpc_request_method",X.RPC_REQUEST_RESPONSE_TIMEOUT_MS="lk.rpc_request_response_timeout_ms",X.RPC_REQUEST_VERSION="l
1k.rpc_request_version";class cZ extends rj{constructor(e,t,i,n){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=i,this.getServerVersion=n}performRpc(e){return rx(this,arguments,void 0,function(e){var t=this;let{destinationIdentity:i,method:n,payload:r,responseTimeout:a=15e3}=e;return function*(){let e=t.getRemoteParticipantClientProtocol(i);if(cY(r)>15360&&e<1)throw cK.builtIn("REQUEST_PAYLOAD_TOO_LARGE");let s=t.getServerVersion();if(s&&0>sR(s,"1.8.0"))throw cK.builtIn("UNSUPPORTED_SERVER");let o=crypto.randomUUID(),c=new sL,l=setTimeout(()=>{var e;t.pendingAcks.delete(o),null===(e=c.reject)||void 0===e||e.call(c,cK.builtIn("CONNECTION_TIMEOUT")),t.pendingResponses.delete(o),clearTimeout(d)},7e3);t.pendingAcks.set(o,{resolve:()=>{clearTimeout(l)},participantIdentity:i}),t.pendingResponses.set(o,{completionFuture:c,participantIdentity:i}),yield t.publishRpcRequest(i,o,n,r,Math.max(a,8e3),e);let d=setTimeout(()=>{var e;t.pendingResponses.delete(o),null===(e=c.reject)||void 0===e||e.call(c,cK.builtIn("RESPONSE_TIMEOUT"))},a),u=c.promise.finally(()=>{clearTimeout(d),t.pendingAcks.has(o)&&(t.log.warn("RPC response received before ack",o),t.pendingAcks.delete(o),clearTimeout(l))});return[o,u]}()})}publishRpcRequest(e,t,i,n,r,a){return rx(this,void 0,void 0,function*(){if(a>=1){let a=yield this.outgoingDataStreamManager.streamText({topic:cJ,destinationIdentities:[e],attributes:{[eQ.RPC_REQUEST_ID]:t,[eQ.RPC_REQUEST_METHOD]:i,[eQ.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:"".concat(r),[eQ.RPC_REQUEST_VERSION]:"".concat(2)}});yield a.write(n),yield a.close();return}this.emit("sendDataPacket",{packet:new iN({destinationIdentities:[e],kind:ix.RELIABLE,value:{case:"rpcRequest",value:new iz({id:t,method:i,payload:n,responseTimeoutMs:r,version:1})}})})})}handleIncomingDataStream(e,t,i){return rx(this,void 0,void 0,function*(){let n;let r=i[eQ.RPC_REQUEST_ID];if(!r){this.log.warn("RPC data stream malformed: ".concat(eQ.RPC_REQUEST_ID," not set."));return}let a=this.pendingResponses.get(r);if(a&&a.participantIdentity!==t){this.log.warn("RPC response stream for ".concat(r," arrived from unexpected sender ").concat(t,", expected ").concat(a.participantIdentity,". Ignoring."));return}try{n=yield e.readAll()}catch(e){this.log.warn("Error reading RPC response payload: ".concat(e)),this.handleIncomingRpcResponseFailure(r,cK.builtIn("APPLICATION_ERROR","Error reading RPC response payload",{cause:e}));return}this.handleIncomingRpcResponseSuccess(r,n)})}handleIncomingRpcResponseSuccess(e,t){var i,n;let r=this.pendingResponses.get(e);r?(null===(n=(i=r.completionFuture).resolve)||void 0===n||n.call(i,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcResponseFailure(e,t){var i,n;let r=this.pendingResponses.get(e);r?(null===(n=(i=r.completionFuture).reject)||void 0===n||n.call(i,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcAck(e){let 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(let[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(let[i,{participantIdentity:n,completionFuture:r}]of this.pendingResponses)n===e&&(null===(t=r.reject)||void 0===t||t.call(r,cK.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(i))}}class c$ extends rj{constructor(e,t,i){super(),this.rpcHandlers=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=i}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 rx(this,void 0,void 0,function*(){var i;let n;if(this.publishRpcAck(e,t.id),1!==t.version){this.publishRpcResponsePacket(e,t.id,null,cK.builtIn("UNSUPPORTED_VERSION"));return}let r=this.rpcHandlers.get(t.method);if(!r){this.publishRpcResponsePacket(e,t.id,null,cK.builtIn("UNSUPPORTED_METHOD"));return}try{n=yield r({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(r){let n;r instanceof cK?n=r:(this.log.warn("Uncaught error returned by RPC handler for ".concat(t.method,". Returning APPLICATION_ERROR instead."),r),n=cK.builtIn("APPLICATION_ERROR","Uncaught error: ".concat(null!==(i=null==r?void 0:r.message)&&void 0!==i?i:r),{cause:r})),this.publishRpcResponsePacket(e,t.id,null,n);return}yield this.publishRpcResponse(e,t.id,null!=n?n:"")})}handleIncomingDataStream(e,t,i){return rx(this,void 0,void 0,function*(){let n,r;let a=i[eQ.RPC_REQUEST_ID],s=i[eQ.RPC_REQUEST_METHOD],o=parseInt(i[eQ.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),c=parseInt(i[eQ.RPC_REQUEST_VERSION],10);if(!a||!s||Number.isNaN(o)||Number.isNaN(c)){this.log.warn("RPC data stream malformed: ".concat(eQ.RPC_REQUEST_ID," / ").concat(eQ.RPC_REQUEST_METHOD," / ").concat(eQ.RPC_REQUEST_RESPONSE_TIMEOUT_MS," / ").concat(eQ.RPC_REQUEST_VERSION," not set.")),this.publishRpcResponsePacket(t,a,null,cK.builtIn("APPLICATION_ERROR","RPC data stream malformed"));return}if(this.publishRpcAck(t,a),2!==c){this.publishRpcResponsePacket(t,a,null,cK.builtIn("UNSUPPORTED_VERSION"));return}
1try{n=yield e.readAll()}catch(e){this.log.warn("Error reading RPC request payload: ".concat(e)),this.publishRpcResponsePacket(t,a,null,cK.builtIn("APPLICATION_ERROR","Error reading RPC request payload",{cause:e}));return}let l=this.rpcHandlers.get(s);if(!l){this.publishRpcResponsePacket(t,a,null,cK.builtIn("UNSUPPORTED_METHOD"));return}try{r=yield l({requestId:a,callerIdentity:t,payload:n,responseTimeout:o})}catch(i){let e;i instanceof cK?e=i:(this.log.warn("Uncaught error returned by RPC handler for ".concat(s,". Returning APPLICATION_ERROR instead."),i),e=cK.builtIn("APPLICATION_ERROR")),this.publishRpcResponsePacket(t,a,null,e);return}yield this.publishRpcResponse(t,a,null!=r?r:"")})}publishRpcAck(e,t){this.emit("sendDataPacket",{packet:new iN({destinationIdentities:[e],kind:ix.RELIABLE,value:{case:"rpcAck",value:new iG({requestId:t})}})})}publishRpcResponsePacket(e,t,i,n){this.emit("sendDataPacket",{packet:new iN({destinationIdentities:[e],kind:ix.RELIABLE,value:{case:"rpcResponse",value:new iK({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}})})}publishRpcResponse(e,t,i){return rx(this,void 0,void 0,function*(){if(this.getRemoteParticipantClientProtocol(e)>=1){let n=yield this.outgoingDataStreamManager.streamText({topic:cQ,destinationIdentities:[e],attributes:{[eQ.RPC_REQUEST_ID]:t}});yield n.write(i),yield n.close();return}if(cY(i)>15360){this.log.warn("RPC Response payload too large for request ".concat(t,". To send larger responses, consider updating the sending client.")),this.publishRpcResponsePacket(e,t,null,cK.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"));return}this.publishRpcResponsePacket(e,t,i,null)})}}class c0 extends s6{constructor(e,t,i,n,r,a){super(e,t,ss.Kind.Audio,i,a),this.monitorReceiver=()=>rx(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=s9(e,this.prevStats)),this.prevStats=e}),this.audioContext=n,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(let i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;sT()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(sT())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return rx(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(sm(t))return t.setSinkId(e)}))})}attach(e){let t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&sm(e)&&e.setSinkId(this.sinkId).catch(e=>{this.log.error("Failed to set sink id on remote audio track",e,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{i.connect(e),i=e}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then(()=>{"running"!==e.state&&this.emit(eb.AudioPlaybackFailed,Error("Audio Context couldn't be started automatically"))}).catch(e=>
1{this.emit(eb.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return rx(this,void 0,void 0,function*(){let e;if(this.receiver&&this.receiver.getStats)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 c1 extends rB.EventEmitter{constructor(e,t,i,n){var r;super(),this.metadataMuted=!1,this.encryption=iR.NONE,this.log=r_,this.handleMuted=()=>{this.emit(eb.Muted)},this.handleUnmuted=()=>{this.emit(eb.Unmuted)},this.log=rM(null!==(r=null==n?void 0:n.loggerName)&&void 0!==r?r:el.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=ss.Source.Unknown}setTrack(e){this.track&&(this.track.off(eb.Muted,this.handleMuted),this.track.off(eb.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(eb.Muted,this.handleMuted),e.on(eb.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),si(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==iR.NONE}get audioTrack(){if(sW(this.track))return this.track}get videoTrack(){if(sz(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=ss.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===ss.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}))}}($=(Z=c1||(c1={})).SubscriptionStatus||(Z.SubscriptionStatus={})).Desired="desired",$.Subscribed="subscribed",$.Unsubscribed="unsubscribed",(ee=Z.PermissionStatus||(Z.PermissionStatus={})).Allowed="allowed",ee.NotAllowed="not_allowed";class c2 extends c1{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit(eb.Ended)},this.handleCpuConstrained=()=>{this.track&&sz(this.track)&&this.emit(eb.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(eb.Ended,this.handleTrackEnded),this.track.off(eb.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(eb.Ended,this.handleTrackEnded),e.on(eb.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 rx(this,void 0,void 0,function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()})}unmute(){return rx(this,void 0,void 0,function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()})}pauseUpstream(){return rx(this,void 0,void 0,function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()})}resumeUpstream(){return rx(this,void 0,void 0,function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(!sW(this.track))return[];{let t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(ik.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(ik.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(ik.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(ik.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||i.add(ik.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(ik.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}}}(et=eY||(eY={})).Excellent="excellent",et.Good="good",et.Poor="poor",et.Lost="lost",et.Unknown="unknown";class c3 extends rB.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===iw.AGENT}get isActive(){var e;return(null===(e=this.participantInfo)||void 0===e?void 0:e.state)===iE.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,n,r,a){var s;let o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:iw.STANDARD;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=eY.Unknown,this.log=r_,this.loggerOptions=a,this.log=rM(null!==(s=null==a?void 0:a.loggerName)&&void 0!==s?s:el.Participant,()=>this.logContext),this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=null!=r?r:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(let[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(let[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new sL,this.once(ev.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;let t=this.getTrackPublication(ss.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;let t=this.getTrackPublication(ss.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(ss.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){var t;return(!this.participantInfo||this.participantInfo.sid!==e.sid||!(this.participantInfo.version>e.version))&&(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===iE.ACTIVE&&(null===(t=this.participantInfo)||void 0===t?void 0:t.state)!==iE.ACTIVE&&this.emit
1(ev.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){let t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(ev.ParticipantMetadataChanged,i)}_setName(e){let t=this.name!==e;this.name=e,t&&this.emit(ev.ParticipantNameChanged,e)}_setAttributes(e){let t=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});let n=[...Object.keys(t),...Object.keys(e)],r={};for(let a of n)e[a]!==t[a]&&(r[a]=null!==(i=t[a])&&void 0!==i?i:"");return r}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(ev.AttributesChanged,t)}setPermissions(e){var t,i,n,r,a,s;let o=this.permissions,c=e.canPublish!==(null===(t=this.permissions)||void 0===t?void 0:t.canPublish)||e.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||e.canPublishData!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishData)||e.hidden!==(null===(r=this.permissions)||void 0===r?void 0:r.hidden)||e.recorder!==(null===(a=this.permissions)||void 0===a?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])})||e.canSubscribeMetrics!==(null===(s=this.permissions)||void 0===s?void 0:s.canSubscribeMetrics);return this.permissions=e,c&&this.emit(ev.ParticipantPermissionsChanged,o),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(ev.IsSpeakingChanged,e))}setConnectionQuality(e){let t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case ih.EXCELLENT:return eY.Excellent;case ih.GOOD:return eY.Good;case ih.POOR:return eY.Poor;case ih.LOST:return eY.Lost;default:return eY.Unknown}}(e),t!==this._connectionQuality&&this.emit(ev.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&(null===(t=(e=this.activeFuture).reject)||void 0===t||t.call(e,Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>sW(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){switch(e.on(eb.Muted,()=>{this.emit(ev.TrackMuted,e)}),e.on(eb.Unmuted,()=>{this.emit(ev.TrackUnmuted,e)}),e.track&&(e.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case ss.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case ss.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class c4 extends c3{constructor(e,t,i,n,r,a,s,o){super(e,t,void 0,void 0,void 0,{loggerName:n.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=iR.NONE,this.e2eeStateMutex=new e3,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new sL)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,i,n,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,Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null===(n=(i=this.signalConnectedFuture).reject)||void 0===n||n.call(i,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,Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,i;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new sL),null===(i=(t=this.signalConnectedFuture).resolve)||void 0===i||i.call(t)},this.handleSignalRequestResponse=e=>{let{requestId:t,reason:i,message:n}=e,r=this.pendingSignalRequests.get(t);if(r&&(i!==rb.OK&&r.reject(new aQ(n,i)),this.pendingSignalRequests.delete(t)),"publishDataTrack"===e.request.case){let t;switch(e.reason){case rb.NOT_ALLOWED:t=cB.notAllowed(e.message);break;case rb.DUPLICATE_NAME:t=cB.duplicateName(e.message);break;
1case rb.INVALID_NAME:t=cB.invalidName(e.message);break;case rb.LIMIT_EXCEEDED:t=cB.limitReached(e.message);break;default:t=cB.unknown(e.reason,e.message)}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(e.request.value.pubHandle,{type:"error",error:t})}},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,i,n;if(!e.participantSid&&!e.participantIdentity)throw Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new ra({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(i=e.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=e.allowAll)&&void 0!==n&&n,trackSids:e.allowedTrackSids||[]})})(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{if(void 0===t&&(t=!0),!e.sid){this.log.error("could not update mute status for unpublished track",si(e));return}this.engine.updateMuteStatus(e.sid,t)},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",si(e)),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",si(e)),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{let t=this.audioTrackPublications.get(e.sid);if(!t){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid));return}this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures())},this.onTrackCpuConstrained=(e,t)=>{this.log.debug("track cpu constrained",si(t)),this.emit(ev.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>rx(this,void 0,void 0,function*(){if(!(null===(o=this.roomOptions)||void 0===o?void 0:o.dynacast))return;let t=this.videoTrackPublications.get(e.trackSid);if(!t){this.log.warn("received subscribed quality update for unknown track",{trackSid:e.trackSid});return}if(!t.videoTrack)return;let i=yield t.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var n,r,a,s,o,c,l=!0,d=rU(i);!(n=(c=yield d.next()).done);l=!0)s=c.value,l=!1,a2(s)&&(this.log.debug("publish ".concat(s," for ").concat(t.videoTrack.sid),si(t)),yield this.publishAdditionalCodecForTrack(t.videoTrack,s,t.options))}catch(e){r={error:e}}finally{try{!l&&!n&&(a=d.return)&&(yield a.call(d))}finally{if(r)throw r.error}}}),this.handleLocalTrackUnpublished=e=>{let t=this.trackPublications.get(e.trackSid);if(!t){this.log.warn("received unpublished event for unknown track",{trackSid:e.trackSid});return}this.unpublishTrack(t.track)},this.handleTrackEnded=e=>rx(this,void 0,void 0,function*(){if(e.source===ss.Source.ScreenShare||e.source===ss.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",si(e)),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(sK(e)||sG(e))try{if(sy())try{let t=yield null==navigator?void 0:navigator.permissions.query({name:e.source===ss.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),si(e)),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",si(e)),sK(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",si(e)),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.roomOutgoingDataStreamManager=r,this.roomOutgoingDataTrackManager=a,this.rpcClientManager=s,this.rpcServerManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==iR.NONE}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);
1if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(ek.RemoteMute,(e,t)=>{let i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.unmute())}),(null===(t=this.signalConnectedFuture)||void 0===t?void 0:t.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(ek.Connected,this.handleReconnected).on(ek.SignalConnected,this.handleSignalConnected).on(ek.SignalRestarted,this.handleReconnected).on(ek.SignalResumed,this.handleReconnected).on(ek.Restarting,this.handleReconnecting).on(ek.Resuming,this.handleReconnecting).on(ek.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(ek.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(ek.Closing,this.handleClosing).on(ek.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return rx(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return rx(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return rx(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return rx(this,arguments,void 0,function(e){var t=this;let{metadata:i,name:n,attributes:r}=e;return function*(){return new aN((e,a)=>rx(t,void 0,void 0,function*(){var t,s;try{let o=!1,c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(s=null!=n?n:this.name)&&void 0!==s?s:"",r),l=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{a(e),o=!0},values:{name:n,metadata:i,attributes:r}});performance.now()-l<5e3&&!o;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!r||Object.entries(r).every(e=>{let[t,i]=e;return this.attributes[t]===i||""===i&&!this.attributes[t]}))){this.pendingSignalRequests.delete(c),e();return}yield sd(50)}a(new aQ("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error?a(e):a(Error(String(e)))}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(ss.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(ss.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(ss.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return rx(this,void 0,void 0,function*(){let t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?iR.GCM:iR.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(e,t,i,n){return rx(this,void 0,void 0,function*(){this.log.debug("setTrackEnabled",{source:e,enabled:t}),this.republishPromise&&(yield this.republishPromise);let r=this.getTrackPublication(e);if(t){if(r)yield r.unmute();else{let t;if(this.pendingPublishing.has(e)){let t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info("waiting for pending publication promise timed out",{source:e}),yield null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case ss.Source.Camera:t=yield this.createTracks({video:null==i||i});break;case ss.Source.Microphone:t=yield this.createTracks({audio:null==i||i});break;case ss.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new aW(e)}}catch(i){throw null==t||t.forEach(e=>{e.stop()}),i instanceof Error&&this.emit(ev.MediaDevicesError,i,se(e)),this.pendingPublishing.delete(e),i}for(let n of t){let t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===ss.Source.Microphone&&sW(n)&&t.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone"),n.startPreConnectBuffer())}try{let e=[];for(let i of t)this.log.info("publishing track",si(i)),e.push(this.publishTrack(i,n));let i=yield Promise.all(e);[r]=i}catch(e){throw null==t||t.forEach(e=>{e.stop()}),e}finally{this.pendingPublishing.delete(e)}}}else if(!(!(null==r?void 0:r.track)&&this.pendingPublishing.has(e))||(r=yield this.waitForPendingPublicationOfSource(e))||this.log.info("waiting for pending publication promise timed out",{source:e}),r&&r.track){if(e===ss.Source.ScreenShare){let e=[this.unpublishTrack(r.track)],t=this.getTrackPublication(ss.Source.ScreenShareAudio);t&&t.track&&e.push(this.unpublishTrack(t.track)),[r]=yield Promise.all(e)}else yield r.mute()}return r})}enableCameraAndMicrophone(){return rx(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(ss.Source.Camera)||this.pendingPublishing.has(ss.Source.Microphone))){this.pendingPublishing.add(ss.Source.Camera),this.pendingPublishing.add(ss.Source.Microphone);try{let e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete(ss.Source.Camera),this.pendingPublishing.delete(ss.Source.Microphone)}}})}createTracks(e){return rx(this,void 0,void 0,function*(){var t,i;null!=e||(e={});let n=a6(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults);try{return(yield function e(t,i){return rx(this,void 0,void 0,function*(){null!=t||(t={});let n=!1,{audioProcessor:r,videoProcessor:a,optionsWithoutProcessor:s}=sn(t),o=s.audio,c=s.video;
1if(r&&"object"==typeof s.audio&&(s.audio.processor=r),a&&"object"==typeof s.video&&(s.video.processor=a),t.audio&&"object"==typeof s.audio&&"string"==typeof s.audio.deviceId){let 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){let 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");let l=a5(a6(s,ox,oL)),d=navigator.mediaDevices.getUserMedia(l);s.audio&&(os.userMediaPromiseMap.set("audioinput",d),d.catch(()=>os.userMediaPromiseMap.delete("audioinput"))),s.video&&(os.userMediaPromiseMap.set("videoinput",d),d.catch(()=>os.userMediaPromiseMap.delete("videoinput")));try{let e=yield d;return yield Promise.all(e.getTracks().map(t=>rx(this,void 0,void 0,function*(){let n;let s="audio"===t.kind?l.audio:l.video;"boolean"!=typeof s&&(n=s);let o=t.getSettings().deviceId;(null==n?void 0:n.deviceId)&&sF(n.deviceId)!==o?n.deviceId=o:n||(n={deviceId:o});let c=function(e,t,i){switch(e.kind){case"audio":return new oz(e,t,!1,void 0,i);case"video":return new o9(e,t,!1,i);default:throw new aW("unsupported track type: ".concat(e.kind))}}(t,n,i);return c.kind===ss.Kind.Video?c.source=ss.Source.Camera:c.kind===ss.Kind.Audio&&(c.source=ss.Source.Microphone),c.mediaStream=e,sW(c)&&r?yield c.setProcessor(r):sz(c)&&a&&(yield c.setProcessor(a)),c})))}catch(r){if(!n)throw r;return e(Object.assign(Object.assign({},t),{audio:o,video:c}),i)}})}(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(e=>(sW(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=ss.Source.Microphone,this.emit(ev.AudioStreamAcquired)),sz(e)&&(this.cameraError=void 0,e.source=ss.Source.Camera),e))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}})}createScreenTracks(e){return rx(this,void 0,void 0,function*(){var t,i,n;let r;if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new aH("getDisplayMedia not supported");void 0===e.resolution&&!function(){let e=aL();return(null==e?void 0:e.name)==="Safari"&&e.version.startsWith("17.")||(null==e?void 0:e.os)==="iOS"&&!!(null==e?void 0:e.osVersion)&&sR(e.osVersion,"17")>=0}()&&(e.resolution=a9.h1080fps30.resolution);let a=(r=null===(i=(t=e).video)||void 0===i||i,t.resolution&&t.resolution.width>0&&t.resolution.height>0&&(r="boolean"==typeof r?{}:r,r=sv()?Object.assign(Object.assign({},r),{width:{max:t.resolution.width},height:{max:t.resolution.height},frameRate:t.resolution.frameRate}):Object.assign(Object.assign({},r),{width:{ideal:t.resolution.width},height:{ideal:t.resolution.height},frameRate:t.resolution.frameRate})),{audio:null!==(n=t.audio)&&void 0!==n&&n,video:r,controller:t.controller,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio,preferCurrentTab:t.preferCurrentTab}),s=yield navigator.mediaDevices.getDisplayMedia(a),o=s.getVideoTracks();if(0===o.length)throw new aW("no video track found");let c=new o9(o[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});c.source=ss.Source.ScreenShare,e.contentHint&&(c.mediaStreamTrack.contentHint=e.contentHint);let l=[c];if(s.getAudioTracks().length>0){this.emit(ev.AudioStreamAcquired);let e=new oz(s.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=ss.Source.ScreenShareAudio,l.push(e)}return l})}publishTrack(e,t){return rx(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}waitForNextEngineRestart(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:15e3;return new Promise((t,i)=>{let n=()=>{clearTimeout(s),this.engine.off(ek.Restarted,r),this.engine.off(ek.Closing,a)},r=()=>{n(),t()},a=()=>{n(),i(Error("engine closed before restart completed"))},s=setTimeout(()=>{n(),i(Error("timed out waiting for engine restart"))},e);this.engine.once(ek.Restarted,r),this.engine.once(ek.Closing,a)})}publishOrRepublishTrack(e,t){return rx(this,arguments,void 0,function(e,t){var i=this;let n=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 l,d;if(sK(e)&&e.setAudioContext(i.audioContext),yield null===(a=i.reconnectFuture)||void 0===a?void 0:a.promise,i.republishPromise&&!n&&(yield i.republishPromise),sH(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)l=e.getConstraints();else{let t;switch(l=e.constraints,e.source){case ss.Source.Microphone:t="audioinput";break;case ss.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(l=Object.assign(Object.assign({},l),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new oz(e,l,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new o9(e,l,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new aW("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});if(i.trackPublications.forEach(t=>{t.track&&t.track===e&&(d=t)}),d)return i.log.warn("track has already been published, skipping",si(d)),d;let u=Object.assign(Object.assign({},i.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&&i.log.debug("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",si(e)),void 0===u.red&&i.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(){let e=aL(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&sR(e.osVersion,t)>=0)||!!("Safari"===e.name&&sR(e.version,t)>=0)}()&&i.roomOptions.e2ee&&(i.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2"),u.simulcast=!1),u.source&&(e.source=u.source);let m=new Promise((t,n)=>rx(i,void 0,void 0,function*(){try{if(this.engine.client.currentState!==e_.CONNECTED){this.log.debug("deferring track publication until signal is connected",{track:si(e)});let i=!1,r=setTimeout(()=>{i=!0,e.stop(),n(new aJ("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(r),i)return;let a=yield this.publish(e,u,p);t(a)}else try{let i=yield this.publish(e,u,p);t(i)}catch(e){n(e)}}catch(e){n(e)}}));i.pendingPublishPromises.set(e,m);try{return yield m}catch(a){if(!r&&a instanceof aK)return i.log.warn("negotiation due to track publish failed, retrying after reconnect",{error:a}),i.pendingPublishPromises.delete(e),yield i.waitForNextEngineRestart(),yield i.publishOrRepublishTrack(e,t,n,!0);throw a}finally{i.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new sL),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",si(e)),!1;let{canPublish:t,canPublishSources:i}=this.permissions;return!!(t&&(0===i.length||i.map(e=>(function(e){switch(e){case id.CAMERA:return ss.Source.Camera;case id.MICROPHONE:return ss.Source.Microphone;case id.SCREEN_SHARE:return ss.Source.ScreenShare;case id.SCREEN_SHARE_AUDIO:return ss.Source.ScreenShareAudio;default:return ss.Source.Unknown}})(e)).includes(e.source)))||(this.log.warn("insufficient permissions to publish",si(e)),!1)}publish(e,t,i){return rx(this,void 0,void 0,function*(){var n,r,a,s,o,c,l,d,u,h;let p,m;if(!this.hasPermissionsToPublish(e))throw new aJ("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(t=>sH(e)&&t.source===e.source)&&e.source!==ss.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),si(e)),t.stopMicTrackOnMute&&sW(e)&&(e.stopOnMute=!0),e.source===ss.Source.ScreenShare&&sg()&&(t.simulcast=!1),"av1"===t.videoCodec&&!function(){if(!("getCapabilities"in RTCRtpSender)||sv()||sg())return!1;let e=RTCRtpSender.getCapabilities("video"),t=!1;if(e){for(let i of e.codecs)if("video/av1"===i.mimeType.toLowerCase()){t=!0;break}}return t}()&&(t.videoCodec=void 0),"vp9"===t.videoCodec&&!function(){if(!("getCapabilities"in RTCRtpSender)||sg())return!1;if(sv()){let e=aL();if((null==e?void 0:e.version)&&0>sR(e.version,"16")||(null==e?void 0:e.os)==="iOS"&&(null==e?void 0:e.osVersion)&&0>sR(e.osVersion,"16"))return!1}let e=RTCRtpSender.getCapabilities("video"),t=!1;if(e){for(let i of e.codecs)if("video/vp9"===i.mimeType.toLowerCase()){t=!0;break}}return t}()&&(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec="vp8"),this.enabledPublishVideoCodecs.length>0&&!this.enabledPublishVideoCodecs.some(e=>t.videoCodec===st(e.mime))&&(t.videoCodec=st(this.enabledPublishVideoCodecs[0].mime));let g=t.videoCodec;e.on(eb.Muted,this.onTrackMuted),e.on(eb.Unmuted,this.onTrackUnmuted),e.on(eb.Ended,this.handleTrackEnded),e.on(eb.UpstreamPaused,this.onTrackUpstreamPaused),e.on(eb.UpstreamResumed,this.onTrackUpstreamResumed),e.on(eb.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);let f=[],v=!(null===(n=t.dtx)||void 0===n||n),k=e.getSourceTrackSettings();k.autoGainControl&&f.push(ik.TF_AUTO_GAIN_CONTROL),k.echoCancellation&&f.push(ik.TF_ECHO_CANCELLATION),k.noiseSuppression&&f.push(ik.TF_NOISE_SUPPRESSION),k.channelCount&&k.channelCount>
11&&f.push(ik.TF_STEREO),v&&f.push(ik.TF_NO_DTX),sK(e)&&e.hasPreConnectBuffer&&f.push(ik.TF_PRECONNECT_BUFFER);let b=this.normalizeRequestedPacketTrailerOptions(e,t),y=new nA({cid:e.mediaStreamTrack.id,name:t.name,type:ss.kindToProto(e.kind),muted:e.isMuted,source:ss.sourceToProto(e.source),disableDtx:v,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(r=t.red)||void 0===r||r),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy,audioFeatures:f,packetTrailerFeatures:b});if(e.kind===ss.Kind.Video){let i;try{i=yield e.waitForDimensions()}catch(n){let t=null!==(s=null===(a=this.roomOptions.videoCaptureDefaults)||void 0===a?void 0:a.resolution)&&void 0!==s?s:a3.h720.resolution;i={width:t.width,height:t.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},si(e)),{dims:i}))}y.width=i.width,y.height=i.height,sG(e)&&(sp(g)&&(e.source===ss.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.debug("forcing contentHint to motion for screenshare with SVC codecs",si(e)))),t.scalabilityMode=null!==(o=t.scalabilityMode)&&void 0!==o?o:"L3T3_KEY"),y.simulcastCodecs=[new nO({codec:g,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:"vp8"}),t.backupCodec&&g!==t.backupCodec.codec&&y.encryption===iR.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),y.simulcastCodecs.push(new nO({codec:t.backupCodec.codec,cid:""})))),p=o$(e.source===ss.Source.ScreenShare,y.width,y.height,t),y.layers=o5(y.width,y.height,p,sp(t.videoCodec))}else e.kind===ss.Kind.Audio&&(p=[{maxBitrate:null===(c=t.audioPreset)||void 0===c?void 0:c.maxBitrate,priority:null!==(d=null===(l=t.audioPreset)||void 0===l?void 0:l.priority)&&void 0!==d?d:"high",networkPriority:null!==(h=null===(u=t.audioPreset)||void 0===u?void 0:u.priority)&&void 0!==h?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new aG("cannot publish track when not connected");let T=()=>rx(this,void 0,void 0,function*(){var i,n,r;if(!this.engine.pcManager)throw new aG("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,p),sG(e)&&(e.publishOptions=t),this.emit(ev.LocalSenderCreated,e.sender,e),sG(e)&&(null!==(i=t.degradationPreference)&&void 0!==i||(t.degradationPreference=e.source===ss.Source.ScreenShare||e.constraints.height&&sF(e.constraints.height)>=1080?"maintain-resolution":"balanced"),e.setDegradationPreference(t.degradationPreference)),p){if(sg()&&e.kind===ss.Kind.Audio){let t;for(let i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===e.sender){t=i;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:"opus",maxbr:(null===(n=p[0])||void 0===n?void 0:n.maxBitrate)?p[0].maxBitrate/1e3:0})}else e.codec&&sp(e.codec)&&(null===(r=p[0])||void 0===r?void 0:r.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:y.cid,codec:e.codec,maxbr:p[0].maxBitrate/1e3})}yield this.engine.negotiate()}),S=new Promise((t,i)=>rx(this,void 0,void 0,function*(){var n;try{m=yield this.engine.addTrack(y),t(m)}catch(t){if(e.sender&&(null===(n=this.engine.pcManager)||void 0===n?void 0:n.publisher)){try{this.engine.pcManager.publisher.removeTrack(e.sender)}catch(e){this.log.error(e)}yield this.engine.negotiate().catch(t=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign({},si(e)),{error:t}))})}i(t)}}));if(this.enabledPublishVideoCodecs.length>0&&0===b.length)m=(yield Promise.all([S,T()]))[0];else{let i;if((m=yield S).codecs.forEach(e=>{void 0===i&&(i=e.mimeType)}),i&&e.kind===ss.Kind.Video){let n=st(i);n!==g&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign({},si(e)),{codec:n})),t.videoCodec=n,p=o$(e.source===ss.Source.ScreenShare,y.width,y.height,t))}yield T()}let C=new c2(e.kind,m,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(C.on(eb.CpuConstrained,e=>this.onTrackCpuConstrained(e,C)),C.options=t,e.sid=m.sid,sG(e)&&(e.publishOptions=t,y.width&&y.height&&(e.lastEncodedDimensions={width:y.width,height:y.height})),this.log.debug("publishing ".concat(e.kind," with encodings"),{encodings:p,trackInfo:m}),sG(e)?e.startMonitor(this.engine.client):sK(e)&&e.startMonitor(),this.addTrackPublication(C),this.emit
1(ev.LocalTrackPublished,C),sK(e)&&m.audioFeatures.includes(ik.TF_PRECONNECT_BUFFER)){let t=e.getPreConnectBuffer(),i=e.getPreConnectBufferMimeType();this.on(ev.LocalTrackSubscribed,t=>{if(t.trackSid===m.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed");return}this.log.debug("finished recording preconnect buffer",si(e)),e.stopPreConnectBuffer()}}),t&&new Promise((n,r)=>rx(this,void 0,void 0,function*(){try{this.log.debug("waiting for agent",si(e));let m=setTimeout(()=>{r(Error("agent not active within 10 seconds"))},1e4),g=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug("sending preconnect buffer",si(e));let f=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!==(l=k.sampleRate)&&void 0!==l?l:"48000"),channels:String(null!==(d=k.channelCount)&&void 0!==d?d:"1")}});try{for(var a,s,o,c,l,d,u,h=!0,p=rU(t);!(a=(u=yield p.next()).done);h=!0)c=u.value,h=!1,yield f.write(c)}catch(e){s={error:e}}finally{try{!h&&!a&&(o=p.return)&&(yield o.call(p))}finally{if(s)throw s.error}}yield f.close(),n()}catch(e){r(e)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",si(e))}).catch(t=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign({},si(e)),{error:t}))})}return C})}canPublishPacketTrailer(){return!!(this.roomOptions.e2ee||this.roomOptions.encryption||s2(this.roomOptions.packetTrailer))}normalizeRequestedPacketTrailerOptions(e,t){if(e.kind!==ss.Kind.Video||!s3(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),si(e))),t.packetTrailer=void 0,[];let i=function(e){let t=[];return(null==e?void 0:e.timestamp)&&t.push(ib.PTF_USER_TIMESTAMP),(null==e?void 0:e.frameId)&&t.push(ib.PTF_FRAME_ID),t}(t.packetTrailer);return t.packetTrailer=function(e){if(!e||0===e.length)return;let t={};return e.includes(ib.PTF_USER_TIMESTAMP)&&(t.timestamp=!0),e.includes(ib.PTF_FRAME_ID)&&(t.frameId=!0),t.timestamp||t.frameId?t:void 0}(i),i}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return rx(this,void 0,void 0,function*(){var n;let r;if(this.encryptionType!==iR.NONE)return;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(r=t)}),!r)throw new aW("track is not published");if(!sG(e))throw new aW("track is not a video track");let a=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),s=o0(e,t,a);if(!s){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",si(e));return}let o=e.addSimulcastTrack(t,s);if(!o)return;let c=this.normalizeRequestedPacketTrailerOptions(e,a),l=new nA({cid:o.mediaStreamTrack.id,type:ss.kindToProto(e.kind),muted:e.isMuted,source:ss.sourceToProto(e.source),sid:e.sid,packetTrailerFeatures:c,simulcastCodecs:[{codec:a.videoCodec,cid:o.mediaStreamTrack.id}]});if(l.layers=o5(l.width,l.height,s),!this.engine||this.engine.isClosed)throw new aG("cannot publish track when not connected");let d=(yield Promise.all([this.engine.addTrack(l),rx(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:d})})}unpublishTrack(e,t){return rx(this,void 0,void 0,function*(){var i,n;if(sH(e)){let t=this.pendingPublishPromises.get(e);t&&(this.log.debug("awaiting publish promise before attempting to unpublish",si(e)),yield t)}let r=this.getPublicationForTrack(e),a=r?si(r):void 0;if(this.log.info("unpublishing track",a),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",a);return}(e=r.track).off(eb.Muted,this.onTrackMuted),e.off(eb.Unmuted,this.onTrackUnmuted),e.off(eb.Ended,this.handleTrackEnded),e.off(eb.UpstreamPaused,this.onTrackUpstreamPaused),e.off(eb.UpstreamResumed,this.onTrackUpstreamResumed),e.off(eb.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null===(n=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===n||n),t?e.stop():e.stopMonitor();let s=!1,o=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<eL.FAILED&&o)try{for(let e of this.engine.pcManager.publisher.getTransceivers())e.sender===o&&(e.direction="inactive",s=!0);try{s=this.engine.removeTrack(o)}catch(e){this.log.warn(e),s=!0}if(sG(e)){for(let[,t]of e.simulcastCodecs)if(t.sender){try{s=this.engine.removeTrack(t.sender)}catch(e){this.log.warn(e),s=!0}t.sender=void 0}e.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign({},a),{error:e}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case ss.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case ss.Kind.Video:this.videoTrackPublications.delete(r.trackSid)}
vendor: 3,075 bytes, line 1
1return this.emit(ev.LocalTrackUnpublished,r),r.setTrack(void 0),s&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return rx(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return rx(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new aN((n,r)=>rx(t,void 0,void 0,function*(){try{let t=[];this.trackPublications.forEach(i=>{i.track&&(e&&(i.options=Object.assign(Object.assign({},i.options),e)),t.push(i))}),yield Promise.all(t.map(e=>rx(this,void 0,void 0,function*(){let t=e.track;yield this.unpublishTrack(t,!1),i&&!t.isMuted&&t.source!==ss.Source.ScreenShare&&t.source!==ss.Source.ScreenShareAudio&&(sK(t)||sG(t))&&!t.isUserProvided&&(this.log.debug("restarting existing track",{track:e.trackSid}),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))),n()}catch(e){e instanceof Error?r(e):r(Error(String(e)))}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return rx(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){let n=i.reliable?eF.RELIABLE:eF.LOSSY,r=i.reliable?ix.RELIABLE:ix.LOSSY,a=i.destinationIdentities,s=i.topic,o=new iN({kind:r,value:{case:"user",value:new ij({participantIdentity:t.identity,payload:e,destinationIdentities:a,topic:s})}});yield t.engine.sendDataPacket(o,n)}()})}publishDtmf(e,t){return rx(this,void 0,void 0,function*(){let i=new iN({kind:ix.RELIABLE,value:{case:"sipDtmf",value:new iq({code:e,digit:t})}});yield this.engine.sendDataPacket(i,eF.RELIABLE)})}sendChatMessage(e,t){return rx(this,void 0,void 0,function*(){let i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments},n=new iN({value:{case:"chatMessage",value:new iW(Object.assign(Object.assign({},i),{timestamp:th.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,eF.RELIABLE),this.emit(ev.ChatMessage,i),i})}editChatMessage(e,t){return rx(this,void 0,void 0,function*(){let i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new iN({value:{case:"chatMessage",value:new iW(Object.assign(Object.assign({},i),{timestamp:th.parse(i.timestamp),editTimestamp:th.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,eF.RELIABLE),this.emit(ev.ChatMessage,i),i})}sendText(e,t){return rx(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return rx(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return rx(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return rx(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return this.rpcClientManager.performRpc(e).then(e=>{let[t,i]=e;return i})}
1registerRpcMethod(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,i;let n=this.trackPublications.get(e.sid);if(n){let r=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;r!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign({},si(n)),{mutedOnServer:r})),this.engine.client.sendMuteTrack(e.sid,r))}}),!0)}setActiveAgent(e){var t,i,n,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?null===(i=null===(t=this.activeAgentFuture)||void 0===t?void 0:t.resolve)||void 0===i||i.call(t,e):null===(r=null===(n=this.activeAgentFuture)||void 0===n?void 0:n.reject)||void 0===r||r.call(n,Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new sL),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{let n=i.track;n&&(e instanceof MediaStreamTrack?(sK(n)||sG(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))}),t}waitForPendingPublicationOfSource(e){return rx(this,void 0,void 0,function*(){let t=Date.now();for(;Date.now()<t+1e4;){let t=Array.from(this.pendingPublishPromises.entries()).find(t=>{let[i]=t;return i.source===e});if(t)return t[1];yield sd(20)}})}publishDataTrack(e){return rx(this,void 0,void 0,function*(){let t=new cV(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}}class c9 extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}}class c6 extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var i,n;super.set(e,t);let r=null===(i=this.pending)||void 0===i?void 0:i.get(e);if(r){for(let e of r)e.isResolved||null===(n=e.resolve)||void 0===n||n.call(e,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return"DeferrableMap"}getDeferred(e,t){return rx(this,void 0,void 0,function*(){let i=this.get(e);if(void 0!==i)return i;if(null==t?void 0:t.aborted)throw new c9("The operation was aborted.",t.reason);let n=new sL(void 0,()=>{let t=this.pending.get(e);if(!t)return;let i=t.indexOf(n);-1!==i&&t.splice(i,1),0===t.length&&this.pending.delete(e)}),r=this.pending.get(e);if(r?r.push(n):this.pending.set(e,[n]),t){let e=()=>{var e;n.isResolved||null===(e=n.reject)||void 0===e||e.call(n,new c9("The operation was aborted.",t.reason))};t.addEventListener("abort",e,{once:!0}),n.promise.finally(()=>{t.removeEventListener("abort",e)})}return n.promise})}}class c8 extends c1{constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(eb.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){let t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);let n=new nJ({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new iQ({participantSid:"",trackSids:[this.trackSid]})]});this.emit(eb.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?c1.SubscriptionStatus.Unsubscribed:super.isSubscribed?c1.SubscriptionStatus.Subscribed:c1.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?c1.PermissionStatus.Allowed:c1.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()&&!e!==this.requestedDisabled&&(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.requestedMaxQuality!==e&&(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null===(t=this.requestedVideoDimensions)||void 0===t?void 0:t.width)!==e.width||(null===(i=this.requestedVideoDimensions)||void 0===i?void 0:i.height)!==e.height)&&(sQ(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate())}setVideoFPS(e){this.isManualOperationAllowed()&&sQ(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return null!==(e=this.requestedMaxQuality)&&void 0!==e?e:eS.HIGH}setTrack(e){let t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(eb.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(eb.VisibilityChanged,this.handleVisibilityChange),n.off(eb.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit
1(eb.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(eb.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(eb.VisibilityChanged,this.handleVisibilityChange),e.on(eb.Ended,this.handleEnded),this.emit(eb.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){let t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(eb.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);let t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?eb.Muted:eb.Unmuted)}emitSubscriptionUpdateIfChanged(e){let t=this.subscriptionStatus;e!==t&&this.emit(eb.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(eb.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return sQ(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new nX({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===ss.Kind.Video){let r=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream){if(r)sr(this.videoDimensionsAdaptiveStream,r)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),r=this.videoDimensionsAdaptiveStream);else if(void 0!==this.requestedMaxQuality&&this.trackInfo){var t,i,n;let e=(t=this.trackInfo,i=this.requestedMaxQuality,null===(n=t.layers)||void 0===n?void 0:n.find(e=>e.quality===i));e&&sr(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),r=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),r=this.videoDimensionsAdaptiveStream}r?(e.width=Math.ceil(r.width),e.height=Math.ceil(r.height)):void 0!==this.requestedMaxQuality?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:eS.HIGH})),e.quality=eS.HIGH)}this.emit(eb.UpdateSettings,e)}}class c5 extends c3{static fromParticipantInfo(e,t,i,n){return new c5(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind,t.dataTracks.map(e=>new cP(om(e),n,{publisherIdentity:t.identity})),t.clientProtocol)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,n,r,a,s){let o=arguments.length>7&&void 0!==arguments[7]?arguments[7]:iw.STANDARD,c=arguments.length>8&&void 0!==arguments[8]?arguments[8]:[],l=arguments.length>9&&void 0!==arguments[9]?arguments[9]:0;super(t,i||"",n,r,a,s,o),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new c6(c.map(e=>[e.info.name,e])),this.volumeMap=new Map,this.clientProtocol=l}addTrackPublication(e){super.addTrackPublication(e),e.on(eb.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),si(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(eb.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(eb.SubscriptionPermissionChanged,t=>{this.emit(ev.TrackSubscriptionPermissionChanged,e,t)}),e.on(eb.SubscriptionStatusChanged,t=>{this.emit(ev.TrackSubscriptionStatusChanged,e,t)}),e.on(eb.Subscribed,t=>{this.emit(ev.TrackSubscribed,t,e)}),e.on(eb.Unsubscribed,t=>
1{this.emit(ev.TrackUnsubscribed,t,e)}),e.on(eb.SubscriptionFailed,t=>{this.emit(ev.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ss.Source.Microphone;this.volumeMap.set(t,e);let i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ss.Source.Microphone,t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,n,r,a){let s,o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(t=>{o||e.kind!==t.kind.toString()||(o=t)}),!o){if(0===a){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(ev.TrackSubscriptionFailed,t);return}void 0===a&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,n,r,a-1)},150);return}if("ended"===e.readyState){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),si(o))),this.emit(ev.TrackSubscriptionFailed,t);return}return(s="video"===e.kind?new s8(e,t,n,r):new c0(e,t,n,this.audioContext,this.audioOutput)).source=o.source,s.isMuted=o.isMuted,s.setMediaStream(i),s.start(),o.setTrack(s),this.volumeMap.has(o.source)&&sJ(s)&&sW(s)&&s.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;let t=new Map,i=new Map;return e.tracks.forEach(e=>{var n,r;let a=this.getTrackPublicationBySid(e.sid);if(a)a.updateInfo(e);else{let t=ss.kindFromProto(e.type);if(!t)return;(a=new c8(t,e,null===(n=this.signalClient.connectOptions)||void 0===n?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(r=this.loggerOptions)||void 0===r?void 0:r.loggerName})).updateInfo(e),i.set(e.sid,a);let s=Array.from(this.trackPublications.values()).find(e=>e.source===(null==a?void 0:a.source));s&&a.source!==ss.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:si(s),newTrack:si(a)})),this.addTrackPublication(a)}t.set(e.sid,a)}),this.trackPublications.forEach(e=>{t.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),si(e))),this.unpublishTrack(e.trackSid,!0))}
1),i.forEach(e=>{this.emit(ev.TrackPublished,e)}),!0}unpublishTrack(e,t){let i=this.trackPublications.get(e);if(!i)return;let{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case ss.Kind.Audio:this.audioTrackPublications.delete(e);break;case ss.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(ev.TrackUnpublished,i)}setAudioOutput(e){return rx(this,void 0,void 0,function*(){this.audioOutput=e;let t=[];this.audioTrackPublications.forEach(i=>{var n;sW(i.track)&&sJ(i.track)&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))}),yield Promise.all(t)})}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(let[t,i]of this.dataTracks.entries())e===i.info.sid&&this.dataTracks.delete(t)}emit(e){for(var t=arguments.length,i=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}(ei=eX||(eX={})).Disconnected="disconnected",ei.Connecting="connecting",ei.Connected="connected",ei.Reconnecting="reconnecting",ei.SignalReconnecting="signalReconnecting";class c7 extends rB.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(e){var t,i,n,r,a,s,o;if(super(),t=this,this.state=eX.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new e3,this.isVideoPlaybackBlocked=!1,this.log=r_,this.bufferedEvents=[],this.isResuming=!1,this.connect=(e,t,i)=>rx(this,void 0,void 0,function*(){var n;if(!("undefined"!=typeof RTCPeerConnection&&(su()||sh()))){if(sT())throw Error("WebRTC isn't detected, have you called registerGlobals?");throw Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.")}let r=yield this.disconnectLock.lock();if(this.state===eX.Connected)return this.log.info("already connected to room ".concat(this.name)),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(eX.Connecting),(null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getServerUrl().toString())!==sX(e)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),sS(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new ca(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn("could not fetch region settings",{error:e})}));let a=(n,s,o)=>rx(this,void 0,void 0,function*(){var c,l;this.abortController&&this.abortController.abort();let d=new AbortController;this.abortController=d,null==r||r();try{if(yield or.getInstance().getBackOffPromise(e),d.signal.aborted)throw aV.cancelled("Connection attempt aborted");yield this.attemptConnection(null!=o?o:e,t,i,d),this.abortController=void 0,n()}catch(t){if(this.regionUrlProvider&&t instanceof aV&&t.reason!==ep.Cancelled&&t.reason!==ep.NotAllowed){let i=null;try{this.log.debug("Fetching next region"),i=yield this.regionUrlProvider.getNextBestRegionUrl(null===(c=this.abortController)||void 0===c?void 0:c.signal)}catch(e){if(e instanceof aV&&(401===e.status||e.reason===ep.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),s(e);return}}[ep.InternalError,ep.ServerUnreachable,ep.Timeout].includes(t.reason)&&(this.log.debug("Adding failed connection attempt to back off"),or.getInstance().addFailedConnectionAttempt(e)),!i||(null===(l=this.abortController)||void 0===l?void 0:l.signal.aborted)?(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,sj(t)),s(t)):(this.log.info("Initial connection failed with ConnectionError: ".concat(t.message,". Retrying with another region: ").concat(i)),this.recreateEngine(!0),yield a(n,s,i))}else{let e=im.UNKNOWN_REASON;t instanceof aV&&(e=sj(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),s(t)}}}),s=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new sL((e,t)=>{a(e,t,s)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,i,n,r,a)=>rx(this,void 0,void 0,function*(){let{joinResponse:s,serverInfo:o}=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof r.adaptiveStream||r.adaptiveStream,clientInfoCapabilities:s2(r.packetTrailer)||this.e2eeManager?[i0.CAP_PACKET_TRAILER]:void 0,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},a.signal,!r.singlePeerConnection);
1if(this.serverInfo=o,!o.version)throw new az("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=>{let t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",{error:e})}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>rx(this,void 0,void 0,function*(){var r,a;this.state===eX.Reconnecting||this.isResuming||(null===(r=this.engine)||void 0===r?void 0:r.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine(!0)):this.maybeCreateEngine(),(null===(a=this.regionUrlProvider)||void 0===a?void 0:a.isCloud())&&this.engine.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},oF),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{let i=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,n);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(ef.SignalConnected)}catch(t){yield this.engine.close(),this.recreateEngine();let e=n.signal.aborted?aV.cancelled("Signal connection aborted"):aV.serverUnreachable("could not establish signal connection");throw t instanceof Error&&(e.message="".concat(e.message,": ").concat(t.message)),t instanceof aV&&(e.reason=t.reason,e.status=t.status),this.log.debug("error trying to establish signal connection",{error:t}),e}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),aV.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}sy()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),sy()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(eX.Connected),this.emit(ef.Connected),or.getInstance().resetFailedConnectionAttempts(e),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var e=arguments.length,i=Array(e),n=0;n<e;n++)i[n]=arguments[n];return rx(t,[...i],void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){var i,n,r;let a=yield e.disconnectLock.lock();try{if(e.state===eX.Disconnected){e.log.debug("already disconnected");return}if(e.log.info("disconnect from room"),e.state===eX.Connecting||e.state===eX.Reconnecting||e.isResuming){let t="Abort connection attempt due to user initiated disconnect";e.log.warn(t),null===(i=e.abortController)||void 0===i||i.abort(t),null===(r=null===(n=e.connectFuture)||void 0===n?void 0:n.reject)||void 0===r||r.call(n,aV.cancelled("Client initiated disconnect")),e.connectFuture=void 0}e.engine&&(e.engine.client.isDisconnected||(yield e.engine.client.sendLeave()),yield e.engine.close()),e.handleDisconnect(t,im.CLIENT_INITIATED),e.engine=void 0}finally{a()}}()})},this.onPageLeave=()=>rx(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting"),yield this.disconnect()}),this.startAudio=()=>rx(this,void 0,void 0,function*(){let e=[],t=aL();if(t&&"iOS"===t.os){let t="livekit-dummy-audio-el",i=document.getElementById(t);if(!i){(i=document.createElement("audio")).id=t,i.autoplay=!0,i.hidden=!0;let e=sx();e.enabled=!0;let n=new MediaStream([e]);i.srcObject=n,document.addEventListener("visibilitychange",()=>{i&&(i.srcObject=document.hidden?null:n,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status"),this.startAudio()))}),document.body.append(i),this.once(ef.Disconnected,()=>{null==i||i.remove(),i=null})}e.push(i)}
1this.remoteParticipants.forEach(t=>{t.audioTrackPublications.forEach(t=>{t.track&&t.track.attachedElements.forEach(t=>{e.push(t)})})});try{yield Promise.all([this.acquireAudioContext(),...e.map(e=>(e.muted=!1,e.play()))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}),this.startVideo=()=>rx(this,void 0,void 0,function*(){let e=[];for(let t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var i;null===(i=t.track)||void 0===i||i.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler")})}),this.handleRestarting=()=>{for(let e of(this.clearConnectionReconcile(),this.isResuming=!1,this.remoteParticipants.values()))this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(eX.Reconnecting)&&this.emit(ef.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=e=>rx(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(e.serverRegion),{region:e.serverRegion}),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error("error trying to re-publish tracks after reconnection",{error:e})}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",{region:e.serverRegion})}catch(e){return}this.setAndEmitConnectionState(eX.Connected),this.emit(ef.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{var t;for(let i of e){if(i.identity===this.localParticipant.identity){this.localParticipant.updateInfo(i);continue}""===i.identity&&(i.identity=null!==(t=this.sidToIdentity.get(i.sid))&&void 0!==t?t:"");let e=this.remoteParticipants.get(i.identity);i.state===iE.DISCONNECTED?this.handleParticipantDisconnected(i.identity,e):this.getOrCreateParticipant(i.identity,i)}let i=new Map(e.filter(e=>e.identity!==this.localParticipant.identity).map(e=>[e.identity,e.dataTracks.map(e=>om(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(i)},this.handleActiveSpeakersUpdate=e=>{let t=[],i={};e.forEach(e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{let i=this.getRemoteParticipantBySid(e.sid);i&&(i.audioLevel=e.level,i.setIsSpeaking(!0),t.push(i))}}),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEac
1h(e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(ef.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{let t=new Map;this.activeSpeakers.forEach(e=>{let i=this.remoteParticipants.get(e.identity);i&&i.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let i=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=e.level,i.setIsSpeaking(e.active),e.active?t.set(e.sid,i):t.delete(e.sid))});let i=Array.from(t.values());i.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=i,this.emitWhenConnected(ef.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let i=t.getTrackPublicationBySid(e.trackSid);if(!i||!i.track)return;let n=ss.streamStateFromProto(e.state);i.track.setStreamState(n),n!==i.track.streamState&&(t.emit(ev.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(ef.TrackStreamStateChanged,i,i.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{let t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;let i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{let i=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(i,e.value.value,e.kind,t);else if("transcription"===e.value.case)this.handleTranscription(i,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(i,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(i,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,i);else if("streamHeader"===e.value.case||"streamChunk"===e.value.case||"streamTrailer"===e.value.case)this.handleDataStream(e,t);else if("rpcRequest"===e.value.case){let t=e.value.value;this.rpcServerManager.handleIncomingRpcRequest(e.participantIdentity,t)}else if("rpcResponse"===e.value.case){let 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,cK.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=(e,t,i,n)=>{this.emit(ef.DataReceived,t.payload,e,i,t.topic,n),null==e||e.emit(ev.DataReceived,t.payload,i,n)},this.handleSipDtmf=(e,t)=>{this.emit(ef.SipDTMFReceived,t,e),null==e||e.emit(ev.SipDTMFReceived,t)},this.handleTranscription=(e,t)=>{var i;let n=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),r=null==n?void 0:n.trackPublications.get(t.trackId),a=(i=this.transcriptionReceivedTimes,t.segments.map(e=>{var t;let{id:n,text:r,language:a,startTime:s,endTime:o,final:c}=e,l=null!==(t=i.get(n))&&void 0!==t?t:Date.now(),d=Date.now();return c?i.delete(n):i.set(n,l),{id:n,text:r,startTime:Number.parseInt(s.toString()),endTime:Number.parseInt(o.toString()),final:c,language:a,firstReceivedTime:l,lastReceivedTime:d}}));null==r||r.emit(eb.TranscriptionReceived,a),null==n||n.emit(ev.TranscriptionReceived,a,r),this.emit(ef.TranscriptionReceived,a,n,r)},this.handleChatMessage=(e,t)=>{let i=function(e){let{id:t,timestamp:i,message:n,editTimestamp:r}=e;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:n}}(t);this.emit(ef.ChatMessage,i,e)},this.handleMetrics=(e,t)=>{this.emit(ef.MetricsReceived,e,t)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>
1{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(ef.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn("could not playback audio",{error:e}),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(ef.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(ef.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(ef.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>rx(this,void 0,void 0,function*(){var e;(null===(e=aL())||void 0===e?void 0:e.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(ef.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{let t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(ef.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(ef.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach(e=>{if(e.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(e.quality);return}let t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)})},this.getRemoteParticipantClientProtocol=e=>{var t,i;return null!==(i=null===(t=this.remoteParticipants.get(e))||void 0===t?void 0:t.clientProtocol)&&void 0!==i?i:0},this.onLocalParticipantMetadataChanged=e=>{this.emit(ef.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(ef.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(ef.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(ef.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(ef.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=e=>rx(this,void 0,void 0,function*(){var t,i,n,r,a,s;null===(t=e.track)||void 0===t||t.on(eb.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.on(eb.Restarted,this.onLocalTrackRestarted),null===(a=null===(r=null===(n=e.track)||void 0===n?void 0:n.getProcessor())||void 0===r?void 0:r.onPublish)||void 0===a||a.call(r,this),this.emit(ef.LocalTrackPublished,e,this.localParticipant),sK(e.track)&&(yield e.track.checkForSilence())&&this.emit(ef.LocalAudioSilenceDetected,e);let o=yield null===(s=e.track)||void 0===s?void 0:s.getDeviceId(!1),c=se(e.source);c&&o&&o!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,o),this.emit(ef.ActiveDeviceChanged,c,o))}),this.onLocalTrackUnpublished=e=>{var t,i;null===(t=e.track)||void 0===t||t.off(eb.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.off(eb.Restarted,this.onLocalTrackRestarted),this.emit(ef.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>rx(this,void 0,void 0,function*(){let t=yield e.getDeviceId(!1),i=se(e.source);i&&t&&t!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(t," active")),this.localParticipant.activeDeviceMap.set(i,t),this.emit(ef.ActiveDeviceChanged,i,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(ef.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(ef.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(ef.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(ef.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},oU),e),this.log=rM(null!==(i=this.options.loggerName)&&void 0!==i?i:el.Room,()=>this.logContext),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},ox),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},oL),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},oN),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new cl,this.outgoingDataStreamManager=new cp(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",e=>{var t;e.track.publisherIdentity!==this.localParticipant.identity&&(this.emit
1(ef.DataTrackPublished,e.track),null===(t=this.remoteParticipants.get(e.track.publisherIdentity))||void 0===t||t.addRemoteDataTrack(e.track))}).on("trackUnpublished",e=>{var t;e.publisherIdentity!==this.localParticipant.identity&&(this.emit(ef.DataTrackUnpublished,e.sid),null===(t=this.remoteParticipants.get(e.publisherIdentity))||void 0===t||t.removeRemoteDataTrack(e.sid))}),this.outgoingDataTrackManager=new cG({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on("sfuPublishRequest",e=>{this.engine.client.sendPublishDataTrackRequest(e.handle,e.name,e.usesE2ee)}).on("sfuUnpublishRequest",e=>{this.engine.client.sendUnPublishDataTrackRequest(e.handle)}).on("trackPublished",e=>{this.emit(ef.LocalDataTrackPublished,e.track)}).on("trackUnpublished",e=>{this.emit(ef.LocalDataTrackUnpublished,e.sid)}).on("packetAvailable",e=>{let{handle:t,bytes:i}=e;this.engine.sendLossyBytes(i,eF.DATA_TRACK_LOSSY,"wait").finally(()=>this.outgoingDataTrackManager.handlePacketSendComplete(t))}),this.registerRpcDataStreamHandler(),this.rpcClientManager=new cZ(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=>{var t;let{packet:i}=e;null===(t=this.engine)||void 0===t||t.sendDataPacket(i,eF.RELIABLE)}),this.rpcServerManager=new c$(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol),this.rpcServerManager.on("sendDataPacket",e=>{var t;let{packet:i}=e;null===(t=this.engine)||void 0===t||t.sendDataPacket(i,eF.RELIABLE)}),this.disconnectLock=new e3,this.localParticipant=new c4("","",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!==(n=this.e2eeManager)&&void 0!==n?n:null),this.outgoingDataTrackManager.updateE2eeManager(null!==(r=this.e2eeManager)&&void 0!==r?r:null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",sF(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",sF(this.options.audioCaptureDefaults.deviceId)),(null===(a=this.options.audioOutput)||void 0===a?void 0:a.deviceId)&&this.switchActiveDevice("audiooutput",sF(this.options.audioOutput.deviceId)).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message))),sy()){let e=new AbortController;null===(o=null===(s=navigator.mediaDevices)||void 0===s?void 0:s.addEventListener)||void 0===o||o.call(s,"devicechange",this.handleDeviceChange,{signal:e.signal}),c7.cleanupRegistry&&c7.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)}
1registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setE2EEEnabled(e){return rx(this,void 0,void 0,function*(){let t=yield this.e2eeStateMutex.lock();try{if(this.e2eeManager)this.isE2EEEnabled!==e&&(yield this.localParticipant.setE2EEEnabled(e),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity));else throw Error("e2ee not configured, please set e2ee settings within the room options")}finally{t()}})}setupE2EE(){var e,t;let i=!!this.options.encryption,n=this.options.encryption||this.options.e2ee;n&&("e2eeManager"in n?(this.e2eeManager=n.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=i):this.e2eeManager=new ot(n,i),this.e2eeManager.on(ew.ParticipantEncryptionStatusChanged,(e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit(ef.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(ew.EncryptionError,(e,t)=>{let i=t?this.getParticipantByIdentity(t):void 0;this.emit(ef.EncryptionError,e,i)}),null===(e=this.e2eeManager)||void 0===e||e.setup(this),null===(t=this.e2eeManager)||void 0===t||t.setupEngine(this.engine))}setupPacketTrailer(){this.packetTrailerManager=new on(this.options.packetTrailer),this.packetTrailerManager.setup(this)}get logContext(){var e,t,i;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===(i=this.localParticipant)||void 0===i?void 0:i.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===eX.Disconnected?aN.resolve(""):this.roomInfo&&""!==this.roomInfo.sid?aN.resolve(this.roomInfo.sid):new aN((e,t)=>{let i=t=>{""!==t.sid&&(this.engine.off(ek.RoomUpdate,i),e(t.sid))};this.engine.on(ek.RoomUpdate,i),this.once(ef.Disconnected,()=>{this.engine.off(ek.RoomUpdate,i),t(new aG("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 cn(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(ek.ParticipantUpdate,this.handleParticipantUpdates).on(ek.RoomUpdate,this.handleRoomUpdate).on(ek.SpeakersChanged,this.handleSpeakersChanged).on(ek.StreamStateChanged,this.handleStreamStateUpdate).on(ek.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(ek.SubscriptionError,this.handleSubscriptionError).on(ek.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(ek.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(ek.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(ek.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(ek.DataPacketReceived,this.handleDataPacket).on(ek.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.debug("Resuming signal connection"),this.setAndEmitConnectionState(eX.SignalReconnecting)&&this.emit(ef.SignalReconnecting)}).on(ek.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug("Resumed signal connection"),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(eX.Connected)&&this.emit(ef.Reconnected)}).on(ek.SignalResumed,()=>{this.bufferedEvents=[],(this.state===eX.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(ek.Restarting,this.handleRestarting).on(ek.Restarted,this.handleRestarted).on(ek.SignalRestarted,this.handleSignalRestarted).on(ek.Offline,()=>
1{this.setAndEmitConnectionState(eX.Reconnecting)&&this.emit(ef.Reconnecting)}).on(ek.DCBufferStatusChanged,(e,t)=>{this.emit(ef.DCBufferStatusChanged,e,t)}).on(ek.LocalTrackSubscribed,e=>{this.handleLocalTrackSubscribed(e)}).on(ek.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((e,t)=>{this.handleParticipantDisconnected(t,e)}),this.emit(ef.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(ek.PublishDataTrackResponse,e=>{if(!e.info){this.log.warn("received PublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."));return}this.outgoingDataTrackManager.receivedSfuPublishResponse(e.info.pubHandle,{type:"ok",data:{sid:e.info.sid,pubHandle:e.info.pubHandle,name:e.info.name,usesE2ee:e.info.encryption!==iR.NONE}})}).on(ek.UnPublishDataTrackResponse,e=>{if(!e.info){this.log.warn("received UnPublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."));return}this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle)}).on(ek.DataTrackSubscriberHandles,e=>{let t=new Map(Object.entries(e.subHandles).map(e=>{let[t,i]=e;return[parseInt(t,10),i.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(ek.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(e){throw e}}).on(ek.Joined,e=>{let t=new Map(e.otherParticipants.map(e=>[e.identity,e.dataTracks.map(e=>om(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)}).on(ek.TokenRefreshed,e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.updateToken(e)}).on(ek.ServerRegionsReported,e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions({regionSettings:e,updatedAtInMs:Date.now(),maxAgeInMs:5e3})}),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=>rx(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 os.getInstance().getDevices(e,t)}prepareConnection(e,t){return rx(this,void 0,void 0,function*(){if(this.state===eX.Disconnected){this.log.debug("prepareConnection to ".concat(e));try{if(sS(new URL(e))&&t){this.regionUrlProvider=new ca(e,t);let i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===eX.Disconnected&&(this.regionUrl=i,yield fetch(sB(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i)))}else yield fetch(sB(e),{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 rx(this,void 0,void 0,function*(){let i,n=()=>rx(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":i=new rh({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new rh({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new rh({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new rh({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>rx(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new rh({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>rx(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new rh({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":i=new rh({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>rx(this,void 0,void 0,function*(){let e=this.engine.client.onLeave;e&&e(new n0({reason:im.CLIENT_INITIATED,action:n1.RECONNECT}))});break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw Error("subscriber-bandwidth requires a number as argument");i=new rh({scenario:{case:"subscriberBandwidth",value:sV(t)}});break;case"leave-full-reconnect":i=new rh({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return rx(this,arguments,void 0,function(e,t){var i=this;let n=!(arguments.length>2)||void 0===arguments[2]||arguments[2];return function*(){var r,a,s,o,c,l,d;let u=!0,h=!1,p=n?{exact:t}:t;if("audioinput"===e){h=0===i.localParticipant.audioTrackPublications.size;let t=null!==(r=i.getActiveDevice(e))&&void 0!==r?r:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=p;let n=Array.from(i.localParticipant.audioTrackPublications.values()).filter(e=>e.source===ss.Source.Microphone);try{u=(yield Promise.all(n.map(e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(p)}
1))).every(e=>!0===e)}catch(e){throw i.options.audioCaptureDefaults.deviceId=t,e}let a=n.some(e=>{var t,i;return null!==(i=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==i&&i});u&&a&&(h=!0)}else if("videoinput"===e){h=0===i.localParticipant.videoTrackPublications.size;let t=null!==(a=i.getActiveDevice(e))&&void 0!==a?a:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=p;let n=Array.from(i.localParticipant.videoTrackPublications.values()).filter(e=>e.source===ss.Source.Camera);try{u=(yield Promise.all(n.map(e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(p)}))).every(e=>!0===e)}catch(e){throw i.options.videoCaptureDefaults.deviceId=t,e}let r=n.some(e=>{var t,i;return null!==(i=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==i&&i});u&&r&&(h=!0)}else if("audiooutput"===e){if(h=!0,!sm()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw Error("cannot switch audio output, the current browser does not support it");i.options.webAudioMix&&(t=null!==(s=yield os.getInstance().normalizeDeviceId("audiooutput",t))&&void 0!==s?s:""),null!==(o=(d=i.options).audioOutput)&&void 0!==o||(d.audioOutput={});let n=null!==(c=i.getActiveDevice(e))&&void 0!==c?c:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=t;try{i.options.webAudioMix&&(null===(l=i.audioContext)||void 0===l||l.setSinkId(t)),yield Promise.all(Array.from(i.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(e){throw i.options.audioOutput.deviceId=n,e}}return h&&(i.localParticipant.activeDeviceMap.set(e,t),i.emit(ef.ActiveDeviceChanged,e,t)),u}()})}setupLocalParticipantEvents(){this.localParticipant.on(ev.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(ev.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(ev.AttributesChanged,this.onLocalAttributesChanged).on(ev.TrackMuted,this.onLocalTrackMuted).on(ev.TrackUnmuted,this.onLocalTrackUnmuted).on(ev.LocalTrackPublished,this.onLocalTrackPublished).on(ev.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(ev.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(ev.MediaDevicesError,this.onMediaDevicesError).on(ev.AudioStreamAcquired,this.startAudio).on(ev.ChatMessage,this.onLocalChatMessageSent).on(ev.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){let 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(e,t,i){let n;if(this.state===eX.Connecting||this.state===eX.Reconnecting){let n=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(e=>e.id)}),this.onTrackAdded(e,t,i),r()},r=()=>{this.off(ef.Reconnected,n),this.off(ef.Connected,n),this.off(ef.Disconnected,r)};this.once(ef.Reconnected,n),this.once(ef.Connected,n),this.once(ef.Disconnected,r);return}if(this.state===eX.Disconnected){this.log.warn("skipping incoming track after Room disconnected");return}if("ended"===e.readyState){this.log.debug("skipping incoming track as it already ended");return}let r=function(e){let t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),a=r[0],s=r[1],o=e.id;if(s&&s.startsWith("TR")&&(o=s),a===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant");return}let c=Array.from(this.remoteParticipants.values()).find(e=>e.sid===a);if(!c){a.startsWith("PA")&&this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(a));return}if(!o.startsWith("TR")){let e=this.engine.getTrackIdForReceiver(i);if(!e){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(a));return}o=e}o.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(a,", streamId: ").concat(s,", trackId: ").concat(o),{remoteParticipantID:a,streamId:s,trackId:o}),this.options.adaptiveStream&&(n="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});let l=c.addSubscribedMediaTrack(e,o,t,i,n);
1(null==l?void 0:l.isEncrypted)&&!this.e2eeManager&&this.emit(ef.EncryptionError,Error("Encrypted ".concat(l.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleLocalTrackSubscribed(e){let t;let i=()=>this.localParticipant.getTrackPublications().find(t=>{let{trackSid:i}=t;return i===e}),n=i();if(n){this.emitLocalTrackSubscribed(n);return}this.log.debug("deferring LocalTrackSubscribed, publication not yet available",{subscribedSid:e});let r=t=>{t.trackSid===e&&(a(),this.emitLocalTrackSubscribed(t))},a=()=>{clearTimeout(t),this.localParticipant.off(ev.LocalTrackPublished,r),this.off(ef.Disconnected,a)};this.localParticipant.on(ev.LocalTrackPublished,r),this.once(ef.Disconnected,a),t=setTimeout(()=>{a();let t=i();t?this.emitLocalTrackSubscribed(t):this.log.warn("could not find local track publication for LocalTrackSubscribed event after timeout",{subscribedSid:e})},1e4)}emitLocalTrackSubscribed(e){this.localParticipant.emit(ev.LocalTrackSubscribed,e),this.emitWhenConnected(ef.LocalTrackSubscribed,e,this.localParticipant)}handleDisconnect(){var e,t;let i=!(arguments.length>0)||void 0===arguments[0]||arguments[0],n=arguments.length>1?arguments[1]:void 0;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.incomingDataTrackManager.reset(),this.outgoingDataTrackManager.reset(),this.state!==eX.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();
1try{this.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{e.unpublishTrack(t.trackSid)})}),this.localParticipant.trackPublications.forEach(e=>{var t,n,r;e.track&&this.localParticipant.unpublishTrack(e.track,i),i?(null===(t=e.track)||void 0===t||t.detach(),null===(n=e.track)||void 0===n||n.stop()):null===(r=e.track)||void 0===r||r.stopMonitor()}),this.localParticipant.off(ev.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(ev.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(ev.AttributesChanged,this.onLocalAttributesChanged).off(ev.TrackMuted,this.onLocalTrackMuted).off(ev.TrackUnmuted,this.onLocalTrackUnmuted).off(ev.LocalTrackPublished,this.onLocalTrackPublished).off(ev.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(ev.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(ev.MediaDevicesError,this.onMediaDevicesError).off(ev.AudioStreamAcquired,this.startAudio).off(ev.ChatMessage,this.onLocalChatMessageSent).off(ev.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),sy()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(t=null===(e=navigator.mediaDevices)||void 0===e?void 0:e.removeEventListener)||void 0===t||t.call(e,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(eX.Disconnected),this.emit(ef.Disconnected,n)}}}handleParticipantDisconnected(e,t){this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(ef.ParticipantDisconnected,t),t.setDisconnected(),this.rpcClientManager.handleParticipantDisconnected(t.identity))}selectDefaultDevices(){return rx(this,void 0,void 0,function*(){var e,t,i;let n=os.getInstance().previousDevices,r=yield os.getInstance().getDevices(void 0,!1),a=aL();if((null==a?void 0:a.name)==="Chrome"&&"iOS"!==a.os)for(let e of r){let t=n.find(t=>t.deviceId===e.deviceId);t&&""!==t.label&&t.kind===e.kind&&t.label!==e.label&&"default"===this.getActiveDevice(e.kind)&&this.emit(ef.ActiveDeviceChanged,e.kind,e.deviceId)}for(let a of["audiooutput","audioinput","videoinput"]){let s="audioinput"===a?ss.Source.Microphone:"videoinput"===a?ss.Source.Camera:ss.Source.Unknown,o=this.localParticipant.getTrackPublication(s);if(o&&(null===(e=o.track)||void 0===e?void 0:e.isUserProvided))continue;let c=r.filter(e=>e.kind===a),l=this.getActiveDevice(a);if(l===(null===(t=n.filter(e=>e.kind===a)[0])||void 0===t?void 0:t.deviceId)&&c.length>0&&(null===(i=c[0])||void 0===i?void 0:i.deviceId)!==l){yield this.switchActiveDevice(a,c[0].deviceId);continue}("audioinput"!==a||sk())&&"videoinput"!==a&&(!(c.length>0)||c.find(e=>e.deviceId===this.getActiveDevice(a))||"audiooutput"===a&&sk()||(yield this.switchActiveDevice(a,c[0].deviceId)))}})}acquireAudioContext(){return rx(this,void 0,void 0,function*(){var e,t;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(e=a7())&&void 0!==e?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEac
1h(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),sd(200)])}catch(e){this.log.warn("Could not resume audio context",{error:e})}let i=(null===(t=this.audioContext)||void 0===t?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(ef.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let n;return n=t?c5.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):new c5(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),(null===(i=this.options.audioOutput)||void 0===i?void 0:i.deviceId)&&n.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message))),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){let i=this.remoteParticipants.get(e);return t&&i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),i}let i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(ef.ParticipantConnected,i),i.on(ev.TrackPublished,e=>{this.emitWhenConnected(ef.TrackPublished,e,i)}).on(ev.TrackSubscribed,(e,t)=>{e.kind===ss.Kind.Audio?(e.on(eb.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(eb.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===ss.Kind.Video&&(e.on(eb.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(eb.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(ef.TrackSubscribed,e,t,i)}).on(ev.TrackUnpublished,e=>{this.emit(ef.TrackUnpublished,e,i)}).on(ev.TrackUnsubscribed,(e,t)=>{this.emit(ef.TrackUnsubscribed,e,t,i)}).on(ev.TrackMuted,e=>{this.emitWhenConnected(ef.TrackMuted,e,i)}).on(ev.TrackUnmuted,e=>{this.emitWhenConnected(ef.TrackUnmuted,e,i)}).on(ev.ParticipantMetadataChanged,e=>{this.emitWhenConnected(ef.ParticipantMetadataChanged,e,i)}).on(ev.ParticipantNameChanged,e=>{this.emitWhenConnected(ef.ParticipantNameChanged,e,i)}).on(ev.AttributesChanged,e=>{this.emitWhenConnected(ef.ParticipantAttributesChanged,e,i)}).on(ev.ConnectionQualityChanged,e=>{this.emitWhenConnected(ef.ConnectionQualityChanged,e,i)}).on(ev.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(ef.ParticipantPermissionsChanged,e,i)}).on(ev.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(ef.TrackSubscriptionStatusChanged,e,t,i)}).on(ev.TrackSubscriptionFailed,(e,t)=>{this.emit(ef.TrackSubscriptionFailed,e,i,t)}).on(ev.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(ef.TrackSubscriptionPermissionChanged,e,t,i)}).on(ev.Active,()=>{this.emitWhenConnected(ef.ParticipantActive,i),i.kind===iw.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){let e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications(),i=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,i)}updateSubscriptions(){for(let t of this.remoteParticipants.values())for(let i of t.videoTrackPublications.values()){var e;i.isSubscribed&&(e=i)&&!e.isLocal&&i.emitTrackUpdate()}}getRemoteParticipantBySid(e){let t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(cJ,(e,t)=>rx(this,[e,t],void 0,function(e,t){var i=this;let{identity:n}=t;return function*(){var t;let r=null!==(t=e.info.attributes)&&void 0!==t?t:{};yield i.rpcServerManager.handleIncomingDataStream(e,n,r)}()})),this.incomingDataStreamManager.registerTextStreamHandler(cQ,(e,t)=>rx(this,[e,t],void 0,function(e,t){var i=this;let{identity:n}=t;return function*(){var t;let r=null!==(t=e.info.attributes)&&void 0!==t?t:{};yield i.rpcClientManager.handleIncomingDataStream(e,n,r)}()}))}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=aZ.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,im.STATE_MISMATCH)))},4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&aZ.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.log.info("connection state changed: ".concat(this.state," -> ").concat(e)),this.state=e,this.incomingDataStreamManager.setConnected(e===eX.Connected),this.emit
1(ef.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(this.state===eX.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===eX.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return rx(this,void 0,void 0,function*(){var t,i,n,r;let a=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new iy({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:th.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new iC({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(ef.SignalConnected),this.emit(ef.Connected),this.setAndEmitConnectionState(eX.Connected),a.video){let e=new c2(ss.Kind.Video,new iD({source:id.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:il.AUDIO,name:"video-dummy"}),new o9(a.useRealTracks&&(null===(t=window.navigator.mediaDevices)||void 0===t?void 0:t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:sN(160*(null!==(i=s.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(e),this.localParticipant.emit(ev.LocalTrackPublished,e)}if(a.audio){let e=new c2(ss.Kind.Audio,new iD({source:id.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:il.AUDIO}),new oz(a.useRealTracks&&(null===(n=navigator.mediaDevices)||void 0===n?void 0:n.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:sx(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(ev.LocalTrackPublished,e)}for(let e=0;e<s.count-1;e+=1){let t=new iC({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:iE.ACTIVE,tracks:[],joinedAt:th.parse(Date.now())}),i=this.getOrCreateParticipant(t.identity,t);if(s.video){let n=sN(160*(null!==(r=s.aspectRatios[e%s.aspectRatios.length])&&void 0!==r?r:1),160,!1,!0),a=new iD({source:id.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:il.AUDIO});i.addSubscribedMediaTrack(n,a.sid,new MediaStream([n]),new RTCRtpReceiver),t.tracks=[...t.tracks,a]}if(s.audio){let e=sx(),n=new iD({source:id.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:il.AUDIO});i.addSubscribedMediaTrack(e,n.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,n]}i.updateInfo(t)}})}emit(e){for(var t=arguments.length,i=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(e!==ef.ActiveSpeakersChanged&&e!==ef.TranscriptionReceived){let t=(function e(t){return t.map(t=>t?Array.isArray(t)?e(t):"object"==typeof t?"logContext"in t?t.logContext:void 0:t:void 0)})(i).filter(e=>void 0!==e);(e===ef.TrackSubscribed||e===ef.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),{event:e,args:t}),this.log.debug("room event ".concat(e),{event:e,args:t})}return super.emit(e,...i)}}function le(e,t,i){var n;return(t="symbol"==typeof(n=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t);if("object"!=typeof n)return n;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"))?n:n+"")in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}c7.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()}),(en=eZ||(eZ={}))[en.IDLE=0]="IDLE",en[en.RUNNING=1]="RUNNING",en[en.SKIPPED=2]="SKIPPED",en[en.SUCCESS=3]="SUCCESS",en[en.FAILED=4]="FAILED",new TextEncoder,new TextDecoder;
vendor: 1,198 bytes, line 1
1class lt extends Error{constructor(e,t){var i;super(e,t),le(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(i=Error.captureStackTrace)||void 0===i||i.call(Error,this,this.constructor)}}le(lt,"code","ERR_JOSE_GENERIC");class li extends lt{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:n,payload:t}}),le(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),le(this,"claim",void 0),le(this,"reason",void 0),le(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}}le(li,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class ln extends lt{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:n,payload:t}}),le(this,"code","ERR_JWT_EXPIRED"),le(this,"claim",void 0),le(this,"reason",void 0),le(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}}le(ln,"code","ERR_JWT_EXPIRED");class lr extends lt{constructor(){super(...arguments),le(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}
1le(lr,"code","ERR_JOSE_ALG_NOT_ALLOWED");class la extends lt{constructor(){super(...arguments),le(this,"code","ERR_JOSE_NOT_SUPPORTED")}}le(la,"code","ERR_JOSE_NOT_SUPPORTED");class ls extends lt{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),le(this,"code","ERR_JWE_DECRYPTION_FAILED")}}le(ls,"code","ERR_JWE_DECRYPTION_FAILED");class lo extends lt{constructor(){super(...arguments),le(this,"code","ERR_JWE_INVALID")}}le(lo,"code","ERR_JWE_INVALID");class lc extends lt{constructor(){super(...arguments),le(this,"code","ERR_JWS_INVALID")}}le(lc,"code","ERR_JWS_INVALID");class ll extends lt{constructor(){super(...arguments),le(this,"code","ERR_JWT_INVALID")}}le(ll,"code","ERR_JWT_INVALID");class ld extends lt{constructor(){super(...arguments),le(this,"code","ERR_JWK_INVALID")}}le(ld,"code","ERR_JWK_INVALID");class lu extends lt{constructor(){super(...arguments),le(this,"code","ERR_JWKS_INVALID")}}le(lu,"code","ERR_JWKS_INVALID");class lh extends lt{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),le(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}le(lh,"code","ERR_JWKS_NO_MATCHING_KEY");class lp extends lt{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),le(this,Symbol.asyncIterator,void 0),le(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}le(lp,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class lm extends lt{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),le(this,"code","ERR_JWKS_TIMEOUT")}}le(lm,"code","ERR_JWKS_TIMEOUT");class lg extends lt{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),le(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}le(lg,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED"),Symbol.for("lk.serializer")}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.